code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/native_menu_win.h" #include <utility> #include "base/check.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/strings/string_util_win.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/base/models/menu_model.h" #include "ui/views/controls/menu/menu_insertion_delegate_win.h" namespace views { struct NativeMenuWin::ItemData { // The Windows API requires that whoever creates the menus must own the // strings used for labels, and keep them around for the lifetime of the // created menu. So be it. std::u16string label; // Someone needs to own submenus, it may as well be us. std::unique_ptr<NativeMenuWin> submenu; // We need a pointer back to the containing menu in various circumstances. raw_ptr<NativeMenuWin> native_menu_win; // The index of the item within the menu's model. size_t model_index; }; // Returns the NativeMenuWin for a particular HMENU. static NativeMenuWin* GetNativeMenuWinFromHMENU(HMENU hmenu) { MENUINFO mi = {0}; mi.cbSize = sizeof(mi); mi.fMask = MIM_MENUDATA | MIM_STYLE; GetMenuInfo(hmenu, &mi); return reinterpret_cast<NativeMenuWin*>(mi.dwMenuData); } //////////////////////////////////////////////////////////////////////////////// // NativeMenuWin, public: NativeMenuWin::NativeMenuWin(ui::MenuModel* model, HWND system_menu_for) : model_(model), menu_(nullptr), owner_draw_(l10n_util::NeedOverrideDefaultUIFont(nullptr, nullptr) && !system_menu_for), system_menu_for_(system_menu_for), first_item_index_(0), parent_(nullptr) {} NativeMenuWin::~NativeMenuWin() { items_.clear(); DestroyMenu(menu_); } //////////////////////////////////////////////////////////////////////////////// // NativeMenuWin, MenuWrapper implementation: void NativeMenuWin::Rebuild(MenuInsertionDelegateWin* delegate) { ResetNativeMenu(); items_.clear(); owner_draw_ = model_->HasIcons() || owner_draw_; first_item_index_ = delegate ? delegate->GetInsertionIndex(menu_) : size_t{0}; for (size_t model_index = 0; model_index < model_->GetItemCount(); ++model_index) { size_t menu_index = model_index + first_item_index_; if (model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_SEPARATOR) AddSeparatorItemAt(menu_index, model_index); else AddMenuItemAt(menu_index, model_index); } } void NativeMenuWin::UpdateStates() { // A depth-first walk of the menu items, updating states. size_t model_index = 0; for (const auto& item : items_) { size_t menu_index = model_index + first_item_index_; SetMenuItemState(menu_index, model_->IsEnabledAt(model_index), model_->IsItemCheckedAt(model_index), false); if (model_->IsItemDynamicAt(model_index)) { // TODO(atwilson): Update the icon as well (http://crbug.com/66508). SetMenuItemLabel(menu_index, model_index, model_->GetLabelAt(model_index)); } NativeMenuWin* submenu = item->submenu.get(); if (submenu) submenu->UpdateStates(); ++model_index; } } //////////////////////////////////////////////////////////////////////////////// // NativeMenuWin, private: bool NativeMenuWin::IsSeparatorItemAt(size_t menu_index) const { MENUITEMINFO mii = {0}; mii.cbSize = sizeof(mii); mii.fMask = MIIM_FTYPE; GetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii); return !!(mii.fType & MF_SEPARATOR); } void NativeMenuWin::AddMenuItemAt(size_t menu_index, size_t model_index) { MENUITEMINFO mii = {0}; mii.cbSize = sizeof(mii); mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_DATA; if (!owner_draw_) mii.fType = MFT_STRING; else mii.fType = MFT_OWNERDRAW; std::unique_ptr<ItemData> item_data = std::make_unique<ItemData>(); item_data->label = std::u16string(); ui::MenuModel::ItemType type = model_->GetTypeAt(model_index); if (type == ui::MenuModel::TYPE_SUBMENU) { item_data->submenu = std::make_unique<NativeMenuWin>( model_->GetSubmenuModelAt(model_index), nullptr); item_data->submenu->Rebuild(nullptr); mii.fMask |= MIIM_SUBMENU; mii.hSubMenu = item_data->submenu->menu_; GetNativeMenuWinFromHMENU(mii.hSubMenu)->parent_ = this; } else { if (type == ui::MenuModel::TYPE_RADIO) mii.fType |= MFT_RADIOCHECK; mii.wID = static_cast<UINT>(model_->GetCommandIdAt(model_index)); } item_data->native_menu_win = this; item_data->model_index = model_index; mii.dwItemData = reinterpret_cast<ULONG_PTR>(item_data.get()); items_.insert(items_.begin() + static_cast<ptrdiff_t>(model_index), std::move(item_data)); UpdateMenuItemInfoForString(&mii, model_index, model_->GetLabelAt(model_index)); InsertMenuItem(menu_, menu_index, TRUE, &mii); } void NativeMenuWin::AddSeparatorItemAt(size_t menu_index, size_t model_index) { MENUITEMINFO mii = {0}; mii.cbSize = sizeof(mii); mii.fMask = MIIM_FTYPE; mii.fType = MFT_SEPARATOR; // Insert a dummy entry into our label list so we can index directly into it // using item indices if need be. items_.insert(items_.begin() + static_cast<ptrdiff_t>(model_index), std::make_unique<ItemData>()); InsertMenuItem(menu_, static_cast<UINT>(menu_index), TRUE, &mii); } void NativeMenuWin::SetMenuItemState(size_t menu_index, bool enabled, bool checked, bool is_default) { if (IsSeparatorItemAt(menu_index)) return; UINT state = enabled ? MFS_ENABLED : MFS_DISABLED; if (checked) state |= MFS_CHECKED; if (is_default) state |= MFS_DEFAULT; MENUITEMINFO mii = {0}; mii.cbSize = sizeof(mii); mii.fMask = MIIM_STATE; mii.fState = state; SetMenuItemInfo(menu_, static_cast<UINT>(menu_index), MF_BYPOSITION, &mii); } void NativeMenuWin::SetMenuItemLabel(size_t menu_index, size_t model_index, const std::u16string& label) { if (IsSeparatorItemAt(menu_index)) return; MENUITEMINFO mii = {0}; mii.cbSize = sizeof(mii); UpdateMenuItemInfoForString(&mii, model_index, label); SetMenuItemInfo(menu_, static_cast<UINT>(menu_index), MF_BYPOSITION, &mii); } void NativeMenuWin::UpdateMenuItemInfoForString(MENUITEMINFO* mii, size_t model_index, const std::u16string& label) { std::u16string formatted = label; ui::MenuModel::ItemType type = model_->GetTypeAt(model_index); // Strip out any tabs, otherwise they get interpreted as accelerators and can // lead to weird behavior. base::ReplaceSubstringsAfterOffset(&formatted, 0, u"\t", u" "); if (type != ui::MenuModel::TYPE_SUBMENU) { // Add accelerator details to the label if provided. ui::Accelerator accelerator(ui::VKEY_UNKNOWN, ui::EF_NONE); if (model_->GetAcceleratorAt(model_index, &accelerator)) { formatted += u"\t"; formatted += accelerator.GetShortcutText(); } } // Update the owned string, since Windows will want us to keep this new // version around. items_[model_index]->label = formatted; // Give Windows a pointer to the label string. mii->fMask |= MIIM_STRING; mii->dwTypeData = base::as_writable_wcstr(items_[model_index]->label); } void NativeMenuWin::ResetNativeMenu() { if (IsWindow(system_menu_for_)) { if (menu_) GetSystemMenu(system_menu_for_, TRUE); menu_ = GetSystemMenu(system_menu_for_, FALSE); } else { if (menu_) DestroyMenu(menu_); menu_ = CreatePopupMenu(); // Rather than relying on the return value of TrackPopupMenuEx, which is // always a command identifier, instead we tell the menu to notify us via // our host window and the WM_MENUCOMMAND message. MENUINFO mi = {0}; mi.cbSize = sizeof(mi); mi.fMask = MIM_STYLE | MIM_MENUDATA; mi.dwStyle = MNS_NOTIFYBYPOS; mi.dwMenuData = reinterpret_cast<ULONG_PTR>(this); SetMenuInfo(menu_, &mi); } } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/native_menu_win.cc
C++
unknown
8,376
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_ #define UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_ #include <memory> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/views_export.h" namespace ui { class MenuModel; } namespace views { class MenuInsertionDelegateWin; // A wrapper around a native Windows menu. class VIEWS_EXPORT NativeMenuWin { public: // Construct a NativeMenuWin, with a model and delegate. If |system_menu_for| // is non-NULL, the NativeMenuWin wraps the system menu for that window. // The caller owns the model and the delegate. NativeMenuWin(ui::MenuModel* model, HWND system_menu_for); NativeMenuWin(const NativeMenuWin&) = delete; NativeMenuWin& operator=(const NativeMenuWin&) = delete; ~NativeMenuWin(); void Rebuild(MenuInsertionDelegateWin* delegate); void UpdateStates(); private: // IMPORTANT: Note about indices. // Functions in this class deal in two index spaces: // 1. menu_index - the index of an item within the actual Windows // native menu. // 2. model_index - the index of the item within our model. // These two are most often but not always the same value! The // notable exception is when this object is used to wrap the // Windows System Menu. In this instance, the model indices start // at 0, but the insertion index into the existing menu is not. // It is important to take this into consideration when editing the // code in the functions in this class. // Returns true if the item at the specified index is a separator. bool IsSeparatorItemAt(size_t menu_index) const; // Add items. See note above about indices. void AddMenuItemAt(size_t menu_index, size_t model_index); void AddSeparatorItemAt(size_t menu_index, size_t model_index); // Sets the state of the item at the specified index. void SetMenuItemState(size_t menu_index, bool enabled, bool checked, bool is_default); // Sets the label of the item at the specified index. void SetMenuItemLabel(size_t menu_index, size_t model_index, const std::u16string& label); // Updates the local data structure with the correctly formatted version of // |label| at the specified model_index, and adds string data to |mii| if // the menu is not owner-draw. That's a mouthful. This function exists because // of the peculiarities of the Windows menu API. void UpdateMenuItemInfoForString(MENUITEMINFO* mii, size_t model_index, const std::u16string& label); // Resets the native menu stored in |menu_| by destroying any old menu then // creating a new empty one. void ResetNativeMenu(); // Our attached model and delegate. raw_ptr<ui::MenuModel> model_; HMENU menu_; // True if the contents of menu items in this menu are drawn by the menu host // window, rather than Windows. bool owner_draw_; // An object that collects all of the data associated with an individual menu // item. struct ItemData; std::vector<std::unique_ptr<ItemData>> items_; // The HWND this menu is the system menu for, or NULL if the menu is not a // system menu. HWND system_menu_for_; // The index of the first item in the model in the menu. size_t first_item_index_; // If we're a submenu, this is our parent. raw_ptr<NativeMenuWin> parent_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/native_menu_win.h
C++
unknown
3,850
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/submenu_view.h" #include <algorithm> #include <numeric> #include <set> #include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/numerics/safe_conversions.h" #include "base/ranges/algorithm.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/ime/input_method.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/owned_window_anchor.h" #include "ui/base/ui_base_types.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/paint_recorder.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/menu/menu_config.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/views/controls/menu/menu_host.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/menu_scroll_view_container.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" namespace { // Height of the drop indicator. This should be an even number. constexpr int kDropIndicatorHeight = 2; } // namespace namespace views { SubmenuView::SubmenuView(MenuItemView* parent) : parent_menu_item_(parent), host_(nullptr), drop_item_(nullptr), scroll_view_container_(nullptr), scroll_animator_(new ScrollAnimator(this)), prefix_selector_(this, this) { DCHECK(parent); // We'll delete ourselves, otherwise the ScrollView would delete us on close. set_owned_by_client(); } SubmenuView::~SubmenuView() { // The menu may not have been closed yet (it will be hidden, but not // necessarily closed). Close(); delete scroll_view_container_; } bool SubmenuView::HasEmptyMenuItemView() const { return base::Contains(children(), MenuItemView::kEmptyMenuItemViewID, &View::GetID); } bool SubmenuView::HasVisibleChildren() const { return base::ranges::any_of(GetMenuItems(), [](const MenuItemView* item) { return item->GetVisible(); }); } SubmenuView::MenuItems SubmenuView::GetMenuItems() const { MenuItems menu_items; for (View* child : children()) { if (child->GetID() == MenuItemView::kMenuItemViewID) menu_items.push_back(static_cast<MenuItemView*>(child)); } return menu_items; } MenuItemView* SubmenuView::GetMenuItemAt(size_t index) { const MenuItems menu_items = GetMenuItems(); DCHECK_LT(index, menu_items.size()); return menu_items[index]; } PrefixSelector* SubmenuView::GetPrefixSelector() { return &prefix_selector_; } void SubmenuView::ChildPreferredSizeChanged(View* child) { if (!resize_open_menu_) return; MenuItemView* item = parent_menu_item_; MenuController* controller = item->GetMenuController(); if (controller) { bool dir; ui::OwnedWindowAnchor anchor; gfx::Rect bounds = controller->CalculateMenuBounds(item, false, &dir, &anchor); Reposition(bounds, anchor); } } void SubmenuView::Layout() { // We're in a ScrollView, and need to set our width/height ourselves. if (!parent()) return; // Use our current y, unless it means part of the menu isn't visible anymore. int pref_height = GetPreferredSize().height(); int new_y; if (pref_height > parent()->height()) new_y = std::max(parent()->height() - pref_height, y()); else new_y = 0; SetBounds(x(), new_y, parent()->width(), pref_height); gfx::Insets insets = GetInsets(); int x = insets.left(); int y = insets.top(); int menu_item_width = width() - insets.width(); for (View* child : children()) { if (child->GetVisible()) { int child_height = child->GetHeightForWidth(menu_item_width); child->SetBounds(x, y, menu_item_width, child_height); y += child_height; } } } gfx::Size SubmenuView::CalculatePreferredSize() const { if (children().empty()) return gfx::Size(); max_minor_text_width_ = 0; // The maximum width of items which contain maybe a label and multiple views. int max_complex_width = 0; // The max. width of items which contain a label and maybe an accelerator. int max_simple_width = 0; // The minimum width of touchable items. int touchable_minimum_width = 0; // We perform the size calculation in two passes. In the first pass, we // calculate the width of the menu. In the second, we calculate the height // using that width. This allows views that have flexible widths to adjust // accordingly. for (const View* child : children()) { if (!child->GetVisible()) continue; if (child->GetID() == MenuItemView::kMenuItemViewID) { const MenuItemView* menu = static_cast<const MenuItemView*>(child); const MenuItemView::MenuItemDimensions& dimensions = menu->GetDimensions(); max_simple_width = std::max(max_simple_width, dimensions.standard_width); max_minor_text_width_ = std::max(max_minor_text_width_, dimensions.minor_text_width); max_complex_width = std::max(max_complex_width, dimensions.standard_width + dimensions.children_width); touchable_minimum_width = dimensions.standard_width; } else { max_complex_width = std::max(max_complex_width, child->GetPreferredSize().width()); } } if (max_minor_text_width_ > 0) max_minor_text_width_ += MenuConfig::instance().item_horizontal_padding; // Finish calculating our optimum width. gfx::Insets insets = GetInsets(); int width = std::max( max_complex_width, std::max(max_simple_width + max_minor_text_width_ + insets.width(), minimum_preferred_width_ - 2 * insets.width())); if (parent_menu_item_->GetMenuController() && parent_menu_item_->GetMenuController()->use_ash_system_ui_layout()) { width = std::max(touchable_minimum_width, width); } // Then, the height for that width. const int menu_item_width = width - insets.width(); const auto get_height = [menu_item_width](int height, const View* child) { return height + (child->GetVisible() ? child->GetHeightForWidth(menu_item_width) : 0); }; const int height = std::accumulate(children().cbegin(), children().cend(), 0, get_height); return gfx::Size(width, height + insets.height()); } void SubmenuView::GetAccessibleNodeData(ui::AXNodeData* node_data) { // Inherit most of the state from the parent menu item, except the role and // the orientation. if (parent_menu_item_) parent_menu_item_->GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kMenu; // Menus in Chrome are always traversed in a vertical direction. node_data->AddState(ax::mojom::State::kVertical); } void SubmenuView::PaintChildren(const PaintInfo& paint_info) { View::PaintChildren(paint_info); bool paint_drop_indicator = false; if (drop_item_) { switch (drop_position_) { case MenuDelegate::DropPosition::kNone: case MenuDelegate::DropPosition::kOn: break; case MenuDelegate::DropPosition::kUnknow: case MenuDelegate::DropPosition::kBefore: case MenuDelegate::DropPosition::kAfter: paint_drop_indicator = true; break; } } if (paint_drop_indicator) { gfx::Rect bounds = CalculateDropIndicatorBounds(drop_item_, drop_position_); ui::PaintRecorder recorder(paint_info.context(), size()); const SkColor drop_indicator_color = GetColorProvider()->GetColor(ui::kColorMenuDropmarker); recorder.canvas()->FillRect(bounds, drop_indicator_color); } } bool SubmenuView::GetDropFormats( int* formats, std::set<ui::ClipboardFormatType>* format_types) { DCHECK(parent_menu_item_->GetMenuController()); return parent_menu_item_->GetMenuController()->GetDropFormats(this, formats, format_types); } bool SubmenuView::AreDropTypesRequired() { DCHECK(parent_menu_item_->GetMenuController()); return parent_menu_item_->GetMenuController()->AreDropTypesRequired(this); } bool SubmenuView::CanDrop(const OSExchangeData& data) { DCHECK(parent_menu_item_->GetMenuController()); return parent_menu_item_->GetMenuController()->CanDrop(this, data); } void SubmenuView::OnDragEntered(const ui::DropTargetEvent& event) { DCHECK(parent_menu_item_->GetMenuController()); parent_menu_item_->GetMenuController()->OnDragEntered(this, event); } int SubmenuView::OnDragUpdated(const ui::DropTargetEvent& event) { DCHECK(parent_menu_item_->GetMenuController()); return parent_menu_item_->GetMenuController()->OnDragUpdated(this, event); } void SubmenuView::OnDragExited() { DCHECK(parent_menu_item_->GetMenuController()); parent_menu_item_->GetMenuController()->OnDragExited(this); } views::View::DropCallback SubmenuView::GetDropCallback( const ui::DropTargetEvent& event) { DCHECK(parent_menu_item_->GetMenuController()); return parent_menu_item_->GetMenuController()->GetDropCallback(this, event); } bool SubmenuView::OnMouseWheel(const ui::MouseWheelEvent& e) { gfx::Rect vis_bounds = GetVisibleBounds(); const auto menu_items = GetMenuItems(); if (vis_bounds.height() == height() || menu_items.empty()) { // All menu items are visible, nothing to scroll. return true; } auto i = base::ranges::lower_bound(menu_items, vis_bounds.y(), {}, &MenuItemView::y); if (i == menu_items.cend()) return true; // If the first item isn't entirely visible, make it visible, otherwise make // the next/previous one entirely visible. If enough wasn't scrolled to show // any new rows, then just scroll the amount so that smooth scrolling using // the trackpad is possible. int delta = abs(e.y_offset() / ui::MouseWheelEvent::kWheelDelta); if (delta == 0) return OnScroll(0, e.y_offset()); const auto scrolled_to_top = [&vis_bounds](const MenuItemView* item) { return item->y() == vis_bounds.y(); }; if (i != menu_items.cbegin() && !scrolled_to_top(*i)) --i; for (bool scroll_up = (e.y_offset() > 0); delta != 0; --delta) { int scroll_target; if (scroll_up) { if (scrolled_to_top(*i)) { if (i == menu_items.cbegin()) break; --i; } scroll_target = (*i)->y(); } else { const auto next_iter = std::next(i); if (next_iter == menu_items.cend()) break; scroll_target = (*next_iter)->y(); if (scrolled_to_top(*i)) i = next_iter; } ScrollRectToVisible( gfx::Rect(gfx::Point(0, scroll_target), vis_bounds.size())); vis_bounds = GetVisibleBounds(); } return true; } void SubmenuView::OnGestureEvent(ui::GestureEvent* event) { bool handled = true; switch (event->type()) { case ui::ET_GESTURE_SCROLL_BEGIN: scroll_animator_->Stop(); break; case ui::ET_GESTURE_SCROLL_UPDATE: handled = OnScroll(0, event->details().scroll_y()); break; case ui::ET_GESTURE_SCROLL_END: break; case ui::ET_SCROLL_FLING_START: if (event->details().velocity_y() != 0.0f) scroll_animator_->Start(0, event->details().velocity_y()); break; case ui::ET_GESTURE_TAP_DOWN: case ui::ET_SCROLL_FLING_CANCEL: if (scroll_animator_->is_scrolling()) scroll_animator_->Stop(); else handled = false; break; default: handled = false; break; } if (handled) event->SetHandled(); } size_t SubmenuView::GetRowCount() { return GetMenuItems().size(); } absl::optional<size_t> SubmenuView::GetSelectedRow() { const auto menu_items = GetMenuItems(); const auto i = base::ranges::find_if(menu_items, &MenuItemView::IsSelected); return (i == menu_items.cend()) ? absl::nullopt : absl::make_optional(static_cast<size_t>( std::distance(menu_items.cbegin(), i))); } void SubmenuView::SetSelectedRow(absl::optional<size_t> row) { parent_menu_item_->GetMenuController()->SetSelection( GetMenuItemAt(row.value()), MenuController::SELECTION_DEFAULT); } std::u16string SubmenuView::GetTextForRow(size_t row) { return MenuItemView::GetAccessibleNameForMenuItem( GetMenuItemAt(row)->title(), std::u16string(), GetMenuItemAt(row)->ShouldShowNewBadge()); } bool SubmenuView::IsShowing() const { return host_ && host_->IsMenuHostVisible(); } void SubmenuView::ShowAt(const MenuHost::InitParams& init_params) { if (host_) { host_->SetMenuHostBounds(init_params.bounds); host_->ShowMenuHost(init_params.do_capture); } else { host_ = new MenuHost(this); // Force construction of the scroll view container. GetScrollViewContainer(); // Force a layout since our preferred size may not have changed but our // content may have. InvalidateLayout(); MenuHost::InitParams new_init_params = init_params; new_init_params.contents_view = scroll_view_container_; host_->InitMenuHost(new_init_params); } // Only fire kMenuStart when a top level menu is being shown to notify that // menu interaction is about to begin. Note that the ScrollViewContainer // is not exposed as a kMenu, but as a kMenuBar for most platforms and a // kNone on the Mac. See MenuScrollViewContainer::GetAccessibleNodeData. if (!GetMenuItem()->GetParentMenuItem()) { GetScrollViewContainer()->NotifyAccessibilityEvent( ax::mojom::Event::kMenuStart, true); } // Fire kMenuPopupStart for each menu/submenu that is shown. NotifyAccessibilityEvent(ax::mojom::Event::kMenuPopupStart, true); } void SubmenuView::Reposition(const gfx::Rect& bounds, const ui::OwnedWindowAnchor& anchor) { if (host_) { // Anchor must be updated first. host_->SetMenuHostOwnedWindowAnchor(anchor); host_->SetMenuHostBounds(bounds); } } void SubmenuView::Close() { if (host_) { host_->DestroyMenuHost(); host_ = nullptr; } } void SubmenuView::Hide() { if (host_) { /// -- Fire accessibility events ---- // Both of these must be fired before HideMenuHost(). // Only fire kMenuEnd when a top level menu closes, not for each submenu. // This is sent before kMenuPopupEnd to allow ViewAXPlatformNodeDelegate to // remove its focus override before AXPlatformNodeAuraLinux needs to access // the previously-focused node while handling kMenuPopupEnd. if (!GetMenuItem()->GetParentMenuItem()) { GetScrollViewContainer()->NotifyAccessibilityEvent( ax::mojom::Event::kMenuEnd, true); GetViewAccessibility().EndPopupFocusOverride(); } // Fire these kMenuPopupEnd for each menu/submenu that closes/hides. if (host_->IsVisible()) NotifyAccessibilityEvent(ax::mojom::Event::kMenuPopupEnd, true); host_->HideMenuHost(); } if (scroll_animator_->is_scrolling()) scroll_animator_->Stop(); } void SubmenuView::ReleaseCapture() { if (host_) host_->ReleaseMenuHostCapture(); } bool SubmenuView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) { return views::FocusManager::IsTabTraversalKeyEvent(e); } MenuItemView* SubmenuView::GetMenuItem() { return parent_menu_item_; } void SubmenuView::SetDropMenuItem(MenuItemView* item, MenuDelegate::DropPosition position) { if (drop_item_ == item && drop_position_ == position) return; SchedulePaintForDropIndicator(drop_item_, drop_position_); MenuItemView* old_drop_item = drop_item_; drop_item_ = item; drop_position_ = position; if (!old_drop_item || !item) { // Whether the selection is actually drawn // (`MenuItemView:last_paint_as_selected_`) depends upon whether there is a // drop item. Find the selected item and have it updates its paint as // selected state. for (View* child : children()) { if (!child->GetVisible() || child->GetID() != MenuItemView::kMenuItemViewID) { continue; } MenuItemView* child_menu_item = static_cast<MenuItemView*>(child); if (child_menu_item->IsSelected()) { child_menu_item->OnDropOrSelectionStatusMayHaveChanged(); // Only one menu item is selected, so no need to continue iterating once // the selected item is found. break; } } } else { if (old_drop_item && old_drop_item != drop_item_) old_drop_item->OnDropOrSelectionStatusMayHaveChanged(); if (drop_item_) drop_item_->OnDropOrSelectionStatusMayHaveChanged(); } SchedulePaintForDropIndicator(drop_item_, drop_position_); } bool SubmenuView::GetShowSelection(const MenuItemView* item) const { if (drop_item_ == nullptr) return true; // Something is being dropped on one of this menus items. Show the // selection if the drop is on the passed in item and the drop position is // ON. return (drop_item_ == item && drop_position_ == MenuDelegate::DropPosition::kOn); } MenuScrollViewContainer* SubmenuView::GetScrollViewContainer() { if (!scroll_view_container_) { scroll_view_container_ = new MenuScrollViewContainer(this); // Otherwise MenuHost would delete us. scroll_view_container_->set_owned_by_client(); scroll_view_container_->SetBorderColorId(border_color_id_); } return scroll_view_container_; } MenuItemView* SubmenuView::GetLastItem() { const auto menu_items = GetMenuItems(); return menu_items.empty() ? nullptr : menu_items.back(); } void SubmenuView::MenuHostDestroyed() { host_ = nullptr; MenuController* controller = parent_menu_item_->GetMenuController(); if (controller) controller->Cancel(MenuController::ExitType::kDestroyed); } void SubmenuView::OnBoundsChanged(const gfx::Rect& previous_bounds) { SchedulePaint(); } void SubmenuView::SchedulePaintForDropIndicator( MenuItemView* item, MenuDelegate::DropPosition position) { if (item == nullptr) return; if (position == MenuDelegate::DropPosition::kOn) { item->SchedulePaint(); } else if (position != MenuDelegate::DropPosition::kNone) { SchedulePaintInRect(CalculateDropIndicatorBounds(item, position)); } } gfx::Rect SubmenuView::CalculateDropIndicatorBounds( MenuItemView* item, MenuDelegate::DropPosition position) { DCHECK(position != MenuDelegate::DropPosition::kNone); gfx::Rect item_bounds = item->bounds(); switch (position) { case MenuDelegate::DropPosition::kBefore: item_bounds.Offset(0, -kDropIndicatorHeight / 2); item_bounds.set_height(kDropIndicatorHeight); return item_bounds; case MenuDelegate::DropPosition::kAfter: item_bounds.Offset(0, item_bounds.height() - kDropIndicatorHeight / 2); item_bounds.set_height(kDropIndicatorHeight); return item_bounds; default: // Don't render anything for on. return gfx::Rect(); } } bool SubmenuView::OnScroll(float dx, float dy) { const gfx::Rect& vis_bounds = GetVisibleBounds(); const gfx::Rect& full_bounds = bounds(); int x = vis_bounds.x(); float y_f = vis_bounds.y() - dy - roundoff_error_; int y = base::ClampRound(y_f); roundoff_error_ = y - y_f; // Ensure that we never try to scroll outside the actual child view. // Note: the old code here was effectively: // std::clamp(y, 0, full_bounds.height() - vis_bounds.height() - 1) // but the -1 there prevented fully scrolling to the bottom here. As a // worked example, suppose that: // full_bounds = { x = 0, y = 0, w = 100, h = 1000 } // vis_bounds = { x = 0, y = 450, w = 100, h = 500 } // and dy = 50. It should be the case that the new vis_bounds are: // new_vis_bounds = { x = 0, y = 500, w = 100, h = 500 } // because full_bounds.height() - vis_bounds.height() == 500. Intuitively, // this makes sense - the bottom 500 pixels of this view, starting with y = // 500, are shown. // // With the clamp set to full_bounds.height() - vis_bounds.height() - 1, // this code path instead would produce: // new_vis_bounds = { x = 0, y = 499, w = 100, h = 500 } // so pixels y=499 through y=998 of this view are drawn, and pixel y=999 is // hidden - oops. y = std::clamp(y, 0, full_bounds.height() - vis_bounds.height()); gfx::Rect new_vis_bounds(x, y, vis_bounds.width(), vis_bounds.height()); if (new_vis_bounds != vis_bounds) { ScrollRectToVisible(new_vis_bounds); return true; } return false; } void SubmenuView::SetBorderColorId(absl::optional<ui::ColorId> color_id) { if (scroll_view_container_) { scroll_view_container_->SetBorderColorId(color_id); } border_color_id_ = color_id; } BEGIN_METADATA(SubmenuView, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/submenu_view.cc
C++
unknown
20,872
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_ #define UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_ #include <memory> #include <set> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/views/animation/scroll_animator.h" #include "ui/views/controls/menu/menu_delegate.h" #include "ui/views/controls/menu/menu_host.h" #include "ui/views/controls/prefix_delegate.h" #include "ui/views/controls/prefix_selector.h" #include "ui/views/view.h" namespace ui { struct OwnedWindowAnchor; } // namespace ui namespace views { class MenuItemView; class MenuScrollViewContainer; namespace test { class MenuControllerTest; } // namespace test // SubmenuView is the parent of all menu items. // // SubmenuView has the following responsibilities: // . It positions and sizes all child views (any type of View may be added, // not just MenuItemViews). // . Forwards the appropriate events to the MenuController. This allows the // MenuController to update the selection as the user moves the mouse around. // . Renders the drop indicator during a drop operation. // . Shows and hides the window (a NativeWidget) when the menu is shown on // screen. // // SubmenuView is itself contained in a MenuScrollViewContainer. // MenuScrollViewContainer handles showing as much of the SubmenuView as the // screen allows. If the SubmenuView is taller than the screen, scroll buttons // are provided that allow the user to see all the menu items. class VIEWS_EXPORT SubmenuView : public View, public PrefixDelegate, public ScrollDelegate { public: METADATA_HEADER(SubmenuView); using MenuItems = std::vector<MenuItemView*>; // Creates a SubmenuView for the specified menu item. explicit SubmenuView(MenuItemView* parent); SubmenuView(const SubmenuView&) = delete; SubmenuView& operator=(const SubmenuView&) = delete; ~SubmenuView() override; // Returns true if the submenu has at least one empty menu item. bool HasEmptyMenuItemView() const; // Returns true if the submenu has at least one visible child item. bool HasVisibleChildren() const; // Returns the children which are menu items. MenuItems GetMenuItems() const; // Returns the MenuItemView at the specified index. MenuItemView* GetMenuItemAt(size_t index); PrefixSelector* GetPrefixSelector(); // Positions and sizes the child views. This tiles the views vertically, // giving each child the available width. void Layout() override; gfx::Size CalculatePreferredSize() const override; // Override from View. void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // Painting. void PaintChildren(const PaintInfo& paint_info) override; // Drag and drop methods. These are forwarded to the MenuController. bool GetDropFormats(int* formats, std::set<ui::ClipboardFormatType>* format_types) override; bool AreDropTypesRequired() override; bool CanDrop(const OSExchangeData& data) override; void OnDragEntered(const ui::DropTargetEvent& event) override; int OnDragUpdated(const ui::DropTargetEvent& event) override; void OnDragExited() override; views::View::DropCallback GetDropCallback( const ui::DropTargetEvent& event) override; // Scrolls on menu item boundaries. bool OnMouseWheel(const ui::MouseWheelEvent& e) override; // Overridden from ui::EventHandler. // Scrolls on menu item boundaries. void OnGestureEvent(ui::GestureEvent* event) override; // Overridden from PrefixDelegate. size_t GetRowCount() override; absl::optional<size_t> GetSelectedRow() override; void SetSelectedRow(absl::optional<size_t> row) override; std::u16string GetTextForRow(size_t row) override; // Returns true if the menu is showing. virtual bool IsShowing() const; // Shows the menu using the specified |init_params|. |init_params.bounds| are // in screen coordinates. void ShowAt(const MenuHost::InitParams& init_params); // Resets the bounds of the submenu to |bounds| and its anchor to |anchor|. void Reposition(const gfx::Rect& bounds, const ui::OwnedWindowAnchor& anchor); // Closes the menu, destroying the host. void Close(); // Hides the hosting window. // // The hosting window is hidden first, then deleted (Close) when the menu is // done running. This is done to avoid deletion ordering dependencies. In // particular, during drag and drop (and when a modal dialog is shown as // a result of choosing a context menu) it is possible that an event is // being processed by the host, so that host is on the stack when we need to // close the window. If we closed the window immediately (and deleted it), // when control returned back to host we would crash as host was deleted. void Hide(); // If mouse capture was grabbed, it is released. Does nothing if mouse was // not captured. void ReleaseCapture(); // Overriden from View to prevent tab from doing anything. bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) override; // Returns the parent menu item we're showing children for. MenuItemView* GetMenuItem(); // Set the drop item and position. void SetDropMenuItem(MenuItemView* item, MenuDelegate::DropPosition position); // Returns whether the selection should be shown for the specified item. // The selection is NOT shown during drag and drop when the drop is over // the menu. bool GetShowSelection(const MenuItemView* item) const; // Returns the container for the SubmenuView. MenuScrollViewContainer* GetScrollViewContainer(); // Returns the last MenuItemView in this submenu. MenuItemView* GetLastItem(); // Invoked if the menu is prematurely destroyed. This can happen if the window // closes while the menu is shown. If invoked the SubmenuView must drop all // references to the MenuHost as the MenuHost is about to be deleted. void MenuHostDestroyed(); // Max width of minor text (accelerator or subtitle) in child menu items. This // doesn't include children's children, only direct children. int max_minor_text_width() const { return max_minor_text_width_; } // Minimum width of menu in pixels (default 0). This becomes the smallest // width returned by GetPreferredSize(). void set_minimum_preferred_width(int minimum_preferred_width) { minimum_preferred_width_ = minimum_preferred_width; } // Automatically resize menu if a subview's preferred size changes. bool resize_open_menu() const { return resize_open_menu_; } void set_resize_open_menu(bool resize_open_menu) { resize_open_menu_ = resize_open_menu; } MenuHost* host() { return host_; } void SetBorderColorId(absl::optional<ui::ColorId> color_id); protected: // View method. Overridden to schedule a paint. We do this so that when // scrolling occurs, everything is repainted correctly. void OnBoundsChanged(const gfx::Rect& previous_bounds) override; void ChildPreferredSizeChanged(View* child) override; private: friend class test::MenuControllerTest; void SchedulePaintForDropIndicator(MenuItemView* item, MenuDelegate::DropPosition position); // Calculates the location of th edrop indicator. gfx::Rect CalculateDropIndicatorBounds(MenuItemView* item, MenuDelegate::DropPosition position); // Implementation of ScrollDelegate bool OnScroll(float dx, float dy) override; // Parent menu item. raw_ptr<MenuItemView> parent_menu_item_; // Widget subclass used to show the children. This is deleted when we invoke // |DestroyMenuHost|, or |MenuHostDestroyed| is invoked back on us. raw_ptr<MenuHost> host_; // If non-null, indicates a drop is in progress and drop_item is the item // the drop is over. raw_ptr<MenuItemView> drop_item_; // Position of the drop. MenuDelegate::DropPosition drop_position_ = MenuDelegate::DropPosition::kNone; // Ancestor of the SubmenuView, lazily created. raw_ptr<MenuScrollViewContainer, DanglingUntriaged> scroll_view_container_; // See description above getter. mutable int max_minor_text_width_ = 0; // Minimum width returned in GetPreferredSize(). int minimum_preferred_width_ = 0; // Reposition open menu when contained views change size. bool resize_open_menu_ = false; // The submenu's scroll animator std::unique_ptr<ScrollAnimator> scroll_animator_; // Difference between current position and cumulative deltas passed to // OnScroll. // TODO(tdresser): This should be removed when raw pixel scrolling for views // is enabled. See crbug.com/329354. float roundoff_error_ = 0; PrefixSelector prefix_selector_; absl::optional<ui::ColorId> border_color_id_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/submenu_view.h
C++
unknown
8,967
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/submenu_view.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/test/views_test_base.h" namespace views { using SubmenuViewTest = ViewsTestBase; TEST_F(SubmenuViewTest, GetLastItem) { MenuItemView* parent = new MenuItemView(); MenuRunner menu_runner(parent, 0); SubmenuView* submenu = parent->CreateSubmenu(); EXPECT_EQ(nullptr, submenu->GetLastItem()); submenu->AddChildView(new View()); EXPECT_EQ(nullptr, submenu->GetLastItem()); MenuItemView* first = new MenuItemView(); submenu->AddChildView(first); EXPECT_EQ(first, submenu->GetLastItem()); submenu->AddChildView(new View()); EXPECT_EQ(first, submenu->GetLastItem()); MenuItemView* second = new MenuItemView(); submenu->AddChildView(second); EXPECT_EQ(second, submenu->GetLastItem()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/submenu_view_unittest.cc
C++
unknown
1,097
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/test_menu_item_view.h" namespace views { TestMenuItemView::TestMenuItemView() = default; TestMenuItemView::TestMenuItemView(MenuDelegate* delegate) : MenuItemView(delegate) {} TestMenuItemView::~TestMenuItemView() = default; } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/test_menu_item_view.cc
C++
unknown
433
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_MENU_TEST_MENU_ITEM_VIEW_H_ #define UI_VIEWS_CONTROLS_MENU_TEST_MENU_ITEM_VIEW_H_ #include "ui/views/controls/menu/menu_item_view.h" namespace views { class MenuDelegate; // A MenuItemView implementation with a public destructor (so we can clean up // in tests). class TestMenuItemView : public MenuItemView { public: TestMenuItemView(); explicit TestMenuItemView(MenuDelegate* delegate); TestMenuItemView(const TestMenuItemView&) = delete; TestMenuItemView& operator=(const TestMenuItemView&) = delete; ~TestMenuItemView() override; using MenuItemView::AddEmptyMenus; void set_has_mnemonics(bool has_mnemonics) { has_mnemonics_ = has_mnemonics; } bool show_mnemonics() { return show_mnemonics_; } static ImageView* submenu_arrow_image_view(MenuItemView* view) { return view->submenu_arrow_image_view_; } }; } // namespace views #endif // UI_VIEWS_CONTROLS_MENU_TEST_MENU_ITEM_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/menu/test_menu_item_view.h
C++
unknown
1,094
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/message_box_view.h" #include <stddef.h> #include <memory> #include <numeric> #include <utility> #include "base/functional/bind.h" #include "base/i18n/rtl.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/accessibility/accessibility_paint_checks.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/label.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/views/window/dialog_delegate.h" namespace { constexpr int kDefaultMessageWidth = 400; // Paragraph separators are defined in // http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedBidiClass.txt // // # Bidi_Class=Paragraph_Separator // // 000A ; B # Cc <control-000A> // 000D ; B # Cc <control-000D> // 001C..001E ; B # Cc [3] <control-001C>..<control-001E> // 0085 ; B # Cc <control-0085> // 2029 ; B # Zp PARAGRAPH SEPARATOR bool IsParagraphSeparator(char16_t c) { return (c == 0x000A || c == 0x000D || c == 0x001C || c == 0x001D || c == 0x001E || c == 0x0085 || c == 0x2029); } // Splits |text| into a vector of paragraphs. // Given an example "\nabc\ndef\n\n\nhij\n", the split results should be: // "", "abc", "def", "", "", "hij", and "". void SplitStringIntoParagraphs(const std::u16string& text, std::vector<std::u16string>* paragraphs) { paragraphs->clear(); size_t start = 0; for (size_t i = 0; i < text.length(); ++i) { if (IsParagraphSeparator(text[i])) { paragraphs->push_back(text.substr(start, i - start)); start = i + 1; } } paragraphs->push_back(text.substr(start, text.length() - start)); } } // namespace namespace views { /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, public: MessageBoxView::MessageBoxView(const std::u16string& message, bool detect_directionality) : inter_row_vertical_spacing_(LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_CONTROL_VERTICAL)), message_width_(kDefaultMessageWidth) { const LayoutProvider* provider = LayoutProvider::Get(); auto horizontal_insets = GetHorizontalInsets(provider); auto message_contents = Builder<BoxLayoutView>() .SetOrientation(BoxLayout::Orientation::kVertical) // We explicitly set insets on the message contents instead of the // scroll view so that the scroll view borders are not capped by // dialog insets. .SetBorder(CreateEmptyBorder(GetHorizontalInsets(provider))); auto add_label = [&message_contents, this]( const std::u16string& text, gfx::HorizontalAlignment alignment) { message_contents.AddChild( Builder<Label>() .SetText(text) .SetTextContext(style::CONTEXT_DIALOG_BODY_TEXT) .SetMultiLine(!text.empty()) .SetAllowCharacterBreak(true) .SetHorizontalAlignment(alignment) .CustomConfigure(base::BindOnce( [](std::vector<Label*>& message_labels, Label* message_label) { message_labels.push_back(message_label); }, std::ref(message_labels_)))); }; if (detect_directionality) { std::vector<std::u16string> texts; SplitStringIntoParagraphs(message, &texts); for (const auto& text : texts) { // Avoid empty multi-line labels, which have a height of 0. add_label(text, gfx::ALIGN_TO_HEAD); } } else { add_label(message, gfx::ALIGN_LEFT); } Builder<MessageBoxView>(this) .SetOrientation(BoxLayout::Orientation::kVertical) .AddChildren( Builder<ScrollView>() .CopyAddressTo(&scroll_view_) .ClipHeightTo(0, provider->GetDistanceMetric( DISTANCE_DIALOG_SCROLLABLE_AREA_MAX_HEIGHT)) .SetContents(std::move(message_contents)), // TODO(crbug.com/1218186): Remove this, this is in place temporarily // to be able to submit accessibility checks, but this focusable View // needs to add a name so that the screen reader knows what to // announce. Builder<Textfield>() .CopyAddressTo(&prompt_field_) .SetProperty(kSkipAccessibilityPaintChecks, true) .SetProperty(kMarginsKey, horizontal_insets) .SetAccessibleName(message) .SetVisible(false) .CustomConfigure(base::BindOnce([](Textfield* prompt_field) { prompt_field->GetViewAccessibility().OverrideIsIgnored(true); })), Builder<Checkbox>() .CopyAddressTo(&checkbox_) .SetProperty(kMarginsKey, horizontal_insets) .SetVisible(false), Builder<Link>() .CopyAddressTo(&link_) .SetProperty(kMarginsKey, horizontal_insets) .SetHorizontalAlignment(gfx::ALIGN_LEFT) .SetVisible(false)) .BuildChildren(); // Don't enable text selection if multiple labels are used, since text // selection can't span multiple labels. if (message_labels_.size() == 1u) message_labels_[0]->SetSelectable(true); ResetLayoutManager(); } MessageBoxView::~MessageBoxView() = default; views::Textfield* MessageBoxView::GetVisiblePromptField() { return prompt_field_ && prompt_field_->GetVisible() ? prompt_field_.get() : nullptr; } std::u16string MessageBoxView::GetInputText() { return prompt_field_ && prompt_field_->GetVisible() ? prompt_field_->GetText() : std::u16string(); } bool MessageBoxView::HasVisibleCheckBox() const { return checkbox_ && checkbox_->GetVisible(); } bool MessageBoxView::IsCheckBoxSelected() { return checkbox_ && checkbox_->GetVisible() && checkbox_->GetChecked(); } void MessageBoxView::SetCheckBoxLabel(const std::u16string& label) { DCHECK(checkbox_); if (checkbox_->GetVisible() && checkbox_->GetText() == label) return; checkbox_->SetText(label); checkbox_->SetVisible(true); ResetLayoutManager(); } void MessageBoxView::SetCheckBoxSelected(bool selected) { // Only update the checkbox's state after the checkbox is shown. if (!checkbox_->GetVisible()) return; checkbox_->SetChecked(selected); } void MessageBoxView::SetLink(const std::u16string& text, Link::ClickedCallback callback) { DCHECK(!text.empty()); DCHECK(!callback.is_null()); DCHECK(link_); link_->SetCallback(std::move(callback)); if (link_->GetVisible() && link_->GetText() == text) return; link_->SetText(text); link_->SetVisible(true); ResetLayoutManager(); } void MessageBoxView::SetInterRowVerticalSpacing(int spacing) { if (inter_row_vertical_spacing_ == spacing) return; inter_row_vertical_spacing_ = spacing; ResetLayoutManager(); } void MessageBoxView::SetMessageWidth(int width) { if (message_width_ == width) return; message_width_ = width; ResetLayoutManager(); } void MessageBoxView::SetPromptField(const std::u16string& default_prompt) { DCHECK(prompt_field_); if (prompt_field_->GetVisible() && prompt_field_->GetText() == default_prompt) return; prompt_field_->SetText(default_prompt); prompt_field_->SetVisible(true); prompt_field_->GetViewAccessibility().OverrideIsIgnored(false); // The same text visible in the message box is used as an accessible name for // the prompt. To prevent it from being announced twice, we hide the message // to ATs. scroll_view_->GetViewAccessibility().OverrideIsLeaf(true); ResetLayoutManager(); } /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, View overrides: void MessageBoxView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.child == this && details.is_add) { if (prompt_field_ && prompt_field_->GetVisible()) prompt_field_->SelectAll(true); } } bool MessageBoxView::AcceleratorPressed(const ui::Accelerator& accelerator) { // We only accept Ctrl-C. DCHECK(accelerator.key_code() == 'C' && accelerator.IsCtrlDown()); // We must not intercept Ctrl-C when we have a text box and it's focused. if (prompt_field_ && prompt_field_->HasFocus()) return false; // Don't intercept Ctrl-C if we only use a single message label supporting // text selection. if (message_labels_.size() == 1u && message_labels_[0]->GetSelectable()) return false; ui::ScopedClipboardWriter scw(ui::ClipboardBuffer::kCopyPaste); scw.WriteText(std::accumulate(message_labels_.cbegin(), message_labels_.cend(), std::u16string(), [](const std::u16string& left, Label* right) { return left + right->GetText(); })); return true; } /////////////////////////////////////////////////////////////////////////////// // MessageBoxView, private: void MessageBoxView::ResetLayoutManager() { SetBetweenChildSpacing(inter_row_vertical_spacing_); SetMinimumCrossAxisSize(message_width_); scroll_view_->SetPreferredSize(gfx::Size(message_width_, 0)); views::DialogContentType trailing_content_type = views::DialogContentType::kText; if (prompt_field_->GetVisible()) trailing_content_type = views::DialogContentType::kControl; bool checkbox_is_visible = checkbox_->GetVisible(); if (checkbox_is_visible) trailing_content_type = views::DialogContentType::kText; // Ignored views are not in the accessibility tree, but their children // still can be exposed. Leaf views have no accessible children. checkbox_->GetViewAccessibility().OverrideIsIgnored(!checkbox_is_visible); checkbox_->GetViewAccessibility().OverrideIsLeaf(!checkbox_is_visible); if (link_->GetVisible()) trailing_content_type = views::DialogContentType::kText; const LayoutProvider* provider = LayoutProvider::Get(); gfx::Insets border_insets = provider->GetDialogInsetsForContentType( views::DialogContentType::kText, trailing_content_type); // Horizontal insets have already been applied to the message contents and // controls as padding columns. Only apply the missing vertical insets. border_insets.set_left_right(0, 0); SetBorder(CreateEmptyBorder(border_insets)); InvalidateLayout(); } gfx::Insets MessageBoxView::GetHorizontalInsets( const LayoutProvider* provider) { gfx::Insets horizontal_insets = provider->GetInsetsMetric(views::INSETS_DIALOG); horizontal_insets.set_top_bottom(0, 0); return horizontal_insets; } BEGIN_METADATA(MessageBoxView, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/message_box_view.cc
C++
unknown
11,627
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_ #define UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_ #include <stdint.h> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/controls/link.h" #include "ui/views/layout/box_layout_view.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" namespace views { class Checkbox; class Label; class LayoutProvider; class ScrollView; class Textfield; // This class displays the contents of a message box. It is intended for use // within a constrained window, and has options for a message, prompt, OK // and Cancel buttons. class VIEWS_EXPORT MessageBoxView : public BoxLayoutView { public: METADATA_HEADER(MessageBoxView); // |detect_directionality| indicates whether |message|'s directionality is // auto-detected. // For a message from a web page (not from Chrome's UI), such as script // dialog text, each paragraph's directionality is auto-detected using the // directionality of the paragraph's first strong character's. Please refer // to HTML5 spec for details. // http://dev.w3.org/html5/spec/Overview.html#text-rendered-in-native-user-interfaces: // The spec does not say anything about alignment. And we choose to // align all paragraphs according to the direction of the first paragraph. explicit MessageBoxView(const std::u16string& message = std::u16string(), bool detect_directionality = false); MessageBoxView(const MessageBoxView&) = delete; MessageBoxView& operator=(const MessageBoxView&) = delete; ~MessageBoxView() override; // Returns the visible prompt field, returns nullptr otherwise. views::Textfield* GetVisiblePromptField(); // Returns user entered data in the prompt field, returns an empty string if // no visible prompt field. std::u16string GetInputText(); // Returns true if this message box has a visible checkbox, false otherwise. bool HasVisibleCheckBox() const; // Returns true if a checkbox is selected, false otherwise. (And false if // the message box has no checkbox.) bool IsCheckBoxSelected(); // Shows a checkbox with the specified label to the message box if this is the // first call. Otherwise, it changes the label of the current checkbox. To // start, the message box has no visible checkbox until this function is // called. void SetCheckBoxLabel(const std::u16string& label); // Sets the state of the check-box if it is visible. void SetCheckBoxSelected(bool selected); // Sets the text and the callback of the link. |text| must be non-empty. void SetLink(const std::u16string& text, Link::ClickedCallback callback); void SetInterRowVerticalSpacing(int spacing); void SetMessageWidth(int width); // Adds a prompt field with |default_prompt| as the displayed text. void SetPromptField(const std::u16string& default_prompt); protected: // View: void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; // Handles Ctrl-C and writes the message in the system clipboard. bool AcceleratorPressed(const ui::Accelerator& accelerator) override; private: FRIEND_TEST_ALL_PREFIXES(MessageBoxViewTest, CheckMessageOnlySize); FRIEND_TEST_ALL_PREFIXES(MessageBoxViewTest, CheckWithOptionalViewsSize); FRIEND_TEST_ALL_PREFIXES(MessageBoxViewTest, CheckInterRowHeightChange); // Sets up the layout manager based on currently initialized views and layout // parameters. Should be called when a view is initialized or changed. void ResetLayoutManager(); // Return the proper horizontal insets based on the given layout provider. gfx::Insets GetHorizontalInsets(const LayoutProvider* provider); // Message for the message box. std::vector<Label*> message_labels_; // Scrolling view containing the message labels. raw_ptr<ScrollView> scroll_view_ = nullptr; // Input text field for the message box. raw_ptr<Textfield> prompt_field_ = nullptr; // Checkbox for the message box. raw_ptr<Checkbox> checkbox_ = nullptr; // Link displayed at the bottom of the view. raw_ptr<Link> link_ = nullptr; // Spacing between rows in the grid layout. int inter_row_vertical_spacing_ = 0; // Maximum width of the message label. int message_width_ = 0; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, MessageBoxView, BoxLayoutView) VIEW_BUILDER_PROPERTY(const std::u16string&, CheckBoxLabel) VIEW_BUILDER_PROPERTY(bool, CheckBoxSelected) VIEW_BUILDER_METHOD(SetLink, const std::u16string&, Link::ClickedCallback) VIEW_BUILDER_PROPERTY(int, InterRowVerticalSpacing) VIEW_BUILDER_PROPERTY(int, MessageWidth) VIEW_BUILDER_PROPERTY(const std::u16string&, PromptField) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, views::MessageBoxView) #endif // UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/message_box_view.h
C++
unknown
5,082
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/message_box_view.h" #include <algorithm> #include <memory> #include <string> #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/link.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/test/views_test_base.h" namespace views { namespace { // The default mesage width same as defined in message_box_view.cc. constexpr int kDefaultMessageWidth = 400; const std::u16string kDefaultMessage = u"This is a test message for MessageBoxView."; } // namespace class MessageBoxViewTest : public ViewsTestBase { public: MessageBoxViewTest() = default; MessageBoxViewTest(const MessageBoxViewTest&) = delete; MessageBoxViewTest& operator=(const MessageBoxViewTest&) = delete; ~MessageBoxViewTest() override = default; protected: void SetUp() override { ViewsTestBase::SetUp(); message_box_ = std::make_unique<MessageBoxView>(kDefaultMessage); provider_ = LayoutProvider::Get(); } std::unique_ptr<MessageBoxView> message_box_; raw_ptr<const LayoutProvider> provider_; }; TEST_F(MessageBoxViewTest, CheckMessageOnlySize) { message_box_->SizeToPreferredSize(); gfx::Insets box_border = provider_->GetDialogInsetsForContentType( views::DialogContentType::kText, views::DialogContentType::kText); gfx::Size scroll_size = message_box_->scroll_view_->size(); scroll_size.Enlarge(0, box_border.top() + box_border.bottom()); EXPECT_EQ(scroll_size, message_box_->size()); } TEST_F(MessageBoxViewTest, CheckWithOptionalViewsSize) { message_box_->SetPromptField(std::u16string()); message_box_->SizeToPreferredSize(); gfx::Insets box_border = provider_->GetDialogInsetsForContentType( views::DialogContentType::kText, views::DialogContentType::kControl); gfx::Size scroll_size = message_box_->scroll_view_->size(); gfx::Size prompt_size = message_box_->prompt_field_->size(); gfx::Size content_size(std::max(scroll_size.width(), prompt_size.width()), scroll_size.height() + prompt_size.height()); content_size.Enlarge(0, box_border.top() + box_border.bottom() + message_box_->inter_row_vertical_spacing_); EXPECT_EQ(content_size, message_box_->size()); // Add a checkbox and a link. message_box_->SetCheckBoxLabel(u"A checkbox"); message_box_->SetLink(u"Link to display", base::DoNothing()); message_box_->SizeToPreferredSize(); box_border = provider_->GetDialogInsetsForContentType( views::DialogContentType::kText, views::DialogContentType::kText); gfx::Size checkbox_size = message_box_->checkbox_->size(); gfx::Size link_size = message_box_->link_->size(); content_size = gfx::Size(std::max(std::max(scroll_size.width(), prompt_size.width()), std::max(checkbox_size.width(), link_size.width())), scroll_size.height() + prompt_size.height() + checkbox_size.height() + link_size.height()); content_size.Enlarge(0, box_border.top() + box_border.bottom() + 3 * message_box_->inter_row_vertical_spacing_); EXPECT_EQ(content_size, message_box_->size()); } TEST_F(MessageBoxViewTest, CheckMessageWidthChange) { message_box_->SizeToPreferredSize(); EXPECT_EQ(kDefaultMessageWidth, message_box_->width()); static constexpr int kNewWidth = 210; message_box_->SetMessageWidth(kNewWidth); message_box_->SizeToPreferredSize(); EXPECT_EQ(kNewWidth, message_box_->width()); } TEST_F(MessageBoxViewTest, CheckInterRowHeightChange) { message_box_->SetPromptField(std::u16string()); message_box_->SizeToPreferredSize(); int scroll_height = message_box_->scroll_view_->height(); int prompt_height = message_box_->prompt_field_->height(); gfx::Insets box_border = provider_->GetDialogInsetsForContentType( views::DialogContentType::kText, views::DialogContentType::kControl); int inter_row_spacing = message_box_->inter_row_vertical_spacing_; EXPECT_EQ( scroll_height + inter_row_spacing + prompt_height + box_border.height(), message_box_->height()); static constexpr int kNewInterRowSpacing = 50; EXPECT_NE(kNewInterRowSpacing, inter_row_spacing); message_box_->SetInterRowVerticalSpacing(kNewInterRowSpacing); message_box_->SizeToPreferredSize(); EXPECT_EQ(kNewInterRowSpacing, message_box_->inter_row_vertical_spacing_); EXPECT_EQ( scroll_height + kNewInterRowSpacing + prompt_height + box_border.height(), message_box_->height()); } TEST_F(MessageBoxViewTest, CheckHasVisibleCheckBox) { EXPECT_FALSE(message_box_->HasVisibleCheckBox()); // Set and show a checkbox. message_box_->SetCheckBoxLabel(u"test checkbox"); EXPECT_TRUE(message_box_->HasVisibleCheckBox()); } TEST_F(MessageBoxViewTest, CheckGetVisiblePromptField) { EXPECT_FALSE(message_box_->GetVisiblePromptField()); // Set the prompt field. message_box_->SetPromptField(std::u16string()); EXPECT_TRUE(message_box_->GetVisiblePromptField()); } TEST_F(MessageBoxViewTest, CheckGetInputText) { EXPECT_TRUE(message_box_->GetInputText().empty()); // Set the prompt field with an empty string. The returned text is still // empty. message_box_->SetPromptField(std::u16string()); EXPECT_TRUE(message_box_->GetInputText().empty()); const std::u16string prompt = u"prompt"; message_box_->SetPromptField(prompt); EXPECT_FALSE(message_box_->GetInputText().empty()); EXPECT_EQ(prompt, message_box_->GetInputText()); // After user types some text, the returned input text should change to the // user input. views::Textfield* text_field = message_box_->GetVisiblePromptField(); const std::u16string input = u"new input"; text_field->SetText(input); EXPECT_FALSE(message_box_->GetInputText().empty()); EXPECT_EQ(input, message_box_->GetInputText()); } TEST_F(MessageBoxViewTest, CheckIsCheckBoxSelected) { EXPECT_FALSE(message_box_->IsCheckBoxSelected()); // Set and show a checkbox. message_box_->SetCheckBoxLabel(u"test checkbox"); EXPECT_FALSE(message_box_->IsCheckBoxSelected()); // Select the checkbox. message_box_->SetCheckBoxSelected(true); EXPECT_TRUE(message_box_->IsCheckBoxSelected()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/message_box_view_unittest.cc
C++
unknown
6,693
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host.h" #include <memory> #include <utility> #include "base/check.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/canvas.h" #include "ui/views/controls/native/native_view_host_wrapper.h" #include "ui/views/painter.h" #include "ui/views/view_utils.h" #include "ui/views/widget/widget.h" namespace views { // static const char kWidgetNativeViewHostKey[] = "WidgetNativeViewHost"; //////////////////////////////////////////////////////////////////////////////// // NativeViewHost, public: NativeViewHost::NativeViewHost() { set_suppress_default_focus_handling(); } NativeViewHost::~NativeViewHost() { // As part of deleting NativeViewHostWrapper the native view is unparented. // Make sure the FocusManager is updated. ClearFocus(); } void NativeViewHost::Attach(gfx::NativeView native_view) { DCHECK(native_view); DCHECK(!native_view_); native_view_ = native_view; native_wrapper_->AttachNativeView(); InvalidateLayout(); // The call to InvalidateLayout() triggers an async call to Layout(), which // updates the visibility of the NativeView. The call to Layout() only happens // if |this| is drawn. Call hide if not drawn as otherwise the NativeView // could be visible when |this| is not. if (!IsDrawn()) native_wrapper_->HideWidget(); Widget* widget = Widget::GetWidgetForNativeView(native_view); if (widget) widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, this); } void NativeViewHost::Detach() { Detach(false); } void NativeViewHost::SetParentAccessible(gfx::NativeViewAccessible accessible) { if (!native_wrapper_) return; native_wrapper_->SetParentAccessible(accessible); } gfx::NativeViewAccessible NativeViewHost::GetParentAccessible() { if (!native_wrapper_) return nullptr; return native_wrapper_->GetParentAccessible(); } bool NativeViewHost::SetCornerRadii(const gfx::RoundedCornersF& corner_radii) { return native_wrapper_->SetCornerRadii(corner_radii); } bool NativeViewHost::SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) { DCHECK(native_wrapper_); return native_wrapper_->SetCustomMask(std::move(mask)); } void NativeViewHost::SetHitTestTopInset(int top_inset) { native_wrapper_->SetHitTestTopInset(top_inset); } int NativeViewHost::GetHitTestTopInset() const { return native_wrapper_->GetHitTestTopInset(); } void NativeViewHost::SetNativeViewSize(const gfx::Size& size) { if (native_view_size_ == size) return; native_view_size_ = size; InvalidateLayout(); } gfx::NativeView NativeViewHost::GetNativeViewContainer() const { return native_view_ ? native_wrapper_->GetNativeViewContainer() : nullptr; } void NativeViewHost::NativeViewDestroyed() { // Detach so we can clear our state and notify the native_wrapper_ to release // ref on the native view. Detach(true); } void NativeViewHost::SetBackgroundColorWhenClipped( absl::optional<SkColor> color) { background_color_when_clipped_ = color; } //////////////////////////////////////////////////////////////////////////////// // NativeViewHost, View overrides: void NativeViewHost::Layout() { if (!native_view_ || !native_wrapper_.get()) return; gfx::Rect vis_bounds = GetVisibleBounds(); bool visible = !vis_bounds.IsEmpty(); if (visible && !fast_resize_) { if (vis_bounds.size() != size()) { // Only a portion of the Widget is really visible. int x = vis_bounds.x(); int y = vis_bounds.y(); native_wrapper_->InstallClip(x, y, vis_bounds.width(), vis_bounds.height()); } else if (native_wrapper_->HasInstalledClip()) { // The whole widget is visible but we installed a clip on the widget, // uninstall it. native_wrapper_->UninstallClip(); } } if (visible) { // Since widgets know nothing about the View hierarchy (they are direct // children of the Widget that hosts our View hierarchy) they need to be // positioned in the coordinate system of the Widget, not the current // view. Also, they should be positioned respecting the border insets // of the native view. gfx::Rect local_bounds = ConvertRectToWidget(GetContentsBounds()); gfx::Size native_view_size = native_view_size_.IsEmpty() ? local_bounds.size() : native_view_size_; native_wrapper_->ShowWidget(local_bounds.x(), local_bounds.y(), local_bounds.width(), local_bounds.height(), native_view_size.width(), native_view_size.height()); } else { native_wrapper_->HideWidget(); } } void NativeViewHost::OnPaint(gfx::Canvas* canvas) { // Paint background if there is one. NativeViewHost needs to paint // a background when it is hosted in a TabbedPane. For Gtk implementation, // NativeTabbedPaneGtk uses a NativeWidgetGtk as page container and because // NativeWidgetGtk hook "expose" with its root view's paint, we need to // fill the content. Otherwise, the tab page's background is not properly // cleared. For Windows case, it appears okay to not paint background because // we don't have a container window in-between. However if you want to use // customized background, then this becomes necessary. OnPaintBackground(canvas); // The area behind our window is black, so during a fast resize (where our // content doesn't draw over the full size of our native view, and the native // view background color doesn't show up), we need to cover that blackness // with something so that fast resizes don't result in black flash. // // Affected views should set the desired color using // SetBackgroundColorWhenClipped(), otherwise the background is left // transparent to let the lower layers show through. if (native_wrapper_->HasInstalledClip()) { if (background_color_when_clipped_) { canvas->FillRect(GetLocalBounds(), *background_color_when_clipped_); } } } void NativeViewHost::VisibilityChanged(View* starting_from, bool is_visible) { // This does not use InvalidateLayout() to ensure the visibility state is // correctly set (if this View isn't visible, Layout() won't be called). Layout(); } bool NativeViewHost::GetNeedsNotificationWhenVisibleBoundsChange() const { // The native widget is placed relative to the root. As such, we need to // know when the position of any ancestor changes, or our visibility relative // to other views changed as it'll effect our position relative to the root. return true; } void NativeViewHost::OnVisibleBoundsChanged() { InvalidateLayout(); } void NativeViewHost::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { views::Widget* this_widget = GetWidget(); // A non-NULL |details.move_view| indicates a move operation i.e. |this| is // is being reparented. If the previous and new parents belong to the same // widget, don't remove |this| from the widget. This saves resources from // removing from widget and immediately followed by adding to widget; in // particular, there wouldn't be spurious visibilitychange events for web // contents of |WebView|. if (details.move_view && this_widget && details.move_view->GetWidget() == this_widget) { return; } if (details.is_add && this_widget) { if (!native_wrapper_.get()) native_wrapper_.reset(NativeViewHostWrapper::CreateWrapper(this)); native_wrapper_->AddedToWidget(); } else if (!details.is_add && native_wrapper_) { native_wrapper_->RemovedFromWidget(); } } void NativeViewHost::OnFocus() { if (native_view_) native_wrapper_->SetFocus(); NotifyAccessibilityEvent(ax::mojom::Event::kFocus, true); } gfx::NativeViewAccessible NativeViewHost::GetNativeViewAccessible() { if (native_wrapper_.get()) { gfx::NativeViewAccessible accessible_view = native_wrapper_->GetNativeViewAccessible(); if (accessible_view) return accessible_view; } return View::GetNativeViewAccessible(); } ui::Cursor NativeViewHost::GetCursor(const ui::MouseEvent& event) { return native_wrapper_->GetCursor(event.x(), event.y()); } void NativeViewHost::SetVisible(bool visible) { if (native_view_) native_wrapper_->SetVisible(visible); View::SetVisible(visible); } bool NativeViewHost::OnMousePressed(const ui::MouseEvent& event) { // In the typical case the attached NativeView receives the events directly // from the system and this function is not called. There are scenarios // where that may not happen. For example, if the NativeView is configured // not to receive events, then this function will be called. An additional // scenario is if the WidgetDelegate overrides // ShouldDescendIntoChildForEventHandling(). In that case the NativeView // will not receive the events, and this function will be called. Regardless, // this function does not need to forward to the NativeView, because it is // expected to be done by the system, and the only cases where this is called // is if the NativeView should not receive events. return View::OnMousePressed(event); } //////////////////////////////////////////////////////////////////////////////// // NativeViewHost, private: void NativeViewHost::Detach(bool destroyed) { if (native_view_) { if (!destroyed) { Widget* widget = Widget::GetWidgetForNativeView(native_view_); if (widget) widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, nullptr); ClearFocus(); } native_wrapper_->NativeViewDetaching(destroyed); native_view_ = nullptr; } } void NativeViewHost::ClearFocus() { FocusManager* focus_manager = GetFocusManager(); if (!focus_manager || !focus_manager->GetFocusedView()) return; Widget::Widgets widgets; Widget::GetAllChildWidgets(native_view(), &widgets); for (auto* widget : widgets) { focus_manager->ViewRemoved(widget->GetRootView()); if (!focus_manager->GetFocusedView()) return; } } BEGIN_METADATA(NativeViewHost, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host.cc
C++
unknown
10,307
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_ #define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_ #include <memory> #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/view.h" namespace gfx { class RoundedCornersF; } namespace views { namespace test { class NativeViewHostTestBase; } class NativeViewHostWrapper; // If a NativeViewHost's native view is a Widget, this native window // property is set on the widget, pointing to the owning NativeViewHost. extern const char kWidgetNativeViewHostKey[]; // A View type that hosts a gfx::NativeView. The bounds of the native view are // kept in sync with the bounds of this view as it is moved and sized. // Under the hood, a platform-specific NativeViewHostWrapper implementation does // the platform-specific work of manipulating the underlying OS widget type. class VIEWS_EXPORT NativeViewHost : public View { public: METADATA_HEADER(NativeViewHost); NativeViewHost(); NativeViewHost(const NativeViewHost&) = delete; NativeViewHost& operator=(const NativeViewHost&) = delete; ~NativeViewHost() override; // Attach a gfx::NativeView to this View. Its bounds will be kept in sync // with the bounds of this View until Detach is called. // // Because native views are positioned in the coordinates of their parent // native view, this function should only be called after this View has been // added to a View hierarchy hosted within a valid Widget. void Attach(gfx::NativeView native_view); // Detach the attached native view. Its bounds and visibility will no // longer be manipulated by this View. The native view may be destroyed and // detached before calling this function, and this has no effect in that case. void Detach(); // Sets the corner radii for clipping gfx::NativeView. Returns true on success // or false if the platform doesn't support the operation. This method calls // SetCustomMask internally. bool SetCornerRadii(const gfx::RoundedCornersF& corner_radii); // Sets the custom layer mask for clipping gfx::NativeView. Returns true on // success or false if the platform doesn't support the operation. // NB: This does not interact nicely with fast_resize. // TODO(tluk): This is currently only being used to apply rounded corners in // ash code. Migrate existing use to SetCornerRadii(). bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask); // Sets the height of the top region where the gfx::NativeView shouldn't be // targeted. This will be used when another view is covering there // temporarily, like the immersive fullscreen mode of ChromeOS. void SetHitTestTopInset(int top_inset); int GetHitTestTopInset() const; // Sets the size for the NativeView that may or may not match the size of this // View when it is being captured. If the size does not match, scaling will // occur. Pass an empty size to revert to the default behavior, where the // NatieView's size always equals this View's size. void SetNativeViewSize(const gfx::Size& size); // Returns the container that contains this host's native view. Returns null // if there's no attached native view or it has no container. gfx::NativeView GetNativeViewContainer() const; // Pass the parent accessible object to this host's native view so that // it can return this value when querying its parent accessible. void SetParentAccessible(gfx::NativeViewAccessible); // Returns the parent accessible object to this host's native view. gfx::NativeViewAccessible GetParentAccessible(); // Fast resizing will move the native view and clip its visible region, this // will result in white areas and will not resize the content (so scrollbars // will be all wrong and content will flow offscreen). Only use this // when you're doing extremely quick, high-framerate vertical resizes // and don't care about accuracy. Make sure you do a real resize at the // end. USE WITH CAUTION. void set_fast_resize(bool fast_resize) { fast_resize_ = fast_resize; } bool fast_resize() const { return fast_resize_; } gfx::NativeView native_view() const { return native_view_; } void NativeViewDestroyed(); // Sets the desired background color for repainting when the view is clipped. // Defaults to transparent color if unset. void SetBackgroundColorWhenClipped(absl::optional<SkColor> color); // Overridden from View: void Layout() override; void OnPaint(gfx::Canvas* canvas) override; void VisibilityChanged(View* starting_from, bool is_visible) override; void OnFocus() override; gfx::NativeViewAccessible GetNativeViewAccessible() override; ui::Cursor GetCursor(const ui::MouseEvent& event) override; void SetVisible(bool visible) override; bool OnMousePressed(const ui::MouseEvent& event) override; protected: bool GetNeedsNotificationWhenVisibleBoundsChange() const override; void OnVisibleBoundsChanged() override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; private: friend class test::NativeViewHostTestBase; // Detach the native view. |destroyed| is true if the native view is // detached because it's being destroyed, or false otherwise. void Detach(bool destroyed); // Invokes ViewRemoved() on the FocusManager for all the child Widgets of our // NativeView. This is used when detaching to ensure the FocusManager doesn't // have a reference to a View that is no longer reachable. void ClearFocus(); // The attached native view. There is exactly one native_view_ attached. gfx::NativeView native_view_ = nullptr; // A platform-specific wrapper that does the OS-level manipulation of the // attached gfx::NativeView. std::unique_ptr<NativeViewHostWrapper> native_wrapper_; // The actual size of the NativeView, or an empty size if no scaling of the // NativeView should occur. gfx::Size native_view_size_; // True if the native view is being resized using the fast method described // in the setter/accessor above. bool fast_resize_ = false; // The color to use for repainting the background when the view is clipped. absl::optional<SkColor> background_color_when_clipped_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host.h
C++
unknown
6,452
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host_aura.h" #include <memory> #include <utility> #include "base/check.h" #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_occlusion_tracker.h" #include "ui/aura/window_targeter.h" #include "ui/base/cursor/cursor.h" #include "ui/base/hit_test.h" #include "ui/compositor/layer.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/geometry/insets.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/painter.h" #include "ui/views/view_class_properties.h" #include "ui/views/view_constants_aura.h" #include "ui/views/widget/widget.h" namespace views { class NativeViewHostAura::ClippingWindowDelegate : public aura::WindowDelegate { public: ClippingWindowDelegate() = default; ~ClippingWindowDelegate() override = default; void set_native_view(aura::Window* native_view) { native_view_ = native_view; } gfx::Size GetMinimumSize() const override { return gfx::Size(); } gfx::Size GetMaximumSize() const override { return gfx::Size(); } void OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override {} ui::Cursor GetCursor(const gfx::Point& point) override { return ui::Cursor(); } int GetNonClientComponent(const gfx::Point& point) const override { return HTCLIENT; } bool ShouldDescendIntoChildForEventHandling( aura::Window* child, const gfx::Point& location) override { return true; } bool CanFocus() override { // Ask the hosted native view's delegate because directly calling // aura::Window::CanFocus() will call back into this when checking whether // parents can focus. return !native_view_ || !native_view_->delegate() || native_view_->delegate()->CanFocus(); } void OnCaptureLost() override {} void OnPaint(const ui::PaintContext& context) override {} void OnDeviceScaleFactorChanged(float old_device_scale_factor, float new_device_scale_factor) override {} void OnWindowDestroying(aura::Window* window) override {} void OnWindowDestroyed(aura::Window* window) override {} void OnWindowTargetVisibilityChanged(bool visible) override {} bool HasHitTestMask() const override { return false; } void GetHitTestMask(SkPath* mask) const override {} private: raw_ptr<aura::Window> native_view_ = nullptr; }; NativeViewHostAura::NativeViewHostAura(NativeViewHost* host) : host_(host) {} NativeViewHostAura::~NativeViewHostAura() { if (host_->native_view()) { host_->native_view()->RemoveObserver(this); host_->native_view()->ClearProperty(views::kHostViewKey); host_->native_view()->ClearProperty(aura::client::kHostWindowKey); host_->native_view()->ClearProperty( aura::client::kParentNativeViewAccessibleKey); clipping_window_->ClearProperty(views::kHostViewKey); if (host_->native_view()->parent() == clipping_window_.get()) clipping_window_->RemoveChild(host_->native_view()); } } //////////////////////////////////////////////////////////////////////////////// // NativeViewHostAura, NativeViewHostWrapper implementation: void NativeViewHostAura::AttachNativeView() { if (!clipping_window_) CreateClippingWindow(); clipping_window_delegate_->set_native_view(host_->native_view()); host_->native_view()->AddObserver(this); host_->native_view()->SetProperty(views::kHostViewKey, static_cast<View*>(host_)); original_transform_ = host_->native_view()->transform(); original_transform_changed_ = false; AddClippingWindow(); InstallMask(); ApplyRoundedCorners(); } void NativeViewHostAura::SetParentAccessible( gfx::NativeViewAccessible accessible) { host_->native_view()->SetProperty( aura::client::kParentNativeViewAccessibleKey, accessible); } gfx::NativeViewAccessible NativeViewHostAura::GetParentAccessible() { return host_->native_view()->GetProperty( aura::client::kParentNativeViewAccessibleKey); } void NativeViewHostAura::NativeViewDetaching(bool destroyed) { // This method causes a succession of window tree changes. ScopedPause ensures // that occlusion is recomputed at the end of the method instead of after each // change. absl::optional<aura::WindowOcclusionTracker::ScopedPause> pause_occlusion; if (clipping_window_) pause_occlusion.emplace(); clipping_window_delegate_->set_native_view(nullptr); RemoveClippingWindow(); if (!destroyed) { host_->native_view()->RemoveObserver(this); host_->native_view()->ClearProperty(views::kHostViewKey); host_->native_view()->ClearProperty(aura::client::kHostWindowKey); host_->native_view()->ClearProperty( aura::client::kParentNativeViewAccessibleKey); if (original_transform_changed_) host_->native_view()->SetTransform(original_transform_); host_->native_view()->Hide(); if (host_->native_view()->parent()) Widget::ReparentNativeView(host_->native_view(), nullptr); } } void NativeViewHostAura::AddedToWidget() { if (!host_->native_view()) return; AddClippingWindow(); if (host_->IsDrawn()) host_->native_view()->Show(); else host_->native_view()->Hide(); host_->InvalidateLayout(); } void NativeViewHostAura::RemovedFromWidget() { if (host_->native_view()) { // Clear kHostWindowKey before Hide() because it could be accessed during // the call. In MUS aura, the hosting window could be destroyed at this // point. host_->native_view()->ClearProperty(aura::client::kHostWindowKey); host_->native_view()->Hide(); if (host_->native_view()->parent()) host_->native_view()->parent()->RemoveChild(host_->native_view()); RemoveClippingWindow(); } } bool NativeViewHostAura::SetCornerRadii( const gfx::RoundedCornersF& corner_radii) { corner_radii_ = corner_radii; ApplyRoundedCorners(); return true; } bool NativeViewHostAura::SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) { UninstallMask(); mask_ = std::move(mask); if (mask_) mask_->layer()->SetFillsBoundsOpaquely(false); InstallMask(); return true; } void NativeViewHostAura::SetHitTestTopInset(int top_inset) { if (top_inset_ == top_inset) return; top_inset_ = top_inset; UpdateInsets(); } void NativeViewHostAura::InstallClip(int x, int y, int w, int h) { clip_rect_ = std::make_unique<gfx::Rect>( host_->ConvertRectToWidget(gfx::Rect(x, y, w, h))); } int NativeViewHostAura::GetHitTestTopInset() const { return top_inset_; } bool NativeViewHostAura::HasInstalledClip() { return !!clip_rect_; } void NativeViewHostAura::UninstallClip() { clip_rect_.reset(); } void NativeViewHostAura::ShowWidget(int x, int y, int w, int h, int native_w, int native_h) { if (host_->fast_resize()) { gfx::Point origin(x, y); views::View::ConvertPointFromWidget(host_, &origin); InstallClip(origin.x(), origin.y(), w, h); native_w = host_->native_view()->bounds().width(); native_h = host_->native_view()->bounds().height(); } else { gfx::Transform transform = original_transform_; if (w > 0 && h > 0 && native_w > 0 && native_h > 0) { transform.Scale(static_cast<SkScalar>(w) / native_w, static_cast<SkScalar>(h) / native_h); } // Only set the transform when it is actually different. if (transform != host_->native_view()->transform()) { host_->native_view()->SetTransform(transform); original_transform_changed_ = true; } } clipping_window_->SetBounds(clip_rect_ ? *clip_rect_ : gfx::Rect(x, y, w, h)); gfx::Point clip_offset = clipping_window_->bounds().origin(); host_->native_view()->SetBounds( gfx::Rect(x - clip_offset.x(), y - clip_offset.y(), native_w, native_h)); host_->native_view()->Show(); clipping_window_->Show(); } void NativeViewHostAura::HideWidget() { host_->native_view()->Hide(); clipping_window_->Hide(); } void NativeViewHostAura::SetFocus() { aura::Window* window = host_->native_view(); aura::client::FocusClient* client = aura::client::GetFocusClient(window); if (client) client->FocusWindow(window); } gfx::NativeView NativeViewHostAura::GetNativeViewContainer() const { return clipping_window_.get(); } gfx::NativeViewAccessible NativeViewHostAura::GetNativeViewAccessible() { return nullptr; } ui::Cursor NativeViewHostAura::GetCursor(int x, int y) { if (host_->native_view()) return host_->native_view()->GetCursor(gfx::Point(x, y)); return ui::Cursor(); } void NativeViewHostAura::SetVisible(bool visible) { if (!visible) host_->native_view()->Hide(); else host_->native_view()->Show(); } void NativeViewHostAura::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) { if (mask_) mask_->layer()->SetBounds(gfx::Rect(host_->native_view()->bounds().size())); } void NativeViewHostAura::OnWindowDestroying(aura::Window* window) { DCHECK(window == host_->native_view()); clipping_window_delegate_->set_native_view(nullptr); } void NativeViewHostAura::OnWindowDestroyed(aura::Window* window) { DCHECK(window == host_->native_view()); host_->NativeViewDestroyed(); } // static NativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper( NativeViewHost* host) { return new NativeViewHostAura(host); } void NativeViewHostAura::CreateClippingWindow() { clipping_window_delegate_ = std::make_unique<ClippingWindowDelegate>(); // Use WINDOW_TYPE_CONTROLLER type so descendant views (including popups) get // positioned appropriately. clipping_window_ = std::make_unique<aura::Window>( clipping_window_delegate_.get(), aura::client::WINDOW_TYPE_CONTROL); clipping_window_->Init(ui::LAYER_NOT_DRAWN); clipping_window_->set_owned_by_parent(false); clipping_window_->SetName("NativeViewHostAuraClip"); clipping_window_->layer()->SetMasksToBounds(true); clipping_window_->SetProperty(views::kHostViewKey, static_cast<View*>(host_)); UpdateInsets(); } void NativeViewHostAura::AddClippingWindow() { RemoveClippingWindow(); host_->native_view()->SetProperty(aura::client::kHostWindowKey, host_->GetWidget()->GetNativeView()); Widget::ReparentNativeView(host_->native_view(), clipping_window_.get()); if (host_->GetWidget()->GetNativeView()) { Widget::ReparentNativeView(clipping_window_.get(), host_->GetWidget()->GetNativeView()); } } void NativeViewHostAura::RemoveClippingWindow() { clipping_window_->Hide(); if (host_->native_view()) host_->native_view()->ClearProperty(aura::client::kHostWindowKey); if (host_->native_view()->parent() == clipping_window_.get()) { if (host_->GetWidget() && host_->GetWidget()->GetNativeView()) { Widget::ReparentNativeView(host_->native_view(), host_->GetWidget()->GetNativeView()); } else { clipping_window_->RemoveChild(host_->native_view()); } } if (clipping_window_->parent()) clipping_window_->parent()->RemoveChild(clipping_window_.get()); } void NativeViewHostAura::ApplyRoundedCorners() { if (!host_->native_view()) return; ui::Layer* layer = host_->native_view()->layer(); if (layer->rounded_corner_radii() != corner_radii_) { layer->SetRoundedCornerRadius(corner_radii_); layer->SetIsFastRoundedCorner(true); } } void NativeViewHostAura::InstallMask() { if (!mask_) return; if (host_->native_view()) { mask_->layer()->SetBounds(gfx::Rect(host_->native_view()->bounds().size())); host_->native_view()->layer()->SetMaskLayer(mask_->layer()); } } void NativeViewHostAura::UninstallMask() { if (!host_->native_view() || !mask_) return; host_->native_view()->layer()->SetMaskLayer(nullptr); mask_.reset(); } void NativeViewHostAura::UpdateInsets() { if (!clipping_window_) return; if (top_inset_ == 0) { // The window targeter needs to be uninstalled when not used; keeping empty // targeter here actually conflicts with ash::ImmersiveWindowTargeter on // immersive mode in Ash. // TODO(mukai): fix this. clipping_window_->SetEventTargeter(nullptr); } else { if (!clipping_window_->targeter()) { clipping_window_->SetEventTargeter( std::make_unique<aura::WindowTargeter>()); } clipping_window_->targeter()->SetInsets( gfx::Insets::TLBR(top_inset_, 0, 0, 0)); } } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_aura.cc
C++
unknown
13,089
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_ #define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "ui/aura/window_observer.h" #include "ui/compositor/layer_owner.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/transform.h" #include "ui/views/controls/native/native_view_host_wrapper.h" #include "ui/views/views_export.h" namespace aura { class Window; } namespace views { class NativeViewHost; // Aura implementation of NativeViewHostWrapper. class NativeViewHostAura : public NativeViewHostWrapper, public aura::WindowObserver { public: explicit NativeViewHostAura(NativeViewHost* host); NativeViewHostAura(const NativeViewHostAura&) = delete; NativeViewHostAura& operator=(const NativeViewHostAura&) = delete; ~NativeViewHostAura() override; // Overridden from NativeViewHostWrapper: void AttachNativeView() override; void NativeViewDetaching(bool destroyed) override; void AddedToWidget() override; void RemovedFromWidget() override; bool SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override; bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) override; void SetHitTestTopInset(int top_inset) override; int GetHitTestTopInset() const override; void InstallClip(int x, int y, int w, int h) override; bool HasInstalledClip() override; void UninstallClip() override; void ShowWidget(int x, int y, int w, int h, int native_w, int native_h) override; void HideWidget() override; void SetFocus() override; gfx::NativeView GetNativeViewContainer() const override; gfx::NativeViewAccessible GetNativeViewAccessible() override; ui::Cursor GetCursor(int x, int y) override; void SetVisible(bool visible) override; void SetParentAccessible(gfx::NativeViewAccessible) override; gfx::NativeViewAccessible GetParentAccessible() override; private: friend class NativeViewHostAuraTest; class ClippingWindowDelegate; // Overridden from aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override; void OnWindowDestroyed(aura::Window* window) override; void OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) override; void CreateClippingWindow(); // Reparents the native view with the clipping window existing between it and // its old parent, so that the fast resize path works. void AddClippingWindow(); // If the native view has been reparented via AddClippingWindow, this call // undoes it. void RemoveClippingWindow(); // Sets or updates the |corner_radii_| on the native view's layer. void ApplyRoundedCorners(); // Sets or updates the mask layer on the native view's layer. void InstallMask(); // Unsets the mask layer on the native view's layer. void UninstallMask(); // Updates the top insets of |clipping_window_|. void UpdateInsets(); // Our associated NativeViewHost. raw_ptr<NativeViewHost> host_; std::unique_ptr<ClippingWindowDelegate> clipping_window_delegate_; // Window that exists between the native view and the parent that allows for // clipping to occur. This is positioned in the coordinate space of // host_->GetWidget(). std::unique_ptr<aura::Window> clipping_window_; std::unique_ptr<gfx::Rect> clip_rect_; // This mask exists for the sake of SetCornerRadius(). std::unique_ptr<ui::LayerOwner> mask_; // Holds the corner_radii to be applied. gfx::RoundedCornersF corner_radii_; // Set when AttachNativeView() is called. This is the original transform of // the NativeView's layer. The NativeView's layer may be modified to scale // when ShowWidget() is called with a native view size not equal to the // region's size. When NativeViewDetaching() is called, the NativeView's // transform is restored to this. gfx::Transform original_transform_; // True if a transform different from the original was set. bool original_transform_changed_ = false; // The top insets to exclude the underlying native view from the target. int top_inset_ = 0; }; } // namespace views #endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_aura.h
C++
unknown
4,493
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host_aura.h" #include <memory> #include <utility> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_targeter.h" #include "ui/aura/window_tree_host.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/events/event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/controls/native/native_view_host_test_base.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/view.h" #include "ui/views/view_constants_aura.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace views { // Observer watching for window visibility and bounds change events. This is // used to verify that the child and clipping window operations are done in the // right order. class NativeViewHostWindowObserver : public aura::WindowObserver { public: enum EventType { EVENT_NONE, EVENT_SHOWN, EVENT_HIDDEN, EVENT_BOUNDS_CHANGED, EVENT_DESTROYED, }; struct EventDetails { EventType type; raw_ptr<aura::Window> window; gfx::Rect bounds; bool operator!=(const EventDetails& rhs) { return type != rhs.type || window != rhs.window || bounds != rhs.bounds; } }; NativeViewHostWindowObserver() = default; NativeViewHostWindowObserver(const NativeViewHostWindowObserver&) = delete; NativeViewHostWindowObserver& operator=(const NativeViewHostWindowObserver&) = delete; ~NativeViewHostWindowObserver() override = default; const std::vector<EventDetails>& events() const { return events_; } // aura::WindowObserver overrides void OnWindowVisibilityChanged(aura::Window* window, bool visible) override { EventDetails event; event.type = visible ? EVENT_SHOWN : EVENT_HIDDEN; event.window = window; event.bounds = window->GetBoundsInRootWindow(); // Dedupe events as a single Hide() call can result in several // notifications. if (events_.size() == 0u || events_.back() != event) events_.push_back(event); } void OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) override { EventDetails event; event.type = EVENT_BOUNDS_CHANGED; event.window = window; event.bounds = window->GetBoundsInRootWindow(); events_.push_back(event); } void OnWindowDestroyed(aura::Window* window) override { EventDetails event = {EVENT_DESTROYED, window, gfx::Rect()}; events_.push_back(event); } private: std::vector<EventDetails> events_; gfx::Rect bounds_at_visibility_changed_; }; class NativeViewHostAuraTest : public test::NativeViewHostTestBase { public: NativeViewHostAuraTest() = default; NativeViewHostAuraTest(const NativeViewHostAuraTest&) = delete; NativeViewHostAuraTest& operator=(const NativeViewHostAuraTest&) = delete; NativeViewHostAura* native_host() { return static_cast<NativeViewHostAura*>(GetNativeWrapper()); } Widget* child() { return child_.get(); } aura::Window* clipping_window() { return native_host()->clipping_window_.get(); } void CreateHost() { CreateTopLevel(); CreateTestingHost(); child_.reset(CreateChildForHost(toplevel()->GetNativeView(), toplevel()->client_view(), new View, host())); } // test::NativeViewHostTestBase: void TearDown() override { child_.reset(); test::NativeViewHostTestBase::TearDown(); } private: std::unique_ptr<Widget> child_; }; // Verifies NativeViewHostAura stops observing native view on destruction. TEST_F(NativeViewHostAuraTest, StopObservingNativeViewOnDestruct) { CreateHost(); aura::Window* child_win = child()->GetNativeView(); NativeViewHostAura* aura_host = native_host(); EXPECT_TRUE(child_win->HasObserver(aura_host)); DestroyHost(); EXPECT_FALSE(child_win->HasObserver(aura_host)); } // Tests that the kHostViewKey is correctly set and cleared. TEST_F(NativeViewHostAuraTest, HostViewPropertyKey) { // Create the NativeViewHost and attach a NativeView. CreateHost(); aura::Window* child_win = child()->GetNativeView(); EXPECT_EQ(host(), child_win->GetProperty(views::kHostViewKey)); EXPECT_EQ(host()->GetWidget()->GetNativeView(), child_win->GetProperty(aura::client::kHostWindowKey)); EXPECT_EQ(host(), clipping_window()->GetProperty(views::kHostViewKey)); host()->Detach(); EXPECT_FALSE(child_win->GetProperty(views::kHostViewKey)); EXPECT_FALSE(child_win->GetProperty(aura::client::kHostWindowKey)); EXPECT_TRUE(clipping_window()->GetProperty(views::kHostViewKey)); host()->Attach(child_win); EXPECT_EQ(host(), child_win->GetProperty(views::kHostViewKey)); EXPECT_EQ(host()->GetWidget()->GetNativeView(), child_win->GetProperty(aura::client::kHostWindowKey)); EXPECT_EQ(host(), clipping_window()->GetProperty(views::kHostViewKey)); DestroyHost(); EXPECT_FALSE(child_win->GetProperty(views::kHostViewKey)); EXPECT_FALSE(child_win->GetProperty(aura::client::kHostWindowKey)); } // Tests that the NativeViewHost reports the cursor set on its native view. TEST_F(NativeViewHostAuraTest, CursorForNativeView) { CreateHost(); toplevel()->SetCursor(ui::mojom::CursorType::kHand); child()->SetCursor(ui::mojom::CursorType::kWait); ui::MouseEvent move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0), gfx::Point(0, 0), ui::EventTimeForNow(), 0, 0); EXPECT_EQ(ui::mojom::CursorType::kWait, host()->GetCursor(move_event).type()); DestroyHost(); } // Test that destroying the top level widget before destroying the attached // NativeViewHost works correctly. Specifically the associated NVH should be // destroyed and there shouldn't be any errors. TEST_F(NativeViewHostAuraTest, DestroyWidget) { ResetHostDestroyedCount(); CreateHost(); ReleaseHost(); EXPECT_EQ(0, host_destroyed_count()); DestroyTopLevel(); EXPECT_EQ(1, host_destroyed_count()); } // Test that the fast resize path places the clipping and content windows were // they are supposed to be. TEST_F(NativeViewHostAuraTest, FastResizePath) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); // Without fast resize, the clipping window should size to the native view // with the native view positioned at the origin of the clipping window and // the clipping window positioned where the native view was requested. host()->set_fast_resize(false); native_host()->ShowWidget(5, 10, 100, 100, 100, 100); EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(5, 10, 100, 100).ToString(), clipping_window()->bounds().ToString()); // With fast resize, the native view should remain the same size but be // clipped the requested size. host()->set_fast_resize(true); native_host()->ShowWidget(10, 25, 50, 50, 50, 50); EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), clipping_window()->bounds().ToString()); // Turning off fast resize should make the native view start resizing again. host()->set_fast_resize(false); native_host()->ShowWidget(10, 25, 50, 50, 50, 50); EXPECT_EQ(gfx::Rect(0, 0, 50, 50).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), clipping_window()->bounds().ToString()); DestroyHost(); } // Test that the clipping and content windows' bounds are set to the correct // values while the native size is not equal to the View size. During fast // resize, the size and transform of the NativeView should not be modified. TEST_F(NativeViewHostAuraTest, BoundsWhileScaling) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); EXPECT_EQ(gfx::Transform(), host()->native_view()->transform()); // Without fast resize, the clipping window should size to the native view // with the native view positioned at the origin of the clipping window and // the clipping window positioned where the native view was requested. The // size of the native view should be 200x200 (so it's content will be // shown at half-size). host()->set_fast_resize(false); native_host()->ShowWidget(5, 10, 100, 100, 200, 200); EXPECT_EQ(gfx::Rect(0, 0, 200, 200).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(5, 10, 100, 100).ToString(), clipping_window()->bounds().ToString()); gfx::Transform expected_transform; expected_transform.Scale(0.5, 0.5); EXPECT_EQ(expected_transform, host()->native_view()->transform()); // With fast resize, the native view should remain the same size but be // clipped the requested size. Also, its transform should not be changed. host()->set_fast_resize(true); native_host()->ShowWidget(10, 25, 50, 50, 200, 200); EXPECT_EQ(gfx::Rect(0, 0, 200, 200).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), clipping_window()->bounds().ToString()); EXPECT_EQ(expected_transform, host()->native_view()->transform()); // Turning off fast resize should make the native view start resizing again, // and its transform modified to show at the new quarter-size. host()->set_fast_resize(false); native_host()->ShowWidget(10, 25, 50, 50, 200, 200); EXPECT_EQ(gfx::Rect(0, 0, 200, 200).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), clipping_window()->bounds().ToString()); expected_transform = gfx::Transform(); expected_transform.Scale(0.25, 0.25); EXPECT_EQ(expected_transform, host()->native_view()->transform()); // When the NativeView is detached, its original transform should be restored. auto* const detached_view = host()->native_view(); host()->Detach(); EXPECT_EQ(gfx::Transform(), detached_view->transform()); // Attach it again so it's torn down with everything else at the end. host()->Attach(detached_view); DestroyHost(); } // Test installing and uninstalling a clip. TEST_F(NativeViewHostAuraTest, InstallClip) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); gfx::Rect client_bounds = toplevel()->client_view()->bounds(); // Without a clip, the clipping window should always be positioned at the // requested coordinates with the native view positioned at the origin of the // clipping window. native_host()->ShowWidget(10, 20, 100, 100, 100, 100); EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), clipping_window()->bounds().ToString()); // Clip to the bottom right quarter of the native view. native_host()->InstallClip(60 - client_bounds.x(), 70 - client_bounds.y(), 50, 50); native_host()->ShowWidget(10, 20, 100, 100, 100, 100); EXPECT_EQ(gfx::Rect(-50, -50, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(60, 70, 50, 50).ToString(), clipping_window()->bounds().ToString()); // Clip to the center of the native view. native_host()->InstallClip(35 - client_bounds.x(), 45 - client_bounds.y(), 50, 50); native_host()->ShowWidget(10, 20, 100, 100, 100, 100); EXPECT_EQ(gfx::Rect(-25, -25, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(35, 45, 50, 50).ToString(), clipping_window()->bounds().ToString()); // Uninstalling the clip should make the clipping window match the native view // again. native_host()->UninstallClip(); native_host()->ShowWidget(10, 20, 100, 100, 100, 100); EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), host()->native_view()->bounds().ToString()); EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), clipping_window()->bounds().ToString()); DestroyHost(); } // Ensure native view is parented to the root window after detaching. This is // a regression test for http://crbug.com/389261. TEST_F(NativeViewHostAuraTest, ParentAfterDetach) { CreateHost(); // Force a Layout() now so that the visibility is set to false (because the // bounds is empty). test::RunScheduledLayout(host()); aura::Window* child_win = child()->GetNativeView(); aura::Window* root_window = child_win->GetRootWindow(); aura::WindowTreeHost* child_win_tree_host = child_win->GetHost(); NativeViewHostWindowObserver test_observer; child_win->AddObserver(&test_observer); host()->Detach(); EXPECT_EQ(root_window, child_win->GetRootWindow()); EXPECT_EQ(child_win_tree_host, child_win->GetHost()); DestroyHost(); DestroyTopLevel(); // The window is detached, so no longer associated with any Widget // hierarchy. The root window still owns it, but the test harness checks // for orphaned windows during TearDown(). EXPECT_EQ(0u, test_observer.events().size()) << (*test_observer.events().begin()).type; delete child_win; ASSERT_EQ(1u, test_observer.events().size()); EXPECT_EQ(NativeViewHostWindowObserver::EVENT_DESTROYED, test_observer.events().back().type); } // Ensure the clipping window is hidden before any other operations. // This is a regression test for http://crbug.com/388699. TEST_F(NativeViewHostAuraTest, RemoveClippingWindowOrder) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); native_host()->ShowWidget(10, 20, 100, 100, 100, 100); NativeViewHostWindowObserver test_observer; clipping_window()->AddObserver(&test_observer); aura::Window* child_win = child()->GetNativeView(); child_win->AddObserver(&test_observer); host()->Detach(); ASSERT_GE(test_observer.events().size(), 1u); EXPECT_EQ(NativeViewHostWindowObserver::EVENT_HIDDEN, test_observer.events()[0].type); EXPECT_EQ(clipping_window(), test_observer.events()[0].window); clipping_window()->RemoveObserver(&test_observer); child()->GetNativeView()->RemoveObserver(&test_observer); DestroyHost(); delete child_win; // See comments in ParentAfterDetach. } // Ensure the native view receives the correct bounds notification when it is // attached. This is a regression test for https://crbug.com/399420. TEST_F(NativeViewHostAuraTest, Attach) { CreateHost(); host()->Detach(); child()->GetNativeView()->SetBounds(gfx::Rect(0, 0, 0, 0)); toplevel()->SetBounds(gfx::Rect(0, 0, 100, 100)); gfx::Rect client_bounds = toplevel()->client_view()->bounds(); host()->SetBoundsRect(client_bounds); NativeViewHostWindowObserver test_observer; child()->GetNativeView()->AddObserver(&test_observer); host()->Attach(child()->GetNativeView()); // Visibiliity is not updated until Layout() happens. This is normally async, // but force a Layout() so this code doesn't have to wait. test::RunScheduledLayout(host()); auto expected_bounds = client_bounds; ASSERT_EQ(3u, test_observer.events().size()); EXPECT_EQ(NativeViewHostWindowObserver::EVENT_BOUNDS_CHANGED, test_observer.events()[0].type); EXPECT_EQ(child()->GetNativeView(), test_observer.events()[0].window); EXPECT_EQ(expected_bounds.ToString(), test_observer.events()[0].bounds.ToString()); EXPECT_EQ(NativeViewHostWindowObserver::EVENT_SHOWN, test_observer.events()[1].type); EXPECT_EQ(child()->GetNativeView(), test_observer.events()[1].window); EXPECT_EQ(expected_bounds.ToString(), test_observer.events()[1].bounds.ToString()); EXPECT_EQ(NativeViewHostWindowObserver::EVENT_SHOWN, test_observer.events()[2].type); EXPECT_EQ(clipping_window(), test_observer.events()[2].window); EXPECT_EQ(expected_bounds.ToString(), test_observer.events()[2].bounds.ToString()); child()->GetNativeView()->RemoveObserver(&test_observer); DestroyHost(); } // Ensure the clipping window is hidden with the native view. This is a // regression test for https://crbug.com/408877. TEST_F(NativeViewHostAuraTest, SimpleShowAndHide) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); toplevel()->Show(); host()->SetBounds(10, 10, 80, 80); EXPECT_TRUE(clipping_window()->IsVisible()); EXPECT_TRUE(child()->IsVisible()); host()->SetVisible(false); EXPECT_FALSE(clipping_window()->IsVisible()); EXPECT_FALSE(child()->IsVisible()); DestroyHost(); DestroyTopLevel(); } namespace { class TestFocusChangeListener : public FocusChangeListener { public: explicit TestFocusChangeListener(FocusManager* focus_manager) : focus_manager_(focus_manager) { focus_manager_->AddFocusChangeListener(this); } TestFocusChangeListener(const TestFocusChangeListener&) = delete; TestFocusChangeListener& operator=(const TestFocusChangeListener&) = delete; ~TestFocusChangeListener() override { focus_manager_->RemoveFocusChangeListener(this); } int did_change_focus_count() const { return did_change_focus_count_; } private: // FocusChangeListener: void OnWillChangeFocus(View* focused_before, View* focused_now) override {} void OnDidChangeFocus(View* focused_before, View* focused_now) override { did_change_focus_count_++; } raw_ptr<FocusManager> focus_manager_; int did_change_focus_count_ = 0; }; } // namespace // Verifies the FocusManager is properly updated if focus is in a child widget // that is parented to a NativeViewHost and the NativeViewHost is destroyed. TEST_F(NativeViewHostAuraTest, FocusManagerUpdatedDuringDestruction) { CreateTopLevel(); toplevel()->Show(); std::unique_ptr<aura::Window> window = std::make_unique<aura::Window>(nullptr); window->Init(ui::LAYER_NOT_DRAWN); window->set_owned_by_parent(false); std::unique_ptr<NativeViewHost> native_view_host = std::make_unique<NativeViewHost>(); toplevel()->GetContentsView()->AddChildView(native_view_host.get()); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_CONTROL); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = new views::WidgetDelegateView(); // Owned by the widget. params.child = true; params.bounds = gfx::Rect(10, 10, 100, 100); params.parent = window.get(); std::unique_ptr<Widget> child_widget = std::make_unique<Widget>(); child_widget->Init(std::move(params)); native_view_host->Attach(window.get()); View* view1 = new View; // Owned by |child_widget|. view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); view1->SetBounds(0, 0, 20, 20); child_widget->GetContentsView()->AddChildView(view1); child_widget->Show(); view1->RequestFocus(); EXPECT_EQ(view1, toplevel()->GetFocusManager()->GetFocusedView()); TestFocusChangeListener focus_change_listener(toplevel()->GetFocusManager()); // ~NativeViewHost() unparents |window|. native_view_host.reset(); EXPECT_EQ(nullptr, toplevel()->GetFocusManager()->GetFocusedView()); EXPECT_EQ(1, focus_change_listener.did_change_focus_count()); child_widget.reset(); EXPECT_EQ(nullptr, toplevel()->GetFocusManager()->GetFocusedView()); } namespace { ui::EventTarget* GetTarget(aura::Window* window, const gfx::Point& location) { gfx::Point root_location = location; aura::Window::ConvertPointToTarget(window, window->GetRootWindow(), &root_location); ui::MouseEvent event(ui::ET_MOUSE_MOVED, root_location, root_location, base::TimeTicks::Now(), 0, 0); return window->GetHost()->dispatcher()->event_targeter()->FindTargetForEvent( window->GetRootWindow(), &event); } } // namespace TEST_F(NativeViewHostAuraTest, TopInsets) { CreateHost(); toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); toplevel()->Show(); // The child window is placed relative to the client view. Take that into // account. gfx::Vector2d offset = toplevel()->client_view()->bounds().OffsetFromOrigin(); aura::Window* toplevel_window = toplevel()->GetNativeWindow(); aura::Window* child_window = child()->GetNativeWindow(); EXPECT_EQ(child_window, GetTarget(toplevel_window, gfx::Point(1, 1) + offset)); EXPECT_EQ(child_window, GetTarget(toplevel_window, gfx::Point(1, 11) + offset)); host()->SetHitTestTopInset(10); EXPECT_EQ(toplevel_window, GetTarget(toplevel_window, gfx::Point(1, 1))); EXPECT_EQ(child_window, GetTarget(toplevel_window, gfx::Point(1, 11) + offset)); host()->SetHitTestTopInset(0); EXPECT_EQ(child_window, GetTarget(toplevel_window, gfx::Point(1, 1) + offset)); EXPECT_EQ(child_window, GetTarget(toplevel_window, gfx::Point(1, 11) + offset)); DestroyHost(); DestroyTopLevel(); } TEST_F(NativeViewHostAuraTest, WindowHiddenWhenAttached) { std::unique_ptr<aura::Window> window = std::make_unique<aura::Window>(nullptr); window->Init(ui::LAYER_NOT_DRAWN); window->set_owned_by_parent(false); window->Show(); EXPECT_TRUE(window->TargetVisibility()); CreateTopLevel(); NativeViewHost* host = toplevel()->GetRootView()->AddChildView( std::make_unique<NativeViewHost>()); host->SetVisible(false); host->Attach(window.get()); // Is |host| is not visible, |window| should immediately be hidden. EXPECT_FALSE(window->TargetVisibility()); } TEST_F(NativeViewHostAuraTest, ClippedWindowNotResizedOnDetach) { CreateTopLevel(); toplevel()->SetSize(gfx::Size(100, 100)); toplevel()->Show(); std::unique_ptr<aura::Window> window = std::make_unique<aura::Window>(nullptr); window->Init(ui::LAYER_NOT_DRAWN); window->set_owned_by_parent(false); window->SetBounds(gfx::Rect(0, 0, 200, 200)); window->Show(); NativeViewHost* host = toplevel()->GetRootView()->AddChildView( std::make_unique<NativeViewHost>()); host->SetVisible(true); host->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); host->Attach(window.get()); EXPECT_EQ(gfx::Size(200, 200), window->bounds().size()); host->Detach(); EXPECT_EQ(gfx::Size(200, 200), window->bounds().size()); } class WidgetDelegateForShouldDescendIntoChildForEventHandling : public WidgetDelegate { public: void set_window(aura::Window* window) { window_ = window; } bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override { return child != window_; } private: raw_ptr<aura::Window> window_ = nullptr; }; TEST_F(NativeViewHostAuraTest, ShouldDescendIntoChildForEventHandling) { WidgetDelegateForShouldDescendIntoChildForEventHandling widget_delegate; CreateTopLevel(&widget_delegate); toplevel()->SetSize(gfx::Size(200, 200)); toplevel()->Show(); std::unique_ptr<aura::Window> window = std::make_unique<aura::Window>(nullptr); window->Init(ui::LAYER_NOT_DRAWN); window->set_owned_by_parent(false); window->SetBounds(gfx::Rect(0, 0, 200, 200)); window->Show(); widget_delegate.set_window(window.get()); CreateTestingHost(); toplevel()->GetRootView()->AddChildView(host()); host()->SetVisible(true); host()->SetBoundsRect(gfx::Rect(0, 0, 200, 200)); host()->Attach(window.get()); ui::test::EventGenerator event_generator(window->GetRootWindow()); gfx::Point press_location(100, 100); aura::Window::ConvertPointToTarget(toplevel()->GetNativeView(), window->GetRootWindow(), &press_location); event_generator.MoveMouseTo(press_location); event_generator.PressLeftButton(); // Because the delegate overrides ShouldDescendIntoChildForEventHandling() // the NativeView does not get the event, but NativeViewHost will. EXPECT_EQ(1, on_mouse_pressed_called_count()); DestroyHost(); DestroyTopLevel(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_aura_unittest.cc
C++
unknown
24,466
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_MAC_H_ #define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_MAC_H_ #include <memory> #include "base/mac/scoped_nsobject.h" #include "base/memory/raw_ptr.h" #include "ui/base/cocoa/views_hostable.h" #include "ui/views/controls/native/native_view_host_wrapper.h" #include "ui/views/views_export.h" namespace ui { class LayerOwner; class ViewsHostableView; } // namespace ui namespace gfx { class RoundedCornersF; } // namespace gfx namespace views { class NativeWidgetMacNSWindowHost; class NativeViewHost; // Mac implementation of NativeViewHostWrapper. class NativeViewHostMac : public NativeViewHostWrapper, public ui::ViewsHostableView::Host { public: explicit NativeViewHostMac(NativeViewHost* host); NativeViewHostMac(const NativeViewHostMac&) = delete; NativeViewHostMac& operator=(const NativeViewHostMac&) = delete; ~NativeViewHostMac() override; // ViewsHostableView::Host: ui::Layer* GetUiLayer() const override; remote_cocoa::mojom::Application* GetRemoteCocoaApplication() const override; uint64_t GetNSViewId() const override; void OnHostableViewDestroying() override; // NativeViewHostWrapper: void AttachNativeView() override; void NativeViewDetaching(bool destroyed) override; void AddedToWidget() override; void RemovedFromWidget() override; bool SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override; bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) override; void SetHitTestTopInset(int top_inset) override; int GetHitTestTopInset() const override; void InstallClip(int x, int y, int w, int h) override; bool HasInstalledClip() override; void UninstallClip() override; void ShowWidget(int x, int y, int w, int h, int native_w, int native_h) override; void HideWidget() override; void SetFocus() override; gfx::NativeView GetNativeViewContainer() const override; gfx::NativeViewAccessible GetNativeViewAccessible() override; ui::Cursor GetCursor(int x, int y) override; void SetVisible(bool visible) override; void SetParentAccessible(gfx::NativeViewAccessible) override; gfx::NativeViewAccessible GetParentAccessible() override; private: // Return the NativeWidgetMacNSWindowHost for this hosted view. NativeWidgetMacNSWindowHost* GetNSWindowHost() const; // Our associated NativeViewHost. Owns this. raw_ptr<NativeViewHost> host_; // Retain the native view as it may be destroyed at an unpredictable time. base::scoped_nsobject<NSView> native_view_; // If |native_view| supports the ViewsHostable protocol, then this is the // the corresponding ViewsHostableView interface (which is implemeted only // by WebContents and tests). raw_ptr<ui::ViewsHostableView> native_view_hostable_ = nullptr; }; } // namespace views #endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_MAC_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_mac.h
C++
unknown
3,041
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host_mac.h" #import <Cocoa/Cocoa.h> #include "base/mac/foundation_util.h" #import "ui/accessibility/platform/ax_platform_node_mac.h" #include "ui/compositor/layer.h" #import "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/widget/native_widget_mac.h" #include "ui/views/widget/widget.h" namespace views { namespace { void EnsureNativeViewHasNoChildWidgets(NSView* native_view) { DCHECK(native_view); // Mac's NativeViewHost has no support for hosting its own child widgets. // This check is probably overly restrictive, since the Widget containing the // NativeViewHost _is_ allowed child Widgets. However, we don't know yet // whether those child Widgets need to be distinguished from Widgets that code // might want to associate with the hosted NSView instead. { Widget::Widgets child_widgets; Widget::GetAllChildWidgets(native_view, &child_widgets); CHECK_GE(1u, child_widgets.size()); // 1 (itself) or 0 if detached. } } } // namespace NativeViewHostMac::NativeViewHostMac(NativeViewHost* host) : host_(host) { // Ensure that |host_| have its own ui::Layer and that it draw nothing. host_->SetPaintToLayer(ui::LAYER_NOT_DRAWN); } NativeViewHostMac::~NativeViewHostMac() = default; NativeWidgetMacNSWindowHost* NativeViewHostMac::GetNSWindowHost() const { return NativeWidgetMacNSWindowHost::GetFromNativeWindow( host_->GetWidget()->GetNativeWindow()); } //////////////////////////////////////////////////////////////////////////////// // NativeViewHostMac, ViewsHostableView::Host implementation: ui::Layer* NativeViewHostMac::GetUiLayer() const { return host_->layer(); } remote_cocoa::mojom::Application* NativeViewHostMac::GetRemoteCocoaApplication() const { if (auto* window_host = GetNSWindowHost()) { if (auto* application_host = window_host->application_host()) return application_host->GetApplication(); } return nullptr; } uint64_t NativeViewHostMac::GetNSViewId() const { auto* window_host = GetNSWindowHost(); if (window_host) return window_host->GetRootViewNSViewId(); return 0; } void NativeViewHostMac::OnHostableViewDestroying() { DCHECK(native_view_hostable_); host_->NativeViewDestroyed(); DCHECK(!native_view_hostable_); } //////////////////////////////////////////////////////////////////////////////// // NativeViewHostMac, NativeViewHostWrapper implementation: void NativeViewHostMac::AttachNativeView() { DCHECK(host_->native_view()); DCHECK(!native_view_); native_view_.reset([host_->native_view().GetNativeNSView() retain]); if ([native_view_ conformsToProtocol:@protocol(ViewsHostable)]) { id hostable = native_view_; native_view_hostable_ = [hostable viewsHostableView]; } EnsureNativeViewHasNoChildWidgets(native_view_); auto* window_host = GetNSWindowHost(); CHECK(window_host); // TODO(https://crbug.com/933679): This is lifted out the ViewsHostableAttach // call below because of crashes being observed in the field. NSView* superview = window_host->native_widget_mac()->GetNativeView().GetNativeNSView(); [superview addSubview:native_view_]; if (native_view_hostable_) { native_view_hostable_->ViewsHostableAttach(this); // Initially set the parent to match the views::Views parent. Note that this // may be overridden (e.g, by views::WebView). native_view_hostable_->ViewsHostableSetParentAccessible( host_->parent()->GetNativeViewAccessible()); } window_host->OnNativeViewHostAttach(host_, native_view_); } void NativeViewHostMac::NativeViewDetaching(bool destroyed) { // |destroyed| is only true if this class calls host_->NativeViewDestroyed(), // which is called if a hosted WebContentsView about to be destroyed (note // that its corresponding NSView may still exist). // |native_view_| can be nil here if RemovedFromWidget() is called before // NativeViewHost::Detach(). NSView* host_native_view = host_->native_view().GetNativeNSView(); if (!native_view_) { DCHECK(![host_native_view superview]); return; } DCHECK(native_view_ == host_native_view); if (native_view_hostable_) { native_view_hostable_->ViewsHostableDetach(); native_view_hostable_ = nullptr; } else { [native_view_ setHidden:YES]; [native_view_ removeFromSuperview]; } EnsureNativeViewHasNoChildWidgets(native_view_); auto* window_host = GetNSWindowHost(); // NativeWidgetNSWindowBridge can be null when Widget is closing. if (window_host) window_host->OnNativeViewHostDetach(host_); native_view_.reset(); } void NativeViewHostMac::AddedToWidget() { if (!host_->native_view()) return; AttachNativeView(); host_->Layout(); } void NativeViewHostMac::RemovedFromWidget() { if (!host_->native_view()) return; NativeViewDetaching(false); } bool NativeViewHostMac::SetCornerRadii( const gfx::RoundedCornersF& corner_radii) { ui::Layer* layer = GetUiLayer(); DCHECK(layer); layer->SetRoundedCornerRadius(corner_radii); layer->SetIsFastRoundedCorner(true); return true; } bool NativeViewHostMac::SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) { NOTIMPLEMENTED(); return false; } void NativeViewHostMac::SetHitTestTopInset(int top_inset) { NOTIMPLEMENTED(); } int NativeViewHostMac::GetHitTestTopInset() const { NOTIMPLEMENTED(); return 0; } void NativeViewHostMac::InstallClip(int x, int y, int w, int h) { NOTIMPLEMENTED(); } bool NativeViewHostMac::HasInstalledClip() { return false; } void NativeViewHostMac::UninstallClip() { NOTIMPLEMENTED(); } void NativeViewHostMac::ShowWidget(int x, int y, int w, int h, int native_w, int native_h) { // TODO(https://crbug.com/415024): Implement host_->fast_resize(). if (native_view_hostable_) { native_view_hostable_->ViewsHostableSetBounds(gfx::Rect(x, y, w, h)); native_view_hostable_->ViewsHostableSetVisible(true); } else { // Coordinates will be from the top left of the parent Widget. The // NativeView is already in the same NSWindow, so just flip to get Cooca // coordinates and then convert to the containing view. NSRect window_rect = NSMakeRect( x, host_->GetWidget()->GetClientAreaBoundsInScreen().height() - y - h, w, h); // Convert window coordinates to the hosted view's superview, since that's // how coordinates of the hosted view's frame is based. NSRect container_rect = [[native_view_ superview] convertRect:window_rect fromView:nil]; [native_view_ setFrame:container_rect]; [native_view_ setHidden:NO]; } } void NativeViewHostMac::HideWidget() { if (native_view_hostable_) native_view_hostable_->ViewsHostableSetVisible(false); else [native_view_ setHidden:YES]; } void NativeViewHostMac::SetFocus() { if (native_view_hostable_) { native_view_hostable_->ViewsHostableMakeFirstResponder(); } else { if ([native_view_ acceptsFirstResponder]) [[native_view_ window] makeFirstResponder:native_view_]; } } gfx::NativeView NativeViewHostMac::GetNativeViewContainer() const { NOTIMPLEMENTED(); return nullptr; } gfx::NativeViewAccessible NativeViewHostMac::GetNativeViewAccessible() { if (native_view_hostable_) return native_view_hostable_->ViewsHostableGetAccessibilityElement(); else return native_view_; } ui::Cursor NativeViewHostMac::GetCursor(int x, int y) { // Intentionally not implemented: Not required on non-aura Mac because OSX // will query the native view for the cursor directly. For NativeViewHostMac // in practice, OSX will retrieve the cursor that was last set by // -[RenderWidgetHostViewCocoa updateCursor:] whenever the pointer is over the // hosted view. With some plumbing, NativeViewHostMac could return that same // cursor here, but it doesn't achieve anything. The implications of returning // null simply mean that the "fallback" cursor on the window itself will be // cleared (see -[NativeWidgetMacNSWindow cursorUpdate:]). However, while the // pointer is over a RenderWidgetHostViewCocoa, OSX won't ask for the fallback // cursor. return ui::Cursor(); } void NativeViewHostMac::SetVisible(bool visible) { if (native_view_hostable_) native_view_hostable_->ViewsHostableSetVisible(visible); else [native_view_ setHidden:!visible]; } void NativeViewHostMac::SetParentAccessible( gfx::NativeViewAccessible parent_accessibility_element) { if (native_view_hostable_) { native_view_hostable_->ViewsHostableSetParentAccessible( parent_accessibility_element); } else { // It is not easy to force a generic NSView to return a different // accessibility parent. Fortunately, this interface is only ever used // in practice to host a WebContentsView. } } gfx::NativeViewAccessible NativeViewHostMac::GetParentAccessible() { return native_view_hostable_ ? native_view_hostable_->ViewsHostableGetParentAccessible() : nullptr; } // static NativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper( NativeViewHost* host) { return new NativeViewHostMac(host); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_mac.mm
Objective-C++
unknown
9,588
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host_mac.h" #import <Cocoa/Cocoa.h> #include <memory> #include "base/mac/mac_util.h" #import "base/mac/scoped_nsobject.h" #import "testing/gtest_mac.h" #import "ui/base/cocoa/views_hostable.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/controls/native/native_view_host_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" class TestViewsHostable : public ui::ViewsHostableView { public: id parent_accessibility_element() const { return parent_accessibility_element_; } private: // ui::ViewsHostableView: void ViewsHostableAttach(ui::ViewsHostableView::Host* host) override { } void ViewsHostableDetach() override { parent_accessibility_element_ = nil; } void ViewsHostableSetBounds(const gfx::Rect& bounds_in_window) override {} void ViewsHostableSetVisible(bool visible) override {} void ViewsHostableMakeFirstResponder() override {} void ViewsHostableSetParentAccessible( gfx::NativeViewAccessible parent_accessibility_element) override { parent_accessibility_element_ = parent_accessibility_element; } gfx::NativeViewAccessible ViewsHostableGetParentAccessible() override { return parent_accessibility_element_; } gfx::NativeViewAccessible ViewsHostableGetAccessibilityElement() override { return nil; } id parent_accessibility_element_ = nil; }; @interface TestViewsHostableView : NSView<ViewsHostable> @property(nonatomic, assign) ui::ViewsHostableView* viewsHostableView; @end @implementation TestViewsHostableView @synthesize viewsHostableView = _viewsHostableView; @end namespace views { class NativeViewHostMacTest : public test::NativeViewHostTestBase { public: NativeViewHostMacTest() = default; NativeViewHostMacTest(const NativeViewHostMacTest&) = delete; NativeViewHostMacTest& operator=(const NativeViewHostMacTest&) = delete; // testing::Test: void TearDown() override { // On Aura, the compositor is destroyed when the WindowTreeHost provided by // AuraTestHelper is destroyed. On Mac, the Widget is the host, so it must // be closed before the ContextFactory is torn down by ViewsTestBase. DestroyTopLevel(); NativeViewHostTestBase::TearDown(); } NativeViewHostMac* native_host() { return static_cast<NativeViewHostMac*>(GetNativeWrapper()); } void CreateHost() { CreateTopLevel(); CreateTestingHost(); native_view_.reset([[NSView alloc] initWithFrame:NSZeroRect]); // Verify the expectation that the NativeViewHostWrapper is only created // after the NativeViewHost is added to a widget. EXPECT_FALSE(native_host()); toplevel()->GetRootView()->AddChildView(host()); EXPECT_TRUE(native_host()); host()->Attach(native_view_.get()); } protected: base::scoped_nsobject<NSView> native_view_; }; // Test destroying the top level widget before destroying the NativeViewHost. // On Mac, also ensure that the native view is removed from its superview when // the Widget containing its host is destroyed. TEST_F(NativeViewHostMacTest, DestroyWidget) { ResetHostDestroyedCount(); CreateHost(); ReleaseHost(); EXPECT_EQ(0, host_destroyed_count()); EXPECT_TRUE([native_view_ superview]); DestroyTopLevel(); EXPECT_FALSE([native_view_ superview]); EXPECT_EQ(1, host_destroyed_count()); } // Ensure the native view receives the correct bounds when it is attached. On // Mac, the bounds of the native view is relative to the NSWindow it is in, not // the screen, and the coordinates have to be flipped. TEST_F(NativeViewHostMacTest, Attach) { CreateHost(); EXPECT_TRUE([native_view_ superview]); EXPECT_TRUE([native_view_ window]); host()->Detach(); [native_view_ setFrame:NSZeroRect]; toplevel()->SetBounds(gfx::Rect(64, 48, 100, 200)); host()->SetBounds(10, 10, 80, 60); EXPECT_FALSE([native_view_ superview]); EXPECT_FALSE([native_view_ window]); EXPECT_NSEQ(NSZeroRect, [native_view_ frame]); host()->Attach(native_view_.get()); EXPECT_TRUE([native_view_ superview]); EXPECT_TRUE([native_view_ window]); // Layout() is normally async, call it now to ensure bounds have been applied. host()->Layout(); // Expect the top-left to be 10 pixels below the titlebar. int bottom = toplevel()->GetClientAreaBoundsInScreen().height() - 10 - 60; EXPECT_NSEQ(NSMakeRect(10, bottom, 80, 60), [native_view_ frame]); DestroyHost(); } // Ensure the native view is integrated into the views accessibility // hierarchy if the native view conforms to the AccessibilityParent // protocol. TEST_F(NativeViewHostMacTest, AccessibilityParent) { CreateHost(); host()->Detach(); base::scoped_nsobject<TestViewsHostableView> view( [[TestViewsHostableView alloc] init]); TestViewsHostable views_hostable; [view setViewsHostableView:&views_hostable]; host()->Attach(view.get()); EXPECT_NSEQ(views_hostable.parent_accessibility_element(), toplevel()->GetRootView()->GetNativeViewAccessible()); host()->Detach(); DestroyHost(); EXPECT_FALSE(views_hostable.parent_accessibility_element()); } // Test that the content windows' bounds are set to the correct values while the // native size is equal or not equal to the View size. TEST_F(NativeViewHostMacTest, ContentViewPositionAndSize) { CreateHost(); toplevel()->SetBounds(gfx::Rect(0, 0, 100, 100)); // The new visual style on macOS 11 (and presumably later) has slightly taller // titlebars, which means the window rect has to leave a bit of extra space // for the titlebar. int titlebar_extra = base::mac::IsAtLeastOS11() ? 6 : 0; native_host()->ShowWidget(5, 10, 100, 100, 200, 200); EXPECT_NSEQ(NSMakeRect(5, -32 - titlebar_extra, 100, 100), [native_view_ frame]); native_host()->ShowWidget(10, 25, 50, 50, 50, 50); EXPECT_NSEQ(NSMakeRect(10, 3 - titlebar_extra, 50, 50), [native_view_ frame]); DestroyHost(); } // Ensure the native view is hidden along with its host, and when detaching, or // when attaching to a host that is already hidden. TEST_F(NativeViewHostMacTest, NativeViewHidden) { CreateHost(); toplevel()->SetBounds(gfx::Rect(0, 0, 100, 100)); host()->SetBounds(10, 10, 80, 60); EXPECT_FALSE([native_view_ isHidden]); host()->SetVisible(false); EXPECT_TRUE([native_view_ isHidden]); host()->SetVisible(true); EXPECT_FALSE([native_view_ isHidden]); host()->Detach(); EXPECT_TRUE([native_view_ isHidden]); // Hidden when detached. [native_view_ setHidden:NO]; host()->SetVisible(false); EXPECT_FALSE([native_view_ isHidden]); // Stays visible. host()->Attach(native_view_.get()); EXPECT_TRUE([native_view_ isHidden]); // Hidden when attached. host()->Detach(); [native_view_ setHidden:YES]; host()->SetVisible(true); EXPECT_TRUE([native_view_ isHidden]); // Stays hidden. host()->Attach(native_view_.get()); // Layout() updates visibility, and is normally async, call it now to ensure // visibility updated. host()->Layout(); EXPECT_FALSE([native_view_ isHidden]); // Made visible when attached. EXPECT_TRUE([native_view_ superview]); toplevel()->GetRootView()->RemoveChildView(host()); EXPECT_TRUE([native_view_ isHidden]); // Hidden when removed from Widget. EXPECT_FALSE([native_view_ superview]); toplevel()->GetRootView()->AddChildView(host()); EXPECT_FALSE([native_view_ isHidden]); // And visible when added. EXPECT_TRUE([native_view_ superview]); DestroyHost(); } // Check that we can destroy cleanly even if the native view has already been // released. TEST_F(NativeViewHostMacTest, NativeViewReleased) { @autoreleasepool { CreateHost(); // In practice the native view is a WebContentsViewCocoa which is retained // by its superview (a TabContentsContainerView) and by WebContentsViewMac. // It's possible for both of them to be destroyed without calling // NativeHostView::Detach(). [native_view_ removeFromSuperview]; native_view_.reset(); } // During teardown, NativeViewDetaching() is called in RemovedFromWidget(). // Just trigger it with Detach(). host()->Detach(); DestroyHost(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_mac_unittest.mm
Objective-C++
unknown
8,336
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host_test_base.h" #include <utility> #include "base/memory/raw_ptr.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/widget/widget.h" namespace views::test { // Testing wrapper of the NativeViewHost. class NativeViewHostTestBase::NativeViewHostTesting : public NativeViewHost { public: explicit NativeViewHostTesting(NativeViewHostTestBase* owner) : owner_(owner) {} NativeViewHostTesting(const NativeViewHostTesting&) = delete; NativeViewHostTesting& operator=(const NativeViewHostTesting&) = delete; ~NativeViewHostTesting() override { owner_->host_destroyed_count_++; } // NativeViewHost: bool OnMousePressed(const ui::MouseEvent& event) override { ++owner_->on_mouse_pressed_called_count_; return NativeViewHost::OnMousePressed(event); } private: raw_ptr<NativeViewHostTestBase> owner_; }; NativeViewHostTestBase::NativeViewHostTestBase() = default; NativeViewHostTestBase::~NativeViewHostTestBase() = default; void NativeViewHostTestBase::TearDown() { DestroyTopLevel(); ViewsTestBase::TearDown(); } void NativeViewHostTestBase::CreateTopLevel(WidgetDelegate* widget_delegate) { toplevel_ = std::make_unique<Widget>(); Widget::InitParams toplevel_params = CreateParams(Widget::InitParams::TYPE_WINDOW); toplevel_params.delegate = widget_delegate; toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; toplevel_->Init(std::move(toplevel_params)); } void NativeViewHostTestBase::CreateTestingHost() { host_ = std::make_unique<NativeViewHostTesting>(this); } Widget* NativeViewHostTestBase::CreateChildForHost( gfx::NativeView native_parent_view, View* parent_view, View* contents_view, NativeViewHost* host) { Widget* child = new Widget; Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = native_parent_view; child->Init(std::move(child_params)); child->SetContentsView(contents_view); // Owned by |parent_view|. parent_view->AddChildView(host); host->Attach(child->GetNativeView()); return child; } void NativeViewHostTestBase::DestroyTopLevel() { toplevel_.reset(); } void NativeViewHostTestBase::DestroyHost() { host_.reset(); } NativeViewHost* NativeViewHostTestBase::ReleaseHost() { return host_.release(); } NativeViewHostWrapper* NativeViewHostTestBase::GetNativeWrapper() { return host_->native_wrapper_.get(); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_test_base.cc
C++
unknown
2,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. #ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_TEST_BASE_H_ #define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_TEST_BASE_H_ #include <memory> #include "ui/views/test/views_test_base.h" namespace views { class NativeViewHost; class NativeViewHostWrapper; class Widget; class WidgetDelegate; namespace test { // Base class for NativeViewHost tests on different platforms. class NativeViewHostTestBase : public ViewsTestBase { public: NativeViewHostTestBase(); NativeViewHostTestBase(const NativeViewHostTestBase&) = delete; NativeViewHostTestBase& operator=(const NativeViewHostTestBase&) = delete; ~NativeViewHostTestBase() override; // testing::Test: void TearDown() override; // Create the |toplevel_| widget. void CreateTopLevel(WidgetDelegate* widget_delegate = nullptr); // Create a testing |host_| that tracks destructor calls. void CreateTestingHost(); // The number of times a host created by CreateHost() has been destroyed. int host_destroyed_count() { return host_destroyed_count_; } void ResetHostDestroyedCount() { host_destroyed_count_ = 0; } // Create a child widget whose native parent is |native_parent_view|, uses // |contents_view|, and is attached to |host| which is added as a child to // |parent_view|. This effectively borrows the native content view from a // newly created child Widget, and attaches it to |host|. Widget* CreateChildForHost(gfx::NativeView native_parent_view, View* parent_view, View* contents_view, NativeViewHost* host); Widget* toplevel() { return toplevel_.get(); } void DestroyTopLevel(); NativeViewHost* host() { return host_.get(); } void DestroyHost(); NativeViewHost* ReleaseHost(); NativeViewHostWrapper* GetNativeWrapper(); protected: int on_mouse_pressed_called_count() { return on_mouse_pressed_called_count_; } private: class NativeViewHostTesting; std::unique_ptr<Widget> toplevel_; std::unique_ptr<NativeViewHost> host_; int host_destroyed_count_ = 0; int on_mouse_pressed_called_count_ = 0; }; } // namespace test } // namespace views #endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_TEST_BASE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_test_base.h
C++
unknown
2,378
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/native/native_view_host.h" #include <memory> #include "ui/aura/window.h" #include "ui/views/controls/native/native_view_host_test_base.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" namespace views { class NativeViewHostTest : public test::NativeViewHostTestBase { public: NativeViewHostTest() = default; NativeViewHostTest(const NativeViewHostTest&) = delete; NativeViewHostTest& operator=(const NativeViewHostTest&) = delete; void SetUp() override { ViewsTestBase::SetUp(); CreateTopLevel(); } }; namespace { // View implementation used by NativeViewHierarchyChanged to count number of // times NativeViewHierarchyChanged() is invoked. class NativeViewHierarchyChangedTestView : public View { public: NativeViewHierarchyChangedTestView() = default; NativeViewHierarchyChangedTestView( const NativeViewHierarchyChangedTestView&) = delete; NativeViewHierarchyChangedTestView& operator=( const NativeViewHierarchyChangedTestView&) = delete; void ResetCount() { notification_count_ = 0; } int notification_count() const { return notification_count_; } // Overriden from View: void NativeViewHierarchyChanged() override { ++notification_count_; View::NativeViewHierarchyChanged(); } private: int notification_count_ = 0; }; aura::Window* GetNativeParent(aura::Window* window) { return window->parent(); } class ViewHierarchyChangedTestHost : public NativeViewHost { public: ViewHierarchyChangedTestHost() = default; ViewHierarchyChangedTestHost(const ViewHierarchyChangedTestHost&) = delete; ViewHierarchyChangedTestHost& operator=(const ViewHierarchyChangedTestHost&) = delete; void ResetParentChanges() { num_parent_changes_ = 0; } int num_parent_changes() const { return num_parent_changes_; } // NativeViewHost: void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { gfx::NativeView parent_before = native_view() ? GetNativeParent(native_view()) : nullptr; NativeViewHost::ViewHierarchyChanged(details); gfx::NativeView parent_after = native_view() ? GetNativeParent(native_view()) : nullptr; if (parent_before != parent_after) ++num_parent_changes_; } private: int num_parent_changes_ = 0; }; } // namespace // Verifies NativeViewHierarchyChanged is sent. TEST_F(NativeViewHostTest, NativeViewHierarchyChanged) { // Create a child widget. NativeViewHierarchyChangedTestView* test_view = new NativeViewHierarchyChangedTestView; NativeViewHost* host = new NativeViewHost; std::unique_ptr<Widget> child(CreateChildForHost( toplevel()->GetNativeView(), toplevel()->GetRootView(), test_view, host)); #if defined(USE_AURA) // Two notifications are generated from inserting the native view into the // clipping window and then inserting the clipping window into the root // window. EXPECT_EQ(2, test_view->notification_count()); #else EXPECT_EQ(0, test_view->notification_count()); #endif test_view->ResetCount(); // Detaching should send a NativeViewHierarchyChanged() notification and // change the parent. host->Detach(); #if defined(USE_AURA) // Two notifications are generated from removing the native view from the // clipping window and then reparenting it to the root window. EXPECT_EQ(2, test_view->notification_count()); #else EXPECT_EQ(1, test_view->notification_count()); #endif EXPECT_NE(toplevel()->GetNativeView(), GetNativeParent(child->GetNativeView())); test_view->ResetCount(); // Attaching should send a NativeViewHierarchyChanged() notification and // reset the parent. host->Attach(child->GetNativeView()); #if defined(USE_AURA) // There is a clipping window inserted above the native view that needs to be // accounted for when looking at the relationship between the native views. EXPECT_EQ(2, test_view->notification_count()); EXPECT_EQ(toplevel()->GetNativeView(), GetNativeParent(GetNativeParent(child->GetNativeView()))); #else EXPECT_EQ(1, test_view->notification_count()); EXPECT_EQ(toplevel()->GetNativeView(), GetNativeParent(child->GetNativeView())); #endif } // Verifies ViewHierarchyChanged handles NativeViewHost remove, add and move // (reparent) operations with correct parent changes. // This exercises the non-recursive code paths in // View::PropagateRemoveNotifications() and View::PropagateAddNotifications(). TEST_F(NativeViewHostTest, ViewHierarchyChangedForHost) { // Original tree: // toplevel // +-- host0 (NativeViewHost) // +-- child0 (Widget, attached to host0) // +-- test_host (ViewHierarchyChangedTestHost) // +-- test_child (Widget, attached to test_host) // +-- host1 (NativeViewHost) // +-- child1 (Widget, attached to host1) // Add two children widgets attached to a NativeViewHost, and a test // grandchild as child widget of host0. NativeViewHost* host0 = new NativeViewHost; std::unique_ptr<Widget> child0(CreateChildForHost( toplevel()->GetNativeView(), toplevel()->GetRootView(), new View, host0)); NativeViewHost* host1 = new NativeViewHost; std::unique_ptr<Widget> child1(CreateChildForHost( toplevel()->GetNativeView(), toplevel()->GetRootView(), new View, host1)); ViewHierarchyChangedTestHost* test_host = new ViewHierarchyChangedTestHost; std::unique_ptr<Widget> test_child( CreateChildForHost(host0->native_view(), host0, new View, test_host)); // Remove test_host from host0, expect 1 parent change. test_host->ResetParentChanges(); EXPECT_EQ(0, test_host->num_parent_changes()); host0->RemoveChildView(test_host); EXPECT_EQ(1, test_host->num_parent_changes()); // Add test_host back to host0, expect 1 parent change. test_host->ResetParentChanges(); EXPECT_EQ(0, test_host->num_parent_changes()); host0->AddChildView(test_host); EXPECT_EQ(1, test_host->num_parent_changes()); // Reparent test_host to host1, expect no parent change because the old and // new parents, host0 and host1, belong to the same toplevel widget. test_host->ResetParentChanges(); EXPECT_EQ(0, test_host->num_parent_changes()); host1->AddChildView(test_host); EXPECT_EQ(0, test_host->num_parent_changes()); // Reparent test_host to contents view of child0, expect 2 parent changes // because the old parent belongs to the toplevel widget whereas the new // parent belongs to the child0. test_host->ResetParentChanges(); EXPECT_EQ(0, test_host->num_parent_changes()); child0->GetContentsView()->AddChildView(test_host); EXPECT_EQ(2, test_host->num_parent_changes()); } // Verifies ViewHierarchyChanged handles NativeViewHost's parent remove, add and // move (reparent) operations with correct parent changes. // This exercises the recursive code paths in // View::PropagateRemoveNotifications() and View::PropagateAddNotifications(). TEST_F(NativeViewHostTest, ViewHierarchyChangedForHostParent) { // Original tree: // toplevel // +-- view0 (View) // +-- host0 (NativeViewHierarchyChangedTestHost) // +-- child0 (Widget, attached to host0) // +-- view1 (View) // +-- host1 (NativeViewHierarchyChangedTestHost) // +-- child1 (Widget, attached to host1) // Add two children views. View* view0 = new View; toplevel()->GetRootView()->AddChildView(view0); View* view1 = new View; toplevel()->GetRootView()->AddChildView(view1); // To each child view, add a child widget. ViewHierarchyChangedTestHost* host0 = new ViewHierarchyChangedTestHost; std::unique_ptr<Widget> child0( CreateChildForHost(toplevel()->GetNativeView(), view0, new View, host0)); ViewHierarchyChangedTestHost* host1 = new ViewHierarchyChangedTestHost; std::unique_ptr<Widget> child1( CreateChildForHost(toplevel()->GetNativeView(), view1, new View, host1)); // Remove view0 from top level, expect 1 parent change. host0->ResetParentChanges(); EXPECT_EQ(0, host0->num_parent_changes()); toplevel()->GetRootView()->RemoveChildView(view0); EXPECT_EQ(1, host0->num_parent_changes()); // Add view0 back to top level, expect 1 parent change. host0->ResetParentChanges(); EXPECT_EQ(0, host0->num_parent_changes()); toplevel()->GetRootView()->AddChildView(view0); EXPECT_EQ(1, host0->num_parent_changes()); // Reparent view0 to view1, expect no parent change because the old and new // parents of both view0 and view1 belong to the same toplevel widget. host0->ResetParentChanges(); host1->ResetParentChanges(); EXPECT_EQ(0, host0->num_parent_changes()); EXPECT_EQ(0, host1->num_parent_changes()); view1->AddChildView(view0); EXPECT_EQ(0, host0->num_parent_changes()); EXPECT_EQ(0, host1->num_parent_changes()); // Restore original view hierarchy by adding back view0 to top level. // Then, reparent view1 to contents view of child0. // Expect 2 parent changes because the old parent belongs to the toplevel // widget whereas the new parent belongs to the 1st child widget. toplevel()->GetRootView()->AddChildView(view0); host0->ResetParentChanges(); host1->ResetParentChanges(); EXPECT_EQ(0, host0->num_parent_changes()); EXPECT_EQ(0, host1->num_parent_changes()); child0->GetContentsView()->AddChildView(view1); EXPECT_EQ(0, host0->num_parent_changes()); EXPECT_EQ(2, host1->num_parent_changes()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_unittest.cc
C++
unknown
9,577
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_ #define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_ #include <memory> #include "ui/base/cursor/cursor.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/views_export.h" namespace gfx { class RoundedCornersF; } namespace ui { class LayerOwner; } namespace views { class NativeViewHost; // An interface that implemented by an object that wraps a gfx::NativeView on // a specific platform, used to perform platform specific operations on that // native view when attached, detached, moved and sized. class NativeViewHostWrapper { public: virtual ~NativeViewHostWrapper() = default; // Called at the end of NativeViewHost::Attach, allowing the wrapper to // perform platform-specific operations that need to occur to complete // attaching the gfx::NativeView. virtual void AttachNativeView() = 0; // Called before the attached gfx::NativeView is detached from the // NativeViewHost, allowing the wrapper to perform platform-specific // cleanup. |destroyed| is true if the native view is detached // because it's being destroyed, or false otherwise. virtual void NativeViewDetaching(bool destroyed) = 0; // Called when our associated NativeViewHost is added to a View hierarchy // rooted at a valid Widget. virtual void AddedToWidget() = 0; // Called when our associated NativeViewHost is removed from a View hierarchy // rooted at a valid Widget. virtual void RemovedFromWidget() = 0; // Clips the corners of the gfx::NativeView to the |corner_radii| specififed. // Returns true on success or false if the platform doesn't support the // operation. virtual bool SetCornerRadii(const gfx::RoundedCornersF& corner_radii) = 0; // Sets the custom mask for clipping gfx::NativeView. Returns true on // success or false if the platform doesn't support the operation. virtual bool SetCustomMask(std::unique_ptr<ui::LayerOwner> mask) = 0; // Sets the height of the top region where gfx::NativeView shouldn't be // targeted. virtual void SetHitTestTopInset(int top_inset) = 0; virtual int GetHitTestTopInset() const = 0; // Installs a clip on the gfx::NativeView. These values are in the coordinate // space of the Widget, so if this method is called from ShowWidget // then the values need to be translated. virtual void InstallClip(int x, int y, int w, int h) = 0; // Whether or not a clip has been installed on the wrapped gfx::NativeView. virtual bool HasInstalledClip() = 0; // Removes the clip installed on the gfx::NativeView by way of InstallClip. A // following call to ShowWidget should occur after calling this method to // position the gfx::NativeView correctly, since the clipping process may have // adjusted its position. virtual void UninstallClip() = 0; // Shows the gfx::NativeView within the specified region (relative to the // parent native view) and with the given native size. The content will // appear scaled if the |native_w| or |native_h| are different from |w| or // |h|. virtual void ShowWidget(int x, int y, int w, int h, int native_w, int native_h) = 0; // Hides the gfx::NativeView. NOTE: this may be invoked when the native view // is already hidden. virtual void HideWidget() = 0; // Sets focus to the gfx::NativeView. virtual void SetFocus() = 0; // Returns the container that contains the NativeViewHost's native view if // any. virtual gfx::NativeView GetNativeViewContainer() const = 0; // Return the native view accessible corresponding to the wrapped native // view. virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0; // Returns the cursor corresponding to the point (x, y) in the native view. virtual ui::Cursor GetCursor(int x, int y) = 0; // Sets the visibility of the gfx::NativeView. This differs from // {Show,Hide}Widget because it doesn't affect the placement, size, // or clipping of the view. virtual void SetVisible(bool visible) = 0; // Pass the parent accessible object to the native view so that it can return // this value when querying its parent accessible. virtual void SetParentAccessible(gfx::NativeViewAccessible) = 0; // Returns the parent accessible object to the native view. virtual gfx::NativeViewAccessible GetParentAccessible() = 0; // Creates a platform-specific instance of an object implementing this // interface. static NativeViewHostWrapper* CreateWrapper(NativeViewHost* host); }; } // namespace views #endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/native/native_view_host_wrapper.h
C++
unknown
4,864
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_ #define UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { // An interface used to expose lists of items for selection by text input. class VIEWS_EXPORT PrefixDelegate { public: // Returns the total number of selectable items. virtual size_t GetRowCount() = 0; // Returns the row of the currently selected item, or -1 if no item is // selected. virtual absl::optional<size_t> GetSelectedRow() = 0; // Sets the selection to the specified row. virtual void SetSelectedRow(absl::optional<size_t> row) = 0; // Returns the item at the specified row. virtual std::u16string GetTextForRow(size_t row) = 0; }; } // namespace views #endif // UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/prefix_delegate.h
C++
unknown
1,010
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/prefix_selector.h" #include <algorithm> #include <limits> #include "base/i18n/case_conversion.h" #include "base/time/default_tick_clock.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/base/ime/input_method.h" #include "ui/base/ime/text_input_type.h" #include "ui/gfx/range/range.h" #include "ui/views/controls/prefix_delegate.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_WIN) #include <vector> #endif namespace views { PrefixSelector::PrefixSelector(PrefixDelegate* delegate, View* host_view) : prefix_delegate_(delegate), host_view_(host_view), tick_clock_(base::DefaultTickClock::GetInstance()) {} PrefixSelector::~PrefixSelector() = default; void PrefixSelector::OnViewBlur() { ClearText(); } bool PrefixSelector::ShouldContinueSelection() const { const base::TimeTicks now(tick_clock_->NowTicks()); constexpr auto kTimeBeforeClearing = base::Seconds(1); return (now - time_of_last_key_) < kTimeBeforeClearing; } void PrefixSelector::SetCompositionText( const ui::CompositionText& composition) {} size_t PrefixSelector::ConfirmCompositionText(bool keep_selection) { return std::numeric_limits<size_t>::max(); } void PrefixSelector::ClearCompositionText() {} void PrefixSelector::InsertText(const std::u16string& text, InsertTextCursorBehavior cursor_behavior) { // TODO(crbug.com/1155331): Handle |cursor_behavior| correctly. OnTextInput(text); } void PrefixSelector::InsertChar(const ui::KeyEvent& event) { OnTextInput(std::u16string(1, event.GetCharacter())); } ui::TextInputType PrefixSelector::GetTextInputType() const { return ui::TEXT_INPUT_TYPE_TEXT; } ui::TextInputMode PrefixSelector::GetTextInputMode() const { return ui::TEXT_INPUT_MODE_DEFAULT; } base::i18n::TextDirection PrefixSelector::GetTextDirection() const { return base::i18n::UNKNOWN_DIRECTION; } int PrefixSelector::GetTextInputFlags() const { return 0; } bool PrefixSelector::CanComposeInline() const { return false; } gfx::Rect PrefixSelector::GetCaretBounds() const { gfx::Rect rect(host_view_->GetVisibleBounds().origin(), gfx::Size()); // TextInputClient::GetCaretBounds is expected to return a value in screen // coordinates. views::View::ConvertRectToScreen(host_view_, &rect); return rect; } gfx::Rect PrefixSelector::GetSelectionBoundingBox() const { NOTIMPLEMENTED_LOG_ONCE(); return gfx::Rect(); } bool PrefixSelector::GetCompositionCharacterBounds(size_t index, gfx::Rect* rect) const { // TextInputClient::GetCompositionCharacterBounds is expected to fill |rect| // in screen coordinates and GetCaretBounds returns screen coordinates. *rect = GetCaretBounds(); return false; } bool PrefixSelector::HasCompositionText() const { return false; } ui::TextInputClient::FocusReason PrefixSelector::GetFocusReason() const { // TODO(https://crbug.com/824604): Implement this correctly. NOTIMPLEMENTED_LOG_ONCE(); return ui::TextInputClient::FOCUS_REASON_OTHER; } bool PrefixSelector::GetTextRange(gfx::Range* range) const { *range = gfx::Range(); return false; } bool PrefixSelector::GetCompositionTextRange(gfx::Range* range) const { *range = gfx::Range(); return false; } bool PrefixSelector::GetEditableSelectionRange(gfx::Range* range) const { *range = gfx::Range(); return false; } bool PrefixSelector::SetEditableSelectionRange(const gfx::Range& range) { return false; } #if BUILDFLAG(IS_MAC) bool PrefixSelector::DeleteRange(const gfx::Range& range) { return false; } #endif bool PrefixSelector::GetTextFromRange(const gfx::Range& range, std::u16string* text) const { return false; } void PrefixSelector::OnInputMethodChanged() { ClearText(); } bool PrefixSelector::ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) { return true; } void PrefixSelector::ExtendSelectionAndDelete(size_t before, size_t after) {} void PrefixSelector::EnsureCaretNotInRect(const gfx::Rect& rect) {} bool PrefixSelector::IsTextEditCommandEnabled( ui::TextEditCommand command) const { return false; } void PrefixSelector::SetTextEditCommandForNextKeyEvent( ui::TextEditCommand command) {} ukm::SourceId PrefixSelector::GetClientSourceForMetrics() const { // TODO(shend): Implement this method. NOTIMPLEMENTED_LOG_ONCE(); return ukm::SourceId(); } bool PrefixSelector::ShouldDoLearning() { // TODO(https://crbug.com/311180): Implement this method. NOTIMPLEMENTED_LOG_ONCE(); return false; } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) bool PrefixSelector::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) { // TODO(https://crbug.com/952757): Implement this method. NOTIMPLEMENTED_LOG_ONCE(); return false; } #endif #if BUILDFLAG(IS_CHROMEOS) gfx::Range PrefixSelector::GetAutocorrectRange() const { NOTIMPLEMENTED_LOG_ONCE(); return gfx::Range(); } gfx::Rect PrefixSelector::GetAutocorrectCharacterBounds() const { NOTIMPLEMENTED_LOG_ONCE(); return gfx::Rect(); } bool PrefixSelector::SetAutocorrectRange(const gfx::Range& range) { // TODO(crbug.com/1091088): Implement SetAutocorrectRange. NOTIMPLEMENTED_LOG_ONCE(); return false; } #endif #if BUILDFLAG(IS_WIN) void PrefixSelector::SetActiveCompositionForAccessibility( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) {} #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS) void PrefixSelector::GetActiveTextInputControlLayoutBounds( absl::optional<gfx::Rect>* control_bounds, absl::optional<gfx::Rect>* selection_bounds) {} #endif void PrefixSelector::OnTextInput(const std::u16string& text) { // Small hack to filter out 'tab' and 'enter' input, as the expectation is // that they are control characters and will not affect the currently-active // prefix. if (text.length() == 1 && (text[0] == L'\t' || text[0] == L'\r' || text[0] == L'\n')) return; const size_t row_count = prefix_delegate_->GetRowCount(); if (row_count == 0) return; // Search for |text| if it has been a while since the user typed, otherwise // append |text| to |current_text_| and search for that. If it has been a // while search after the current row, otherwise search starting from the // current row. size_t row = prefix_delegate_->GetSelectedRow().value_or(0); if (ShouldContinueSelection()) { current_text_ += text; } else { current_text_ = text; if (prefix_delegate_->GetSelectedRow().has_value()) row = (row + 1) % row_count; } time_of_last_key_ = tick_clock_->NowTicks(); const size_t start_row = row; const std::u16string lower_text(base::i18n::ToLower(current_text_)); do { if (TextAtRowMatchesText(row, lower_text)) { prefix_delegate_->SetSelectedRow(row); return; } row = (row + 1) % row_count; } while (row != start_row); } bool PrefixSelector::TextAtRowMatchesText(size_t row, const std::u16string& lower_text) { const std::u16string model_text( base::i18n::ToLower(prefix_delegate_->GetTextForRow(row))); return (model_text.size() >= lower_text.size()) && (model_text.compare(0, lower_text.size(), lower_text) == 0); } void PrefixSelector::ClearText() { current_text_.clear(); time_of_last_key_ = base::TimeTicks(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/prefix_selector.cc
C++
unknown
7,769
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_ #define UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_ #include <stddef.h> #include <stdint.h> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/time/time.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/base/ime/text_input_client.h" #include "ui/views/views_export.h" namespace base { class TickClock; } namespace views { class PrefixDelegate; class View; // PrefixSelector is used to change the selection in a view as the user // types characters. class VIEWS_EXPORT PrefixSelector : public ui::TextInputClient { public: PrefixSelector(PrefixDelegate* delegate, View* host_view); PrefixSelector(const PrefixSelector&) = delete; PrefixSelector& operator=(const PrefixSelector&) = delete; ~PrefixSelector() override; // Invoked from the view when it loses focus. void OnViewBlur(); // Returns whether a key typed now would continue the existing search or start // a new search. bool ShouldContinueSelection() const; // ui::TextInputClient: void SetCompositionText(const ui::CompositionText& composition) override; size_t ConfirmCompositionText(bool keep_selection) override; void ClearCompositionText() override; void InsertText(const std::u16string& text, InsertTextCursorBehavior cursor_behavior) override; void InsertChar(const ui::KeyEvent& event) override; ui::TextInputType GetTextInputType() const override; ui::TextInputMode GetTextInputMode() const override; base::i18n::TextDirection GetTextDirection() const override; int GetTextInputFlags() const override; bool CanComposeInline() const override; gfx::Rect GetCaretBounds() const override; gfx::Rect GetSelectionBoundingBox() const override; bool GetCompositionCharacterBounds(size_t index, gfx::Rect* rect) const override; bool HasCompositionText() const override; FocusReason GetFocusReason() const override; bool GetTextRange(gfx::Range* range) const override; bool GetCompositionTextRange(gfx::Range* range) const override; bool GetEditableSelectionRange(gfx::Range* range) const override; bool SetEditableSelectionRange(const gfx::Range& range) override; #if BUILDFLAG(IS_MAC) bool DeleteRange(const gfx::Range& range) override; #endif bool GetTextFromRange(const gfx::Range& range, std::u16string* text) const override; void OnInputMethodChanged() override; bool ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) override; void ExtendSelectionAndDelete(size_t before, size_t after) override; void EnsureCaretNotInRect(const gfx::Rect& rect) override; bool IsTextEditCommandEnabled(ui::TextEditCommand command) const override; void SetTextEditCommandForNextKeyEvent(ui::TextEditCommand command) override; ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override; #endif #if BUILDFLAG(IS_CHROMEOS) gfx::Range GetAutocorrectRange() const override; gfx::Rect GetAutocorrectCharacterBounds() const override; bool SetAutocorrectRange(const gfx::Range& range) override; #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS) void GetActiveTextInputControlLayoutBounds( absl::optional<gfx::Rect>* control_bounds, absl::optional<gfx::Rect>* selection_bounds) override; #endif #if BUILDFLAG(IS_WIN) void SetActiveCompositionForAccessibility( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) override; #endif void set_tick_clock_for_testing(const base::TickClock* clock) { tick_clock_ = clock; } private: // Invoked when text is typed. Tries to change the selection appropriately. void OnTextInput(const std::u16string& text); // Returns true if the text of the node at |row| starts with |lower_text|. bool TextAtRowMatchesText(size_t row, const std::u16string& lower_text); // Clears |current_text_| and resets |time_of_last_key_|. void ClearText(); raw_ptr<PrefixDelegate> prefix_delegate_; raw_ptr<View> host_view_; // Time OnTextInput() was last invoked. base::TimeTicks time_of_last_key_; std::u16string current_text_; // TickClock used for getting the time of the current keystroke, used for // continuing or restarting selections. raw_ptr<const base::TickClock> tick_clock_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/prefix_selector.h
C++
unknown
4,858
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/prefix_selector.h" #include <memory> #include <string> #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/views/controls/prefix_delegate.h" #include "ui/views/test/views_test_base.h" using base::ASCIIToUTF16; namespace views { class TestPrefixDelegate : public View, public PrefixDelegate { public: TestPrefixDelegate() { rows_.push_back(u"aardvark"); rows_.push_back(u"antelope"); rows_.push_back(u"badger"); rows_.push_back(u"gnu"); } TestPrefixDelegate(const TestPrefixDelegate&) = delete; TestPrefixDelegate& operator=(const TestPrefixDelegate&) = delete; ~TestPrefixDelegate() override = default; size_t GetRowCount() override { return rows_.size(); } absl::optional<size_t> GetSelectedRow() override { return selected_row_; } void SetSelectedRow(absl::optional<size_t> row) override { selected_row_ = row; } std::u16string GetTextForRow(size_t row) override { return rows_[row]; } private: std::vector<std::u16string> rows_; absl::optional<size_t> selected_row_ = 0; }; class PrefixSelectorTest : public ViewsTestBase { public: PrefixSelectorTest() { selector_ = std::make_unique<PrefixSelector>(&delegate_, &delegate_); } PrefixSelectorTest(const PrefixSelectorTest&) = delete; PrefixSelectorTest& operator=(const PrefixSelectorTest&) = delete; ~PrefixSelectorTest() override { // Explicitly release |selector_| here which can happen before releasing // |delegate_|. selector_.reset(); } protected: std::unique_ptr<PrefixSelector> selector_; TestPrefixDelegate delegate_; }; TEST_F(PrefixSelectorTest, PrefixSelect) { selector_->InsertText( u"an", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(1u, delegate_.GetSelectedRow()); // Invoke OnViewBlur() to reset time. selector_->OnViewBlur(); selector_->InsertText( u"a", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(0u, delegate_.GetSelectedRow()); selector_->OnViewBlur(); selector_->InsertText( u"g", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(3u, delegate_.GetSelectedRow()); selector_->OnViewBlur(); selector_->InsertText( u"b", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); selector_->InsertText( u"a", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(2u, delegate_.GetSelectedRow()); selector_->OnViewBlur(); selector_->InsertText( u"\t", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); selector_->InsertText( u"b", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); selector_->InsertText( u"a", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(2u, delegate_.GetSelectedRow()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/prefix_selector_unittest.cc
C++
unknown
3,151
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/progress_bar.h" #include <algorithm> #include <cmath> #include <memory> #include <string> #include "base/check_op.h" #include "base/i18n/number_formatting.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/views/widget/widget.h" namespace views { namespace { // In DP, the amount to round the corners of the progress bar (both bg and // fg, aka slice). constexpr int kCornerRadius = 3; constexpr int kSmallCornerRadius = 1; // Adds a rectangle to the path. The corners will be rounded with regular corner // radius if the progress bar height is larger than the regular corner radius. // Otherwise the corners will be rounded with the small corner radius if there // is room for it. void AddPossiblyRoundRectToPath(const gfx::Rect& rectangle, bool allow_round_corner, SkPath* path) { if (!allow_round_corner || rectangle.height() < kSmallCornerRadius) { path->addRect(gfx::RectToSkRect(rectangle)); } else if (rectangle.height() < kCornerRadius) { path->addRoundRect(gfx::RectToSkRect(rectangle), kSmallCornerRadius, kSmallCornerRadius); } else { path->addRoundRect(gfx::RectToSkRect(rectangle), kCornerRadius, kCornerRadius); } } int RoundToPercent(double fractional_value) { return static_cast<int>(fractional_value * 100); } } // namespace ProgressBar::ProgressBar(int preferred_height, bool allow_round_corner) : preferred_height_(preferred_height), allow_round_corner_(allow_round_corner) { SetFlipCanvasOnPaintForRTLUI(true); SetAccessibilityProperties(ax::mojom::Role::kProgressIndicator); } ProgressBar::~ProgressBar() = default; void ProgressBar::GetAccessibleNodeData(ui::AXNodeData* node_data) { View::GetAccessibleNodeData(node_data); if (IsIndeterminate()) { node_data->RemoveStringAttribute(ax::mojom::StringAttribute::kValue); } else { node_data->SetValue(base::FormatPercent(RoundToPercent(current_value_))); } } gfx::Size ProgressBar::CalculatePreferredSize() const { // The width will typically be ignored. gfx::Size pref_size(1, preferred_height_); gfx::Insets insets = GetInsets(); pref_size.Enlarge(insets.width(), insets.height()); return pref_size; } void ProgressBar::VisibilityChanged(View* starting_from, bool is_visible) { MaybeNotifyAccessibilityValueChanged(); } void ProgressBar::AddedToWidget() { MaybeNotifyAccessibilityValueChanged(); } void ProgressBar::OnPaint(gfx::Canvas* canvas) { if (IsIndeterminate()) { return OnPaintIndeterminate(canvas); } gfx::Rect content_bounds = GetContentsBounds(); // Draw background. SkPath background_path; AddPossiblyRoundRectToPath(content_bounds, allow_round_corner_, &background_path); cc::PaintFlags background_flags; background_flags.setStyle(cc::PaintFlags::kFill_Style); background_flags.setAntiAlias(true); background_flags.setColor(GetBackgroundColor()); canvas->DrawPath(background_path, background_flags); // Draw slice. SkPath slice_path; const int slice_width = static_cast<int>( content_bounds.width() * std::min(current_value_, 1.0) + 0.5); if (slice_width < 1) { return; } gfx::Rect slice_bounds = content_bounds; slice_bounds.set_width(slice_width); AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path); cc::PaintFlags slice_flags; slice_flags.setStyle(cc::PaintFlags::kFill_Style); slice_flags.setAntiAlias(true); slice_flags.setColor(GetForegroundColor()); canvas->DrawPath(slice_path, slice_flags); } double ProgressBar::GetValue() const { return current_value_; } void ProgressBar::SetValue(double value) { double adjusted_value = (value < 0.0 || value > 1.0) ? -1.0 : value; if (adjusted_value == current_value_) { return; } current_value_ = adjusted_value; if (IsIndeterminate()) { indeterminate_bar_animation_ = std::make_unique<gfx::LinearAnimation>(this); indeterminate_bar_animation_->SetDuration(base::Seconds(2)); indeterminate_bar_animation_->Start(); } else { indeterminate_bar_animation_.reset(); OnPropertyChanged(&current_value_, kPropertyEffectsPaint); } MaybeNotifyAccessibilityValueChanged(); } void ProgressBar::SetPaused(bool is_paused) { if (is_paused_ == is_paused) { return; } is_paused_ = is_paused; OnPropertyChanged(&is_paused_, kPropertyEffectsPaint); } SkColor ProgressBar::GetForegroundColor() const { if (foreground_color_) { return foreground_color_.value(); } return GetColorProvider()->GetColor(foreground_color_id_.value_or( GetPaused() ? ui::kColorProgressBarPaused : ui::kColorProgressBar)); } void ProgressBar::SetForegroundColor(SkColor color) { if (foreground_color_ == color) { return; } foreground_color_ = color; foreground_color_id_ = absl::nullopt; OnPropertyChanged(&foreground_color_, kPropertyEffectsPaint); } absl::optional<ui::ColorId> ProgressBar::GetForegroundColorId() const { return foreground_color_id_; } void ProgressBar::SetForegroundColorId(absl::optional<ui::ColorId> color_id) { if (foreground_color_id_ == color_id) { return; } foreground_color_id_ = color_id; foreground_color_ = absl::nullopt; OnPropertyChanged(&foreground_color_id_, kPropertyEffectsPaint); } SkColor ProgressBar::GetBackgroundColor() const { if (background_color_id_) { return GetColorProvider()->GetColor(background_color_id_.value()); } return background_color_.value_or( color_utils::BlendTowardMaxContrast(GetForegroundColor(), 0xCC)); } void ProgressBar::SetBackgroundColor(SkColor color) { if (background_color_ == color) { return; } background_color_ = color; background_color_id_ = absl::nullopt; OnPropertyChanged(&background_color_, kPropertyEffectsPaint); } absl::optional<ui::ColorId> ProgressBar::GetBackgroundColorId() const { return background_color_id_; } void ProgressBar::SetBackgroundColorId(absl::optional<ui::ColorId> color_id) { if (background_color_id_ == color_id) { return; } background_color_id_ = color_id; background_color_ = absl::nullopt; OnPropertyChanged(&background_color_id_, kPropertyEffectsPaint); } void ProgressBar::AnimationProgressed(const gfx::Animation* animation) { DCHECK_EQ(animation, indeterminate_bar_animation_.get()); DCHECK(IsIndeterminate()); SchedulePaint(); } void ProgressBar::AnimationEnded(const gfx::Animation* animation) { DCHECK_EQ(animation, indeterminate_bar_animation_.get()); // Restarts animation. if (IsIndeterminate()) { indeterminate_bar_animation_->Start(); } } bool ProgressBar::IsIndeterminate() { return current_value_ < 0.0; } void ProgressBar::OnPaintIndeterminate(gfx::Canvas* canvas) { gfx::Rect content_bounds = GetContentsBounds(); // Draw background. SkPath background_path; AddPossiblyRoundRectToPath(content_bounds, allow_round_corner_, &background_path); cc::PaintFlags background_flags; background_flags.setStyle(cc::PaintFlags::kFill_Style); background_flags.setAntiAlias(true); background_flags.setColor(GetBackgroundColor()); canvas->DrawPath(background_path, background_flags); // Draw slice. SkPath slice_path; double time = indeterminate_bar_animation_->GetCurrentValue(); // The animation spec corresponds to the material design lite's parameter. // (cf. https://github.com/google/material-design-lite/) double bar1_left; double bar1_width; double bar2_left; double bar2_width; if (time < 0.50) { bar1_left = time / 2; bar1_width = time * 1.5; bar2_left = 0; bar2_width = 0; } else if (time < 0.75) { bar1_left = time * 3 - 1.25; bar1_width = 0.75 - (time - 0.5) * 3; bar2_left = 0; bar2_width = time - 0.5; } else { bar1_left = 1; bar1_width = 0; bar2_left = (time - 0.75) * 4; bar2_width = 0.25 - (time - 0.75); } int bar1_start_x = std::round(content_bounds.width() * bar1_left); int bar1_end_x = std::round(content_bounds.width() * std::min(1.0, bar1_left + bar1_width)); int bar2_start_x = std::round(content_bounds.width() * bar2_left); int bar2_end_x = std::round(content_bounds.width() * std::min(1.0, bar2_left + bar2_width)); gfx::Rect slice_bounds = content_bounds; slice_bounds.set_x(content_bounds.x() + bar1_start_x); slice_bounds.set_width(bar1_end_x - bar1_start_x); AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path); slice_bounds.set_x(content_bounds.x() + bar2_start_x); slice_bounds.set_width(bar2_end_x - bar2_start_x); AddPossiblyRoundRectToPath(slice_bounds, allow_round_corner_, &slice_path); cc::PaintFlags slice_flags; slice_flags.setStyle(cc::PaintFlags::kFill_Style); slice_flags.setAntiAlias(true); slice_flags.setColor(GetForegroundColor()); canvas->DrawPath(slice_path, slice_flags); } void ProgressBar::MaybeNotifyAccessibilityValueChanged() { if (!GetWidget() || !GetWidget()->IsVisible() || RoundToPercent(current_value_) == last_announced_percentage_) { return; } last_announced_percentage_ = RoundToPercent(current_value_); NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true); } BEGIN_METADATA(ProgressBar, View) ADD_PROPERTY_METADATA(SkColor, ForegroundColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, ForegroundColorId); ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, BackgroundColorId); ADD_PROPERTY_METADATA(bool, Paused) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/progress_bar.cc
C++
unknown
10,350
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_PROGRESS_BAR_H_ #define UI_VIEWS_CONTROLS_PROGRESS_BAR_H_ #include <memory> #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/color/color_id.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/views/view.h" namespace gfx { class LinearAnimation; } namespace views { // Progress bar is a control that indicates progress visually. class VIEWS_EXPORT ProgressBar : public View, public gfx::AnimationDelegate { public: METADATA_HEADER(ProgressBar); // The preferred height parameter makes it easier to use a ProgressBar with // layout managers that size to preferred size. explicit ProgressBar(int preferred_height = 5, bool allow_round_corner = true); ProgressBar(const ProgressBar&) = delete; ProgressBar& operator=(const ProgressBar&) = delete; ~ProgressBar() override; // View: void GetAccessibleNodeData(ui::AXNodeData* node_data) override; gfx::Size CalculatePreferredSize() const override; void VisibilityChanged(View* starting_from, bool is_visible) override; void AddedToWidget() override; void OnPaint(gfx::Canvas* canvas) override; double GetValue() const; // Sets the current value. Values outside of the display range of 0.0-1.0 will // be displayed with an infinite loading animation. void SetValue(double value); // Sets whether the progress bar is paused. void SetPaused(bool is_paused); // The color of the progress portion. SkColor GetForegroundColor() const; void SetForegroundColor(SkColor color); absl::optional<ui::ColorId> GetForegroundColorId() const; void SetForegroundColorId(absl::optional<ui::ColorId> color_id); // The color of the portion that displays potential progress. SkColor GetBackgroundColor() const; void SetBackgroundColor(SkColor color); absl::optional<ui::ColorId> GetBackgroundColorId() const; void SetBackgroundColorId(absl::optional<ui::ColorId> color_id); protected: int preferred_height() const { return preferred_height_; } private: // gfx::AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; bool IsIndeterminate(); bool GetPaused() const { return is_paused_; } void OnPaintIndeterminate(gfx::Canvas* canvas); // Fire an accessibility event if visible and the progress has changed. void MaybeNotifyAccessibilityValueChanged(); // Current progress to display, should be in the range 0.0 to 1.0. double current_value_ = 0.0; // Is the progress bar paused. bool is_paused_ = false; // In DP, the preferred height of this progress bar. const int preferred_height_; const bool allow_round_corner_; absl::optional<SkColor> foreground_color_; absl::optional<ui::ColorId> foreground_color_id_; absl::optional<SkColor> background_color_; absl::optional<ui::ColorId> background_color_id_; std::unique_ptr<gfx::LinearAnimation> indeterminate_bar_animation_; int last_announced_percentage_ = -1; }; } // namespace views #endif // UI_VIEWS_CONTROLS_PROGRESS_BAR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/progress_bar.h
C++
unknown
3,253
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/progress_bar.h" #include <string> #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/color/color_id.h" #include "ui/events/test/event_generator.h" #include "ui/gfx/color_utils.h" #include "ui/native_theme/native_theme.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget_utils.h" namespace views { class ProgressBarTest : public ViewsTestBase { protected: // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateTestWidget(); bar_ = widget_->SetContentsView(std::make_unique<ProgressBar>()); widget_->Show(); event_generator_ = std::make_unique<ui::test::EventGenerator>( GetRootWindow(widget_.get())); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } raw_ptr<ProgressBar> bar_; std::unique_ptr<Widget> widget_; std::unique_ptr<ui::test::EventGenerator> event_generator_; }; TEST_F(ProgressBarTest, AccessibleNodeData) { bar_->SetValue(0.626); ui::AXNodeData node_data; bar_->GetAccessibleNodeData(&node_data); EXPECT_EQ(ax::mojom::Role::kProgressIndicator, node_data.role); EXPECT_EQ(std::u16string(), node_data.GetString16Attribute(ax::mojom::StringAttribute::kName)); EXPECT_EQ(std::string("62%"), node_data.GetStringAttribute(ax::mojom::StringAttribute::kValue)); EXPECT_FALSE( node_data.HasIntAttribute(ax::mojom::IntAttribute::kRestriction)); } // Verifies the correct a11y events are raised for an accessible progress bar. TEST_F(ProgressBarTest, AccessibilityEvents) { test::AXEventCounter ax_counter(views::AXEventManager::Get()); EXPECT_EQ(0, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); bar_->SetValue(0.50); EXPECT_EQ(1, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); bar_->SetValue(0.63); EXPECT_EQ(2, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); bar_->SetValue(0.636); EXPECT_EQ(2, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); bar_->SetValue(0.642); EXPECT_EQ(3, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); widget_->Hide(); widget_->Show(); EXPECT_EQ(3, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); widget_->Hide(); bar_->SetValue(0.8); EXPECT_EQ(3, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); widget_->Show(); EXPECT_EQ(4, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); } // Test that default colors can be overridden. Used by Chromecast. TEST_F(ProgressBarTest, OverrideDefaultColors) { EXPECT_NE(SK_ColorRED, bar_->GetForegroundColor()); EXPECT_NE(SK_ColorGREEN, bar_->GetBackgroundColor()); EXPECT_NE(bar_->GetForegroundColor(), bar_->GetBackgroundColor()); bar_->SetForegroundColor(SK_ColorRED); bar_->SetBackgroundColor(SK_ColorGREEN); EXPECT_EQ(SK_ColorRED, bar_->GetForegroundColor()); EXPECT_EQ(SK_ColorGREEN, bar_->GetBackgroundColor()); // Override colors with color ID. It will also override the colors set with // SkColor. bar_->SetForegroundColorId(ui::kColorSysPrimary); bar_->SetBackgroundColorId(ui::kColorSysPrimaryContainer); const auto* color_provider = bar_->GetColorProvider(); EXPECT_EQ(color_provider->GetColor(ui::kColorSysPrimary), bar_->GetForegroundColor()); EXPECT_EQ(color_provider->GetColor(ui::kColorSysPrimaryContainer), bar_->GetBackgroundColor()); EXPECT_EQ(ui::kColorSysPrimary, bar_->GetForegroundColorId().value()); EXPECT_EQ(ui::kColorSysPrimaryContainer, bar_->GetBackgroundColorId().value()); // Override the colors set with color ID by SkColor. bar_->SetForegroundColor(SK_ColorRED); bar_->SetBackgroundColor(SK_ColorGREEN); EXPECT_EQ(SK_ColorRED, bar_->GetForegroundColor()); EXPECT_EQ(SK_ColorGREEN, bar_->GetBackgroundColor()); EXPECT_EQ(absl::nullopt, bar_->GetForegroundColorId()); EXPECT_EQ(absl::nullopt, bar_->GetBackgroundColorId()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/progress_bar_unittest.cc
C++
unknown
4,313
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/progress_ring_utils.h" #include <utility> #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/skia_conversions.h" namespace views { namespace { void DrawRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkPath path) { // Draw the background ring. SkPath background_path; background_path.addArc(bounds, /*startAngle=*/-90, /*SweepAngle=*/360); cc::PaintFlags background_flags; background_flags.setStyle(cc::PaintFlags::Style::kStroke_Style); background_flags.setAntiAlias(true); background_flags.setColor(background_color); background_flags.setStrokeWidth(stroke_width); canvas->DrawPath(std::move(background_path), std::move(background_flags)); // Draw the filled portion of the ring. cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::Style::kStroke_Style); flags.setAntiAlias(true); flags.setColor(progress_color); flags.setStrokeWidth(stroke_width); canvas->DrawPath(std::move(path), std::move(flags)); } } // namespace void DrawProgressRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle, SkScalar sweep_angle) { SkPath path; path.addArc(bounds, start_angle, sweep_angle); DrawRing(canvas, bounds, background_color, progress_color, stroke_width, std::move(path)); } void DrawSpinningRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle) { SkPath path; path.addArc(bounds, start_angle, 60); path.addArc(bounds, start_angle + 120, 60); path.addArc(bounds, start_angle + 240, 60); DrawRing(canvas, bounds, background_color, progress_color, stroke_width, std::move(path)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/progress_ring_utils.cc
C++
unknown
2,331
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_PROGRESS_RING_UTILS_H_ #define UI_VIEWS_CONTROLS_PROGRESS_RING_UTILS_H_ #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { // Helper function that draws a progress ring on `canvas`. The progress ring // consists a background full ring and a partial ring that indicates the // progress. `start_angle` and `sweep_angle` are used to indicate the current // progress of the ring. VIEWS_EXPORT void DrawProgressRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle, SkScalar sweep_angle); // Helper function that draws a spinning ring on `canvas`. The spinning ring // consists a background full ring and three arches distributed evenly on the // ring. `start_angle` is used to indicate the start angle of the first arch. VIEWS_EXPORT void DrawSpinningRing(gfx::Canvas* canvas, const SkRect& bounds, SkColor background_color, SkColor progress_color, float stroke_width, SkScalar start_angle); } // namespace views #endif // UI_VIEWS_CONTROLS_PROGRESS_RING_UTILS_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/progress_ring_utils.h
C++
unknown
1,637
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/resize_area.h" #include "base/i18n/rtl.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/controls/resize_area_delegate.h" namespace views { ResizeArea::ResizeArea(ResizeAreaDelegate* delegate) : delegate_(delegate) { SetAccessibilityProperties(ax::mojom::Role::kSplitter); } ResizeArea::~ResizeArea() = default; ui::Cursor ResizeArea::GetCursor(const ui::MouseEvent& event) { return GetEnabled() ? ui::Cursor(ui::mojom::CursorType::kEastWestResize) : ui::Cursor(); } void ResizeArea::OnGestureEvent(ui::GestureEvent* event) { if (event->type() == ui::ET_GESTURE_TAP_DOWN) { SetInitialPosition(event->x()); event->SetHandled(); } else if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN || event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { ReportResizeAmount(event->x(), false); event->SetHandled(); } else if (event->type() == ui::ET_GESTURE_END) { ReportResizeAmount(event->x(), true); event->SetHandled(); } } bool ResizeArea::OnMousePressed(const ui::MouseEvent& event) { if (!event.IsOnlyLeftMouseButton()) return false; SetInitialPosition(event.x()); return true; } bool ResizeArea::OnMouseDragged(const ui::MouseEvent& event) { if (!event.IsLeftMouseButton()) return false; ReportResizeAmount(event.x(), false); return true; } void ResizeArea::OnMouseReleased(const ui::MouseEvent& event) { ReportResizeAmount(event.x(), true); } void ResizeArea::OnMouseCaptureLost() { ReportResizeAmount(initial_position_, true); } void ResizeArea::ReportResizeAmount(int resize_amount, bool last_update) { gfx::Point point(resize_amount, 0); View::ConvertPointToScreen(this, &point); resize_amount = point.x() - initial_position_; delegate_->OnResize(base::i18n::IsRTL() ? -resize_amount : resize_amount, last_update); } void ResizeArea::SetInitialPosition(int event_x) { gfx::Point point(event_x, 0); View::ConvertPointToScreen(this, &point); initial_position_ = point.x(); } BEGIN_METADATA(ResizeArea, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/resize_area.cc
C++
unknown
2,355
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_RESIZE_AREA_H_ #define UI_VIEWS_CONTROLS_RESIZE_AREA_H_ #include "base/memory/raw_ptr.h" #include "ui/views/view.h" namespace views { class ResizeAreaDelegate; // An invisible area that acts like a horizontal resizer. class VIEWS_EXPORT ResizeArea : public View { public: METADATA_HEADER(ResizeArea); explicit ResizeArea(ResizeAreaDelegate* delegate); ResizeArea(const ResizeArea&) = delete; ResizeArea& operator=(const ResizeArea&) = delete; ~ResizeArea() override; // views::View: ui::Cursor GetCursor(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; private: // Report the amount the user resized by to the delegate, accounting for // directionality. void ReportResizeAmount(int resize_amount, bool last_update); // Converts |event_x| to screen coordinates and sets |initial_position_| to // this value. void SetInitialPosition(int event_x); // The delegate to notify when we have updates. raw_ptr<ResizeAreaDelegate> delegate_; // The event's x-position at the start of the resize operation. The resize // area will move while being dragged, so |initial_position_| is represented // in screen coordinates so that we don't lose our bearings. int initial_position_ = 0; }; } // namespace views #endif // UI_VIEWS_CONTROLS_RESIZE_AREA_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/resize_area.h
C++
unknown
1,734
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_ #define UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_ namespace views { // An interface implemented by objects that want to be notified about the resize // event. class ResizeAreaDelegate { public: // OnResize is sent when resizing is detected. |resize_amount| specifies the // number of pixels that the user wants to resize by, and can be negative or // positive (depending on direction of dragging and flips according to // locale directionality: dragging to the left in LTR locales gives negative // |resize_amount| but positive amount for RTL). |done_resizing| is true if // the user has released the pointer (mouse, stylus, touch, etc.). virtual void OnResize(int resize_amount, bool done_resizing) = 0; protected: virtual ~ResizeAreaDelegate() = default; }; } // namespace views #endif // UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/resize_area_delegate.h
C++
unknown
1,052
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/resize_area.h" #include <memory> #include <utility> #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/resize_area_delegate.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_utils.h" #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #endif namespace { // Constants used by the ResizeAreaTest.SuccessfulGestureDrag test to simulate // a gesture drag by |kGestureScrollDistance| resulting from // |kGestureScrollSteps| ui::ET_GESTURE_SCROLL_UPDATE events being delivered. const int kGestureScrollDistance = 100; const int kGestureScrollSteps = 4; const int kDistancePerGestureScrollUpdate = kGestureScrollDistance / kGestureScrollSteps; } // namespace namespace views { // Testing delegate used by ResizeAreaTest. class TestResizeAreaDelegate : public ResizeAreaDelegate { public: TestResizeAreaDelegate(); TestResizeAreaDelegate(const TestResizeAreaDelegate&) = delete; TestResizeAreaDelegate& operator=(const TestResizeAreaDelegate&) = delete; ~TestResizeAreaDelegate() override; // ResizeAreaDelegate: void OnResize(int resize_amount, bool done_resizing) override; int resize_amount() { return resize_amount_; } bool done_resizing() { return done_resizing_; } bool on_resize_called() { return on_resize_called_; } private: int resize_amount_ = 0; bool done_resizing_ = false; bool on_resize_called_ = false; }; TestResizeAreaDelegate::TestResizeAreaDelegate() = default; TestResizeAreaDelegate::~TestResizeAreaDelegate() = default; void TestResizeAreaDelegate::OnResize(int resize_amount, bool done_resizing) { resize_amount_ = resize_amount; done_resizing_ = done_resizing; on_resize_called_ = true; } // Test fixture for testing the ResizeArea class. class ResizeAreaTest : public ViewsTestBase { public: ResizeAreaTest(); ResizeAreaTest(const ResizeAreaTest&) = delete; ResizeAreaTest& operator=(const ResizeAreaTest&) = delete; ~ResizeAreaTest() override; // Callback used by the SuccessfulGestureDrag test. void ProcessGesture(ui::EventType type, const gfx::Vector2dF& delta); protected: // testing::Test: void SetUp() override; void TearDown() override; ui::test::EventGenerator* event_generator() { return event_generator_.get(); } int resize_amount() { return delegate_->resize_amount(); } bool done_resizing() { return delegate_->done_resizing(); } bool on_resize_called() { return delegate_->on_resize_called(); } views::Widget* widget() { return widget_; } private: std::unique_ptr<TestResizeAreaDelegate> delegate_; raw_ptr<views::Widget> widget_ = nullptr; std::unique_ptr<ui::test::EventGenerator> event_generator_; // The number of ui::ET_GESTURE_SCROLL_UPDATE events seen by // ProcessGesture(). int gesture_scroll_updates_seen_ = 0; }; ResizeAreaTest::ResizeAreaTest() = default; ResizeAreaTest::~ResizeAreaTest() = default; void ResizeAreaTest::ProcessGesture(ui::EventType type, const gfx::Vector2dF& delta) { if (type == ui::ET_GESTURE_SCROLL_BEGIN) { EXPECT_FALSE(done_resizing()); EXPECT_FALSE(on_resize_called()); } else if (type == ui::ET_GESTURE_SCROLL_UPDATE) { gesture_scroll_updates_seen_++; EXPECT_EQ(kDistancePerGestureScrollUpdate * gesture_scroll_updates_seen_, resize_amount()); EXPECT_FALSE(done_resizing()); EXPECT_TRUE(on_resize_called()); } else if (type == ui::ET_GESTURE_SCROLL_END) { EXPECT_TRUE(done_resizing()); } } void ResizeAreaTest::SetUp() { views::ViewsTestBase::SetUp(); delegate_ = std::make_unique<TestResizeAreaDelegate>(); auto resize_area = std::make_unique<ResizeArea>(delegate_.get()); gfx::Size size(10, 10); resize_area->SetBounds(0, 0, size.width(), size.height()); views::Widget::InitParams init_params( CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)); init_params.bounds = gfx::Rect(size); widget_ = new views::Widget(); widget_->Init(std::move(init_params)); widget_->SetContentsView(std::move(resize_area)); widget_->Show(); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_)); } void ResizeAreaTest::TearDown() { if (widget_ && !widget_->IsClosed()) widget_->Close(); views::ViewsTestBase::TearDown(); } // TODO(tdanderson): Enable these tests on OSX. See crbug.com/710475. #if !BUILDFLAG(IS_MAC) // Verifies the correct calls have been made to // TestResizeAreaDelegate::OnResize() for a sequence of mouse events // corresponding to a successful resize operation. TEST_F(ResizeAreaTest, SuccessfulMouseDrag) { event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); event_generator()->PressLeftButton(); const int kFirstDragAmount = -5; event_generator()->MoveMouseBy(kFirstDragAmount, 0); EXPECT_EQ(kFirstDragAmount, resize_amount()); EXPECT_FALSE(done_resizing()); EXPECT_TRUE(on_resize_called()); const int kSecondDragAmount = 17; event_generator()->MoveMouseBy(kSecondDragAmount, 0); EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); EXPECT_FALSE(done_resizing()); event_generator()->ReleaseLeftButton(); EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); EXPECT_TRUE(done_resizing()); } // Verifies that no resize is performed when attempting to resize using the // right mouse button. TEST_F(ResizeAreaTest, FailedMouseDrag) { event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); event_generator()->PressRightButton(); const int kDragAmount = 18; event_generator()->MoveMouseBy(kDragAmount, 0); EXPECT_EQ(0, resize_amount()); } // Verifies the correct calls have been made to // TestResizeAreaDelegate::OnResize() for a sequence of gesture events // corresponding to a successful resize operation. TEST_F(ResizeAreaTest, SuccessfulGestureDrag) { gfx::Point start = widget()->GetNativeView()->bounds().CenterPoint(); event_generator()->GestureScrollSequenceWithCallback( start, gfx::Point(start.x() + kGestureScrollDistance, start.y()), base::Milliseconds(200), kGestureScrollSteps, base::BindRepeating(&ResizeAreaTest::ProcessGesture, base::Unretained(this))); } // Verifies that no resize is performed on a gesture tap. TEST_F(ResizeAreaTest, NoDragOnGestureTap) { event_generator()->GestureTapAt( widget()->GetNativeView()->bounds().CenterPoint()); EXPECT_EQ(0, resize_amount()); } TEST_F(ResizeAreaTest, AccessibleRole) { auto* resize_area = widget()->GetContentsView(); ui::AXNodeData data; resize_area->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kSplitter); EXPECT_EQ(resize_area->GetAccessibleRole(), ax::mojom::Role::kSplitter); data = ui::AXNodeData(); resize_area->SetAccessibleRole(ax::mojom::Role::kButton); resize_area->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kButton); EXPECT_EQ(resize_area->GetAccessibleRole(), ax::mojom::Role::kButton); } #endif // !BUILDFLAG(IS_MAC) } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/resize_area_unittest.cc
C++
unknown
7,443
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scroll_view.h" #include <algorithm> #include "base/check_op.h" #include "base/feature_list.h" #include "base/functional/bind.h" #include "base/i18n/rtl.h" #include "base/memory/raw_ptr.h" #include "base/ranges/algorithm.h" #include "build/build_config.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/ui_base_features.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_type.h" #include "ui/compositor/overscroll/scroll_input_handler.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/style/platform_style.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace views { namespace { // Returns the combined scroll amount given separate x and y offsets. This is // used in the "treat all scroll events as horizontal" case when there is both // an x and y offset and we do not want them to add in unintuitive ways. // // The current approach is to return whichever offset has the larger absolute // value, which should at least handle the case in which the gesture is mostly // vertical or horizontal. It does mean that for a gesture at 135° or 315° from // the x axis there is a breakpoint where scroll direction reverses, but we do // not typically expect users to try to scroll a horizontal-scroll-only view at // this exact angle. template <class T> T CombineScrollOffsets(T x, T y) { return std::abs(x) >= std::abs(y) ? x : y; } class ScrollCornerView : public View { public: METADATA_HEADER(ScrollCornerView); ScrollCornerView() = default; ScrollCornerView(const ScrollCornerView&) = delete; ScrollCornerView& operator=(const ScrollCornerView&) = delete; void OnPaint(gfx::Canvas* canvas) override { ui::NativeTheme::ExtraParams ignored; GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), ui::NativeTheme::kScrollbarCorner, ui::NativeTheme::kNormal, GetLocalBounds(), ignored); } }; BEGIN_METADATA(ScrollCornerView, View) END_METADATA // Returns true if any descendants of |view| have a layer (not including // |view|). bool DoesDescendantHaveLayer(View* view) { return base::ranges::any_of(view->children(), [](View* child) { return child->layer() || DoesDescendantHaveLayer(child); }); } // Returns the position for the view so that it isn't scrolled off the visible // region. int CheckScrollBounds(int viewport_size, int content_size, int current_pos) { return std::clamp(current_pos, 0, std::max(content_size - viewport_size, 0)); } // Make sure the content is not scrolled out of bounds void ConstrainScrollToBounds(View* viewport, View* view, bool scroll_with_layers_enabled) { if (!view) return; // Note that even when ScrollView::ScrollsWithLayers() is true, the header row // scrolls by repainting. const bool scrolls_with_layers = scroll_with_layers_enabled && viewport->layer() != nullptr; if (scrolls_with_layers) { DCHECK(view->layer()); DCHECK_EQ(0, view->x()); DCHECK_EQ(0, view->y()); } gfx::PointF offset = scrolls_with_layers ? view->layer()->CurrentScrollOffset() : gfx::PointF(-view->x(), -view->y()); int x = CheckScrollBounds(viewport->width(), view->width(), offset.x()); int y = CheckScrollBounds(viewport->height(), view->height(), offset.y()); if (scrolls_with_layers) { view->layer()->SetScrollOffset(gfx::PointF(x, y)); } else { // This is no op if bounds are the same view->SetBounds(-x, -y, view->width(), view->height()); } } // Used by ScrollToPosition() to make sure the new position fits within the // allowed scroll range. int AdjustPosition(int current_position, int new_position, int content_size, int viewport_size) { if (-current_position == new_position) return new_position; if (new_position < 0) return 0; const int max_position = std::max(0, content_size - viewport_size); return (new_position > max_position) ? max_position : new_position; } } // namespace // Viewport contains the contents View of the ScrollView. class ScrollView::Viewport : public View { public: METADATA_HEADER(Viewport); explicit Viewport(ScrollView* scroll_view) : scroll_view_(scroll_view) {} Viewport(const Viewport&) = delete; Viewport& operator=(const Viewport&) = delete; ~Viewport() override = default; void ScrollRectToVisible(const gfx::Rect& rect) override { if (children().empty() || !parent()) return; View* contents = children().front(); gfx::Rect scroll_rect(rect); if (scroll_view_->ScrollsWithLayers()) { // With layer scrolling, there's no need to "undo" the offset done in the // child's View::ScrollRectToVisible() before it calls this. DCHECK_EQ(0, contents->x()); DCHECK_EQ(0, contents->y()); } else { scroll_rect.Offset(-contents->x(), -contents->y()); } scroll_view_->ScrollContentsRegionToBeVisible(scroll_rect); } void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { if (details.is_add && GetIsContentsViewport() && Contains(details.parent)) { scroll_view_->UpdateViewportLayerForClipping(); UpdateContentsViewportLayer(); } } void OnChildLayerChanged(View* child) override { // If scroll_with_layers is enabled, explicitly disallowing to change the // layer on contents after the contents of ScrollView are set. DCHECK(!scroll_view_->scroll_with_layers_enabled_ || child != scroll_view_->contents_) << "Layer of contents cannot be changed manually after the contents " "are set when scroll_with_layers is enabled."; if (GetIsContentsViewport()) { scroll_view_->UpdateViewportLayerForClipping(); UpdateContentsViewportLayer(); } } void InitializeContentsViewportLayer() { const ui::LayerType layer_type = CalculateLayerTypeForContentsViewport(); SetContentsViewportLayer(layer_type); } private: void UpdateContentsViewportLayer() { if (!layer()) return; const ui::LayerType new_layer_type = CalculateLayerTypeForContentsViewport(); bool layer_needs_update = layer()->type() != new_layer_type; if (layer_needs_update) SetContentsViewportLayer(new_layer_type); } // Calculates the layer type to use for |contents_viewport_|. ui::LayerType CalculateLayerTypeForContentsViewport() const { // Since contents_viewport_ is transparent, layer of contents_viewport_ // can be NOT_DRAWN if contents_ have a TEXTURED layer. // When scroll_with_layers is enabled, we can always determine the layer // type of contents_viewport based on the type of layer that will be enabled // on contents. if (scroll_view_->scroll_with_layers_enabled_) { return scroll_view_->layer_type_ == ui::LAYER_TEXTURED ? ui::LAYER_NOT_DRAWN : ui::LAYER_TEXTURED; } // Getting contents of viewport through view hierarchy tree rather than // scroll_view->contents_, as this method can be called after the view // hierarchy is changed but before contents_ variable is updated. Hence // scroll_view->contents_ will have stale value in such situation. const View* contents = !this->children().empty() ? this->children()[0] : nullptr; auto has_textured_layer{[](const View* contents) { return contents->layer() && contents->layer()->type() == ui::LAYER_TEXTURED; }}; if (!contents || has_textured_layer(contents)) return ui::LAYER_NOT_DRAWN; else return ui::LAYER_TEXTURED; } // Initializes or updates the layer of |contents_viewport|. void SetContentsViewportLayer(ui::LayerType layer_type) { // Only LAYER_NOT_DRAWN and LAYER_TEXTURED are allowed since // contents_viewport is a container view. DCHECK(layer_type == ui::LAYER_TEXTURED || layer_type == ui::LAYER_NOT_DRAWN); SetPaintToLayer(layer_type); } bool GetIsContentsViewport() const { return parent() && scroll_view_->contents_viewport_ == this; } raw_ptr<ScrollView> scroll_view_; }; BEGIN_METADATA(ScrollView, Viewport, View) ADD_READONLY_PROPERTY_METADATA(bool, IsContentsViewport) END_METADATA ScrollView::ScrollView() : ScrollView(base::FeatureList::IsEnabled( ::features::kUiCompositorScrollWithLayers) ? ScrollWithLayers::kEnabled : ScrollWithLayers::kDisabled) {} ScrollView::ScrollView(ScrollWithLayers scroll_with_layers) : horiz_sb_(AddChildView(PlatformStyle::CreateScrollBar(true))), vert_sb_(AddChildView(PlatformStyle::CreateScrollBar(false))), corner_view_(std::make_unique<ScrollCornerView>()), scroll_with_layers_enabled_(scroll_with_layers == ScrollWithLayers::kEnabled) { SetNotifyEnterExitOnChild(true); // Since |contents_viewport_| is accessed during the AddChildView call, make // sure the field is initialized. auto contents_viewport = std::make_unique<Viewport>(this); contents_viewport_ = contents_viewport.get(); // Add content view port as the first child, so that the scollbars can // overlay it. AddChildViewAt(std::move(contents_viewport), 0); header_viewport_ = AddChildView(std::make_unique<Viewport>(this)); horiz_sb_->SetVisible(false); horiz_sb_->set_controller(this); vert_sb_->SetVisible(false); vert_sb_->set_controller(this); corner_view_->SetVisible(false); // "Ignored" removes the scrollbar from the accessibility tree. // "IsLeaf" removes their children (e.g. the buttons and thumb). horiz_sb_->GetViewAccessibility().OverrideIsIgnored(true); horiz_sb_->GetViewAccessibility().OverrideIsLeaf(true); vert_sb_->GetViewAccessibility().OverrideIsIgnored(true); vert_sb_->GetViewAccessibility().OverrideIsLeaf(true); // Just make sure the more_content indicators aren't visible for now. They'll // be added as child controls and appropriately made visible depending on // |show_edges_with_hidden_content_|. more_content_left_->SetVisible(false); more_content_top_->SetVisible(false); more_content_right_->SetVisible(false); more_content_bottom_->SetVisible(false); if (scroll_with_layers_enabled_) EnableViewportLayer(); // If we're scrolling with layers, paint the overflow indicators to the layer. if (ScrollsWithLayers()) { more_content_left_->SetPaintToLayer(); more_content_top_->SetPaintToLayer(); more_content_right_->SetPaintToLayer(); more_content_bottom_->SetPaintToLayer(); } FocusRing::Install(this); views::FocusRing::Get(this)->SetHasFocusPredicate([](View* view) -> bool { auto* v = static_cast<ScrollView*>(view); return v->draw_focus_indicator_; }); } ScrollView::~ScrollView() = default; // static std::unique_ptr<ScrollView> ScrollView::CreateScrollViewWithBorder() { auto scroll_view = std::make_unique<ScrollView>(); scroll_view->AddBorder(); return scroll_view; } // static ScrollView* ScrollView::GetScrollViewForContents(View* contents) { View* grandparent = contents->parent() ? contents->parent()->parent() : nullptr; if (!grandparent || grandparent->GetClassName() != ScrollView::kViewClassName) return nullptr; auto* scroll_view = static_cast<ScrollView*>(grandparent); DCHECK_EQ(contents, scroll_view->contents()); return scroll_view; } void ScrollView::SetContentsImpl(std::unique_ptr<View> a_view) { // Protect against clients passing a contents view that has its own Layer. DCHECK(!a_view || !a_view->layer()); if (a_view && ScrollsWithLayers()) { a_view->SetPaintToLayer(layer_type_); a_view->layer()->SetDidScrollCallback(base::BindRepeating( &ScrollView::OnLayerScrolled, base::Unretained(this))); a_view->layer()->SetScrollable(contents_viewport_->bounds().size()); } SetHeaderOrContents(contents_viewport_, std::move(a_view), &contents_); UpdateBackground(); } void ScrollView::SetContents(std::nullptr_t) { SetContentsImpl(nullptr); } void ScrollView::SetContentsLayerType(ui::LayerType layer_type) { // This function should only be called when scroll with layers is enabled and // before `contents_` is set. DCHECK(ScrollsWithLayers() && !contents_); // Currently only allow LAYER_TEXTURED and LAYER_NOT_DRAWN. If other types of // layer are needed, consult with the owner. DCHECK(layer_type == ui::LAYER_TEXTURED || layer_type == ui::LAYER_NOT_DRAWN); if (layer_type_ == layer_type) return; layer_type_ = layer_type; } void ScrollView::SetHeaderImpl(std::unique_ptr<View> a_header) { SetHeaderOrContents(header_viewport_, std::move(a_header), &header_); } void ScrollView::SetHeader(std::nullptr_t) { SetHeaderImpl(nullptr); } void ScrollView::SetPreferredViewportMargins(const gfx::Insets& margins) { preferred_viewport_margins_ = margins; } void ScrollView::SetViewportRoundedCornerRadius( const gfx::RoundedCornersF& radii) { DCHECK(contents_viewport_->layer()) << "Please ensure you have enabled ScrollWithLayers."; contents_viewport_->layer()->SetRoundedCornerRadius(radii); } void ScrollView::SetBackgroundColor(const absl::optional<SkColor>& color) { if (background_color_ == color && !background_color_id_) return; background_color_ = color; background_color_id_ = absl::nullopt; UpdateBackground(); OnPropertyChanged(&background_color_, kPropertyEffectsPaint); } void ScrollView::SetBackgroundThemeColorId( const absl::optional<ui::ColorId>& color_id) { if (background_color_id_ == color_id && !background_color_) return; background_color_id_ = color_id; background_color_ = absl::nullopt; UpdateBackground(); OnPropertyChanged(&background_color_id_, kPropertyEffectsPaint); } gfx::Rect ScrollView::GetVisibleRect() const { if (!contents_) return gfx::Rect(); gfx::PointF offset = CurrentOffset(); return gfx::Rect(offset.x(), offset.y(), contents_viewport_->width(), contents_viewport_->height()); } void ScrollView::SetHorizontalScrollBarMode( ScrollBarMode horizontal_scroll_bar_mode) { if (horizontal_scroll_bar_mode_ == horizontal_scroll_bar_mode) return; horizontal_scroll_bar_mode_ = horizontal_scroll_bar_mode; OnPropertyChanged(&horizontal_scroll_bar_mode_, kPropertyEffectsPaint); // "Ignored" removes the scrollbar from the accessibility tree. // "IsLeaf" removes their children (e.g. the buttons and thumb). bool is_disabled = horizontal_scroll_bar_mode == ScrollBarMode::kDisabled; horiz_sb_->GetViewAccessibility().OverrideIsIgnored(is_disabled); horiz_sb_->GetViewAccessibility().OverrideIsLeaf(is_disabled); } void ScrollView::SetVerticalScrollBarMode( ScrollBarMode vertical_scroll_bar_mode) { if (vertical_scroll_bar_mode_ == vertical_scroll_bar_mode) return; // Enabling vertical scrolling is incompatible with all scrolling being // interpreted as horizontal. DCHECK(!treat_all_scroll_events_as_horizontal_ || vertical_scroll_bar_mode == ScrollBarMode::kDisabled); vertical_scroll_bar_mode_ = vertical_scroll_bar_mode; OnPropertyChanged(&vertical_scroll_bar_mode_, kPropertyEffectsPaint); // "Ignored" removes the scrollbar from the accessibility tree. // "IsLeaf" removes their children (e.g. the buttons and thumb). bool is_disabled = vertical_scroll_bar_mode == ScrollBarMode::kDisabled; vert_sb_->GetViewAccessibility().OverrideIsIgnored(is_disabled); vert_sb_->GetViewAccessibility().OverrideIsLeaf(is_disabled); } void ScrollView::SetTreatAllScrollEventsAsHorizontal( bool treat_all_scroll_events_as_horizontal) { if (treat_all_scroll_events_as_horizontal_ == treat_all_scroll_events_as_horizontal) { return; } treat_all_scroll_events_as_horizontal_ = treat_all_scroll_events_as_horizontal; OnPropertyChanged(&treat_all_scroll_events_as_horizontal_, kPropertyEffectsNone); // Since this effectively disables vertical scrolling, don't show a // vertical scrollbar. SetVerticalScrollBarMode(ScrollBarMode::kDisabled); } void ScrollView::SetAllowKeyboardScrolling(bool allow_keyboard_scrolling) { if (allow_keyboard_scrolling_ == allow_keyboard_scrolling) return; allow_keyboard_scrolling_ = allow_keyboard_scrolling; OnPropertyChanged(&allow_keyboard_scrolling_, kPropertyEffectsNone); } void ScrollView::SetDrawOverflowIndicator(bool draw_overflow_indicator) { if (draw_overflow_indicator_ == draw_overflow_indicator) return; draw_overflow_indicator_ = draw_overflow_indicator; OnPropertyChanged(&draw_overflow_indicator_, kPropertyEffectsPaint); } View* ScrollView::SetCustomOverflowIndicator(OverflowIndicatorAlignment side, std::unique_ptr<View> indicator, int thickness, bool fills_opaquely) { if (thickness < 0) thickness = 0; if (ScrollsWithLayers()) { indicator->SetPaintToLayer(); indicator->layer()->SetFillsBoundsOpaquely(fills_opaquely); } View* indicator_ptr = indicator.get(); switch (side) { case OverflowIndicatorAlignment::kLeft: more_content_left_ = std::move(indicator); more_content_left_thickness_ = thickness; break; case OverflowIndicatorAlignment::kTop: more_content_top_ = std::move(indicator); more_content_top_thickness_ = thickness; break; case OverflowIndicatorAlignment::kRight: more_content_right_ = std::move(indicator); more_content_right_thickness_ = thickness; break; case OverflowIndicatorAlignment::kBottom: more_content_bottom_ = std::move(indicator); more_content_bottom_thickness_ = thickness; break; default: NOTREACHED_NORETURN(); } UpdateOverflowIndicatorVisibility(CurrentOffset()); PositionOverflowIndicators(); return indicator_ptr; } void ScrollView::ClipHeightTo(int min_height, int max_height) { if (min_height != min_height_ || max_height != max_height_) PreferredSizeChanged(); min_height_ = min_height; max_height_ = max_height; } int ScrollView::GetScrollBarLayoutWidth() const { return vert_sb_->OverlapsContent() ? 0 : vert_sb_->GetThickness(); } int ScrollView::GetScrollBarLayoutHeight() const { return horiz_sb_->OverlapsContent() ? 0 : horiz_sb_->GetThickness(); } ScrollBar* ScrollView::SetHorizontalScrollBar( std::unique_ptr<ScrollBar> horiz_sb) { horiz_sb->SetVisible(horiz_sb_->GetVisible()); horiz_sb->set_controller(this); RemoveChildViewT(horiz_sb_.get()); horiz_sb_ = AddChildView(std::move(horiz_sb)); return horiz_sb_; } ScrollBar* ScrollView::SetVerticalScrollBar( std::unique_ptr<ScrollBar> vert_sb) { DCHECK(vert_sb); vert_sb->SetVisible(vert_sb_->GetVisible()); vert_sb->set_controller(this); RemoveChildViewT(vert_sb_.get()); vert_sb_ = AddChildView(std::move(vert_sb)); return vert_sb_; } void ScrollView::SetHasFocusIndicator(bool has_focus_indicator) { if (has_focus_indicator == draw_focus_indicator_) return; draw_focus_indicator_ = has_focus_indicator; views::FocusRing::Get(this)->SchedulePaint(); SchedulePaint(); OnPropertyChanged(&draw_focus_indicator_, kPropertyEffectsPaint); } base::CallbackListSubscription ScrollView::AddContentsScrolledCallback( ScrollViewCallback callback) { return on_contents_scrolled_.Add(std::move(callback)); } base::CallbackListSubscription ScrollView::AddContentsScrollEndedCallback( ScrollViewCallback callback) { return on_contents_scroll_ended_.Add(std::move(callback)); } gfx::Size ScrollView::CalculatePreferredSize() const { gfx::Size size = contents_ ? contents_->GetPreferredSize() : gfx::Size(); if (is_bounded()) { size.SetToMax(gfx::Size(size.width(), min_height_)); size.SetToMin(gfx::Size(size.width(), max_height_)); } gfx::Insets insets = GetInsets(); size.Enlarge(insets.width(), insets.height()); return size; } int ScrollView::GetHeightForWidth(int width) const { if (!is_bounded()) return View::GetHeightForWidth(width); gfx::Insets insets = GetInsets(); width = std::max(0, width - insets.width()); int height = contents_ ? contents_->GetHeightForWidth(width) + insets.height() : insets.height(); return std::clamp(height, min_height_, max_height_); } void ScrollView::Layout() { // When either scrollbar is disabled, it should not matter // if its OverlapsContent matches other bar's. if (horizontal_scroll_bar_mode_ == ScrollBarMode::kEnabled && vertical_scroll_bar_mode_ == ScrollBarMode::kEnabled) { #if BUILDFLAG(IS_MAC) // On Mac, scrollbars may update their style one at a time, so they may // temporarily be of different types. Refuse to lay out at this point. if (horiz_sb_->OverlapsContent() != vert_sb_->OverlapsContent()) return; #endif DCHECK_EQ(horiz_sb_->OverlapsContent(), vert_sb_->OverlapsContent()); } if (views::FocusRing::Get(this)) views::FocusRing::Get(this)->Layout(); gfx::Rect available_rect = GetContentsBounds(); if (is_bounded()) { int content_width = available_rect.width(); int content_height = contents_->GetHeightForWidth(content_width); if (content_height > available_rect.height()) { content_width = std::max(content_width - GetScrollBarLayoutWidth(), 0); content_height = contents_->GetHeightForWidth(content_width); } contents_->SetSize(gfx::Size(content_width, content_height)); } // Place an overflow indicator on each of the four edges of the content // bounds. PositionOverflowIndicators(); // Most views will want to auto-fit the available space. Most of them want to // use all available width (without overflowing) and only overflow in // height. Examples are HistoryView, MostVisitedView, DownloadTabView, etc. // Other views want to fit in both ways. An example is PrintView. To make both // happy, assume a vertical scrollbar but no horizontal scrollbar. To override // this default behavior, the inner view has to calculate the available space, // used ComputeScrollBarsVisibility() to use the same calculation that is done // here and sets its bound to fit within. gfx::Rect viewport_bounds = available_rect; const int contents_x = viewport_bounds.x(); const int contents_y = viewport_bounds.y(); if (viewport_bounds.IsEmpty()) { // There's nothing to layout. return; } const int header_height = std::min(viewport_bounds.height(), header_ ? header_->GetPreferredSize().height() : 0); viewport_bounds.set_height( std::max(0, viewport_bounds.height() - header_height)); viewport_bounds.set_y(viewport_bounds.y() + header_height); // viewport_size is the total client space available. gfx::Size viewport_size = viewport_bounds.size(); // Assume both a vertical and horizontal scrollbar exist before calling // contents_->Layout(). This is because some contents_ will set their own size // to the contents_viewport_'s bounds. Failing to pre-allocate space for // the scrollbars will [non-intuitively] cause scrollbars to appear in // ComputeScrollBarsVisibility. This solution is also not perfect - if // scrollbars turn out *not* to be necessary, the contents will have slightly // less horizontal/vertical space than it otherwise would have had access to. // Unfortunately, there's no way to determine this without introducing a // circular dependency. const int horiz_sb_layout_height = GetScrollBarLayoutHeight(); const int vert_sb_layout_width = GetScrollBarLayoutWidth(); viewport_bounds.set_width(viewport_bounds.width() - vert_sb_layout_width); viewport_bounds.set_height(viewport_bounds.height() - horiz_sb_layout_height); // Update the bounds right now so the inner views can fit in it. contents_viewport_->SetBoundsRect(viewport_bounds); // Give |contents_| a chance to update its bounds if it depends on the // viewport. if (contents_) contents_->Layout(); bool should_layout_contents = false; bool horiz_sb_required = false; bool vert_sb_required = false; if (contents_) { gfx::Size content_size = contents_->size(); ComputeScrollBarsVisibility(viewport_size, content_size, &horiz_sb_required, &vert_sb_required); } // Overlay scrollbars don't need a corner view. bool corner_view_required = horiz_sb_required && vert_sb_required && !vert_sb_->OverlapsContent(); // Take action. horiz_sb_->SetVisible(horiz_sb_required); vert_sb_->SetVisible(vert_sb_required); SetControlVisibility(corner_view_.get(), corner_view_required); // Default. if (!horiz_sb_required) { viewport_bounds.set_height(viewport_bounds.height() + horiz_sb_layout_height); should_layout_contents = true; } // Default. if (!vert_sb_required) { viewport_bounds.set_width(viewport_bounds.width() + vert_sb_layout_width); should_layout_contents = true; } if (horiz_sb_required) { gfx::Rect horiz_sb_bounds(contents_x, viewport_bounds.bottom(), viewport_bounds.right() - contents_x, horiz_sb_layout_height); if (horiz_sb_->OverlapsContent()) { horiz_sb_bounds.Inset( gfx::Insets::TLBR(-horiz_sb_->GetThickness(), 0, 0, vert_sb_required ? vert_sb_->GetThickness() : 0)); } horiz_sb_->SetBoundsRect(horiz_sb_bounds); } if (vert_sb_required) { gfx::Rect vert_sb_bounds(viewport_bounds.right(), contents_y, vert_sb_layout_width, viewport_bounds.bottom() - contents_y); if (vert_sb_->OverlapsContent()) { // In the overlay scrollbar case, the scrollbar only covers the viewport // (and not the header). vert_sb_bounds.Inset(gfx::Insets::TLBR( header_height, -vert_sb_->GetThickness(), horiz_sb_required ? horiz_sb_->GetThickness() : 0, 0)); } vert_sb_->SetBoundsRect(vert_sb_bounds); } if (corner_view_required) { // Show the resize corner. corner_view_->SetBounds(vert_sb_->bounds().x(), horiz_sb_->bounds().y(), vert_sb_layout_width, horiz_sb_layout_height); } // Update to the real client size with the visible scrollbars. contents_viewport_->SetBoundsRect(viewport_bounds); if (should_layout_contents && contents_) contents_->Layout(); // Even when |contents_| needs to scroll, it can still be narrower or wider // the viewport. So ensure the scrolling layer can fill the viewport, so that // events will correctly hit it, and overscroll looks correct. if (contents_ && ScrollsWithLayers()) { gfx::Size container_size = contents_ ? contents_->size() : gfx::Size(); container_size.SetToMax(viewport_bounds.size()); contents_->SetBoundsRect(gfx::Rect(container_size)); contents_->layer()->SetScrollable(viewport_bounds.size()); // Flip the viewport with layer transforms under RTL. Note the net effect is // to flip twice, so the text is not mirrored. This is necessary because // compositor scrolling is not RTL-aware. So although a toolkit-views layout // will flip, increasing a horizontal scroll offset will move content to // the left, regardless of RTL. A scroll offset must be positive, so to // move (unscrolled) content to the right, we need to flip the viewport // layer. That would flip all the content as well, so flip (and translate) // the content layer. Compensating in this way allows the scrolling/offset // logic to remain the same when scrolling via layers or bounds offsets. if (base::i18n::IsRTL()) { gfx::Transform flip; flip.Translate(viewport_bounds.width(), 0); flip.Scale(-1, 1); contents_viewport_->layer()->SetTransform(flip); // Add `contents_->width() - viewport_width` to the translation step. This // is to prevent the top-left of the (flipped) contents aligning to the // top-left of the viewport. Instead, the top-right should align in RTL. gfx::Transform shift; shift.Translate(2 * contents_->width() - viewport_bounds.width(), 0); shift.Scale(-1, 1); contents_->layer()->SetTransform(shift); } } header_viewport_->SetBounds(contents_x, contents_y, viewport_bounds.width(), header_height); if (header_) header_->Layout(); ConstrainScrollToBounds(header_viewport_, header_, scroll_with_layers_enabled_); ConstrainScrollToBounds(contents_viewport_, contents_, scroll_with_layers_enabled_); SchedulePaint(); UpdateScrollBarPositions(); if (contents_) UpdateOverflowIndicatorVisibility(CurrentOffset()); } bool ScrollView::OnKeyPressed(const ui::KeyEvent& event) { bool processed = false; if (!allow_keyboard_scrolling_) return false; // Give vertical scrollbar priority if (IsVerticalScrollEnabled()) processed = vert_sb_->OnKeyPressed(event); if (!processed && IsHorizontalScrollEnabled()) processed = horiz_sb_->OnKeyPressed(event); return processed; } bool ScrollView::OnMouseWheel(const ui::MouseWheelEvent& e) { bool processed = false; const ui::MouseWheelEvent to_propagate = treat_all_scroll_events_as_horizontal_ ? ui::MouseWheelEvent( e, CombineScrollOffsets(e.x_offset(), e.y_offset()), 0) : e; // TODO(https://crbug.com/615948): Use composited scrolling. if (IsVerticalScrollEnabled()) processed = vert_sb_->OnMouseWheel(to_propagate); if (IsHorizontalScrollEnabled()) { // When there is no vertical scrollbar, allow vertical scroll events to be // interpreted as horizontal scroll events. processed |= horiz_sb_->OnMouseWheel(to_propagate); } return processed; } void ScrollView::OnScrollEvent(ui::ScrollEvent* event) { if (!contents_) return; // Possibly force the scroll event to horizontal based on the configuration // option. ui::ScrollEvent e = treat_all_scroll_events_as_horizontal_ ? ui::ScrollEvent( event->type(), event->location_f(), event->root_location_f(), event->time_stamp(), event->flags(), CombineScrollOffsets(event->x_offset(), event->y_offset()), 0.0f, CombineScrollOffsets(event->y_offset_ordinal(), event->x_offset_ordinal()), 0.0f, event->finger_count(), event->momentum_phase(), event->scroll_event_phase()) : *event; ui::ScrollInputHandler* compositor_scroller = GetWidget()->GetCompositor()->scroll_input_handler(); if (compositor_scroller) { DCHECK(scroll_with_layers_enabled_); if (compositor_scroller->OnScrollEvent(e, contents_->layer())) { e.SetHandled(); e.StopPropagation(); } } // A direction might not be known when the event stream starts, notify both // scrollbars that they may be about scroll, or that they may need to cancel // UI feedback once the scrolling direction is known. horiz_sb_->ObserveScrollEvent(e); vert_sb_->ObserveScrollEvent(e); // Need to copy state back to original event. if (e.handled()) event->SetHandled(); if (e.stopped_propagation()) event->StopPropagation(); } void ScrollView::OnGestureEvent(ui::GestureEvent* event) { // If the event happened on one of the scrollbars, then those events are // sent directly to the scrollbars. Otherwise, only scroll events are sent to // the scrollbars. bool scroll_event = event->type() == ui::ET_GESTURE_SCROLL_UPDATE || event->type() == ui::ET_GESTURE_SCROLL_BEGIN || event->type() == ui::ET_GESTURE_SCROLL_END || event->type() == ui::ET_SCROLL_FLING_START; // Note: we will not invert gesture events because it will be confusing to // have a vertical finger gesture on a touchscreen cause the scroll pane to // scroll horizontally. // TODO(https://crbug.com/615948): Use composited scrolling. if (IsVerticalScrollEnabled() && (scroll_event || (vert_sb_->GetVisible() && vert_sb_->bounds().Contains(event->location())))) { vert_sb_->OnGestureEvent(event); } if (!event->handled() && IsHorizontalScrollEnabled() && (scroll_event || (horiz_sb_->GetVisible() && horiz_sb_->bounds().Contains(event->location())))) { horiz_sb_->OnGestureEvent(event); } } void ScrollView::OnThemeChanged() { View::OnThemeChanged(); UpdateBorder(); UpdateBackground(); } void ScrollView::GetAccessibleNodeData(ui::AXNodeData* node_data) { View::GetAccessibleNodeData(node_data); if (!contents_) return; node_data->role = ax::mojom::Role::kScrollView; node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollX, CurrentOffset().x()); node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollXMin, horiz_sb_->GetMinPosition()); node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollXMax, horiz_sb_->GetMaxPosition()); node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollY, CurrentOffset().y()); node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollYMin, vert_sb_->GetMinPosition()); node_data->AddIntAttribute(ax::mojom::IntAttribute::kScrollYMax, vert_sb_->GetMaxPosition()); node_data->AddBoolAttribute(ax::mojom::BoolAttribute::kScrollable, true); } bool ScrollView::HandleAccessibleAction(const ui::AXActionData& action_data) { if (!contents_) return View::HandleAccessibleAction(action_data); switch (action_data.action) { case ax::mojom::Action::kScrollLeft: return horiz_sb_->ScrollByAmount(ScrollBar::ScrollAmount::kPrevPage); case ax::mojom::Action::kScrollRight: return horiz_sb_->ScrollByAmount(ScrollBar::ScrollAmount::kNextPage); case ax::mojom::Action::kScrollUp: return vert_sb_->ScrollByAmount(ScrollBar::ScrollAmount::kPrevPage); case ax::mojom::Action::kScrollDown: return vert_sb_->ScrollByAmount(ScrollBar::ScrollAmount::kNextPage); case ax::mojom::Action::kSetScrollOffset: ScrollToOffset(gfx::PointF(action_data.target_point)); return true; default: return View::HandleAccessibleAction(action_data); } } void ScrollView::ScrollToPosition(ScrollBar* source, int position) { if (!contents_) return; gfx::PointF offset = CurrentOffset(); if (source == horiz_sb_ && IsHorizontalScrollEnabled()) { position = AdjustPosition(offset.x(), position, contents_->width(), contents_viewport_->width()); if (offset.x() == position) return; offset.set_x(position); } else if (source == vert_sb_ && IsVerticalScrollEnabled()) { position = AdjustPosition(offset.y(), position, contents_->height(), contents_viewport_->height()); if (offset.y() == position) return; offset.set_y(position); } ScrollToOffset(offset); if (!ScrollsWithLayers()) contents_->SchedulePaintInRect(contents_->GetVisibleBounds()); } int ScrollView::GetScrollIncrement(ScrollBar* source, bool is_page, bool is_positive) { bool is_horizontal = source->IsHorizontal(); if (is_page) { return is_horizontal ? contents_viewport_->width() : contents_viewport_->height(); } return is_horizontal ? contents_viewport_->width() / 5 : contents_viewport_->height() / 5; } void ScrollView::OnScrollEnded() { on_contents_scroll_ended_.Notify(); } bool ScrollView::DoesViewportOrScrollViewHaveLayer() const { return layer() || contents_viewport_->layer(); } void ScrollView::UpdateViewportLayerForClipping() { if (scroll_with_layers_enabled_) return; const bool has_layer = DoesViewportOrScrollViewHaveLayer(); const bool needs_layer = DoesDescendantHaveLayer(contents_viewport_); if (has_layer == needs_layer) return; if (needs_layer) EnableViewportLayer(); else contents_viewport_->DestroyLayer(); } void ScrollView::SetHeaderOrContents(View* parent, std::unique_ptr<View> new_view, View** member) { if (*member) parent->RemoveChildViewT(*member); if (new_view.get()) *member = parent->AddChildViewAt(std::move(new_view), 0); else *member = nullptr; InvalidateLayout(); } void ScrollView::ScrollContentsRegionToBeVisible(const gfx::Rect& rect) { if (!contents_ || (!IsHorizontalScrollEnabled() && !IsVerticalScrollEnabled())) { return; } gfx::Rect contents_region = rect; contents_region.Inset(-preferred_viewport_margins_); // Figure out the maximums for this scroll view. const int contents_max_x = std::max(contents_viewport_->width(), contents_->width()); const int contents_max_y = std::max(contents_viewport_->height(), contents_->height()); int x = std::clamp(contents_region.x(), 0, contents_max_x); int y = std::clamp(contents_region.y(), 0, contents_max_y); // Figure out how far and down the rectangle will go taking width // and height into account. This will be "clipped" by the viewport. const int max_x = std::min( contents_max_x, x + std::min(contents_region.width(), contents_viewport_->width())); const int max_y = std::min( contents_max_y, y + std::min(contents_region.height(), contents_viewport_->height())); // See if the rect is already visible. Note the width is (max_x - x) // and the height is (max_y - y) to take into account the clipping of // either viewport or the content size. const gfx::Rect vis_rect = GetVisibleRect(); if (vis_rect.Contains(gfx::Rect(x, y, max_x - x, max_y - y))) return; // Shift contents_'s X and Y so that the region is visible. If we // need to shift up or left from where we currently are then we need // to get it so that the content appears in the upper/left // corner. This is done by setting the offset to -X or -Y. For down // or right shifts we need to make sure it appears in the // lower/right corner. This is calculated by taking max_x or max_y // and scaling it back by the size of the viewport. const int new_x = (vis_rect.x() > x) ? x : std::max(0, max_x - contents_viewport_->width()); const int new_y = (vis_rect.y() > y) ? y : std::max(0, max_y - contents_viewport_->height()); ScrollToOffset(gfx::PointF(new_x, new_y)); } void ScrollView::ComputeScrollBarsVisibility(const gfx::Size& vp_size, const gfx::Size& content_size, bool* horiz_is_shown, bool* vert_is_shown) const { const bool horizontal_enabled = horizontal_scroll_bar_mode_ == ScrollBarMode::kEnabled; const bool vertical_enabled = vertical_scroll_bar_mode_ == ScrollBarMode::kEnabled; if (!horizontal_enabled) { *horiz_is_shown = false; *vert_is_shown = vertical_enabled && content_size.height() > vp_size.height(); return; } if (!vertical_enabled) { *vert_is_shown = false; *horiz_is_shown = content_size.width() > vp_size.width(); return; } // Try to fit both ways first, then try vertical bar only, then horizontal // bar only, then defaults to both shown. if (content_size.width() <= vp_size.width() && content_size.height() <= vp_size.height()) { *horiz_is_shown = false; *vert_is_shown = false; } else if (content_size.width() <= vp_size.width() - GetScrollBarLayoutWidth()) { *horiz_is_shown = false; *vert_is_shown = true; } else if (content_size.height() <= vp_size.height() - GetScrollBarLayoutHeight()) { *horiz_is_shown = true; *vert_is_shown = false; } else { *horiz_is_shown = true; *vert_is_shown = true; } } // Make sure that a single scrollbar is created and visible as needed void ScrollView::SetControlVisibility(View* control, bool should_show) { if (!control) return; if (should_show) { if (!control->GetVisible()) { AddChildView(control); control->SetVisible(true); } } else { RemoveChildView(control); control->SetVisible(false); } } void ScrollView::UpdateScrollBarPositions() { if (!contents_) return; const gfx::PointF offset = CurrentOffset(); if (IsHorizontalScrollEnabled()) { int vw = contents_viewport_->width(); int cw = contents_->width(); horiz_sb_->Update(vw, cw, offset.x()); } if (IsVerticalScrollEnabled()) { int vh = contents_viewport_->height(); int ch = contents_->height(); vert_sb_->Update(vh, ch, offset.y()); } } gfx::PointF ScrollView::CurrentOffset() const { return ScrollsWithLayers() ? contents_->layer()->CurrentScrollOffset() : gfx::PointF(-contents_->x(), -contents_->y()); } void ScrollView::ScrollByOffset(const gfx::PointF& offset) { if (!contents_) return; gfx::PointF current_offset = CurrentOffset(); ScrollToOffset(gfx::PointF(current_offset.x() + offset.x(), current_offset.y() + offset.y())); } void ScrollView::ScrollToOffset(const gfx::PointF& offset) { if (ScrollsWithLayers()) { contents_->layer()->SetScrollOffset(offset); } else { contents_->SetPosition(gfx::Point(-offset.x(), -offset.y())); } OnScrolled(offset); } bool ScrollView::ScrollsWithLayers() const { if (!scroll_with_layers_enabled_) return false; // Just check for the presence of a layer since it's cheaper than querying the // Feature flag each time. return contents_viewport_->layer() != nullptr; } bool ScrollView::IsHorizontalScrollEnabled() const { return horizontal_scroll_bar_mode_ == ScrollBarMode::kHiddenButEnabled || (horizontal_scroll_bar_mode_ == ScrollBarMode::kEnabled && horiz_sb_->GetVisible()); } bool ScrollView::IsVerticalScrollEnabled() const { return vertical_scroll_bar_mode_ == ScrollBarMode::kHiddenButEnabled || (vertical_scroll_bar_mode_ == ScrollBarMode::kEnabled && vert_sb_->GetVisible()); } void ScrollView::EnableViewportLayer() { if (DoesViewportOrScrollViewHaveLayer()) return; contents_viewport_->InitializeContentsViewportLayer(); contents_viewport_->layer()->SetMasksToBounds(true); more_content_left_->SetPaintToLayer(); more_content_top_->SetPaintToLayer(); more_content_right_->SetPaintToLayer(); more_content_bottom_->SetPaintToLayer(); UpdateBackground(); } void ScrollView::OnLayerScrolled(const gfx::PointF& current_offset, const cc::ElementId&) { OnScrolled(current_offset); } void ScrollView::OnScrolled(const gfx::PointF& offset) { UpdateOverflowIndicatorVisibility(offset); UpdateScrollBarPositions(); ScrollHeader(); on_contents_scrolled_.Notify(); NotifyAccessibilityEvent(ax::mojom::Event::kScrollPositionChanged, /*send_native_event=*/true); } void ScrollView::ScrollHeader() { if (!header_) return; int x_offset = CurrentOffset().x(); if (header_->x() != -x_offset) { header_->SetX(-x_offset); header_->SchedulePaintInRect(header_->GetVisibleBounds()); } } void ScrollView::AddBorder() { draw_border_ = true; UpdateBorder(); } void ScrollView::UpdateBorder() { if (!draw_border_ || !GetWidget()) return; SetBorder(CreateSolidBorder( 1, GetColorProvider()->GetColor( draw_focus_indicator_ ? ui::kColorFocusableBorderFocused : ui::kColorFocusableBorderUnfocused))); } void ScrollView::UpdateBackground() { if (!GetWidget()) return; const absl::optional<SkColor> background_color = GetBackgroundColor(); auto create_background = [background_color]() { return background_color ? CreateSolidBackground(background_color.value()) : nullptr; }; SetBackground(create_background()); // In addition to setting the background of |this|, set the background on // the viewport as well. This way if the viewport has a layer // SetFillsBoundsOpaquely() is honored. contents_viewport_->SetBackground(create_background()); if (contents_ && ScrollsWithLayers()) { contents_->SetBackground(create_background()); // Contents views may not be aware they need to fill their entire bounds - // play it safe here to avoid graphical glitches (https://crbug.com/826472). // If there's no solid background, mark the contents view as not filling its // bounds opaquely. contents_->layer()->SetFillsBoundsOpaquely(!!background_color); } if (contents_viewport_->layer()) { contents_viewport_->layer()->SetFillsBoundsOpaquely(!!background_color); } } absl::optional<SkColor> ScrollView::GetBackgroundColor() const { return background_color_id_ ? GetColorProvider()->GetColor(background_color_id_.value()) : background_color_; } absl::optional<ui::ColorId> ScrollView::GetBackgroundThemeColorId() const { return background_color_id_; } void ScrollView::PositionOverflowIndicators() { // TODO(https://crbug.com/1166949): Use a layout manager to position these. const gfx::Rect contents_bounds = GetContentsBounds(); const int x = contents_bounds.x(); const int y = contents_bounds.y(); const int w = contents_bounds.width(); const int h = contents_bounds.height(); more_content_left_->SetBoundsRect( gfx::Rect(x, y, more_content_left_thickness_, h)); more_content_top_->SetBoundsRect( gfx::Rect(x, y, w, more_content_top_thickness_)); more_content_right_->SetBoundsRect( gfx::Rect(contents_bounds.right() - more_content_right_thickness_, y, more_content_right_thickness_, h)); more_content_bottom_->SetBoundsRect( gfx::Rect(x, contents_bounds.bottom() - more_content_bottom_thickness_, w, more_content_bottom_thickness_)); } void ScrollView::UpdateOverflowIndicatorVisibility(const gfx::PointF& offset) { SetControlVisibility(more_content_top_.get(), !draw_border_ && !header_ && IsVerticalScrollEnabled() && offset.y() > vert_sb_->GetMinPosition() && draw_overflow_indicator_); SetControlVisibility( more_content_bottom_.get(), !draw_border_ && IsVerticalScrollEnabled() && !horiz_sb_->GetVisible() && offset.y() < vert_sb_->GetMaxPosition() && draw_overflow_indicator_); SetControlVisibility(more_content_left_.get(), !draw_border_ && IsHorizontalScrollEnabled() && offset.x() > horiz_sb_->GetMinPosition() && draw_overflow_indicator_); SetControlVisibility( more_content_right_.get(), !draw_border_ && IsHorizontalScrollEnabled() && !vert_sb_->GetVisible() && offset.x() < horiz_sb_->GetMaxPosition() && draw_overflow_indicator_); } View* ScrollView::GetContentsViewportForTest() const { return contents_viewport_; } BEGIN_METADATA(ScrollView, View) ADD_READONLY_PROPERTY_METADATA(int, MinHeight) ADD_READONLY_PROPERTY_METADATA(int, MaxHeight) ADD_PROPERTY_METADATA(bool, AllowKeyboardScrolling) ADD_PROPERTY_METADATA(absl::optional<SkColor>, BackgroundColor) ADD_PROPERTY_METADATA(absl::optional<ui::ColorId>, BackgroundThemeColorId) ADD_PROPERTY_METADATA(bool, DrawOverflowIndicator) ADD_PROPERTY_METADATA(bool, HasFocusIndicator) ADD_PROPERTY_METADATA(ScrollView::ScrollBarMode, HorizontalScrollBarMode) ADD_PROPERTY_METADATA(ScrollView::ScrollBarMode, VerticalScrollBarMode) ADD_PROPERTY_METADATA(bool, TreatAllScrollEventsAsHorizontal) END_METADATA // VariableRowHeightScrollHelper ---------------------------------------------- VariableRowHeightScrollHelper::VariableRowHeightScrollHelper( Controller* controller) : controller_(controller) {} VariableRowHeightScrollHelper::~VariableRowHeightScrollHelper() = default; int VariableRowHeightScrollHelper::GetPageScrollIncrement( ScrollView* scroll_view, bool is_horizontal, bool is_positive) { if (is_horizontal) return 0; // y coordinate is most likely negative. int y = abs(scroll_view->contents()->y()); int vis_height = scroll_view->contents()->parent()->height(); if (is_positive) { // Align the bottom most row to the top of the view. int bottom = std::min(scroll_view->contents()->height() - 1, y + vis_height); RowInfo bottom_row_info = GetRowInfo(bottom); // If 0, ScrollView will provide a default value. return std::max(0, bottom_row_info.origin - y); } else { // Align the row on the previous page to to the top of the view. int last_page_y = y - vis_height; RowInfo last_page_info = GetRowInfo(std::max(0, last_page_y)); if (last_page_y != last_page_info.origin) return std::max(0, y - last_page_info.origin - last_page_info.height); return std::max(0, y - last_page_info.origin); } } int VariableRowHeightScrollHelper::GetLineScrollIncrement( ScrollView* scroll_view, bool is_horizontal, bool is_positive) { if (is_horizontal) return 0; // y coordinate is most likely negative. int y = abs(scroll_view->contents()->y()); RowInfo row = GetRowInfo(y); if (is_positive) { return row.height - (y - row.origin); } else if (y == row.origin) { row = GetRowInfo(std::max(0, row.origin - 1)); return y - row.origin; } else { return y - row.origin; } } VariableRowHeightScrollHelper::RowInfo VariableRowHeightScrollHelper::GetRowInfo(int y) { return controller_->GetRowInfo(y); } // FixedRowHeightScrollHelper ----------------------------------------------- FixedRowHeightScrollHelper::FixedRowHeightScrollHelper(int top_margin, int row_height) : VariableRowHeightScrollHelper(nullptr), top_margin_(top_margin), row_height_(row_height) { DCHECK_GT(row_height, 0); } VariableRowHeightScrollHelper::RowInfo FixedRowHeightScrollHelper::GetRowInfo( int y) { if (y < top_margin_) return RowInfo(0, top_margin_); return RowInfo((y - top_margin_) / row_height_ * row_height_ + top_margin_, row_height_); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scroll_view.cc
C++
unknown
51,577
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLL_VIEW_H_ #define UI_VIEWS_CONTROLS_SCROLL_VIEW_H_ #include <memory> #include <utility> #include "base/callback_list.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/color/color_id.h" #include "ui/compositor/layer_type.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/controls/separator.h" namespace cc { struct ElementId; } namespace gfx { class PointF; class RoundedCornersF; } namespace views { namespace test { class ScrollViewTestApi; } enum class OverflowIndicatorAlignment { kLeft, kTop, kRight, kBottom }; ///////////////////////////////////////////////////////////////////////////// // // ScrollView class // // A ScrollView is used to make any View scrollable. The view is added to // a viewport which takes care of clipping. // // In this current implementation both horizontal and vertical scrollbars are // added as needed. // // The scrollview supports keyboard UI and mousewheel. // ///////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ScrollView : public View, public ScrollBarController { public: METADATA_HEADER(ScrollView); // Indicates whether or not scroll view is initialized with layer-scrolling. enum class ScrollWithLayers { kDisabled, kEnabled }; // Controls how a scroll bar appears and functions. enum class ScrollBarMode { // The scrollbar is hidden, and the pane will not respond to e.g. mousewheel // events even if the contents are larger than the viewport. kDisabled, // The scrollbar is hidden whether or not the contents are larger than the // viewport, but the pane will respond to scroll events. kHiddenButEnabled, // The scrollbar will be visible if the contents are larger than the // viewport and the pane will respond to scroll events. kEnabled }; using ScrollViewCallbackList = base::RepeatingClosureList; using ScrollViewCallback = ScrollViewCallbackList::CallbackType; ScrollView(); // Additional constructor for overriding scrolling as defined by // |kUiCompositorScrollWithLayers|. See crbug.com/873923 for more details on // enabling by default this for all platforms. explicit ScrollView(ScrollWithLayers scroll_with_layers); ScrollView(const ScrollView&) = delete; ScrollView& operator=(const ScrollView&) = delete; ~ScrollView() override; // Creates a ScrollView with a theme specific border. static std::unique_ptr<ScrollView> CreateScrollViewWithBorder(); // Returns the ScrollView for which |contents| is its contents, or null if // |contents| is not in a ScrollView. static ScrollView* GetScrollViewForContents(View* contents); // Set the contents. Any previous contents will be deleted. The contents // is the view that needs to scroll. template <typename T> T* SetContents(std::unique_ptr<T> a_view) { T* content_view = a_view.get(); SetContentsImpl(std::move(a_view)); return content_view; } void SetContents(std::nullptr_t); const View* contents() const { return contents_; } View* contents() { return contents_; } // `layer_type` specifies the kind of layer used if scroll with layers is // enabled. This function should be called before SetContents(). void SetContentsLayerType(ui::LayerType layer_type); // Sets the header, deleting the previous header. template <typename T> T* SetHeader(std::unique_ptr<T> a_header) { T* header_view = a_header.get(); SetHeaderImpl(std::move(a_header)); return header_view; } void SetHeader(std::nullptr_t); int GetMaxHeight() const { return max_height_; } int GetMinHeight() const { return min_height_; } // Sets the preferred margins within the scroll viewport - when scrolling // rects to visible, these margins will be added to the visible rect. void SetPreferredViewportMargins(const gfx::Insets& margins); // You must be using layer scrolling for this method to work as it applies // rounded corners to the `contents_viewport_` layer. See `ScrollWithLayers`. void SetViewportRoundedCornerRadius(const gfx::RoundedCornersF& radii); // The background color can be configured in two distinct ways: // . By way of SetBackgroundThemeColorId(). This is the default and when // called the background color comes from the theme (and changes if the // theme changes). // . By way of setting an explicit color, i.e. SetBackgroundColor(). Use // absl::nullopt if you don't want any color, but be warned this // produces awful results when layers are used with subpixel rendering. absl::optional<SkColor> GetBackgroundColor() const; void SetBackgroundColor(const absl::optional<SkColor>& color); absl::optional<ui::ColorId> GetBackgroundThemeColorId() const; void SetBackgroundThemeColorId(const absl::optional<ui::ColorId>& color_id); // Returns the visible region of the content View. gfx::Rect GetVisibleRect() const; // Scrolls the `contents_` by an offset. void ScrollByOffset(const gfx::PointF& offset); // Scrolls the `contents_` to an offset. void ScrollToOffset(const gfx::PointF& offset); bool GetUseColorId() const { return !!background_color_id_; } ScrollBarMode GetHorizontalScrollBarMode() const { return horizontal_scroll_bar_mode_; } ScrollBarMode GetVerticalScrollBarMode() const { return vertical_scroll_bar_mode_; } bool GetTreatAllScrollEventsAsHorizontal() const { return treat_all_scroll_events_as_horizontal_; } void SetHorizontalScrollBarMode(ScrollBarMode horizontal_scroll_bar_mode); void SetVerticalScrollBarMode(ScrollBarMode vertical_scroll_bar_mode); void SetTreatAllScrollEventsAsHorizontal( bool treat_all_scroll_events_as_horizontal); // Gets/Sets whether the keyboard arrow keys attempt to scroll the view. bool GetAllowKeyboardScrolling() const { return allow_keyboard_scrolling_; } void SetAllowKeyboardScrolling(bool allow_keyboard_scrolling); bool GetDrawOverflowIndicator() const { return draw_overflow_indicator_; } void SetDrawOverflowIndicator(bool draw_overflow_indicator); View* SetCustomOverflowIndicator(OverflowIndicatorAlignment side, std::unique_ptr<View> indicator, int thickness, bool fills_opaquely); // Turns this scroll view into a bounded scroll view, with a fixed height. // By default, a ScrollView will stretch to fill its outer container. void ClipHeightTo(int min_height, int max_height); // Returns whether or not the ScrollView is bounded (as set by ClipHeightTo). bool is_bounded() const { return max_height_ >= 0 && min_height_ >= 0; } // Retrieves the width/height reserved for scrollbars. These return 0 if the // scrollbar has not yet been created or in the case of overlay scrollbars. int GetScrollBarLayoutWidth() const; int GetScrollBarLayoutHeight() const; // Returns the horizontal/vertical scrollbar. ScrollBar* horizontal_scroll_bar() { return horiz_sb_; } const ScrollBar* horizontal_scroll_bar() const { return horiz_sb_; } ScrollBar* vertical_scroll_bar() { return vert_sb_; } const ScrollBar* vertical_scroll_bar() const { return vert_sb_; } // Customize the scrollbar design. |horiz_sb| and |vert_sb| cannot be null. ScrollBar* SetHorizontalScrollBar(std::unique_ptr<ScrollBar> horiz_sb); ScrollBar* SetVerticalScrollBar(std::unique_ptr<ScrollBar> vert_sb); // Gets/Sets whether this ScrollView has a focus indicator or not. bool GetHasFocusIndicator() const { return draw_focus_indicator_; } void SetHasFocusIndicator(bool has_focus_indicator); // Called when |contents_| scrolled. This can be triggered by each single // event that is able to scroll the contents. KeyEvents like ui::VKEY_LEFT, // ui::VKEY_RIGHT, or only ui::ET_MOUSEWHEEL will only trigger this function // but not OnContentsScrollEnded below, since they do not belong to any // events sequence. This function will also be triggered by each // ui::ET_GESTURE_SCROLL_UPDATE event in the gesture scroll sequence or // each ui::ET_MOUSEWHEEL event that associated with the ScrollEvent in the // scroll events sequence while the OnContentsScrollEnded below will only be // triggered once at the end of the events sequence. base::CallbackListSubscription AddContentsScrolledCallback( ScrollViewCallback callback); // Called at the end of a sequence of events that are generated to scroll // the contents. The gesture scroll sequence {ui::ET_GESTURE_SCROLL_BEGIN, // ui::ET_GESTURE_SCROLL_UPDATE, ..., ui::ET_GESTURE_SCROLL_UPDATE, // ui::ET_GESTURE_SCROLL_END or ui::ET_SCROLL_FLING_START} or the scroll // events sequence {ui::ET_SCROLL_FLING_CANCEL, ui::ET_SCROLL, ..., // ui::ET_SCROLL, ui::ET_SCROLL_FLING_START} both will trigger this function // on the events sequence end. base::CallbackListSubscription AddContentsScrollEndedCallback( ScrollViewCallback callback); // View overrides: gfx::Size CalculatePreferredSize() const override; int GetHeightForWidth(int width) const override; void Layout() override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnMouseWheel(const ui::MouseWheelEvent& e) override; void OnScrollEvent(ui::ScrollEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; void OnThemeChanged() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; // ScrollBarController overrides: void ScrollToPosition(ScrollBar* source, int position) override; int GetScrollIncrement(ScrollBar* source, bool is_page, bool is_positive) override; void OnScrollEnded() override; bool is_scrolling() const { return horiz_sb_->is_scrolling() || vert_sb_->is_scrolling(); } private: friend class test::ScrollViewTestApi; class Viewport; bool IsHorizontalScrollEnabled() const; bool IsVerticalScrollEnabled() const; // Forces |contents_viewport_| to have a Layer (assuming it doesn't already). void EnableViewportLayer(); // Returns true if this or the viewport has a layer. bool DoesViewportOrScrollViewHaveLayer() const; // Updates or destroys the viewport layer as necessary. If any descendants // of the viewport have a layer, then the viewport needs to have a layer, // otherwise it doesn't. void UpdateViewportLayerForClipping(); void SetContentsImpl(std::unique_ptr<View> a_view); void SetHeaderImpl(std::unique_ptr<View> a_header); // Used internally by SetHeaderImpl() and SetContentsImpl() to reset the view. // Sets |member| to |new_view|. If |new_view| is non-null it is added to // |parent|. void SetHeaderOrContents(View* parent, std::unique_ptr<View> new_view, View** member); // Scrolls the minimum amount necessary to make the specified rectangle // visible, in the coordinates of the contents view. The specified rectangle // is constrained by the bounds of the contents view. This has no effect if // the contents have not been set. void ScrollContentsRegionToBeVisible(const gfx::Rect& rect); // Computes the visibility of both scrollbars, taking in account the view port // and content sizes. void ComputeScrollBarsVisibility(const gfx::Size& viewport_size, const gfx::Size& content_size, bool* horiz_is_shown, bool* vert_is_shown) const; // Shows or hides the scrollbar/corner_view based on the value of // |should_show|. void SetControlVisibility(View* control, bool should_show); // Update the scrollbars positions given viewport and content sizes. void UpdateScrollBarPositions(); // Get the current scroll offset either from the ui::Layer or from the // |contents_| origin offset. gfx::PointF CurrentOffset() const; // Whether the ScrollView scrolls using ui::Layer APIs. bool ScrollsWithLayers() const; // Callback entrypoint when hosted Layers are scrolled by the Compositor. void OnLayerScrolled(const gfx::PointF&, const cc::ElementId&); // Updates accessory elements when |contents_| is scrolled. void OnScrolled(const gfx::PointF& offset); // Horizontally scrolls the header (if any) to match the contents. void ScrollHeader(); void AddBorder(); void UpdateBorder(); void UpdateBackground(); // Positions each overflow indicator against their respective content edge. void PositionOverflowIndicators(); // Shows/hides the overflow indicators depending on the position of the // scrolling content within the viewport. void UpdateOverflowIndicatorVisibility(const gfx::PointF& offset); View* GetContentsViewportForTest() const; // The current contents and its viewport. |contents_| is contained in // |contents_viewport_|. // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION View* contents_ = nullptr; raw_ptr<Viewport> contents_viewport_ = nullptr; // The current header and its viewport. |header_| is contained in // |header_viewport_|. // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION View* header_ = nullptr; raw_ptr<Viewport> header_viewport_ = nullptr; // Horizontal scrollbar. raw_ptr<ScrollBar, DanglingUntriaged> horiz_sb_; // Vertical scrollbar. raw_ptr<ScrollBar, DanglingUntriaged> vert_sb_; // Corner view. std::unique_ptr<View> corner_view_; // Hidden content indicators // TODO(https://crbug.com/1166949): Use preferred width/height instead of // thickness members. std::unique_ptr<View> more_content_left_ = std::make_unique<Separator>(); int more_content_left_thickness_ = Separator::kThickness; std::unique_ptr<View> more_content_top_ = std::make_unique<Separator>(); int more_content_top_thickness_ = Separator::kThickness; std::unique_ptr<View> more_content_right_ = std::make_unique<Separator>(); int more_content_right_thickness_ = Separator::kThickness; std::unique_ptr<View> more_content_bottom_ = std::make_unique<Separator>(); int more_content_bottom_thickness_ = Separator::kThickness; // The min and max height for the bounded scroll view. These are negative // values if the view is not bounded. int min_height_ = -1; int max_height_ = -1; // See description of SetBackgroundColor() for details. absl::optional<SkColor> background_color_; absl::optional<ui::ColorId> background_color_id_ = ui::kColorDialogBackground; // How to handle the case when the contents overflow the viewport. ScrollBarMode horizontal_scroll_bar_mode_ = ScrollBarMode::kEnabled; ScrollBarMode vertical_scroll_bar_mode_ = ScrollBarMode::kEnabled; // Causes vertical scroll events (e.g. scrolling with the mousewheel) as // horizontal events, to make scrolling in horizontal-only scroll situations // easier for the user. bool treat_all_scroll_events_as_horizontal_ = false; // In Harmony, the indicator is a focus ring. Pre-Harmony, the indicator is a // different border painter. bool draw_focus_indicator_ = false; // Only needed for pre-Harmony. Remove when Harmony is default. bool draw_border_ = false; // Whether to draw a white separator on the four sides of the scroll view when // it overflows. bool draw_overflow_indicator_ = true; // Set to true if the scroll with layers feature is enabled. const bool scroll_with_layers_enabled_; // Whether the left/right/up/down arrow keys attempt to scroll the view. bool allow_keyboard_scrolling_ = true; // The layer type used for content view when scroll by layers is enabled. ui::LayerType layer_type_ = ui::LAYER_TEXTURED; gfx::Insets preferred_viewport_margins_; // Scrolling callbacks. ScrollViewCallbackList on_contents_scrolled_; ScrollViewCallbackList on_contents_scroll_ended_; }; // When building with GCC this ensures that an instantiation of the // ScrollView::SetContents<View> template is available with which to link. template View* ScrollView::SetContents<View>(std::unique_ptr<View> a_view); BEGIN_VIEW_BUILDER(VIEWS_EXPORT, ScrollView, View) VIEW_BUILDER_VIEW_TYPE_PROPERTY(View, Contents) VIEW_BUILDER_PROPERTY(ui::LayerType, ContentsLayerType) VIEW_BUILDER_VIEW_TYPE_PROPERTY(View, Header) VIEW_BUILDER_PROPERTY(bool, AllowKeyboardScrolling) VIEW_BUILDER_PROPERTY(absl::optional<ui::ColorId>, BackgroundThemeColorId) VIEW_BUILDER_METHOD(ClipHeightTo, int, int) VIEW_BUILDER_PROPERTY(ScrollView::ScrollBarMode, HorizontalScrollBarMode) VIEW_BUILDER_PROPERTY(ScrollView::ScrollBarMode, VerticalScrollBarMode) VIEW_BUILDER_PROPERTY(bool, TreatAllScrollEventsAsHorizontal) VIEW_BUILDER_PROPERTY(bool, DrawOverflowIndicator) VIEW_BUILDER_PROPERTY(absl::optional<SkColor>, BackgroundColor) VIEW_BUILDER_VIEW_PROPERTY(ScrollBar, HorizontalScrollBar) VIEW_BUILDER_VIEW_PROPERTY(ScrollBar, VerticalScrollBar) VIEW_BUILDER_PROPERTY(bool, HasFocusIndicator) END_VIEW_BUILDER // VariableRowHeightScrollHelper is intended for views that contain rows of // varying height. To use a VariableRowHeightScrollHelper create one supplying // a Controller and delegate GetPageScrollIncrement and GetLineScrollIncrement // to the helper. VariableRowHeightScrollHelper calls back to the // Controller to determine row boundaries. class VariableRowHeightScrollHelper { public: // The origin and height of a row. struct RowInfo { RowInfo(int origin, int height) : origin(origin), height(height) {} // Origin of the row. int origin; // Height of the row. int height; }; // Used to determine row boundaries. class Controller { public: // Returns the origin and size of the row at the specified location. virtual VariableRowHeightScrollHelper::RowInfo GetRowInfo(int y) = 0; }; // Creates a new VariableRowHeightScrollHelper. Controller is // NOT deleted by this VariableRowHeightScrollHelper. explicit VariableRowHeightScrollHelper(Controller* controller); VariableRowHeightScrollHelper(const VariableRowHeightScrollHelper&) = delete; VariableRowHeightScrollHelper& operator=( const VariableRowHeightScrollHelper&) = delete; virtual ~VariableRowHeightScrollHelper(); // Delegate the View methods of the same name to these. The scroll amount is // determined by querying the Controller for the appropriate row to scroll // to. int GetPageScrollIncrement(ScrollView* scroll_view, bool is_horizontal, bool is_positive); int GetLineScrollIncrement(ScrollView* scroll_view, bool is_horizontal, bool is_positive); protected: // Returns the row information for the row at the specified location. This // calls through to the method of the same name on the controller. virtual RowInfo GetRowInfo(int y); private: raw_ptr<Controller> controller_; }; // FixedRowHeightScrollHelper is intended for views that contain fixed height // height rows. To use a FixedRowHeightScrollHelper delegate // GetPageScrollIncrement and GetLineScrollIncrement to it. class FixedRowHeightScrollHelper : public VariableRowHeightScrollHelper { public: // Creates a FixedRowHeightScrollHelper. top_margin gives the distance from // the top of the view to the first row, and may be 0. row_height gives the // height of each row. FixedRowHeightScrollHelper(int top_margin, int row_height); FixedRowHeightScrollHelper(const FixedRowHeightScrollHelper&) = delete; FixedRowHeightScrollHelper& operator=(const FixedRowHeightScrollHelper&) = delete; protected: // Calculates the bounds of the row from the top margin and row height. RowInfo GetRowInfo(int y) override; private: int top_margin_; int row_height_; }; } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, ScrollView) #endif // UI_VIEWS_CONTROLS_SCROLL_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scroll_view.h
C++
unknown
20,411
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scroll_view.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/scoped_observation.h" #include "base/task/single_thread_task_runner.h" #include "base/test/gtest_util.h" #include "base/test/icu_test_util.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_timeouts.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/ui_base_features.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_type.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/test/event_generator.h" #include "ui/events/types/event_type.h" #include "ui/gfx/geometry/point_f.h" #include "ui/views/border.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/controls/scrollbar/overlay_scroll_bar.h" #include "ui/views/controls/scrollbar/scroll_bar_views.h" #include "ui/views/test/test_views.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/test/widget_test.h" #include "ui/views/view_observer.h" #include "ui/views/view_test_api.h" #if BUILDFLAG(IS_MAC) #include "ui/base/test/scoped_preferred_scroller_style_mac.h" #endif enum ScrollBarOrientation { HORIZONTAL, VERTICAL }; namespace views { namespace test { class ScrollViewTestApi { public: explicit ScrollViewTestApi(ScrollView* scroll_view) : scroll_view_(scroll_view) {} ScrollViewTestApi(const ScrollViewTestApi&) = delete; ScrollViewTestApi& operator=(const ScrollViewTestApi&) = delete; ~ScrollViewTestApi() = default; ScrollBar* GetScrollBar(ScrollBarOrientation orientation) { ScrollBar* scroll_bar = orientation == VERTICAL ? scroll_view_->vertical_scroll_bar() : scroll_view_->horizontal_scroll_bar(); return scroll_bar; } const base::OneShotTimer& GetScrollBarTimer( ScrollBarOrientation orientation) { return GetScrollBar(orientation)->repeater_.timer_for_testing(); } BaseScrollBarThumb* GetScrollBarThumb(ScrollBarOrientation orientation) { return GetScrollBar(orientation)->thumb_; } gfx::Vector2d IntegralViewOffset() { return gfx::Point() - gfx::ToFlooredPoint(CurrentOffset()); } gfx::PointF CurrentOffset() const { return scroll_view_->CurrentOffset(); } base::RetainingOneShotTimer* GetScrollBarHideTimer( ScrollBarOrientation orientation) { return ScrollBar::GetHideTimerForTesting(GetScrollBar(orientation)); } View* corner_view() { return scroll_view_->corner_view_.get(); } View* contents_viewport() { return scroll_view_->GetContentsViewportForTest(); } View* more_content_left() { return scroll_view_->more_content_left_.get(); } View* more_content_top() { return scroll_view_->more_content_top_.get(); } View* more_content_right() { return scroll_view_->more_content_right_.get(); } View* more_content_bottom() { return scroll_view_->more_content_bottom_.get(); } private: raw_ptr<ScrollView> scroll_view_; }; class ObserveViewDeletion : public ViewObserver { public: explicit ObserveViewDeletion(View* view) { observer_.Observe(view); } void OnViewIsDeleting(View* observed_view) override { deleted_view_ = observed_view; observer_.Reset(); } View* deleted_view() { return deleted_view_; } private: base::ScopedObservation<View, ViewObserver> observer_{this}; raw_ptr<View> deleted_view_ = nullptr; }; } // namespace test namespace { const int kWidth = 100; const int kMinHeight = 50; const int kMaxHeight = 100; class FixedView : public View { public: FixedView() = default; FixedView(const FixedView&) = delete; FixedView& operator=(const FixedView&) = delete; ~FixedView() override = default; void Layout() override { gfx::Size pref = GetPreferredSize(); SetBounds(x(), y(), pref.width(), pref.height()); } void SetFocus() { Focus(); } }; class CustomView : public View { public: CustomView() = default; CustomView(const CustomView&) = delete; CustomView& operator=(const CustomView&) = delete; ~CustomView() override = default; const gfx::Point last_location() const { return last_location_; } void Layout() override { gfx::Size pref = GetPreferredSize(); int width = pref.width(); int height = pref.height(); if (parent()) { width = std::max(parent()->width(), width); height = std::max(parent()->height(), height); } SetBounds(x(), y(), width, height); } bool OnMousePressed(const ui::MouseEvent& event) override { last_location_ = event.location(); return true; } private: gfx::Point last_location_; }; void CheckScrollbarVisibility(const ScrollView* scroll_view, ScrollBarOrientation orientation, bool should_be_visible) { const ScrollBar* scrollbar = orientation == HORIZONTAL ? scroll_view->horizontal_scroll_bar() : scroll_view->vertical_scroll_bar(); if (should_be_visible) { ASSERT_TRUE(scrollbar); EXPECT_TRUE(scrollbar->GetVisible()); } else { EXPECT_TRUE(!scrollbar || !scrollbar->GetVisible()); } } ui::MouseEvent TestLeftMouseAt(const gfx::Point& location, ui::EventType type) { return ui::MouseEvent(type, location, location, base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); } // This view has a large width, but the height always matches the parent's // height. This is similar to a TableView that has many columns showing, but // very few rows. class VerticalResizingView : public View { public: VerticalResizingView() = default; VerticalResizingView(const VerticalResizingView&) = delete; VerticalResizingView& operator=(const VerticalResizingView&) = delete; ~VerticalResizingView() override = default; void Layout() override { int width = 10000; int height = parent()->height(); SetBounds(x(), y(), width, height); } }; // Same as VerticalResizingView, but horizontal instead. class HorizontalResizingView : public View { public: HorizontalResizingView() = default; HorizontalResizingView(const HorizontalResizingView&) = delete; HorizontalResizingView& operator=(const HorizontalResizingView&) = delete; ~HorizontalResizingView() override = default; void Layout() override { int height = 10000; int width = parent()->width(); SetBounds(x(), y(), width, height); } }; class TestScrollBarThumb : public BaseScrollBarThumb { public: using BaseScrollBarThumb::BaseScrollBarThumb; // BaseScrollBarThumb: gfx::Size CalculatePreferredSize() const override { return gfx::Size(1, 1); } void OnPaint(gfx::Canvas* canvas) override {} }; class TestScrollBar : public ScrollBar { public: TestScrollBar(bool horizontal, bool overlaps_content, int thickness) : ScrollBar(horizontal), overlaps_content_(overlaps_content), thickness_(thickness) { SetThumb(new TestScrollBarThumb(this)); } // ScrollBar: int GetThickness() const override { return thickness_; } bool OverlapsContent() const override { return overlaps_content_; } gfx::Rect GetTrackBounds() const override { gfx::Rect bounds = GetLocalBounds(); bounds.set_width(GetThickness()); return bounds; } private: const bool overlaps_content_ = false; const int thickness_ = 0; }; } // namespace using test::ScrollViewTestApi; // Simple test harness for testing a ScrollView directly. class ScrollViewTest : public ViewsTestBase { public: ScrollViewTest() = default; ScrollViewTest(const ScrollViewTest&) = delete; ScrollViewTest& operator=(const ScrollViewTest&) = delete; void SetUp() override { ViewsTestBase::SetUp(); scroll_view_ = std::make_unique<ScrollView>(); } View* InstallContents() { const gfx::Rect default_outer_bounds(0, 0, 100, 100); auto* view = scroll_view_->SetContents(std::make_unique<View>()); scroll_view_->SetBoundsRect(default_outer_bounds); // Setting the contents will invalidate the layout. Call RunScheduledLayout // to immediately run the scheduled layout. views::test::RunScheduledLayout(scroll_view_.get()); return view; } // For the purposes of these tests, we directly call SetBounds on the // contents of the ScrollView to see how the ScrollView reacts to it. Calling // SetBounds will not invalidate parent layouts. Thus, we need to manually // invalidate the layout of the scroll view. Production code should not need // to manually invalidate the layout of the ScrollView as the ScrollView's // layout should be invalidated through the call paths that change the size of // the ScrollView's contents. (For example, via AddChildView). void InvalidateAndRunScheduledLayoutOnScrollView() { scroll_view_->InvalidateLayout(); views::test::RunScheduledLayout(scroll_view_.get()); } protected: #if BUILDFLAG(IS_MAC) void SetOverlayScrollersEnabled(bool enabled) { // Ensure the old scroller override is destroyed before creating a new one. // Otherwise, the swizzlers are interleaved and restore incorrect methods. scroller_style_.reset(); scroller_style_ = std::make_unique<ui::test::ScopedPreferredScrollerStyle>(enabled); } private: // Disable overlay scrollers by default. This needs to be set before // |scroll_view_| is initialized, otherwise scrollers will try to animate to // change modes, which requires a MessageLoop to exist. Tests should only // modify this via SetOverlayScrollersEnabled(). std::unique_ptr<ui::test::ScopedPreferredScrollerStyle> scroller_style_ = std::make_unique<ui::test::ScopedPreferredScrollerStyle>(false); protected: #endif int VerticalScrollBarWidth() { return scroll_view_->vertical_scroll_bar()->GetThickness(); } int HorizontalScrollBarHeight() { return scroll_view_->horizontal_scroll_bar()->GetThickness(); } std::unique_ptr<ScrollView> scroll_view_; }; // Test harness that includes a Widget to help test ui::Event handling. class WidgetScrollViewTest : public test::WidgetTest, public ui::CompositorObserver { public: static constexpr int kDefaultHeight = 100; static constexpr int kDefaultWidth = 100; WidgetScrollViewTest() = default; WidgetScrollViewTest(const WidgetScrollViewTest&) = delete; WidgetScrollViewTest& operator=(const WidgetScrollViewTest&) = delete; // Call this before adding the ScrollView to test with overlay scrollbars. void SetUseOverlayScrollers() { use_overlay_scrollers_ = true; } // Adds a ScrollView with the given |contents_view| and does layout. ScrollView* AddScrollViewWithContents(std::unique_ptr<View> contents, bool commit_layers = true) { #if BUILDFLAG(IS_MAC) scroller_style_ = std::make_unique<ui::test::ScopedPreferredScrollerStyle>( use_overlay_scrollers_); #endif const gfx::Rect default_bounds(50, 50, kDefaultWidth, kDefaultHeight); widget_ = CreateTopLevelFramelessPlatformWidget(); widget_->SetBounds(default_bounds); widget_->Show(); ScrollView* scroll_view = widget_->SetContentsView(std::make_unique<ScrollView>()); scroll_view->SetContents(std::move(contents)); views::test::RunScheduledLayout(scroll_view); widget_->GetCompositor()->AddObserver(this); // Ensure the Compositor has committed layer changes before attempting to // use them for impl-side scrolling. Note that simply RunUntilIdle() works // when tests are run in isolation, but compositor scheduling can interact // between test runs in the general case. if (commit_layers) WaitForCommit(); return scroll_view; } // Adds a ScrollView with a contents view of the given |size| and does layout. ScrollView* AddScrollViewWithContentSize(const gfx::Size& contents_size, bool commit_layers = true) { auto contents = std::make_unique<View>(); contents->SetSize(contents_size); return AddScrollViewWithContents(std::move(contents), commit_layers); } // Wait for a commit to be observed on the compositor. void WaitForCommit() { base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, quit_closure_, TestTimeouts::action_timeout()); run_loop.Run(); EXPECT_TRUE(quit_closure_.is_null()) << "Timed out waiting for a commit."; } void TestClickAt(const gfx::Point& location) { ui::MouseEvent press(TestLeftMouseAt(location, ui::ET_MOUSE_PRESSED)); ui::MouseEvent release(TestLeftMouseAt(location, ui::ET_MOUSE_RELEASED)); widget_->OnMouseEvent(&press); widget_->OnMouseEvent(&release); } // testing::Test: void TearDown() override { widget_->GetCompositor()->RemoveObserver(this); if (widget_) widget_->CloseNow(); WidgetTest::TearDown(); } protected: Widget* widget() const { return widget_; } private: // ui::CompositorObserver: void OnCompositingDidCommit(ui::Compositor* compositor) override { quit_closure_.Run(); quit_closure_.Reset(); } raw_ptr<Widget> widget_ = nullptr; // Disable scrollbar hiding (i.e. disable overlay scrollbars) by default. bool use_overlay_scrollers_ = false; base::RepeatingClosure quit_closure_; #if BUILDFLAG(IS_MAC) std::unique_ptr<ui::test::ScopedPreferredScrollerStyle> scroller_style_; #endif }; constexpr int WidgetScrollViewTest::kDefaultHeight; constexpr int WidgetScrollViewTest::kDefaultWidth; // A gtest parameter to permute over whether ScrollView uses a left-to-right or // right-to-left locale, or whether it uses ui::Layers or View bounds offsets to // position contents (i.e. ::features::kUiCompositorScrollWithLayers). enum class UiConfig { kLtr, kLtrWithLayers, kRtl, kRtlWithLayers }; class WidgetScrollViewTestRTLAndLayers : public WidgetScrollViewTest, public ::testing::WithParamInterface<UiConfig> { public: WidgetScrollViewTestRTLAndLayers() : locale_(IsTestingRtl() ? "he" : "en") { if (IsTestingLayers()) { layer_config_.InitAndEnableFeature( ::features::kUiCompositorScrollWithLayers); } else { layer_config_.InitAndDisableFeature( ::features::kUiCompositorScrollWithLayers); } } WidgetScrollViewTestRTLAndLayers(const WidgetScrollViewTestRTLAndLayers&) = delete; WidgetScrollViewTestRTLAndLayers& operator=( const WidgetScrollViewTestRTLAndLayers&) = delete; bool IsTestingRtl() const { return GetParam() == UiConfig::kRtl || GetParam() == UiConfig::kRtlWithLayers; } bool IsTestingLayers() const { return GetParam() == UiConfig::kLtrWithLayers || GetParam() == UiConfig::kRtlWithLayers; } // Returns a point in the coordinate space of |target| by translating a point // inset one pixel from the top of the Widget and one pixel on the leading // side of the Widget. There should be no scroll bar on this side. If // |flip_result| is true, automatically account for flipped coordinates in // RTL. gfx::Point HitTestInCorner(View* target, bool flip_result = true) const { const gfx::Point test_mouse_point_in_root = IsTestingRtl() ? gfx::Point(kDefaultWidth - 1, 1) : gfx::Point(1, 1); gfx::Point point = test_mouse_point_in_root; View::ConvertPointToTarget(widget()->GetRootView(), target, &point); if (flip_result) return gfx::Point(target->GetMirroredXInView(point.x()), point.y()); return point; } private: base::test::ScopedRestoreICUDefaultLocale locale_; base::test::ScopedFeatureList layer_config_; }; std::string UiConfigToString(const testing::TestParamInfo<UiConfig>& info) { switch (info.param) { case UiConfig::kLtr: return "LTR"; case UiConfig::kLtrWithLayers: return "LTR_LAYERS"; case UiConfig::kRtl: return "RTL"; case UiConfig::kRtlWithLayers: return "RTL_LAYERS"; } NOTREACHED_NORETURN(); } // Verifies the viewport is sized to fit the available space. TEST_F(ScrollViewTest, ViewportSizedToFit) { View* contents = InstallContents(); EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); } // Verifies the viewport and content is sized to fit the available space for // bounded scroll view. TEST_F(ScrollViewTest, BoundedViewportSizedToFit) { View* contents = InstallContents(); scroll_view_->ClipHeightTo(100, 200); scroll_view_->SetBorder(CreateSolidBorder(2, 0)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ("2,2 96x96", contents->parent()->bounds().ToString()); // Make sure the width of |contents| is set properly not to overflow the // viewport. EXPECT_EQ(96, contents->width()); } // Verifies that the vertical scrollbar does not unnecessarily appear for a // contents whose height always matches the height of the viewport. TEST_F(ScrollViewTest, VerticalScrollbarDoesNotAppearUnnecessarily) { const gfx::Rect default_outer_bounds(0, 0, 100, 100); scroll_view_->SetContents(std::make_unique<VerticalResizingView>()); scroll_view_->SetBoundsRect(default_outer_bounds); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_FALSE(scroll_view_->vertical_scroll_bar()->GetVisible()); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->GetVisible()); } // Same as above, but setting horizontal scroll bar to hidden. TEST_F(ScrollViewTest, HorizontalScrollbarDoesNotAppearIfHidden) { const gfx::Rect default_outer_bounds(0, 0, 100, 100); scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); scroll_view_->SetContents(std::make_unique<VerticalResizingView>()); scroll_view_->SetBoundsRect(default_outer_bounds); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_FALSE(scroll_view_->vertical_scroll_bar()->GetVisible()); EXPECT_FALSE(scroll_view_->horizontal_scroll_bar()->GetVisible()); } // Same as above, but setting vertical scrollbar instead. TEST_F(ScrollViewTest, VerticalScrollbarDoesNotAppearIfHidden) { const gfx::Rect default_outer_bounds(0, 0, 100, 100); scroll_view_->SetVerticalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); scroll_view_->SetContents(std::make_unique<HorizontalResizingView>()); scroll_view_->SetBoundsRect(default_outer_bounds); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_FALSE(scroll_view_->vertical_scroll_bar()->GetVisible()); EXPECT_FALSE(scroll_view_->horizontal_scroll_bar()->GetVisible()); } // Same as above, but setting horizontal scroll bar to disabled. TEST_F(ScrollViewTest, HorizontalScrollbarDoesNotAppearIfDisabled) { const gfx::Rect default_outer_bounds(0, 0, 100, 100); scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kDisabled); scroll_view_->SetContents(std::make_unique<VerticalResizingView>()); scroll_view_->SetBoundsRect(default_outer_bounds); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_FALSE(scroll_view_->vertical_scroll_bar()->GetVisible()); EXPECT_FALSE(scroll_view_->horizontal_scroll_bar()->GetVisible()); } // Same as above, but setting vertical scrollbar instead. TEST_F(ScrollViewTest, VerticallScrollbarDoesNotAppearIfDisabled) { const gfx::Rect default_outer_bounds(0, 0, 100, 100); scroll_view_->SetVerticalScrollBarMode(ScrollView::ScrollBarMode::kDisabled); scroll_view_->SetContents(std::make_unique<HorizontalResizingView>()); scroll_view_->SetBoundsRect(default_outer_bounds); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_FALSE(scroll_view_->vertical_scroll_bar()->GetVisible()); EXPECT_FALSE(scroll_view_->horizontal_scroll_bar()->GetVisible()); } // Verifies the scrollbars are added as necessary. // If on Mac, test the non-overlay scrollbars. TEST_F(ScrollViewTest, ScrollBars) { View* contents = InstallContents(); // Size the contents such that vertical scrollbar is needed. contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), contents->parent()->width()); EXPECT_EQ(100, contents->parent()->height()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->GetVisible()); ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->GetVisible()); // Size the contents such that horizontal scrollbar is needed. contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100, contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight(), contents->parent()->height()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, false); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); // Both horizontal and vertical. contents->SetBounds(0, 0, 300, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight(), contents->parent()->height()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); // Add a border, test vertical scrollbar. const int kTopPadding = 1; const int kLeftPadding = 2; const int kBottomPadding = 3; const int kRightPadding = 4; scroll_view_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR( kTopPadding, kLeftPadding, kBottomPadding, kRightPadding))); contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth() - kLeftPadding - kRightPadding, contents->parent()->width()); EXPECT_EQ(100 - kTopPadding - kBottomPadding, contents->parent()->height()); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->GetVisible()); ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->GetVisible()); gfx::Rect bounds = scroll_view_->vertical_scroll_bar()->bounds(); EXPECT_EQ(100 - VerticalScrollBarWidth() - kRightPadding, bounds.x()); EXPECT_EQ(100 - kRightPadding, bounds.right()); EXPECT_EQ(kTopPadding, bounds.y()); EXPECT_EQ(100 - kBottomPadding, bounds.bottom()); // Horizontal with border. contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100 - kLeftPadding - kRightPadding, contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight() - kTopPadding - kBottomPadding, contents->parent()->height()); ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->GetVisible()); EXPECT_TRUE(!scroll_view_->vertical_scroll_bar() || !scroll_view_->vertical_scroll_bar()->GetVisible()); bounds = scroll_view_->horizontal_scroll_bar()->bounds(); EXPECT_EQ(kLeftPadding, bounds.x()); EXPECT_EQ(100 - kRightPadding, bounds.right()); EXPECT_EQ(100 - kBottomPadding - HorizontalScrollBarHeight(), bounds.y()); EXPECT_EQ(100 - kBottomPadding, bounds.bottom()); // Both horizontal and vertical with border. contents->SetBounds(0, 0, 300, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth() - kLeftPadding - kRightPadding, contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight() - kTopPadding - kBottomPadding, contents->parent()->height()); bounds = scroll_view_->horizontal_scroll_bar()->bounds(); // Check horiz. ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->GetVisible()); bounds = scroll_view_->horizontal_scroll_bar()->bounds(); EXPECT_EQ(kLeftPadding, bounds.x()); EXPECT_EQ(100 - kRightPadding - VerticalScrollBarWidth(), bounds.right()); EXPECT_EQ(100 - kBottomPadding - HorizontalScrollBarHeight(), bounds.y()); EXPECT_EQ(100 - kBottomPadding, bounds.bottom()); // Check vert. ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->GetVisible()); bounds = scroll_view_->vertical_scroll_bar()->bounds(); EXPECT_EQ(100 - VerticalScrollBarWidth() - kRightPadding, bounds.x()); EXPECT_EQ(100 - kRightPadding, bounds.right()); EXPECT_EQ(kTopPadding, bounds.y()); EXPECT_EQ(100 - kBottomPadding - HorizontalScrollBarHeight(), bounds.bottom()); } // Assertions around adding a header. TEST_F(WidgetScrollViewTest, Header) { auto contents_ptr = std::make_unique<View>(); auto* contents = contents_ptr.get(); ScrollView* scroll_view = AddScrollViewWithContents(std::move(contents_ptr)); auto* header = scroll_view->SetHeader(std::make_unique<CustomView>()); View* header_parent = header->parent(); views::test::RunScheduledLayout(widget()); // |header|s preferred size is empty, which should result in all space going // to contents. EXPECT_EQ("0,0 100x0", header->parent()->bounds().ToString()); EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); // With layered scrolling, ScrollView::Layout() will impose a size on the // contents that fills the viewport. Since the test view doesn't have its own // Layout, reset it in this case so that adding a header doesn't shift the // contents down and require scrollbars. if (contents->layer()) { EXPECT_EQ("0,0 100x100", contents->bounds().ToString()); contents->SetBoundsRect(gfx::Rect()); } EXPECT_EQ("0,0 0x0", contents->bounds().ToString()); // Get the header a height of 20. header->SetPreferredSize(gfx::Size(10, 20)); EXPECT_TRUE(ViewTestApi(scroll_view).needs_layout()); views::test::RunScheduledLayout(widget()); EXPECT_EQ("0,0 100x20", header->parent()->bounds().ToString()); EXPECT_EQ("0,20 100x80", contents->parent()->bounds().ToString()); if (contents->layer()) { EXPECT_EQ("0,0 100x80", contents->bounds().ToString()); contents->SetBoundsRect(gfx::Rect()); } EXPECT_EQ("0,0 0x0", contents->bounds().ToString()); // Remove the header. scroll_view->SetHeader(nullptr); // SetHeader(nullptr) deletes header. header = nullptr; views::test::RunScheduledLayout(widget()); EXPECT_EQ("0,0 100x0", header_parent->bounds().ToString()); EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); } // Verifies the scrollbars are added as necessary when a header is present. TEST_F(ScrollViewTest, ScrollBarsWithHeader) { auto* header = scroll_view_->SetHeader(std::make_unique<CustomView>()); View* contents = InstallContents(); header->SetPreferredSize(gfx::Size(10, 20)); // Size the contents such that vertical scrollbar is needed. contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(0, contents->parent()->x()); EXPECT_EQ(20, contents->parent()->y()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), contents->parent()->width()); EXPECT_EQ(80, contents->parent()->height()); EXPECT_EQ(0, header->parent()->x()); EXPECT_EQ(0, header->parent()->y()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), header->parent()->width()); EXPECT_EQ(20, header->parent()->height()); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->GetVisible()); ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->GetVisible()); // Make sure the vertical scrollbar overlaps the header for traditional // scrollbars and doesn't overlap the header for overlay scrollbars. const int expected_scrollbar_y = scroll_view_->vertical_scroll_bar()->OverlapsContent() ? header->bounds().bottom() : header->y(); EXPECT_EQ(expected_scrollbar_y, scroll_view_->vertical_scroll_bar()->y()); EXPECT_EQ(header->y(), contents->y()); // Size the contents such that horizontal scrollbar is needed. contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(0, contents->parent()->x()); EXPECT_EQ(20, contents->parent()->y()); EXPECT_EQ(100, contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight() - 20, contents->parent()->height()); EXPECT_EQ(0, header->parent()->x()); EXPECT_EQ(0, header->parent()->y()); EXPECT_EQ(100, header->parent()->width()); EXPECT_EQ(20, header->parent()->height()); ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->GetVisible()); EXPECT_TRUE(!scroll_view_->vertical_scroll_bar() || !scroll_view_->vertical_scroll_bar()->GetVisible()); // Both horizontal and vertical. contents->SetBounds(0, 0, 300, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(0, contents->parent()->x()); EXPECT_EQ(20, contents->parent()->y()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), contents->parent()->width()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight() - 20, contents->parent()->height()); EXPECT_EQ(0, header->parent()->x()); EXPECT_EQ(0, header->parent()->y()); EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), header->parent()->width()); EXPECT_EQ(20, header->parent()->height()); ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->GetVisible()); ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->GetVisible()); } // Verifies the header scrolls horizontally with the content. TEST_F(ScrollViewTest, HeaderScrollsWithContent) { ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(500, 500)); scroll_view_->SetContents(std::move(contents)); auto* header = scroll_view_->SetHeader(std::make_unique<CustomView>()); header->SetPreferredSize(gfx::Size(500, 20)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); EXPECT_EQ(gfx::Vector2d(0, 0), test_api.IntegralViewOffset()); EXPECT_EQ(gfx::Point(0, 0), header->origin()); // Scroll the horizontal scrollbar. ASSERT_TRUE(scroll_view_->horizontal_scroll_bar()); scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), 1); EXPECT_EQ(gfx::Vector2d(-1, 0), test_api.IntegralViewOffset()); EXPECT_EQ(gfx::Point(-1, 0), header->origin()); // Scrolling the vertical scrollbar shouldn't effect the header. ASSERT_TRUE(scroll_view_->vertical_scroll_bar()); scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), 1); EXPECT_EQ(gfx::Vector2d(-1, -1), test_api.IntegralViewOffset()); EXPECT_EQ(gfx::Point(-1, 0), header->origin()); } // Test that calling ScrollToPosition() also updates the position of the // corresponding ScrollBar. TEST_F(ScrollViewTest, ScrollToPositionUpdatesScrollBar) { ScrollViewTestApi test_api(scroll_view_.get()); View* contents = InstallContents(); // Scroll the horizontal scrollbar, after which, the scroll bar thumb position // should be updated (i.e. it should be non-zero). contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); auto* scroll_bar = test_api.GetScrollBar(HORIZONTAL); ASSERT_TRUE(scroll_bar); EXPECT_TRUE(scroll_bar->GetVisible()); EXPECT_EQ(0, scroll_bar->GetPosition()); scroll_view_->ScrollToPosition(scroll_bar, 20); EXPECT_GT(scroll_bar->GetPosition(), 0); // Scroll the vertical scrollbar. contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); scroll_bar = test_api.GetScrollBar(VERTICAL); ASSERT_TRUE(scroll_bar); EXPECT_TRUE(scroll_bar->GetVisible()); EXPECT_EQ(0, scroll_bar->GetPosition()); scroll_view_->ScrollToPosition(scroll_bar, 20); EXPECT_GT(scroll_bar->GetPosition(), 0); } // Test that calling ScrollToPosition() also updates the position of the // child view even when the horizontal scrollbar is hidden. TEST_F(ScrollViewTest, ScrollToPositionUpdatesWithHiddenHorizontalScrollBar) { scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); ScrollViewTestApi test_api(scroll_view_.get()); View* contents = InstallContents(); contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); auto* scroll_bar = test_api.GetScrollBar(HORIZONTAL); ASSERT_TRUE(scroll_bar); EXPECT_FALSE(scroll_bar->GetVisible()); // We can't rely on the scrollbar, which may not be updated as it's not // visible, but we can check the scroll offset itself. EXPECT_EQ(0, test_api.CurrentOffset().x()); scroll_view_->ScrollToPosition(scroll_bar, 20); EXPECT_GT(test_api.CurrentOffset().x(), 0); } // Test that calling ScrollToPosition() also updates the position of the // child view even when the horizontal scrollbar is hidden. TEST_F(ScrollViewTest, ScrollToPositionUpdatesWithHiddenVerticalScrollBar) { scroll_view_->SetVerticalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); ScrollViewTestApi test_api(scroll_view_.get()); View* contents = InstallContents(); contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); auto* scroll_bar = test_api.GetScrollBar(VERTICAL); ASSERT_TRUE(scroll_bar); EXPECT_FALSE(scroll_bar->GetVisible()); // We can't rely on the scrollbar, which may not be updated as it's not // visible, but we can check the scroll offset itself. EXPECT_EQ(0, test_api.CurrentOffset().y()); scroll_view_->ScrollToPosition(scroll_bar, 20); EXPECT_GT(test_api.CurrentOffset().y(), 0); } // Verifies ScrollRectToVisible() on the child works. TEST_F(ScrollViewTest, ScrollRectToVisible) { ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(500, 1000)); auto* contents_ptr = scroll_view_->SetContents(std::move(contents)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(0, 0), test_api.IntegralViewOffset()); // Scroll to y=405 height=10, this should make the y position of the content // at (405 + 10) - viewport_height (scroll region bottom aligned). contents_ptr->ScrollRectToVisible(gfx::Rect(0, 405, 10, 10)); const int viewport_height = test_api.contents_viewport()->height(); // Expect there to be a horizontal scrollbar, making the viewport shorter. EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight(), viewport_height); gfx::PointF offset = test_api.CurrentOffset(); EXPECT_EQ(415 - viewport_height, offset.y()); // Scroll to the current y-location and 10x10; should do nothing. contents_ptr->ScrollRectToVisible(gfx::Rect(0, offset.y(), 10, 10)); EXPECT_EQ(415 - viewport_height, test_api.CurrentOffset().y()); } // Verifies ScrollByOffset() method works as expected TEST_F(ScrollViewTest, ScrollByOffset) { // setup ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(500, 1000)); scroll_view_->SetContents(std::move(contents)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(0, 0), test_api.IntegralViewOffset()); // scroll by an offset of x=5 and y=5 scroll_view_->ScrollByOffset(gfx::PointF(5, 5)); EXPECT_EQ(test_api.CurrentOffset().x(), 5); EXPECT_EQ(test_api.CurrentOffset().y(), 5); // scroll back to the initial position scroll_view_->ScrollByOffset(gfx::PointF(-5, -5)); EXPECT_EQ(test_api.CurrentOffset().x(), 0); EXPECT_EQ(test_api.CurrentOffset().y(), 0); } // Verifies ScrollRectToVisible() scrolls the view horizontally even if the // horizontal scrollbar is hidden (but not disabled). TEST_F(ScrollViewTest, ScrollRectToVisibleWithHiddenHorizontalScrollbar) { scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(500, 1000)); auto* contents_ptr = scroll_view_->SetContents(std::move(contents)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(0, 0), test_api.IntegralViewOffset()); // Scroll to x=305 width=10, this should make the x position of the content // at (305 + 10) - viewport_width (scroll region right aligned). contents_ptr->ScrollRectToVisible(gfx::Rect(305, 0, 10, 10)); const int viewport_width = test_api.contents_viewport()->width(); // Expect there to be a vertical scrollbar, making the viewport shorter. EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), viewport_width); gfx::PointF offset = test_api.CurrentOffset(); EXPECT_EQ(315 - viewport_width, offset.x()); // Scroll to the current x-location and 10x10; should do nothing. contents_ptr->ScrollRectToVisible(gfx::Rect(offset.x(), 0, 10, 10)); EXPECT_EQ(315 - viewport_width, test_api.CurrentOffset().x()); } // Verifies ScrollRectToVisible() scrolls the view horizontally even if the // horizontal scrollbar is hidden (but not disabled). TEST_F(ScrollViewTest, ScrollRectToVisibleWithHiddenVerticalScrollbar) { scroll_view_->SetVerticalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(1000, 500)); auto* contents_ptr = scroll_view_->SetContents(std::move(contents)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(0, 0), test_api.IntegralViewOffset()); // Scroll to y=305 height=10, this should make the y position of the content // at (305 + 10) - viewport_height (scroll region bottom aligned). contents_ptr->ScrollRectToVisible(gfx::Rect(0, 305, 10, 10)); const int viewport_height = test_api.contents_viewport()->height(); // Expect there to be a vertical scrollbar, making the viewport shorter. EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight(), viewport_height); gfx::PointF offset = test_api.CurrentOffset(); EXPECT_EQ(315 - viewport_height, offset.y()); // Scroll to the current x-location and 10x10; should do nothing. contents_ptr->ScrollRectToVisible(gfx::Rect(0, offset.y(), 10, 10)); EXPECT_EQ(315 - viewport_height, test_api.CurrentOffset().y()); } // Verifies that child scrolls into view when it's focused. TEST_F(ScrollViewTest, ScrollChildToVisibleOnFocus) { ScrollViewTestApi test_api(scroll_view_.get()); auto contents = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(500, 1000)); auto* contents_ptr = scroll_view_->SetContents(std::move(contents)); auto child = std::make_unique<FixedView>(); child->SetPreferredSize(gfx::Size(10, 10)); child->SetPosition(gfx::Point(0, 405)); auto* child_ptr = contents_ptr->AddChildView(std::move(child)); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 100)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(), test_api.IntegralViewOffset()); // Set focus to the child control. This should cause the control to scroll to // y=405 height=10. Like the above test, this should make the y position of // the content at (405 + 10) - viewport_height (scroll region bottom aligned). child_ptr->SetFocus(); const int viewport_height = test_api.contents_viewport()->height(); // Expect there to be a horizontal scrollbar, making the viewport shorter. EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight(), viewport_height); gfx::PointF offset = test_api.CurrentOffset(); EXPECT_EQ(415 - viewport_height, offset.y()); } // Verifies that ScrollView scrolls into view when its contents root is focused. TEST_F(ScrollViewTest, ScrollViewToVisibleOnContentsRootFocus) { ScrollViewTestApi outer_test_api(scroll_view_.get()); auto outer_contents = std::make_unique<CustomView>(); outer_contents->SetPreferredSize(gfx::Size(500, 1000)); auto* outer_contents_ptr = scroll_view_->SetContents(std::move(outer_contents)); auto inner_scroll_view = std::make_unique<ScrollView>(); auto* inner_scroll_view_ptr = outer_contents_ptr->AddChildView(std::move(inner_scroll_view)); ScrollViewTestApi inner_test_api(inner_scroll_view_ptr); auto inner_contents = std::make_unique<FixedView>(); inner_contents->SetPreferredSize(gfx::Size(500, 1000)); auto* inner_contents_ptr = inner_scroll_view_ptr->SetContents(std::move(inner_contents)); inner_scroll_view_ptr->SetBoundsRect(gfx::Rect(0, 510, 100, 100)); views::test::RunScheduledLayout(inner_scroll_view_ptr); EXPECT_EQ(gfx::Vector2d(), inner_test_api.IntegralViewOffset()); scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 200, 200)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Vector2d(), outer_test_api.IntegralViewOffset()); // Scroll the inner scroll view to y=405 height=10. This should make the y // position of the inner content at (405 + 10) - inner_viewport_height // (scroll region bottom aligned). The outer scroll view should not scroll. inner_contents_ptr->ScrollRectToVisible(gfx::Rect(0, 405, 10, 10)); const int inner_viewport_height = inner_test_api.contents_viewport()->height(); gfx::PointF inner_offset = inner_test_api.CurrentOffset(); EXPECT_EQ(415 - inner_viewport_height, inner_offset.y()); gfx::PointF outer_offset = outer_test_api.CurrentOffset(); EXPECT_EQ(0, outer_offset.y()); // Set focus to the inner scroll view's contents root. This should cause the // outer scroll view to scroll to y=510 height=100 so that the y position of // the outer content is at (510 + 100) - outer_viewport_height (scroll region // bottom aligned). The inner scroll view should not scroll. inner_contents_ptr->SetFocus(); const int outer_viewport_height = outer_test_api.contents_viewport()->height(); inner_offset = inner_test_api.CurrentOffset(); EXPECT_EQ(415 - inner_viewport_height, inner_offset.y()); outer_offset = outer_test_api.CurrentOffset(); EXPECT_EQ(610 - outer_viewport_height, outer_offset.y()); } // Verifies ClipHeightTo() uses the height of the content when it is between the // minimum and maximum height values. TEST_F(ScrollViewTest, ClipHeightToNormalContentHeight) { scroll_view_->ClipHeightTo(kMinHeight, kMaxHeight); const int kNormalContentHeight = 75; scroll_view_->SetContents(std::make_unique<views::StaticSizedView>( gfx::Size(kWidth, kNormalContentHeight))); EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), scroll_view_->GetPreferredSize()); scroll_view_->SizeToPreferredSize(); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), scroll_view_->contents()->size()); EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), scroll_view_->size()); } // Verifies ClipHeightTo() uses the minimum height when the content is shorter // than the minimum height value. TEST_F(ScrollViewTest, ClipHeightToShortContentHeight) { scroll_view_->ClipHeightTo(kMinHeight, kMaxHeight); const int kShortContentHeight = 10; View* contents = scroll_view_->SetContents(std::make_unique<views::StaticSizedView>( gfx::Size(kWidth, kShortContentHeight))); EXPECT_EQ(gfx::Size(kWidth, kMinHeight), scroll_view_->GetPreferredSize()); scroll_view_->SizeToPreferredSize(); views::test::RunScheduledLayout(scroll_view_.get()); // Layered scrolling requires the contents to fill the viewport. if (contents->layer()) { EXPECT_EQ(gfx::Size(kWidth, kMinHeight), scroll_view_->contents()->size()); } else { EXPECT_EQ(gfx::Size(kWidth, kShortContentHeight), scroll_view_->contents()->size()); } EXPECT_EQ(gfx::Size(kWidth, kMinHeight), scroll_view_->size()); } // Verifies ClipHeightTo() uses the maximum height when the content is longer // thamn the maximum height value. TEST_F(ScrollViewTest, ClipHeightToTallContentHeight) { scroll_view_->ClipHeightTo(kMinHeight, kMaxHeight); const int kTallContentHeight = 1000; scroll_view_->SetContents(std::make_unique<views::StaticSizedView>( gfx::Size(kWidth, kTallContentHeight))); EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view_->GetPreferredSize()); scroll_view_->SizeToPreferredSize(); views::test::RunScheduledLayout(scroll_view_.get()); // The width may be less than kWidth if the scroll bar takes up some width. EXPECT_GE(kWidth, scroll_view_->contents()->width()); EXPECT_EQ(kTallContentHeight, scroll_view_->contents()->height()); EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view_->size()); } // Verifies that when ClipHeightTo() produces a scrollbar, it reduces the width // of the inner content of the ScrollView. TEST_F(ScrollViewTest, ClipHeightToScrollbarUsesWidth) { scroll_view_->ClipHeightTo(kMinHeight, kMaxHeight); // Create a view that will be much taller than it is wide. scroll_view_->SetContents( std::make_unique<views::ProportionallySizedView>(1000)); // Without any width, it will default to 0,0 but be overridden by min height. scroll_view_->SizeToPreferredSize(); EXPECT_EQ(gfx::Size(0, kMinHeight), scroll_view_->GetPreferredSize()); gfx::Size new_size(kWidth, scroll_view_->GetHeightForWidth(kWidth)); scroll_view_->SetSize(new_size); views::test::RunScheduledLayout(scroll_view_.get()); int expected_width = kWidth - scroll_view_->GetScrollBarLayoutWidth(); EXPECT_EQ(scroll_view_->contents()->size().width(), expected_width); EXPECT_EQ(scroll_view_->contents()->size().height(), 1000 * expected_width); EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view_->size()); } // Verifies ClipHeightTo() updates the ScrollView's preferred size. TEST_F(ScrollViewTest, ClipHeightToUpdatesPreferredSize) { auto contents_view = std::make_unique<View>(); contents_view->SetPreferredSize(gfx::Size(100, 100)); scroll_view_->SetContents(std::move(contents_view)); EXPECT_FALSE(scroll_view_->is_bounded()); constexpr int kMinHeight1 = 20; constexpr int kMaxHeight1 = 80; scroll_view_->ClipHeightTo(kMinHeight1, kMaxHeight1); EXPECT_TRUE(scroll_view_->is_bounded()); EXPECT_EQ(scroll_view_->GetPreferredSize().height(), kMaxHeight1); constexpr int kMinHeight2 = 200; constexpr int kMaxHeight2 = 300; scroll_view_->ClipHeightTo(kMinHeight2, kMaxHeight2); EXPECT_EQ(scroll_view_->GetPreferredSize().height(), kMinHeight2); } TEST_F(ScrollViewTest, CornerViewVisibility) { View* contents = InstallContents(); View* corner_view = ScrollViewTestApi(scroll_view_.get()).corner_view(); contents->SetBounds(0, 0, 200, 200); InvalidateAndRunScheduledLayoutOnScrollView(); // Corner view should not exist if using overlay scrollbars. if (scroll_view_->vertical_scroll_bar()->OverlapsContent()) { EXPECT_FALSE(corner_view->parent()); return; } // Corner view should be visible when both scrollbars are visible. EXPECT_EQ(scroll_view_.get(), corner_view->parent()); EXPECT_TRUE(corner_view->GetVisible()); // Corner view should be aligned to the scrollbars. EXPECT_EQ(scroll_view_->vertical_scroll_bar()->x(), corner_view->x()); EXPECT_EQ(scroll_view_->horizontal_scroll_bar()->y(), corner_view->y()); EXPECT_EQ(scroll_view_->GetScrollBarLayoutWidth(), corner_view->width()); EXPECT_EQ(scroll_view_->GetScrollBarLayoutHeight(), corner_view->height()); // Corner view should be removed when only the vertical scrollbar is visible. contents->SetBounds(0, 0, 50, 200); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_FALSE(corner_view->parent()); // ... or when only the horizontal scrollbar is visible. contents->SetBounds(0, 0, 200, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_FALSE(corner_view->parent()); // ... or when no scrollbar is visible. contents->SetBounds(0, 0, 50, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_FALSE(corner_view->parent()); // Corner view should reappear when both scrollbars reappear. contents->SetBounds(0, 0, 200, 200); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(scroll_view_.get(), corner_view->parent()); EXPECT_TRUE(corner_view->GetVisible()); } // This test needs a widget so that color changes will be reflected. TEST_F(WidgetScrollViewTest, ChildWithLayerTest) { auto contents_ptr = std::make_unique<View>(); auto* contents = contents_ptr.get(); ScrollView* scroll_view = AddScrollViewWithContents(std::move(contents_ptr)); ScrollViewTestApi test_api(scroll_view); if (test_api.contents_viewport()->layer()) return; View* child = contents->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(ui::LAYER_TEXTURED); ASSERT_TRUE(test_api.contents_viewport()->layer()); // The default ScrollView color is opaque, so that fills bounds opaquely // should be true. EXPECT_TRUE(test_api.contents_viewport()->layer()->fills_bounds_opaquely()); // Setting a absl::nullopt color should make fills opaquely false. scroll_view->SetBackgroundColor(absl::nullopt); EXPECT_FALSE(test_api.contents_viewport()->layer()->fills_bounds_opaquely()); child->DestroyLayer(); EXPECT_FALSE(test_api.contents_viewport()->layer()); child->AddChildView(std::make_unique<View>()); EXPECT_FALSE(test_api.contents_viewport()->layer()); child->SetPaintToLayer(ui::LAYER_TEXTURED); EXPECT_TRUE(test_api.contents_viewport()->layer()); } // Validates that if a child of a ScrollView adds a layer, then a layer // is not added to the ScrollView's viewport. TEST_F(ScrollViewTest, DontCreateLayerOnViewportIfLayerOnScrollViewCreated) { View* contents = InstallContents(); ScrollViewTestApi test_api(scroll_view_.get()); if (test_api.contents_viewport()->layer()) return; scroll_view_->SetPaintToLayer(); View* child = contents->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(ui::LAYER_TEXTURED); EXPECT_FALSE(test_api.contents_viewport()->layer()); } // Validates if the contents_viewport uses correct layer type when adding views // with different types of layers. TEST_F(ScrollViewTest, ContentsViewportLayerUsed_ScrollWithLayersDisabled) { // Disabling scroll_with_layers feature explicitly. ScrollView scroll_view(ScrollView::ScrollWithLayers::kDisabled); ScrollViewTestApi test_api(&scroll_view); View* contents = scroll_view.SetContents(std::make_unique<View>()); ASSERT_FALSE(test_api.contents_viewport()->layer()); View* child = contents->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(); // When contents does not have a layer, contents_viewport is TEXTURED layer. EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); contents->SetPaintToLayer(); // When contents is a TEXTURED layer. EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_NOT_DRAWN); contents->SetPaintToLayer(ui::LAYER_NOT_DRAWN); // When contents is a NOT_DRAWN layer. EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); } // Validates the layer of contents_viewport_, when contents_ does not have a // layer. TEST_F( ScrollViewTest, ContentsViewportLayerWhenContentsDoesNotHaveLayer_ScrollWithLayersDisabled) { // Disabling scroll_with_layers feature explicitly. ScrollView scroll_view(ScrollView::ScrollWithLayers::kDisabled); ScrollViewTestApi test_api(&scroll_view); auto contents = std::make_unique<View>(); View* child = contents->AddChildView(std::make_unique<View>()); contents->AddChildView(std::make_unique<View>()); scroll_view.SetContents(std::move(contents)); // No layer needed for contents_viewport since no descendant view has a layer. EXPECT_FALSE(test_api.contents_viewport()->layer()); child->SetPaintToLayer(); // TEXTURED layer needed for contents_viewport since a descendant view has a // layer. EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); } // Validates if scroll_with_layers is enabled, we disallow to change the layer // of contents_ once the contents of ScrollView are set. TEST_F( ScrollViewTest, ContentsLayerCannotBeChangedAfterContentsAreSet_ScrollWithLayersEnabled) { ScrollView scroll_view(ScrollView::ScrollWithLayers::kEnabled); ScrollViewTestApi test_api(&scroll_view); View* contents = scroll_view.SetContents(std::make_unique<View>()); EXPECT_DCHECK_DEATH(contents->SetPaintToLayer(ui::LAYER_NOT_DRAWN)); } // Validates if scroll_with_layers is disabled, we can change the layer of // contents_ once the contents of ScrollView are set. TEST_F(ScrollViewTest, ContentsLayerCanBeChangedAfterContentsAreSet_ScrollWithLayersDisabled) { ScrollView scroll_view(ScrollView::ScrollWithLayers::kDisabled); ScrollViewTestApi test_api(&scroll_view); View* contents = scroll_view.SetContents(std::make_unique<View>()); ASSERT_NO_FATAL_FAILURE(contents->SetPaintToLayer()); } // Validates if the content of contents_viewport is changed, a correct layer is // used for contents_viewport. TEST_F( ScrollViewTest, ContentsViewportLayerUsedWhenScrollViewContentsAreChanged_ScrollWithLayersDisabled) { // Disabling scroll_with_layers feature explicitly. ScrollView scroll_view(ScrollView::ScrollWithLayers::kDisabled); ScrollViewTestApi test_api(&scroll_view); auto contents = std::make_unique<View>(); contents->AddChildView(std::make_unique<View>()); scroll_view.SetContents(std::move(contents)); // Replacing the old contents of scroll view. auto a_view = std::make_unique<View>(); a_view->AddChildView(std::make_unique<View>()); View* child = a_view->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(); scroll_view.SetContents(std::move(a_view)); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); } // Validates correct behavior of layers used for contents_viewport used when // scroll with layers is enabled. TEST_F(ScrollViewTest, ContentsViewportLayerUsed_ScrollWithLayersEnabled) { ScrollView scroll_view(ScrollView::ScrollWithLayers::kEnabled); ScrollViewTestApi test_api(&scroll_view); // scroll_with_layer feature ensures that contents_viewport always have a // layer. ASSERT_TRUE(test_api.contents_viewport()->layer()); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_NOT_DRAWN); // scroll_with_layer feature enables a layer on content before adding to // contents_viewport_. View* contents = scroll_view.SetContents(std::make_unique<View>()); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_NOT_DRAWN); View* child = contents->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_NOT_DRAWN); } // Validates if correct layers are used for contents_viewport used when // ScrollView enables a NOT_DRAWN layer on contents when scroll with layers in // enabled. TEST_F( ScrollViewTest, ContentsViewportLayerUsedWhenNotDrawnUsedForContents_ScrollWithLayersEnabled) { ScrollView scroll_view(ScrollView::ScrollWithLayers::kEnabled); ScrollViewTestApi test_api(&scroll_view); // scroll_with_layer feature ensures that contents_viewport always have a // layer. ASSERT_TRUE(test_api.contents_viewport()->layer()); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_NOT_DRAWN); // changing the layer type that the scrollview enables on contents. scroll_view.SetContentsLayerType(ui::LAYER_NOT_DRAWN); View* contents = scroll_view.SetContents(std::make_unique<View>()); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); View* child = contents->AddChildView(std::make_unique<View>()); child->SetPaintToLayer(); EXPECT_EQ(test_api.contents_viewport()->layer()->type(), ui::LAYER_TEXTURED); } TEST_F(ScrollViewTest, ContentsViewportLayerHasRoundedCorners_ScrollWithLayersEnabled) { ScrollView scroll_view(ScrollView::ScrollWithLayers::kEnabled); ScrollViewTestApi test_api(&scroll_view); ASSERT_TRUE(test_api.contents_viewport()->layer()); const gfx::RoundedCornersF corner_radii = gfx::RoundedCornersF{16}; scroll_view.SetViewportRoundedCornerRadius(corner_radii); EXPECT_EQ(test_api.contents_viewport()->layer()->rounded_corner_radii(), corner_radii); } #if BUILDFLAG(IS_MAC) // Tests the overlay scrollbars on Mac. Ensure that they show up properly and // do not overlap each other. TEST_F(ScrollViewTest, CocoaOverlayScrollBars) { SetOverlayScrollersEnabled(true); View* contents = InstallContents(); // Size the contents such that vertical scrollbar is needed. // Since it is overlaid, the ViewPort size should match the ScrollView. contents->SetBounds(0, 0, 50, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100, contents->parent()->width()); EXPECT_EQ(100, contents->parent()->height()); EXPECT_EQ(0, scroll_view_->GetScrollBarLayoutWidth()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); // Size the contents such that horizontal scrollbar is needed. contents->SetBounds(0, 0, 400, 50); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100, contents->parent()->width()); EXPECT_EQ(100, contents->parent()->height()); EXPECT_EQ(0, scroll_view_->GetScrollBarLayoutHeight()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, false); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); // Both horizontal and vertical scrollbars. contents->SetBounds(0, 0, 300, 400); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(100, contents->parent()->width()); EXPECT_EQ(100, contents->parent()->height()); EXPECT_EQ(0, scroll_view_->GetScrollBarLayoutWidth()); EXPECT_EQ(0, scroll_view_->GetScrollBarLayoutHeight()); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); // Make sure the horizontal and vertical scrollbars don't overlap each other. gfx::Rect vert_bounds = scroll_view_->vertical_scroll_bar()->bounds(); gfx::Rect horiz_bounds = scroll_view_->horizontal_scroll_bar()->bounds(); EXPECT_EQ(vert_bounds.x(), horiz_bounds.right()); EXPECT_EQ(horiz_bounds.y(), vert_bounds.bottom()); // Switch to the non-overlay style and check that the ViewPort is now sized // to be smaller, and ScrollbarWidth and ScrollbarHeight are non-zero. SetOverlayScrollersEnabled(false); EXPECT_TRUE(ViewTestApi(scroll_view_.get()).needs_layout()); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(100 - VerticalScrollBarWidth(), contents->parent()->width()); EXPECT_EQ(100 - HorizontalScrollBarHeight(), contents->parent()->height()); EXPECT_NE(0, VerticalScrollBarWidth()); EXPECT_NE(0, HorizontalScrollBarHeight()); } // Test that overlay scroll bars will only process events when visible. TEST_F(WidgetScrollViewTest, OverlayScrollBarsCannotProcessEventsWhenTransparent) { // Allow expectations to distinguish between fade outs and immediate changes. ui::ScopedAnimationDurationScaleMode really_animate( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); SetUseOverlayScrollers(); ScrollView* scroll_view = AddScrollViewWithContentSize( gfx::Size(kDefaultWidth * 5, kDefaultHeight * 5)); ScrollViewTestApi test_api(scroll_view); ScrollBar* scroll_bar = test_api.GetScrollBar(HORIZONTAL); // Verify scroll bar is unable to process events. EXPECT_FALSE(scroll_bar->GetCanProcessEventsWithinSubtree()); ui::test::EventGenerator generator( GetContext(), scroll_view->GetWidget()->GetNativeWindow()); generator.GenerateTrackpadRest(); // Since the scroll bar will become visible, it should now be able to process // events. EXPECT_TRUE(scroll_bar->GetCanProcessEventsWithinSubtree()); } // Test overlay scrollbar behavior when just resting fingers on the trackpad. TEST_F(WidgetScrollViewTest, ScrollersOnRest) { // Allow expectations to distinguish between fade outs and immediate changes. ui::ScopedAnimationDurationScaleMode really_animate( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); const float kMaxOpacity = 0.8f; // Constant from cocoa_scroll_bar.mm. SetUseOverlayScrollers(); // Set up with both scrollers. ScrollView* scroll_view = AddScrollViewWithContentSize( gfx::Size(kDefaultWidth * 5, kDefaultHeight * 5)); ScrollViewTestApi test_api(scroll_view); ScrollBar* bar[]{test_api.GetScrollBar(HORIZONTAL), test_api.GetScrollBar(VERTICAL)}; base::RetainingOneShotTimer* hide_timer[] = { test_api.GetScrollBarHideTimer(HORIZONTAL), test_api.GetScrollBarHideTimer(VERTICAL)}; EXPECT_EQ(0, bar[HORIZONTAL]->layer()->opacity()); EXPECT_EQ(0, bar[VERTICAL]->layer()->opacity()); ui::test::EventGenerator generator( GetContext(), scroll_view->GetWidget()->GetNativeWindow()); generator.GenerateTrackpadRest(); // Scrollers should be max opacity without an animation. EXPECT_EQ(kMaxOpacity, bar[HORIZONTAL]->layer()->opacity()); EXPECT_EQ(kMaxOpacity, bar[VERTICAL]->layer()->opacity()); EXPECT_FALSE(hide_timer[HORIZONTAL]->IsRunning()); EXPECT_FALSE(hide_timer[VERTICAL]->IsRunning()); generator.CancelTrackpadRest(); // Scrollers should start fading out, but only after a delay. for (ScrollBarOrientation orientation : {HORIZONTAL, VERTICAL}) { EXPECT_EQ(kMaxOpacity, bar[orientation]->layer()->GetTargetOpacity()); EXPECT_TRUE(hide_timer[orientation]->IsRunning()); // Trigger the timer. Should then be fading out. hide_timer[orientation]->user_task().Run(); hide_timer[orientation]->Stop(); EXPECT_EQ(0, bar[orientation]->layer()->GetTargetOpacity()); } // Rest again. generator.GenerateTrackpadRest(); EXPECT_EQ(kMaxOpacity, bar[HORIZONTAL]->layer()->GetTargetOpacity()); EXPECT_EQ(kMaxOpacity, bar[VERTICAL]->layer()->GetTargetOpacity()); // Scroll vertically. const float y_offset = 3; const int kSteps = 1; const int kNnumFingers = 2; generator.ScrollSequence(generator.current_screen_location(), base::TimeDelta(), 0, y_offset, kSteps, kNnumFingers); // Horizontal scroller should start fading out immediately. EXPECT_EQ(kMaxOpacity, bar[HORIZONTAL]->layer()->opacity()); EXPECT_EQ(0, bar[HORIZONTAL]->layer()->GetTargetOpacity()); EXPECT_FALSE(hide_timer[HORIZONTAL]->IsRunning()); // Vertical should remain visible, but ready to fade out after a delay. EXPECT_EQ(kMaxOpacity, bar[VERTICAL]->layer()->opacity()); EXPECT_EQ(kMaxOpacity, bar[VERTICAL]->layer()->GetTargetOpacity()); EXPECT_TRUE(hide_timer[VERTICAL]->IsRunning()); // Scrolling should have occurred. EXPECT_EQ(gfx::PointF(0, y_offset), test_api.CurrentOffset()); // Then, scrolling horizontally should show the horizontal scroller. The // vertical scroller should still be visible, running its hide timer. const float x_offset = 5; generator.ScrollSequence(generator.current_screen_location(), base::TimeDelta(), x_offset, 0, kSteps, kNnumFingers); for (ScrollBarOrientation orientation : {HORIZONTAL, VERTICAL}) { EXPECT_EQ(kMaxOpacity, bar[orientation]->layer()->opacity()); EXPECT_EQ(kMaxOpacity, bar[orientation]->layer()->GetTargetOpacity()); EXPECT_TRUE(hide_timer[orientation]->IsRunning()); } // Now scrolling has occurred in both directions. EXPECT_EQ(gfx::PointF(x_offset, y_offset), test_api.CurrentOffset()); } #endif // BUILDFLAG(IS_MAC) // Test that increasing the size of the viewport "below" scrolled content causes // the content to scroll up so that it still fills the viewport. TEST_F(ScrollViewTest, ConstrainScrollToBounds) { ScrollViewTestApi test_api(scroll_view_.get()); View* contents = InstallContents(); contents->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(gfx::PointF(), test_api.CurrentOffset()); // Scroll as far as it goes and query location to discount scroll bars. contents->ScrollRectToVisible(gfx::Rect(300, 300, 1, 1)); const gfx::PointF fully_scrolled = test_api.CurrentOffset(); EXPECT_NE(gfx::PointF(), fully_scrolled); // Making the viewport 55 pixels taller should scroll up the same amount. scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 100, 155)); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(fully_scrolled.y() - 55, test_api.CurrentOffset().y()); EXPECT_EQ(fully_scrolled.x(), test_api.CurrentOffset().x()); // And 77 pixels wider should scroll left. Also make it short again: the y- // offset from the last change should remain. scroll_view_->SetBoundsRect(gfx::Rect(0, 0, 177, 100)); InvalidateAndRunScheduledLayoutOnScrollView(); EXPECT_EQ(fully_scrolled.y() - 55, test_api.CurrentOffset().y()); EXPECT_EQ(fully_scrolled.x() - 77, test_api.CurrentOffset().x()); } // Calling Layout on ScrollView should not reset the scroll location. TEST_F(ScrollViewTest, ContentScrollNotResetOnLayout) { ScrollViewTestApi test_api(scroll_view_.get()); auto* contents = scroll_view_->SetContents(std::make_unique<CustomView>()); contents->SetPreferredSize(gfx::Size(300, 300)); scroll_view_->ClipHeightTo(0, 150); scroll_view_->SizeToPreferredSize(); // ScrollView preferred width matches that of |contents|, with the height // capped at the value we clipped to. EXPECT_EQ(gfx::Size(300, 150), scroll_view_->size()); // Scroll down. scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), 25); EXPECT_EQ(25, test_api.CurrentOffset().y()); // Call Layout; no change to scroll position. views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(25, test_api.CurrentOffset().y()); // Change contents of |contents|, call Layout; still no change to scroll // position. contents->SetPreferredSize(gfx::Size(300, 500)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(25, test_api.CurrentOffset().y()); // Change |contents| to be shorter than the ScrollView's clipped height. // This /will/ change the scroll location due to ConstrainScrollToBounds. contents->SetPreferredSize(gfx::Size(300, 50)); views::test::RunScheduledLayout(scroll_view_.get()); EXPECT_EQ(0, test_api.CurrentOffset().y()); } TEST_F(ScrollViewTest, ArrowKeyScrolling) { // Set up with vertical scrollbar. auto contents = std::make_unique<FixedView>(); contents->SetPreferredSize(gfx::Size(kWidth, kMaxHeight * 5)); scroll_view_->SetContents(std::move(contents)); scroll_view_->ClipHeightTo(0, kMaxHeight); scroll_view_->SetSize(gfx::Size(kWidth, kMaxHeight)); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); // The vertical position starts at 0. ScrollViewTestApi test_api(scroll_view_.get()); EXPECT_EQ(0, test_api.IntegralViewOffset().y()); // Pressing the down arrow key scrolls down. The amount isn't important. ui::KeyEvent down_arrow(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE); EXPECT_TRUE(scroll_view_->OnKeyPressed(down_arrow)); EXPECT_GT(0, test_api.IntegralViewOffset().y()); // Pressing the up arrow key scrolls back to the origin. ui::KeyEvent up_arrow(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE); EXPECT_TRUE(scroll_view_->OnKeyPressed(up_arrow)); EXPECT_EQ(0, test_api.IntegralViewOffset().y()); } TEST_F(ScrollViewTest, ArrowKeyScrollingDisabled) { // Set up with vertical scrollbar. auto contents = std::make_unique<FixedView>(); contents->SetPreferredSize(gfx::Size(kWidth, kMaxHeight * 5)); scroll_view_->SetContents(std::move(contents)); scroll_view_->ClipHeightTo(0, kMaxHeight); scroll_view_->SetSize(gfx::Size(kWidth, kMaxHeight)); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); // Disable keyboard scrolling. scroll_view_->SetAllowKeyboardScrolling(false); // The vertical position starts at 0. ScrollViewTestApi test_api(scroll_view_.get()); EXPECT_EQ(0, test_api.IntegralViewOffset().y()); // Pressing the down arrow key does not consume the event, nor scroll. ui::KeyEvent down(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE); EXPECT_FALSE(scroll_view_->OnKeyPressed(down)); EXPECT_EQ(0, test_api.IntegralViewOffset().y()); } // Test that overflow indicators turn on appropriately. TEST_F(ScrollViewTest, VerticalOverflowIndicators) { ScrollViewTestApi test_api(scroll_view_.get()); // Set up with vertical scrollbar. auto contents = std::make_unique<FixedView>(); contents->SetPreferredSize(gfx::Size(kWidth, kMaxHeight * 5)); scroll_view_->SetContents(std::move(contents)); scroll_view_->ClipHeightTo(0, kMaxHeight); // Make sure the size is set such that no horizontal scrollbar gets shown. scroll_view_->SetSize(gfx::Size( kWidth + test_api.GetScrollBar(VERTICAL)->GetThickness(), kMaxHeight)); // Make sure the initial origin is 0,0 EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // The vertical scroll bar should be visible and the horizontal scroll bar // should not. CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); // The overflow indicator on the bottom should be visible. EXPECT_TRUE(test_api.more_content_bottom()->GetVisible()); // The overflow indicator on the top should not be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); // No other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Now scroll the view to someplace in the middle of the scrollable region. int offset = kMaxHeight * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset); EXPECT_EQ(gfx::PointF(0, offset), test_api.CurrentOffset()); // At this point, both overflow indicators on the top and bottom should be // visible. EXPECT_TRUE(test_api.more_content_top()->GetVisible()); EXPECT_TRUE(test_api.more_content_bottom()->GetVisible()); // The left and right overflow indicators should still not be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Finally scroll the view to end of the scrollable region. offset = kMaxHeight * 4; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset); EXPECT_EQ(gfx::PointF(0, offset), test_api.CurrentOffset()); // The overflow indicator on the bottom should not be visible. EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The overflow indicator on the top should be visible. EXPECT_TRUE(test_api.more_content_top()->GetVisible()); // As above, no other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); } TEST_F(ScrollViewTest, HorizontalOverflowIndicators) { const int kHeight = 100; ScrollViewTestApi test_api(scroll_view_.get()); // Set up with horizontal scrollbar. auto* contents = scroll_view_->SetContents(std::make_unique<FixedView>()); contents->SetPreferredSize(gfx::Size(kWidth * 5, kHeight)); // Make sure the size is set such that no vertical scrollbar gets shown. scroll_view_->SetSize(gfx::Size( kWidth, kHeight + test_api.GetScrollBar(HORIZONTAL)->GetThickness())); contents->SetBounds(0, 0, kWidth * 5, kHeight); // Make sure the initial origin is 0,0 EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // The horizontal scroll bar should be visible and the vertical scroll bar // should not. CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, false); // The overflow indicator on the right should be visible. EXPECT_TRUE(test_api.more_content_right()->GetVisible()); // The overflow indicator on the left should not be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); // No other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // Now scroll the view to someplace in the middle of the scrollable region. int offset = kWidth * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset); EXPECT_EQ(gfx::PointF(offset, 0), test_api.CurrentOffset()); // At this point, both overflow indicators on the left and right should be // visible. EXPECT_TRUE(test_api.more_content_left()->GetVisible()); EXPECT_TRUE(test_api.more_content_right()->GetVisible()); // The top and bottom overflow indicators should still not be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // Finally scroll the view to end of the scrollable region. offset = kWidth * 4; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset); EXPECT_EQ(gfx::PointF(offset, 0), test_api.CurrentOffset()); // The overflow indicator on the right should not be visible. EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // The overflow indicator on the left should be visible. EXPECT_TRUE(test_api.more_content_left()->GetVisible()); // As above, no other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); } TEST_F(ScrollViewTest, HorizontalVerticalOverflowIndicators) { const int kHeight = 100; ScrollViewTestApi test_api(scroll_view_.get()); // Set up with both horizontal and vertical scrollbars. auto contents = std::make_unique<FixedView>(); contents->SetPreferredSize(gfx::Size(kWidth * 5, kHeight * 5)); scroll_view_->SetContents(std::move(contents)); // Make sure the size is set such that both scrollbars are shown. scroll_view_->SetSize(gfx::Size(kWidth, kHeight)); // Make sure the initial origin is 0,0 EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // The horizontal and vertical scroll bars should be visible. CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, true); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); // The overflow indicators on the right and bottom should not be visible since // they are against the scrollbars. EXPECT_FALSE(test_api.more_content_right()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The overflow indicators on the left and top should not be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_top()->GetVisible()); // Now scroll the view to someplace in the middle of the horizontal scrollable // region. int offset_x = kWidth * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset_x); EXPECT_EQ(gfx::PointF(offset_x, 0), test_api.CurrentOffset()); // Since there is a vertical scrollbar only the overflow indicator on the left // should be visible and the one on the right should still not be visible. EXPECT_TRUE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // The top and bottom overflow indicators should still not be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // Next, scroll the view to end of the scrollable region. offset_x = kWidth * 4; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset_x); EXPECT_EQ(gfx::PointF(offset_x, 0), test_api.CurrentOffset()); // The overflow indicator on the right should still not be visible. EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // The overflow indicator on the left should be visible. EXPECT_TRUE(test_api.more_content_left()->GetVisible()); // As above, the other overflow indicators should not be visible because the // view hasn't scrolled vertically and the bottom indicator is against the // horizontal scrollbar. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // Return the view back to the horizontal origin. scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), 0); EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // The overflow indicators on the right and bottom should not be visible since // they are against the scrollbars. EXPECT_FALSE(test_api.more_content_right()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The overflow indicators on the left and top should not be visible since the // is at the origin. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_top()->GetVisible()); // Now scroll the view to somplace in the middle of the vertical scrollable // region. int offset_y = kHeight * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset_y); EXPECT_EQ(gfx::PointF(0, offset_y), test_api.CurrentOffset()); // Similar to the above, since there is a horizontal scrollbar only the // overflow indicator on the top should be visible and the one on the bottom // should still not be visible. EXPECT_TRUE(test_api.more_content_top()->GetVisible()); EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The left and right overflow indicators should still not be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Finally, for the vertical test scroll the region all the way to the end. offset_y = kHeight * 4; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset_y); EXPECT_EQ(gfx::PointF(0, offset_y), test_api.CurrentOffset()); // The overflow indicator on the bottom should still not be visible. EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The overflow indicator on the top should still be visible. EXPECT_TRUE(test_api.more_content_top()->GetVisible()); // As above, the other overflow indicators should not be visible because the // view hasn't scrolled horizontally and the right indicator is against the // vertical scrollbar. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Back to the horizontal. Scroll all the way to the end in the horizontal // direction. offset_x = kWidth * 4; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset_x); EXPECT_EQ(gfx::PointF(offset_x, offset_y), test_api.CurrentOffset()); // The overflow indicator on the bottom and right should still not be visible. EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // The overflow indicators on the top and left should now be visible. EXPECT_TRUE(test_api.more_content_top()->GetVisible()); EXPECT_TRUE(test_api.more_content_left()->GetVisible()); } TEST_F(ScrollViewTest, VerticalWithHeaderOverflowIndicators) { ScrollViewTestApi test_api(scroll_view_.get()); // Set up with vertical scrollbar and a header. auto contents = std::make_unique<FixedView>(); auto header = std::make_unique<CustomView>(); contents->SetPreferredSize(gfx::Size(kWidth, kMaxHeight * 5)); header->SetPreferredSize(gfx::Size(10, 20)); scroll_view_->SetContents(std::move(contents)); auto* header_ptr = scroll_view_->SetHeader(std::move(header)); scroll_view_->ClipHeightTo(0, kMaxHeight + header_ptr->height()); // Make sure the size is set such that no horizontal scrollbar gets shown. scroll_view_->SetSize( gfx::Size(kWidth + test_api.GetScrollBar(VERTICAL)->GetThickness(), kMaxHeight + header_ptr->height())); // Make sure the initial origin is 0,0 EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // The vertical scroll bar should be visible and the horizontal scroll bar // should not. CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, true); CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); // The overflow indicator on the bottom should be visible. EXPECT_TRUE(test_api.more_content_bottom()->GetVisible()); // The overflow indicator on the top should not be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); // No other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Now scroll the view to someplace in the middle of the scrollable region. int offset = kMaxHeight * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset); EXPECT_EQ(gfx::PointF(0, offset), test_api.CurrentOffset()); // At this point, only the overflow indicator on the bottom should be visible // because the top indicator never comes on because of the presence of the // header. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); EXPECT_TRUE(test_api.more_content_bottom()->GetVisible()); // The left and right overflow indicators should still not be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); // Finally scroll the view to end of the scrollable region. offset = test_api.GetScrollBar(VERTICAL)->GetMaxPosition(); scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset); EXPECT_EQ(gfx::PointF(0, offset), test_api.CurrentOffset()); // The overflow indicator on the bottom should not be visible now. EXPECT_FALSE(test_api.more_content_bottom()->GetVisible()); // The overflow indicator on the top should still not be visible. EXPECT_FALSE(test_api.more_content_top()->GetVisible()); // As above, no other overflow indicators should be visible. EXPECT_FALSE(test_api.more_content_left()->GetVisible()); EXPECT_FALSE(test_api.more_content_right()->GetVisible()); } TEST_F(ScrollViewTest, CustomOverflowIndicator) { const int kHeight = 100; ScrollViewTestApi test_api(scroll_view_.get()); // Set up with both horizontal and vertical scrolling. auto contents = std::make_unique<FixedView>(); contents->SetPreferredSize(gfx::Size(kWidth * 5, kHeight * 5)); scroll_view_->SetContents(std::move(contents)); // Hide both scrollbars so they don't interfere with indicator visibility. scroll_view_->SetHorizontalScrollBarMode( views::ScrollView::ScrollBarMode::kHiddenButEnabled); scroll_view_->SetVerticalScrollBarMode( views::ScrollView::ScrollBarMode::kHiddenButEnabled); // Make sure the size is set so the ScrollView is smaller than its contents // in both directions. scroll_view_->SetSize(gfx::Size(kWidth, kHeight)); // The horizontal and vertical scroll bars should not be visible. CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); CheckScrollbarVisibility(scroll_view_.get(), VERTICAL, false); // Make sure the initial origin is 0,0 EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // Now scroll the view to someplace in the middle of the scrollable region. int offset_x = kWidth * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(HORIZONTAL), offset_x); int offset_y = kHeight * 2; scroll_view_->ScrollToPosition(test_api.GetScrollBar(VERTICAL), offset_y); EXPECT_EQ(gfx::PointF(offset_x, offset_y), test_api.CurrentOffset()); // All overflow indicators should be visible. ASSERT_TRUE(test_api.more_content_right()->GetVisible()); ASSERT_TRUE(test_api.more_content_bottom()->GetVisible()); ASSERT_TRUE(test_api.more_content_left()->GetVisible()); ASSERT_TRUE(test_api.more_content_top()->GetVisible()); // This should be similar to the default separator. View* left_indicator = scroll_view_->SetCustomOverflowIndicator( OverflowIndicatorAlignment::kLeft, std::make_unique<View>(), 1, true); EXPECT_EQ(gfx::Rect(0, 0, 1, 100), left_indicator->bounds()); if (left_indicator->layer()) EXPECT_TRUE(left_indicator->layer()->fills_bounds_opaquely()); // A larger, but still reasonable, indicator that is not opaque. View* top_indicator = scroll_view_->SetCustomOverflowIndicator( OverflowIndicatorAlignment::kTop, std::make_unique<View>(), 20, false); EXPECT_EQ(gfx::Rect(0, 0, 100, 20), top_indicator->bounds()); if (top_indicator->layer()) EXPECT_FALSE(top_indicator->layer()->fills_bounds_opaquely()); // Negative thickness doesn't make sense. It should be treated like zero. View* right_indicator = scroll_view_->SetCustomOverflowIndicator( OverflowIndicatorAlignment::kRight, std::make_unique<View>(), -1, true); EXPECT_EQ(gfx::Rect(100, 0, 0, 100), right_indicator->bounds()); // Thicker than the scrollview is strange, but works as you'd expect. View* bottom_indicator = scroll_view_->SetCustomOverflowIndicator( OverflowIndicatorAlignment::kBottom, std::make_unique<View>(), 1000, true); EXPECT_EQ(gfx::Rect(0, -900, 100, 1000), bottom_indicator->bounds()); } // Ensure ScrollView::Layout succeeds if a disabled scrollbar's overlap style // does not match the other scrollbar. TEST_F(ScrollViewTest, IgnoreOverlapWithDisabledHorizontalScroll) { ScrollViewTestApi test_api(scroll_view_.get()); constexpr int kThickness = 1; // Assume horizontal scroll bar is the default and is overlapping. scroll_view_->SetHorizontalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ true, /* overlaps_content */ true, kThickness)); // Assume vertical scroll bar is custom and it we want it to not overlap. scroll_view_->SetVerticalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ false, /* overlaps_content */ false, kThickness)); // Also, let's turn off horizontal scroll bar. scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kDisabled); View* contents = InstallContents(); contents->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); InvalidateAndRunScheduledLayoutOnScrollView(); gfx::Size expected_size = scroll_view_->size(); expected_size.Enlarge(-kThickness, 0); EXPECT_EQ(expected_size, test_api.contents_viewport()->size()); } // Ensure ScrollView::Layout succeeds if a hidden but enabled scrollbar's // overlap style does not match the other scrollbar. TEST_F(ScrollViewTest, IgnoreOverlapWithHiddenHorizontalScroll) { ScrollViewTestApi test_api(scroll_view_.get()); constexpr int kThickness = 1; // Assume horizontal scroll bar is the default and is overlapping. scroll_view_->SetHorizontalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ true, /* overlaps_content */ true, kThickness)); // Assume vertical scroll bar is custom and it we want it to not overlap. scroll_view_->SetVerticalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ false, /* overlaps_content */ false, kThickness)); // Also, let's turn off horizontal scroll bar. scroll_view_->SetHorizontalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); View* contents = InstallContents(); contents->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); InvalidateAndRunScheduledLayoutOnScrollView(); gfx::Size expected_size = scroll_view_->size(); expected_size.Enlarge(-kThickness, 0); EXPECT_EQ(expected_size, test_api.contents_viewport()->size()); } // Ensure ScrollView::Layout succeeds if a disabled scrollbar's overlap style // does not match the other scrollbar. TEST_F(ScrollViewTest, IgnoreOverlapWithDisabledVerticalScroll) { ScrollViewTestApi test_api(scroll_view_.get()); constexpr int kThickness = 1; // Assume horizontal scroll bar is custom and it we want it to not overlap. scroll_view_->SetHorizontalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ true, /* overlaps_content */ false, kThickness)); // Assume vertical scroll bar is the default and is overlapping. scroll_view_->SetVerticalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ false, /* overlaps_content */ true, kThickness)); // Also, let's turn off horizontal scroll bar. scroll_view_->SetVerticalScrollBarMode(ScrollView::ScrollBarMode::kDisabled); View* contents = InstallContents(); contents->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); InvalidateAndRunScheduledLayoutOnScrollView(); gfx::Size expected_size = scroll_view_->size(); expected_size.Enlarge(0, -kThickness); EXPECT_EQ(expected_size, test_api.contents_viewport()->size()); } // Ensure ScrollView::Layout succeeds if a hidden but enabled scrollbar's // overlap style does not match the other scrollbar. TEST_F(ScrollViewTest, IgnoreOverlapWithHiddenVerticalScroll) { ScrollViewTestApi test_api(scroll_view_.get()); constexpr int kThickness = 1; // Assume horizontal scroll bar is custom and it we want it to not overlap. scroll_view_->SetHorizontalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ true, /* overlaps_content */ false, kThickness)); // Assume vertical scroll bar is the default and is overlapping. scroll_view_->SetVerticalScrollBar(std::make_unique<TestScrollBar>( /* horizontal */ false, /* overlaps_content */ true, kThickness)); // Also, let's turn off horizontal scroll bar. scroll_view_->SetVerticalScrollBarMode( ScrollView::ScrollBarMode::kHiddenButEnabled); View* contents = InstallContents(); contents->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); InvalidateAndRunScheduledLayoutOnScrollView(); gfx::Size expected_size = scroll_view_->size(); expected_size.Enlarge(0, -kThickness); EXPECT_EQ(expected_size, test_api.contents_viewport()->size()); } TEST_F(ScrollViewTest, TestSettingContentsToNull) { View* contents = InstallContents(); test::ObserveViewDeletion view_deletion{contents}; // Make sure the content is installed and working. EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); // This should be legal and not DCHECK. scroll_view_->SetContents(nullptr); // The content should now be gone. EXPECT_FALSE(scroll_view_->contents()); // The contents view should have also been deleted. EXPECT_EQ(contents, view_deletion.deleted_view()); } // Test scrolling behavior when clicking on the scroll track. TEST_F(WidgetScrollViewTest, ScrollTrackScrolling) { // Set up with a vertical scroller. ScrollView* scroll_view = AddScrollViewWithContentSize(gfx::Size(10, kDefaultHeight * 5)); ScrollViewTestApi test_api(scroll_view); ScrollBar* scroll_bar = test_api.GetScrollBar(VERTICAL); View* thumb = test_api.GetScrollBarThumb(VERTICAL); // Click in the middle of the track, ensuring it's below the thumb. const gfx::Point location = scroll_bar->bounds().CenterPoint(); EXPECT_GT(location.y(), thumb->bounds().bottom()); ui::MouseEvent press(TestLeftMouseAt(location, ui::ET_MOUSE_PRESSED)); ui::MouseEvent release(TestLeftMouseAt(location, ui::ET_MOUSE_RELEASED)); const base::OneShotTimer& timer = test_api.GetScrollBarTimer(VERTICAL); EXPECT_FALSE(timer.IsRunning()); EXPECT_EQ(0, scroll_view->GetVisibleRect().y()); scroll_bar->OnMouseEvent(&press); // Clicking the scroll track should scroll one "page". EXPECT_EQ(kDefaultHeight, scroll_view->GetVisibleRect().y()); // While the mouse is pressed, timer should trigger more scroll events. EXPECT_TRUE(timer.IsRunning()); // Upon release timer should stop (and scroll position should remain). scroll_bar->OnMouseEvent(&release); EXPECT_FALSE(timer.IsRunning()); EXPECT_EQ(kDefaultHeight, scroll_view->GetVisibleRect().y()); } // Test that LocatedEvents are transformed correctly when scrolling. TEST_F(WidgetScrollViewTest, EventLocation) { // Set up with both scrollers. auto contents = std::make_unique<CustomView>(); auto* contents_ptr = contents.get(); contents->SetPreferredSize(gfx::Size(kDefaultHeight * 5, kDefaultHeight * 5)); AddScrollViewWithContents(std::move(contents)); const gfx::Point location_in_widget(10, 10); // Click without scrolling. TestClickAt(location_in_widget); EXPECT_EQ(location_in_widget, contents_ptr->last_location()); // Scroll down a page. contents_ptr->ScrollRectToVisible( gfx::Rect(0, kDefaultHeight, 1, kDefaultHeight)); TestClickAt(location_in_widget); EXPECT_EQ(gfx::Point(10, 10 + kDefaultHeight), contents_ptr->last_location()); // Scroll right a page (and back up). contents_ptr->ScrollRectToVisible( gfx::Rect(kDefaultWidth, 0, kDefaultWidth, 1)); TestClickAt(location_in_widget); EXPECT_EQ(gfx::Point(10 + kDefaultWidth, 10), contents_ptr->last_location()); // Scroll both directions. contents_ptr->ScrollRectToVisible( gfx::Rect(kDefaultWidth, kDefaultHeight, kDefaultWidth, kDefaultHeight)); TestClickAt(location_in_widget); EXPECT_EQ(gfx::Point(10 + kDefaultWidth, 10 + kDefaultHeight), contents_ptr->last_location()); } // Ensure behavior of ScrollRectToVisible() is consistent when scrolling with // and without layers, and under LTR and RTL. TEST_P(WidgetScrollViewTestRTLAndLayers, ScrollOffsetWithoutLayers) { // Set up with both scrollers. And a nested view hierarchy like: // +-------------+ // |XX | // | +----------| // | | | // | | +-------| // | | | | // | | | etc. | // | | | | // +-------------+ // Note that "XX" indicates the size of the viewport. constexpr int kNesting = 5; constexpr int kCellWidth = kDefaultWidth; constexpr int kCellHeight = kDefaultHeight; constexpr gfx::Size kContentSize(kCellWidth * kNesting, kCellHeight * kNesting); ScrollView* scroll_view = AddScrollViewWithContentSize(kContentSize, false); ScrollViewTestApi test_api(scroll_view); EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // Sanity check that the contents has a layer iff testing layers. EXPECT_EQ(IsTestingLayers(), !!scroll_view->contents()->layer()); if (IsTestingRtl()) { // Sanity check the hit-testing logic on the root view. That is, verify that // coordinates really do flip in RTL. The difference inside the viewport is // that the flipping should occur consistently in the entire contents (not // just the visible contents), and take into account the scroll offset. EXPECT_EQ(gfx::Point(kDefaultWidth - 1, 1), HitTestInCorner(scroll_view->GetWidget()->GetRootView(), false)); EXPECT_EQ(gfx::Point(kContentSize.width() - 1, 1), HitTestInCorner(scroll_view->contents(), false)); } else { EXPECT_EQ(gfx::Point(1, 1), HitTestInCorner(scroll_view->GetWidget()->GetRootView(), false)); EXPECT_EQ(gfx::Point(1, 1), HitTestInCorner(scroll_view->contents(), false)); } // Test vertical scrolling using coordinates on the contents canvas. gfx::Rect offset(0, kCellHeight * 2, kCellWidth, kCellHeight); scroll_view->contents()->ScrollRectToVisible(offset); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); // Rely on auto-flipping for this and future HitTestInCorner() calls. EXPECT_EQ(gfx::Point(1, kCellHeight * 2 + 1), HitTestInCorner(scroll_view->contents())); // Test horizontal scrolling. offset.set_x(kCellWidth * 2); scroll_view->contents()->ScrollRectToVisible(offset); EXPECT_EQ(gfx::PointF(offset.x(), offset.y()), test_api.CurrentOffset()); EXPECT_EQ(gfx::Point(kCellWidth * 2 + 1, kCellHeight * 2 + 1), HitTestInCorner(scroll_view->contents())); // Reset the scrolling. scroll_view->contents()->ScrollRectToVisible(gfx::Rect(0, 0, 1, 1)); // Test transformations through a nested view hierarchy. View* deepest_view = scroll_view->contents(); constexpr gfx::Rect kCellRect(kCellWidth, kCellHeight, kContentSize.width(), kContentSize.height()); for (int i = 1; i < kNesting; ++i) { SCOPED_TRACE(testing::Message("Nesting = ") << i); View* child = new View; child->SetBoundsRect(kCellRect); deepest_view->AddChildView(child); deepest_view = child; // Add a view in one quadrant. Scrolling just this view should only scroll // far enough for it to become visible. That is, it should be positioned at // the bottom right of the viewport, not the top-left. But since there are // scroll bars, the scroll offset needs to go "a bit more". View* partial_view = new View; partial_view->SetSize(gfx::Size(kCellWidth / 3, kCellHeight / 3)); deepest_view->AddChildView(partial_view); partial_view->ScrollViewToVisible(); int x_offset_in_cell = kCellWidth - partial_view->width(); if (!scroll_view->horizontal_scroll_bar()->OverlapsContent()) x_offset_in_cell -= scroll_view->horizontal_scroll_bar()->GetThickness(); int y_offset_in_cell = kCellHeight - partial_view->height(); if (!scroll_view->vertical_scroll_bar()->OverlapsContent()) y_offset_in_cell -= scroll_view->vertical_scroll_bar()->GetThickness(); EXPECT_EQ(gfx::PointF(kCellWidth * i - x_offset_in_cell, kCellHeight * i - y_offset_in_cell), test_api.CurrentOffset()); // Now scroll the rest. deepest_view->ScrollViewToVisible(); EXPECT_EQ(gfx::PointF(kCellWidth * i, kCellHeight * i), test_api.CurrentOffset()); // The partial view should now be at the top-left of the viewport (top-right // in RTL). EXPECT_EQ(gfx::Point(1, 1), HitTestInCorner(partial_view)); gfx::Point origin; View::ConvertPointToWidget(partial_view, &origin); constexpr gfx::Point kTestPointRTL(kDefaultWidth - kCellWidth / 3, 0); EXPECT_EQ(IsTestingRtl() ? kTestPointRTL : gfx::Point(), origin); } // Scrolling to the deepest view should have moved the viewport so that the // (kNesting - 1) parent views are all off-screen. EXPECT_EQ( gfx::PointF(kCellWidth * (kNesting - 1), kCellHeight * (kNesting - 1)), test_api.CurrentOffset()); } // Test that views scroll offsets are in sync with the layer scroll offsets. TEST_P(WidgetScrollViewTestRTLAndLayers, ScrollOffsetUsingLayers) { // Set up with both scrollers, but don't commit the layer changes yet. ScrollView* scroll_view = AddScrollViewWithContentSize( gfx::Size(kDefaultWidth * 5, kDefaultHeight * 5), false); ScrollViewTestApi test_api(scroll_view); EXPECT_EQ(gfx::PointF(0, 0), test_api.CurrentOffset()); // UI code may request a scroll before layer changes are committed. gfx::Rect offset(0, kDefaultHeight * 2, kDefaultWidth, kDefaultHeight); scroll_view->contents()->ScrollRectToVisible(offset); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); // The following only makes sense when layered scrolling is enabled. View* container = scroll_view->contents(); EXPECT_EQ(IsTestingLayers(), !!container->layer()); if (!container->layer()) return; // Container and viewport should have layers. EXPECT_TRUE(container->layer()); EXPECT_TRUE(test_api.contents_viewport()->layer()); // In a Widget, so there should be a compositor. ui::Compositor* compositor = container->layer()->GetCompositor(); EXPECT_TRUE(compositor); // But setting on the impl side should fail since the layer isn't committed. cc::ElementId element_id = container->layer()->cc_layer_for_testing()->element_id(); EXPECT_FALSE(compositor->ScrollLayerTo(element_id, gfx::PointF(0, 0))); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); WaitForCommit(); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); // Upon commit, the impl side should report the same value too. gfx::PointF impl_offset; EXPECT_TRUE(compositor->GetScrollOffsetForLayer(element_id, &impl_offset)); EXPECT_EQ(gfx::PointF(0, offset.y()), impl_offset); // Now impl-side scrolling should work, and also update the ScrollView. offset.set_y(kDefaultHeight * 3); EXPECT_TRUE( compositor->ScrollLayerTo(element_id, gfx::PointF(0, offset.y()))); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); // Scroll via ScrollView API. Should be reflected on the impl side. offset.set_y(kDefaultHeight * 4); scroll_view->contents()->ScrollRectToVisible(offset); EXPECT_EQ(gfx::PointF(0, offset.y()), test_api.CurrentOffset()); EXPECT_TRUE(compositor->GetScrollOffsetForLayer(element_id, &impl_offset)); EXPECT_EQ(gfx::PointF(0, offset.y()), impl_offset); // Test horizontal scrolling. offset.set_x(kDefaultWidth * 2); scroll_view->contents()->ScrollRectToVisible(offset); EXPECT_EQ(gfx::PointF(offset.x(), offset.y()), test_api.CurrentOffset()); EXPECT_TRUE(compositor->GetScrollOffsetForLayer(element_id, &impl_offset)); EXPECT_EQ(gfx::PointF(offset.x(), offset.y()), impl_offset); } namespace { // Applies |scroll_event| to |scroll_view| and verifies that the event is // applied correctly whether or not compositor scrolling is enabled. static void ApplyScrollEvent(const ScrollViewTestApi& test_api, ScrollView* scroll_view, ui::ScrollEvent& scroll_event) { EXPECT_FALSE(scroll_event.handled()); EXPECT_FALSE(scroll_event.stopped_propagation()); scroll_view->OnScrollEvent(&scroll_event); // Check to see if the scroll event is handled by the scroll view. if (base::FeatureList::IsEnabled(::features::kUiCompositorScrollWithLayers)) { // If UiCompositorScrollWithLayers is enabled, the event is set handled // and its propagation is stopped. EXPECT_TRUE(scroll_event.handled()); EXPECT_TRUE(scroll_event.stopped_propagation()); } else { // If UiCompositorScrollWithLayers is disabled, the event isn't handled. // This informs Widget::OnScrollEvent() to convert to a MouseWheel event // and dispatch again. Simulate that. EXPECT_FALSE(scroll_event.handled()); EXPECT_FALSE(scroll_event.stopped_propagation()); EXPECT_EQ(gfx::PointF(), test_api.CurrentOffset()); ui::MouseWheelEvent wheel(scroll_event); scroll_view->OnMouseEvent(&wheel); } } } // namespace // Tests to see the scroll events are handled correctly in composited and // non-composited scrolling. TEST_F(WidgetScrollViewTest, CompositedScrollEvents) { // Set up with a vertical scroll bar. ScrollView* scroll_view = AddScrollViewWithContentSize(gfx::Size(10, kDefaultHeight * 5)); ScrollViewTestApi test_api(scroll_view); // Create a fake scroll event and send it to the scroll view. ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), base::TimeTicks::Now(), 0, 0, -10, 0, -10, 3); ApplyScrollEvent(test_api, scroll_view, scroll); // Check if the scroll view has been offset. EXPECT_EQ(gfx::PointF(0, 10), test_api.CurrentOffset()); } // Tests to see that transposed (treat-as-horizontal) scroll events are handled // correctly in composited and non-composited scrolling. TEST_F(WidgetScrollViewTest, CompositedTransposedScrollEvents) { // Set up with a vertical scroll bar. ScrollView* scroll_view = AddScrollViewWithContentSize(gfx::Size(kDefaultHeight * 5, 10)); scroll_view->SetTreatAllScrollEventsAsHorizontal(true); ScrollViewTestApi test_api(scroll_view); // Create a fake scroll event and send it to the scroll view. // Note that this is still a VERTICAL scroll event, but we'll be looking for // HORIZONTAL motion later because we're transposed. ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), base::TimeTicks::Now(), 0, 0, -10, 0, -10, 3); ApplyScrollEvent(test_api, scroll_view, scroll); // Check if the scroll view has been offset. EXPECT_EQ(gfx::PointF(10, 0), test_api.CurrentOffset()); } // Tests to see that transposed (treat-as-horizontal) scroll events are handled // correctly in composited and non-composited scrolling when the scroll offset // is somewhat ambiguous. This is the case where the horizontal component is // larger than the vertical. TEST_F(WidgetScrollViewTest, DISABLED_CompositedTransposedScrollEventsHorizontalComponentIsLarger) { // Set up with a vertical scroll bar. ScrollView* scroll_view = AddScrollViewWithContentSize(gfx::Size(kDefaultHeight * 5, 10)); scroll_view->SetTreatAllScrollEventsAsHorizontal(true); ScrollViewTestApi test_api(scroll_view); // Create a fake scroll event and send it to the scroll view. // This will be a horizontal scroll event but there will be a conflicting // vertical element. We should still scroll horizontally, since the horizontal // component is greater. ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), base::TimeTicks::Now(), 0, -10, 7, -10, 7, 3); ApplyScrollEvent(test_api, scroll_view, scroll); // Check if the scroll view has been offset. EXPECT_EQ(gfx::PointF(10, 0), test_api.CurrentOffset()); } // Tests to see that transposed (treat-as-horizontal) scroll events are handled // correctly in composited and non-composited scrolling when the scroll offset // is somewhat ambiguous. This is the case where the vertical component is // larger than the horizontal. TEST_F(WidgetScrollViewTest, CompositedTransposedScrollEventsVerticalComponentIsLarger) { // Set up with a vertical scroll bar. ScrollView* scroll_view = AddScrollViewWithContentSize(gfx::Size(kDefaultHeight * 5, 10)); scroll_view->SetTreatAllScrollEventsAsHorizontal(true); ScrollViewTestApi test_api(scroll_view); // Create a fake scroll event and send it to the scroll view. // This will be a vertical scroll event but there will be a conflicting // horizontal element. We should still scroll horizontally, since the vertical // component is greater. ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), base::TimeTicks::Now(), 0, 7, -10, 7, -10, 3); ApplyScrollEvent(test_api, scroll_view, scroll); // Check if the scroll view has been offset. EXPECT_EQ(gfx::PointF(10, 0), test_api.CurrentOffset()); } TEST_F(WidgetScrollViewTest, UnboundedScrollViewUsesContentPreferredSize) { auto contents = std::make_unique<View>(); constexpr gfx::Size kContentsPreferredSize(500, 500); contents->SetPreferredSize(kContentsPreferredSize); ScrollView* scroll_view = AddScrollViewWithContents(std::move(contents), true); EXPECT_EQ(kContentsPreferredSize, scroll_view->GetPreferredSize()); constexpr gfx::Insets kInsets(20); scroll_view->SetBorder(CreateEmptyBorder(kInsets)); gfx::Size preferred_size_with_insets(kContentsPreferredSize); preferred_size_with_insets.Enlarge(kInsets.width(), kInsets.height()); EXPECT_EQ(preferred_size_with_insets, scroll_view->GetPreferredSize()); } INSTANTIATE_TEST_SUITE_P(All, WidgetScrollViewTestRTLAndLayers, ::testing::Values(UiConfig::kLtr, UiConfig::kRtl, UiConfig::kLtrWithLayers, UiConfig::kRtlWithLayers), &UiConfigToString); } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scroll_view_unittest.cc
C++
unknown
108,800
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "base/i18n/rtl.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/controls/scrollbar/scroll_bar.h" namespace { // The distance the mouse can be dragged outside the bounds of the thumb during // dragging before the scrollbar will snap back to its regular position. static constexpr int kScrollThumbDragOutSnap = 100; } // namespace namespace views { BaseScrollBarThumb::BaseScrollBarThumb(ScrollBar* scroll_bar) : scroll_bar_(scroll_bar) {} BaseScrollBarThumb::~BaseScrollBarThumb() = default; void BaseScrollBarThumb::SetLength(int length) { // Make sure the thumb is never sized smaller than its minimum possible // display size. gfx::Size size = GetPreferredSize(); size.SetToMax( gfx::Size(IsHorizontal() ? length : 0, IsHorizontal() ? 0 : length)); SetSize(size); } int BaseScrollBarThumb::GetLength() const { if (IsHorizontal()) return width(); return height(); } void BaseScrollBarThumb::SetPosition(int position) { gfx::Rect thumb_bounds = bounds(); gfx::Rect track_bounds = scroll_bar_->GetTrackBounds(); if (IsHorizontal()) { thumb_bounds.set_x(track_bounds.x() + position); } else { thumb_bounds.set_y(track_bounds.y() + position); } SetBoundsRect(thumb_bounds); } int BaseScrollBarThumb::GetPosition() const { gfx::Rect track_bounds = scroll_bar_->GetTrackBounds(); if (IsHorizontal()) return x() - track_bounds.x(); return y() - track_bounds.y(); } void BaseScrollBarThumb::SetSnapBackOnDragOutside(bool snap) { snap_back_on_drag_outside_ = snap; } bool BaseScrollBarThumb::GetSnapBackOnDragOutside() const { return snap_back_on_drag_outside_; } void BaseScrollBarThumb::OnMouseEntered(const ui::MouseEvent& event) { SetState(Button::STATE_HOVERED); } void BaseScrollBarThumb::OnMouseExited(const ui::MouseEvent& event) { SetState(Button::STATE_NORMAL); } bool BaseScrollBarThumb::OnMousePressed(const ui::MouseEvent& event) { mouse_offset_ = IsHorizontal() ? event.x() : event.y(); drag_start_position_ = GetPosition(); SetState(Button::STATE_PRESSED); return true; } bool BaseScrollBarThumb::OnMouseDragged(const ui::MouseEvent& event) { if (snap_back_on_drag_outside_) { // If the user moves the mouse more than |kScrollThumbDragOutSnap| outside // the bounds of the thumb, the scrollbar will snap the scroll back to the // point it was at before the drag began. if (IsHorizontal()) { if ((event.y() < y() - kScrollThumbDragOutSnap) || (event.y() > (y() + height() + kScrollThumbDragOutSnap))) { scroll_bar_->ScrollToThumbPosition(drag_start_position_, false); return true; } } else { if ((event.x() < x() - kScrollThumbDragOutSnap) || (event.x() > (x() + width() + kScrollThumbDragOutSnap))) { scroll_bar_->ScrollToThumbPosition(drag_start_position_, false); return true; } } } if (IsHorizontal()) { int thumb_x = event.x() - mouse_offset_; if (base::i18n::IsRTL()) thumb_x *= -1; scroll_bar_->ScrollToThumbPosition(GetPosition() + thumb_x, false); } else { int thumb_y = event.y() - mouse_offset_; scroll_bar_->ScrollToThumbPosition(GetPosition() + thumb_y, false); } return true; } void BaseScrollBarThumb::OnMouseReleased(const ui::MouseEvent& event) { SetState(HitTestPoint(event.location()) ? Button::STATE_HOVERED : Button::STATE_NORMAL); } void BaseScrollBarThumb::OnMouseCaptureLost() { SetState(Button::STATE_HOVERED); } Button::ButtonState BaseScrollBarThumb::GetState() const { return state_; } void BaseScrollBarThumb::SetState(Button::ButtonState state) { if (state_ == state) return; state_ = state; OnStateChanged(); } void BaseScrollBarThumb::OnStateChanged() { SchedulePaint(); } bool BaseScrollBarThumb::IsHorizontal() const { return scroll_bar_->IsHorizontal(); } BEGIN_METADATA(BaseScrollBarThumb, View) ADD_PROPERTY_METADATA(bool, SnapBackOnDragOutside); END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/base_scroll_bar_thumb.cc
C++
unknown
4,325
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_ #include "base/memory/raw_ptr.h" #include "ui/gfx/geometry/size.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/view.h" namespace gfx { class Canvas; } namespace views { class ScrollBar; /////////////////////////////////////////////////////////////////////////////// // // BaseScrollBarThumb // // A view that acts as the thumb in the scroll bar track that the user can // drag to scroll the associated contents view within the viewport. // /////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT BaseScrollBarThumb : public View { public: METADATA_HEADER(BaseScrollBarThumb); explicit BaseScrollBarThumb(ScrollBar* scroll_bar); BaseScrollBarThumb(const BaseScrollBarThumb&) = delete; BaseScrollBarThumb& operator=(const BaseScrollBarThumb&) = delete; ~BaseScrollBarThumb() override; // Sets the length (width or height) of the thumb to the specified value. void SetLength(int length); // Retrieves the length (width or height) of the thumb. int GetLength() const; // Sets the position of the thumb on the x or y axis. void SetPosition(int position); // Gets the position of the thumb on the x or y axis. int GetPosition() const; // Sets whether a drag that starts on the scroll thumb and then moves far // outside the thumb should "snap back" to the original scroll position. void SetSnapBackOnDragOutside(bool value); bool GetSnapBackOnDragOutside() const; // View overrides: gfx::Size CalculatePreferredSize() const override = 0; protected: // View overrides: void OnPaint(gfx::Canvas* canvas) override = 0; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; Button::ButtonState GetState() const; // Update our state and schedule a repaint when the mouse moves over us. void SetState(Button::ButtonState state); virtual void OnStateChanged(); bool IsHorizontal() const; ScrollBar* scroll_bar() { return scroll_bar_; } private: // The ScrollBar that owns us. raw_ptr<ScrollBar> scroll_bar_; // See SetSnapBackOnDragOutside() above. bool snap_back_on_drag_outside_ = true; int drag_start_position_ = -1; // The position of the mouse on the scroll axis relative to the top of this // View when the drag started. int mouse_offset_ = -1; // The current state of the thumb button. Button::ButtonState state_ = Button::STATE_NORMAL; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/base_scroll_bar_thumb.h
C++
unknown
3,094
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_COCOA_SCROLL_BAR_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_COCOA_SCROLL_BAR_H_ #import "base/mac/scoped_nsobject.h" #include "base/timer/timer.h" #import "components/remote_cocoa/app_shim/views_scrollbar_bridge.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/gfx/animation/slide_animation.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/views_export.h" namespace views { class CocoaScrollBarThumb; // The transparent scrollbar for Mac which overlays its contents. class VIEWS_EXPORT CocoaScrollBar : public ScrollBar, public ViewsScrollbarBridgeDelegate, public ui::ImplicitAnimationObserver, public gfx::AnimationDelegate { public: METADATA_HEADER(CocoaScrollBar); explicit CocoaScrollBar(bool horizontal); CocoaScrollBar(const CocoaScrollBar&) = delete; CocoaScrollBar& operator=(const CocoaScrollBar&) = delete; ~CocoaScrollBar() override; // ScrollBar: void Update(int viewport_size, int content_size, int contents_scroll_offset) override; void ObserveScrollEvent(const ui::ScrollEvent& event) override; // ViewsScrollbarBridgeDelegate: void OnScrollerStyleChanged() override; // View: bool GetCanProcessEventsWithinSubtree() const override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; // ui::ImplicitAnimationObserver: void OnImplicitAnimationsCompleted() override; // gfx::AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; // Returns the scroller style. NSScrollerStyle GetScrollerStyle() const { return scroller_style_; } // Returns the thickness of the scrollbar. int ScrollbarThickness() const; // Returns true if the opacity is 0.0. bool IsScrollbarFullyHidden() const; // Get the parameters for painting. ui::NativeTheme::ExtraParams GetPainterParams() const; protected: // ScrollBar: gfx::Rect GetTrackBounds() const override; // ScrollBar: int GetThickness() const override; bool OverlapsContent() const override; // View: void Layout() override; gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; private: friend class ScrollBar; // For ScrollBar::GetHideTimerForTesting(). // Methods to change the visibility of the scrollbar. void ShowScrollbar(); void HideScrollbar(); // Returns true if the scrollbar is in a hover or pressed state. bool IsHoverOrPressedState() const; // Updates the thickness of the scrollbar according to the current state of // the expand animation. void UpdateScrollbarThickness(); // Resets the scrolltrack and the thickness if the scrollbar is not hidden // and is not in a hover/pressed state. void ResetOverlayScrollbar(); // Sets the scrolltrack's visibility and then repaints it. void SetScrolltrackVisible(bool visible); // Converts GetThumb() into a CocoaScrollBarThumb object and returns it. CocoaScrollBarThumb* GetCocoaScrollBarThumb() const; // Scroller style the scrollbar is using. NSScrollerStyle scroller_style_; // Timer that will start the scrollbar's hiding animation when it reaches 0. base::RetainingOneShotTimer hide_scrollbar_timer_; // Slide animation that animates the thickness of an overlay scrollbar. // The animation expands the scrollbar as the showing animation and shrinks // the scrollbar as the hiding animation. gfx::SlideAnimation thickness_animation_; // The scroll offset from the last adjustment to the scrollbar. int last_contents_scroll_offset_ = 0; // True when the scrollbar is expanded. bool is_expanded_ = false; // True when the scrolltrack should be drawn. bool has_scrolltrack_; // True when the scrollbar has started dragging since it was last shown. // This is set to false when we begin to hide the scrollbar. bool did_start_dragging_ = false; // The bridge for NSScroller. base::scoped_nsobject<ViewsScrollbarBridge> bridge_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_COCOA_SCROLL_BAR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/cocoa_scroll_bar.h
Objective-C
unknown
4,582
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/raw_ptr.h" #import "ui/views/controls/scrollbar/cocoa_scroll_bar.h" #include "base/functional/bind.h" #include "base/i18n/rtl.h" #include "cc/paint/paint_shader.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/canvas.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" namespace views { namespace { // The thickness of the normal, overlay, and expanded overlay scrollbars. constexpr int kScrollbarThickness = 15; constexpr int kOverlayScrollbarThickness = 12; constexpr int kExpandedOverlayScrollbarThickness = 16; // Opacity of the overlay scrollbar. constexpr float kOverlayOpacity = 0.8f; } // namespace ////////////////////////////////////////////////////////////////// // CocoaScrollBarThumb class CocoaScrollBarThumb : public BaseScrollBarThumb { public: explicit CocoaScrollBarThumb(CocoaScrollBar* scroll_bar); CocoaScrollBarThumb(const CocoaScrollBarThumb&) = delete; CocoaScrollBarThumb& operator=(const CocoaScrollBarThumb&) = delete; ~CocoaScrollBarThumb() override; // Returns true if the thumb is in hovered state. bool IsStateHovered() const; // Returns true if the thumb is in pressed state. bool IsStatePressed() const; void UpdateIsMouseOverTrack(bool mouse_over_track); protected: // View: gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; private: // The CocoaScrollBar that owns us. raw_ptr<CocoaScrollBar> cocoa_scroll_bar_; // weak. }; CocoaScrollBarThumb::CocoaScrollBarThumb(CocoaScrollBar* scroll_bar) : BaseScrollBarThumb(scroll_bar), cocoa_scroll_bar_(scroll_bar) { DCHECK(scroll_bar); // This is necessary, otherwise the thumb will be rendered below the views if // those views paint to their own layers. SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); } CocoaScrollBarThumb::~CocoaScrollBarThumb() = default; bool CocoaScrollBarThumb::IsStateHovered() const { return GetState() == Button::STATE_HOVERED; } bool CocoaScrollBarThumb::IsStatePressed() const { return GetState() == Button::STATE_PRESSED; } void CocoaScrollBarThumb::UpdateIsMouseOverTrack(bool mouse_over_track) { // The state should not change if the thumb is pressed. The thumb will be // set back to its hover or normal state when the mouse is released. if (IsStatePressed()) return; SetState(mouse_over_track ? Button::STATE_HOVERED : Button::STATE_NORMAL); } gfx::Size CocoaScrollBarThumb::CalculatePreferredSize() const { int thickness = cocoa_scroll_bar_->ScrollbarThickness(); return gfx::Size(thickness, thickness); } void CocoaScrollBarThumb::OnPaint(gfx::Canvas* canvas) { auto params = cocoa_scroll_bar_->GetPainterParams(); // Set the hover state based only on the thumb. params.scrollbar_extra.is_hovering = IsStateHovered() || IsStatePressed(); ui::NativeTheme::Part thumb_part = params.scrollbar_extra.orientation == ui::NativeTheme::ScrollbarOrientation::kHorizontal ? ui::NativeTheme::kScrollbarHorizontalThumb : ui::NativeTheme::kScrollbarVerticalThumb; GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), thumb_part, ui::NativeTheme::kNormal, GetLocalBounds(), params); } bool CocoaScrollBarThumb::OnMousePressed(const ui::MouseEvent& event) { // Ignore the mouse press if the scrollbar is hidden. if (cocoa_scroll_bar_->IsScrollbarFullyHidden()) return false; return BaseScrollBarThumb::OnMousePressed(event); } void CocoaScrollBarThumb::OnMouseReleased(const ui::MouseEvent& event) { BaseScrollBarThumb::OnMouseReleased(event); scroll_bar()->OnMouseReleased(event); } void CocoaScrollBarThumb::OnMouseEntered(const ui::MouseEvent& event) { BaseScrollBarThumb::OnMouseEntered(event); scroll_bar()->OnMouseEntered(event); } void CocoaScrollBarThumb::OnMouseExited(const ui::MouseEvent& event) { // The thumb should remain pressed when dragged, even if the mouse leaves // the scrollview. The thumb will be set back to its hover or normal state // when the mouse is released. if (GetState() != Button::STATE_PRESSED) SetState(Button::STATE_NORMAL); } ////////////////////////////////////////////////////////////////// // CocoaScrollBar class CocoaScrollBar::CocoaScrollBar(bool horizontal) : ScrollBar(horizontal), hide_scrollbar_timer_(FROM_HERE, base::Milliseconds(500), base::BindRepeating(&CocoaScrollBar::HideScrollbar, base::Unretained(this))), thickness_animation_(this) { SetThumb(new CocoaScrollBarThumb(this)); bridge_.reset([[ViewsScrollbarBridge alloc] initWithDelegate:this]); scroller_style_ = [ViewsScrollbarBridge getPreferredScrollerStyle]; thickness_animation_.SetSlideDuration(base::Milliseconds(240)); SetPaintToLayer(); has_scrolltrack_ = scroller_style_ == NSScrollerStyleLegacy; layer()->SetOpacity(scroller_style_ == NSScrollerStyleOverlay ? 0.0f : 1.0f); } CocoaScrollBar::~CocoaScrollBar() { [bridge_ clearDelegate]; } ////////////////////////////////////////////////////////////////// // CocoaScrollBar, ScrollBar: gfx::Rect CocoaScrollBar::GetTrackBounds() const { return GetLocalBounds(); } ////////////////////////////////////////////////////////////////// // CocoaScrollBar, ScrollBar: int CocoaScrollBar::GetThickness() const { return ScrollbarThickness(); } bool CocoaScrollBar::OverlapsContent() const { return scroller_style_ == NSScrollerStyleOverlay; } ////////////////////////////////////////////////////////////////// // CocoaScrollBar::View: void CocoaScrollBar::Layout() { // Set the thickness of the thumb according to the track bounds. // The length of the thumb is set by ScrollBar::Update(). gfx::Rect thumb_bounds(GetThumb()->bounds()); gfx::Rect track_bounds(GetTrackBounds()); if (IsHorizontal()) { GetThumb()->SetBounds(thumb_bounds.x(), track_bounds.y(), thumb_bounds.width(), track_bounds.height()); } else { GetThumb()->SetBounds(track_bounds.x(), thumb_bounds.y(), track_bounds.width(), thumb_bounds.height()); } } gfx::Size CocoaScrollBar::CalculatePreferredSize() const { return gfx::Size(); } void CocoaScrollBar::OnPaint(gfx::Canvas* canvas) { if (!has_scrolltrack_) return; auto params = GetPainterParams(); // Transparency of the track is handled by the View opacity, so always draw // using the non-overlay path. params.scrollbar_extra.is_overlay = false; ui::NativeTheme::Part track_part = params.scrollbar_extra.orientation == ui::NativeTheme::ScrollbarOrientation::kHorizontal ? ui::NativeTheme::kScrollbarHorizontalTrack : ui::NativeTheme::kScrollbarVerticalTrack; GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), track_part, ui::NativeTheme::kNormal, GetLocalBounds(), params); } bool CocoaScrollBar::GetCanProcessEventsWithinSubtree() const { // If using overlay scrollbars, do not process events when fully hidden. return scroller_style_ == NSScrollerStyleOverlay ? !IsScrollbarFullyHidden() : ScrollBar::GetCanProcessEventsWithinSubtree(); } bool CocoaScrollBar::OnMousePressed(const ui::MouseEvent& event) { // Ignore the mouse press if the scrollbar is hidden. if (IsScrollbarFullyHidden()) return false; return ScrollBar::OnMousePressed(event); } void CocoaScrollBar::OnMouseReleased(const ui::MouseEvent& event) { ResetOverlayScrollbar(); ScrollBar::OnMouseReleased(event); } void CocoaScrollBar::OnMouseEntered(const ui::MouseEvent& event) { GetCocoaScrollBarThumb()->UpdateIsMouseOverTrack(true); if (scroller_style_ == NSScrollerStyleLegacy) return; // If the scrollbar thumb did not completely fade away, then reshow it when // the mouse enters the scrollbar thumb. if (!IsScrollbarFullyHidden()) ShowScrollbar(); // Expand the scrollbar. If the scrollbar is hidden, don't animate it. if (!is_expanded_) { SetScrolltrackVisible(true); is_expanded_ = true; if (IsScrollbarFullyHidden()) { thickness_animation_.Reset(1.0); UpdateScrollbarThickness(); } else { thickness_animation_.Show(); } } hide_scrollbar_timer_.Reset(); } void CocoaScrollBar::OnMouseExited(const ui::MouseEvent& event) { GetCocoaScrollBarThumb()->UpdateIsMouseOverTrack(false); ResetOverlayScrollbar(); } ////////////////////////////////////////////////////////////////// // CocoaScrollBar::ScrollBar: void CocoaScrollBar::Update(int viewport_size, int content_size, int contents_scroll_offset) { // TODO(tapted): Pass in overscroll amounts from the Layer and "Squish" the // scroller thumb accordingly. ScrollBar::Update(viewport_size, content_size, contents_scroll_offset); // Only reveal the scroller when |contents_scroll_offset| changes. Note this // is different to GetPosition() which can change due to layout. A layout // change can also change the offset; show the scroller in these cases. This // is consistent with WebContents (Cocoa will also show a scroller with any // mouse-initiated layout, but not programmatic size changes). if (contents_scroll_offset == last_contents_scroll_offset_) return; last_contents_scroll_offset_ = contents_scroll_offset; if (GetCocoaScrollBarThumb()->IsStatePressed()) did_start_dragging_ = true; if (scroller_style_ == NSScrollerStyleOverlay) { ShowScrollbar(); hide_scrollbar_timer_.Reset(); } } void CocoaScrollBar::ObserveScrollEvent(const ui::ScrollEvent& event) { // Do nothing if the delayed hide timer is running. This means there has been // some recent scrolling in this direction already. if (scroller_style_ != NSScrollerStyleOverlay || hide_scrollbar_timer_.IsRunning()) { return; } // Otherwise, when starting the event stream, show an overlay scrollbar to // indicate possible scroll directions, but do not start the hide timer. if (event.momentum_phase() == ui::EventMomentumPhase::MAY_BEGIN) { // Show only if the direction isn't yet known. if (event.x_offset() == 0 && event.y_offset() == 0) ShowScrollbar(); return; } // If the direction matches, do nothing. This is needed in addition to the // hide timer check because Update() is called asynchronously, after event // processing. So when |event| is the first event in a particular direction // the hide timer will not have started. if ((IsHorizontal() ? event.x_offset() : event.y_offset()) != 0) return; // Otherwise, scrolling has started, but not in this scroller direction. If // already faded out, don't start another fade animation since that would // immediately finish the first fade animation. if (layer()->GetTargetOpacity() != 0) { // If canceling rather than picking a direction, fade out after a delay. if (event.momentum_phase() == ui::EventMomentumPhase::END) hide_scrollbar_timer_.Reset(); else HideScrollbar(); // Fade out immediately. } } ////////////////////////////////////////////////////////////////// // CocoaScrollBar::ViewsScrollbarBridge: void CocoaScrollBar::OnScrollerStyleChanged() { NSScrollerStyle scroller_style = [ViewsScrollbarBridge getPreferredScrollerStyle]; if (scroller_style_ == scroller_style) return; // Cancel all of the animations. thickness_animation_.Reset(); layer()->GetAnimator()->AbortAllAnimations(); scroller_style_ = scroller_style; // Ensure that the ScrollView updates the scrollbar's layout. if (parent()) parent()->InvalidateLayout(); if (scroller_style_ == NSScrollerStyleOverlay) { // Hide the scrollbar, but don't fade out. layer()->SetOpacity(0.0f); ResetOverlayScrollbar(); GetThumb()->SchedulePaint(); } else { is_expanded_ = false; SetScrolltrackVisible(true); ShowScrollbar(); } } ////////////////////////////////////////////////////////////////// // CocoaScrollBar::ImplicitAnimationObserver: void CocoaScrollBar::OnImplicitAnimationsCompleted() { DCHECK_EQ(scroller_style_, NSScrollerStyleOverlay); ResetOverlayScrollbar(); } ////////////////////////////////////////////////////////////////// // CocoaScrollBar::AnimationDelegate: void CocoaScrollBar::AnimationProgressed(const gfx::Animation* animation) { DCHECK(is_expanded_); UpdateScrollbarThickness(); } void CocoaScrollBar::AnimationEnded(const gfx::Animation* animation) { // Remove the scrolltrack and set |is_expanded| to false at the end of // the shrink animation. if (!thickness_animation_.IsShowing()) { is_expanded_ = false; SetScrolltrackVisible(false); } } ////////////////////////////////////////////////////////////////// // CocoaScrollBar, public: int CocoaScrollBar::ScrollbarThickness() const { if (scroller_style_ == NSScrollerStyleLegacy) return kScrollbarThickness; return thickness_animation_.CurrentValueBetween( kOverlayScrollbarThickness, kExpandedOverlayScrollbarThickness); } bool CocoaScrollBar::IsScrollbarFullyHidden() const { return layer()->opacity() == 0.0f; } ui::NativeTheme::ExtraParams CocoaScrollBar::GetPainterParams() const { ui::NativeTheme::ExtraParams params; if (IsHorizontal()) { params.scrollbar_extra.orientation = ui::NativeTheme::ScrollbarOrientation::kHorizontal; } else if (base::i18n::IsRTL()) { params.scrollbar_extra.orientation = ui::NativeTheme::ScrollbarOrientation::kVerticalOnLeft; } else { params.scrollbar_extra.orientation = ui::NativeTheme::ScrollbarOrientation::kVerticalOnRight; } params.scrollbar_extra.is_overlay = GetScrollerStyle() == NSScrollerStyleOverlay; params.scrollbar_extra.scale_from_dip = 1.0f; return params; } ////////////////////////////////////////////////////////////////// // CocoaScrollBar, private: void CocoaScrollBar::HideScrollbar() { DCHECK_EQ(scroller_style_, NSScrollerStyleOverlay); // Don't disappear if the scrollbar is hovered, or pressed but not dragged. // This behavior matches the Cocoa scrollbars, but differs from the Blink // scrollbars which would just disappear. CocoaScrollBarThumb* thumb = GetCocoaScrollBarThumb(); if (IsMouseHovered() || thumb->IsStateHovered() || (thumb->IsStatePressed() && !did_start_dragging_)) { hide_scrollbar_timer_.Reset(); return; } did_start_dragging_ = false; ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator()); animation.SetTransitionDuration(base::Milliseconds(240)); animation.AddObserver(this); layer()->SetOpacity(0.0f); } void CocoaScrollBar::ShowScrollbar() { // If the scrollbar is still expanded but has not completely faded away, // then shrink it back to its original state. if (is_expanded_ && !IsHoverOrPressedState() && layer()->GetAnimator()->IsAnimatingProperty( ui::LayerAnimationElement::OPACITY)) { DCHECK_EQ(scroller_style_, NSScrollerStyleOverlay); thickness_animation_.Hide(); } // Updates the scrolltrack and repaint it, if necessary. double opacity = scroller_style_ == NSScrollerStyleOverlay ? kOverlayOpacity : 1.0f; layer()->SetOpacity(opacity); hide_scrollbar_timer_.Stop(); } bool CocoaScrollBar::IsHoverOrPressedState() const { CocoaScrollBarThumb* thumb = GetCocoaScrollBarThumb(); return thumb->IsStateHovered() || thumb->IsStatePressed() || IsMouseHovered(); } void CocoaScrollBar::UpdateScrollbarThickness() { int thickness = ScrollbarThickness(); if (IsHorizontal()) SetBounds(x(), bounds().bottom() - thickness, width(), thickness); else SetBounds(bounds().right() - thickness, y(), thickness, height()); } void CocoaScrollBar::ResetOverlayScrollbar() { if (!IsHoverOrPressedState() && IsScrollbarFullyHidden() && !thickness_animation_.IsClosing()) { if (is_expanded_) { is_expanded_ = false; thickness_animation_.Reset(); UpdateScrollbarThickness(); } SetScrolltrackVisible(false); } } void CocoaScrollBar::SetScrolltrackVisible(bool visible) { has_scrolltrack_ = visible; SchedulePaint(); } CocoaScrollBarThumb* CocoaScrollBar::GetCocoaScrollBarThumb() const { return static_cast<CocoaScrollBarThumb*>(GetThumb()); } // static base::RetainingOneShotTimer* ScrollBar::GetHideTimerForTesting( ScrollBar* scroll_bar) { return &static_cast<CocoaScrollBar*>(scroll_bar)->hide_scrollbar_timer_; } BEGIN_METADATA(CocoaScrollBar, ScrollBar) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/cocoa_scroll_bar.mm
Objective-C++
unknown
17,444
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/overlay_scroll_bar.h" #include <memory> #include "base/functional/bind.h" #include "base/i18n/rtl.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/layer.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/canvas.h" #include "ui/native_theme/overlay_scrollbar_constants_aura.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/layout/fill_layout.h" namespace views { namespace { // Total thickness of the thumb (matches visuals when hovered). constexpr int kThumbThickness = ui::kOverlayScrollbarThumbWidthPressed + ui::kOverlayScrollbarStrokeWidth; // When hovered, the thumb takes up the full width. Otherwise, it's a bit // slimmer. constexpr int kThumbHoverOffset = 4; // The layout size of the thumb stroke, in DIP. constexpr int kThumbStroke = ui::kOverlayScrollbarStrokeWidth; // The visual size of the thumb stroke, in px. constexpr int kThumbStrokeVisualSize = ui::kOverlayScrollbarStrokeWidth; } // namespace OverlayScrollBar::Thumb::Thumb(OverlayScrollBar* scroll_bar) : BaseScrollBarThumb(scroll_bar), scroll_bar_(scroll_bar) { // |scroll_bar| isn't done being constructed; it's not safe to do anything // that might reference it yet. } OverlayScrollBar::Thumb::~Thumb() = default; void OverlayScrollBar::Thumb::Init() { SetFlipCanvasOnPaintForRTLUI(true); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); // Animate all changes to the layer except the first one. OnStateChanged(); layer()->SetAnimator(ui::LayerAnimator::CreateImplicitAnimator()); } gfx::Size OverlayScrollBar::Thumb::CalculatePreferredSize() const { // The visual size of the thumb is kThumbThickness, but it slides back and // forth by kThumbHoverOffset. To make event targetting work well, expand the // width of the thumb such that it's always taking up the full width of the // track regardless of the offset. return gfx::Size(kThumbThickness + kThumbHoverOffset, kThumbThickness + kThumbHoverOffset); } void OverlayScrollBar::Thumb::OnPaint(gfx::Canvas* canvas) { const bool hovered = GetState() != Button::STATE_NORMAL; cc::PaintFlags fill_flags; fill_flags.setStyle(cc::PaintFlags::kFill_Style); fill_flags.setColor(GetColorProvider()->GetColor( hovered ? ui::kColorOverlayScrollbarFillHovered : ui::kColorOverlayScrollbarFill)); gfx::RectF fill_bounds(GetLocalBounds()); fill_bounds.Inset(gfx::InsetsF::TLBR(IsHorizontal() ? kThumbHoverOffset : 0, IsHorizontal() ? 0 : kThumbHoverOffset, 0, 0)); fill_bounds.Inset(gfx::InsetsF::TLBR(kThumbStroke, kThumbStroke, IsHorizontal() ? 0 : kThumbStroke, IsHorizontal() ? kThumbStroke : 0)); canvas->DrawRect(fill_bounds, fill_flags); cc::PaintFlags stroke_flags; stroke_flags.setStyle(cc::PaintFlags::kStroke_Style); stroke_flags.setColor(GetColorProvider()->GetColor( hovered ? ui::kColorOverlayScrollbarStrokeHovered : ui::kColorOverlayScrollbarStroke)); stroke_flags.setStrokeWidth(kThumbStrokeVisualSize); stroke_flags.setStrokeCap(cc::PaintFlags::kSquare_Cap); // The stroke is a single pixel, so we must deal with the unscaled canvas. const float dsf = canvas->UndoDeviceScaleFactor(); gfx::RectF stroke_bounds(fill_bounds); stroke_bounds.Scale(dsf); // The stroke should be aligned to the pixel center that is nearest the fill, // so outset by a half pixel. stroke_bounds.Inset(gfx::InsetsF(-kThumbStrokeVisualSize / 2.0f)); // The stroke doesn't apply to the far edge of the thumb. SkPath path; path.moveTo(gfx::PointFToSkPoint(stroke_bounds.top_right())); path.lineTo(gfx::PointFToSkPoint(stroke_bounds.origin())); path.lineTo(gfx::PointFToSkPoint(stroke_bounds.bottom_left())); if (IsHorizontal()) { path.moveTo(gfx::PointFToSkPoint(stroke_bounds.bottom_right())); path.close(); } else { path.lineTo(gfx::PointFToSkPoint(stroke_bounds.bottom_right())); } canvas->DrawPath(path, stroke_flags); } void OverlayScrollBar::Thumb::OnBoundsChanged( const gfx::Rect& previous_bounds) { scroll_bar_->Show(); // Don't start the hide countdown if the thumb is still hovered or pressed. if (GetState() == Button::STATE_NORMAL) scroll_bar_->StartHideCountdown(); } void OverlayScrollBar::Thumb::OnStateChanged() { if (GetState() == Button::STATE_NORMAL) { gfx::Transform translation; const int direction = base::i18n::IsRTL() ? -1 : 1; translation.Translate( gfx::Vector2d(IsHorizontal() ? 0 : direction * kThumbHoverOffset, IsHorizontal() ? kThumbHoverOffset : 0)); layer()->SetTransform(translation); if (GetWidget()) scroll_bar_->StartHideCountdown(); } else { layer()->SetTransform(gfx::Transform()); } SchedulePaint(); } OverlayScrollBar::OverlayScrollBar(bool horizontal) : ScrollBar(horizontal) { SetNotifyEnterExitOnChild(true); SetPaintToLayer(); layer()->SetMasksToBounds(true); layer()->SetFillsBoundsOpaquely(false); // Allow the thumb to take up the whole size of the scrollbar. Layout need // only set the thumb cross-axis coordinate; ScrollBar::Update() will set the // thumb size/offset. SetLayoutManager(std::make_unique<views::FillLayout>()); auto* thumb = new Thumb(this); SetThumb(thumb); thumb->Init(); } OverlayScrollBar::~OverlayScrollBar() = default; gfx::Insets OverlayScrollBar::GetInsets() const { return IsHorizontal() ? gfx::Insets::TLBR(-kThumbHoverOffset, 0, 0, 0) : gfx::Insets::TLBR(0, -kThumbHoverOffset, 0, 0); } void OverlayScrollBar::OnMouseEntered(const ui::MouseEvent& event) { Show(); } void OverlayScrollBar::OnMouseExited(const ui::MouseEvent& event) { StartHideCountdown(); } bool OverlayScrollBar::OverlapsContent() const { return true; } gfx::Rect OverlayScrollBar::GetTrackBounds() const { return GetContentsBounds(); } int OverlayScrollBar::GetThickness() const { return kThumbThickness; } void OverlayScrollBar::Show() { layer()->SetOpacity(1.0f); hide_timer_.Stop(); } void OverlayScrollBar::Hide() { ui::ScopedLayerAnimationSettings settings(layer()->GetAnimator()); settings.SetTransitionDuration(ui::kOverlayScrollbarFadeDuration); layer()->SetOpacity(0.0f); } void OverlayScrollBar::StartHideCountdown() { if (IsMouseHovered()) return; hide_timer_.Start( FROM_HERE, ui::kOverlayScrollbarFadeDelay, base::BindOnce(&OverlayScrollBar::Hide, base::Unretained(this))); } BEGIN_METADATA(OverlayScrollBar, ScrollBar) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/overlay_scroll_bar.cc
C++
unknown
7,078
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_ #include "base/memory/raw_ptr.h" #include "base/timer/timer.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/controls/scrollbar/scroll_bar.h" namespace views { // The transparent scrollbar which overlays its contents. class VIEWS_EXPORT OverlayScrollBar : public ScrollBar { public: METADATA_HEADER(OverlayScrollBar); explicit OverlayScrollBar(bool horizontal); OverlayScrollBar(const OverlayScrollBar&) = delete; OverlayScrollBar& operator=(const OverlayScrollBar&) = delete; ~OverlayScrollBar() override; // ScrollBar: gfx::Insets GetInsets() const override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; bool OverlapsContent() const override; gfx::Rect GetTrackBounds() const override; int GetThickness() const override; private: class Thumb : public BaseScrollBarThumb { public: explicit Thumb(OverlayScrollBar* scroll_bar); Thumb(const Thumb&) = delete; Thumb& operator=(const Thumb&) = delete; ~Thumb() override; void Init(); protected: // BaseScrollBarThumb: gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; void OnBoundsChanged(const gfx::Rect& previous_bounds) override; void OnStateChanged() override; private: raw_ptr<OverlayScrollBar> scroll_bar_; }; friend class Thumb; // Shows this (effectively, the thumb) without delay. void Show(); // Hides this with a delay. void Hide(); // Starts a countdown that hides this when it fires. void StartHideCountdown(); base::OneShotTimer hide_timer_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/overlay_scroll_bar.h
C++
unknown
2,018
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/scroll_bar.h" #include <algorithm> #include <memory> #include <string> #include "base/compiler_specific.h" #include "base/containers/flat_map.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" #include "base/no_destructor.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/widget/widget.h" namespace views { ScrollBar::~ScrollBar() = default; bool ScrollBar::IsHorizontal() const { return is_horiz_; } void ScrollBar::SetThumb(BaseScrollBarThumb* thumb) { DCHECK(!thumb_); thumb_ = thumb; AddChildView(thumb); thumb->set_context_menu_controller(this); } bool ScrollBar::ScrollByAmount(ScrollAmount amount) { auto desired_offset = GetDesiredScrollOffset(amount); if (!desired_offset) return false; SetContentsScrollOffset(desired_offset.value()); ScrollContentsToOffset(); return true; } void ScrollBar::ScrollToThumbPosition(int thumb_position, bool scroll_to_middle) { SetContentsScrollOffset(CalculateContentsOffset( static_cast<float>(thumb_position), scroll_to_middle)); ScrollContentsToOffset(); SchedulePaint(); } bool ScrollBar::ScrollByContentsOffset(int contents_offset) { int old_offset = contents_scroll_offset_; SetContentsScrollOffset(contents_scroll_offset_ - contents_offset); if (old_offset == contents_scroll_offset_) return false; ScrollContentsToOffset(); return true; } int ScrollBar::GetMaxPosition() const { return max_pos_; } int ScrollBar::GetMinPosition() const { return 0; } int ScrollBar::GetPosition() const { return thumb_->GetPosition(); } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, View implementation: bool ScrollBar::OnMousePressed(const ui::MouseEvent& event) { if (event.IsOnlyLeftMouseButton()) ProcessPressEvent(event); return true; } void ScrollBar::OnMouseReleased(const ui::MouseEvent& event) { repeater_.Stop(); } void ScrollBar::OnMouseCaptureLost() { repeater_.Stop(); } bool ScrollBar::OnKeyPressed(const ui::KeyEvent& event) { return ScrollByAmount(DetermineScrollAmountByKeyCode(event.key_code())); } bool ScrollBar::OnMouseWheel(const ui::MouseWheelEvent& event) { OnScroll(event.x_offset(), event.y_offset()); return true; } void ScrollBar::OnGestureEvent(ui::GestureEvent* event) { // If a fling is in progress, then stop the fling for any incoming gesture // event (except for the GESTURE_END event that is generated at the end of the // fling). if (scroll_animator_ && scroll_animator_->is_scrolling() && (event->type() != ui::ET_GESTURE_END || event->details().touch_points() > 1)) { scroll_animator_->Stop(); } if (event->type() == ui::ET_GESTURE_TAP_DOWN) { ProcessPressEvent(*event); event->SetHandled(); return; } if (event->type() == ui::ET_GESTURE_LONG_PRESS) { // For a long-press, the repeater started in tap-down should continue. So // return early. return; } #ifdef OHOS_DRAG_DROP if (event->type() == ui::ET_GESTURE_DRAG_LONG_PRESS) { // For a long-press, the repeater started in tap-down should continue. So // return early. return; } #endif repeater_.Stop(); if (event->type() == ui::ET_GESTURE_TAP) { // TAP_DOWN would have already scrolled some amount. So scrolling again on // TAP is not necessary. event->SetHandled(); return; } if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN) { scroll_status_ = ScrollStatus::kScrollStarted; event->SetHandled(); return; } if (event->type() == ui::ET_GESTURE_SCROLL_END) { scroll_status_ = ScrollStatus::kScrollEnded; controller()->OnScrollEnded(); event->SetHandled(); return; } // Update the |scroll_status_| to |kScrollEnded| in case the gesture sequence // ends incorrectly. if (event->type() == ui::ET_GESTURE_END && scroll_status_ != ScrollStatus::kScrollInEnding && scroll_status_ != ScrollStatus::kScrollEnded) { scroll_status_ = ScrollStatus::kScrollEnded; controller()->OnScrollEnded(); } if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { if (scroll_status_ == ScrollStatus::kScrollStarted) scroll_status_ = ScrollStatus::kScrollInProgress; float scroll_amount_f; int scroll_amount; if (IsHorizontal()) { scroll_amount_f = event->details().scroll_x() - roundoff_error_.x(); scroll_amount = base::ClampRound(scroll_amount_f); roundoff_error_.set_x(scroll_amount - scroll_amount_f); } else { scroll_amount_f = event->details().scroll_y() - roundoff_error_.y(); scroll_amount = base::ClampRound(scroll_amount_f); roundoff_error_.set_y(scroll_amount - scroll_amount_f); } if (ScrollByContentsOffset(scroll_amount)) event->SetHandled(); return; } if (event->type() == ui::ET_SCROLL_FLING_START) { scroll_status_ = ScrollStatus::kScrollInEnding; GetOrCreateScrollAnimator()->Start( IsHorizontal() ? event->details().velocity_x() : 0.f, IsHorizontal() ? 0.f : event->details().velocity_y()); event->SetHandled(); } } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, ScrollDelegate implementation: bool ScrollBar::OnScroll(float dx, float dy) { return IsHorizontal() ? ScrollByContentsOffset(dx) : ScrollByContentsOffset(dy); } void ScrollBar::OnFlingScrollEnded() { scroll_status_ = ScrollStatus::kScrollEnded; controller()->OnScrollEnded(); } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, ContextMenuController implementation: enum ScrollBarContextMenuCommands { ScrollBarContextMenuCommand_ScrollHere = 1, ScrollBarContextMenuCommand_ScrollStart, ScrollBarContextMenuCommand_ScrollEnd, ScrollBarContextMenuCommand_ScrollPageUp, ScrollBarContextMenuCommand_ScrollPageDown, ScrollBarContextMenuCommand_ScrollPrev, ScrollBarContextMenuCommand_ScrollNext }; void ScrollBar::ShowContextMenuForViewImpl(View* source, const gfx::Point& p, ui::MenuSourceType source_type) { Widget* widget = GetWidget(); gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); gfx::Point temp_pt(p.x() - widget_bounds.x(), p.y() - widget_bounds.y()); View::ConvertPointFromWidget(this, &temp_pt); context_menu_mouse_position_ = IsHorizontal() ? temp_pt.x() : temp_pt.y(); if (!menu_model_) { menu_model_ = std::make_unique<ui::SimpleMenuModel>(this); menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollHere, IDS_APP_SCROLLBAR_CXMENU_SCROLLHERE); menu_model_->AddSeparator(ui::NORMAL_SEPARATOR); menu_model_->AddItemWithStringId( ScrollBarContextMenuCommand_ScrollStart, IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFTEDGE : IDS_APP_SCROLLBAR_CXMENU_SCROLLHOME); menu_model_->AddItemWithStringId( ScrollBarContextMenuCommand_ScrollEnd, IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHTEDGE : IDS_APP_SCROLLBAR_CXMENU_SCROLLEND); menu_model_->AddSeparator(ui::NORMAL_SEPARATOR); menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPageUp, IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEUP); menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPageDown, IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEDOWN); menu_model_->AddSeparator(ui::NORMAL_SEPARATOR); menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPrev, IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFT : IDS_APP_SCROLLBAR_CXMENU_SCROLLUP); menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollNext, IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHT : IDS_APP_SCROLLBAR_CXMENU_SCROLLDOWN); } menu_runner_ = std::make_unique<MenuRunner>( menu_model_.get(), MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU); menu_runner_->RunMenuAt(GetWidget(), nullptr, gfx::Rect(p, gfx::Size()), MenuAnchorPosition::kTopLeft, source_type); } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, Menu::Delegate implementation: bool ScrollBar::IsCommandIdEnabled(int id) const { switch (id) { case ScrollBarContextMenuCommand_ScrollPageUp: case ScrollBarContextMenuCommand_ScrollPageDown: return !IsHorizontal(); } return true; } bool ScrollBar::IsCommandIdChecked(int id) const { return false; } void ScrollBar::ExecuteCommand(int id, int event_flags) { switch (id) { case ScrollBarContextMenuCommand_ScrollHere: ScrollToThumbPosition(context_menu_mouse_position_, true); break; case ScrollBarContextMenuCommand_ScrollStart: ScrollByAmount(ScrollAmount::kStart); break; case ScrollBarContextMenuCommand_ScrollEnd: ScrollByAmount(ScrollAmount::kEnd); break; case ScrollBarContextMenuCommand_ScrollPageUp: ScrollByAmount(ScrollAmount::kPrevPage); break; case ScrollBarContextMenuCommand_ScrollPageDown: ScrollByAmount(ScrollAmount::kNextPage); break; case ScrollBarContextMenuCommand_ScrollPrev: ScrollByAmount(ScrollAmount::kPrevLine); break; case ScrollBarContextMenuCommand_ScrollNext: ScrollByAmount(ScrollAmount::kNextLine); break; } } /////////////////////////////////////////////////////////////////////////////// // ScrollBar implementation: bool ScrollBar::OverlapsContent() const { return false; } void ScrollBar::Update(int viewport_size, int content_size, int contents_scroll_offset) { max_pos_ = std::max(0, content_size - viewport_size); // Make sure contents_size is always > 0 to avoid divide by zero errors in // calculations throughout this code. contents_size_ = std::max(1, content_size); viewport_size_ = std::max(1, viewport_size); SetContentsScrollOffset(contents_scroll_offset); // Thumb Height and Thumb Pos. // The height of the thumb is the ratio of the Viewport height to the // content size multiplied by the height of the thumb track. float ratio = std::min<float>(1.0, static_cast<float>(viewport_size) / contents_size_); thumb_->SetLength(base::ClampRound(ratio * GetTrackSize())); int thumb_position = CalculateThumbPosition(contents_scroll_offset); thumb_->SetPosition(thumb_position); } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, protected: BaseScrollBarThumb* ScrollBar::GetThumb() const { return thumb_; } void ScrollBar::ScrollToPosition(int position) { controller()->ScrollToPosition(this, position); } int ScrollBar::GetScrollIncrement(bool is_page, bool is_positive) { return controller()->GetScrollIncrement(this, is_page, is_positive); } void ScrollBar::ObserveScrollEvent(const ui::ScrollEvent& event) { switch (event.type()) { case ui::ET_SCROLL_FLING_CANCEL: scroll_status_ = ScrollStatus::kScrollStarted; break; case ui::ET_SCROLL: if (scroll_status_ == ScrollStatus::kScrollStarted) scroll_status_ = ScrollStatus::kScrollInProgress; break; case ui::ET_SCROLL_FLING_START: scroll_status_ = ScrollStatus::kScrollEnded; controller()->OnScrollEnded(); break; case ui::ET_GESTURE_END: if (scroll_status_ != ScrollStatus::kScrollEnded) { scroll_status_ = ScrollStatus::kScrollEnded; controller()->OnScrollEnded(); } break; default: break; } } ScrollAnimator* ScrollBar::GetOrCreateScrollAnimator() { if (!scroll_animator_) { scroll_animator_ = std::make_unique<ScrollAnimator>(this); scroll_animator_->set_velocity_multiplier(fling_multiplier_); } return scroll_animator_.get(); } void ScrollBar::SetFlingMultiplier(float fling_multiplier) { fling_multiplier_ = fling_multiplier; // `scroll_animator_` is lazily created when needed. if (!scroll_animator_) return; GetOrCreateScrollAnimator()->set_velocity_multiplier(fling_multiplier_); } ScrollBar::ScrollBar(bool is_horiz) : is_horiz_(is_horiz), repeater_(base::BindRepeating(&ScrollBar::TrackClicked, base::Unretained(this))) { set_context_menu_controller(this); SetAccessibilityProperties(ax::mojom::Role::kScrollBar); } /////////////////////////////////////////////////////////////////////////////// // ScrollBar, private: #if !BUILDFLAG(IS_MAC) // static base::RetainingOneShotTimer* ScrollBar::GetHideTimerForTesting( ScrollBar* scroll_bar) { return nullptr; } #endif int ScrollBar::GetThumbLengthForTesting() { return thumb_->GetLength(); } void ScrollBar::ProcessPressEvent(const ui::LocatedEvent& event) { gfx::Rect thumb_bounds = thumb_->bounds(); if (IsHorizontal()) { if (GetMirroredXInView(event.x()) < thumb_bounds.x()) { last_scroll_amount_ = ScrollAmount::kPrevPage; } else if (GetMirroredXInView(event.x()) > thumb_bounds.right()) { last_scroll_amount_ = ScrollAmount::kNextPage; } } else { if (event.y() < thumb_bounds.y()) { last_scroll_amount_ = ScrollAmount::kPrevPage; } else if (event.y() > thumb_bounds.bottom()) { last_scroll_amount_ = ScrollAmount::kNextPage; } } TrackClicked(); repeater_.Start(); } void ScrollBar::TrackClicked() { ScrollByAmount(last_scroll_amount_); } void ScrollBar::ScrollContentsToOffset() { ScrollToPosition(contents_scroll_offset_); thumb_->SetPosition(CalculateThumbPosition(contents_scroll_offset_)); } int ScrollBar::GetTrackSize() const { gfx::Rect track_bounds = GetTrackBounds(); return IsHorizontal() ? track_bounds.width() : track_bounds.height(); } int ScrollBar::CalculateThumbPosition(int contents_scroll_offset) const { // In some combination of viewport_size and contents_size_, the result of // simple division can be rounded and there could be 1 pixel gap even when the // contents scroll down to the bottom. See crbug.com/244671. int thumb_max = GetTrackSize() - thumb_->GetLength(); if (contents_scroll_offset + viewport_size_ == contents_size_) return thumb_max; return (contents_scroll_offset * thumb_max) / (contents_size_ - viewport_size_); } int ScrollBar::CalculateContentsOffset(float thumb_position, bool scroll_to_middle) const { float thumb_size = static_cast<float>(thumb_->GetLength()); int track_size = GetTrackSize(); if (track_size == thumb_size) return 0; if (scroll_to_middle) thumb_position = thumb_position - (thumb_size / 2); float result = (thumb_position * (contents_size_ - viewport_size_)) / (track_size - thumb_size); return base::ClampRound(result); } void ScrollBar::SetContentsScrollOffset(int contents_scroll_offset) { contents_scroll_offset_ = std::clamp(contents_scroll_offset, GetMinPosition(), GetMaxPosition()); } ScrollBar::ScrollAmount ScrollBar::DetermineScrollAmountByKeyCode( const ui::KeyboardCode& keycode) const { // Reject arrows that don't match the scrollbar orientation. if (IsHorizontal() ? (keycode == ui::VKEY_UP || keycode == ui::VKEY_DOWN) : (keycode == ui::VKEY_LEFT || keycode == ui::VKEY_RIGHT)) return ScrollAmount::kNone; static const base::NoDestructor< base::flat_map<ui::KeyboardCode, ScrollAmount>> kMap({ {ui::VKEY_LEFT, ScrollAmount::kPrevLine}, {ui::VKEY_RIGHT, ScrollAmount::kNextLine}, {ui::VKEY_UP, ScrollAmount::kPrevLine}, {ui::VKEY_DOWN, ScrollAmount::kNextLine}, {ui::VKEY_PRIOR, ScrollAmount::kPrevPage}, {ui::VKEY_NEXT, ScrollAmount::kNextPage}, {ui::VKEY_HOME, ScrollAmount::kStart}, {ui::VKEY_END, ScrollAmount::kEnd}, }); const auto i = kMap->find(keycode); return (i == kMap->end()) ? ScrollAmount::kNone : i->second; } absl::optional<int> ScrollBar::GetDesiredScrollOffset(ScrollAmount amount) { switch (amount) { case ScrollAmount::kStart: return GetMinPosition(); case ScrollAmount::kEnd: return GetMaxPosition(); case ScrollAmount::kPrevLine: return contents_scroll_offset_ - GetScrollIncrement(false, false); case ScrollAmount::kNextLine: return contents_scroll_offset_ + GetScrollIncrement(false, true); case ScrollAmount::kPrevPage: return contents_scroll_offset_ - GetScrollIncrement(true, false); case ScrollAmount::kNextPage: return contents_scroll_offset_ + GetScrollIncrement(true, true); default: return absl::nullopt; } } BEGIN_METADATA(ScrollBar, View) ADD_READONLY_PROPERTY_METADATA(int, MaxPosition) ADD_READONLY_PROPERTY_METADATA(int, MinPosition) ADD_READONLY_PROPERTY_METADATA(int, Position) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar.cc
C++
unknown
18,091
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_ #include <memory> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/models/simple_menu_model.h" #include "ui/views/animation/scroll_animator.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/repeat_controller.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { namespace test { class ScrollViewTestApi; } class BaseScrollBarThumb; class MenuRunner; class ScrollBar; ///////////////////////////////////////////////////////////////////////////// // // ScrollBarController // // ScrollBarController defines the method that should be implemented to // receive notification from a scrollbar // ///////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ScrollBarController { public: // Invoked by the scrollbar when the scrolling position changes // This method typically implements the actual scrolling. // // The provided position is expressed in pixels. It is the new X or Y // position which is in the GetMinPosition() / GetMaxPosition range. virtual void ScrollToPosition(ScrollBar* source, int position) = 0; // Called when the scroll that triggered by gesture or scroll events sequence // ended. virtual void OnScrollEnded() {} // Returns the amount to scroll. The amount to scroll may be requested in // two different amounts. If is_page is true the 'page scroll' amount is // requested. The page scroll amount typically corresponds to the // visual size of the view. If is_page is false, the 'line scroll' amount // is being requested. The line scroll amount typically corresponds to the // size of one row/column. // // The return value should always be positive. A value <= 0 results in // scrolling by a fixed amount. virtual int GetScrollIncrement(ScrollBar* source, bool is_page, bool is_positive) = 0; }; ///////////////////////////////////////////////////////////////////////////// // // ScrollBar // // A View subclass to wrap to implement a ScrollBar. Our current windows // version simply wraps a native windows scrollbar. // // A scrollbar is either horizontal or vertical // ///////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ScrollBar : public View, public ScrollDelegate, public ContextMenuController, public ui::SimpleMenuModel::Delegate { public: METADATA_HEADER(ScrollBar); // An enumeration of different amounts of incremental scroll, representing // events sent from different parts of the UI/keyboard. enum class ScrollAmount { kNone, kStart, kEnd, kPrevLine, kNextLine, kPrevPage, kNextPage, }; ScrollBar(const ScrollBar&) = delete; ScrollBar& operator=(const ScrollBar&) = delete; ~ScrollBar() override; // Returns whether this scrollbar is horizontal. bool IsHorizontal() const; void set_controller(ScrollBarController* controller) { controller_ = controller; } ScrollBarController* controller() const { return controller_; } void SetThumb(BaseScrollBarThumb* thumb); // Scroll the contents by the specified type (see ScrollAmount above). bool ScrollByAmount(ScrollAmount amount); // Scroll the contents to the appropriate position given the supplied // position of the thumb (thumb track coordinates). If |scroll_to_middle| is // true, then the conversion assumes |thumb_position| is in the middle of the // thumb rather than the top. void ScrollToThumbPosition(int thumb_position, bool scroll_to_middle); // Scroll the contents by the specified offset (contents coordinates). bool ScrollByContentsOffset(int contents_offset); // Returns the max and min positions. int GetMaxPosition() const; int GetMinPosition() const; // Returns the position of the scrollbar. int GetPosition() const; // View: bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnMouseWheel(const ui::MouseWheelEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; // ScrollDelegate: bool OnScroll(float dx, float dy) override; void OnFlingScrollEnded() override; // ContextMenuController: void ShowContextMenuForViewImpl(View* source, const gfx::Point& point, ui::MenuSourceType source_type) override; // ui::SimpleMenuModel::Delegate: bool IsCommandIdChecked(int id) const override; bool IsCommandIdEnabled(int id) const override; void ExecuteCommand(int id, int event_flags) override; // Returns true if the scrollbar should sit on top of the content area (e.g. // for overlay scrollbars). virtual bool OverlapsContent() const; // Update the scrollbar appearance given a viewport size, content size and // current position. virtual void Update(int viewport_size, int content_size, int contents_scroll_offset); // Called when a ScrollEvent (in any, or no, direction) is seen by the parent // ScrollView. E.g., this may reveal an overlay scrollbar to indicate // possible scrolling directions to the user. virtual void ObserveScrollEvent(const ui::ScrollEvent& event); // Get the bounds of the "track" area that the thumb is free to slide within. virtual gfx::Rect GetTrackBounds() const = 0; // Get the width or height of this scrollbar. For a vertical scrollbar, this // is the width of the scrollbar, likewise it is the height for a horizontal // scrollbar. virtual int GetThickness() const = 0; // Gets or creates ScrollAnimator if it does not exist. ScrollAnimator* GetOrCreateScrollAnimator(); // Sets `fling_multiplier_` which is used to modify animation velocities // in `scroll_animator_`. void SetFlingMultiplier(float fling_multiplier); bool is_scrolling() const { return scroll_status_ == ScrollStatus::kScrollInProgress; } protected: // Create new scrollbar, either horizontal or vertical. These are protected // since you need to be creating either a NativeScrollBar or a // ImageScrollBar. explicit ScrollBar(bool is_horiz); BaseScrollBarThumb* GetThumb() const; // Wrapper functions that calls the controller. We need this since native // scrollbars wrap around a different scrollbar. When calling the controller // we need to pass in the appropriate scrollbar. For normal scrollbars it's // the |this| scrollbar, for native scrollbars it's the native scrollbar used // to create this. virtual void ScrollToPosition(int position); virtual int GetScrollIncrement(bool is_page, bool is_positive); private: friend class test::ScrollViewTestApi; FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, ScrollBarFitsToBottom); FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, ThumbFullLengthOfTrack); FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, DragThumbScrollsContent); FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, DragThumbScrollsContentWhenSnapBackDisabled); FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, RightClickOpensMenu); FRIEND_TEST_ALL_PREFIXES(ScrollBarViewsTest, TestPageScrollingByPress); static base::RetainingOneShotTimer* GetHideTimerForTesting( ScrollBar* scroll_bar); int GetThumbLengthForTesting(); // Changes to 'pushed' state and starts a timer to scroll repeatedly. void ProcessPressEvent(const ui::LocatedEvent& event); // Called when the mouse is pressed down in the track area. void TrackClicked(); // Responsible for scrolling the contents and also updating the UI to the // current value of the Scroll Offset. void ScrollContentsToOffset(); // Returns the size (width or height) of the track area of the ScrollBar. int GetTrackSize() const; // Calculate the position of the thumb within the track based on the // specified scroll offset of the contents. int CalculateThumbPosition(int contents_scroll_offset) const; // Calculates the current value of the contents offset (contents coordinates) // based on the current thumb position (thumb track coordinates). See // ScrollToThumbPosition() for an explanation of |scroll_to_middle|. int CalculateContentsOffset(float thumb_position, bool scroll_to_middle) const; // Sets |contents_scroll_offset_| by given |contents_scroll_offset|. // |contents_scroll_offset| is clamped between GetMinPosition() and // GetMaxPosition(). void SetContentsScrollOffset(int contents_scroll_offset); ScrollAmount DetermineScrollAmountByKeyCode( const ui::KeyboardCode& keycode) const; absl::optional<int> GetDesiredScrollOffset(ScrollAmount amount); // The size of the scrolled contents, in pixels. int contents_size_ = 0; // The current amount the contents is offset by in the viewport. int contents_scroll_offset_ = 0; // The current size of the view port, in pixels. int viewport_size_ = 0; // The last amount of incremental scroll that this scrollbar performed. This // is accessed by the callbacks for the auto-repeat up/down buttons to know // what direction to repeatedly scroll in. ScrollAmount last_scroll_amount_ = ScrollAmount::kNone; // The position of the mouse within the scroll bar when the context menu // was invoked. int context_menu_mouse_position_ = 0; const bool is_horiz_; raw_ptr<BaseScrollBarThumb> thumb_ = nullptr; raw_ptr<ScrollBarController> controller_ = nullptr; int max_pos_ = 0; float fling_multiplier_ = 1.f; // An instance of a RepeatController which scrolls the scrollbar continuously // as the user presses the mouse button down on the up/down buttons or the // track. RepeatController repeater_; // Difference between current position and cumulative deltas obtained from // scroll update events. // TODO(tdresser): This should be removed when raw pixel scrolling for views // is enabled. See crbug.com/329354. gfx::Vector2dF roundoff_error_; // The enumeration keeps track of the current status of the scroll. Used when // the contents scrolled by the gesture or scroll events sequence. enum class ScrollStatus { kScrollNone, kScrollStarted, kScrollInProgress, // The contents will keep scrolling for a while if the events sequence ends // with ui::ET_SCROLL_FLING_START. Set the status to kScrollInEnding if it // happens, and set it to kScrollEnded while the scroll really ended. kScrollInEnding, kScrollEnded, }; ScrollStatus scroll_status_ = ScrollStatus::kScrollNone; std::unique_ptr<ui::SimpleMenuModel> menu_model_; std::unique_ptr<MenuRunner> menu_runner_; // Used to animate gesture flings on the scroll bar. std::unique_ptr<ScrollAnimator> scroll_animator_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar.h
C++
unknown
11,449
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/scroll_bar_button.h" #include <utility> #include "base/functional/bind.h" #include "base/time/tick_clock.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #include "ui/events/event_constants.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/rect.h" namespace views { ScrollBarButton::ScrollBarButton(PressedCallback callback, Type type, const base::TickClock* tick_clock) : Button(std::move(callback)), type_(type), repeater_(base::BindRepeating(&ScrollBarButton::RepeaterNotifyClick, base::Unretained(this)), tick_clock) { SetFlipCanvasOnPaintForRTLUI(true); // Not focusable by default. SetFocusBehavior(FocusBehavior::NEVER); } ScrollBarButton::~ScrollBarButton() = default; gfx::Size ScrollBarButton::CalculatePreferredSize() const { if (!GetWidget()) return gfx::Size(); return GetNativeTheme()->GetPartSize( GetNativeThemePart(), GetNativeThemeState(), GetNativeThemeParams()); } bool ScrollBarButton::OnMousePressed(const ui::MouseEvent& event) { Button::NotifyClick(event); repeater_.Start(); return true; } void ScrollBarButton::OnMouseReleased(const ui::MouseEvent& event) { OnMouseCaptureLost(); } void ScrollBarButton::OnMouseCaptureLost() { repeater_.Stop(); } void ScrollBarButton::OnThemeChanged() { Button::OnThemeChanged(); PreferredSizeChanged(); } void ScrollBarButton::PaintButtonContents(gfx::Canvas* canvas) { gfx::Rect bounds(GetPreferredSize()); GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), GetNativeThemePart(), GetNativeThemeState(), bounds, GetNativeThemeParams()); } ui::NativeTheme::ExtraParams ScrollBarButton::GetNativeThemeParams() const { ui::NativeTheme::ExtraParams params; params.scrollbar_arrow.is_hovering = GetState() == Button::STATE_HOVERED; return params; } ui::NativeTheme::Part ScrollBarButton::GetNativeThemePart() const { switch (type_) { case Type::kUp: return ui::NativeTheme::kScrollbarUpArrow; case Type::kDown: return ui::NativeTheme::kScrollbarDownArrow; case Type::kLeft: return ui::NativeTheme::kScrollbarLeftArrow; case Type::kRight: return ui::NativeTheme::kScrollbarRightArrow; } NOTREACHED_NORETURN(); } ui::NativeTheme::State ScrollBarButton::GetNativeThemeState() const { switch (GetState()) { case Button::STATE_HOVERED: return ui::NativeTheme::kHovered; case Button::STATE_PRESSED: return ui::NativeTheme::kPressed; case Button::STATE_DISABLED: return ui::NativeTheme::kDisabled; case Button::STATE_NORMAL: return ui::NativeTheme::kNormal; case Button::STATE_COUNT: break; } NOTREACHED_NORETURN(); } void ScrollBarButton::RepeaterNotifyClick() { gfx::Point cursor_point = display::Screen::GetScreen()->GetCursorScreenPoint(); ui::MouseEvent event(ui::ET_MOUSE_RELEASED, cursor_point, cursor_point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); Button::NotifyClick(event); } BEGIN_METADATA(ScrollBarButton, Button) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar_button.cc
C++
unknown
3,533
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_ #include "ui/base/metadata/metadata_header_macros.h" #include "ui/events/event.h" #include "ui/gfx/geometry/size.h" #include "ui/native_theme/native_theme.h" #include "ui/views/controls/button/button.h" #include "ui/views/repeat_controller.h" #include "ui/views/views_export.h" namespace base { class TickClock; } namespace gfx { class Canvas; } namespace views { // A button that activates on mouse pressed rather than released, and that // continues to fire the clicked action as the mouse button remains pressed // down on the button. class VIEWS_EXPORT ScrollBarButton : public Button { public: METADATA_HEADER(ScrollBarButton); enum class Type { kUp, kDown, kLeft, kRight, }; ScrollBarButton(PressedCallback callback, Type type, const base::TickClock* tick_clock = nullptr); ScrollBarButton(const ScrollBarButton&) = delete; ScrollBarButton& operator=(const ScrollBarButton&) = delete; ~ScrollBarButton() override; gfx::Size CalculatePreferredSize() const override; protected: // Button bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; void OnThemeChanged() override; void PaintButtonContents(gfx::Canvas* canvas) override; private: ui::NativeTheme::ExtraParams GetNativeThemeParams() const; ui::NativeTheme::Part GetNativeThemePart() const; ui::NativeTheme::State GetNativeThemeState() const; void RepeaterNotifyClick(); Type type_; // The repeat controller that we use to repeatedly click the button when the // mouse button is down. RepeatController repeater_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_BUTTON_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar_button.h
C++
unknown
2,031
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/scroll_bar_button.h" #include <memory> #include "base/test/task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/display/test/test_screen.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" #include "ui/views/repeat_controller.h" #include "ui/views/test/view_metadata_test_utils.h" namespace views { namespace { using testing::_; using testing::AtLeast; using testing::AtMost; class MockButtonCallback { public: MockButtonCallback() = default; MockButtonCallback(const MockButtonCallback&) = delete; MockButtonCallback& operator=(const MockButtonCallback&) = delete; ~MockButtonCallback() = default; MOCK_METHOD(void, ButtonPressed, ()); }; class ScrollBarButtonTest : public testing::Test { public: ScrollBarButtonTest() : button_(std::make_unique<ScrollBarButton>( base::BindRepeating(&MockButtonCallback::ButtonPressed, base::Unretained(&callback_)), ScrollBarButton::Type::kLeft, task_environment_.GetMockTickClock())) { display::Screen::SetScreenInstance(&test_screen_); } ScrollBarButtonTest(const ScrollBarButtonTest&) = delete; ScrollBarButtonTest& operator=(const ScrollBarButtonTest&) = delete; ~ScrollBarButtonTest() override { display::Screen::SetScreenInstance(nullptr); } protected: testing::StrictMock<MockButtonCallback>& callback() { return callback_; } Button* button() { return button_.get(); } void AdvanceTime(base::TimeDelta time_delta) { task_environment_.FastForwardBy(time_delta); } private: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; display::test::TestScreen test_screen_; testing::StrictMock<MockButtonCallback> callback_; const std::unique_ptr<Button> button_; }; } // namespace TEST_F(ScrollBarButtonTest, Metadata) { test::TestViewMetadata(button()); } TEST_F(ScrollBarButtonTest, FocusBehavior) { EXPECT_EQ(View::FocusBehavior::NEVER, button()->GetFocusBehavior()); } TEST_F(ScrollBarButtonTest, CallbackFiresOnMouseDown) { EXPECT_CALL(callback(), ButtonPressed()); // By default the button should notify its callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); } TEST_F(ScrollBarButtonTest, CallbackFiresMultipleTimesMouseHeldDown) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); } TEST_F(ScrollBarButtonTest, CallbackStopsFiringAfterMouseReleased) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); testing::Mock::VerifyAndClearExpectations(&callback()); button()->OnMouseReleased(ui::MouseEvent( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); EXPECT_CALL(callback(), ButtonPressed()).Times(AtMost(0)); } TEST_F(ScrollBarButtonTest, CallbackStopsFiringAfterMouseCaptureReleased) { EXPECT_CALL(callback(), ButtonPressed()).Times(AtLeast(2)); // By default the button should notify its callback on mouse release. button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); testing::Mock::VerifyAndClearExpectations(&callback()); button()->OnMouseCaptureLost(); AdvanceTime(RepeatController::GetInitialWaitForTesting() * 10); EXPECT_CALL(callback(), ButtonPressed()).Times(AtMost(0)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar_button_unittest.cc
C++
unknown
4,641
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/scrollbar/scroll_bar_views.h" #include <algorithm> #include <memory> #include <utility> #include "base/check.h" #include "base/memory/raw_ptr.h" #include "base/notreached.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/focusable_border.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/controls/scrollbar/scroll_bar_button.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" namespace views { namespace { // Wrapper for the scroll thumb class ScrollBarThumb : public BaseScrollBarThumb { public: explicit ScrollBarThumb(ScrollBar* scroll_bar); ~ScrollBarThumb() override; gfx::Size CalculatePreferredSize() const override; protected: void OnPaint(gfx::Canvas* canvas) override; void OnThemeChanged() override; private: ui::NativeTheme::ExtraParams GetNativeThemeParams() const; ui::NativeTheme::Part GetNativeThemePart() const; ui::NativeTheme::State GetNativeThemeState() const; raw_ptr<ScrollBar> scroll_bar_; }; ScrollBarThumb::ScrollBarThumb(ScrollBar* scroll_bar) : BaseScrollBarThumb(scroll_bar), scroll_bar_(scroll_bar) {} ScrollBarThumb::~ScrollBarThumb() = default; gfx::Size ScrollBarThumb::CalculatePreferredSize() const { if (!GetWidget()) return gfx::Size(); return GetNativeTheme()->GetPartSize( GetNativeThemePart(), GetNativeThemeState(), GetNativeThemeParams()); } void ScrollBarThumb::OnPaint(gfx::Canvas* canvas) { const gfx::Rect local_bounds(GetLocalBounds()); const ui::NativeTheme::State theme_state = GetNativeThemeState(); const ui::NativeTheme::ExtraParams extra_params(GetNativeThemeParams()); GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), GetNativeThemePart(), theme_state, local_bounds, extra_params); const ui::NativeTheme::Part gripper_part = scroll_bar_->IsHorizontal() ? ui::NativeTheme::kScrollbarHorizontalGripper : ui::NativeTheme::kScrollbarVerticalGripper; GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), gripper_part, theme_state, local_bounds, extra_params); } void ScrollBarThumb::OnThemeChanged() { BaseScrollBarThumb::OnThemeChanged(); PreferredSizeChanged(); } ui::NativeTheme::ExtraParams ScrollBarThumb::GetNativeThemeParams() const { // This gives the behavior we want. ui::NativeTheme::ExtraParams params; params.scrollbar_thumb.is_hovering = (GetState() != Button::STATE_HOVERED); return params; } ui::NativeTheme::Part ScrollBarThumb::GetNativeThemePart() const { if (scroll_bar_->IsHorizontal()) return ui::NativeTheme::kScrollbarHorizontalThumb; return ui::NativeTheme::kScrollbarVerticalThumb; } ui::NativeTheme::State ScrollBarThumb::GetNativeThemeState() const { switch (GetState()) { case Button::STATE_HOVERED: return ui::NativeTheme::kHovered; case Button::STATE_PRESSED: return ui::NativeTheme::kPressed; case Button::STATE_DISABLED: return ui::NativeTheme::kDisabled; case Button::STATE_NORMAL: return ui::NativeTheme::kNormal; case Button::STATE_COUNT: NOTREACHED_NORETURN(); } } } // namespace ScrollBarViews::ScrollBarViews(bool horizontal) : ScrollBar(horizontal) { SetFlipCanvasOnPaintForRTLUI(true); state_ = ui::NativeTheme::kNormal; auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); if (!horizontal) layout->SetOrientation(views::LayoutOrientation::kVertical); const auto scroll_func = [](ScrollBarViews* scrollbar, ScrollAmount amount) { scrollbar->ScrollByAmount(amount); }; using Type = ScrollBarButton::Type; prev_button_ = AddChildView(std::make_unique<ScrollBarButton>( base::BindRepeating(scroll_func, base::Unretained(this), ScrollAmount::kPrevLine), horizontal ? Type::kLeft : Type::kUp)); prev_button_->set_context_menu_controller(this); SetThumb(new ScrollBarThumb(this)); // Allow the thumb to take up the whole size of the scrollbar, save for the // prev/next buttons. Layout need only set the thumb cross-axis coordinate; // ScrollBar::Update() will set the thumb size/offset. GetThumb()->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification(views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kUnbounded)); next_button_ = AddChildView(std::make_unique<ScrollBarButton>( base::BindRepeating(scroll_func, base::Unretained(this), ScrollBar::ScrollAmount::kNextLine), horizontal ? Type::kRight : Type::kDown)); next_button_->set_context_menu_controller(this); part_ = horizontal ? ui::NativeTheme::kScrollbarHorizontalTrack : ui::NativeTheme::kScrollbarVerticalTrack; } ScrollBarViews::~ScrollBarViews() = default; // static int ScrollBarViews::GetVerticalScrollBarWidth(const ui::NativeTheme* theme) { ui::NativeTheme::ExtraParams button_params; button_params.scrollbar_arrow.is_hovering = false; gfx::Size button_size = theme->GetPartSize(ui::NativeTheme::kScrollbarUpArrow, ui::NativeTheme::kNormal, button_params); ui::NativeTheme::ExtraParams thumb_params; thumb_params.scrollbar_thumb.is_hovering = false; gfx::Size track_size = theme->GetPartSize(ui::NativeTheme::kScrollbarVerticalThumb, ui::NativeTheme::kNormal, thumb_params); return std::max(track_size.width(), button_size.width()); } void ScrollBarViews::OnPaint(gfx::Canvas* canvas) { gfx::Rect bounds = GetTrackBounds(); if (bounds.IsEmpty()) return; params_.scrollbar_track.track_x = bounds.x(); params_.scrollbar_track.track_y = bounds.y(); params_.scrollbar_track.track_width = bounds.width(); params_.scrollbar_track.track_height = bounds.height(); params_.scrollbar_track.classic_state = 0; const BaseScrollBarThumb* thumb = GetThumb(); params_.scrollbar_track.is_upper = true; gfx::Rect upper_bounds = bounds; if (IsHorizontal()) upper_bounds.set_width(thumb->x() - upper_bounds.x()); else upper_bounds.set_height(thumb->y() - upper_bounds.y()); if (!upper_bounds.IsEmpty()) { GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), part_, state_, upper_bounds, params_); } params_.scrollbar_track.is_upper = false; if (IsHorizontal()) bounds.Inset( gfx::Insets::TLBR(0, thumb->bounds().right() - bounds.x(), 0, 0)); else bounds.Inset( gfx::Insets::TLBR(thumb->bounds().bottom() - bounds.y(), 0, 0, 0)); if (!bounds.IsEmpty()) { GetNativeTheme()->Paint(canvas->sk_canvas(), GetColorProvider(), part_, state_, bounds, params_); } } int ScrollBarViews::GetThickness() const { const gfx::Size size = GetPreferredSize(); return IsHorizontal() ? size.height() : size.width(); } gfx::Rect ScrollBarViews::GetTrackBounds() const { gfx::Rect bounds = GetLocalBounds(); gfx::Size size = prev_button_->GetPreferredSize(); BaseScrollBarThumb* thumb = GetThumb(); if (IsHorizontal()) { bounds.set_x(bounds.x() + size.width()); bounds.set_width(std::max(0, bounds.width() - 2 * size.width())); bounds.set_height(thumb->GetPreferredSize().height()); } else { bounds.set_y(bounds.y() + size.height()); bounds.set_height(std::max(0, bounds.height() - 2 * size.height())); bounds.set_width(thumb->GetPreferredSize().width()); } return bounds; } BEGIN_METADATA(ScrollBarViews, ScrollBar) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar_views.cc
C++
unknown
8,016
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_VIEWS_H_ #define UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_VIEWS_H_ #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/view.h" namespace gfx { class Canvas; } namespace views { // Views implementation for the scrollbar. class VIEWS_EXPORT ScrollBarViews : public ScrollBar { public: METADATA_HEADER(ScrollBarViews); // Creates new scrollbar, either horizontal or vertical. explicit ScrollBarViews(bool horizontal = true); ScrollBarViews(const ScrollBarViews&) = delete; ScrollBarViews& operator=(const ScrollBarViews&) = delete; ~ScrollBarViews() override; static int GetVerticalScrollBarWidth(const ui::NativeTheme* theme); protected: // View overrides: void OnPaint(gfx::Canvas* canvas) override; // ScrollBar overrides: int GetThickness() const override; // Returns the area for the track. This is the area of the scrollbar minus // the size of the arrow buttons. gfx::Rect GetTrackBounds() const override; private: // The scroll bar buttons (Up/Down, Left/Right). raw_ptr<Button> prev_button_; raw_ptr<Button> next_button_; ui::NativeTheme::ExtraParams params_; ui::NativeTheme::Part part_; ui::NativeTheme::State state_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_VIEWS_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scroll_bar_views.h
C++
unknown
1,607
// 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 <memory> #include "base/memory/raw_ptr.h" #include "base/time/time.h" #include "build/build_config.h" #include "ui/base/ui_base_types.h" #include "ui/events/test/event_generator.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" #include "ui/views/controls/scrollbar/scroll_bar.h" #include "ui/views/controls/scrollbar/scroll_bar_views.h" #include "ui/views/test/view_metadata_test_utils.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/unique_widget_ptr.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_utils.h" namespace { // The Scrollbar controller. This is the widget that should do the real // scrolling of contents. class TestScrollBarController : public views::ScrollBarController { public: virtual ~TestScrollBarController() = default; void ScrollToPosition(views::ScrollBar* source, int position) override { last_source = source; last_position = position; } int GetScrollIncrement(views::ScrollBar* source, bool is_page, bool is_positive) override { last_source = source; last_is_page = is_page; last_is_positive = is_positive; if (is_page) return 20; return 10; } // We save the last values in order to assert the correctness of the scroll // operation. raw_ptr<views::ScrollBar> last_source; bool last_is_positive; bool last_is_page; int last_position; }; // This container is used to forward gesture events to the scrollbar for // testing fling and other gestures. class TestScrollbarContainer : public views::View { public: TestScrollbarContainer() = default; ~TestScrollbarContainer() override = default; TestScrollbarContainer(const TestScrollbarContainer&) = delete; TestScrollbarContainer& operator=(const TestScrollbarContainer&) = delete; void OnGestureEvent(ui::GestureEvent* event) override { children()[0]->OnGestureEvent(event); } }; } // namespace namespace views { class ScrollBarViewsTest : public ViewsTestBase { public: ScrollBarViewsTest() = default; void SetUp() override { ViewsTestBase::SetUp(); controller_ = std::make_unique<TestScrollBarController>(); widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 100, 300); widget_->Init(std::move(params)); widget_->Show(); auto* container = widget_->SetContentsView(std::make_unique<TestScrollbarContainer>()); scrollbar_ = container->AddChildView(std::make_unique<ScrollBarViews>()); scrollbar_->SetBounds(0, 0, 100, 100); scrollbar_->Update(100, 1000, 0); scrollbar_->set_controller(controller_.get()); track_size_ = scrollbar_->GetTrackBounds().width(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } protected: UniqueWidgetPtr widget_; // This is the Views scrollbar. raw_ptr<ScrollBar> scrollbar_ = nullptr; // Keep track of the size of the track. This is how we can tell when we // scroll to the middle. int track_size_; std::unique_ptr<TestScrollBarController> controller_; }; // Verify properties are accessible via metadata. TEST_F(ScrollBarViewsTest, MetaDataTest) { test::TestViewMetadata(scrollbar_); } TEST_F(ScrollBarViewsTest, Scrolling) { EXPECT_EQ(0, scrollbar_->GetPosition()); EXPECT_EQ(900, scrollbar_->GetMaxPosition()); EXPECT_EQ(0, scrollbar_->GetMinPosition()); // Scroll to middle. scrollbar_->ScrollToThumbPosition(track_size_ / 2, true); EXPECT_EQ(450, controller_->last_position); EXPECT_EQ(scrollbar_, controller_->last_source); // Scroll to the end. scrollbar_->ScrollToThumbPosition(track_size_, true); EXPECT_EQ(900, controller_->last_position); // Overscroll. Last position should be the maximum position. scrollbar_->ScrollToThumbPosition(track_size_ + 100, true); EXPECT_EQ(900, controller_->last_position); // Underscroll. Last position should be the minimum position. scrollbar_->ScrollToThumbPosition(-10, false); EXPECT_EQ(0, controller_->last_position); // Test the different fixed scrolling amounts. Generally used by buttons, // or click on track. scrollbar_->ScrollToThumbPosition(0, false); scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kNextLine); EXPECT_EQ(10, controller_->last_position); scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kPrevLine); EXPECT_EQ(0, controller_->last_position); scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kNextPage); EXPECT_EQ(20, controller_->last_position); scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kPrevPage); EXPECT_EQ(0, controller_->last_position); } TEST_F(ScrollBarViewsTest, ScrollBarFitsToBottom) { scrollbar_->Update(100, 1999, 0); EXPECT_EQ(0, scrollbar_->GetPosition()); EXPECT_EQ(1899, scrollbar_->GetMaxPosition()); EXPECT_EQ(0, scrollbar_->GetMinPosition()); // Scroll to the midpoint of the document. scrollbar_->Update(100, 1999, 950); EXPECT_EQ((scrollbar_->GetTrackBounds().width() - scrollbar_->GetThumbLengthForTesting()) / 2, scrollbar_->GetPosition()); // Scroll to the end of the document. scrollbar_->Update(100, 1999, 1899); EXPECT_EQ(scrollbar_->GetTrackBounds().width() - scrollbar_->GetThumbLengthForTesting(), scrollbar_->GetPosition()); } TEST_F(ScrollBarViewsTest, ScrollToEndAfterShrinkAndExpand) { // Scroll to the end of the content. scrollbar_->Update(100, 1001, 0); EXPECT_TRUE(scrollbar_->ScrollByContentsOffset(-1)); // Shrink and then re-expand the content. scrollbar_->Update(100, 1000, 0); scrollbar_->Update(100, 1001, 0); // Ensure the scrollbar allows scrolling to the end. EXPECT_TRUE(scrollbar_->ScrollByContentsOffset(-1)); } TEST_F(ScrollBarViewsTest, ThumbFullLengthOfTrack) { // Shrink content so that it fits within the viewport. scrollbar_->Update(100, 10, 0); EXPECT_EQ(scrollbar_->GetTrackBounds().width(), scrollbar_->GetThumbLengthForTesting()); // Emulate a click on the full size scroll bar. scrollbar_->ScrollToThumbPosition(0, false); EXPECT_EQ(0, scrollbar_->GetPosition()); // Emulate a key down. scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kNextLine); EXPECT_EQ(0, scrollbar_->GetPosition()); // Expand content so that it fits *exactly* within the viewport. scrollbar_->Update(100, 100, 0); EXPECT_EQ(scrollbar_->GetTrackBounds().width(), scrollbar_->GetThumbLengthForTesting()); // Emulate a click on the full size scroll bar. scrollbar_->ScrollToThumbPosition(0, false); EXPECT_EQ(0, scrollbar_->GetPosition()); // Emulate a key down. scrollbar_->ScrollByAmount(ScrollBar::ScrollAmount::kNextLine); EXPECT_EQ(0, scrollbar_->GetPosition()); } TEST_F(ScrollBarViewsTest, AccessibleRole) { ui::AXNodeData data; scrollbar_->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kScrollBar); EXPECT_EQ(scrollbar_->GetAccessibleRole(), ax::mojom::Role::kScrollBar); data = ui::AXNodeData(); scrollbar_->SetAccessibleRole(ax::mojom::Role::kButton); scrollbar_->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kButton); EXPECT_EQ(scrollbar_->GetAccessibleRole(), ax::mojom::Role::kButton); } #if !BUILDFLAG(IS_MAC) TEST_F(ScrollBarViewsTest, RightClickOpensMenu) { EXPECT_EQ(nullptr, scrollbar_->menu_model_); EXPECT_EQ(nullptr, scrollbar_->menu_runner_); scrollbar_->set_context_menu_controller(scrollbar_); // Disabled on Mac because Mac's native menu is synchronous. scrollbar_->ShowContextMenu(scrollbar_->GetBoundsInScreen().CenterPoint(), ui::MENU_SOURCE_MOUSE); EXPECT_NE(nullptr, scrollbar_->menu_model_); EXPECT_NE(nullptr, scrollbar_->menu_runner_); } TEST_F(ScrollBarViewsTest, TestPageScrollingByPress) { ui::test::EventGenerator generator(GetRootWindow(widget_.get())); EXPECT_EQ(0, scrollbar_->GetPosition()); generator.MoveMouseTo( scrollbar_->GetThumb()->GetBoundsInScreen().right_center() + gfx::Vector2d(4, 0)); generator.ClickLeftButton(); generator.ClickLeftButton(); EXPECT_GT(scrollbar_->GetPosition(), 0); } TEST_F(ScrollBarViewsTest, DragThumbScrollsContent) { ui::test::EventGenerator generator(GetRootWindow(widget_.get())); EXPECT_EQ(0, scrollbar_->GetPosition()); generator.MoveMouseTo( scrollbar_->GetThumb()->GetBoundsInScreen().CenterPoint()); generator.PressLeftButton(); generator.MoveMouseBy(15, 0); EXPECT_GE(scrollbar_->GetPosition(), 10); // Dragging the mouse somewhat outside the thumb maintains scroll. generator.MoveMouseBy(0, 100); EXPECT_GE(scrollbar_->GetPosition(), 10); // Dragging the mouse far outside the thumb snaps back to the initial // scroll position. generator.MoveMouseBy(0, 100); EXPECT_EQ(0, scrollbar_->GetPosition()); } TEST_F(ScrollBarViewsTest, DragThumbScrollsContentWhenSnapBackDisabled) { scrollbar_->GetThumb()->SetSnapBackOnDragOutside(false); ui::test::EventGenerator generator(GetRootWindow(widget_.get())); EXPECT_EQ(0, scrollbar_->GetPosition()); generator.MoveMouseTo( scrollbar_->GetThumb()->GetBoundsInScreen().CenterPoint()); generator.PressLeftButton(); generator.MoveMouseBy(10, 0); EXPECT_GT(scrollbar_->GetPosition(), 0); // Move the mouse far down, outside the thumb. generator.MoveMouseBy(0, 200); // Position does not snap back to zero. EXPECT_GT(scrollbar_->GetPosition(), 0); } TEST_F(ScrollBarViewsTest, FlingGestureScrollsView) { constexpr int kNumScrollSteps = 100; constexpr int kScrollVelocity = 10; ui::test::EventGenerator generator(GetRootWindow(widget_.get())); EXPECT_EQ(0, scrollbar_->GetPosition()); const gfx::Point start_pos = widget_->GetContentsView()->GetBoundsInScreen().CenterPoint(); const gfx::Point end_pos = start_pos + gfx::Vector2d(-100, 0); generator.GestureScrollSequence( start_pos, end_pos, generator.CalculateScrollDurationForFlingVelocity( start_pos, end_pos, kScrollVelocity, kNumScrollSteps), kNumScrollSteps); // Just make sure the view scrolled EXPECT_GT(scrollbar_->GetPosition(), 0); } #endif } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/scrollbar/scrollbar_unittest.cc
C++
unknown
10,513
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/separator.h" #include <algorithm> #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/scoped_canvas.h" namespace views { constexpr int Separator::kThickness; Separator::Separator() = default; Separator::~Separator() = default; ui::ColorId Separator::GetColorId() const { return color_id_; } void Separator::SetColorId(ui::ColorId color_id) { if (color_id_ == color_id) return; color_id_ = color_id; OnPropertyChanged(&color_id_, kPropertyEffectsPaint); } int Separator::GetPreferredLength() const { return preferred_length_; } void Separator::SetPreferredLength(int length) { if (preferred_length_ == length) return; preferred_length_ = length; OnPropertyChanged(&preferred_length_, kPropertyEffectsPreferredSizeChanged); } Separator::Orientation Separator::GetOrientation() const { return orientation_; } void Separator::SetOrientation(Orientation orientation) { orientation_ = orientation; } //////////////////////////////////////////////////////////////////////////////// // Separator, View overrides: gfx::Size Separator::CalculatePreferredSize() const { gfx::Size size(kThickness, preferred_length_); if (orientation_ == Orientation::kHorizontal) size.Transpose(); gfx::Insets insets = GetInsets(); size.Enlarge(insets.width(), insets.height()); return size; } void Separator::OnPaint(gfx::Canvas* canvas) { const SkColor color = GetColorProvider()->GetColor(color_id_); // Paint background and border, if any. View::OnPaint(canvas); gfx::ScopedCanvas scoped_canvas(canvas); const gfx::Insets insets = GetInsets(); const gfx::Rect contents_bounds = GetContentsBounds(); const float dsf = canvas->UndoDeviceScaleFactor(); // This is a hybrid of gfx::ScaleToEnclosedRect() and // gfx::ScaleToEnclosingRect() based on whether there are nonzero insets on // any particular side of the separator. If there is no inset, the separator // will paint all the way out to the edge of the view. If there is an inset, // the extent of the separator will rounded inward so that it paints only // full pixels, providing a sharper appearance and preserving the inset. // // This allows separators that entirely fill their area to do so, and those // intended as spacers in a larger flow to do so as well. See // crbug.com/1016760 and crbug.com/1019503 for examples of why we need to // handle both cases. const int x = insets.left() == 0 ? std::floor(contents_bounds.x() * dsf) : std::ceil(contents_bounds.x() * dsf); const int y = insets.top() == 0 ? std::floor(contents_bounds.y() * dsf) : std::ceil(contents_bounds.y() * dsf); const int r = insets.right() == 0 ? std::ceil(contents_bounds.right() * dsf) : std::floor(contents_bounds.right() * dsf); const int b = insets.bottom() == 0 ? std::ceil(contents_bounds.bottom() * dsf) : std::floor(contents_bounds.bottom() * dsf); // Minimum separator size is 1 px. const int w = std::max(1, r - x); const int h = std::max(1, b - y); canvas->FillRect({x, y, w, h}, color); } BEGIN_METADATA(Separator, View) ADD_PROPERTY_METADATA(ui::ColorId, ColorId) ADD_PROPERTY_METADATA(int, PreferredLength) ADD_PROPERTY_METADATA(Separator::Orientation, Orientation) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/separator.cc
C++
unknown
3,670
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SEPARATOR_H_ #define UI_VIEWS_CONTROLS_SEPARATOR_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/color/color_id.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" namespace views { // The Separator class is a view that shows a line used to visually separate // other views. class VIEWS_EXPORT Separator : public View { public: METADATA_HEADER(Separator); // The separator's thickness in dip. static constexpr int kThickness = 1; // The separator's orientation, set to `kVertical` by default. enum class Orientation { kVertical, kHorizontal }; Separator(); Separator(const Separator&) = delete; Separator& operator=(const Separator&) = delete; ~Separator() override; ui::ColorId GetColorId() const; void SetColorId(ui::ColorId color_id); // Vertical or horizontal extension depending on the orientation. Set to // `kThickness` by default. int GetPreferredLength() const; void SetPreferredLength(int length); Orientation GetOrientation() const; void SetOrientation(Orientation orientation); // Overridden from View: gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; private: int preferred_length_ = kThickness; ui::ColorId color_id_ = ui::kColorSeparator; Orientation orientation_ = Orientation::kVertical; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Separator, View) VIEW_BUILDER_PROPERTY(ui::ColorId, ColorId) VIEW_BUILDER_PROPERTY(int, PreferredLength) VIEW_BUILDER_PROPERTY(Separator::Orientation, Orientation) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Separator) #endif // UI_VIEWS_CONTROLS_SEPARATOR_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/separator.h
C++
unknown
1,858
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/separator.h" #include <memory> #include "base/memory/raw_ptr.h" #include "ui/color/color_id.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/image/image_unittest_util.h" #include "ui/views/border.h" #include "ui/views/test/views_test_base.h" namespace views { // Base test fixture for Separator tests. class SeparatorTest : public ViewsTestBase { public: SeparatorTest() = default; SeparatorTest(const SeparatorTest&) = delete; SeparatorTest& operator=(const SeparatorTest&) = delete; ~SeparatorTest() override = default; protected: // views::ViewsTestBase: void SetUp() override; void TearDown() override; SkBitmap PaintToCanvas(float image_scale); void ExpectDrawAtLeastOnePixel(float image_scale); std::unique_ptr<Widget> widget_; raw_ptr<Separator> separator_; SkColor expected_foreground_color_ = gfx::kPlaceholderColor; static const SkColor kBackgroundColor; static const ui::ColorId kForegroundColorId; static const gfx::Size kTestImageSize; }; const SkColor SeparatorTest::kBackgroundColor = SK_ColorRED; const ui::ColorId SeparatorTest::kForegroundColorId = ui::kColorSeparator; const gfx::Size SeparatorTest::kTestImageSize{24, 24}; void SeparatorTest::SetUp() { ViewsTestBase::SetUp(); widget_ = CreateTestWidget(); separator_ = widget_->SetContentsView(std::make_unique<Separator>()); expected_foreground_color_ = widget_->GetColorProvider()->GetColor(kForegroundColorId); } void SeparatorTest::TearDown() { widget_.reset(); ViewsTestBase::TearDown(); } SkBitmap SeparatorTest::PaintToCanvas(float image_scale) { gfx::Canvas canvas(kTestImageSize, image_scale, true); canvas.DrawColor(kBackgroundColor); separator_->OnPaint(&canvas); return canvas.GetBitmap(); } void SeparatorTest::ExpectDrawAtLeastOnePixel(float image_scale) { SkBitmap painted = PaintToCanvas(image_scale); gfx::Canvas unpainted(kTestImageSize, image_scale, true); unpainted.DrawColor(kBackgroundColor); // At least 1 pixel should be changed. EXPECT_FALSE(gfx::test::AreBitmapsEqual(painted, unpainted.GetBitmap())); } TEST_F(SeparatorTest, GetPreferredSize_VerticalOrientation) { // Orientation is vertical by default. constexpr int kLength = 8; separator_->SetPreferredLength(kLength); EXPECT_EQ(separator_->GetPreferredSize(), gfx::Size(Separator::kThickness, kLength)); } TEST_F(SeparatorTest, GetPreferredSize_HorizontalOrientation) { constexpr int kLength = 8; separator_->SetOrientation(Separator::Orientation::kHorizontal); separator_->SetPreferredLength(kLength); EXPECT_EQ(separator_->GetPreferredSize(), gfx::Size(kLength, Separator::kThickness)); } TEST_F(SeparatorTest, ImageScaleBelowOne) { // Vertical line with 1[dp] thickness by default. separator_->SetPreferredLength(8); ExpectDrawAtLeastOnePixel(0.4); } TEST_F(SeparatorTest, ImageScaleBelowOne_HorizontalLine) { const int kThickness = 1; // Use Separator as a horizontal line with 1[dp] thickness. separator_->SetBounds(4, 5, 8, kThickness); ExpectDrawAtLeastOnePixel(0.4); } TEST_F(SeparatorTest, Paint_NoInsets_FillsCanvas_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 0)); } TEST_F(SeparatorTest, Paint_NoInsets_FillsCanvas_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 0)); } TEST_F(SeparatorTest, Paint_NoInsets_FillsCanvas_Scale150) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); SkBitmap painted = PaintToCanvas(1.5f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 14)); EXPECT_EQ(expected_foreground_color_, painted.getColor(14, 14)); EXPECT_EQ(expected_foreground_color_, painted.getColor(14, 0)); } TEST_F(SeparatorTest, Paint_TopInset_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(1, 0, 0, 0))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 1)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 1)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 9)); } TEST_F(SeparatorTest, Paint_TopInset_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(1, 0, 0, 0))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 1)); EXPECT_EQ(kBackgroundColor, painted.getColor(12, 1)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 2)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 2)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 12)); } TEST_F(SeparatorTest, Paint_LeftInset_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 1, 0, 0))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(1, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(1, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 9)); } TEST_F(SeparatorTest, Paint_LeftInset_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 1, 0, 0))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(kBackgroundColor, painted.getColor(1, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(1, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(2, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(2, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 12)); } TEST_F(SeparatorTest, Paint_BottomInset_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 1, 0))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 8)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 8)); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 9)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 9)); } TEST_F(SeparatorTest, Paint_BottomInset_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 1, 0))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 10)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 10)); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 11)); EXPECT_EQ(kBackgroundColor, painted.getColor(12, 11)); } TEST_F(SeparatorTest, Paint_RightInset_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 0, 1))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(8, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(8, 9)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 9)); } TEST_F(SeparatorTest, Paint_RightInset_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 0, 0, 1))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(10, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(10, 12)); EXPECT_EQ(kBackgroundColor, painted.getColor(11, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(11, 12)); } TEST_F(SeparatorTest, Paint_Vertical_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 4, 0, 5))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(kBackgroundColor, painted.getColor(3, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(3, 9)); EXPECT_EQ(expected_foreground_color_, painted.getColor(4, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(4, 9)); EXPECT_EQ(kBackgroundColor, painted.getColor(5, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(5, 9)); } TEST_F(SeparatorTest, Paint_Vertical_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(0, 4, 0, 5))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(kBackgroundColor, painted.getColor(4, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(4, 12)); EXPECT_EQ(expected_foreground_color_, painted.getColor(5, 0)); EXPECT_EQ(expected_foreground_color_, painted.getColor(5, 12)); EXPECT_EQ(kBackgroundColor, painted.getColor(6, 0)); EXPECT_EQ(kBackgroundColor, painted.getColor(6, 12)); } TEST_F(SeparatorTest, Paint_Horizontal_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(4, 0, 5, 0))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 3)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 3)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 4)); EXPECT_EQ(expected_foreground_color_, painted.getColor(9, 4)); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 5)); EXPECT_EQ(kBackgroundColor, painted.getColor(9, 5)); } TEST_F(SeparatorTest, Paint_Horizontal_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(4, 0, 5, 0))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 4)); EXPECT_EQ(kBackgroundColor, painted.getColor(12, 4)); EXPECT_EQ(expected_foreground_color_, painted.getColor(0, 5)); EXPECT_EQ(expected_foreground_color_, painted.getColor(12, 5)); EXPECT_EQ(kBackgroundColor, painted.getColor(0, 6)); EXPECT_EQ(kBackgroundColor, painted.getColor(12, 6)); } // Ensure that the separator is always at least 1px, even if insets would reduce // it to zero. TEST_F(SeparatorTest, Paint_MinimumSize_Scale100) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(5, 5, 5, 5))); SkBitmap painted = PaintToCanvas(1.0f); EXPECT_EQ(expected_foreground_color_, painted.getColor(5, 5)); EXPECT_EQ(kBackgroundColor, painted.getColor(4, 5)); EXPECT_EQ(kBackgroundColor, painted.getColor(5, 4)); EXPECT_EQ(kBackgroundColor, painted.getColor(5, 6)); EXPECT_EQ(kBackgroundColor, painted.getColor(6, 5)); } // Ensure that the separator is always at least 1px, even if insets would reduce // it to zero (with scale factor > 1). TEST_F(SeparatorTest, Paint_MinimumSize_Scale125) { separator_->SetSize({10, 10}); separator_->SetColorId(kForegroundColorId); separator_->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(5, 5, 5, 5))); SkBitmap painted = PaintToCanvas(1.25f); EXPECT_EQ(expected_foreground_color_, painted.getColor(7, 7)); EXPECT_EQ(kBackgroundColor, painted.getColor(6, 7)); EXPECT_EQ(kBackgroundColor, painted.getColor(7, 6)); EXPECT_EQ(kBackgroundColor, painted.getColor(7, 8)); EXPECT_EQ(kBackgroundColor, painted.getColor(8, 7)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/separator_unittest.cc
C++
unknown
13,337
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/slider.h" #include <algorithm> #include <iterator> #include <memory> #include <utility> #include "base/check_op.h" #include "base/i18n/rtl.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "build/build_config.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPaint.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/widget/widget.h" namespace views { namespace { // The thickness of the slider. constexpr int kLineThickness = 2; // The radius used to draw rounded slider ends. constexpr float kSliderRoundedRadius = 2.f; // The padding used to hide the slider underneath the thumb. constexpr int kSliderPadding = 2; // The radius of the highlighted thumb of the slider constexpr float kThumbHighlightRadius = 12.f; float GetNearestAllowedValue(const base::flat_set<float>& allowed_values, float suggested_value) { if (allowed_values.empty()) return suggested_value; const base::flat_set<float>::const_iterator greater = allowed_values.upper_bound(suggested_value); if (greater == allowed_values.end()) return *allowed_values.rbegin(); if (greater == allowed_values.begin()) return *allowed_values.cbegin(); // Select a value nearest to the |suggested_value|. if ((*greater - suggested_value) > (suggested_value - *std::prev(greater))) return *std::prev(greater); return *greater; } } // namespace Slider::Slider(SliderListener* listener) : listener_(listener) { highlight_animation_.SetSlideDuration(base::Milliseconds(150)); SetFlipCanvasOnPaintForRTLUI(true); SetAccessibilityProperties(ax::mojom::Role::kSlider); #if BUILDFLAG(IS_MAC) SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); #else SetFocusBehavior(FocusBehavior::ALWAYS); #endif SchedulePaint(); } Slider::~Slider() = default; float Slider::GetValue() const { return value_; } void Slider::SetValue(float value) { SetValueInternal(value, SliderChangeReason::kByApi); } float Slider::GetValueIndicatorRadius() const { return value_indicator_radius_; } void Slider::SetValueIndicatorRadius(float radius) { value_indicator_radius_ = radius; } bool Slider::GetEnableAccessibilityEvents() const { return accessibility_events_enabled_; } void Slider::SetEnableAccessibilityEvents(bool enabled) { if (accessibility_events_enabled_ == enabled) return; accessibility_events_enabled_ = enabled; OnPropertyChanged(&accessibility_events_enabled_, kPropertyEffectsNone); } void Slider::SetRenderingStyle(RenderingStyle style) { style_ = style; SchedulePaint(); } void Slider::SetAllowedValues(const base::flat_set<float>* allowed_values) { if (!allowed_values) { allowed_values_.clear(); return; } #if DCHECK_IS_ON() // Disallow empty sliders. DCHECK(allowed_values->size()); for (const float v : *allowed_values) { // sanity check. DCHECK_GE(v, 0.0f); DCHECK_LE(v, 1.0f); } #endif allowed_values_ = *allowed_values; const auto position = allowed_values_.lower_bound(value_); const float new_value = (position == allowed_values_.end()) ? *allowed_values_.cbegin() : *position; if (new_value != value_) SetValue(new_value); } float Slider::GetAnimatingValue() const { return move_animation_ && move_animation_->is_animating() ? move_animation_->CurrentValueBetween(initial_animating_value_, value_) : value_; } void Slider::SetHighlighted(bool is_highlighted) { if (is_highlighted) highlight_animation_.Show(); else highlight_animation_.Hide(); } void Slider::AnimationProgressed(const gfx::Animation* animation) { if (animation == &highlight_animation_) { thumb_highlight_radius_ = animation->CurrentValueBetween(kThumbRadius, kThumbHighlightRadius); } SchedulePaint(); } void Slider::AnimationEnded(const gfx::Animation* animation) { if (animation == move_animation_.get()) { move_animation_.reset(); return; } DCHECK_EQ(animation, &highlight_animation_); } void Slider::SetValueInternal(float value, SliderChangeReason reason) { bool old_value_valid = value_is_valid_; value_is_valid_ = true; if (value < 0.0) value = 0.0; else if (value > 1.0) value = 1.0; value = GetNearestAllowedValue(allowed_values_, value); if (value_ == value) return; float old_value = value_; value_ = value; if (listener_) listener_->SliderValueChanged(this, value_, old_value, reason); if (old_value_valid && base::CurrentThread::Get()) { // Do not animate when setting the value of the slider for the first time. // There is no message-loop when running tests. So we cannot animate then. if (!move_animation_) { initial_animating_value_ = old_value; move_animation_ = std::make_unique<gfx::SlideAnimation>(this); move_animation_->SetSlideDuration(base::Milliseconds(150)); move_animation_->Show(); } OnPropertyChanged(&value_, kPropertyEffectsNone); } else { OnPropertyChanged(&value_, kPropertyEffectsPaint); } if (accessibility_events_enabled_) { if (GetWidget() && GetWidget()->IsVisible()) { DCHECK(!pending_accessibility_value_change_); NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true); } else { pending_accessibility_value_change_ = true; } } } void Slider::PrepareForMove(const int new_x) { // Try to remember the position of the mouse cursor on the button. gfx::Insets inset = GetInsets(); gfx::Rect content = GetContentsBounds(); float value = GetAnimatingValue(); const int thumb_x = value * (content.width() - 2 * value_indicator_radius_); const int candidate_x = GetMirroredXInView(new_x - inset.left()) - thumb_x; if (candidate_x >= value_indicator_radius_ - kThumbRadius && candidate_x < value_indicator_radius_ + kThumbRadius) initial_button_offset_ = candidate_x; else initial_button_offset_ = value_indicator_radius_; } void Slider::MoveButtonTo(const gfx::Point& point) { const gfx::Insets inset = GetInsets(); // Calculate the value. int amount = base::i18n::IsRTL() ? width() - inset.left() - point.x() - initial_button_offset_ : point.x() - inset.left() - initial_button_offset_; SetValueInternal(static_cast<float>(amount) / (width() - inset.width() - 2 * value_indicator_radius_), SliderChangeReason::kByUser); } void Slider::OnSliderDragStarted() { SetHighlighted(true); if (listener_) listener_->SliderDragStarted(this); } void Slider::OnSliderDragEnded() { SetHighlighted(false); if (listener_) listener_->SliderDragEnded(this); } gfx::Size Slider::CalculatePreferredSize() const { constexpr int kSizeMajor = 200; constexpr int kSizeMinor = 40; return gfx::Size(std::max(width(), kSizeMajor), kSizeMinor); } bool Slider::OnMousePressed(const ui::MouseEvent& event) { if (!event.IsOnlyLeftMouseButton()) return false; OnSliderDragStarted(); PrepareForMove(event.location().x()); MoveButtonTo(event.location()); return true; } bool Slider::OnMouseDragged(const ui::MouseEvent& event) { MoveButtonTo(event.location()); return true; } void Slider::OnMouseReleased(const ui::MouseEvent& event) { OnSliderDragEnded(); } bool Slider::OnKeyPressed(const ui::KeyEvent& event) { int direction = 1; switch (event.key_code()) { case ui::VKEY_LEFT: direction = base::i18n::IsRTL() ? 1 : -1; break; case ui::VKEY_RIGHT: direction = base::i18n::IsRTL() ? -1 : 1; break; case ui::VKEY_UP: direction = 1; break; case ui::VKEY_DOWN: direction = -1; break; default: return false; } if (allowed_values_.empty()) { SetValueInternal(value_ + direction * keyboard_increment_, SliderChangeReason::kByUser); } else { // discrete slider. if (direction > 0) { const base::flat_set<float>::const_iterator greater = allowed_values_.upper_bound(value_); SetValueInternal(greater == allowed_values_.cend() ? *allowed_values_.crend() : *greater, SliderChangeReason::kByUser); } else { const base::flat_set<float>::const_iterator lesser = allowed_values_.lower_bound(value_); // Current value must be in the list of allowed values. DCHECK(lesser != allowed_values_.cend()); SetValueInternal(lesser == allowed_values_.cbegin() ? *allowed_values_.cbegin() : *std::prev(lesser), SliderChangeReason::kByUser); } } return true; } void Slider::GetAccessibleNodeData(ui::AXNodeData* node_data) { View::GetAccessibleNodeData(node_data); node_data->SetValue(base::UTF8ToUTF16( base::StringPrintf("%d%%", static_cast<int>(value_ * 100 + 0.5)))); node_data->AddAction(ax::mojom::Action::kIncrement); node_data->AddAction(ax::mojom::Action::kDecrement); } bool Slider::HandleAccessibleAction(const ui::AXActionData& action_data) { if (action_data.action == ax::mojom::Action::kIncrement) { SetValueInternal(value_ + keyboard_increment_, SliderChangeReason::kByUser); return true; } else if (action_data.action == ax::mojom::Action::kDecrement) { SetValueInternal(value_ - keyboard_increment_, SliderChangeReason::kByUser); return true; } else { return views::View::HandleAccessibleAction(action_data); } } void Slider::OnPaint(gfx::Canvas* canvas) { // Paint the slider. const gfx::Rect content = GetContentsBounds(); const int width = content.width() - kThumbRadius * 2; const int full = GetAnimatingValue() * width; const int empty = width - full; const int y = content.height() / 2 - kLineThickness / 2; const int x = content.x() + full + kThumbRadius; cc::PaintFlags slider_flags; slider_flags.setAntiAlias(true); slider_flags.setColor(GetThumbColor()); canvas->DrawRoundRect( gfx::Rect(content.x(), y, full - GetSliderExtraPadding(), kLineThickness), kSliderRoundedRadius, slider_flags); slider_flags.setColor(GetTroughColor()); canvas->DrawRoundRect( gfx::Rect(x + kThumbRadius + GetSliderExtraPadding(), y, empty - GetSliderExtraPadding(), kLineThickness), kSliderRoundedRadius, slider_flags); gfx::Point thumb_center(x, content.height() / 2); // Paint the thumb highlight if it exists. const int thumb_highlight_radius = HasFocus() ? kThumbHighlightRadius : thumb_highlight_radius_; if (thumb_highlight_radius > kThumbRadius) { cc::PaintFlags highlight_background; highlight_background.setColor(GetTroughColor()); highlight_background.setAntiAlias(true); canvas->DrawCircle(thumb_center, thumb_highlight_radius, highlight_background); cc::PaintFlags highlight_border; highlight_border.setColor(GetThumbColor()); highlight_border.setAntiAlias(true); highlight_border.setStyle(cc::PaintFlags::kStroke_Style); highlight_border.setStrokeWidth(kLineThickness); canvas->DrawCircle(thumb_center, thumb_highlight_radius, highlight_border); } // Paint the thumb of the slider. cc::PaintFlags flags; flags.setColor(GetThumbColor()); flags.setAntiAlias(true); canvas->DrawCircle(thumb_center, kThumbRadius, flags); } void Slider::OnFocus() { View::OnFocus(); SchedulePaint(); } void Slider::OnBlur() { View::OnBlur(); SchedulePaint(); } void Slider::VisibilityChanged(View* starting_from, bool is_visible) { if (is_visible) NotifyPendingAccessibilityValueChanged(); } void Slider::AddedToWidget() { if (GetWidget()->IsVisible()) NotifyPendingAccessibilityValueChanged(); } void Slider::NotifyPendingAccessibilityValueChanged() { if (!pending_accessibility_value_change_) return; NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true); pending_accessibility_value_change_ = false; } void Slider::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { // In a multi point gesture only the touch point will generate // an ET_GESTURE_TAP_DOWN event. case ui::ET_GESTURE_TAP_DOWN: OnSliderDragStarted(); PrepareForMove(event->location().x()); [[fallthrough]]; case ui::ET_GESTURE_SCROLL_BEGIN: case ui::ET_GESTURE_SCROLL_UPDATE: MoveButtonTo(event->location()); event->SetHandled(); break; case ui::ET_GESTURE_END: MoveButtonTo(event->location()); event->SetHandled(); if (event->details().touch_points() <= 1) OnSliderDragEnded(); break; default: break; } } SkColor Slider::GetThumbColor() const { switch (style_) { case RenderingStyle::kDefaultStyle: return GetColorProvider()->GetColor(ui::kColorSliderThumb); case RenderingStyle::kMinimalStyle: return GetColorProvider()->GetColor(ui::kColorSliderThumbMinimal); } } SkColor Slider::GetTroughColor() const { switch (style_) { case RenderingStyle::kDefaultStyle: return GetColorProvider()->GetColor(ui::kColorSliderTrack); case RenderingStyle::kMinimalStyle: return GetColorProvider()->GetColor(ui::kColorSliderTrackMinimal); } } int Slider::GetSliderExtraPadding() const { // Padding is negative when slider style is default so that there is no // separation between slider and thumb. switch (style_) { case RenderingStyle::kDefaultStyle: return -kSliderPadding; case RenderingStyle::kMinimalStyle: return kSliderPadding; } } BEGIN_METADATA(Slider, View) ADD_PROPERTY_METADATA(float, Value) ADD_PROPERTY_METADATA(bool, EnableAccessibilityEvents) ADD_PROPERTY_METADATA(float, ValueIndicatorRadius) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/slider.cc
C++
unknown
14,640
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_SLIDER_H_ #define UI_VIEWS_CONTROLS_SLIDER_H_ #include <memory> #include "base/containers/flat_set.h" #include "base/memory/raw_ptr.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/slide_animation.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { namespace test { class SliderTestApi; } class Slider; enum class SliderChangeReason { kByUser, // value was changed by the user (e.g. by clicking) kByApi, // value was changed by a call to SetValue. }; class VIEWS_EXPORT SliderListener { public: virtual void SliderValueChanged(Slider* sender, float value, float old_value, SliderChangeReason reason) = 0; // Invoked when a drag starts or ends (more specifically, when the mouse // button is pressed or released). virtual void SliderDragStarted(Slider* sender) {} virtual void SliderDragEnded(Slider* sender) {} protected: virtual ~SliderListener() = default; }; // Slider operates in interval [0,1] by default, but can also switch between a // predefined set of values, see SetAllowedValues method below. class VIEWS_EXPORT Slider : public View, public gfx::AnimationDelegate { public: METADATA_HEADER(Slider); explicit Slider(SliderListener* listener = nullptr); Slider(const Slider&) = delete; Slider& operator=(const Slider&) = delete; ~Slider() override; float GetValue() const; void SetValue(float value); // Getter and Setter of `value_indicator_radius_`. float GetValueIndicatorRadius() const; void SetValueIndicatorRadius(float radius); bool GetEnableAccessibilityEvents() const; void SetEnableAccessibilityEvents(bool enabled); // Represents the visual style of the slider. enum class RenderingStyle { kDefaultStyle, kMinimalStyle, }; // Set rendering style and schedule paint since the colors for the slider // may change. void SetRenderingStyle(RenderingStyle style); RenderingStyle style() const { return style_; } // Sets discrete set of allowed slider values. Each value must be in [0,1]. // Sets active value to the lower bound of the current value in allowed set. // nullptr will drop currently active set and allow full [0,1] interval. void SetAllowedValues(const base::flat_set<float>* allowed_values); const base::flat_set<float>& allowed_values() const { return allowed_values_; } // The radius of the thumb. static constexpr float kThumbRadius = 4.f; protected: // Returns the current position of the thumb on the slider. float GetAnimatingValue() const; // Shows or hides the highlight on the slider thumb. The default // implementation does nothing. void SetHighlighted(bool is_highlighted); // gfx::AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; // views::View: void OnPaint(gfx::Canvas* canvas) override; private: friend class test::SliderTestApi; void SetValueInternal(float value, SliderChangeReason reason); // Should be called on the Mouse Down event. Used to calculate relative // position of the mouse cursor (or the touch point) on the button to // accurately move the button using the MoveButtonTo() method. void PrepareForMove(const int new_x); // Moves the button to the specified point and updates the value accordingly. void MoveButtonTo(const gfx::Point& point); // Notify the listener_, if not NULL, that dragging started. void OnSliderDragStarted(); // Notify the listener_, if not NULL, that dragging ended. void OnSliderDragEnded(); // views::View: gfx::Size CalculatePreferredSize() const override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; bool OnKeyPressed(const ui::KeyEvent& event) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; void OnFocus() override; void OnBlur() override; void VisibilityChanged(View* starting_from, bool is_visible) override; void AddedToWidget() override; // ui::EventHandler: void OnGestureEvent(ui::GestureEvent* event) override; void set_listener(SliderListener* listener) { listener_ = listener; } void NotifyPendingAccessibilityValueChanged(); virtual SkColor GetThumbColor() const; virtual SkColor GetTroughColor() const; int GetSliderExtraPadding() const; raw_ptr<SliderListener, DanglingUntriaged> listener_; std::unique_ptr<gfx::SlideAnimation> move_animation_; // When |allowed_values_| is not empty, slider will allow moving only between // these values. I.e. it will become discrete slider. base::flat_set<float> allowed_values_; // Allowed values. float value_ = 0.f; float keyboard_increment_ = 0.1f; float initial_animating_value_ = 0.f; bool value_is_valid_ = false; bool accessibility_events_enabled_ = true; // Relative position of the mouse cursor (or the touch point) on the slider's // button. int initial_button_offset_ = 0; // The radius of the value indicator. float value_indicator_radius_ = kThumbRadius; RenderingStyle style_ = RenderingStyle::kDefaultStyle; // Animating value of the current radius of the thumb's highlight. float thumb_highlight_radius_ = 0.f; gfx::SlideAnimation highlight_animation_{this}; bool pending_accessibility_value_change_ = false; }; } // namespace views #endif // UI_VIEWS_CONTROLS_SLIDER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/slider.h
C++
unknown
5,907
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/slider.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/i18n/rtl.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/events/event.h" #include "ui/events/gesture_event_details.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/test/event_generator.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/slider_test_api.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/unique_widget_ptr.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_utils.h" namespace { // A views::SliderListener that tracks simple event call history. class TestSliderListener : public views::SliderListener { public: TestSliderListener(); TestSliderListener(const TestSliderListener&) = delete; TestSliderListener& operator=(const TestSliderListener&) = delete; ~TestSliderListener() override; int last_event_epoch() { return last_event_epoch_; } int last_drag_started_epoch() { return last_drag_started_epoch_; } int last_drag_ended_epoch() { return last_drag_ended_epoch_; } views::Slider* last_drag_started_sender() { return last_drag_started_sender_; } views::Slider* last_drag_ended_sender() { return last_drag_ended_sender_; } // Resets the state of this as if it were newly created. virtual void ResetCallHistory(); // views::SliderListener: void SliderValueChanged(views::Slider* sender, float value, float old_value, views::SliderChangeReason reason) override; void SliderDragStarted(views::Slider* sender) override; void SliderDragEnded(views::Slider* sender) override; private: // The epoch of the last event. int last_event_epoch_ = 0; // The epoch of the last time SliderDragStarted was called. int last_drag_started_epoch_ = -1; // The epoch of the last time SliderDragEnded was called. int last_drag_ended_epoch_ = -1; // The sender from the last SliderDragStarted call. raw_ptr<views::Slider> last_drag_started_sender_ = nullptr; // The sender from the last SliderDragEnded call. raw_ptr<views::Slider> last_drag_ended_sender_ = nullptr; }; TestSliderListener::TestSliderListener() = default; TestSliderListener::~TestSliderListener() { last_drag_started_sender_ = nullptr; last_drag_ended_sender_ = nullptr; } void TestSliderListener::ResetCallHistory() { last_event_epoch_ = 0; last_drag_started_epoch_ = -1; last_drag_ended_epoch_ = -1; last_drag_started_sender_ = nullptr; last_drag_ended_sender_ = nullptr; } void TestSliderListener::SliderValueChanged(views::Slider* sender, float value, float old_value, views::SliderChangeReason reason) { ++last_event_epoch_; } void TestSliderListener::SliderDragStarted(views::Slider* sender) { last_drag_started_sender_ = sender; last_drag_started_epoch_ = ++last_event_epoch_; } void TestSliderListener::SliderDragEnded(views::Slider* sender) { last_drag_ended_sender_ = sender; last_drag_ended_epoch_ = ++last_event_epoch_; } } // namespace namespace views { // Base test fixture for Slider tests. enum class TestSliderType { kContinuousTest, // ContinuousSlider kDiscreteEnd2EndTest, // DiscreteSlider with 0 and 1 in the list of values. kDiscreteInnerTest, // DiscreteSlider excluding 0 and 1. }; // Parameter specifies whether to test ContinuousSlider (true) or // DiscreteSlider(false). class SliderTest : public views::ViewsTestBase, public testing::WithParamInterface<TestSliderType> { public: SliderTest() = default; SliderTest(const SliderTest&) = delete; SliderTest& operator=(const SliderTest&) = delete; ~SliderTest() override = default; protected: Slider* slider() { return slider_; } TestSliderListener& slider_listener() { return slider_listener_; } int max_x() { return max_x_; } int max_y() { return max_y_; } virtual void ClickAt(int x, int y); // testing::Test: void SetUp() override; void TearDown() override; ui::test::EventGenerator* event_generator() { return event_generator_.get(); } const base::flat_set<float>& values() const { return values_; } // Returns minimum and maximum possible slider values with respect to test // param. float GetMinValue() const; float GetMaxValue() const; private: // The Slider to be tested. raw_ptr<Slider> slider_ = nullptr; // Populated values for discrete slider. base::flat_set<float> values_; // A simple SliderListener test double. TestSliderListener slider_listener_; // Stores the default locale at test setup so it can be restored // during test teardown. std::string default_locale_; // The maximum x value within the bounds of the slider. int max_x_ = 0; // The maximum y value within the bounds of the slider. int max_y_ = 0; // The widget container for the slider being tested. views::UniqueWidgetPtr widget_; // An event generator. std::unique_ptr<ui::test::EventGenerator> event_generator_; }; void SliderTest::ClickAt(int x, int y) { gfx::Point point = slider_->GetBoundsInScreen().origin() + gfx::Vector2d(x, y); event_generator_->MoveMouseTo(point); event_generator_->ClickLeftButton(); } void SliderTest::SetUp() { views::ViewsTestBase::SetUp(); auto slider = std::make_unique<Slider>(); switch (GetParam()) { case TestSliderType::kContinuousTest: break; case TestSliderType::kDiscreteEnd2EndTest: values_ = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}; slider->SetAllowedValues(&values_); break; case TestSliderType::kDiscreteInnerTest: values_ = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}; slider->SetAllowedValues(&values_); break; default: NOTREACHED_NORETURN(); } gfx::Size size = slider->GetPreferredSize(); slider->SetSize(size); max_x_ = size.width() - 1; max_y_ = size.height() - 1; default_locale_ = base::i18n::GetConfiguredLocale(); views::Widget::InitParams init_params( CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)); init_params.bounds = gfx::Rect(size); widget_ = std::make_unique<Widget>(); widget_->Init(std::move(init_params)); slider_ = widget_->SetContentsView(std::move(slider)); widget_->Show(); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_.get())); } void SliderTest::TearDown() { widget_.reset(); base::i18n::SetICUDefaultLocale(default_locale_); views::ViewsTestBase::TearDown(); } float SliderTest::GetMinValue() const { if (GetParam() == TestSliderType::kContinuousTest) return 0.0f; return *values().cbegin(); } float SliderTest::GetMaxValue() const { if (GetParam() == TestSliderType::kContinuousTest) return 1.0f; return *values().crbegin(); } TEST_P(SliderTest, UpdateFromClickHorizontal) { ClickAt(0, 0); EXPECT_EQ(GetMinValue(), slider()->GetValue()); ClickAt(max_x(), 0); EXPECT_EQ(GetMaxValue(), slider()->GetValue()); } TEST_P(SliderTest, UpdateFromClickRTLHorizontal) { base::i18n::SetICUDefaultLocale("he"); ClickAt(0, 0); EXPECT_EQ(GetMaxValue(), slider()->GetValue()); ClickAt(max_x(), 0); EXPECT_EQ(GetMinValue(), slider()->GetValue()); } TEST_P(SliderTest, NukeAllowedValues) { // No more Allowed Values. slider()->SetAllowedValues(nullptr); // Verify that slider is now able to take full scale despite the original // configuration. ClickAt(0, 0); EXPECT_EQ(0, slider()->GetValue()); ClickAt(max_x(), 0); EXPECT_EQ(1, slider()->GetValue()); const int position = max_x() / 18.0f; ClickAt(position, 0); // These values were copied from the slider source. constexpr float kThumbRadius = 4.f; constexpr float kThumbWidth = 2 * kThumbRadius; // This formula is copied here from Slider::MoveButtonTo() to verify that // slider does use full scale and previous Allowed Values no longer affect // calculations. EXPECT_FLOAT_EQ( static_cast<float>( position - test::SliderTestApi(slider()).initial_button_offset()) / (slider()->width() - kThumbWidth), slider()->GetValue()); } TEST_P(SliderTest, AccessibleRole) { ui::AXNodeData data; slider()->GetViewAccessibility().GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kSlider); EXPECT_EQ(slider()->GetAccessibleRole(), ax::mojom::Role::kSlider); slider()->SetAccessibleRole(ax::mojom::Role::kMeter); data = ui::AXNodeData(); slider()->GetViewAccessibility().GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kMeter); EXPECT_EQ(slider()->GetAccessibleRole(), ax::mojom::Role::kMeter); } // No touch on desktop Mac. Tracked in http://crbug.com/445520. #if !BUILDFLAG(IS_MAC) || defined(USE_AURA) // Test the slider location after a tap gesture. TEST_P(SliderTest, SliderValueForTapGesture) { // Tap below the minimum. slider()->SetValue(0.5); event_generator()->GestureTapAt(gfx::Point(0, 0)); EXPECT_FLOAT_EQ(GetMinValue(), slider()->GetValue()); // Tap above the maximum. slider()->SetValue(0.5); event_generator()->GestureTapAt(gfx::Point(max_x(), max_y())); EXPECT_FLOAT_EQ(GetMaxValue(), slider()->GetValue()); // Tap somewhere in the middle. // 0.76 is closer to 0.8 which is important for discrete slider. slider()->SetValue(0.5); event_generator()->GestureTapAt(gfx::Point(0.76 * max_x(), 0.76 * max_y())); if (GetParam() == TestSliderType::kContinuousTest) { EXPECT_NEAR(0.76, slider()->GetValue(), 0.03); } else { // Discrete slider has 0.1 steps. EXPECT_NEAR(0.8, slider()->GetValue(), 0.01); } } // Test the slider location after a scroll gesture. TEST_P(SliderTest, SliderValueForScrollGesture) { // Scroll below the minimum. slider()->SetValue(0.5); event_generator()->GestureScrollSequence( gfx::Point(0.5 * max_x(), 0.5 * max_y()), gfx::Point(0, 0), base::Milliseconds(10), 5 /* steps */); EXPECT_EQ(GetMinValue(), slider()->GetValue()); // Scroll above the maximum. slider()->SetValue(0.5); event_generator()->GestureScrollSequence( gfx::Point(0.5 * max_x(), 0.5 * max_y()), gfx::Point(max_x(), max_y()), base::Milliseconds(10), 5 /* steps */); EXPECT_EQ(GetMaxValue(), slider()->GetValue()); // Scroll somewhere in the middle. // 0.78 is closer to 0.8 which is important for discrete slider. slider()->SetValue(0.25); event_generator()->GestureScrollSequence( gfx::Point(0.25 * max_x(), 0.25 * max_y()), gfx::Point(0.78 * max_x(), 0.78 * max_y()), base::Milliseconds(10), 5 /* steps */); if (GetParam() == TestSliderType::kContinuousTest) { // Continuous slider. EXPECT_NEAR(0.78, slider()->GetValue(), 0.03); } else { // Discrete slider has 0.1 steps. EXPECT_NEAR(0.8, slider()->GetValue(), 0.01); } } // Test the slider location by adjusting it using keyboard. TEST_P(SliderTest, SliderValueForKeyboard) { float value = 0.5; slider()->SetValue(value); slider()->RequestFocus(); event_generator()->PressKey(ui::VKEY_RIGHT, 0); EXPECT_GT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_LEFT, 0); EXPECT_LT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_UP, 0); EXPECT_GT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_DOWN, 0); EXPECT_LT(slider()->GetValue(), value); // RTL reverse left/right but not up/down. base::i18n::SetICUDefaultLocale("he"); EXPECT_TRUE(base::i18n::IsRTL()); event_generator()->PressKey(ui::VKEY_RIGHT, 0); EXPECT_LT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_LEFT, 0); EXPECT_GT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_UP, 0); EXPECT_GT(slider()->GetValue(), value); slider()->SetValue(value); event_generator()->PressKey(ui::VKEY_DOWN, 0); EXPECT_LT(slider()->GetValue(), value); } // Verifies the correct SliderListener events are raised for a tap gesture. TEST_P(SliderTest, SliderListenerEventsForTapGesture) { test::SliderTestApi slider_test_api(slider()); slider_test_api.SetListener(&slider_listener()); event_generator()->GestureTapAt(gfx::Point(0, 0)); EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); EXPECT_EQ(2, slider_listener().last_drag_ended_epoch()); EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); } // Verifies the correct SliderListener events are raised for a scroll gesture. TEST_P(SliderTest, SliderListenerEventsForScrollGesture) { test::SliderTestApi slider_test_api(slider()); slider_test_api.SetListener(&slider_listener()); event_generator()->GestureScrollSequence( gfx::Point(0.25 * max_x(), 0.25 * max_y()), gfx::Point(0.75 * max_x(), 0.75 * max_y()), base::Milliseconds(0), 5 /* steps */); EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); EXPECT_GT(slider_listener().last_drag_ended_epoch(), slider_listener().last_drag_started_epoch()); EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); } // Verifies the correct SliderListener events are raised for a multi // finger scroll gesture. TEST_P(SliderTest, SliderListenerEventsForMultiFingerScrollGesture) { test::SliderTestApi slider_test_api(slider()); slider_test_api.SetListener(&slider_listener()); gfx::Point points[] = {gfx::Point(0, 0.1 * max_y()), gfx::Point(0, 0.2 * max_y())}; event_generator()->GestureMultiFingerScroll( 2 /* count */, points, 0 /* event_separation_time_ms */, 5 /* steps */, 2 /* move_x */, 0 /* move_y */); EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); EXPECT_GT(slider_listener().last_drag_ended_epoch(), slider_listener().last_drag_started_epoch()); EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); } // Verifies the correct SliderListener events are raised for an accessible // slider. TEST_P(SliderTest, SliderRaisesA11yEvents) { test::AXEventCounter ax_counter(views::AXEventManager::Get()); EXPECT_EQ(0, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); // First, detach/reattach the slider without setting value. // Temporarily detach the slider. View* root_view = slider()->parent(); root_view->RemoveChildView(slider()); // Re-attachment should cause nothing to get fired. root_view->AddChildView(slider()); EXPECT_EQ(0, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); // Now, set value before reattaching. root_view->RemoveChildView(slider()); // Value changes won't trigger accessibility events before re-attachment. slider()->SetValue(22); EXPECT_EQ(0, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); // Re-attachment should trigger the value change. root_view->AddChildView(slider()); EXPECT_EQ(1, ax_counter.GetCount(ax::mojom::Event::kValueChanged)); } #endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA) INSTANTIATE_TEST_SUITE_P(All, SliderTest, ::testing::Values(TestSliderType::kContinuousTest, TestSliderType::kDiscreteEnd2EndTest, TestSliderType::kDiscreteInnerTest)); } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/slider_unittest.cc
C++
unknown
16,279
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/styled_label.h" #include <stddef.h> #include <algorithm> #include <limits> #include <utility> #include "base/i18n/rtl.h" #include "base/ranges/algorithm.h" #include "base/strings/string_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/font_list.h" #include "ui/gfx/text_constants.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/text_utils.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/controls/link_fragment.h" #include "ui/views/view_class_properties.h" namespace views { DEFINE_UI_CLASS_PROPERTY_KEY(bool, kStyledLabelCustomViewKey, false) StyledLabel::RangeStyleInfo::RangeStyleInfo() = default; StyledLabel::RangeStyleInfo::RangeStyleInfo(const RangeStyleInfo&) = default; StyledLabel::RangeStyleInfo& StyledLabel::RangeStyleInfo::operator=( const RangeStyleInfo&) = default; StyledLabel::RangeStyleInfo::~RangeStyleInfo() = default; // static StyledLabel::RangeStyleInfo StyledLabel::RangeStyleInfo::CreateForLink( base::RepeatingClosure callback) { // Adapt this closure to a Link::ClickedCallback by discarding the extra arg. return CreateForLink(base::BindRepeating( [](base::RepeatingClosure closure, const ui::Event&) { closure.Run(); }, std::move(callback))); } // static StyledLabel::RangeStyleInfo StyledLabel::RangeStyleInfo::CreateForLink( Link::ClickedCallback callback) { RangeStyleInfo result; result.callback = std::move(callback); result.text_style = style::STYLE_LINK; return result; } StyledLabel::LayoutSizeInfo::LayoutSizeInfo(int max_valid_width) : max_valid_width(max_valid_width) {} StyledLabel::LayoutSizeInfo::LayoutSizeInfo(const LayoutSizeInfo&) = default; StyledLabel::LayoutSizeInfo& StyledLabel::LayoutSizeInfo::operator=( const LayoutSizeInfo&) = default; StyledLabel::LayoutSizeInfo::~LayoutSizeInfo() = default; bool StyledLabel::StyleRange::operator<( const StyledLabel::StyleRange& other) const { return range.start() < other.range.start(); } struct StyledLabel::LayoutViews { // All views to be added as children, line by line. std::vector<std::vector<View*>> views_per_line; // The subset of |views| that are created by StyledLabel itself. Basically, // this is all non-custom views; These appear in the same order as |views|. std::vector<std::unique_ptr<View>> owned_views; }; StyledLabel::StyledLabel() { SetAccessibilityProperties(text_context_ == style::CONTEXT_DIALOG_TITLE ? ax::mojom::Role::kTitleBar : ax::mojom::Role::kStaticText); } StyledLabel::~StyledLabel() = default; const std::u16string& StyledLabel::GetText() const { return text_; } void StyledLabel::SetText(std::u16string text) { // Failing to trim trailing whitespace will cause later confusion when the // text elider tries to do so internally. There's no obvious reason to // preserve trailing whitespace anyway. base::TrimWhitespace(std::move(text), base::TRIM_TRAILING, &text); if (text_ == text) return; text_ = text; SetAccessibleName(text_); style_ranges_.clear(); RemoveOrDeleteAllChildViews(); OnPropertyChanged(&text_, kPropertyEffectsPreferredSizeChanged); } gfx::FontList StyledLabel::GetFontList(const RangeStyleInfo& style_info) const { return style_info.custom_font.value_or(style::GetFont( text_context_, style_info.text_style.value_or(default_text_style_))); } void StyledLabel::AddStyleRange(const gfx::Range& range, const RangeStyleInfo& style_info) { DCHECK(!range.is_reversed()); DCHECK(!range.is_empty()); DCHECK(gfx::Range(0, text_.size()).Contains(range)); // Insert the new range in sorted order. StyleRanges new_range; new_range.emplace_front(range, style_info); style_ranges_.merge(new_range); PreferredSizeChanged(); } void StyledLabel::AddCustomView(std::unique_ptr<View> custom_view) { DCHECK(!custom_view->owned_by_client()); custom_view->SetProperty(kStyledLabelCustomViewKey, true); custom_views_.push_back(std::move(custom_view)); } int StyledLabel::GetTextContext() const { return text_context_; } void StyledLabel::SetTextContext(int text_context) { if (text_context_ == text_context) return; text_context_ = text_context; SetAccessibleRole(text_context_ == style::CONTEXT_DIALOG_TITLE ? ax::mojom::Role::kTitleBar : ax::mojom::Role::kStaticText); OnPropertyChanged(&text_context_, kPropertyEffectsPreferredSizeChanged); } int StyledLabel::GetDefaultTextStyle() const { return default_text_style_; } void StyledLabel::SetDefaultTextStyle(int text_style) { if (default_text_style_ == text_style) return; default_text_style_ = text_style; OnPropertyChanged(&default_text_style_, kPropertyEffectsPreferredSizeChanged); } int StyledLabel::GetLineHeight() const { return line_height_.value_or( style::GetLineHeight(text_context_, default_text_style_)); } void StyledLabel::SetLineHeight(int line_height) { if (line_height_ == line_height) return; line_height_ = line_height; OnPropertyChanged(&line_height_, kPropertyEffectsPreferredSizeChanged); } StyledLabel::ColorVariant StyledLabel::GetDisplayedOnBackgroundColor() const { return displayed_on_background_color_; } void StyledLabel::SetDisplayedOnBackgroundColor(ColorVariant color) { if (color == displayed_on_background_color_) { return; } displayed_on_background_color_ = color; if (GetWidget()) { UpdateLabelBackgroundColor(); } OnPropertyChanged(&displayed_on_background_color_, kPropertyEffectsPaint); } bool StyledLabel::GetAutoColorReadabilityEnabled() const { return auto_color_readability_enabled_; } void StyledLabel::SetAutoColorReadabilityEnabled(bool auto_color_readability) { if (auto_color_readability_enabled_ == auto_color_readability) return; auto_color_readability_enabled_ = auto_color_readability; OnPropertyChanged(&auto_color_readability_enabled_, kPropertyEffectsPaint); } bool StyledLabel::GetSubpixelRenderingEnabled() const { return subpixel_rendering_enabled_; } void StyledLabel::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) { if (subpixel_rendering_enabled_ == subpixel_rendering_enabled) return; subpixel_rendering_enabled_ = subpixel_rendering_enabled; OnPropertyChanged(&subpixel_rendering_enabled_, kPropertyEffectsPaint); } const StyledLabel::LayoutSizeInfo& StyledLabel::GetLayoutSizeInfoForWidth( int w) const { CalculateLayout(w); return layout_size_info_; } void StyledLabel::SizeToFit(int fixed_width) { CalculateLayout(fixed_width == 0 ? std::numeric_limits<int>::max() : fixed_width); gfx::Size size = layout_size_info_.total_size; size.set_width(std::max(size.width(), fixed_width)); SetSize(size); } gfx::Size StyledLabel::CalculatePreferredSize() const { // Respect any existing size. If there is none, default to a single line. CalculateLayout((width() == 0) ? std::numeric_limits<int>::max() : width()); return layout_size_info_.total_size; } int StyledLabel::GetHeightForWidth(int w) const { return GetLayoutSizeInfoForWidth(w).total_size.height(); } void StyledLabel::Layout() { CalculateLayout(width()); // If the layout has been recalculated, add and position all views. if (layout_views_) { // Delete all non-custom views on removal; custom views are temporarily // moved to |custom_views_|. RemoveOrDeleteAllChildViews(); DCHECK_EQ(layout_size_info_.line_sizes.size(), layout_views_->views_per_line.size()); int line_y = GetInsets().top(); auto next_owned_view = layout_views_->owned_views.begin(); for (size_t line = 0; line < layout_views_->views_per_line.size(); ++line) { const auto& line_size = layout_size_info_.line_sizes[line]; int x = StartX(width() - line_size.width()); for (auto* view : layout_views_->views_per_line[line]) { gfx::Size size = view->GetPreferredSize(); size.set_width(std::min(size.width(), width() - x)); // Compute the view y such that the view center y and the line center y // match. Because of added rounding errors, this is not the same as // doing (line_size.height() - size.height()) / 2. const int y = line_size.height() / 2 - size.height() / 2; view->SetBoundsRect({{x, line_y + y}, size}); x += size.width(); // Transfer ownership for any views in layout_views_->owned_views or // custom_views_. The actual pointer is the same in both arms below. if (view->GetProperty(kStyledLabelCustomViewKey)) { auto custom_view = base::ranges::find(custom_views_, view, &std::unique_ptr<View>::get); DCHECK(custom_view != custom_views_.end()); AddChildView(std::move(*custom_view)); custom_views_.erase(custom_view); } else { DCHECK(next_owned_view != layout_views_->owned_views.end()); DCHECK(view == next_owned_view->get()); AddChildView(std::move(*next_owned_view)); ++next_owned_view; } } line_y += line_size.height(); } DCHECK(next_owned_view == layout_views_->owned_views.end()); layout_views_.reset(); } else if (horizontal_alignment_ != gfx::ALIGN_LEFT) { // Recompute all child X coordinates in case the width has shifted, which // will move the children if the label is center/right-aligned. If the // width hasn't changed, all the SetX() calls below will no-op, so this // won't have side effects. int line_bottom = GetInsets().top(); auto i = children().begin(); for (const auto& line_size : layout_size_info_.line_sizes) { DCHECK(i != children().end()); // Should not have an empty trailing line. int x = StartX(width() - line_size.width()); line_bottom += line_size.height(); for (; (i != children().end()) && ((*i)->y() < line_bottom); ++i) { (*i)->SetX(x); x += (*i)->GetPreferredSize().width(); } } DCHECK(i == children().end()); // Should not be short any lines. } } void StyledLabel::PreferredSizeChanged() { layout_size_info_ = LayoutSizeInfo(0); layout_views_.reset(); View::PreferredSizeChanged(); } // TODO(wutao): support gfx::ALIGN_TO_HEAD alignment. void StyledLabel::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { DCHECK_NE(gfx::ALIGN_TO_HEAD, alignment); alignment = gfx::MaybeFlipForRTL(alignment); if (horizontal_alignment_ == alignment) return; horizontal_alignment_ = alignment; PreferredSizeChanged(); } void StyledLabel::ClearStyleRanges() { style_ranges_.clear(); PreferredSizeChanged(); } void StyledLabel::ClickFirstLinkForTesting() { GetFirstLinkForTesting()->OnKeyPressed( // IN-TEST ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE)); } views::Link* StyledLabel::GetFirstLinkForTesting() { const auto it = base::ranges::find(children(), LinkFragment::kViewClassName, &View::GetClassName); DCHECK(it != children().cend()); return static_cast<views::Link*>(*it); } int StyledLabel::StartX(int excess_space) const { int x = GetInsets().left(); // If the element should be aligned to the leading side (left in LTR, or right // in RTL), position it at the leading side Insets (left). if (horizontal_alignment_ == (base::i18n::IsRTL() ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT)) { return x; } return x + (horizontal_alignment_ == gfx::ALIGN_CENTER ? (excess_space / 2) : excess_space); } void StyledLabel::CalculateLayout(int width) const { const gfx::Insets insets = GetInsets(); width = std::max(width, insets.width()); if (width >= layout_size_info_.total_size.width() && width <= layout_size_info_.max_valid_width) return; layout_size_info_ = LayoutSizeInfo(width); layout_views_ = std::make_unique<LayoutViews>(); const int content_width = width - insets.width(); const int line_height = GetLineHeight(); RangeStyleInfo default_style; default_style.text_style = default_text_style_; int max_width = 0, total_height = 0; // Try to preserve leading whitespace on the first line. bool can_trim_leading_whitespace = false; StyleRanges::const_iterator current_range = style_ranges_.begin(); // A pointer to the previous link fragment if a logical link consists of // multiple `LinkFragment` elements. LinkFragment* previous_link_fragment = nullptr; for (std::u16string remaining_string = text_; content_width > 0 && !remaining_string.empty();) { layout_size_info_.line_sizes.emplace_back(0, line_height); auto& line_size = layout_size_info_.line_sizes.back(); layout_views_->views_per_line.emplace_back(); auto& views = layout_views_->views_per_line.back(); while (!remaining_string.empty()) { if (views.empty() && can_trim_leading_whitespace) { if (remaining_string.front() == '\n') { // Wrapped to the next line on \n, remove it. Other whitespace, // e.g. spaces to indent the next line, are preserved. remaining_string.erase(0, 1); } else { // Wrapped on whitespace character or characters in the middle of the // line - none of them are needed at the beginning of the next line. base::TrimWhitespace(remaining_string, base::TRIM_LEADING, &remaining_string); } } gfx::Range range = gfx::Range::InvalidRange(); if (current_range != style_ranges_.end()) range = current_range->range; const size_t position = text_.size() - remaining_string.size(); std::vector<std::u16string> substrings; // If the current range is not a custom_view, then we use // ElideRectangleText() to determine the line wrapping. Note: if it is a // custom_view, then the |position| should equal range.start() because the // custom_view is treated as one unit. if (position != range.start() || (current_range != style_ranges_.end() && !current_range->style_info.custom_view)) { const gfx::Rect chunk_bounds(line_size.width(), 0, content_width - line_size.width(), line_height); // If the start of the remaining text is inside a styled range, the font // style may differ from the base font. The font specified by the range // should be used when eliding text. gfx::FontList text_font_list = GetFontList((position >= range.start()) ? current_range->style_info : RangeStyleInfo()); int elide_result = gfx::ElideRectangleText( remaining_string, text_font_list, chunk_bounds.width(), chunk_bounds.height(), gfx::WRAP_LONG_WORDS, &substrings); if (substrings.empty()) { // There is no room for anything. Since wrapping is enabled, this // should only occur if there is insufficient vertical space // remaining. ElideRectangleText() always adds a single character, // even if there is no room horizontally. DCHECK_NE(0, elide_result & gfx::INSUFFICIENT_SPACE_VERTICAL); // There's no way to continue processing; clear |remaining_string| so // the outer loop will terminate after this iteration completes. remaining_string.clear(); break; } // Views are aligned to integer coordinates, but typesetting is not. // This means that it's possible for an ElideRectangleText on a prior // iteration to fit a word on the current line, which does not fit after // that word is wrapped in a View for its chunk at the end of the line. // In most cases, this will just wrap more words on to the next line. // However, if the remaining chunk width is insufficient for the very // _first_ word, that word will be incorrectly split. In this case, // start a new line instead. bool truncated_chunk = line_size.width() != 0 && (elide_result & gfx::INSUFFICIENT_SPACE_FOR_FIRST_WORD) != 0; if (substrings[0].empty() || truncated_chunk) { // The entire line is \n, or nothing else fits on this line. Wrap, // unless this is the first line, in which case we strip leading // whitespace and try again. if ((line_size.width() != 0) || (layout_views_->views_per_line.size() > 1)) break; can_trim_leading_whitespace = true; continue; } } std::u16string chunk; View* custom_view = nullptr; std::unique_ptr<Label> label; if (position >= range.start()) { const RangeStyleInfo& style_info = current_range->style_info; if (style_info.custom_view) { custom_view = style_info.custom_view; // Custom views must be marked as such. DCHECK(custom_view->GetProperty(kStyledLabelCustomViewKey)); // Do not allow wrap in custom view. DCHECK_EQ(position, range.start()); chunk = remaining_string.substr(0, range.end() - position); } else { chunk = substrings[0]; } if ((custom_view && line_size.width() + custom_view->GetPreferredSize().width() > content_width) && position == range.start() && line_size.width() != 0) { // If the chunk should not be wrapped, try to fit it entirely on the // next line. break; } if (chunk.size() > range.end() - position) chunk = chunk.substr(0, range.end() - position); if (!custom_view) { label = CreateLabel(chunk, style_info, range, &previous_link_fragment); } else { previous_link_fragment = nullptr; } if (position + chunk.size() >= range.end()) { ++current_range; // Links do not connect across separate style ranges. previous_link_fragment = nullptr; } } else { chunk = substrings[0]; if (position + chunk.size() > range.start()) chunk = chunk.substr(0, range.start() - position); // This chunk is normal text. label = CreateLabel(chunk, default_style, range, &previous_link_fragment); } View* child_view = custom_view ? custom_view : label.get(); const gfx::Size child_size = child_view->GetPreferredSize(); // A custom view could be wider than the available width. line_size.SetSize( std::min(line_size.width() + child_size.width(), content_width), std::max(line_size.height(), child_size.height())); views.push_back(child_view); if (label) layout_views_->owned_views.push_back(std::move(label)); remaining_string = remaining_string.substr(chunk.size()); // If |gfx::ElideRectangleText| returned more than one substring, that // means the whole text did not fit into remaining line width, with text // after |susbtring[0]| spilling into next line. If whole |substring[0]| // was added to the current line (this may not be the case if part of the // substring has different style), proceed to the next line. if (!custom_view && substrings.size() > 1 && chunk.size() == substrings[0].size()) { break; } } if (views.empty() && remaining_string.empty()) { // Remove an empty last line. layout_size_info_.line_sizes.pop_back(); layout_views_->views_per_line.pop_back(); } else { max_width = std::max(max_width, line_size.width()); total_height += line_size.height(); // Trim whitespace at the start of the next line. can_trim_leading_whitespace = true; } } layout_size_info_.total_size.SetSize(max_width + insets.width(), total_height + insets.height()); } std::unique_ptr<Label> StyledLabel::CreateLabel( const std::u16string& text, const RangeStyleInfo& style_info, const gfx::Range& range, LinkFragment** previous_link_fragment) const { std::unique_ptr<Label> result; if (style_info.text_style == style::STYLE_LINK) { // Nothing should (and nothing does) use a custom font for links. DCHECK(!style_info.custom_font); // Note this ignores |default_text_style_|, in favor of `style::STYLE_LINK`. auto link = std::make_unique<LinkFragment>( text, text_context_, style::STYLE_LINK, *previous_link_fragment); *previous_link_fragment = link.get(); link->SetCallback(style_info.callback); if (!style_info.accessible_name.empty()) link->SetAccessibleName(style_info.accessible_name); result = std::move(link); } else if (style_info.custom_font) { result = std::make_unique<Label>( text, Label::CustomFont{style_info.custom_font.value()}); } else { result = std::make_unique<Label>( text, text_context_, style_info.text_style.value_or(default_text_style_)); } if (style_info.override_color) result->SetEnabledColor(style_info.override_color.value()); if (!style_info.tooltip.empty()) result->SetTooltipText(style_info.tooltip); if (!style_info.accessible_name.empty()) result->SetAccessibleName(style_info.accessible_name); if (absl::holds_alternative<SkColor>(displayed_on_background_color_)) { result->SetBackgroundColor( absl::get<SkColor>(displayed_on_background_color_)); } else if (absl::holds_alternative<ui::ColorId>( displayed_on_background_color_)) { result->SetBackgroundColorId( absl::get<ui::ColorId>(displayed_on_background_color_)); } result->SetAutoColorReadabilityEnabled(auto_color_readability_enabled_); result->SetSubpixelRenderingEnabled(subpixel_rendering_enabled_); return result; } void StyledLabel::UpdateLabelBackgroundColor() { for (View* child : children()) { if (!child->GetProperty(kStyledLabelCustomViewKey)) { // TODO(kylixrd): Should updating the label background color even be // allowed if there are custom views? DCHECK((child->GetClassName() == Label::kViewClassName) || (child->GetClassName() == LinkFragment::kViewClassName)); static_cast<Label*>(child)->SetBackgroundColorId( absl::holds_alternative<ui::ColorId>(displayed_on_background_color_) ? absl::optional<ui::ColorId>( absl::get<ui::ColorId>(displayed_on_background_color_)) : absl::nullopt); if (absl::holds_alternative<SkColor>(displayed_on_background_color_)) { static_cast<Label*>(child)->SetBackgroundColor( absl::get<SkColor>(displayed_on_background_color_)); } } } } void StyledLabel::RemoveOrDeleteAllChildViews() { while (children().size() > 0) { std::unique_ptr<View> view = RemoveChildViewT(children()[0]); if (view->GetProperty(kStyledLabelCustomViewKey)) custom_views_.push_back(std::move(view)); } } BEGIN_METADATA(StyledLabel, View) ADD_PROPERTY_METADATA(std::u16string, Text) ADD_PROPERTY_METADATA(int, TextContext) ADD_PROPERTY_METADATA(int, DefaultTextStyle) ADD_PROPERTY_METADATA(int, LineHeight) ADD_PROPERTY_METADATA(bool, AutoColorReadabilityEnabled) ADD_PROPERTY_METADATA(StyledLabel::ColorVariant, DisplayedOnBackgroundColor) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/styled_label.cc
C++
unknown
24,109
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_STYLED_LABEL_H_ #define UI_VIEWS_CONTROLS_STYLED_LABEL_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/class_property.h" #include "ui/color/color_id.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/range/range.h" #include "ui/gfx/text_constants.h" #include "ui/views/controls/link.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/style/typography.h" #include "ui/views/view.h" namespace views { class Label; class Link; class LinkFragment; // A class which can apply mixed styles to a block of text. Currently, text is // always multiline. Trailing whitespace in the styled label text is not // supported and will be trimmed on StyledLabel construction. Leading // whitespace is respected, provided not only whitespace fits in the first line. // In this case, leading whitespace is ignored. class VIEWS_EXPORT StyledLabel : public View { public: METADATA_HEADER(StyledLabel); // Parameters that define label style for a styled label's text range. struct VIEWS_EXPORT RangeStyleInfo { RangeStyleInfo(); RangeStyleInfo(const RangeStyleInfo&); RangeStyleInfo& operator=(const RangeStyleInfo&); ~RangeStyleInfo(); // Creates a range style info with default values for link. static RangeStyleInfo CreateForLink(Link::ClickedCallback callback); static RangeStyleInfo CreateForLink(base::RepeatingClosure callback); // Allows full customization of the font used in the range. Ignores the // StyledLabel's default text context and |text_style|. absl::optional<gfx::FontList> custom_font; // The style::TextStyle for this range. absl::optional<int> text_style; // Overrides the text color given by |text_style| for this range. // DEPRECATED: Use TextStyle. absl::optional<SkColor> override_color; // A callback to be called when this link is clicked. Only used if // |text_style| is style::STYLE_LINK. Link::ClickedCallback callback; // Tooltip for the range. std::u16string tooltip; // Accessible name for the range. std::u16string accessible_name; // A custom view shown instead of the underlying text. Ownership of custom // views must be passed to StyledLabel via AddCustomView(). raw_ptr<View> custom_view = nullptr; }; // Sizing information for laying out the label based on a particular width. struct VIEWS_EXPORT LayoutSizeInfo { explicit LayoutSizeInfo(int max_valid_width); LayoutSizeInfo(const LayoutSizeInfo&); LayoutSizeInfo& operator=(const LayoutSizeInfo&); ~LayoutSizeInfo(); // The maximum width for which this info is guaranteed to be valid. // Requesting a larger width than this will force a recomputation. int max_valid_width = 0; // The actual size needed to lay out the label for a requested width of // |max_valid_width|. total_size.width() is at most |max_valid_width| but // may be smaller depending on how line wrapping is computed. Requesting a // smaller width than this will force a recomputation. gfx::Size total_size; // The sizes of each line of child views. |total_size| can be computed // directly from these values and is kept separately just for convenience. std::vector<gfx::Size> line_sizes; }; using ColorVariant = absl::variant<absl::monostate, SkColor, ui::ColorId>; StyledLabel(); StyledLabel(const StyledLabel&) = delete; StyledLabel& operator=(const StyledLabel&) = delete; ~StyledLabel() override; // Sets the text to be displayed, and clears any previous styling. Trailing // whitespace is trimmed from the text. const std::u16string& GetText() const; void SetText(std::u16string text); // Returns the FontList that should be used. |style_info| is an optional // argument that takes precedence over the default values. gfx::FontList GetFontList( const RangeStyleInfo& style_info = RangeStyleInfo()) const; // Marks the given range within |text_| with style defined by |style_info|. // |range| must be contained in |text_|. void AddStyleRange(const gfx::Range& range, const RangeStyleInfo& style_info); // Passes ownership of a custom view for use by RangeStyleInfo structs. void AddCustomView(std::unique_ptr<View> custom_view); // Get/Set the context of this text. All ranges have the same context. // |text_context| must be a value from views::style::TextContext. int GetTextContext() const; void SetTextContext(int text_context); // Set the default text style. // |text_style| must be a value from views::style::TextStyle. int GetDefaultTextStyle() const; void SetDefaultTextStyle(int text_style); // Get or set the distance in pixels between baselines of multi-line text. // Default is 0, indicating the distance between lines should be the standard // one for the label's text, font list, and platform. int GetLineHeight() const; void SetLineHeight(int height); // Gets/Sets the color or color id of the background on which the label is // drawn. This won't be explicitly drawn, but the label will force the text // color to be readable over it. ColorVariant GetDisplayedOnBackgroundColor() const; void SetDisplayedOnBackgroundColor(ColorVariant color); bool GetAutoColorReadabilityEnabled() const; void SetAutoColorReadabilityEnabled(bool auto_color_readability); bool GetSubpixelRenderingEnabled() const; void SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled); // Returns the layout size information that would be used to layout the label // at width |w|. This can be used by callers who need more detail than what's // provided by GetHeightForWidth(). const LayoutSizeInfo& GetLayoutSizeInfoForWidth(int w) const; // Resizes the label so its width is set to the fixed width and its height // deduced accordingly. Even if all widths of the lines are shorter than // |fixed_width|, the given value is applied to the element's width. // This is only intended for multi-line labels and is useful when the label's // text contains several lines separated with \n. // |fixed_width| is the fixed width that will be used (longer lines will be // wrapped). If 0, no fixed width is enforced. void SizeToFit(int fixed_width); // View: gfx::Size CalculatePreferredSize() const override; int GetHeightForWidth(int w) const override; void Layout() override; void PreferredSizeChanged() override; // Sets the horizontal alignment; the argument value is mirrored in RTL UI. void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); // Clears all the styles applied to the label. void ClearStyleRanges(); // Sends a space keypress to the first child that is a link. Assumes at least // one such child exists. void ClickFirstLinkForTesting(); // Get the first child that is a link. views::Link* GetFirstLinkForTesting(); private: struct StyleRange { StyleRange(const gfx::Range& range, const RangeStyleInfo& style_info) : range(range), style_info(style_info) {} ~StyleRange() = default; bool operator<(const StyleRange& other) const; gfx::Range range; RangeStyleInfo style_info; }; using StyleRanges = std::list<StyleRange>; // Child view-related information for layout. struct LayoutViews; // Returns the starting X coordinate for the views in a line, based on the // current |horizontal_alignment_| and insets and given the amount of excess // space available on that line. int StartX(int excess_space) const; // Sets |layout_size_info_| and |layout_views_| for the given |width|. No-op // if current_width <= width <= max_width, where: // current_width = layout_size_info_.total_size.width() // width = max(width, GetInsets().width()) // max_width = layout_size_info_.max_valid_width void CalculateLayout(int width) const; // Creates a Label for a given |text|, |style_info|, and |range|. std::unique_ptr<Label> CreateLabel( const std::u16string& text, const RangeStyleInfo& style_info, const gfx::Range& range, LinkFragment** previous_link_component) const; // Update the label background color from the theme or // |displayed_on_background_color_| if set. void UpdateLabelBackgroundColor(); // Remove all child views. Place all custom views back into custom_views_ and // delete the rest. void RemoveOrDeleteAllChildViews(); // The text to display. std::u16string text_; int text_context_ = style::CONTEXT_LABEL; int default_text_style_ = style::STYLE_PRIMARY; absl::optional<int> line_height_; // The ranges that should be linkified, sorted by start position. StyleRanges style_ranges_; // Temporarily owns the custom views until they've been been placed into the // StyledLabel's child list. This list also holds the custom views during // layout. std::list<std::unique_ptr<View>> custom_views_; // Saves the effects of the last CalculateLayout() call to avoid repeated // calculation. |layout_size_info_| can then be cached until the next // recalculation, while |layout_views_| only exists until the next Layout(). mutable LayoutSizeInfo layout_size_info_{0}; mutable std::unique_ptr<LayoutViews> layout_views_; // Background color on which the label is drawn, for auto color readability. ColorVariant displayed_on_background_color_; // Controls whether the text is automatically re-colored to be readable on the // background. bool auto_color_readability_enabled_ = true; // Controls whether subpixel rendering is enabled. bool subpixel_rendering_enabled_ = true; // The horizontal alignment. This value is flipped for RTL. The default // behavior is to align left in LTR UI and right in RTL UI. gfx::HorizontalAlignment horizontal_alignment_ = base::i18n::IsRTL() ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, StyledLabel, View) VIEW_BUILDER_PROPERTY(const std::u16string&, Text) VIEW_BUILDER_PROPERTY(int, TextContext) VIEW_BUILDER_PROPERTY(int, DefaultTextStyle) VIEW_BUILDER_PROPERTY(int, LineHeight) VIEW_BUILDER_PROPERTY(StyledLabel::ColorVariant, DisplayedOnBackgroundColor) VIEW_BUILDER_PROPERTY(bool, AutoColorReadabilityEnabled) VIEW_BUILDER_PROPERTY(gfx::HorizontalAlignment, HorizontalAlignment) VIEW_BUILDER_METHOD(SizeToFit, int) VIEW_BUILDER_METHOD(AddStyleRange, gfx::Range, StyledLabel::RangeStyleInfo) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, views::StyledLabel) #endif // UI_VIEWS_CONTROLS_STYLED_LABEL_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/styled_label.h
C++
unknown
11,023
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/styled_label.h" #include <stddef.h> #include <memory> #include <string> #include <utility> #include "base/command_line.h" #include "base/functional/callback.h" #include "base/i18n/base_i18n_switches.h" #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/test/icu_test_util.h" #include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/font_list.h" #include "ui/gfx/text_constants.h" #include "ui/views/border.h" #include "ui/views/controls/link.h" #include "ui/views/controls/link_fragment.h" #include "ui/views/style/typography.h" #include "ui/views/test/test_layout_provider.h" #include "ui/views/test/test_views.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/widget/widget.h" using base::ASCIIToUTF16; namespace views { namespace { using ::testing::SizeIs; Label* LabelAt(StyledLabel* styled, size_t index, std::string expected_classname = Label::kViewClassName) { View* const child = styled->children()[index]; EXPECT_EQ(expected_classname, child->GetClassName()); return static_cast<Label*>(child); } int StyledLabelContentHeightForWidth(StyledLabel* styled, int w) { return styled->GetHeightForWidth(w) - styled->GetInsets().height(); } } // namespace class StyledLabelTest : public ViewsTestBase { public: StyledLabelTest() = default; StyledLabelTest(const StyledLabelTest&) = delete; StyledLabelTest& operator=(const StyledLabelTest&) = delete; ~StyledLabelTest() override = default; protected: StyledLabel* styled() const { return styled_.get(); } void InitStyledLabel(const std::string& ascii_text) { styled_ = std::make_unique<StyledLabel>(); styled_->SetText(ASCIIToUTF16(ascii_text)); } private: std::unique_ptr<StyledLabel> styled_; }; class StyledLabelInWidgetTest : public ViewsTestBase { public: StyledLabelInWidgetTest() = default; StyledLabelInWidgetTest(const StyledLabelInWidgetTest&) = delete; StyledLabelInWidgetTest& operator=(const StyledLabelInWidgetTest&) = delete; ~StyledLabelInWidgetTest() override = default; protected: void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateTestWidget(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } StyledLabel* styled() const { return styled_; } Widget* widget() const { return widget_.get(); } void InitStyledLabel(const std::string& ascii_text) { View* container = widget_->SetContentsView(std::make_unique<View>()); styled_ = container->AddChildView(std::make_unique<StyledLabel>()); styled_->SetText(ASCIIToUTF16(ascii_text)); } private: raw_ptr<StyledLabel> styled_; std::unique_ptr<Widget> widget_; }; TEST_F(StyledLabelTest, NoWrapping) { const std::string text("This is a test block of text"); InitStyledLabel(text); Label label(ASCIIToUTF16(text)); const gfx::Size label_preferred_size = label.GetPreferredSize(); EXPECT_EQ(label_preferred_size.height(), StyledLabelContentHeightForWidth(styled(), label_preferred_size.width() * 2)); } TEST_F(StyledLabelTest, TrailingWhitespaceiIgnored) { const std::string text("This is a test block of text "); InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); EXPECT_EQ(u"This is a test block of text", LabelAt(styled(), 0)->GetText()); } TEST_F(StyledLabelTest, RespectLeadingWhitespace) { const std::string text(" This is a test block of text"); InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); EXPECT_EQ(u" This is a test block of text", LabelAt(styled(), 0)->GetText()); } TEST_F(StyledLabelTest, RespectLeadingSpacesInNonFirstLine) { const std::string indented_line = " indented line"; const std::string text(std::string("First line\n") + indented_line); InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(ASCIIToUTF16(indented_line), LabelAt(styled(), 1)->GetText()); } TEST_F(StyledLabelTest, CorrectWrapAtNewline) { const std::string first_line = "Line one"; const std::string second_line = " two"; const std::string multiline_text(first_line + "\n" + second_line); InitStyledLabel(multiline_text); Label label(ASCIIToUTF16(first_line)); gfx::Size label_preferred_size = label.GetPreferredSize(); // Correct handling of \n and label width limit encountered at the same place styled()->SetBounds(0, 0, label_preferred_size.width(), 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(ASCIIToUTF16(first_line), LabelAt(styled(), 0)->GetText()); const auto* label_1 = LabelAt(styled(), 1); EXPECT_EQ(ASCIIToUTF16(second_line), label_1->GetText()); EXPECT_EQ(styled()->GetHeightForWidth(1000), label_1->bounds().bottom()); } TEST_F(StyledLabelTest, FirstLineNotEmptyWhenLeadingWhitespaceTooLong) { const std::string text(" a"); InitStyledLabel(text); Label label(ASCIIToUTF16(text)); gfx::Size label_preferred_size = label.GetPreferredSize(); styled()->SetBounds(0, 0, label_preferred_size.width() / 2, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); EXPECT_EQ(u"a", LabelAt(styled(), 0)->GetText()); EXPECT_EQ(label_preferred_size.height(), styled()->GetHeightForWidth(label_preferred_size.width() / 2)); } TEST_F(StyledLabelTest, BasicWrapping) { const std::string text("This is a test block of text"); InitStyledLabel(text); Label label(ASCIIToUTF16(text.substr(0, text.size() * 2 / 3))); gfx::Size label_preferred_size = label.GetPreferredSize(); EXPECT_EQ( label_preferred_size.height() * 2, StyledLabelContentHeightForWidth(styled(), label_preferred_size.width())); // Also respect the border. styled()->SetBorder(CreateEmptyBorder(3)); styled()->SetBounds( 0, 0, styled()->GetInsets().width() + label_preferred_size.width(), styled()->GetInsets().height() + 2 * label_preferred_size.height()); test::RunScheduledLayout(styled()); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(3, styled()->children()[0]->x()); EXPECT_EQ(3, styled()->children()[0]->y()); EXPECT_EQ(styled()->height() - 3, styled()->children()[1]->bounds().bottom()); } TEST_F(StyledLabelTest, AllowEmptyLines) { const std::string text("one"); InitStyledLabel(text); int default_height = styled()->GetHeightForWidth(1000); const std::string multiline_text("one\n\nthree"); InitStyledLabel(multiline_text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); EXPECT_EQ(3 * default_height, styled()->GetHeightForWidth(1000)); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(styled()->GetHeightForWidth(1000), styled()->children()[1]->bounds().bottom()); } TEST_F(StyledLabelTest, WrapLongWords) { const std::string text("ThisIsTextAsASingleWord"); InitStyledLabel(text); Label label(ASCIIToUTF16(text.substr(0, text.size() * 2 / 3))); gfx::Size label_preferred_size = label.GetPreferredSize(); EXPECT_EQ( label_preferred_size.height() * 2, StyledLabelContentHeightForWidth(styled(), label_preferred_size.width())); styled()->SetBounds( 0, 0, styled()->GetInsets().width() + label_preferred_size.width(), styled()->GetInsets().height() + 2 * label_preferred_size.height()); test::RunScheduledLayout(styled()); ASSERT_EQ(2u, styled()->children().size()); ASSERT_EQ(gfx::Point(), styled()->origin()); const auto* label_0 = LabelAt(styled(), 0); const auto* label_1 = LabelAt(styled(), 1); EXPECT_EQ(gfx::Point(), label_0->origin()); EXPECT_EQ(gfx::Point(0, styled()->height() / 2), label_1->origin()); EXPECT_FALSE(label_0->GetText().empty()); EXPECT_FALSE(label_1->GetText().empty()); EXPECT_EQ(ASCIIToUTF16(text), label_0->GetText() + label_1->GetText()); } TEST_F(StyledLabelTest, CreateLinks) { const std::string text("This is a test block of text."); InitStyledLabel(text); // Without links, there should be no focus border. EXPECT_TRUE(styled()->GetInsets().IsEmpty()); // Now let's add some links. styled()->AddStyleRange( gfx::Range(0, 1), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); styled()->AddStyleRange( gfx::Range(1, 2), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); styled()->AddStyleRange( gfx::Range(10, 11), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); styled()->AddStyleRange( gfx::Range(12, 13), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); // Insets shouldn't change when links are added, since the links indicate // focus by adding an underline instead. EXPECT_TRUE(styled()->GetInsets().IsEmpty()); // Verify layout creates the right number of children. styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); EXPECT_EQ(7u, styled()->children().size()); } TEST_F(StyledLabelTest, StyledRangeCustomFontUnderlined) { const std::string text("This is a test block of text, "); const std::string underlined_text("and this should be undelined"); InitStyledLabel(text + underlined_text); StyledLabel::RangeStyleInfo style_info; style_info.tooltip = u"tooltip"; style_info.custom_font = styled()->GetFontList().DeriveWithStyle(gfx::Font::UNDERLINE); styled()->AddStyleRange( gfx::Range(text.size(), text.size() + underlined_text.size()), style_info); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(gfx::Font::UNDERLINE, LabelAt(styled(), 1)->font_list().GetFontStyle()); } TEST_F(StyledLabelTest, StyledRangeTextStyleBold) { test::TestLayoutProvider bold_provider; const std::string bold_text( "This is a block of text whose style will be set to BOLD in the test"); const std::string text(" normal text"); InitStyledLabel(bold_text + text); // Pretend disabled text becomes bold for testing. auto details = bold_provider.GetFontDetails(style::CONTEXT_LABEL, style::STYLE_DISABLED); details.weight = gfx::Font::Weight::BOLD; bold_provider.SetFontDetails(style::CONTEXT_LABEL, style::STYLE_DISABLED, details); StyledLabel::RangeStyleInfo style_info; style_info.text_style = style::STYLE_DISABLED; styled()->AddStyleRange(gfx::Range(0u, bold_text.size()), style_info); // Calculate the bold text width if it were a pure label view, both with bold // and normal style. Label label(ASCIIToUTF16(bold_text)); const gfx::Size normal_label_size = label.GetPreferredSize(); label.SetFontList( label.font_list().DeriveWithWeight(gfx::Font::Weight::BOLD)); const gfx::Size bold_label_size = label.GetPreferredSize(); ASSERT_GE(bold_label_size.width(), normal_label_size.width()); // Set the width so |bold_text| doesn't fit on a single line with bold style, // but does with normal font style. int styled_width = (normal_label_size.width() + bold_label_size.width()) / 2; int pref_height = styled()->GetHeightForWidth(styled_width); // Sanity check that |bold_text| with normal font style would fit on a single // line in a styled label with width |styled_width|. StyledLabel unstyled; unstyled.SetText(ASCIIToUTF16(bold_text)); unstyled.SetBounds(0, 0, styled_width, pref_height); test::RunScheduledLayout(&unstyled); EXPECT_EQ(1u, unstyled.children().size()); styled()->SetBounds(0, 0, styled_width, pref_height); test::RunScheduledLayout(styled()); ASSERT_EQ(3u, styled()->children().size()); // The bold text should be broken up into two parts. const auto* label_0 = LabelAt(styled(), 0); const auto* label_1 = LabelAt(styled(), 1); const auto* label_2 = LabelAt(styled(), 2); EXPECT_EQ(gfx::Font::Weight::BOLD, label_0->font_list().GetFontWeight()); EXPECT_EQ(gfx::Font::Weight::BOLD, label_1->font_list().GetFontWeight()); EXPECT_EQ(gfx::Font::NORMAL, label_2->font_list().GetFontStyle()); // The second bold part should start on a new line. EXPECT_EQ(0, label_0->x()); EXPECT_EQ(0, label_1->x()); EXPECT_EQ(label_1->bounds().right(), label_2->x()); } TEST_F(StyledLabelInWidgetTest, Color) { const std::string text_blue("BLUE"); const std::string text_link("link"); const std::string text("word"); InitStyledLabel(text_blue + text_link + text); StyledLabel::RangeStyleInfo style_info_blue; style_info_blue.override_color = SK_ColorBLUE; styled()->AddStyleRange(gfx::Range(0u, text_blue.size()), style_info_blue); StyledLabel::RangeStyleInfo style_info_link = StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure()); styled()->AddStyleRange( gfx::Range(text_blue.size(), text_blue.size() + text_link.size()), style_info_link); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); // The code below is not prepared to deal with dark mode. auto* const native_theme = widget()->GetNativeTheme(); native_theme->set_use_dark_colors(false); native_theme->NotifyOnNativeThemeUpdated(); auto* container = widget()->GetContentsView(); // Obtain the default text color for a label. Label* label = container->AddChildView(std::make_unique<Label>(ASCIIToUTF16(text))); const SkColor kDefaultTextColor = label->GetEnabledColor(); // Obtain the default text color for a link. Link* link = container->AddChildView(std::make_unique<Link>(ASCIIToUTF16(text_link))); const SkColor kDefaultLinkColor = link->GetEnabledColor(); ASSERT_EQ(3u, styled()->children().size()); EXPECT_EQ(SK_ColorBLUE, LabelAt(styled(), 0)->GetEnabledColor()); EXPECT_EQ( kDefaultLinkColor, LabelAt(styled(), 1, LinkFragment::kViewClassName)->GetEnabledColor()); EXPECT_EQ(kDefaultTextColor, LabelAt(styled(), 2)->GetEnabledColor()); // Test adjusted color readability. styled()->SetDisplayedOnBackgroundColor(SK_ColorBLACK); test::RunScheduledLayout(styled()); label->SetBackgroundColor(SK_ColorBLACK); const SkColor kAdjustedTextColor = label->GetEnabledColor(); EXPECT_NE(kAdjustedTextColor, kDefaultTextColor); EXPECT_EQ(kAdjustedTextColor, LabelAt(styled(), 2)->GetEnabledColor()); } TEST_F(StyledLabelInWidgetTest, SetBackgroundColor) { InitStyledLabel("test label"); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_THAT(styled()->children(), SizeIs(1u)); // The default background color is `ui::kColorDialogBackground`. EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorDialogBackground), LabelAt(styled(), 0)->GetBackgroundColor()); styled()->SetDisplayedOnBackgroundColor(SK_ColorBLUE); EXPECT_EQ(SK_ColorBLUE, LabelAt(styled(), 0)->GetBackgroundColor()); styled()->SetDisplayedOnBackgroundColor(ui::kColorAlertHighSeverity); EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorAlertHighSeverity), LabelAt(styled(), 0)->GetBackgroundColor()); // Setting a color overwrites the color id. styled()->SetDisplayedOnBackgroundColor(SK_ColorCYAN); EXPECT_EQ(SK_ColorCYAN, LabelAt(styled(), 0)->GetBackgroundColor()); } TEST_F(StyledLabelInWidgetTest, SetBackgroundColorIdReactsToThemeChange) { InitStyledLabel("test label"); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_THAT(styled()->children(), SizeIs(1u)); auto* const native_theme = widget()->GetNativeTheme(); native_theme->set_use_dark_colors(true); native_theme->NotifyOnNativeThemeUpdated(); EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorDialogBackground), LabelAt(styled(), 0)->GetBackgroundColor()); native_theme->set_use_dark_colors(false); native_theme->NotifyOnNativeThemeUpdated(); EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorDialogBackground), LabelAt(styled(), 0)->GetBackgroundColor()); styled()->SetDisplayedOnBackgroundColor(ui::kColorAlertHighSeverity); EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorAlertHighSeverity), LabelAt(styled(), 0)->GetBackgroundColor()); native_theme->set_use_dark_colors(true); native_theme->NotifyOnNativeThemeUpdated(); EXPECT_EQ(widget()->GetColorProvider()->GetColor(ui::kColorAlertHighSeverity), LabelAt(styled(), 0)->GetBackgroundColor()); } TEST_F(StyledLabelTest, StyledRangeWithTooltip) { const std::string text("This is a test block of text, "); const std::string tooltip_text("this should have a tooltip,"); const std::string normal_text(" this should not have a tooltip, "); const std::string link_text("and this should be a link"); const size_t tooltip_start = text.size(); const size_t link_start = text.size() + tooltip_text.size() + normal_text.size(); InitStyledLabel(text + tooltip_text + normal_text + link_text); StyledLabel::RangeStyleInfo tooltip_style; tooltip_style.tooltip = u"tooltip"; styled()->AddStyleRange( gfx::Range(tooltip_start, tooltip_start + tooltip_text.size()), tooltip_style); styled()->AddStyleRange( gfx::Range(link_start, link_start + link_text.size()), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); // Break line inside the range with the tooltip. Label label( ASCIIToUTF16(text + tooltip_text.substr(0, tooltip_text.size() - 3))); gfx::Size label_preferred_size = label.GetPreferredSize(); int pref_height = styled()->GetHeightForWidth(label_preferred_size.width()); EXPECT_EQ(label_preferred_size.height() * 3, pref_height - styled()->GetInsets().height()); styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height); test::RunScheduledLayout(styled()); EXPECT_EQ(label_preferred_size.width(), styled()->width()); ASSERT_EQ(6u, styled()->children().size()); // The labels shouldn't be offset to cater for focus rings. EXPECT_EQ(0, styled()->children()[0]->x()); EXPECT_EQ(0, styled()->children()[2]->x()); EXPECT_EQ(styled()->children()[0]->bounds().right(), styled()->children()[1]->x()); EXPECT_EQ(styled()->children()[2]->bounds().right(), styled()->children()[3]->x()); std::u16string tooltip = styled()->children()[1]->GetTooltipText(gfx::Point(1, 1)); EXPECT_EQ(u"tooltip", tooltip); tooltip = styled()->children()[2]->GetTooltipText(gfx::Point(1, 1)); EXPECT_EQ(u"tooltip", tooltip); } TEST_F(StyledLabelTest, SetTextContextAndDefaultStyle) { const std::string text("This is a test block of text."); InitStyledLabel(text); styled()->SetTextContext(style::CONTEXT_DIALOG_TITLE); styled()->SetDefaultTextStyle(style::STYLE_DISABLED); Label label(ASCIIToUTF16(text), style::CONTEXT_DIALOG_TITLE, style::STYLE_DISABLED); styled()->SetBounds(0, 0, label.GetPreferredSize().width(), label.GetPreferredSize().height()); // Make sure we have the same sizing as a label with the same style. EXPECT_EQ(label.GetPreferredSize().height(), styled()->height()); EXPECT_EQ(label.GetPreferredSize().width(), styled()->width()); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); Label* sublabel = LabelAt(styled(), 0); EXPECT_EQ(style::CONTEXT_DIALOG_TITLE, sublabel->GetTextContext()); EXPECT_NE(SK_ColorBLACK, label.GetEnabledColor()); // Sanity check, EXPECT_EQ(label.GetEnabledColor(), sublabel->GetEnabledColor()); } TEST_F(StyledLabelTest, LineHeight) { const std::string text("one\ntwo\nthree"); InitStyledLabel(text); styled()->SetLineHeight(18); EXPECT_EQ(18 * 3, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, LineHeightWithBorder) { const std::string text("one\ntwo\nthree"); InitStyledLabel(text); styled()->SetLineHeight(18); styled()->SetBorder(views::CreateSolidBorder(1, SK_ColorGRAY)); EXPECT_EQ(18 * 3 + 2, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, LineHeightWithLink) { const std::string text("one\ntwo\nthree"); InitStyledLabel(text); styled()->SetLineHeight(18); styled()->AddStyleRange( gfx::Range(0, 3), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); styled()->AddStyleRange( gfx::Range(4, 7), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); styled()->AddStyleRange( gfx::Range(8, 13), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); EXPECT_EQ(18 * 3, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, HandleEmptyLayout) { const std::string text("This is a test block of text."); InitStyledLabel(text); test::RunScheduledLayout(styled()); EXPECT_EQ(0u, styled()->children().size()); } TEST_F(StyledLabelTest, CacheSize) { const int preferred_height = 50; const int preferred_width = 100; const std::string text("This is a test block of text."); const std::u16string another_text( u"This is a test block of text. This text is much longer than previous"); InitStyledLabel(text); // we should be able to calculate height without any problem // no controls should be created int precalculated_height = styled()->GetHeightForWidth(preferred_width); EXPECT_LT(0, precalculated_height); EXPECT_EQ(0u, styled()->children().size()); styled()->SetBounds(0, 0, preferred_width, preferred_height); test::RunScheduledLayout(styled()); // controls should be created after layout // height should be the same as precalculated int real_height = styled()->GetHeightForWidth(styled()->width()); View* first_child_after_layout = styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_LT(0u, styled()->children().size()); EXPECT_LT(0, real_height); EXPECT_EQ(real_height, precalculated_height); // another call to Layout should not kill and recreate all controls test::RunScheduledLayout(styled()); View* first_child_after_second_layout = styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_EQ(first_child_after_layout, first_child_after_second_layout); // if text is changed: // layout should be recalculated // all controls should be recreated styled()->SetText(another_text); int updated_height = styled()->GetHeightForWidth(styled()->width()); EXPECT_NE(updated_height, real_height); View* first_child_after_text_update = styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_NE(first_child_after_text_update, first_child_after_layout); } TEST_F(StyledLabelTest, Border) { const std::string text("One line"); InitStyledLabel(text); Label label(ASCIIToUTF16(text)); gfx::Size label_preferred_size = label.GetPreferredSize(); styled()->SetBorder(CreateEmptyBorder(gfx::Insets::TLBR(5, 10, 6, 20))); styled()->SetBounds(0, 0, 1000, 0); test::RunScheduledLayout(styled()); EXPECT_EQ( label_preferred_size.height() + 5 /*top border*/ + 6 /*bottom border*/, styled()->GetPreferredSize().height()); EXPECT_EQ( label_preferred_size.width() + 10 /*left border*/ + 20 /*right border*/, styled()->GetPreferredSize().width()); } TEST_F(StyledLabelTest, LineHeightWithShorterCustomView) { const std::string text("one "); InitStyledLabel(text); int default_height = styled()->GetHeightForWidth(1000); const std::string custom_view_text("with custom view"); const int less_height = 10; std::unique_ptr<View> custom_view = std::make_unique<StaticSizedView>( gfx::Size(20, default_height - less_height)); StyledLabel::RangeStyleInfo style_info; style_info.custom_view = custom_view.get(); InitStyledLabel(text + custom_view_text); styled()->AddStyleRange( gfx::Range(text.size(), text.size() + custom_view_text.size()), style_info); styled()->AddCustomView(std::move(custom_view)); EXPECT_EQ(default_height, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, LineHeightWithTallerCustomView) { const std::string text("one "); InitStyledLabel(text); int default_height = styled()->GetHeightForWidth(100); const std::string custom_view_text("with custom view"); const int more_height = 10; std::unique_ptr<View> custom_view = std::make_unique<StaticSizedView>( gfx::Size(20, default_height + more_height)); StyledLabel::RangeStyleInfo style_info; style_info.custom_view = custom_view.get(); InitStyledLabel(text + custom_view_text); styled()->AddStyleRange( gfx::Range(text.size(), text.size() + custom_view_text.size()), style_info); styled()->AddCustomView(std::move(custom_view)); EXPECT_EQ(default_height + more_height, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, LineWrapperWithCustomView) { const std::string text_before("one "); InitStyledLabel(text_before); int default_height = styled()->GetHeightForWidth(100); const std::string custom_view_text("two with custom view "); const std::string text_after("three"); int custom_view_height = 25; std::unique_ptr<View> custom_view = std::make_unique<StaticSizedView>(gfx::Size(200, custom_view_height)); StyledLabel::RangeStyleInfo style_info; style_info.custom_view = custom_view.get(); InitStyledLabel(text_before + custom_view_text + text_after); styled()->AddStyleRange( gfx::Range(text_before.size(), text_before.size() + custom_view_text.size()), style_info); styled()->AddCustomView(std::move(custom_view)); EXPECT_EQ(default_height * 2 + custom_view_height, styled()->GetHeightForWidth(100)); } TEST_F(StyledLabelTest, AlignmentInLTR) { const std::string text("text"); InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); const auto& children = styled()->children(); ASSERT_EQ(1u, children.size()); // Test the default alignment puts the text on the leading side (left). EXPECT_EQ(0, children.front()->bounds().x()); // Setting |ALIGN_RIGHT| indicates the text should be aligned to the trailing // side, and hence its trailing side coordinates (i.e. right) should align // with the trailing side coordinate of the label (right). styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); test::RunScheduledLayout(styled()); EXPECT_EQ(1000, children.front()->bounds().right()); // Setting |ALIGN_LEFT| indicates the text should be aligned to the leading // side, and hence its leading side coordinates (i.e. x) should align with the // leading side coordinate of the label (x). styled()->SetHorizontalAlignment(gfx::ALIGN_LEFT); test::RunScheduledLayout(styled()); EXPECT_EQ(0, children.front()->bounds().x()); styled()->SetHorizontalAlignment(gfx::ALIGN_CENTER); test::RunScheduledLayout(styled()); Label label(ASCIIToUTF16(text)); EXPECT_EQ((1000 - label.GetPreferredSize().width()) / 2, children.front()->bounds().x()); } TEST_F(StyledLabelTest, AlignmentInRTL) { // |g_icu_text_direction| is cached to prevent reading new commandline switch. // Set |g_icu_text_direction| to |UNKNOWN_DIRECTION| in order to read the new // commandline switch. base::test::ScopedRestoreICUDefaultLocale scoped_locale("en_US"); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kForceUIDirection, switches::kForceDirectionRTL); const std::string text("text"); InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); const auto& children = styled()->children(); ASSERT_EQ(1u, children.size()); // Test the default alignment puts the text on the leading side (right). // Note that x-coordinates in RTL place the origin (0) on the right. EXPECT_EQ(0, children.front()->bounds().x()); // Setting |ALIGN_RIGHT| indicates the text should be aligned to the trailing // side, and hence its trailing side coordinates (i.e. right) should align // with the trailing side coordinate of the label (right). styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); test::RunScheduledLayout(styled()); EXPECT_EQ(1000, children.front()->bounds().right()); // Setting |ALIGN_LEFT| indicates the text should be aligned to the leading // side, and hence its leading side coordinates (i.e. x) should align with the // leading side coordinate of the label (x). styled()->SetHorizontalAlignment(gfx::ALIGN_LEFT); test::RunScheduledLayout(styled()); EXPECT_EQ(0, children.front()->bounds().x()); styled()->SetHorizontalAlignment(gfx::ALIGN_CENTER); test::RunScheduledLayout(styled()); Label label(ASCIIToUTF16(text)); EXPECT_EQ((1000 - label.GetPreferredSize().width()) / 2, children.front()->bounds().x()); } TEST_F(StyledLabelTest, ViewsCenteredWithLinkAndCustomView) { const std::string text("This is a test block of text, "); const std::string link_text("and this should be a link"); const std::string custom_view_text("And this is a custom view"); InitStyledLabel(text + link_text + custom_view_text); styled()->AddStyleRange( gfx::Range(text.size(), text.size() + link_text.size()), StyledLabel::RangeStyleInfo::CreateForLink(base::RepeatingClosure())); int custom_view_height = 25; std::unique_ptr<View> custom_view = std::make_unique<StaticSizedView>(gfx::Size(20, custom_view_height)); StyledLabel::RangeStyleInfo style_info; style_info.custom_view = custom_view.get(); styled()->AddStyleRange( gfx::Range(text.size() + link_text.size(), text.size() + link_text.size() + custom_view_text.size()), style_info); styled()->AddCustomView(std::move(custom_view)); styled()->SetBounds(0, 0, 1000, 500); test::RunScheduledLayout(styled()); const int height = styled()->GetPreferredSize().height(); for (const auto* child : styled()->children()) EXPECT_EQ(height / 2, child->bounds().CenterPoint().y()); } TEST_F(StyledLabelTest, ViewsCenteredForEvenAndOddSizes) { constexpr int kViewWidth = 30; for (int height : {60, 61}) { InitStyledLabel("abc"); const int view_heights[] = {height, height / 2, height / 2 + 1}; for (uint32_t i = 0; i < 3; ++i) { auto view = std::make_unique<StaticSizedView>( gfx::Size(kViewWidth, view_heights[i])); StyledLabel::RangeStyleInfo style_info; style_info.custom_view = view.get(); styled()->AddStyleRange(gfx::Range(i, i + 1), style_info); styled()->AddCustomView(std::move(view)); } styled()->SetBounds(0, 0, kViewWidth * 3, height); test::RunScheduledLayout(styled()); for (const auto* child : styled()->children()) EXPECT_EQ(height / 2, child->bounds().CenterPoint().y()); } } TEST_F(StyledLabelTest, CacheSizeWithAlignment) { const std::string text("text"); InitStyledLabel(text); styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); styled()->SetBounds(0, 0, 1000, 1000); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); const View* child = styled()->children().front(); EXPECT_EQ(1000, child->bounds().right()); styled()->SetSize({800, 1000}); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); const View* new_child = styled()->children().front(); EXPECT_EQ(child, new_child); EXPECT_EQ(800, new_child->bounds().right()); } // Verifies that calling SizeToFit() on a label which requires less width still // causes it to take the whole requested width. TEST_F(StyledLabelTest, SizeToFit) { const std::string text("text"); InitStyledLabel(text); styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); styled()->SizeToFit(1000); test::RunScheduledLayout(styled()); ASSERT_EQ(1u, styled()->children().size()); EXPECT_EQ(1000, styled()->children().front()->bounds().right()); } // Verifies that a non-empty label has a preferred size by default. TEST_F(StyledLabelTest, PreferredSizeNonEmpty) { const std::string text("text"); InitStyledLabel(text); EXPECT_FALSE(styled()->GetPreferredSize().IsEmpty()); } // Verifies that GetPreferredSize() respects the existing wrapping. TEST_F(StyledLabelTest, PreferredSizeRespectsWrapping) { const std::string text("Long text that can be split across lines"); InitStyledLabel(text); gfx::Size size = styled()->GetPreferredSize(); size.set_width(size.width() / 2); size.set_height(styled()->GetHeightForWidth(size.width())); styled()->SetSize(size); test::RunScheduledLayout(styled()); const gfx::Size new_size = styled()->GetPreferredSize(); EXPECT_LE(new_size.width(), size.width()); EXPECT_EQ(new_size.height(), size.height()); } // Verifies that calling a const method does not change the preferred size. TEST_F(StyledLabelTest, PreferredSizeAcrossConstCall) { const std::string text("Long text that can be split across lines"); InitStyledLabel(text); const gfx::Size size = styled()->GetPreferredSize(); styled()->GetHeightForWidth(size.width() / 2); EXPECT_EQ(size, styled()->GetPreferredSize()); } TEST_F(StyledLabelTest, AccessibleNameAndRole) { const std::string text("Text"); InitStyledLabel(text); EXPECT_EQ(styled()->GetAccessibleName(), base::UTF8ToUTF16(text)); EXPECT_EQ(styled()->GetAccessibleRole(), ax::mojom::Role::kStaticText); ui::AXNodeData data; styled()->GetAccessibleNodeData(&data); EXPECT_EQ(data.GetStringAttribute(ax::mojom::StringAttribute::kName), text); EXPECT_EQ(data.role, ax::mojom::Role::kStaticText); styled()->SetTextContext(style::CONTEXT_DIALOG_TITLE); EXPECT_EQ(styled()->GetAccessibleName(), base::UTF8ToUTF16(text)); EXPECT_EQ(styled()->GetAccessibleRole(), ax::mojom::Role::kTitleBar); data = ui::AXNodeData(); styled()->GetAccessibleNodeData(&data); EXPECT_EQ(data.GetStringAttribute(ax::mojom::StringAttribute::kName), text); EXPECT_EQ(data.role, ax::mojom::Role::kTitleBar); styled()->SetText(u"New Text"); styled()->SetAccessibleRole(ax::mojom::Role::kLink); EXPECT_EQ(styled()->GetAccessibleName(), u"New Text"); EXPECT_EQ(styled()->GetAccessibleRole(), ax::mojom::Role::kLink); data = ui::AXNodeData(); styled()->GetAccessibleNodeData(&data); EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName), u"New Text"); EXPECT_EQ(data.role, ax::mojom::Role::kLink); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/styled_label_unittest.cc
C++
unknown
35,049
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include <algorithm> #include <string> #include <utility> #include "base/check_op.h" #include "base/i18n/rtl.h" #include "build/build_config.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/default_style.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/controls/label.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/layout_manager.h" #include "ui/views/view_class_properties.h" #include "ui/views/widget/widget.h" namespace views { TabbedPaneTab::TabbedPaneTab(TabbedPane* tabbed_pane, const std::u16string& title, View* contents) : tabbed_pane_(tabbed_pane), contents_(contents) { // Calculate the size while the font list is bold. auto title_label = std::make_unique<Label>(title, style::CONTEXT_LABEL, style::STYLE_TAB_ACTIVE); title_ = title_label.get(); UpdatePreferredTitleWidth(); if (tabbed_pane_->GetOrientation() == TabbedPane::Orientation::kVertical) { title_label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); const bool is_highlight_style = tabbed_pane_->GetStyle() == TabbedPane::TabStripStyle::kHighlight; constexpr auto kTabPadding = gfx::Insets::VH(5, 10); constexpr auto kTabPaddingHighlight = gfx::Insets::TLBR(8, 32, 8, 0); SetBorder(CreateEmptyBorder(is_highlight_style ? kTabPaddingHighlight : kTabPadding)); } else { constexpr auto kBorderThickness = gfx::Insets(2); SetBorder(CreateEmptyBorder(kBorderThickness)); } SetState(State::kInactive); AddChildView(std::move(title_label)); SetLayoutManager(std::make_unique<FillLayout>()); // Use leaf so that name is spoken by screen reader without exposing the // children. GetViewAccessibility().OverrideIsLeaf(true); OnStateChanged(); } TabbedPaneTab::~TabbedPaneTab() = default; void TabbedPaneTab::SetSelected(bool selected) { contents_->SetVisible(selected); contents_->parent()->InvalidateLayout(); SetState(selected ? State::kActive : State::kInactive); #if BUILDFLAG(IS_MAC) SetFocusBehavior(selected ? FocusBehavior::ACCESSIBLE_ONLY : FocusBehavior::NEVER); #else SetFocusBehavior(selected ? FocusBehavior::ALWAYS : FocusBehavior::NEVER); #endif } const std::u16string& TabbedPaneTab::GetTitleText() const { return title_->GetText(); } void TabbedPaneTab::SetTitleText(const std::u16string& text) { title_->SetText(text); UpdatePreferredTitleWidth(); PreferredSizeChanged(); } bool TabbedPaneTab::OnMousePressed(const ui::MouseEvent& event) { if (GetEnabled() && event.IsOnlyLeftMouseButton()) tabbed_pane_->SelectTab(this); return true; } void TabbedPaneTab::OnMouseEntered(const ui::MouseEvent& event) { SetState(selected() ? State::kActive : State::kHovered); } void TabbedPaneTab::OnMouseExited(const ui::MouseEvent& event) { SetState(selected() ? State::kActive : State::kInactive); } void TabbedPaneTab::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: case ui::ET_GESTURE_TAP: // SelectTab also sets the right tab color. tabbed_pane_->SelectTab(this); break; case ui::ET_GESTURE_TAP_CANCEL: SetState(selected() ? State::kActive : State::kInactive); break; default: break; } event->SetHandled(); } gfx::Size TabbedPaneTab::CalculatePreferredSize() const { int width = preferred_title_width_ + GetInsets().width(); if (tabbed_pane_->GetStyle() == TabbedPane::TabStripStyle::kHighlight && tabbed_pane_->GetOrientation() == TabbedPane::Orientation::kVertical) width = std::max(width, 192); return gfx::Size(width, 32); } void TabbedPaneTab::GetAccessibleNodeData(ui::AXNodeData* data) { data->role = ax::mojom::Role::kTab; data->SetName(title_->GetText()); data->SetNameFrom(ax::mojom::NameFrom::kContents); data->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, selected()); } bool TabbedPaneTab::HandleAccessibleAction( const ui::AXActionData& action_data) { // If the assistive tool sends kSetSelection, handle it like kDoDefault. // These generate a click event handled in TabbedPaneTab::OnMousePressed. ui::AXActionData action_data_copy(action_data); if (action_data.action == ax::mojom::Action::kSetSelection) action_data_copy.action = ax::mojom::Action::kDoDefault; return View::HandleAccessibleAction(action_data_copy); } void TabbedPaneTab::OnFocus() { // Do not draw focus ring in kHighlight mode. if (tabbed_pane_->GetStyle() != TabbedPane::TabStripStyle::kHighlight) { // Maintain the current Insets with CreatePaddedBorder. int border_size = 2; SetBorder(CreatePaddedBorder( CreateSolidBorder(border_size, GetColorProvider()->GetColor( ui::kColorFocusableBorderFocused)), GetInsets() - gfx::Insets(border_size))); } SchedulePaint(); } void TabbedPaneTab::OnBlur() { // Do not draw focus ring in kHighlight mode. if (tabbed_pane_->GetStyle() != TabbedPane::TabStripStyle::kHighlight) SetBorder(CreateEmptyBorder(GetInsets())); SchedulePaint(); } bool TabbedPaneTab::OnKeyPressed(const ui::KeyEvent& event) { const ui::KeyboardCode key = event.key_code(); if (tabbed_pane_->GetOrientation() == TabbedPane::Orientation::kHorizontal) { // Use left and right arrows to navigate tabs in horizontal orientation. return (key == ui::VKEY_LEFT || key == ui::VKEY_RIGHT) && tabbed_pane_->MoveSelectionBy(key == ui::VKEY_RIGHT ? 1 : -1); } // Use up and down arrows to navigate tabs in vertical orientation. return (key == ui::VKEY_UP || key == ui::VKEY_DOWN) && tabbed_pane_->MoveSelectionBy(key == ui::VKEY_DOWN ? 1 : -1); } void TabbedPaneTab::OnThemeChanged() { View::OnThemeChanged(); UpdateTitleColor(); } void TabbedPaneTab::SetState(State state) { if (state == state_) return; state_ = state; OnStateChanged(); SchedulePaint(); } void TabbedPaneTab::OnStateChanged() { // Update colors that depend on state if present in a Widget hierarchy. if (GetWidget()) UpdateTitleColor(); // TabbedPaneTab design spec dictates special handling of font weight for // the windows platform when dealing with border style tabs. #if BUILDFLAG(IS_WIN) gfx::Font::Weight font_weight = gfx::Font::Weight::BOLD; #else gfx::Font::Weight font_weight = gfx::Font::Weight::MEDIUM; #endif int font_size_delta = ui::kLabelFontSizeDelta; if (tabbed_pane_->GetStyle() == TabbedPane::TabStripStyle::kHighlight) { // Notify assistive tools to update this tab's selected status. The way // ChromeOS accessibility is implemented right now, firing almost any event // will work, we just need to trigger its state to be refreshed. if (state_ == State::kInactive) NotifyAccessibilityEvent(ax::mojom::Event::kCheckedStateChanged, true); // Style the tab text according to the spec for highlight style tabs. We no // longer have windows specific bolding of text in this case. font_size_delta = 1; if (state_ == State::kActive) font_weight = gfx::Font::Weight::BOLD; else font_weight = gfx::Font::Weight::MEDIUM; } ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); title_->SetFontList(rb.GetFontListForDetails(ui::ResourceBundle::FontDetails( std::string(), font_size_delta, font_weight))); } void TabbedPaneTab::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); // Paints the active tab for the vertical highlighted tabbed pane. if (!selected() || tabbed_pane_->GetOrientation() != TabbedPane::Orientation::kVertical || tabbed_pane_->GetStyle() != TabbedPane::TabStripStyle::kHighlight) { return; } constexpr SkScalar kRadius = SkIntToScalar(32); constexpr SkScalar kLTRRadii[8] = {0, 0, kRadius, kRadius, kRadius, kRadius, 0, 0}; constexpr SkScalar kRTLRadii[8] = {kRadius, kRadius, 0, 0, 0, 0, kRadius, kRadius}; SkPath path; path.addRoundRect(gfx::RectToSkRect(GetLocalBounds()), base::i18n::IsRTL() ? kRTLRadii : kLTRRadii); cc::PaintFlags fill_flags; fill_flags.setAntiAlias(true); fill_flags.setColor(GetColorProvider()->GetColor( HasFocus() ? ui::kColorTabBackgroundHighlightedFocused : ui::kColorTabBackgroundHighlighted)); canvas->DrawPath(path, fill_flags); } void TabbedPaneTab::UpdatePreferredTitleWidth() { // Active and inactive states use different font sizes. Find the largest size // and reserve that amount of space. const State old_state = state_; SetState(State::kActive); preferred_title_width_ = title_->GetPreferredSize().width(); SetState(State::kInactive); preferred_title_width_ = std::max(preferred_title_width_, title_->GetPreferredSize().width()); SetState(old_state); } void TabbedPaneTab::UpdateTitleColor() { DCHECK(GetWidget()); const SkColor font_color = GetColorProvider()->GetColor( state_ == State::kActive ? ui::kColorTabForegroundSelected : ui::kColorTabForeground); title_->SetEnabledColor(font_color); } BEGIN_METADATA(TabbedPaneTab, View) END_METADATA // static constexpr size_t TabStrip::kNoSelectedTab; TabStrip::TabStrip(TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style) : orientation_(orientation), style_(style) { std::unique_ptr<BoxLayout> layout; if (orientation == TabbedPane::Orientation::kHorizontal) { layout = std::make_unique<BoxLayout>(BoxLayout::Orientation::kHorizontal); layout->set_main_axis_alignment(BoxLayout::MainAxisAlignment::kCenter); layout->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kStretch); layout->SetDefaultFlex(1); } else { constexpr auto kEdgePadding = gfx::Insets::TLBR(8, 0, 0, 0); constexpr int kTabSpacing = 8; layout = std::make_unique<BoxLayout>(BoxLayout::Orientation::kVertical, kEdgePadding, kTabSpacing); layout->set_main_axis_alignment(BoxLayout::MainAxisAlignment::kStart); layout->set_cross_axis_alignment(BoxLayout::CrossAxisAlignment::kStart); layout->SetDefaultFlex(0); } SetLayoutManager(std::move(layout)); GetViewAccessibility().OverrideRole(ax::mojom::Role::kNone); // These durations are taken from the Paper Tabs source: // https://github.com/PolymerElements/paper-tabs/blob/master/paper-tabs.html // See |selectionBar.expand| and |selectionBar.contract|. expand_animation_->SetDuration(base::Milliseconds(150)); contract_animation_->SetDuration(base::Milliseconds(180)); } TabStrip::~TabStrip() = default; void TabStrip::AnimationProgressed(const gfx::Animation* animation) { SchedulePaint(); } void TabStrip::AnimationEnded(const gfx::Animation* animation) { if (animation == expand_animation_.get()) contract_animation_->Start(); } void TabStrip::OnSelectedTabChanged(TabbedPaneTab* from_tab, TabbedPaneTab* to_tab, bool animate) { DCHECK(!from_tab->selected()); DCHECK(to_tab->selected()); if (!animate || !GetWidget()) return; if (GetOrientation() == TabbedPane::Orientation::kHorizontal) { animating_from_ = {from_tab->GetMirroredX(), from_tab->GetMirroredX() + from_tab->width()}; animating_to_ = {to_tab->GetMirroredX(), to_tab->GetMirroredX() + to_tab->width()}; } else { animating_from_ = {from_tab->bounds().y(), from_tab->bounds().y() + from_tab->height()}; animating_to_ = {to_tab->bounds().y(), to_tab->bounds().y() + to_tab->height()}; } contract_animation_->Stop(); expand_animation_->Start(); } TabbedPaneTab* TabStrip::GetSelectedTab() const { size_t index = GetSelectedTabIndex(); return index == kNoSelectedTab ? nullptr : GetTabAtIndex(index); } TabbedPaneTab* TabStrip::GetTabAtDeltaFromSelected(int delta) const { const size_t selected_tab_index = GetSelectedTabIndex(); DCHECK_NE(kNoSelectedTab, selected_tab_index); const size_t num_children = children().size(); // Clamping |delta| here ensures that even a large negative |delta| will be // positive after the addition in the next statement. delta %= base::checked_cast<int>(num_children); delta += static_cast<int>(num_children); return GetTabAtIndex((selected_tab_index + static_cast<size_t>(delta)) % num_children); } TabbedPaneTab* TabStrip::GetTabAtIndex(size_t index) const { DCHECK_LT(index, children().size()); return static_cast<TabbedPaneTab*>(children()[index]); } size_t TabStrip::GetSelectedTabIndex() const { for (size_t i = 0; i < children().size(); ++i) if (GetTabAtIndex(i)->selected()) return i; return kNoSelectedTab; } TabbedPane::Orientation TabStrip::GetOrientation() const { return orientation_; } TabbedPane::TabStripStyle TabStrip::GetStyle() const { return style_; } gfx::Size TabStrip::CalculatePreferredSize() const { // In horizontal mode, use the preferred size as determined by the largest // child or the minimum size necessary to display the tab titles, whichever is // larger. if (GetOrientation() == TabbedPane::Orientation::kHorizontal) { return GetLayoutManager()->GetPreferredSize(this); } // In vertical mode, Tabstrips don't require any minimum space along their // main axis, and can shrink all the way to zero size. Only the cross axis // thickness matters. const gfx::Size size = GetLayoutManager()->GetPreferredSize(this); return gfx::Size(size.width(), 0); } void TabStrip::OnPaintBorder(gfx::Canvas* canvas) { // Do not draw border line in kHighlight mode. if (GetStyle() == TabbedPane::TabStripStyle::kHighlight) return; // First, draw the unselected border across the TabStrip's entire width or // height, depending on the orientation of the tab alignment. The area // underneath or on the right of the selected tab will be overdrawn later. const bool is_horizontal = GetOrientation() == TabbedPane::Orientation::kHorizontal; int max_cross_axis; gfx::Rect rect; constexpr int kUnselectedBorderThickness = 1; if (is_horizontal) { max_cross_axis = children().front()->bounds().bottom(); rect = gfx::Rect(0, max_cross_axis - kUnselectedBorderThickness, width(), kUnselectedBorderThickness); } else { max_cross_axis = width(); rect = gfx::Rect(max_cross_axis - kUnselectedBorderThickness, 0, kUnselectedBorderThickness, height()); } canvas->FillRect(rect, GetColorProvider()->GetColor(ui::kColorTabContentSeparator)); TabbedPaneTab* tab = GetSelectedTab(); if (!tab) return; // Now, figure out the range to draw the selection marker underneath. There // are three states here: // 1) Expand animation is running: use FAST_OUT_LINEAR_IN to grow the // selection marker until it encompasses both the previously selected tab // and the currently selected tab; // 2) Contract animation is running: use LINEAR_OUT_SLOW_IN to shrink the // selection marker until it encompasses only the currently selected tab; // 3) No animations running: the selection marker is only under the currently // selected tab. int min_main_axis = 0; int max_main_axis = 0; if (expand_animation_->is_animating()) { bool animating_leading = animating_to_.start < animating_from_.start; double anim_value = gfx::Tween::CalculateValue( gfx::Tween::FAST_OUT_LINEAR_IN, expand_animation_->GetCurrentValue()); if (animating_leading) { min_main_axis = gfx::Tween::IntValueBetween( anim_value, animating_from_.start, animating_to_.start); max_main_axis = animating_from_.end; } else { min_main_axis = animating_from_.start; max_main_axis = gfx::Tween::IntValueBetween( anim_value, animating_from_.end, animating_to_.end); } } else if (contract_animation_->is_animating()) { bool animating_leading = animating_to_.start < animating_from_.start; double anim_value = gfx::Tween::CalculateValue( gfx::Tween::LINEAR_OUT_SLOW_IN, contract_animation_->GetCurrentValue()); if (animating_leading) { min_main_axis = animating_to_.start; max_main_axis = gfx::Tween::IntValueBetween( anim_value, animating_from_.end, animating_to_.end); } else { min_main_axis = gfx::Tween::IntValueBetween( anim_value, animating_from_.start, animating_to_.start); max_main_axis = animating_to_.end; } } else if (is_horizontal) { min_main_axis = tab->GetMirroredX(); max_main_axis = min_main_axis + tab->width(); } else { min_main_axis = tab->bounds().y(); max_main_axis = min_main_axis + tab->height(); } DCHECK_NE(min_main_axis, max_main_axis); // Draw over the unselected border from above. constexpr int kSelectedBorderThickness = 2; rect = gfx::Rect(min_main_axis, max_cross_axis - kSelectedBorderThickness, max_main_axis - min_main_axis, kSelectedBorderThickness); if (!is_horizontal) rect.Transpose(); canvas->FillRect(rect, GetColorProvider()->GetColor(ui::kColorTabBorderSelected)); } BEGIN_METADATA(TabStrip, View) ADD_READONLY_PROPERTY_METADATA(size_t, SelectedTabIndex) ADD_READONLY_PROPERTY_METADATA(TabbedPane::Orientation, Orientation) ADD_READONLY_PROPERTY_METADATA(TabbedPane::TabStripStyle, Style) END_METADATA TabbedPane::TabbedPane(TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style, bool scrollable) { DCHECK(orientation != TabbedPane::Orientation::kHorizontal || style != TabbedPane::TabStripStyle::kHighlight); auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); if (orientation == TabbedPane::Orientation::kHorizontal) layout->SetOrientation(views::LayoutOrientation::kVertical); auto tab_strip = std::make_unique<TabStrip>(orientation, style); if (scrollable) { scroll_view_ = AddChildView( std::make_unique<ScrollView>(ScrollView::ScrollWithLayers::kEnabled)); tab_strip_ = tab_strip.get(); scroll_view_->SetContents(std::move(tab_strip)); scroll_view_->ClipHeightTo(0, 0); } else { tab_strip_ = AddChildView(std::move(tab_strip)); } contents_ = AddChildView(std::make_unique<View>()); contents_->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToZero, views::MaximumFlexSizeRule::kUnbounded)); contents_->SetLayoutManager(std::make_unique<views::FillLayout>()); // Support navigating tabs by Ctrl+TabbedPaneTab and Ctrl+Shift+TabbedPaneTab. AddAccelerator( ui::Accelerator(ui::VKEY_TAB, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN)); AddAccelerator(ui::Accelerator(ui::VKEY_TAB, ui::EF_CONTROL_DOWN)); } TabbedPane::~TabbedPane() = default; size_t TabbedPane::GetSelectedTabIndex() const { return tab_strip_->GetSelectedTabIndex(); } size_t TabbedPane::GetTabCount() const { DCHECK_EQ(tab_strip_->children().size(), contents_->children().size()); return contents_->children().size(); } void TabbedPane::AddTabInternal(size_t index, const std::u16string& title, std::unique_ptr<View> contents) { DCHECK_LE(index, GetTabCount()); contents->SetVisible(false); contents->GetViewAccessibility().OverrideRole(ax::mojom::Role::kTabPanel); if (!title.empty()) contents->GetViewAccessibility().OverrideName(title); tab_strip_->AddChildViewAt( std::make_unique<TabbedPaneTab>(this, title, contents.get()), index); contents_->AddChildViewAt(std::move(contents), index); if (!GetSelectedTab()) SelectTabAt(index); PreferredSizeChanged(); } void TabbedPane::SelectTab(TabbedPaneTab* new_selected_tab, bool animate) { TabbedPaneTab* old_selected_tab = tab_strip_->GetSelectedTab(); if (old_selected_tab == new_selected_tab) return; new_selected_tab->SetSelected(true); if (old_selected_tab) { if (old_selected_tab->HasFocus()) new_selected_tab->RequestFocus(); old_selected_tab->SetSelected(false); tab_strip_->OnSelectedTabChanged(old_selected_tab, new_selected_tab, animate); new_selected_tab->NotifyAccessibilityEvent(ax::mojom::Event::kSelection, true); NotifyAccessibilityEvent(ax::mojom::Event::kSelectedChildrenChanged, true); } tab_strip_->SchedulePaint(); FocusManager* focus_manager = new_selected_tab->contents()->GetFocusManager(); if (focus_manager) { const View* focused_view = focus_manager->GetFocusedView(); if (focused_view && contents_->Contains(focused_view) && !new_selected_tab->contents()->Contains(focused_view)) focus_manager->SetFocusedView(new_selected_tab->contents()); } if (listener()) { listener()->TabSelectedAt(base::checked_cast<int>( tab_strip_->GetIndexOf(new_selected_tab).value())); } } void TabbedPane::SelectTabAt(size_t index, bool animate) { TabbedPaneTab* tab = tab_strip_->GetTabAtIndex(index); if (tab) SelectTab(tab, animate); } ScrollView* TabbedPane::GetScrollView() { return scroll_view_; } TabbedPane::Orientation TabbedPane::GetOrientation() const { return tab_strip_->GetOrientation(); } TabbedPane::TabStripStyle TabbedPane::GetStyle() const { return tab_strip_->GetStyle(); } TabbedPaneTab* TabbedPane::GetTabAt(size_t index) { return tab_strip_->GetTabAtIndex(index); } TabbedPaneTab* TabbedPane::GetSelectedTab() { return tab_strip_->GetSelectedTab(); } View* TabbedPane::GetSelectedTabContentView() { return GetSelectedTab() ? GetSelectedTab()->contents() : nullptr; } bool TabbedPane::MoveSelectionBy(int delta) { if (contents_->children().size() <= 1) return false; SelectTab(tab_strip_->GetTabAtDeltaFromSelected(delta)); return true; } bool TabbedPane::AcceleratorPressed(const ui::Accelerator& accelerator) { // Handle Ctrl+TabbedPaneTab and Ctrl+Shift+TabbedPaneTab navigation of pages. DCHECK(accelerator.key_code() == ui::VKEY_TAB && accelerator.IsCtrlDown()); return MoveSelectionBy(accelerator.IsShiftDown() ? -1 : 1); } void TabbedPane::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kTabList; const TabbedPaneTab* const selected_tab = GetSelectedTab(); if (selected_tab) node_data->SetName(selected_tab->GetTitleText()); } BEGIN_METADATA(TabbedPane, View) END_METADATA } // namespace views DEFINE_ENUM_CONVERTERS(views::TabbedPane::Orientation, {views::TabbedPane::Orientation::kHorizontal, u"HORIZONTAL"}, {views::TabbedPane::Orientation::kVertical, u"VERTICAL"}) DEFINE_ENUM_CONVERTERS(views::TabbedPane::TabStripStyle, {views::TabbedPane::TabStripStyle::kBorder, u"BORDER"}, {views::TabbedPane::TabStripStyle::kHighlight, u"HIGHLIGHT"})
Zhao-PengFei35/chromium_src_4
ui/views/controls/tabbed_pane/tabbed_pane.cc
C++
unknown
24,383
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_ #define UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_ #include <memory> #include <string> #include <utility> #include "base/memory/raw_ptr.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" namespace views { class Label; class TabbedPaneTab; class TabbedPaneListener; class TabStrip; namespace test { class TabbedPaneAccessibilityMacTest; class TabbedPaneWithWidgetTest; } // namespace test // TabbedPane is a view that shows tabs. When the user clicks on a tab, the // associated view is displayed. // Support for horizontal-highlight and vertical-border modes is limited and // may require additional polish. class VIEWS_EXPORT TabbedPane : public View { public: METADATA_HEADER(TabbedPane); // The orientation of the tab alignment. enum class Orientation { kHorizontal, kVertical, }; // The style of the tab strip. enum class TabStripStyle { kBorder, // Draw border around the selected tab. kHighlight, // Highlight background and text of the selected tab. }; explicit TabbedPane(Orientation orientation = Orientation::kHorizontal, TabStripStyle style = TabStripStyle::kBorder, bool scrollable = false); TabbedPane(const TabbedPane&) = delete; TabbedPane& operator=(const TabbedPane&) = delete; ~TabbedPane() override; TabbedPaneListener* listener() const { return listener_; } void set_listener(TabbedPaneListener* listener) { listener_ = listener; } // Returns the index of the currently selected tab, or // TabStrip::kNoSelectedTab if no tab is selected. size_t GetSelectedTabIndex() const; // Returns the number of tabs. size_t GetTabCount() const; // Adds a new tab at the end of this TabbedPane with the specified |title|. // |contents| is the view displayed when the tab is selected and is owned by // the TabbedPane. template <typename T> T* AddTab(const std::u16string& title, std::unique_ptr<T> contents) { return AddTabAtIndex(GetTabCount(), title, std::move(contents)); } // Adds a new tab at |index| with |title|. |contents| is the view displayed // when the tab is selected and is owned by the TabbedPane. If the tabbed pane // is currently empty, the new tab is selected. template <typename T> T* AddTabAtIndex(size_t index, const std::u16string& title, std::unique_ptr<T> contents) { T* result = contents.get(); AddTabInternal(index, title, std::move(contents)); return result; } // Selects the tab at |index|, which must be valid. void SelectTabAt(size_t index, bool animate = true); // Selects |tab| (the tabstrip view, not its content) if it is valid. void SelectTab(TabbedPaneTab* tab, bool animate = true); // Gets the scroll view containing the tab strip, if it exists ScrollView* GetScrollView(); // Gets the orientation of the tab alignment. Orientation GetOrientation() const; // Gets the style of the tab strip. TabStripStyle GetStyle() const; // Returns the tab at the given index. TabbedPaneTab* GetTabAt(size_t index); private: friend class FocusTraversalTest; friend class TabbedPaneTab; friend class TabStrip; friend class test::TabbedPaneWithWidgetTest; friend class test::TabbedPaneAccessibilityMacTest; // Adds a new tab at |index| with |title|. |contents| is the view displayed // when the tab is selected and is owned by the TabbedPane. If the tabbed pane // is currently empty, the new tab is selected. void AddTabInternal(size_t index, const std::u16string& title, std::unique_ptr<View> contents); // Get the TabbedPaneTab (the tabstrip view, not its content) at the selected // index. TabbedPaneTab* GetSelectedTab(); // Returns the content View of the currently selected TabbedPaneTab. View* GetSelectedTabContentView(); // Moves the selection by |delta| tabs, where negative delta means leftwards // and positive delta means rightwards. Returns whether the selection could be // moved by that amount; the only way this can fail is if there is only one // tab. bool MoveSelectionBy(int delta); // Overridden from View: bool AcceleratorPressed(const ui::Accelerator& accelerator) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // A listener notified when tab selection changes. Weak, not owned. raw_ptr<TabbedPaneListener> listener_ = nullptr; // The tab strip and contents container. The child indices of these members // correspond to match each TabbedPaneTab with its respective content View. raw_ptr<TabStrip> tab_strip_ = nullptr; raw_ptr<View> contents_ = nullptr; // The scroll view containing the tab strip, if |scrollable| is specified on // creation. raw_ptr<ScrollView> scroll_view_ = nullptr; }; // The tab view shown in the tab strip. class VIEWS_EXPORT TabbedPaneTab : public View { public: METADATA_HEADER(TabbedPaneTab); TabbedPaneTab(TabbedPane* tabbed_pane, const std::u16string& title, View* contents); TabbedPaneTab(const TabbedPaneTab&) = delete; TabbedPaneTab& operator=(const TabbedPaneTab&) = delete; ~TabbedPaneTab() override; View* contents() const { return contents_; } bool selected() const { return contents_->GetVisible(); } void SetSelected(bool selected); const std::u16string& GetTitleText() const; void SetTitleText(const std::u16string& text); // Overridden from View: bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; gfx::Size CalculatePreferredSize() const override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; void OnFocus() override; void OnBlur() override; bool OnKeyPressed(const ui::KeyEvent& event) override; void OnThemeChanged() override; private: enum class State { kInactive, kActive, kHovered, }; void SetState(State state); // Called whenever |state_| changes. void OnStateChanged(); // views::View: void OnPaint(gfx::Canvas* canvas) override; void UpdatePreferredTitleWidth(); void UpdateTitleColor(); raw_ptr<TabbedPane> tabbed_pane_; raw_ptr<Label> title_ = nullptr; int preferred_title_width_; State state_ = State::kActive; // The content view associated with this tab. raw_ptr<View> contents_; }; // The tab strip shown above/left of the tab contents. class TabStrip : public View, public gfx::AnimationDelegate { public: METADATA_HEADER(TabStrip); // The return value of GetSelectedTabIndex() when no tab is selected. static constexpr size_t kNoSelectedTab = static_cast<size_t>(-1); TabStrip(TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style); TabStrip(const TabStrip&) = delete; TabStrip& operator=(const TabStrip&) = delete; ~TabStrip() override; // AnimationDelegate: void AnimationProgressed(const gfx::Animation* animation) override; void AnimationEnded(const gfx::Animation* animation) override; // Called by TabStrip when the selected tab changes. This function is only // called if |from_tab| is not null, i.e., there was a previously selected // tab. void OnSelectedTabChanged(TabbedPaneTab* from_tab, TabbedPaneTab* to_tab, bool animate = true); TabbedPaneTab* GetSelectedTab() const; TabbedPaneTab* GetTabAtDeltaFromSelected(int delta) const; TabbedPaneTab* GetTabAtIndex(size_t index) const; size_t GetSelectedTabIndex() const; TabbedPane::Orientation GetOrientation() const; TabbedPane::TabStripStyle GetStyle() const; protected: // View: gfx::Size CalculatePreferredSize() const override; void OnPaintBorder(gfx::Canvas* canvas) override; private: struct Coordinates { int start, end; }; // The orientation of the tab alignment. const TabbedPane::Orientation orientation_; // The style of the tab strip. const TabbedPane::TabStripStyle style_; // Animations for expanding and contracting the selection bar. When changing // selections, the selection bar first grows to encompass both the old and new // selections, then shrinks to encompass only the new selection. The rates of // expansion and contraction each follow the cubic bezier curves used in // gfx::Tween; see TabStrip::OnPaintBorder for details. std::unique_ptr<gfx::LinearAnimation> expand_animation_ = std::make_unique<gfx::LinearAnimation>(this); std::unique_ptr<gfx::LinearAnimation> contract_animation_ = std::make_unique<gfx::LinearAnimation>(this); // The x-coordinate ranges of the old selection and the new selection. Coordinates animating_from_; Coordinates animating_to_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, TabbedPane, View) VIEW_BUILDER_METHOD_ALIAS(AddTab, AddTab<View>, const std::u16string&, std::unique_ptr<View>) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, TabbedPane) #endif // UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/tabbed_pane/tabbed_pane.h
C++
unknown
9,623
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/raw_ptr.h" #import <Cocoa/Cocoa.h> #import "base/mac/foundation_util.h" #import "base/mac/mac_util.h" #import "base/mac/scoped_nsobject.h" #include "base/strings/utf_string_conversions.h" #import "testing/gtest_mac.h" #include "ui/gfx/geometry/point.h" #import "ui/gfx/mac/coordinate_conversion.h" #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" namespace views::test { namespace { id<NSAccessibility> ToNSAccessibility(id obj) { return [obj conformsToProtocol:@protocol(NSAccessibility)] ? obj : nil; } // Unboxes an accessibilityValue into an int via NSNumber. int IdToInt(id value) { return base::mac::ObjCCastStrict<NSNumber>(value).intValue; } // TODO(https://crbug.com/936990): NSTabItemView is not an NSView (despite the // name) and doesn't conform to NSAccessibility, so we have to fall back to the // legacy NSObject accessibility API to get its accessibility properties. id GetLegacyA11yAttributeValue(id obj, NSString* attribute) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return [obj accessibilityAttributeValue:attribute]; #pragma clang diagnostic pop } } // namespace class TabbedPaneAccessibilityMacTest : public WidgetTest { public: TabbedPaneAccessibilityMacTest() = default; TabbedPaneAccessibilityMacTest(const TabbedPaneAccessibilityMacTest&) = delete; TabbedPaneAccessibilityMacTest& operator=( const TabbedPaneAccessibilityMacTest&) = delete; // WidgetTest: void SetUp() override { WidgetTest::SetUp(); widget_ = CreateTopLevelPlatformWidget(); widget_->SetBounds(gfx::Rect(50, 50, 100, 100)); auto tabbed_pane = std::make_unique<TabbedPane>(); tabbed_pane->SetSize(gfx::Size(100, 100)); // Create two tabs and position/size them. tabbed_pane->AddTab(u"Tab 1", std::make_unique<View>()); tabbed_pane->AddTab(u"Tab 2", std::make_unique<View>()); tabbed_pane->Layout(); tabbed_pane_ = widget_->GetContentsView()->AddChildView(std::move(tabbed_pane)); widget_->Show(); } void TearDown() override { widget_->CloseNow(); WidgetTest::TearDown(); } TabbedPaneTab* GetTabAt(size_t index) { return static_cast<TabbedPaneTab*>( tabbed_pane_->tab_strip_->children()[index]); } id<NSAccessibility> A11yElementAtPoint(const gfx::Point& point) { // Accessibility hit tests come in Cocoa screen coordinates. NSPoint ns_point = gfx::ScreenPointToNSPoint(point); return ToNSAccessibility([widget_->GetNativeWindow().GetNativeNSWindow() accessibilityHitTest:ns_point]); } gfx::Point TabCenterPoint(size_t index) { return GetTabAt(index)->GetBoundsInScreen().CenterPoint(); } protected: raw_ptr<Widget> widget_ = nullptr; raw_ptr<TabbedPane> tabbed_pane_ = nullptr; }; // Test the Tab's a11y information compared to a Cocoa NSTabViewItem. TEST_F(TabbedPaneAccessibilityMacTest, AttributesMatchAppKit) { // Create a Cocoa NSTabView to test against and select the first tab. base::scoped_nsobject<NSTabView> cocoa_tab_group( [[NSTabView alloc] initWithFrame:NSMakeRect(50, 50, 100, 100)]); NSArray* cocoa_tabs = @[ [[[NSTabViewItem alloc] init] autorelease], [[[NSTabViewItem alloc] init] autorelease], ]; for (size_t i = 0; i < [cocoa_tabs count]; ++i) { [cocoa_tabs[i] setLabel:[NSString stringWithFormat:@"Tab %zu", i + 1]]; [cocoa_tab_group addTabViewItem:cocoa_tabs[i]]; } // General a11y information. EXPECT_NSEQ( GetLegacyA11yAttributeValue(cocoa_tabs[0], NSAccessibilityRoleAttribute), A11yElementAtPoint(TabCenterPoint(0)).accessibilityRole); // Older versions of Cocoa expose browser tabs with the accessible role // description of "radio button." We match the user experience of more recent // versions of Cocoa by exposing the role description of "tab" even in older // versions of macOS. Doing so causes a mismatch between native Cocoa and our // tabs. if (base::mac::IsAtLeastOS12()) { EXPECT_NSEQ( GetLegacyA11yAttributeValue(cocoa_tabs[0], NSAccessibilityRoleDescriptionAttribute), A11yElementAtPoint(TabCenterPoint(0)).accessibilityRoleDescription); } EXPECT_NSEQ( GetLegacyA11yAttributeValue(cocoa_tabs[0], NSAccessibilityTitleAttribute), A11yElementAtPoint(TabCenterPoint(0)).accessibilityTitle); // Compare the value attribute against native Cocoa and check it matches up // with whether tabs are actually selected. for (size_t i : {0, 1}) { NSNumber* cocoa_value = GetLegacyA11yAttributeValue( cocoa_tabs[i], NSAccessibilityValueAttribute); // Verify that only the second tab is selected. EXPECT_EQ(i ? 0 : 1, [cocoa_value intValue]); EXPECT_NSEQ(cocoa_value, A11yElementAtPoint(TabCenterPoint(i)).accessibilityValue); } // NSTabViewItem doesn't support NSAccessibilitySelectedAttribute, so don't // compare against Cocoa here. EXPECT_TRUE(A11yElementAtPoint(TabCenterPoint(0)).accessibilitySelected); EXPECT_FALSE(A11yElementAtPoint(TabCenterPoint(1)).accessibilitySelected); } // Make sure tabs can be selected by writing the value attribute. TEST_F(TabbedPaneAccessibilityMacTest, WritableValue) { id<NSAccessibility> tab1_a11y = A11yElementAtPoint(TabCenterPoint(0)); id<NSAccessibility> tab2_a11y = A11yElementAtPoint(TabCenterPoint(1)); // Only unselected tabs should be writable. EXPECT_FALSE([tab1_a11y isAccessibilitySelectorAllowed:@selector(setAccessibilityValue:)]); EXPECT_TRUE([tab2_a11y isAccessibilitySelectorAllowed:@selector(setAccessibilityValue:)]); // Select the second tab. AXValue actually accepts any type, but for tabs, // Cocoa uses an integer. Despite this, the Accessibility Inspector provides a // textfield to set the value for a control, so test this with an NSString. tab2_a11y.accessibilityValue = @"string"; EXPECT_EQ(0, IdToInt(tab1_a11y.accessibilityValue)); EXPECT_EQ(1, IdToInt(tab2_a11y.accessibilityValue)); EXPECT_FALSE(tab1_a11y.accessibilitySelected); EXPECT_TRUE(tab2_a11y.accessibilitySelected); EXPECT_TRUE(GetTabAt(1)->selected()); // It doesn't make sense to 'deselect' a tab (i.e., without specifying another // to select). So any value passed to -accessibilitySetValue: should select // that tab. Try an empty string. tab1_a11y.accessibilityValue = @""; EXPECT_EQ(1, IdToInt(tab1_a11y.accessibilityValue)); EXPECT_EQ(0, IdToInt(tab2_a11y.accessibilityValue)); EXPECT_TRUE(tab1_a11y.accessibilitySelected); EXPECT_FALSE(tab2_a11y.accessibilitySelected); EXPECT_TRUE(GetTabAt(0)->selected()); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/controls/tabbed_pane/tabbed_pane_accessibility_mac_unittest.mm
Objective-C++
unknown
6,919
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_ #define UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_ #include "ui/views/views_export.h" namespace views { // An interface implemented by an object to let it know that a tabbed pane was // selected by the user at the specified index. class VIEWS_EXPORT TabbedPaneListener { public: // Called when the tab at |index| is selected by the user. virtual void TabSelectedAt(int index) = 0; protected: virtual ~TabbedPaneListener() = default; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/tabbed_pane/tabbed_pane_listener.h
C++
unknown
754
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/tabbed_pane/tabbed_pane.h" #include <memory> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/utf_string_conversions.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.h" #include "ui/accessibility/ax_node_data.h" #include "ui/events/keycodes/keyboard_code_conversion.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/test_views.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" using base::ASCIIToUTF16; namespace views::test { namespace { std::u16string DefaultTabTitle() { return u"tab"; } std::u16string GetAccessibleName(View* view) { ui::AXNodeData ax_node_data; view->GetViewAccessibility().GetAccessibleNodeData(&ax_node_data); return ax_node_data.GetString16Attribute(ax::mojom::StringAttribute::kName); } ax::mojom::Role GetAccessibleRole(View* view) { ui::AXNodeData ax_node_data; view->GetViewAccessibility().GetAccessibleNodeData(&ax_node_data); return ax_node_data.role; } } // namespace using TabbedPaneTest = ViewsTestBase; // Tests tab orientation. TEST_F(TabbedPaneTest, HorizontalOrientationDefault) { auto tabbed_pane = std::make_unique<TabbedPane>(); EXPECT_EQ(tabbed_pane->GetOrientation(), TabbedPane::Orientation::kHorizontal); } // Tests tab orientation. TEST_F(TabbedPaneTest, VerticalOrientation) { auto tabbed_pane = std::make_unique<TabbedPane>( TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kBorder); EXPECT_EQ(tabbed_pane->GetOrientation(), TabbedPane::Orientation::kVertical); } // Tests tab strip style. TEST_F(TabbedPaneTest, TabStripBorderStyle) { auto tabbed_pane = std::make_unique<TabbedPane>(); EXPECT_EQ(tabbed_pane->GetStyle(), TabbedPane::TabStripStyle::kBorder); } // Tests tab strip style. TEST_F(TabbedPaneTest, TabStripHighlightStyle) { auto tabbed_pane = std::make_unique<TabbedPane>(TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kHighlight); EXPECT_EQ(tabbed_pane->GetStyle(), TabbedPane::TabStripStyle::kHighlight); } TEST_F(TabbedPaneTest, ScrollingDisabled) { auto tabbed_pane = std::make_unique<TabbedPane>( TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kBorder); EXPECT_EQ(tabbed_pane->GetScrollView(), nullptr); } TEST_F(TabbedPaneTest, ScrollingEnabled) { auto tabbed_pane_vertical = std::make_unique<TabbedPane>(TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kBorder, true); ASSERT_NE(tabbed_pane_vertical->GetScrollView(), nullptr); EXPECT_THAT(tabbed_pane_vertical->GetScrollView(), testing::A<ScrollView*>()); auto tabbed_pane_horizontal = std::make_unique<TabbedPane>(TabbedPane::Orientation::kHorizontal, TabbedPane::TabStripStyle::kBorder, true); ASSERT_NE(tabbed_pane_horizontal->GetScrollView(), nullptr); EXPECT_THAT(tabbed_pane_horizontal->GetScrollView(), testing::A<ScrollView*>()); } // Tests the preferred size and layout when tabs are aligned vertically.. TEST_F(TabbedPaneTest, SizeAndLayoutInVerticalOrientation) { auto tabbed_pane = std::make_unique<TabbedPane>( TabbedPane::Orientation::kVertical, TabbedPane::TabStripStyle::kBorder); View* child1 = tabbed_pane->AddTab( u"tab1", std::make_unique<StaticSizedView>(gfx::Size(20, 10))); View* child2 = tabbed_pane->AddTab( u"tab2", std::make_unique<StaticSizedView>(gfx::Size(5, 5))); tabbed_pane->SelectTabAt(0); // |tabbed_pane_| reserves extra width for the tab strip in vertical mode. EXPECT_GT(tabbed_pane->GetPreferredSize().width(), 20); // |tabbed_pane_| height should match the largest child in vertical mode. EXPECT_EQ(tabbed_pane->GetPreferredSize().height(), 10); // The child views should resize to fit in larger tabbed panes. tabbed_pane->SetBounds(0, 0, 100, 200); EXPECT_GT(child1->bounds().width(), 0); // |tabbed_pane_| reserves extra width for the tab strip. Therefore the // children's width should be smaller than the |tabbed_pane_|'s width. EXPECT_LT(child1->bounds().width(), 100); // |tabbed_pane_| has no border. Therefore the children should be as high as // the |tabbed_pane_|. EXPECT_EQ(child1->bounds().height(), 200); // If we switch to the other tab, it should get assigned the same bounds. tabbed_pane->SelectTabAt(1); EXPECT_EQ(child1->bounds(), child2->bounds()); } class TabbedPaneWithWidgetTest : public ViewsTestBase { public: TabbedPaneWithWidgetTest() = default; TabbedPaneWithWidgetTest(const TabbedPaneWithWidgetTest&) = delete; TabbedPaneWithWidgetTest& operator=(const TabbedPaneWithWidgetTest&) = delete; void SetUp() override { ViewsTestBase::SetUp(); auto tabbed_pane = std::make_unique<TabbedPane>(); // Create a widget so that accessibility data will be returned correctly. widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); widget_->Init(std::move(params)); tabbed_pane_ = tabbed_pane.get(); widget_->SetContentsView(std::move(tabbed_pane)); } void TearDown() override { tabbed_pane_ = nullptr; widget_.reset(); ViewsTestBase::TearDown(); } protected: TabbedPaneTab* GetTabAt(size_t index) { return static_cast<TabbedPaneTab*>( tabbed_pane_->tab_strip_->children()[index]); } View* GetSelectedTabContentView() { return tabbed_pane_->GetSelectedTabContentView(); } void SendKeyPressToSelectedTab(ui::KeyboardCode keyboard_code) { tabbed_pane_->GetSelectedTab()->OnKeyPressed( ui::KeyEvent(ui::ET_KEY_PRESSED, keyboard_code, ui::UsLayoutKeyboardCodeToDomCode(keyboard_code), 0)); } std::unique_ptr<Widget> widget_; raw_ptr<TabbedPane> tabbed_pane_; }; // Tests the preferred size and layout when tabs are aligned horizontally. // TabbedPane requests a size that fits the largest child or the minimum size // necessary to display the tab titles, whichever is larger. TEST_F(TabbedPaneWithWidgetTest, SizeAndLayout) { View* child1 = tabbed_pane_->AddTab( u"tab1", std::make_unique<StaticSizedView>(gfx::Size(20, 10))); View* child2 = tabbed_pane_->AddTab( u"tab2", std::make_unique<StaticSizedView>(gfx::Size(5, 5))); tabbed_pane_->SelectTabAt(0); // In horizontal mode, |tabbed_pane_| width should match the largest child or // the minimum size necessary to display the tab titles, whichever is larger. EXPECT_EQ(tabbed_pane_->GetPreferredSize().width(), tabbed_pane_->GetTabAt(0)->GetPreferredSize().width() + tabbed_pane_->GetTabAt(1)->GetPreferredSize().width()); // |tabbed_pane_| reserves extra height for the tab strip in horizontal mode. EXPECT_GT(tabbed_pane_->GetPreferredSize().height(), 10); // Test that the preferred size is now the size of the size of the largest // child. View* child3 = tabbed_pane_->AddTab( u"tab3", std::make_unique<StaticSizedView>(gfx::Size(150, 5))); EXPECT_EQ(tabbed_pane_->GetPreferredSize().width(), 150); // The child views should resize to fit in larger tabbed panes. widget_->SetBounds(gfx::Rect(0, 0, 300, 200)); tabbed_pane_->SetBounds(0, 0, 300, 200); RunPendingMessages(); // |tabbed_pane_| has no border. Therefore the children should be as wide as // the |tabbed_pane_|. EXPECT_EQ(child1->bounds().width(), 300); EXPECT_GT(child1->bounds().height(), 0); // |tabbed_pane_| reserves extra height for the tab strip. Therefore the // children's height should be smaller than the |tabbed_pane_|'s height. EXPECT_LT(child1->bounds().height(), 200); // If we switch to the other tab, it should get assigned the same bounds. tabbed_pane_->SelectTabAt(1); EXPECT_EQ(child1->bounds(), child2->bounds()); EXPECT_EQ(child2->bounds(), child3->bounds()); } TEST_F(TabbedPaneWithWidgetTest, AddAndSelect) { // Add several tabs; only the first should be selected automatically. for (size_t i = 0; i < 3; ++i) { tabbed_pane_->AddTab(DefaultTabTitle(), std::make_unique<View>()); EXPECT_EQ(i + 1, tabbed_pane_->GetTabCount()); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); } // Select each tab. for (size_t i = 0; i < tabbed_pane_->GetTabCount(); ++i) { tabbed_pane_->SelectTabAt(i); EXPECT_EQ(i, tabbed_pane_->GetSelectedTabIndex()); } // Add a tab at index 0, it should not be selected automatically. View* tab0 = tabbed_pane_->AddTabAtIndex(0, u"tab0", std::make_unique<View>()); EXPECT_NE(tab0, GetSelectedTabContentView()); EXPECT_NE(0u, tabbed_pane_->GetSelectedTabIndex()); } TEST_F(TabbedPaneWithWidgetTest, ArrowKeyBindings) { // Add several tabs; only the first should be selected automatically. for (size_t i = 0; i < 3; ++i) { tabbed_pane_->AddTab(DefaultTabTitle(), std::make_unique<View>()); EXPECT_EQ(i + 1, tabbed_pane_->GetTabCount()); } EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); // Right arrow should select tab 1: SendKeyPressToSelectedTab(ui::VKEY_RIGHT); EXPECT_EQ(1u, tabbed_pane_->GetSelectedTabIndex()); // Left arrow should select tab 0: SendKeyPressToSelectedTab(ui::VKEY_LEFT); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); // Left arrow again should wrap to tab 2: SendKeyPressToSelectedTab(ui::VKEY_LEFT); EXPECT_EQ(2u, tabbed_pane_->GetSelectedTabIndex()); // Right arrow again should wrap to tab 0: SendKeyPressToSelectedTab(ui::VKEY_RIGHT); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); } // Use TabbedPane::HandleAccessibleAction() to select tabs and make sure their // a11y information is correct. TEST_F(TabbedPaneWithWidgetTest, SelectTabWithAccessibleAction) { constexpr size_t kNumTabs = 3; for (size_t i = 0; i < kNumTabs; ++i) { tabbed_pane_->AddTab(DefaultTabTitle(), std::make_unique<View>()); } // Check the first tab is selected. EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); // Check the a11y information for each tab. for (size_t i = 0; i < kNumTabs; ++i) { ui::AXNodeData data; GetTabAt(i)->GetAccessibleNodeData(&data); SCOPED_TRACE(testing::Message() << "TabbedPaneTab at index: " << i); EXPECT_EQ(ax::mojom::Role::kTab, data.role); EXPECT_EQ(DefaultTabTitle(), data.GetString16Attribute(ax::mojom::StringAttribute::kName)); EXPECT_EQ(i == 0, data.GetBoolAttribute(ax::mojom::BoolAttribute::kSelected)); } ui::AXActionData action; action.action = ax::mojom::Action::kSetSelection; // Select the first tab. GetTabAt(0)->HandleAccessibleAction(action); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); // Select the second tab. GetTabAt(1)->HandleAccessibleAction(action); EXPECT_EQ(1u, tabbed_pane_->GetSelectedTabIndex()); // Select the second tab again. GetTabAt(1)->HandleAccessibleAction(action); EXPECT_EQ(1u, tabbed_pane_->GetSelectedTabIndex()); } TEST_F(TabbedPaneWithWidgetTest, AccessiblePaneTitleTracksActiveTabTitle) { const std::u16string kFirstTitle = u"Tab1"; const std::u16string kSecondTitle = u"Tab2"; tabbed_pane_->AddTab(kFirstTitle, std::make_unique<View>()); tabbed_pane_->AddTab(kSecondTitle, std::make_unique<View>()); EXPECT_EQ(kFirstTitle, GetAccessibleName(tabbed_pane_)); tabbed_pane_->SelectTabAt(1); EXPECT_EQ(kSecondTitle, GetAccessibleName(tabbed_pane_)); } TEST_F(TabbedPaneWithWidgetTest, AccessiblePaneContentsTitleTracksTabTitle) { const std::u16string kFirstTitle = u"Tab1"; const std::u16string kSecondTitle = u"Tab2"; View* const tab1_contents = tabbed_pane_->AddTab(kFirstTitle, std::make_unique<View>()); View* const tab2_contents = tabbed_pane_->AddTab(kSecondTitle, std::make_unique<View>()); EXPECT_EQ(kFirstTitle, GetAccessibleName(tab1_contents)); EXPECT_EQ(kSecondTitle, GetAccessibleName(tab2_contents)); } TEST_F(TabbedPaneWithWidgetTest, AccessiblePaneContentsRoleIsTabPanel) { const std::u16string kFirstTitle = u"Tab1"; const std::u16string kSecondTitle = u"Tab2"; View* const tab1_contents = tabbed_pane_->AddTab(kFirstTitle, std::make_unique<View>()); View* const tab2_contents = tabbed_pane_->AddTab(kSecondTitle, std::make_unique<View>()); EXPECT_EQ(ax::mojom::Role::kTabPanel, GetAccessibleRole(tab1_contents)); EXPECT_EQ(ax::mojom::Role::kTabPanel, GetAccessibleRole(tab2_contents)); } TEST_F(TabbedPaneWithWidgetTest, AccessibleEvents) { tabbed_pane_->AddTab(u"Tab1", std::make_unique<View>()); tabbed_pane_->AddTab(u"Tab2", std::make_unique<View>()); test::AXEventCounter counter(views::AXEventManager::Get()); // This is needed for FocusManager::SetFocusedViewWithReason to notify // observers observers of focus changes. if (widget_ && !widget_->IsActive()) widget_->Activate(); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); // Change the selected tab without giving the tab focus should result in a // selection change for the new tab and a selected-children-changed for the // tab list. No focus events should occur. tabbed_pane_->SelectTabAt(1); EXPECT_EQ(1u, tabbed_pane_->GetSelectedTabIndex()); EXPECT_EQ( 1, counter.GetCount(ax::mojom::Event::kSelection, ax::mojom::Role::kTab)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged, ax::mojom::Role::kTabList)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kFocus)); counter.ResetAllCounts(); // Focusing the selected tab should only result in a focus event for that tab. tabbed_pane_->GetFocusManager()->SetFocusedView(tabbed_pane_->GetTabAt(1)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kFocus)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kFocus, ax::mojom::Role::kTab)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kSelection)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged)); counter.ResetAllCounts(); // Arrowing left to the first tab selects it. Therefore we should get the same // events as we did when SelectTabAt() was called. SendKeyPressToSelectedTab(ui::VKEY_LEFT); EXPECT_EQ(0u, tabbed_pane_->GetSelectedTabIndex()); EXPECT_EQ( 1, counter.GetCount(ax::mojom::Event::kSelection, ax::mojom::Role::kTab)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged, ax::mojom::Role::kTabList)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kFocus)); counter.ResetAllCounts(); // Focusing an unselected tab, if the UI allows it, a should only result in a // focus event for that tab. tabbed_pane_->GetFocusManager()->SetFocusedView(tabbed_pane_->GetTabAt(1)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kFocus)); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kFocus, ax::mojom::Role::kTab)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kSelection)); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kSelectedChildrenChanged)); } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc
C++
unknown
15,559
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_GROUPER_H_ #define UI_VIEWS_CONTROLS_TABLE_TABLE_GROUPER_H_ #include "ui/views/views_export.h" namespace views { struct VIEWS_EXPORT GroupRange { size_t start; size_t length; }; // TableGrouper is used by TableView to group a set of rows and treat them // as one. Rows that fall in the same group are selected together and sorted // together. class VIEWS_EXPORT TableGrouper { public: virtual void GetGroupRange(size_t model_index, GroupRange* range) = 0; protected: virtual ~TableGrouper() = default; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TABLE_TABLE_GROUPER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_grouper.h
C++
unknown
778
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/table_header.h" #include <stddef.h> #include <algorithm> #include <memory> #include <vector> #include "base/i18n/rtl.h" #include "cc/paint/paint_flags.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/cursor/cursor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/text_utils.h" #include "ui/views/background.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/table/table_utils.h" #include "ui/views/controls/table/table_view.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/style/platform_style.h" namespace views { namespace { // The minimum width we allow a column to go down to. constexpr int kMinColumnWidth = 10; // Amount that a column is resized when using the keyboard. constexpr int kResizeKeyboardAmount = 5; constexpr int kVerticalPadding = 4; // Distace from edge columns can be resized by. constexpr int kResizePadding = 5; // Amount of space above/below the separator. constexpr int kSeparatorPadding = 4; // Size of the sort indicator (doesn't include padding). constexpr int kSortIndicatorSize = 8; } // namespace // static const int TableHeader::kHorizontalPadding = 7; // static const int TableHeader::kSortIndicatorWidth = kSortIndicatorSize + TableHeader::kHorizontalPadding * 2; class TableHeader::HighlightPathGenerator : public views::HighlightPathGenerator { public: HighlightPathGenerator() = default; HighlightPathGenerator(const HighlightPathGenerator&) = delete; HighlightPathGenerator& operator=(const HighlightPathGenerator&) = delete; ~HighlightPathGenerator() override = default; // HighlightPathGenerator: SkPath GetHighlightPath(const View* view) override { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return SkPath(); const TableHeader* const header = static_cast<const TableHeader*>(view); // If there's no focus indicator fall back on the default highlight path // (highlights entire view instead of active cell). if (!header->HasFocusIndicator()) return SkPath(); // Draw a focus indicator around the active cell. gfx::Rect bounds = header->GetActiveHeaderCellBounds(); bounds.set_x(header->GetMirroredXForRect(bounds)); return SkPath().addRect(gfx::RectToSkRect(bounds)); } }; using Columns = std::vector<TableView::VisibleColumn>; TableHeader::TableHeader(TableView* table) : table_(table) { HighlightPathGenerator::Install( this, std::make_unique<TableHeader::HighlightPathGenerator>()); FocusRing::Install(this); views::FocusRing::Get(this)->SetHasFocusPredicate([&](View* view) { return static_cast<TableHeader*>(view)->GetHeaderRowHasFocus(); }); } TableHeader::~TableHeader() = default; void TableHeader::UpdateFocusState() { views::FocusRing::Get(this)->SchedulePaint(); } void TableHeader::OnPaint(gfx::Canvas* canvas) { ui::ColorProvider* color_provider = GetColorProvider(); const SkColor text_color = color_provider->GetColor(ui::kColorTableHeaderForeground); const SkColor separator_color = color_provider->GetColor(ui::kColorTableHeaderSeparator); // Paint the background and a separator at the bottom. The separator color // matches that of the border around the scrollview. OnPaintBackground(canvas); SkColor border_color = color_provider->GetColor(ui::kColorFocusableBorderUnfocused); canvas->DrawSharpLine(gfx::PointF(0, height() - 1), gfx::PointF(width(), height() - 1), border_color); const Columns& columns = table_->visible_columns(); const int sorted_column_id = table_->sort_descriptors().empty() ? -1 : table_->sort_descriptors()[0].column_id; for (const auto& column : columns) { if (column.width >= 2) { const int separator_x = GetMirroredXInView(column.x + column.width - 1); canvas->DrawSharpLine( gfx::PointF(separator_x, kSeparatorPadding), gfx::PointF(separator_x, height() - kSeparatorPadding), separator_color); } const int x = column.x + kHorizontalPadding; int width = column.width - kHorizontalPadding - kHorizontalPadding; if (width <= 0) continue; const int title_width = gfx::GetStringWidth(column.column.title, font_list_); const bool paint_sort_indicator = (column.column.id == sorted_column_id && title_width + kSortIndicatorWidth <= width); if (paint_sort_indicator) width -= kSortIndicatorWidth; canvas->DrawStringRectWithFlags( column.column.title, font_list_, text_color, gfx::Rect(GetMirroredXWithWidthInView(x, width), kVerticalPadding, width, height() - kVerticalPadding * 2), TableColumnAlignmentToCanvasAlignment( GetMirroredTableColumnAlignment(column.column.alignment))); if (paint_sort_indicator) { cc::PaintFlags flags; flags.setColor(text_color); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setAntiAlias(true); int indicator_x = 0; switch (column.column.alignment) { case ui::TableColumn::LEFT: indicator_x = x + title_width; break; case ui::TableColumn::CENTER: indicator_x = x + width / 2 + title_width / 2; break; case ui::TableColumn::RIGHT: indicator_x = x + width; break; } const int scale = base::i18n::IsRTL() ? -1 : 1; indicator_x += (kSortIndicatorWidth - kSortIndicatorSize) / 2; indicator_x = GetMirroredXInView(indicator_x); int indicator_y = height() / 2 - kSortIndicatorSize / 2; SkPath indicator_path; if (table_->sort_descriptors()[0].ascending) { indicator_path.moveTo(SkIntToScalar(indicator_x), SkIntToScalar(indicator_y + kSortIndicatorSize)); indicator_path.lineTo( SkIntToScalar(indicator_x + kSortIndicatorSize * scale), SkIntToScalar(indicator_y + kSortIndicatorSize)); indicator_path.lineTo( SkIntToScalar(indicator_x + kSortIndicatorSize / 2 * scale), SkIntToScalar(indicator_y)); } else { indicator_path.moveTo(SkIntToScalar(indicator_x), SkIntToScalar(indicator_y)); indicator_path.lineTo( SkIntToScalar(indicator_x + kSortIndicatorSize * scale), SkIntToScalar(indicator_y)); indicator_path.lineTo( SkIntToScalar(indicator_x + kSortIndicatorSize / 2 * scale), SkIntToScalar(indicator_y + kSortIndicatorSize)); } indicator_path.close(); canvas->DrawPath(indicator_path, flags); } } } gfx::Size TableHeader::CalculatePreferredSize() const { return gfx::Size(1, kVerticalPadding * 2 + font_list_.GetHeight()); } bool TableHeader::GetNeedsNotificationWhenVisibleBoundsChange() const { return true; } void TableHeader::OnVisibleBoundsChanged() { // Ensure the TableView updates its virtual children's bounds, because that // includes the bounds representing this TableHeader. table_->UpdateVirtualAccessibilityChildrenBounds(); } void TableHeader::AddedToWidget() { // Ensure the TableView updates its virtual children's bounds, because that // includes the bounds representing this TableHeader. table_->UpdateVirtualAccessibilityChildrenBounds(); } ui::Cursor TableHeader::GetCursor(const ui::MouseEvent& event) { return GetResizeColumn(GetMirroredXInView(event.x())).has_value() ? ui::mojom::CursorType::kColumnResize : View::GetCursor(event); } bool TableHeader::OnMousePressed(const ui::MouseEvent& event) { if (event.IsOnlyLeftMouseButton()) { StartResize(event); return true; } // Return false so that context menus on ancestors work. return false; } bool TableHeader::OnMouseDragged(const ui::MouseEvent& event) { ContinueResize(event); return true; } void TableHeader::OnMouseReleased(const ui::MouseEvent& event) { const bool was_resizing = resize_details_ != nullptr; resize_details_.reset(); if (!was_resizing && event.IsOnlyLeftMouseButton()) ToggleSortOrder(event); } void TableHeader::OnMouseCaptureLost() { if (is_resizing()) { table_->SetVisibleColumnWidth(resize_details_->column_index, resize_details_->initial_width); } resize_details_.reset(); } void TableHeader::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP: if (!resize_details_.get()) ToggleSortOrder(*event); break; case ui::ET_GESTURE_SCROLL_BEGIN: StartResize(*event); break; case ui::ET_GESTURE_SCROLL_UPDATE: ContinueResize(*event); break; case ui::ET_GESTURE_SCROLL_END: resize_details_.reset(); break; default: return; } event->SetHandled(); } void TableHeader::OnThemeChanged() { View::OnThemeChanged(); SetBackground(CreateSolidBackground( GetColorProvider()->GetColor(ui::kColorTableHeaderBackground))); } void TableHeader::ResizeColumnViaKeyboard( size_t index, TableView::AdvanceDirection direction) { const TableView::VisibleColumn& column = table_->GetVisibleColumn(index); const int needed_for_title = gfx::GetStringWidth(column.column.title, font_list_) + 2 * kHorizontalPadding; int new_width = column.width; switch (direction) { case TableView::AdvanceDirection::kIncrement: new_width += kResizeKeyboardAmount; break; case TableView::AdvanceDirection::kDecrement: new_width -= kResizeKeyboardAmount; break; } table_->SetVisibleColumnWidth( index, std::max({kMinColumnWidth, needed_for_title, new_width})); } bool TableHeader::GetHeaderRowHasFocus() const { return table_->HasFocus() && table_->header_row_is_active(); } gfx::Rect TableHeader::GetActiveHeaderCellBounds() const { const absl::optional<size_t> active_index = table_->GetActiveVisibleColumnIndex(); DCHECK(active_index.has_value()); const TableView::VisibleColumn& column = table_->GetVisibleColumn(active_index.value()); return gfx::Rect(column.x, 0, column.width, height()); } bool TableHeader::HasFocusIndicator() const { return table_->GetActiveVisibleColumnIndex().has_value(); } bool TableHeader::StartResize(const ui::LocatedEvent& event) { if (is_resizing()) return false; const absl::optional<size_t> index = GetResizeColumn(GetMirroredXInView(event.x())); if (!index.has_value()) return false; resize_details_ = std::make_unique<ColumnResizeDetails>(); resize_details_->column_index = index.value(); resize_details_->initial_x = event.root_location().x(); resize_details_->initial_width = table_->GetVisibleColumn(index.value()).width; return true; } void TableHeader::ContinueResize(const ui::LocatedEvent& event) { if (!is_resizing()) return; const int scale = base::i18n::IsRTL() ? -1 : 1; const int delta = scale * (event.root_location().x() - resize_details_->initial_x); const TableView::VisibleColumn& column = table_->GetVisibleColumn(resize_details_->column_index); const int needed_for_title = gfx::GetStringWidth(column.column.title, font_list_) + 2 * kHorizontalPadding; table_->SetVisibleColumnWidth( resize_details_->column_index, std::max({kMinColumnWidth, needed_for_title, resize_details_->initial_width + delta})); } void TableHeader::ToggleSortOrder(const ui::LocatedEvent& event) { if (table_->visible_columns().empty()) return; const int x = GetMirroredXInView(event.x()); const absl::optional<size_t> index = GetClosestVisibleColumnIndex(table_, x); if (!index.has_value()) return; const TableView::VisibleColumn& column( table_->GetVisibleColumn(index.value())); if (x >= column.x && x < column.x + column.width && event.y() >= 0 && event.y() < height()) { table_->ToggleSortOrder(index.value()); } } absl::optional<size_t> TableHeader::GetResizeColumn(int x) const { const Columns& columns(table_->visible_columns()); if (columns.empty()) return absl::nullopt; const absl::optional<size_t> index = GetClosestVisibleColumnIndex(table_, x); DCHECK(index.has_value()); const TableView::VisibleColumn& column( table_->GetVisibleColumn(index.value())); if (index.value() > 0 && x >= column.x - kResizePadding && x <= column.x + kResizePadding) { return index.value() - 1; } const int max_x = column.x + column.width; return (x >= max_x - kResizePadding && x <= max_x + kResizePadding) ? absl::make_optional(index.value()) : absl::nullopt; } BEGIN_METADATA(TableHeader, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_header.cc
C++
unknown
13,261
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_ #define UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/gfx/font_list.h" #include "ui/views/controls/table/table_view.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace views { // Views used to render the header for the table. class VIEWS_EXPORT TableHeader : public views::View { public: METADATA_HEADER(TableHeader); // Amount the text is padded on the left/right side. static const int kHorizontalPadding; // Amount of space reserved for the indicator and padding. static const int kSortIndicatorWidth; explicit TableHeader(TableView* table); TableHeader(const TableHeader&) = delete; TableHeader& operator=(const TableHeader&) = delete; ~TableHeader() override; const gfx::FontList& font_list() const { return font_list_; } void ResizeColumnViaKeyboard(size_t index, TableView::AdvanceDirection direction); // Call to update TableHeader objects that rely on the focus state of its // corresponding virtual accessibility views. void UpdateFocusState(); // views::View overrides. void OnPaint(gfx::Canvas* canvas) override; gfx::Size CalculatePreferredSize() const override; bool GetNeedsNotificationWhenVisibleBoundsChange() const override; void OnVisibleBoundsChanged() override; void AddedToWidget() override; ui::Cursor GetCursor(const ui::MouseEvent& event) override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; void OnGestureEvent(ui::GestureEvent* event) override; void OnThemeChanged() override; private: class HighlightPathGenerator; // Used to track the column being resized. struct ColumnResizeDetails { ColumnResizeDetails() = default; // Index into table_->visible_columns() that is being resized. size_t column_index = 0; // X-coordinate of the mouse at the time the resize started. int initial_x = 0; // Width of the column when the drag started. int initial_width = 0; }; // Returns true if the TableView's header has focus. bool GetHeaderRowHasFocus() const; // Gets the bounds of the currently active header cell. gfx::Rect GetActiveHeaderCellBounds() const; // Returns true if one of the TableHeader's cells has a focus indicator. bool HasFocusIndicator() const; // If not already resizing and |event| is over a resizable column starts // resizing. bool StartResize(const ui::LocatedEvent& event); // Continues a resize operation. Does nothing if not in the process of // resizing. void ContinueResize(const ui::LocatedEvent& event); // Toggles the sort order of the column at the location in |event|. void ToggleSortOrder(const ui::LocatedEvent& event); // Returns the column to resize given the specified x-coordinate, or nullopt // if |x| is not in the resize range of any columns. absl::optional<size_t> GetResizeColumn(int x) const; bool is_resizing() const { return resize_details_.get() != nullptr; } const gfx::FontList font_list_; raw_ptr<TableView, DanglingUntriaged> table_; // If non-null a resize is in progress. std::unique_ptr<ColumnResizeDetails> resize_details_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_header.h
C++
unknown
3,668
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/table_utils.h" #include <stddef.h> #include <algorithm> #include "base/i18n/rtl.h" #include "base/notreached.h" #include "ui/base/models/table_model.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/text_utils.h" #include "ui/views/controls/table/table_view.h" namespace views { const int kUnspecifiedColumnWidth = 90; int WidthForContent(const gfx::FontList& header_font_list, const gfx::FontList& content_font_list, int padding, int header_padding, const ui::TableColumn& column, ui::TableModel* model) { int width = header_padding; if (!column.title.empty()) width = gfx::GetStringWidth(column.title, header_font_list) + header_padding; for (size_t i = 0, row_count = model->RowCount(); i < row_count; ++i) { const int cell_width = gfx::GetStringWidth(model->GetText(i, column.id), content_font_list); width = std::max(width, cell_width); } return width + padding; } std::vector<int> CalculateTableColumnSizes( int width, int first_column_padding, const gfx::FontList& header_font_list, const gfx::FontList& content_font_list, int padding, int header_padding, const std::vector<ui::TableColumn>& columns, ui::TableModel* model) { float total_percent = 0; int non_percent_width = 0; std::vector<int> content_widths(columns.size(), 0); for (size_t i = 0; i < columns.size(); ++i) { const ui::TableColumn& column(columns[i]); if (column.width <= 0) { if (column.percent > 0) { total_percent += column.percent; // Make sure there is at least enough room for the header. content_widths[i] = gfx::GetStringWidth(column.title, header_font_list) + padding + header_padding; } else { content_widths[i] = WidthForContent(header_font_list, content_font_list, padding, header_padding, column, model); if (i == 0) content_widths[i] += first_column_padding; } non_percent_width += content_widths[i]; } else { content_widths[i] = column.width; non_percent_width += column.width; } } std::vector<int> widths; const int available_width = width - non_percent_width; for (size_t i = 0; i < columns.size(); ++i) { const ui::TableColumn& column = columns[i]; int column_width = content_widths[i]; if (column.width <= 0 && column.percent > 0 && available_width > 0) { column_width += static_cast<int>(available_width * (column.percent / total_percent)); } widths.push_back(column_width == 0 ? kUnspecifiedColumnWidth : column_width); } // If no columns have specified a percent give the last column all the extra // space. if (!columns.empty() && total_percent == 0.f && available_width > 0 && columns.back().width <= 0 && columns.back().percent == 0.f) { widths.back() += available_width; } return widths; } int TableColumnAlignmentToCanvasAlignment( ui::TableColumn::Alignment alignment) { switch (alignment) { case ui::TableColumn::LEFT: return gfx::Canvas::TEXT_ALIGN_LEFT; case ui::TableColumn::CENTER: return gfx::Canvas::TEXT_ALIGN_CENTER; case ui::TableColumn::RIGHT: return gfx::Canvas::TEXT_ALIGN_RIGHT; } NOTREACHED_NORETURN(); } absl::optional<size_t> GetClosestVisibleColumnIndex(const TableView* table, int x) { const std::vector<TableView::VisibleColumn>& columns( table->visible_columns()); if (columns.empty()) return absl::nullopt; for (size_t i = 0; i < columns.size(); ++i) { if (x <= columns[i].x + columns[i].width) return i; } return columns.size() - 1; } ui::TableColumn::Alignment GetMirroredTableColumnAlignment( ui::TableColumn::Alignment alignment) { if (!base::i18n::IsRTL()) return alignment; switch (alignment) { case ui::TableColumn::LEFT: return ui::TableColumn::RIGHT; case ui::TableColumn::RIGHT: return ui::TableColumn::LEFT; case ui::TableColumn::CENTER: return ui::TableColumn::CENTER; } } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_utils.cc
C++
unknown
4,467
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_ #define UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_ #include <vector> #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/models/table_model.h" #include "ui/views/views_export.h" namespace gfx { class FontList; } namespace views { class TableView; VIEWS_EXPORT extern const int kUnspecifiedColumnWidth; // Returns the width needed to display the contents of the specified column. // This is used internally by CalculateTableColumnSizes() and generally not // useful by itself. |header_padding| is padding added to the header. VIEWS_EXPORT int WidthForContent(const gfx::FontList& header_font_list, const gfx::FontList& content_font_list, int padding, int header_padding, const ui::TableColumn& column, ui::TableModel* model); // Determines the width for each of the specified columns. |width| is the width // to fit the columns into. |header_font_list| the font list used to draw the // header and |content_font_list| the header used to draw the content. |padding| // is extra horizontal spaced added to each cell, and |header_padding| added to // the width needed for the header. VIEWS_EXPORT std::vector<int> CalculateTableColumnSizes( int width, int first_column_padding, const gfx::FontList& header_font_list, const gfx::FontList& content_font_list, int padding, int header_padding, const std::vector<ui::TableColumn>& columns, ui::TableModel* model); // Converts a TableColumn::Alignment to the alignment for drawing the string. int TableColumnAlignmentToCanvasAlignment(ui::TableColumn::Alignment alignment); // Returns the index of the closest visible column index to |x|. Return value is // in terms of table->visible_columns(). Returns nullopt if there are no visible // columns. absl::optional<size_t> GetClosestVisibleColumnIndex(const TableView* table, int x); // Returns the mirror of the table column alignment if the layout is // right-to-left. If the layout is left-to-right, the same alignment is // returned. ui::TableColumn::Alignment GetMirroredTableColumnAlignment( ui::TableColumn::Alignment alignment); } // namespace views #endif // UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_utils.h
C++
unknown
2,572
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/table_utils.h" #include <stddef.h> #include <string> #include "base/strings/string_number_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/font_list.h" #include "ui/views/controls/table/test_table_model.h" using ui::TableColumn; using ui::TableModel; namespace views { namespace { std::string IntVectorToString(const std::vector<int>& values) { std::string result; for (size_t i = 0; i < values.size(); ++i) { if (i != 0) result += ","; result += base::NumberToString(values[i]); } return result; } ui::TableColumn CreateTableColumnWithWidth(int width) { ui::TableColumn column; column.width = width; return column; } } // namespace // Verifies columns with a specified width is honored. TEST(TableUtilsTest, SetWidthHonored) { TestTableModel model(4); std::vector<TableColumn> columns; columns.push_back(CreateTableColumnWithWidth(20)); columns.push_back(CreateTableColumnWithWidth(30)); gfx::FontList font_list; std::vector<int> result(CalculateTableColumnSizes( 100, 0, font_list, font_list, 0, 0, columns, &model)); EXPECT_EQ("20,30", IntVectorToString(result)); // Same with some padding, it should be ignored. result = CalculateTableColumnSizes(100, 0, font_list, font_list, 2, 0, columns, &model); EXPECT_EQ("20,30", IntVectorToString(result)); // Same with not enough space, it shouldn't matter. result = CalculateTableColumnSizes(10, 0, font_list, font_list, 2, 0, columns, &model); EXPECT_EQ("20,30", IntVectorToString(result)); } // Verifies if no size is specified the last column gets all the available // space. TEST(TableUtilsTest, LastColumnGetsAllSpace) { TestTableModel model(4); std::vector<TableColumn> columns; columns.emplace_back(); columns.emplace_back(); gfx::FontList font_list; std::vector<int> result(CalculateTableColumnSizes( 500, 0, font_list, font_list, 0, 0, columns, &model)); EXPECT_NE(0, result[0]); EXPECT_GE(result[1], WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); EXPECT_EQ(500, result[0] + result[1]); } // Verifies a single column with a percent=1 is resized correctly. TEST(TableUtilsTest, SingleResizableColumn) { TestTableModel model(4); std::vector<TableColumn> columns; columns.emplace_back(); columns.emplace_back(); columns.emplace_back(); columns[2].percent = 1.0f; gfx::FontList font_list; std::vector<int> result(CalculateTableColumnSizes( 500, 0, font_list, font_list, 0, 0, columns, &model)); EXPECT_EQ(result[0], WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); EXPECT_EQ(result[1], WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); EXPECT_EQ(500 - result[0] - result[1], result[2]); // The same with a slightly larger width passed in. result = CalculateTableColumnSizes(1000, 0, font_list, font_list, 0, 0, columns, &model); EXPECT_EQ(result[0], WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); EXPECT_EQ(result[1], WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); EXPECT_EQ(1000 - result[0] - result[1], result[2]); // Verify padding for the first column is honored. result = CalculateTableColumnSizes(1000, 10, font_list, font_list, 0, 0, columns, &model); EXPECT_EQ( result[0], WidthForContent(font_list, font_list, 0, 0, columns[0], &model) + 10); EXPECT_EQ(result[1], WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); EXPECT_EQ(1000 - result[0] - result[1], result[2]); // Just enough space to show the first two columns. Should force last column // to min size. result = CalculateTableColumnSizes(1000, 0, font_list, font_list, 0, 0, columns, &model); result = CalculateTableColumnSizes(result[0] + result[1], 0, font_list, font_list, 0, 0, columns, &model); EXPECT_EQ(result[0], WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); EXPECT_EQ(result[1], WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); EXPECT_EQ(kUnspecifiedColumnWidth, result[2]); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_utils_unittest.cc
C++
unknown
4,571
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/table_view.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <map> #include <utility> #include "base/auto_reset.h" #include "base/containers/contains.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/i18n/rtl.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/ranges/algorithm.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "build/build_config.h" #include "cc/paint/paint_flags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/text_utils.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/accessibility/ax_virtual_view.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/table/table_grouper.h" #include "ui/views/controls/table/table_header.h" #include "ui/views/controls/table/table_utils.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/style/platform_style.h" #include "ui/views/style/typography.h" namespace views { namespace { constexpr int kGroupingIndicatorSize = 6; // Returns result, unless ascending is false in which case -result is returned. int SwapCompareResult(int result, bool ascending) { return ascending ? result : -result; } // Populates |model_index_to_range_start| based on the |grouper|. void GetModelIndexToRangeStart( TableGrouper* grouper, size_t row_count, std::map<size_t, size_t>* model_index_to_range_start) { for (size_t model_index = 0; model_index < row_count;) { GroupRange range; grouper->GetGroupRange(model_index, &range); DCHECK_GT(range.length, 0u); for (size_t i = model_index; i < model_index + range.length; ++i) (*model_index_to_range_start)[i] = model_index; model_index += range.length; } } // Returns the color id for the background of selected text. |has_focus| // indicates if the table has focus. ui::ColorId text_background_color_id(bool has_focus) { return has_focus ? ui::kColorTableBackgroundSelectedFocused : ui::kColorTableBackgroundSelectedUnfocused; } // Returns the color id for text. |has_focus| indicates if the table has focus. ui::ColorId selected_text_color_id(bool has_focus) { return has_focus ? ui::kColorTableForegroundSelectedFocused : ui::kColorTableForegroundSelectedUnfocused; } // Whether the platform "command" key is down. bool IsCmdOrCtrl(const ui::Event& event) { #if BUILDFLAG(IS_MAC) return event.IsCommandDown(); #else return event.IsControlDown(); #endif } } // namespace // Used as the comparator to sort the contents of the table. struct TableView::SortHelper { explicit SortHelper(TableView* table) : table(table) {} bool operator()(size_t model_index1, size_t model_index2) { return table->CompareRows(model_index1, model_index2) < 0; } raw_ptr<TableView> table; }; // Used as the comparator to sort the contents of the table when a TableGrouper // is present. When groups are present we sort the groups based on the first row // in the group and within the groups we keep the same order as the model. struct TableView::GroupSortHelper { explicit GroupSortHelper(TableView* table) : table(table) {} bool operator()(size_t model_index1, size_t model_index2) { const size_t range1 = model_index_to_range_start[model_index1]; const size_t range2 = model_index_to_range_start[model_index2]; if (range1 == range2) { // The two rows are in the same group, sort so that items in the same // group always appear in the same order. return model_index1 < model_index2; } return table->CompareRows(range1, range2) < 0; } raw_ptr<TableView> table; std::map<size_t, size_t> model_index_to_range_start; }; TableView::VisibleColumn::VisibleColumn() = default; TableView::VisibleColumn::~VisibleColumn() = default; TableView::PaintRegion::PaintRegion() = default; TableView::PaintRegion::~PaintRegion() = default; class TableView::HighlightPathGenerator : public views::HighlightPathGenerator { public: HighlightPathGenerator() = default; HighlightPathGenerator(const HighlightPathGenerator&) = delete; HighlightPathGenerator& operator=(const HighlightPathGenerator&) = delete; // HighlightPathGenerator: SkPath GetHighlightPath(const views::View* view) override { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return SkPath(); const TableView* const table = static_cast<const TableView*>(view); // If there's no focus indicator fall back on the default highlight path // (highlights entire view instead of active cell). if (!table->GetHasFocusIndicator()) return SkPath(); // Draw a focus indicator around the active cell. gfx::Rect bounds = table->GetActiveCellBounds(); bounds.set_x(table->GetMirroredXForRect(bounds)); return SkPath().addRect(gfx::RectToSkRect(bounds)); } }; TableView::TableView() : weak_factory_(this) { constexpr int kTextContext = style::CONTEXT_TABLE_ROW; constexpr int kTextStyle = style::STYLE_PRIMARY; font_list_ = style::GetFont(kTextContext, kTextStyle); row_height_ = LayoutProvider::GetControlHeightForFont(kTextContext, kTextStyle, font_list_); // Always focusable, even on Mac (consistent with NSTableView). SetFocusBehavior(FocusBehavior::ALWAYS); set_suppress_default_focus_handling(); views::HighlightPathGenerator::Install( this, std::make_unique<TableView::HighlightPathGenerator>()); FocusRing::Install(this); views::FocusRing::Get(this)->SetHasFocusPredicate([&](View* view) { return static_cast<TableView*>(view)->HasFocus() && !header_row_is_active_; }); } TableView::TableView(ui::TableModel* model, const std::vector<ui::TableColumn>& columns, TableTypes table_type, bool single_selection) : TableView() { Init(model, std::move(columns), table_type, single_selection); } TableView::~TableView() { if (model_) model_->SetObserver(nullptr); } // static std::unique_ptr<ScrollView> TableView::CreateScrollViewWithTable( std::unique_ptr<TableView> table) { auto scroll_view = ScrollView::CreateScrollViewWithBorder(); auto* table_ptr = table.get(); scroll_view->SetContents(std::move(table)); table_ptr->CreateHeaderIfNecessary(scroll_view.get()); return scroll_view; } // static Builder<ScrollView> TableView::CreateScrollViewBuilderWithTable( Builder<TableView>&& table) { auto scroll_view = ScrollView::CreateScrollViewWithBorder(); auto* scroll_view_ptr = scroll_view.get(); return Builder<ScrollView>(std::move(scroll_view)) .SetContents(std::move(table).CustomConfigure(base::BindOnce( [](ScrollView* scroll_view, TableView* table_view) { table_view->CreateHeaderIfNecessary(scroll_view); }, scroll_view_ptr))); } void TableView::Init(ui::TableModel* model, const std::vector<ui::TableColumn>& columns, TableTypes table_type, bool single_selection) { SetColumns(columns); SetTableType(table_type); SetSingleSelection(single_selection); SetModel(model); } // TODO(sky): this doesn't support arbitrarily changing the model, rename this // to ClearModel() or something. void TableView::SetModel(ui::TableModel* model) { if (model == model_) return; if (model_) model_->SetObserver(nullptr); model_ = model; selection_model_.Clear(); if (model_) { model_->SetObserver(this); // Clears and creates a new virtual accessibility tree. RebuildVirtualAccessibilityChildren(); } else { ClearVirtualAccessibilityChildren(); } } void TableView::SetColumns(const std::vector<ui::TableColumn>& columns) { columns_ = columns; visible_columns_.clear(); for (const auto& column : columns) { VisibleColumn visible_column; visible_column.column = column; visible_columns_.push_back(visible_column); } } void TableView::SetTableType(TableTypes table_type) { if (table_type_ == table_type) return; table_type_ = table_type; OnPropertyChanged(&table_type_, PropertyEffects::kPropertyEffectsLayout); } TableTypes TableView::GetTableType() const { return table_type_; } void TableView::SetSingleSelection(bool single_selection) { if (single_selection_ == single_selection) return; single_selection_ = single_selection; OnPropertyChanged(&single_selection_, PropertyEffects::kPropertyEffectsPaint); } bool TableView::GetSingleSelection() const { return single_selection_; } void TableView::SetGrouper(TableGrouper* grouper) { grouper_ = grouper; SortItemsAndUpdateMapping(/*schedule_paint=*/true); } size_t TableView::GetRowCount() const { return model_ ? model_->RowCount() : 0; } void TableView::Select(absl::optional<size_t> model_row) { if (!model_) return; SelectByViewIndex(model_row.has_value() ? absl::make_optional(ModelToView(model_row.value())) : absl::nullopt); } void TableView::SetSelectionAll(bool select) { if (!GetRowCount()) return; ui::ListSelectionModel selection_model; if (select) selection_model.AddIndexRangeToSelection(0, GetRowCount() - 1); selection_model.set_anchor(selection_model_.anchor()); selection_model.set_active(selection_model_.active()); SetSelectionModel(std::move(selection_model)); } absl::optional<size_t> TableView::GetFirstSelectedRow() const { return selection_model_.empty() ? absl::nullopt : absl::make_optional( *selection_model_.selected_indices().begin()); } // TODO(dpenning) : Prevent the last column from being closed. See // crbug.com/1324306 for details. void TableView::SetColumnVisibility(int id, bool is_visible) { if (is_visible == IsColumnVisible(id)) return; if (is_visible) { VisibleColumn visible_column; visible_column.column = FindColumnByID(id); visible_columns_.push_back(visible_column); } else { const auto i = base::ranges::find(visible_columns_, id, [](const auto& column) { return column.column.id; }); if (i != visible_columns_.end()) { visible_columns_.erase(i); if (active_visible_column_index_.has_value() && active_visible_column_index_.value() >= visible_columns_.size()) SetActiveVisibleColumnIndex( visible_columns_.empty() ? absl::nullopt : absl::make_optional(visible_columns_.size() - 1)); } } UpdateVisibleColumnSizes(); PreferredSizeChanged(); SchedulePaint(); if (header_) header_->SchedulePaint(); // This will clear and create the entire accessibility tree, to optimize this // further, removing/adding the cell's dynamically could be done instead. RebuildVirtualAccessibilityChildren(); } void TableView::ToggleSortOrder(size_t visible_column_index) { DCHECK(visible_column_index < visible_columns_.size()); const ui::TableColumn& column = visible_columns_[visible_column_index].column; if (!column.sortable) return; SortDescriptors sort(sort_descriptors_); if (!sort.empty() && sort[0].column_id == column.id) { if (sort[0].ascending == column.initial_sort_is_ascending) { // First toggle inverts the order. sort[0].ascending = !sort[0].ascending; GetViewAccessibility().AnnounceText(l10n_util::GetStringFUTF16( sort[0].ascending ? IDS_APP_TABLE_COLUMN_SORTED_ASC_ACCNAME : IDS_APP_TABLE_COLUMN_SORTED_DESC_ACCNAME, column.title)); } else { // Second toggle clears the sort. sort.clear(); GetViewAccessibility().AnnounceText(l10n_util::GetStringFUTF16( IDS_APP_TABLE_COLUMN_NOT_SORTED_ACCNAME, column.title)); } } else { SortDescriptor descriptor(column.id, column.initial_sort_is_ascending); sort.insert(sort.begin(), descriptor); // Only persist two sort descriptors. if (sort.size() > 2) sort.resize(2); GetViewAccessibility().AnnounceText(l10n_util::GetStringFUTF16( sort[0].ascending ? IDS_APP_TABLE_COLUMN_SORTED_ASC_ACCNAME : IDS_APP_TABLE_COLUMN_SORTED_DESC_ACCNAME, column.title)); } SetSortDescriptors(sort); UpdateFocusRings(); } void TableView::SetSortDescriptors(const SortDescriptors& sort_descriptors) { sort_descriptors_ = sort_descriptors; SortItemsAndUpdateMapping(/*schedule_paint=*/true); if (header_) header_->SchedulePaint(); } bool TableView::IsColumnVisible(int id) const { return base::Contains(visible_columns_, id, [](const VisibleColumn& column) { return column.column.id; }); } bool TableView::HasColumn(int id) const { return base::Contains(columns_, id, &ui::TableColumn::id); } bool TableView::GetHasFocusIndicator() const { return selection_model_.active().has_value() && active_visible_column_index_.has_value(); } void TableView::SetObserver(TableViewObserver* observer) { if (observer_ == observer) return; observer_ = observer; OnPropertyChanged(&observer_, PropertyEffects::kPropertyEffectsNone); } TableViewObserver* TableView::GetObserver() const { return observer_; } const TableView::VisibleColumn& TableView::GetVisibleColumn(size_t index) { DCHECK(index < visible_columns_.size()); return visible_columns_[index]; } void TableView::SetVisibleColumnWidth(size_t index, int width) { DCHECK(index < visible_columns_.size()); if (visible_columns_[index].width == width) return; base::AutoReset<bool> reseter(&in_set_visible_column_width_, true); visible_columns_[index].width = width; for (size_t i = index + 1; i < visible_columns_.size(); ++i) { visible_columns_[i].x = visible_columns_[i - 1].x + visible_columns_[i - 1].width; } PreferredSizeChanged(); SchedulePaint(); UpdateVirtualAccessibilityChildrenBounds(); } size_t TableView::ModelToView(size_t model_index) const { if (!GetIsSorted()) return model_index; DCHECK_LT(model_index, model_to_view_.size()) << " out of bounds model_index " << model_index; return model_to_view_[model_index]; } size_t TableView::ViewToModel(size_t view_index) const { DCHECK_LT(view_index, GetRowCount()); if (!GetIsSorted()) return view_index; DCHECK_LT(view_index, view_to_model_.size()) << " out of bounds view_index " << view_index; return view_to_model_[view_index]; } bool TableView::GetSelectOnRemove() const { return select_on_remove_; } void TableView::SetSelectOnRemove(bool select_on_remove) { if (select_on_remove_ == select_on_remove) return; select_on_remove_ = select_on_remove; OnPropertyChanged(&select_on_remove_, kPropertyEffectsNone); } bool TableView::GetSortOnPaint() const { return sort_on_paint_; } void TableView::SetSortOnPaint(bool sort_on_paint) { if (sort_on_paint_ == sort_on_paint) return; sort_on_paint_ = sort_on_paint; OnPropertyChanged(&sort_on_paint_, kPropertyEffectsNone); } ax::mojom::SortDirection TableView::GetFirstSortDescriptorDirection() const { DCHECK(!sort_descriptors().empty()); if (sort_descriptors()[0].ascending) return ax::mojom::SortDirection::kAscending; return ax::mojom::SortDirection::kDescending; } void TableView::Layout() { // When the scrollview's width changes we force recalculating column sizes. ScrollView* scroll_view = ScrollView::GetScrollViewForContents(this); if (scroll_view) { const int scroll_view_width = scroll_view->GetContentsBounds().width(); if (scroll_view_width != last_parent_width_) { last_parent_width_ = scroll_view_width; if (!in_set_visible_column_width_) { // Layout to the parent (the Viewport), which differs from // |scroll_view_width| when scrollbars are present. layout_width_ = parent()->width(); UpdateVisibleColumnSizes(); } } } // We have to override Layout like this since we're contained in a ScrollView. gfx::Size pref = GetPreferredSize(); int width = pref.width(); int height = pref.height(); if (parent()) { width = std::max(parent()->width(), width); height = std::max(parent()->height(), height); } SetBounds(x(), y(), width, height); if (header_) { header_->SetBoundsRect( gfx::Rect(header_->bounds().origin(), gfx::Size(width, header_->GetPreferredSize().height()))); } views::FocusRing::Get(this)->Layout(); } gfx::Size TableView::CalculatePreferredSize() const { int width = 50; if (header_ && !visible_columns_.empty()) width = visible_columns_.back().x + visible_columns_.back().width; return gfx::Size(width, static_cast<int>(GetRowCount()) * row_height_); } bool TableView::GetNeedsNotificationWhenVisibleBoundsChange() const { return true; } void TableView::OnVisibleBoundsChanged() { // When our visible bounds change, we need to make sure we update the bounds // of our AXVirtualView children. UpdateVirtualAccessibilityChildrenBounds(); } bool TableView::OnKeyPressed(const ui::KeyEvent& event) { if (!HasFocus()) return false; switch (event.key_code()) { case ui::VKEY_A: // control-a selects all. if (IsCmdOrCtrl(event) && !single_selection_ && GetRowCount()) { SetSelectionAll(/*select=*/true); return true; } break; case ui::VKEY_HOME: if (header_row_is_active_) break; if (GetRowCount()) SelectByViewIndex(size_t{0}); return true; case ui::VKEY_END: if (header_row_is_active_) break; if (GetRowCount()) SelectByViewIndex(GetRowCount() - 1); return true; case ui::VKEY_UP: #if BUILDFLAG(IS_MAC) if (event.IsAltDown()) { if (GetRowCount()) SelectByViewIndex(size_t{0}); } else { AdvanceSelection(AdvanceDirection::kDecrement); } #else AdvanceSelection(AdvanceDirection::kDecrement); #endif return true; case ui::VKEY_DOWN: #if BUILDFLAG(IS_MAC) if (event.IsAltDown()) { if (GetRowCount()) SelectByViewIndex(GetRowCount() - 1); } else { AdvanceSelection(AdvanceDirection::kIncrement); } #else AdvanceSelection(AdvanceDirection::kIncrement); #endif return true; case ui::VKEY_LEFT: if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) { const AdvanceDirection direction = base::i18n::IsRTL() ? AdvanceDirection::kIncrement : AdvanceDirection::kDecrement; if (IsCmdOrCtrl(event)) { if (active_visible_column_index_.has_value() && header_) { header_->ResizeColumnViaKeyboard( active_visible_column_index_.value(), direction); UpdateFocusRings(); } } else { AdvanceActiveVisibleColumn(direction); } return true; } break; case ui::VKEY_RIGHT: // TODO(crbug.com/1221001): Update TableView to support keyboard // navigation to table cells on Mac when "Full keyboard access" is // specified. if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) { const AdvanceDirection direction = base::i18n::IsRTL() ? AdvanceDirection::kDecrement : AdvanceDirection::kIncrement; if (IsCmdOrCtrl(event)) { if (active_visible_column_index_.has_value() && header_) { header_->ResizeColumnViaKeyboard( active_visible_column_index_.value(), direction); UpdateFocusRings(); } } else { AdvanceActiveVisibleColumn(direction); } return true; } break; // Currently there are TableView clients that take an action when the return // key is pressed and there is an active selection in the body. To avoid // breaking these cases only allow toggling sort order with the return key // when the table header is active. case ui::VKEY_RETURN: if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell && active_visible_column_index_.has_value() && header_row_is_active_) { ToggleSortOrder(active_visible_column_index_.value()); return true; } break; case ui::VKEY_SPACE: if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell && active_visible_column_index_.has_value()) { ToggleSortOrder(active_visible_column_index_.value()); return true; } break; default: break; } if (observer_) observer_->OnKeyDown(event.key_code()); return false; } bool TableView::OnMousePressed(const ui::MouseEvent& event) { RequestFocus(); if (!event.IsOnlyLeftMouseButton()) return true; const int row = event.y() / row_height_; if (row < 0 || static_cast<size_t>(row) >= GetRowCount()) return true; if (event.GetClickCount() == 2) { SelectByViewIndex(static_cast<size_t>(row)); if (observer_) observer_->OnDoubleClick(); } else if (event.GetClickCount() == 1) { ui::ListSelectionModel new_model; ConfigureSelectionModelForEvent(event, &new_model); SetSelectionModel(std::move(new_model)); } return true; } void TableView::OnGestureEvent(ui::GestureEvent* event) { if (event->type() != ui::ET_GESTURE_TAP_DOWN) return; RequestFocus(); const int row = event->y() / row_height_; if (row < 0 || static_cast<size_t>(row) >= GetRowCount()) return; event->StopPropagation(); ui::ListSelectionModel new_model; ConfigureSelectionModelForEvent(*event, &new_model); SetSelectionModel(std::move(new_model)); } std::u16string TableView::GetTooltipText(const gfx::Point& p) const { const int row = p.y() / row_height_; if (row < 0 || static_cast<size_t>(row) >= GetRowCount() || visible_columns_.empty()) { return std::u16string(); } const int x = GetMirroredXInView(p.x()); const absl::optional<size_t> column = GetClosestVisibleColumnIndex(this, x); if (!column.has_value() || x < visible_columns_[column.value()].x || x > (visible_columns_[column.value()].x + visible_columns_[column.value()].width)) { return std::u16string(); } const size_t model_row = ViewToModel(static_cast<size_t>(row)); if (column.value() == 0 && !model_->GetTooltip(model_row).empty()) return model_->GetTooltip(model_row); return model_->GetText(model_row, visible_columns_[column.value()].column.id); } void TableView::GetAccessibleNodeData(ui::AXNodeData* node_data) { // ID, class name and relative bounds are added by ViewAccessibility for all // non-virtual views, so we don't need to add them here. node_data->role = ax::mojom::Role::kListGrid; node_data->SetRestriction(ax::mojom::Restriction::kReadOnly); node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kActivate); // Subclasses should overwrite the name with the control's associated label. node_data->SetNameExplicitlyEmpty(); node_data->AddIntAttribute(ax::mojom::IntAttribute::kTableRowCount, static_cast<int32_t>(GetRowCount())); node_data->AddIntAttribute(ax::mojom::IntAttribute::kTableColumnCount, static_cast<int32_t>(visible_columns_.size())); } bool TableView::HandleAccessibleAction(const ui::AXActionData& action_data) { const size_t row_count = GetRowCount(); if (!row_count) return false; // On CrOS, the table wrapper node is not a AXVirtualView // and thus |ax_view| will be null. AXVirtualView* ax_view = AXVirtualView::GetFromId(action_data.target_node_id); bool focus_on_row = ax_view ? ax_view->GetData().role == ax::mojom::Role::kRow : false; size_t active_row = selection_model_.active().value_or(ModelToView(0)); switch (action_data.action) { case ax::mojom::Action::kDoDefault: RequestFocus(); if (focus_on_row) { // If the ax focus is on a row, select this row. DCHECK(ax_view); size_t row_index = base::checked_cast<size_t>(ax_view->GetData().GetIntAttribute( ax::mojom::IntAttribute::kTableRowIndex)); SelectByViewIndex(row_index); GetViewAccessibility().AnnounceText(l10n_util::GetStringFUTF16( IDS_TABLE_VIEW_AX_ANNOUNCE_ROW_SELECTED, model_->GetText(ViewToModel(row_index), GetVisibleColumn(0).column.id))); } else { // If the ax focus is on the full table, select the row as indicated by // the model. SelectByViewIndex(ModelToView(active_row)); if (observer_) observer_->OnDoubleClick(); } break; case ax::mojom::Action::kFocus: RequestFocus(); // Setting focus should not affect the current selection. if (selection_model_.empty()) SelectByViewIndex(size_t{0}); break; case ax::mojom::Action::kScrollRight: { const AdvanceDirection direction = base::i18n::IsRTL() ? AdvanceDirection::kDecrement : AdvanceDirection::kIncrement; AdvanceActiveVisibleColumn(direction); break; } case ax::mojom::Action::kScrollLeft: { const AdvanceDirection direction = base::i18n::IsRTL() ? AdvanceDirection::kIncrement : AdvanceDirection::kDecrement; AdvanceActiveVisibleColumn(direction); break; } case ax::mojom::Action::kScrollToMakeVisible: ScrollRectToVisible(GetRowBounds(ModelToView(active_row))); break; case ax::mojom::Action::kSetSelection: // TODO(nektar): Retrieve the anchor and focus nodes once AXVirtualView is // implemented in this class. SelectByViewIndex(active_row); break; case ax::mojom::Action::kShowContextMenu: ShowContextMenu(GetBoundsInScreen().CenterPoint(), ui::MENU_SOURCE_KEYBOARD); break; default: return false; } return true; } void TableView::OnModelChanged() { selection_model_.Clear(); RebuildVirtualAccessibilityChildren(); PreferredSizeChanged(); } void TableView::OnItemsChanged(size_t start, size_t length) { SortItemsAndUpdateMapping(/*schedule_paint=*/true); } void TableView::OnItemsAdded(size_t start, size_t length) { DCHECK_LE(start + length, GetRowCount()); for (size_t i = 0; i < length; ++i) { // Increment selection model counter at start. selection_model_.IncrementFrom(start); // Append new virtual row to accessibility view. const size_t virtual_children_count = GetViewAccessibility().virtual_children().size(); const size_t next_index = header_ ? virtual_children_count - 1 : virtual_children_count; GetViewAccessibility().AddVirtualChildView( CreateRowAccessibilityView(next_index)); } SortItemsAndUpdateMapping(/*schedule_paint=*/true); PreferredSizeChanged(); NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true); } void TableView::OnItemsMoved(size_t old_start, size_t length, size_t new_start) { selection_model_.Move(old_start, new_start, length); SortItemsAndUpdateMapping(/*schedule_paint=*/true); } void TableView::OnItemsRemoved(size_t start, size_t length) { // Determine the currently selected index in terms of the view. We inline the // implementation here since ViewToModel() has DCHECKs that fail since the // model has changed but |model_to_view_| has not been updated yet. const absl::optional<size_t> previously_selected_model_index = GetFirstSelectedRow(); absl::optional<size_t> previously_selected_view_index = previously_selected_model_index; if (previously_selected_model_index.has_value() && GetIsSorted()) previously_selected_view_index = model_to_view_[previously_selected_model_index.value()]; for (size_t i = 0; i < length; ++i) selection_model_.DecrementFrom(start); // Update the `view_to_model_` and `model_to_view_` mappings prior to updating // TableView's virtual children below. We do this because at this point the // table model has changed but the model-view mappings have not yet been // updated to reflect this. `RemoveFromParentView()` below may trigger calls // back into TableView and this would happen before the model-view mappings // have been updated. This can result in memory overflow errors. // See (https://crbug.com/1173373). SortItemsAndUpdateMapping(/*schedule_paint=*/true); if (GetIsSorted()) { DCHECK_EQ(GetRowCount(), view_to_model_.size()); DCHECK_EQ(GetRowCount(), model_to_view_.size()); } // If the selection was empty and is no longer empty select the same visual // index. if (selection_model_.empty() && previously_selected_view_index.has_value() && GetRowCount() && select_on_remove_) { selection_model_.SetSelectedIndex(ViewToModel( std::min(GetRowCount() - 1, previously_selected_view_index.value()))); } if (!selection_model_.empty()) { const size_t selected_model_index = *selection_model_.selected_indices().begin(); if (!selection_model_.active().has_value()) selection_model_.set_active(selected_model_index); if (!selection_model_.anchor().has_value()) selection_model_.set_anchor(selected_model_index); } // Remove the virtual views that are no longer needed. auto& virtual_children = GetViewAccessibility().virtual_children(); for (size_t i = start; !virtual_children.empty() && i < start + length; i++) virtual_children[virtual_children.size() - 1]->RemoveFromParentView(); UpdateVirtualAccessibilityChildrenBounds(); PreferredSizeChanged(); NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true); if (observer_) observer_->OnSelectionChanged(); } gfx::Point TableView::GetKeyboardContextMenuLocation() { absl::optional<size_t> first_selected = GetFirstSelectedRow(); gfx::Rect vis_bounds(GetVisibleBounds()); int y = vis_bounds.height() / 2; if (first_selected.has_value()) { gfx::Rect cell_bounds(GetRowBounds(first_selected.value())); if (cell_bounds.bottom() >= vis_bounds.y() && cell_bounds.bottom() < vis_bounds.bottom()) { y = cell_bounds.bottom(); } } gfx::Point screen_loc(0, y); if (base::i18n::IsRTL()) screen_loc.set_x(width()); ConvertPointToScreen(this, &screen_loc); return screen_loc; } void TableView::OnFocus() { SchedulePaintForSelection(); UpdateFocusRings(); ScheduleUpdateAccessibilityFocusIfNeeded(); } void TableView::OnBlur() { SchedulePaintForSelection(); UpdateFocusRings(); ScheduleUpdateAccessibilityFocusIfNeeded(); } void TableView::OnPaint(gfx::Canvas* canvas) { OnPaintImpl(canvas); } void TableView::OnPaintImpl(gfx::Canvas* canvas) { // Don't invoke View::OnPaint so that we can render our own focus border. if (sort_on_paint_) SortItemsAndUpdateMapping(/*schedule_paint=*/false); ui::ColorProvider* color_provider = GetColorProvider(); const SkColor default_bg_color = color_provider->GetColor(ui::kColorTableBackground); canvas->DrawColor(default_bg_color); if (!GetRowCount() || visible_columns_.empty()) return; const PaintRegion region(GetPaintRegion(GetPaintBounds(canvas))); if (region.min_column == visible_columns_.size()) return; // No need to paint anything. const SkColor selected_bg_color = color_provider->GetColor(text_background_color_id(HasFocus())); const SkColor fg_color = color_provider->GetColor(ui::kColorTableForeground); const SkColor selected_fg_color = color_provider->GetColor(selected_text_color_id(HasFocus())); const SkColor alternate_bg_color = color_provider->GetColor(ui::kColorTableBackgroundAlternate); const int cell_margin = GetCellMargin(); const int cell_element_spacing = GetCellElementSpacing(); for (size_t i = region.min_row; i < region.max_row; ++i) { const size_t model_index = ViewToModel(i); const bool is_selected = selection_model_.IsSelected(model_index); if (is_selected) canvas->FillRect(GetRowBounds(i), selected_bg_color); else if (alternate_bg_color != default_bg_color && (i % 2)) canvas->FillRect(GetRowBounds(i), alternate_bg_color); for (size_t j = region.min_column; j < region.max_column; ++j) { const gfx::Rect cell_bounds = GetCellBounds(i, j); gfx::Rect text_bounds = cell_bounds; text_bounds.Inset(gfx::Insets::VH(0, cell_margin)); // Provide space for the grouping indicator, but draw it separately. if (j == 0 && grouper_) { text_bounds.Inset(gfx::Insets().set_left(kGroupingIndicatorSize + cell_element_spacing)); } // Always paint the icon in the first visible column. if (j == 0 && table_type_ == ICON_AND_TEXT) { gfx::ImageSkia image = model_->GetIcon(model_index).Rasterize(GetColorProvider()); if (!image.isNull()) { int image_x = GetMirroredXWithWidthInView(text_bounds.x(), ui::TableModel::kIconSize); canvas->DrawImageInt( image, 0, 0, image.width(), image.height(), image_x, cell_bounds.y() + (cell_bounds.height() - ui::TableModel::kIconSize) / 2, ui::TableModel::kIconSize, ui::TableModel::kIconSize, true); } text_bounds.Inset(gfx::Insets().set_left(ui::TableModel::kIconSize + cell_element_spacing)); } // Paint text if there is still room for it after all that insetting. if (!text_bounds.IsEmpty()) { canvas->DrawStringRectWithFlags( model_->GetText(model_index, visible_columns_[j].column.id), font_list_, is_selected ? selected_fg_color : fg_color, GetMirroredRect(text_bounds), TableColumnAlignmentToCanvasAlignment( GetMirroredTableColumnAlignment( visible_columns_[j].column.alignment))); } } } if (!grouper_ || region.min_column > 0) return; const SkColor grouping_color = color_provider->GetColor(ui::kColorTableGroupingIndicator); cc::PaintFlags grouping_flags; grouping_flags.setColor(grouping_color); grouping_flags.setStyle(cc::PaintFlags::kFill_Style); grouping_flags.setStrokeWidth(kGroupingIndicatorSize); grouping_flags.setStrokeCap(cc::PaintFlags::kRound_Cap); grouping_flags.setAntiAlias(true); const int group_indicator_x = GetMirroredXInView( GetCellBounds(0, 0).x() + cell_margin + kGroupingIndicatorSize / 2); for (size_t i = region.min_row; i < region.max_row;) { const size_t model_index = ViewToModel(i); GroupRange range; grouper_->GetGroupRange(model_index, &range); DCHECK_GT(range.length, 0u); // The order of rows in a group is consistent regardless of sort, so it's ok // to do this calculation. const size_t start = i - (model_index - range.start); const size_t last = start + range.length - 1; const gfx::RectF start_cell_bounds(GetCellBounds(start, 0)); const gfx::RectF last_cell_bounds(GetCellBounds(last, 0)); canvas->DrawLine( gfx::PointF(group_indicator_x, start_cell_bounds.CenterPoint().y()), gfx::PointF(group_indicator_x, last_cell_bounds.CenterPoint().y()), grouping_flags); i = last + 1; } } int TableView::GetCellMargin() const { return LayoutProvider::Get()->GetDistanceMetric( DISTANCE_TABLE_CELL_HORIZONTAL_MARGIN); } int TableView::GetCellElementSpacing() const { return LayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_LABEL_HORIZONTAL); } void TableView::SortItemsAndUpdateMapping(bool schedule_paint) { const size_t row_count = GetRowCount(); if (!GetIsSorted()) { view_to_model_.clear(); model_to_view_.clear(); } else { view_to_model_.resize(row_count); model_to_view_.resize(row_count); // Resets the mapping so it can be sorted again. for (size_t view_index = 0; view_index < row_count; ++view_index) view_to_model_[view_index] = view_index; if (grouper_) { GroupSortHelper sort_helper(this); GetModelIndexToRangeStart(grouper_, row_count, &sort_helper.model_index_to_range_start); std::stable_sort(view_to_model_.begin(), view_to_model_.end(), sort_helper); } else { std::stable_sort(view_to_model_.begin(), view_to_model_.end(), SortHelper(this)); } for (size_t view_index = 0; view_index < row_count; ++view_index) model_to_view_[view_to_model_[view_index]] = view_index; model_->ClearCollator(); } UpdateVirtualAccessibilityChildrenBounds(); if (schedule_paint) SchedulePaint(); } int TableView::CompareRows(size_t model_row1, size_t model_row2) { const int sort_result = model_->CompareValues(model_row1, model_row2, sort_descriptors_[0].column_id); if (sort_result == 0 && sort_descriptors_.size() > 1) { // Try the secondary sort. return SwapCompareResult( model_->CompareValues(model_row1, model_row2, sort_descriptors_[1].column_id), sort_descriptors_[1].ascending); } return SwapCompareResult(sort_result, sort_descriptors_[0].ascending); } gfx::Rect TableView::GetRowBounds(size_t row) const { return gfx::Rect(0, static_cast<int>(row) * row_height_, width(), row_height_); } gfx::Rect TableView::GetCellBounds(size_t row, size_t visible_column_index) const { if (!header_) return GetRowBounds(row); const VisibleColumn& vis_col(visible_columns_[visible_column_index]); return gfx::Rect(vis_col.x, static_cast<int>(row) * row_height_, vis_col.width, row_height_); } gfx::Rect TableView::GetActiveCellBounds() const { if (!selection_model_.active().has_value()) return gfx::Rect(); return GetCellBounds(ModelToView(selection_model_.active().value()), active_visible_column_index_.value()); } void TableView::AdjustCellBoundsForText(size_t visible_column_index, gfx::Rect* bounds) const { const int cell_margin = GetCellMargin(); const int cell_element_spacing = GetCellElementSpacing(); int text_x = cell_margin + bounds->x(); if (visible_column_index == 0) { if (grouper_) text_x += kGroupingIndicatorSize + cell_element_spacing; if (table_type_ == ICON_AND_TEXT) text_x += ui::TableModel::kIconSize + cell_element_spacing; } bounds->set_x(text_x); bounds->set_width(std::max(0, bounds->right() - cell_margin - text_x)); } void TableView::CreateHeaderIfNecessary(ScrollView* scroll_view) { // Only create a header if there is more than one column or the title of the // only column is not empty. if (header_ || (columns_.size() == 1 && columns_[0].title.empty())) return; header_ = scroll_view->SetHeader(std::make_unique<TableHeader>(this)); // The header accessibility view should be the first row, to match the // original view accessibility construction. GetViewAccessibility().AddVirtualChildViewAt(CreateHeaderAccessibilityView(), 0); } void TableView::UpdateVisibleColumnSizes() { if (!header_) return; std::vector<ui::TableColumn> columns; for (const auto& visible_column : visible_columns_) columns.push_back(visible_column.column); const int cell_margin = GetCellMargin(); const int cell_element_spacing = GetCellElementSpacing(); int first_column_padding = 0; if (table_type_ == ICON_AND_TEXT && header_) first_column_padding += ui::TableModel::kIconSize + cell_element_spacing; if (grouper_) first_column_padding += kGroupingIndicatorSize + cell_element_spacing; std::vector<int> sizes = views::CalculateTableColumnSizes( layout_width_, first_column_padding, header_->font_list(), font_list_, std::max(cell_margin, TableHeader::kHorizontalPadding) * 2, TableHeader::kSortIndicatorWidth, columns, model_); DCHECK_EQ(visible_columns_.size(), sizes.size()); int x = 0; for (size_t i = 0; i < visible_columns_.size(); ++i) { visible_columns_[i].x = x; visible_columns_[i].width = sizes[i]; x += sizes[i]; } } TableView::PaintRegion TableView::GetPaintRegion( const gfx::Rect& bounds) const { DCHECK(!visible_columns_.empty()); DCHECK(GetRowCount()); PaintRegion region; region.min_row = static_cast<size_t>( std::clamp(bounds.y() / row_height_, 0, base::saturated_cast<int>(GetRowCount() - 1))); region.max_row = static_cast<size_t>(bounds.bottom() / row_height_); if (bounds.bottom() % row_height_ != 0) region.max_row++; region.max_row = std::min(region.max_row, GetRowCount()); if (!header_) { region.max_column = 1; return region; } const int paint_x = GetMirroredXForRect(bounds); const int paint_max_x = paint_x + bounds.width(); region.min_column = region.max_column = visible_columns_.size(); for (size_t i = 0; i < visible_columns_.size(); ++i) { int max_x = visible_columns_[i].x + visible_columns_[i].width; if (region.min_column == visible_columns_.size() && max_x >= paint_x) region.min_column = i; if (region.min_column != visible_columns_.size() && visible_columns_[i].x >= paint_max_x) { region.max_column = i; break; } } return region; } gfx::Rect TableView::GetPaintBounds(gfx::Canvas* canvas) const { SkRect sk_clip_rect; if (canvas->sk_canvas()->getLocalClipBounds(&sk_clip_rect)) return gfx::ToEnclosingRect(gfx::SkRectToRectF(sk_clip_rect)); return GetVisibleBounds(); } void TableView::SchedulePaintForSelection() { if (selection_model_.size() == 1) { const absl::optional<size_t> first_model_row = GetFirstSelectedRow(); SchedulePaintInRect(GetRowBounds(ModelToView(first_model_row.value()))); if (selection_model_.active().has_value() && first_model_row != selection_model_.active().value()) { SchedulePaintInRect( GetRowBounds(ModelToView(selection_model_.active().value()))); } } else if (selection_model_.size() > 1) { SchedulePaint(); } } ui::TableColumn TableView::FindColumnByID(int id) const { const auto i = base::ranges::find(columns_, id, &ui::TableColumn::id); DCHECK(i != columns_.cend()); return *i; } void TableView::AdvanceActiveVisibleColumn(AdvanceDirection direction) { if (visible_columns_.empty()) { SetActiveVisibleColumnIndex(absl::nullopt); return; } if (!active_visible_column_index_.has_value()) { if (!selection_model_.active().has_value() && !header_row_is_active_) SelectByViewIndex(size_t{0}); SetActiveVisibleColumnIndex(size_t{0}); return; } if (direction == AdvanceDirection::kDecrement) { SetActiveVisibleColumnIndex( std::max(size_t{1}, active_visible_column_index_.value()) - 1); } else { SetActiveVisibleColumnIndex(std::min( visible_columns_.size() - 1, active_visible_column_index_.value() + 1)); } } absl::optional<size_t> TableView::GetActiveVisibleColumnIndex() const { return active_visible_column_index_; } void TableView::SetActiveVisibleColumnIndex(absl::optional<size_t> index) { if (active_visible_column_index_ == index) return; active_visible_column_index_ = index; if (selection_model_.active().has_value() && active_visible_column_index_.has_value()) { ScrollRectToVisible( GetCellBounds(ModelToView(selection_model_.active().value()), active_visible_column_index_.value())); } UpdateFocusRings(); ScheduleUpdateAccessibilityFocusIfNeeded(); OnPropertyChanged(&active_visible_column_index_, kPropertyEffectsNone); } void TableView::SelectByViewIndex(absl::optional<size_t> view_index) { ui::ListSelectionModel new_selection; if (view_index.has_value()) { SelectRowsInRangeFrom(view_index.value(), true, &new_selection); new_selection.set_anchor(ViewToModel(view_index.value())); new_selection.set_active(ViewToModel(view_index.value())); } SetSelectionModel(std::move(new_selection)); } void TableView::SetSelectionModel(ui::ListSelectionModel new_selection) { if (new_selection == selection_model_) return; SchedulePaintForSelection(); selection_model_ = std::move(new_selection); SchedulePaintForSelection(); // Scroll the group for the active item to visible. if (selection_model_.active().has_value()) { gfx::Rect vis_rect(GetVisibleBounds()); const GroupRange range(GetGroupRange(selection_model_.active().value())); const int start_y = GetRowBounds(ModelToView(range.start)).y(); const int end_y = GetRowBounds(ModelToView(range.start + range.length - 1)).bottom(); vis_rect.set_y(start_y); vis_rect.set_height(end_y - start_y); ScrollRectToVisible(vis_rect); if (!active_visible_column_index_.has_value()) SetActiveVisibleColumnIndex(size_t{0}); } else if (!header_row_is_active_) { SetActiveVisibleColumnIndex(absl::nullopt); } UpdateFocusRings(); ScheduleUpdateAccessibilityFocusIfNeeded(); if (observer_) observer_->OnSelectionChanged(); } void TableView::AdvanceSelection(AdvanceDirection direction) { if (!selection_model_.active().has_value()) { bool make_header_active = header_ && direction == AdvanceDirection::kDecrement; header_row_is_active_ = make_header_active; SelectByViewIndex(make_header_active ? absl::nullopt : absl::make_optional(size_t{0})); UpdateFocusRings(); ScheduleUpdateAccessibilityFocusIfNeeded(); return; } size_t active_index = selection_model_.active().value(); size_t view_index = ModelToView(active_index); const GroupRange range(GetGroupRange(active_index)); size_t view_range_start = ModelToView(range.start); if (direction == AdvanceDirection::kDecrement) { bool make_header_active = header_ && view_index == 0; header_row_is_active_ = make_header_active; SelectByViewIndex( make_header_active ? absl::nullopt : absl::make_optional(std::max(size_t{1}, view_range_start) - 1)); } else { header_row_is_active_ = false; SelectByViewIndex( std::min(GetRowCount() - 1, view_range_start + range.length)); } } void TableView::ConfigureSelectionModelForEvent( const ui::LocatedEvent& event, ui::ListSelectionModel* model) const { const int view_index_int = event.y() / row_height_; DCHECK_GE(view_index_int, 0); const size_t view_index = static_cast<size_t>(view_index_int); DCHECK_LT(view_index, GetRowCount()); if (!selection_model_.anchor().has_value() || single_selection_ || (!IsCmdOrCtrl(event) && !event.IsShiftDown())) { SelectRowsInRangeFrom(view_index, true, model); model->set_anchor(ViewToModel(view_index)); model->set_active(ViewToModel(view_index)); return; } if ((IsCmdOrCtrl(event) && event.IsShiftDown()) || event.IsShiftDown()) { // control-shift: copy existing model and make sure rows between anchor and // |view_index| are selected. // shift: reset selection so that only rows between anchor and |view_index| // are selected. if (IsCmdOrCtrl(event) && event.IsShiftDown()) *model = selection_model_; else model->set_anchor(selection_model_.anchor()); DCHECK(model->anchor().has_value()); const size_t anchor_index = ModelToView(model->anchor().value()); const auto [min, max] = std::minmax(view_index, anchor_index); for (size_t i = min; i <= max; ++i) SelectRowsInRangeFrom(i, true, model); model->set_active(ViewToModel(view_index)); } else { DCHECK(IsCmdOrCtrl(event)); // Toggle the selection state of |view_index| and set the anchor/active to // it and don't change the state of any other rows. *model = selection_model_; model->set_anchor(ViewToModel(view_index)); model->set_active(ViewToModel(view_index)); SelectRowsInRangeFrom(view_index, !model->IsSelected(ViewToModel(view_index)), model); } } void TableView::SelectRowsInRangeFrom(size_t view_index, bool select, ui::ListSelectionModel* model) const { const GroupRange range(GetGroupRange(ViewToModel(view_index))); for (size_t i = 0; i < range.length; ++i) { if (select) model->AddIndexToSelection(range.start + i); else model->RemoveIndexFromSelection(range.start + i); } } GroupRange TableView::GetGroupRange(size_t model_index) const { GroupRange range; if (grouper_) { grouper_->GetGroupRange(model_index, &range); } else { range.start = model_index; range.length = 1; } return range; } void TableView::RebuildVirtualAccessibilityChildren() { ClearVirtualAccessibilityChildren(); if (!GetRowCount() || visible_columns_.empty()) return; if (header_) GetViewAccessibility().AddVirtualChildView(CreateHeaderAccessibilityView()); // Create a virtual accessibility view for each row. At this point on, the // table has no sort behavior, hence the view index is the same as the model // index, the sorting will happen at the end. for (size_t index = 0; index < GetRowCount(); ++index) GetViewAccessibility().AddVirtualChildView( CreateRowAccessibilityView(index)); SortItemsAndUpdateMapping(/*schedule_paint=*/true); NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true); } void TableView::ClearVirtualAccessibilityChildren() { GetViewAccessibility().RemoveAllVirtualChildViews(); } std::unique_ptr<AXVirtualView> TableView::CreateRowAccessibilityView( size_t row_index) { auto ax_row = std::make_unique<AXVirtualView>(); ui::AXNodeData& row_data = ax_row->GetCustomData(); row_data.role = ax::mojom::Role::kRow; row_data.AddIntAttribute(ax::mojom::IntAttribute::kTableRowIndex, static_cast<int32_t>(row_index)); if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) { row_data.AddState(ax::mojom::State::kFocusable); row_data.AddAction(ax::mojom::Action::kFocus); row_data.AddAction(ax::mojom::Action::kScrollToMakeVisible); row_data.AddAction(ax::mojom::Action::kSetSelection); } row_data.SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kSelect); if (!single_selection_) row_data.AddState(ax::mojom::State::kMultiselectable); // Add a dynamic accessibility data callback for each row. ax_row->SetPopulateDataCallback( base::BindRepeating(&TableView::PopulateAccessibilityRowData, base::Unretained(this), ax_row.get())); for (size_t visible_column_index = 0; visible_column_index < visible_columns_.size(); ++visible_column_index) { std::unique_ptr<AXVirtualView> ax_cell = CreateCellAccessibilityView(row_index, visible_column_index); ax_row->AddChildView(std::move(ax_cell)); } return ax_row; } std::unique_ptr<AXVirtualView> TableView::CreateCellAccessibilityView( size_t row_index, size_t column_index) { const VisibleColumn& visible_column = visible_columns_[column_index]; const ui::TableColumn column = visible_column.column; auto ax_cell = std::make_unique<AXVirtualView>(); ui::AXNodeData& cell_data = ax_cell->GetCustomData(); cell_data.role = ax::mojom::Role::kCell; cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, static_cast<int32_t>(row_index)); if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) { cell_data.AddState(ax::mojom::State::kFocusable); cell_data.AddAction(ax::mojom::Action::kFocus); cell_data.AddAction(ax::mojom::Action::kScrollLeft); cell_data.AddAction(ax::mojom::Action::kScrollRight); cell_data.AddAction(ax::mojom::Action::kScrollToMakeVisible); cell_data.AddAction(ax::mojom::Action::kSetSelection); } cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowSpan, 1); cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, static_cast<int32_t>(column_index)); cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnSpan, 1); if (base::i18n::IsRTL()) cell_data.SetTextDirection(ax::mojom::WritingDirection::kRtl); auto sort_direction = ax::mojom::SortDirection::kUnsorted; const absl::optional<int> primary_sorted_column_id = sort_descriptors().empty() ? absl::nullopt : absl::make_optional(sort_descriptors()[0].column_id); if (column.sortable && primary_sorted_column_id.has_value() && column.id == primary_sorted_column_id.value()) { sort_direction = GetFirstSortDescriptorDirection(); } cell_data.AddIntAttribute(ax::mojom::IntAttribute::kSortDirection, static_cast<int32_t>(sort_direction)); // Add a dynamic accessibility data callback for each cell. ax_cell->SetPopulateDataCallback( base::BindRepeating(&TableView::PopulateAccessibilityCellData, base::Unretained(this), ax_cell.get())); return ax_cell; } void TableView::PopulateAccessibilityRowData(AXVirtualView* ax_row, ui::AXNodeData* data) { auto ax_index = GetViewAccessibility().GetIndexOf(ax_row); DCHECK(ax_index.has_value()); size_t row_index = ax_index.value() - (header_ ? 1 : 0); size_t model_index = ViewToModel(row_index); // When navigating using up / down cursor keys on the Mac, we read the // contents of the first cell. If the user needs to explore additional cell's, // they can use VoiceOver shortcuts. if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) data->SetName(model_->GetText(model_index, GetVisibleColumn(0).column.id)); gfx::Rect row_bounds = GetRowBounds(model_index); if (!GetVisibleBounds().Intersects(row_bounds)) data->AddState(ax::mojom::State::kInvisible); if (selection_model().IsSelected(model_index)) data->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); } void TableView::PopulateAccessibilityCellData(AXVirtualView* ax_cell, ui::AXNodeData* data) { AXVirtualView* ax_row = ax_cell->virtual_parent_view(); DCHECK(ax_row); auto ax_index = GetViewAccessibility().GetIndexOf(ax_row); DCHECK(ax_index.has_value()); size_t row_index = ax_index.value() - (header_ ? 1 : 0); auto column_index = ax_row->GetIndexOf(ax_cell); DCHECK(column_index.has_value()); size_t model_index = ViewToModel(row_index); gfx::Rect cell_bounds = GetCellBounds(row_index, column_index.value()); if (!GetVisibleBounds().Intersects(cell_bounds)) data->AddState(ax::mojom::State::kInvisible); if (PlatformStyle::kTableViewSupportsKeyboardNavigationByCell && column_index.value() == GetActiveVisibleColumnIndex()) { if (selection_model().IsSelected(model_index)) data->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true); } // Set the cell's value since it changes dynamically. std::u16string current_name = base::UTF8ToUTF16( data->GetStringAttribute(ax::mojom::StringAttribute::kName)); std::u16string new_name = model()->GetText( model_index, GetVisibleColumn(column_index.value()).column.id); data->SetName(new_name); if (current_name != new_name) { ui::AXNodeData& cell_data = ax_cell->GetCustomData(); cell_data.SetName(new_name); ax_cell->NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged); } } void TableView::UpdateFocusRings() { views::FocusRing::Get(this)->SchedulePaint(); if (header_) header_->UpdateFocusState(); } std::unique_ptr<AXVirtualView> TableView::CreateHeaderAccessibilityView() { DCHECK(header_) << "header_ needs to be instantiated before setting its" "accessibility view."; const absl::optional<int> primary_sorted_column_id = sort_descriptors().empty() ? absl::nullopt : absl::make_optional(sort_descriptors()[0].column_id); auto ax_header = std::make_unique<AXVirtualView>(); ui::AXNodeData& header_data = ax_header->GetCustomData(); header_data.role = ax::mojom::Role::kRow; for (size_t visible_column_index = 0; visible_column_index < visible_columns_.size(); ++visible_column_index) { const VisibleColumn& visible_column = visible_columns_[visible_column_index]; const ui::TableColumn column = visible_column.column; auto ax_cell = std::make_unique<AXVirtualView>(); ui::AXNodeData& cell_data = ax_cell->GetCustomData(); cell_data.role = ax::mojom::Role::kColumnHeader; cell_data.SetName(column.title); cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnIndex, static_cast<int32_t>(visible_column_index)); cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellColumnSpan, 1); if (base::i18n::IsRTL()) { cell_data.SetTextDirection(ax::mojom::WritingDirection::kRtl); } auto sort_direction = ax::mojom::SortDirection::kUnsorted; if (column.sortable && primary_sorted_column_id.has_value() && column.id == primary_sorted_column_id.value()) { sort_direction = GetFirstSortDescriptorDirection(); } cell_data.AddIntAttribute(ax::mojom::IntAttribute::kSortDirection, static_cast<int32_t>(sort_direction)); ax_header->AddChildView(std::move(ax_cell)); } return ax_header; } bool TableView::UpdateVirtualAccessibilityRowData(AXVirtualView* ax_row, int view_index, int model_index) { DCHECK_GE(view_index, 0); ui::AXNodeData& row_data = ax_row->GetCustomData(); int previous_view_index = row_data.GetIntAttribute(ax::mojom::IntAttribute::kTableRowIndex); if (previous_view_index == view_index) return false; row_data.AddIntAttribute(ax::mojom::IntAttribute::kTableRowIndex, static_cast<int32_t>(view_index)); // Update the cell's in the current row to have the new data. for (const auto& ax_cell : ax_row->children()) { ui::AXNodeData& cell_data = ax_cell->GetCustomData(); cell_data.AddIntAttribute(ax::mojom::IntAttribute::kTableCellRowIndex, static_cast<int32_t>(view_index)); } return true; } void TableView::UpdateVirtualAccessibilityChildrenBounds() { // The virtual children may be empty if the |model_| is in the process of // updating (e.g. showing or hiding a column) but the virtual accessibility // children haven't been updated yet to reflect the new model. auto& virtual_children = GetViewAccessibility().virtual_children(); if (virtual_children.empty()) return; // Update the bounds for the header first, if applicable. if (header_) { auto& ax_row = virtual_children[0]; ui::AXNodeData& row_data = ax_row->GetCustomData(); DCHECK_EQ(row_data.role, ax::mojom::Role::kRow); row_data.relative_bounds.bounds = gfx::RectF(CalculateHeaderRowAccessibilityBounds()); // Update the bounds for every child cell in this row. for (size_t visible_column_index = 0; visible_column_index < ax_row->children().size(); visible_column_index++) { ui::AXNodeData& cell_data = ax_row->children()[visible_column_index]->GetCustomData(); DCHECK_EQ(cell_data.role, ax::mojom::Role::kColumnHeader); if (visible_column_index < visible_columns_.size()) { cell_data.relative_bounds.bounds = gfx::RectF( CalculateHeaderCellAccessibilityBounds(visible_column_index)); } else { cell_data.relative_bounds.bounds = gfx::RectF(); } } } // Update the bounds for the table's content rows. for (size_t row_index = 0; row_index < GetRowCount(); row_index++) { const size_t ax_row_index = header_ ? row_index + 1 : row_index; if (ax_row_index >= virtual_children.size()) break; auto& ax_row = virtual_children[ax_row_index]; ui::AXNodeData& row_data = ax_row->GetCustomData(); DCHECK_EQ(row_data.role, ax::mojom::Role::kRow); row_data.relative_bounds.bounds = gfx::RectF(CalculateTableRowAccessibilityBounds(row_index)); // Update the bounds for every child cell in this row. for (size_t visible_column_index = 0; visible_column_index < ax_row->children().size(); visible_column_index++) { ui::AXNodeData& cell_data = ax_row->children()[visible_column_index]->GetCustomData(); DCHECK_EQ(cell_data.role, ax::mojom::Role::kCell); if (visible_column_index < visible_columns_.size()) { cell_data.relative_bounds.bounds = gfx::RectF(CalculateTableCellAccessibilityBounds( row_index, visible_column_index)); } else { cell_data.relative_bounds.bounds = gfx::RectF(); } } } } gfx::Rect TableView::CalculateHeaderRowAccessibilityBounds() const { gfx::Rect header_bounds = header_->GetVisibleBounds(); gfx::Point header_origin = header_bounds.origin(); ConvertPointToTarget(header_, this, &header_origin); header_bounds.set_origin(header_origin); return header_bounds; } gfx::Rect TableView::CalculateHeaderCellAccessibilityBounds( const size_t visible_column_index) const { const gfx::Rect& header_bounds = CalculateHeaderRowAccessibilityBounds(); const VisibleColumn& visible_column = visible_columns_[visible_column_index]; gfx::Rect header_cell_bounds(visible_column.x, header_bounds.y(), visible_column.width, header_bounds.height()); return header_cell_bounds; } gfx::Rect TableView::CalculateTableRowAccessibilityBounds( const size_t row_index) const { gfx::Rect row_bounds = GetRowBounds(row_index); return row_bounds; } gfx::Rect TableView::CalculateTableCellAccessibilityBounds( const size_t row_index, const size_t visible_column_index) const { gfx::Rect cell_bounds = GetCellBounds(row_index, visible_column_index); return cell_bounds; } void TableView::ScheduleUpdateAccessibilityFocusIfNeeded() { if (update_accessibility_focus_pending_) return; update_accessibility_focus_pending_ = true; base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&TableView::UpdateAccessibilityFocus, weak_factory_.GetWeakPtr(), UpdateAccessibilityFocusPassKey())); } void TableView::UpdateAccessibilityFocus( UpdateAccessibilityFocusPassKey pass_key) { DCHECK(update_accessibility_focus_pending_); update_accessibility_focus_pending_ = false; if (!HasFocus()) return; if (header_ && header_row_is_active_) { AXVirtualView* ax_header_row = GetVirtualAccessibilityHeaderRow(); if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell || !active_visible_column_index_.has_value()) { if (ax_header_row) { ax_header_row->NotifyAccessibilityEvent(ax::mojom::Event::kSelection); GetViewAccessibility().OverrideFocus(ax_header_row); } } else { AXVirtualView* ax_header_cell = GetVirtualAccessibilityCellImpl( ax_header_row, active_visible_column_index_.value()); if (ax_header_cell) { ax_header_cell->NotifyAccessibilityEvent(ax::mojom::Event::kSelection); GetViewAccessibility().OverrideFocus(ax_header_cell); } } return; } if (!selection_model_.active().has_value() || !active_visible_column_index_.has_value()) { GetViewAccessibility().OverrideFocus(nullptr); return; } size_t active_row = ModelToView(selection_model_.active().value()); AXVirtualView* ax_row = GetVirtualAccessibilityBodyRow(active_row); if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) { if (ax_row) { ax_row->NotifyAccessibilityEvent(ax::mojom::Event::kSelection); GetViewAccessibility().OverrideFocus(ax_row); } } else { AXVirtualView* ax_cell = GetVirtualAccessibilityCellImpl( ax_row, active_visible_column_index_.value()); if (ax_cell) { ax_cell->NotifyAccessibilityEvent(ax::mojom::Event::kSelection); GetViewAccessibility().OverrideFocus(ax_cell); } } } AXVirtualView* TableView::GetVirtualAccessibilityBodyRow(size_t row) { DCHECK_LT(row, GetRowCount()); if (header_) ++row; CHECK_LT(row, GetViewAccessibility().virtual_children().size()) << "|row| not found. Did you forget to call " "RebuildVirtualAccessibilityChildren()?"; const auto& ax_row = GetViewAccessibility().virtual_children()[row]; DCHECK(ax_row); DCHECK_EQ(ax_row->GetData().role, ax::mojom::Role::kRow); return ax_row.get(); } AXVirtualView* TableView::GetVirtualAccessibilityHeaderRow() { CHECK(header_) << "|row| not found. Did you forget to call " "RebuildVirtualAccessibilityChildren()?"; // The header row is always the first virtual child. const auto& ax_row = GetViewAccessibility().virtual_children()[size_t{0}]; DCHECK(ax_row); DCHECK_EQ(ax_row->GetData().role, ax::mojom::Role::kRow); return ax_row.get(); } AXVirtualView* TableView::GetVirtualAccessibilityCell( size_t row, size_t visible_column_index) { return GetVirtualAccessibilityCellImpl(GetVirtualAccessibilityBodyRow(row), visible_column_index); } AXVirtualView* TableView::GetVirtualAccessibilityCellImpl( AXVirtualView* ax_row, size_t visible_column_index) { DCHECK(ax_row) << "|row| not found. Did you forget to call " "RebuildVirtualAccessibilityChildren()?"; const auto matches_index = [visible_column_index](const auto& ax_cell) { DCHECK(ax_cell); DCHECK(ax_cell->GetData().role == ax::mojom::Role::kColumnHeader || ax_cell->GetData().role == ax::mojom::Role::kCell); return base::checked_cast<size_t>(ax_cell->GetData().GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex)) == visible_column_index; }; const auto i = base::ranges::find_if(ax_row->children(), matches_index); DCHECK(i != ax_row->children().cend()) << "|visible_column_index| not found. Did you forget to call " << "RebuildVirtualAccessibilityChildren()?"; return i->get(); } BEGIN_METADATA(TableView, View) ADD_READONLY_PROPERTY_METADATA(size_t, RowCount) ADD_READONLY_PROPERTY_METADATA(absl::optional<size_t>, FirstSelectedRow) ADD_READONLY_PROPERTY_METADATA(bool, HasFocusIndicator) ADD_PROPERTY_METADATA(absl::optional<size_t>, ActiveVisibleColumnIndex) ADD_READONLY_PROPERTY_METADATA(bool, IsSorted) ADD_PROPERTY_METADATA(TableViewObserver*, Observer) ADD_READONLY_PROPERTY_METADATA(int, RowHeight) ADD_PROPERTY_METADATA(bool, SingleSelection) ADD_PROPERTY_METADATA(bool, SelectOnRemove) ADD_PROPERTY_METADATA(TableTypes, TableType) ADD_PROPERTY_METADATA(bool, SortOnPaint) END_METADATA } // namespace views DEFINE_ENUM_CONVERTERS(views::TableTypes, {views::TableTypes::TEXT_ONLY, u"TEXT_ONLY"}, {views::TableTypes::ICON_AND_TEXT, u"ICON_AND_TEXT"})
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_view.cc
C++
unknown
68,811
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_H_ #define UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_H_ #include <memory> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "ui/base/models/list_selection_model.h" #include "ui/base/models/table_model.h" #include "ui/base/models/table_model_observer.h" #include "ui/gfx/font_list.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace ui { struct AXActionData; struct AXNodeData; } // namespace ui // A TableView is a view that displays multiple rows with any number of columns. // TableView is driven by a TableModel. The model returns the contents // to display. TableModel also has an Observer which is used to notify // TableView of changes to the model so that the display may be updated // appropriately. // // TableView itself has an observer that is notified when the selection // changes. // // When a table is sorted the model coordinates do not necessarily match the // view coordinates. All table methods are in terms of the model. If you need to // convert to view coordinates use ModelToView(). // // Sorting is done by a locale sensitive string sort. You can customize the // sort by way of overriding TableModel::CompareValues(). namespace views { class AXVirtualView; struct GroupRange; class ScrollView; class TableGrouper; class TableHeader; class TableViewObserver; class TableViewTestHelper; // The cell's in the first column of a table can contain: // - only text // - a small icon (16x16) and some text // - a check box and some text enum TableTypes { TEXT_ONLY = 0, ICON_AND_TEXT, }; class VIEWS_EXPORT TableView : public views::View, public ui::TableModelObserver { public: METADATA_HEADER(TableView); // Used by AdvanceActiveVisibleColumn(), AdvanceSelection() and // ResizeColumnViaKeyboard() to determine the direction to change the // selection. enum class AdvanceDirection { kDecrement, kIncrement, }; // Used to track a visible column. Useful only for the header. struct VIEWS_EXPORT VisibleColumn { VisibleColumn(); ~VisibleColumn(); // The column. ui::TableColumn column; // Starting x-coordinate of the column. int x = 0; // Width of the column. int width = 0; }; // Describes a sorted column. struct VIEWS_EXPORT SortDescriptor { SortDescriptor() = default; SortDescriptor(int column_id, bool ascending) : column_id(column_id), ascending(ascending) {} // ID of the sorted column. int column_id = -1; // Is the sort ascending? bool ascending = true; }; using SortDescriptors = std::vector<SortDescriptor>; // Creates a new table using the model and columns specified. // The table type applies to the content of the first column (text, icon and // text, checkbox and text). TableView(); TableView(ui::TableModel* model, const std::vector<ui::TableColumn>& columns, TableTypes table_type, bool single_selection); TableView(const TableView&) = delete; TableView& operator=(const TableView&) = delete; ~TableView() override; // Returns a new ScrollView that contains the given |table|. static std::unique_ptr<ScrollView> CreateScrollViewWithTable( std::unique_ptr<TableView> table); // Returns a new Builder<ScrollView> that contains the |table| constructed // from the given Builder<TableView>. static Builder<ScrollView> CreateScrollViewBuilderWithTable( Builder<TableView>&& table); // Initialize the table with the appropriate data. void Init(ui::TableModel* model, const std::vector<ui::TableColumn>& columns, TableTypes table_type, bool single_selection); // Assigns a new model to the table view, detaching the old one if present. // If |model| is NULL, the table view cannot be used after this call. This // should be called in the containing view's destructor to avoid destruction // issues when the model needs to be deleted before the table. void SetModel(ui::TableModel* model); ui::TableModel* model() const { return model_; } void SetColumns(const std::vector<ui::TableColumn>& columns); void SetTableType(TableTypes table_type); TableTypes GetTableType() const; void SetSingleSelection(bool single_selection); bool GetSingleSelection() const; // Sets the TableGrouper. TableView does not own |grouper| (common use case is // to have TableModel implement TableGrouper). void SetGrouper(TableGrouper* grouper); // Returns the number of rows in the TableView. size_t GetRowCount() const; // Selects the specified item, making sure it's visible. void Select(absl::optional<size_t> model_row); // Selects all items. void SetSelectionAll(bool select); // Returns the first selected row in terms of the model. absl::optional<size_t> GetFirstSelectedRow() const; const ui::ListSelectionModel& selection_model() const { return selection_model_; } // Changes the visibility of the specified column (by id). void SetColumnVisibility(int id, bool is_visible); bool IsColumnVisible(int id) const; // Returns true if the column with the specified id is known (either visible // or not). bool HasColumn(int id) const; // Returns whether an active row and column have been set. bool GetHasFocusIndicator() const; // These functions are deprecated. Favor calling the equivalent functions // below. void set_observer(TableViewObserver* observer) { observer_ = observer; } TableViewObserver* observer() const { return observer_; } // The following are equivalent to the above, but are named for compatibility // with metadata properties and view builder. void SetObserver(TableViewObserver* observer); TableViewObserver* GetObserver() const; absl::optional<size_t> GetActiveVisibleColumnIndex() const; void SetActiveVisibleColumnIndex(absl::optional<size_t> index); const std::vector<VisibleColumn>& visible_columns() const { return visible_columns_; } const VisibleColumn& GetVisibleColumn(size_t index); // Sets the width of the column. |index| is in terms of |visible_columns_|. void SetVisibleColumnWidth(size_t index, int width); // Modify the table sort order, depending on a clicked column and the previous // table sort order. Does nothing if this column is not sortable. // // When called repeatedly on the same sortable column, the sort order will // cycle through three states in order: sorted -> reverse-sorted -> unsorted. // When switching from one sort column to another, the previous sort column // will be remembered and used as a secondary sort key. void ToggleSortOrder(size_t visible_column_index); const SortDescriptors& sort_descriptors() const { return sort_descriptors_; } void SetSortDescriptors(const SortDescriptors& descriptors); bool GetIsSorted() const { return !sort_descriptors_.empty(); } // Maps from the index in terms of the model to that of the view. size_t ModelToView(size_t model_index) const; // Maps from the index in terms of the view to that of the model. size_t ViewToModel(size_t view_index) const; int GetRowHeight() const { return row_height_; } bool GetSelectOnRemove() const; void SetSelectOnRemove(bool select_on_remove); // WARNING: this function forces a sort on every paint, and is therefore // expensive! It assumes you are calling SchedulePaint() at intervals for // the whole table. If your model is properly notifying the table, this is // not needed. This is only used in th extremely rare case, where between the // time the SchedulePaint() is called and the paint is processed, the // underlying data may change. Also, this only works if the number of rows // remains the same. bool GetSortOnPaint() const; void SetSortOnPaint(bool sort_on_paint); // Returns the proper ax sort direction. ax::mojom::SortDirection GetFirstSortDescriptorDirection() const; // Updates the relative bounds of the virtual accessibility children created // in RebuildVirtualAccessibilityChildren(). This function is public so that // the table's |header_| can trigger an update when its visible bounds are // changed, because its accessibility information is also contained in the // table's virtual accessibility children. void UpdateVirtualAccessibilityChildrenBounds(); // Returns the virtual accessibility view corresponding to the specified cell. // |row| should be a view index, not a model index. // |visible_column_index| indexes into |visible_columns_|. AXVirtualView* GetVirtualAccessibilityCell(size_t row, size_t visible_column_index); bool header_row_is_active() const { return header_row_is_active_; } // View overrides: void Layout() override; gfx::Size CalculatePreferredSize() const override; bool GetNeedsNotificationWhenVisibleBoundsChange() const override; void OnVisibleBoundsChanged() override; bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; std::u16string GetTooltipText(const gfx::Point& p) const override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; // ui::TableModelObserver overrides: void OnModelChanged() override; void OnItemsChanged(size_t start, size_t length) override; void OnItemsAdded(size_t start, size_t length) override; void OnItemsRemoved(size_t start, size_t length) override; void OnItemsMoved(size_t old_start, size_t length, size_t new_start) override; protected: // View overrides: gfx::Point GetKeyboardContextMenuLocation() override; void OnFocus() override; void OnBlur() override; void OnPaint(gfx::Canvas* canvas) override; private: friend class TableViewTestHelper; class HighlightPathGenerator; struct GroupSortHelper; struct SortHelper; // Used during painting to determine the range of cell's that need to be // painted. // NOTE: the row indices returned by this are in terms of the view and column // indices in terms of |visible_columns_|. struct VIEWS_EXPORT PaintRegion { PaintRegion(); ~PaintRegion(); size_t min_row = 0; size_t max_row = 0; size_t min_column = 0; size_t max_column = 0; }; void OnPaintImpl(gfx::Canvas* canvas); // Returns the horizontal margin between the bounds of a cell and its // contents. int GetCellMargin() const; // Returns the horizontal spacing between elements (grouper, icon, and text) // in a cell. int GetCellElementSpacing() const; // Does the actual sort and updates the mappings (|view_to_model_| and // |model_to_view_|) appropriately. If |schedule_paint| is true, // schedules a paint. This should be true, unless called from // OnPaint. void SortItemsAndUpdateMapping(bool schedule_paint); // Used to sort the two rows. Returns a value < 0, == 0 or > 0 indicating // whether the row2 comes before row1, row2 is the same as row1 or row1 comes // after row2. This invokes CompareValues on the model with the sorted column. int CompareRows(size_t model_row1, size_t model_row2); // Returns the bounds of the specified row. gfx::Rect GetRowBounds(size_t row) const; // Returns the bounds of the specified cell. |visible_column_index| indexes // into |visible_columns_|. gfx::Rect GetCellBounds(size_t row, size_t visible_column_index) const; // Returns the bounds of the active cell. gfx::Rect GetActiveCellBounds() const; // Adjusts |bounds| based on where the text should be painted. |bounds| comes // from GetCellBounds() and |visible_column_index| is the corresponding column // (in terms of |visible_columns_|). void AdjustCellBoundsForText(size_t visible_column_index, gfx::Rect* bounds) const; // Creates |header_| if necessary. void CreateHeaderIfNecessary(ScrollView* scroll_view); // Updates the |x| and |width| of each of the columns in |visible_columns_|. void UpdateVisibleColumnSizes(); // Returns the cell's that need to be painted for the specified region. // |bounds| is in terms of |this|. PaintRegion GetPaintRegion(const gfx::Rect& bounds) const; // Returns the bounds that need to be painted based on the clip set on // |canvas|. gfx::Rect GetPaintBounds(gfx::Canvas* canvas) const; // Invokes SchedulePaint() for the selected rows. void SchedulePaintForSelection(); // Returns the TableColumn matching the specified id. ui::TableColumn FindColumnByID(int id) const; // Advances the active visible column (from the active visible column index) // in the specified direction. void AdvanceActiveVisibleColumn(AdvanceDirection direction); // Sets the selection to the specified index (in terms of the view). void SelectByViewIndex(absl::optional<size_t> view_index); // Sets the selection model to |new_selection|. void SetSelectionModel(ui::ListSelectionModel new_selection); // Advances the selection (from the active index) in the specified direction. void AdvanceSelection(AdvanceDirection direction); // Sets |model| appropriately based on a event. void ConfigureSelectionModelForEvent(const ui::LocatedEvent& event, ui::ListSelectionModel* model) const; // Set the selection state of row at |view_index| to |select|, additionally // any other rows in the GroupRange containing |view_index| are updated as // well. This does not change the anchor or active index of |model|. void SelectRowsInRangeFrom(size_t view_index, bool select, ui::ListSelectionModel* model) const; // Returns the range of the specified model index. If a TableGrouper has not // been set this returns a group with a start of |model_index| and length of // 1. GroupRange GetGroupRange(size_t model_index) const; // Updates a set of accessibility views that expose the visible table contents // to assistive software. void RebuildVirtualAccessibilityChildren(); // Clears the set of accessibility views set up in // RebuildVirtualAccessibilityChildren(). Useful when the model is in the // process of changing but the virtual accessibility children haven't been // updated yet, e.g. showing or hiding a column via SetColumnVisibility(). void ClearVirtualAccessibilityChildren(); // Helper functions used in UpdateVirtualAccessibilityChildrenBounds() for // calculating the accessibility bounds for the header and table rows and // cell's. gfx::Rect CalculateHeaderRowAccessibilityBounds() const; gfx::Rect CalculateHeaderCellAccessibilityBounds( const size_t visible_column_index) const; gfx::Rect CalculateTableRowAccessibilityBounds(const size_t row_index) const; gfx::Rect CalculateTableCellAccessibilityBounds( const size_t row_index, const size_t visible_column_index) const; // Schedule a future call UpdateAccessibilityFocus if not already pending. void ScheduleUpdateAccessibilityFocusIfNeeded(); // A PassKey so that no other code can call UpdateAccessibilityFocus // directly, only ScheduleUpdateAccessibilityFocusIfNeeded. class UpdateAccessibilityFocusPassKey { public: ~UpdateAccessibilityFocusPassKey() = default; private: friend void TableView::ScheduleUpdateAccessibilityFocusIfNeeded(); // Avoid =default to disallow creation by uniform initialization. UpdateAccessibilityFocusPassKey() {} // NOLINT }; // Updates the internal accessibility state and fires the required // accessibility events to indicate to assistive software which row is active // and which cell is focused, if any. Don't call this directly; call // ScheduleUpdateAccessibilityFocusIfNeeded to ensure that only one call // is made and that it happens after all changes have been made. void UpdateAccessibilityFocus(UpdateAccessibilityFocusPassKey pass_key); // Returns the virtual accessibility view corresponding to the specified row. // |row| should be a view index into the TableView's body elements, not a // model index. AXVirtualView* GetVirtualAccessibilityBodyRow(size_t row); // Returns the virtual accessibility view corresponding to the header row, if // it exists. AXVirtualView* GetVirtualAccessibilityHeaderRow(); // Returns the virtual accessibility view corresponding to the cell in the // given row at the specified column index. // `ax_row` should be the virtual view of either a header or body row. // `visible_column_index` indexes into `visible_columns_`. AXVirtualView* GetVirtualAccessibilityCellImpl(AXVirtualView* ax_row, size_t visible_column_index); // Creates a virtual accessibility view that is used to expose information // about the row at |view_index| to assistive software. std::unique_ptr<AXVirtualView> CreateRowAccessibilityView(size_t view_index); // Creates a virtual accessibility view that is used to expose information // about the cell at the provided coordinates |row_index| and |column_index| // to assistive software. std::unique_ptr<AXVirtualView> CreateCellAccessibilityView( size_t row_index, size_t column_index); // Creates a virtual accessibility view that is used to expose information // about this header to assistive software. std::unique_ptr<AXVirtualView> CreateHeaderAccessibilityView(); // Updates the accessibility data for |ax_row| to match the data in the view // at |view_index| in the table. Returns false if row data not changed. bool UpdateVirtualAccessibilityRowData(AXVirtualView* ax_row, int view_index, int model_index); // The accessibility view |ax_row| callback function that populates the // accessibility data for a table row. void PopulateAccessibilityRowData(AXVirtualView* ax_row, ui::AXNodeData* data); // The accessibility view |ax_cell| callback function that populates the // accessibility data for a table cell. void PopulateAccessibilityCellData(AXVirtualView* ax_cell, ui::AXNodeData* data); // Updates the focus rings of the TableView and the TableHeader if necessary. void UpdateFocusRings(); raw_ptr<ui::TableModel> model_ = nullptr; std::vector<ui::TableColumn> columns_; // The set of visible columns. The values of these point to |columns_|. This // may contain a subset of |columns_|. std::vector<VisibleColumn> visible_columns_; // The active visible column. Used for keyboard access to functionality such // as sorting and resizing. nullopt if no visible column is active. absl::optional<size_t> active_visible_column_index_ = absl::nullopt; // The header. This is only created if more than one column is specified or // the first column has a non-empty title. raw_ptr<TableHeader> header_ = nullptr; // TableView allows using the keyboard to activate a cell or row, including // optionally the header row. This bool keeps track of whether the active row // is the header row, since the selection model doesn't support that. bool header_row_is_active_ = false; TableTypes table_type_ = TableTypes::TEXT_ONLY; bool single_selection_ = true; // If |select_on_remove_| is true: when a selected item is removed, if the // removed item is not the last item, select its next one; otherwise select // its previous one if there is an item. // If |select_on_remove_| is false: when a selected item is removed, no item // is selected then. bool select_on_remove_ = true; raw_ptr<TableViewObserver, DanglingUntriaged> observer_ = nullptr; // If |sort_on_paint_| is true, table will sort before painting. bool sort_on_paint_ = false; // The selection, in terms of the model. ui::ListSelectionModel selection_model_; gfx::FontList font_list_; int row_height_; // Width of the ScrollView last time Layout() was invoked. Used to determine // when we should invoke UpdateVisibleColumnSizes(). int last_parent_width_ = 0; // The width we layout to. This may differ from |last_parent_width_|. int layout_width_ = 0; // Current sort. SortDescriptors sort_descriptors_; // Mappings used when sorted. std::vector<size_t> view_to_model_; std::vector<size_t> model_to_view_; raw_ptr<TableGrouper> grouper_ = nullptr; // True if in SetVisibleColumnWidth(). bool in_set_visible_column_width_ = false; // Keeps track whether a call to UpdateAccessibilityFocus is already // pending or not. bool update_accessibility_focus_pending_ = false; // Weak pointer factory, enables using PostTask safely. base::WeakPtrFactory<TableView> weak_factory_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, TableView, View) VIEW_BUILDER_PROPERTY(absl::optional<size_t>, ActiveVisibleColumnIndex) VIEW_BUILDER_PROPERTY(const std::vector<ui::TableColumn>&, Columns, std::vector<ui::TableColumn>) VIEW_BUILDER_PROPERTY(ui::TableModel*, Model) VIEW_BUILDER_PROPERTY(TableTypes, TableType) VIEW_BUILDER_PROPERTY(bool, SingleSelection) VIEW_BUILDER_PROPERTY(TableGrouper*, Grouper) VIEW_BUILDER_PROPERTY(TableViewObserver*, Observer) VIEW_BUILDER_PROPERTY(bool, SelectOnRemove) VIEW_BUILDER_PROPERTY(bool, SortOnPaint) VIEW_BUILDER_METHOD(SetColumnVisibility, int, bool) VIEW_BUILDER_METHOD(SetVisibleColumnWidth, int, int) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, views::TableView) #endif // UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_view.h
C++
unknown
22,004
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_ #define UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_ #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/views_export.h" namespace views { // TableViewObserver is notified about the TableView selection. class VIEWS_EXPORT TableViewObserver { public: virtual ~TableViewObserver() = default; // Invoked when the selection changes. virtual void OnSelectionChanged() = 0; // Optional method invoked when the user double clicks on the table. virtual void OnDoubleClick() {} // Optional method invoked when the user middle clicks on the table. virtual void OnMiddleClick() {} // Optional method invoked when the user hits a key with the table in focus. virtual void OnKeyDown(ui::KeyboardCode virtual_keycode) {} }; } // namespace views #endif // UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_view_observer.h
C++
unknown
1,033
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/table_view.h" #include <stddef.h> #include <algorithm> #include <string> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/events/event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/gfx/text_utils.h" #include "ui/views/accessibility/ax_virtual_view.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/table/table_grouper.h" #include "ui/views/controls/table/table_header.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/focus_manager_test.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/views_test_utils.h" #include "ui/views/widget/unique_widget_ptr.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_utils.h" // Put the tests in the views namespace to make it easier to declare them as // friend classes. namespace views { class TableViewTestHelper { public: explicit TableViewTestHelper(TableView* table) : table_(table) {} TableViewTestHelper(const TableViewTestHelper&) = delete; TableViewTestHelper& operator=(const TableViewTestHelper&) = delete; std::string GetPaintRegion(const gfx::Rect& bounds) { TableView::PaintRegion region(table_->GetPaintRegion(bounds)); return "rows=" + base::NumberToString(region.min_row) + " " + base::NumberToString(region.max_row) + " cols=" + base::NumberToString(region.min_column) + " " + base::NumberToString(region.max_column); } size_t visible_col_count() { return table_->visible_columns().size(); } absl::optional<size_t> GetActiveVisibleColumnIndex() { return table_->GetActiveVisibleColumnIndex(); } TableHeader* header() { return table_->header_; } void SetSelectionModel(const ui::ListSelectionModel& new_selection) { table_->SetSelectionModel(new_selection); } const gfx::FontList& font_list() { return table_->font_list_; } AXVirtualView* GetVirtualAccessibilityBodyRow(size_t row) { return table_->GetVirtualAccessibilityBodyRow(row); } AXVirtualView* GetVirtualAccessibilityHeaderRow() { return table_->GetVirtualAccessibilityHeaderRow(); } AXVirtualView* GetVirtualAccessibilityHeaderCell( size_t visible_column_index) { return table_->GetVirtualAccessibilityCellImpl( GetVirtualAccessibilityHeaderRow(), visible_column_index); } AXVirtualView* GetVirtualAccessibilityCell(size_t row, size_t visible_column_index) { return table_->GetVirtualAccessibilityCell(row, visible_column_index); } gfx::Rect GetCellBounds(size_t row, size_t visible_column_index) const { return table_->GetCellBounds(row, visible_column_index); } gfx::Rect GetActiveCellBounds() const { return table_->GetActiveCellBounds(); } std::vector<std::vector<gfx::Rect>> GenerateExpectedBounds() { // Generates the expected bounds for |table_|'s rows and cells. Each vector // represents a row. The first entry in each child vector is the bounds for // the entire row. The following entries in that vector are the bounds for // each individual cell contained in that row. auto expected_bounds = std::vector<std::vector<gfx::Rect>>(); // Generate the bounds for the header row and cells. auto header_row = std::vector<gfx::Rect>(); gfx::Rect header_row_bounds = table_->CalculateHeaderRowAccessibilityBounds(); View::ConvertRectToScreen(table_, &header_row_bounds); header_row.push_back(header_row_bounds); for (size_t column_index = 0; column_index < visible_col_count(); column_index++) { gfx::Rect header_cell_bounds = table_->CalculateHeaderCellAccessibilityBounds(column_index); View::ConvertRectToScreen(table_, &header_cell_bounds); header_row.push_back(header_cell_bounds); } expected_bounds.push_back(header_row); // Generate the bounds for the table rows and cells. for (size_t row_index = 0; row_index < table_->GetRowCount(); row_index++) { auto table_row = std::vector<gfx::Rect>(); gfx::Rect table_row_bounds = table_->CalculateTableRowAccessibilityBounds(row_index); View::ConvertRectToScreen(table_, &table_row_bounds); table_row.push_back(table_row_bounds); for (size_t column_index = 0; column_index < visible_col_count(); column_index++) { gfx::Rect table_cell_bounds = table_->CalculateTableCellAccessibilityBounds(row_index, column_index); View::ConvertRectToScreen(table_, &table_cell_bounds); table_row.push_back(table_cell_bounds); } expected_bounds.push_back(table_row); } return expected_bounds; } private: raw_ptr<TableView> table_; }; namespace { #if BUILDFLAG(IS_MAC) constexpr int kCtrlOrCmdMask = ui::EF_COMMAND_DOWN; #else constexpr int kCtrlOrCmdMask = ui::EF_CONTROL_DOWN; #endif // TestTableModel2 ------------------------------------------------------------- // Trivial TableModel implementation that is backed by a vector of vectors. // Provides methods for adding/removing/changing the contents that notify the // observer appropriately. // // Initial contents are: // 0, 1 // 1, 1 // 2, 2 // 3, 0 class TestTableModel2 : public ui::TableModel { public: TestTableModel2(); TestTableModel2(const TestTableModel2&) = delete; TestTableModel2& operator=(const TestTableModel2&) = delete; // Adds a new row at index |row| with values |c1_value| and |c2_value|. void AddRow(size_t row, int c1_value, int c2_value); // Adds new rows starting from |row| to |row| + |length| with the value // of |row| times the |value_multiplier|. The |value_multiplier| can be used // to distinguish these rows from the rest. void AddRows(size_t row, size_t length, int value_multiplier); // Removes the row at index |row|. void RemoveRow(size_t row); // Removes all the rows starting from |row| to |row| + |length|. void RemoveRows(size_t row, size_t length); // Changes the values of the row at |row|. void ChangeRow(size_t row, int c1_value, int c2_value); // Reorders rows in the model. void MoveRows(size_t row_from, size_t length, size_t row_to); // Allows overriding the tooltip for testing. void SetTooltip(const std::u16string& tooltip); // ui::TableModel: size_t RowCount() override; std::u16string GetText(size_t row, int column_id) override; std::u16string GetTooltip(size_t row) override; void SetObserver(ui::TableModelObserver* observer) override; int CompareValues(size_t row1, size_t row2, int column_id) override; private: raw_ptr<ui::TableModelObserver> observer_ = nullptr; absl::optional<std::u16string> tooltip_; // The data. std::vector<std::vector<int>> rows_; }; TestTableModel2::TestTableModel2() { AddRow(0, 0, 1); AddRow(1, 1, 1); AddRow(2, 2, 2); AddRow(3, 3, 0); } void TestTableModel2::AddRow(size_t row, int c1_value, int c2_value) { DCHECK(row <= rows_.size()); std::vector<int> new_row; new_row.push_back(c1_value); new_row.push_back(c2_value); rows_.insert(rows_.begin() + row, new_row); if (observer_) observer_->OnItemsAdded(row, 1); } void TestTableModel2::AddRows(size_t row, size_t length, int value_multiplier) { // Do not DCHECK here since we are testing the OnItemsAdded callback. if (row <= rows_.size()) { for (size_t i = row; i < row + length; i++) { std::vector<int> new_row; new_row.push_back(static_cast<int>(i) + value_multiplier); new_row.push_back(static_cast<int>(i) + value_multiplier); rows_.insert(rows_.begin() + i, new_row); } } if (observer_ && length > 0) observer_->OnItemsAdded(row, length); } void TestTableModel2::RemoveRow(size_t row) { DCHECK(row < rows_.size()); rows_.erase(rows_.begin() + row); if (observer_) observer_->OnItemsRemoved(row, 1); } void TestTableModel2::RemoveRows(size_t row, size_t length) { if (row <= rows_.size()) { rows_.erase( rows_.begin() + row, rows_.begin() + std::clamp(row + length, size_t{0}, rows_.size())); } if (observer_ && length > 0) observer_->OnItemsRemoved(row, length); } void TestTableModel2::ChangeRow(size_t row, int c1_value, int c2_value) { DCHECK(row < rows_.size()); rows_[row][0] = c1_value; rows_[row][1] = c2_value; if (observer_) observer_->OnItemsChanged(row, 1); } void TestTableModel2::MoveRows(size_t row_from, size_t length, size_t row_to) { DCHECK_GT(length, 0u); DCHECK_LE(row_from + length, rows_.size()); DCHECK_LE(row_to + length, rows_.size()); auto old_start = rows_.begin() + row_from; std::vector<std::vector<int>> temp(old_start, old_start + length); rows_.erase(old_start, old_start + length); rows_.insert(rows_.begin() + row_to, temp.begin(), temp.end()); if (observer_) observer_->OnItemsMoved(row_from, length, row_to); } void TestTableModel2::SetTooltip(const std::u16string& tooltip) { tooltip_ = tooltip; } size_t TestTableModel2::RowCount() { return rows_.size(); } std::u16string TestTableModel2::GetText(size_t row, int column_id) { return base::NumberToString16(rows_[row][column_id]); } std::u16string TestTableModel2::GetTooltip(size_t row) { return tooltip_ ? *tooltip_ : u"Tooltip" + base::NumberToString16(row); } void TestTableModel2::SetObserver(ui::TableModelObserver* observer) { observer_ = observer; } int TestTableModel2::CompareValues(size_t row1, size_t row2, int column_id) { return rows_[row1][column_id] - rows_[row2][column_id]; } // Returns the view to model mapping as a string. std::string GetViewToModelAsString(TableView* table) { std::string result; for (size_t i = 0; i < table->GetRowCount(); ++i) { if (i != 0) result += " "; result += base::NumberToString(table->ViewToModel(i)); } return result; } // Returns the model to view mapping as a string. std::string GetModelToViewAsString(TableView* table) { std::string result; for (size_t i = 0; i < table->GetRowCount(); ++i) { if (i != 0) result += " "; result += base::NumberToString(table->ModelToView(i)); } return result; } // Formats the whole table as a string, like: "[a, b, c], [d, e, f]". Rows // scrolled out of view are included; hidden columns are excluded. std::string GetRowsInViewOrderAsString(TableView* table) { std::string result; for (size_t i = 0; i < table->GetRowCount(); ++i) { if (i != 0) result += ", "; // Comma between each row. // Format row |i| like this: "[value1, value2, value3]" result += "["; for (size_t j = 0; j < table->visible_columns().size(); ++j) { const ui::TableColumn& column = table->GetVisibleColumn(j).column; if (j != 0) result += ", "; // Comma between each value in the row. result += base::UTF16ToUTF8( table->model()->GetText(table->ViewToModel(i), column.id)); } result += "]"; } return result; } // Formats the whole accessibility views as a string. // Like: "[a, b, c], [d, e, f]". std::string GetRowsInVirtualViewAsString(TableView* table) { auto& virtual_children = table->GetViewAccessibility().virtual_children(); std::string result; for (size_t row_index = 0; row_index < virtual_children.size(); row_index++) { if (row_index != 0) result += ", "; // Comma between each row. const auto& row = virtual_children[row_index]; result += "["; for (size_t cell_index = 0; cell_index < row->children().size(); cell_index++) { if (cell_index != 0) result += ", "; // Comma between each value in the row. const auto& cell = row->children()[cell_index]; const ui::AXNodeData& cell_data = cell->GetData(); result += cell_data.GetStringAttribute(ax::mojom::StringAttribute::kName); } result += "]"; } return result; } std::string GetHeaderRowAsString(TableView* table) { std::string result = "["; for (size_t col_index = 0; col_index < table->visible_columns().size(); ++col_index) { if (col_index != 0) result += ", "; // Comma between each column. result += base::UTF16ToUTF8(table->GetVisibleColumn(col_index).column.title); } result += "]"; return result; } bool PressLeftMouseAt(views::View* target, const gfx::Point& point) { const ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); return target->OnMousePressed(pressed); } void ReleaseLeftMouseAt(views::View* target, const gfx::Point& point) { const ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); target->OnMouseReleased(release); } bool DragLeftMouseTo(views::View* target, const gfx::Point& point) { const ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); return target->OnMouseDragged(dragged); } } // namespace // The test parameter is used to control whether or not to test the TableView // using the default construction path. class TableViewTest : public ViewsTestBase, public ::testing::WithParamInterface<bool> { public: TableViewTest() = default; TableViewTest(const TableViewTest&) = delete; TableViewTest& operator=(const TableViewTest&) = delete; void SetUp() override { ViewsTestBase::SetUp(); model_ = std::make_unique<TestTableModel2>(); std::vector<ui::TableColumn> columns(2); columns[0].title = u"Title Column 0"; columns[0].sortable = true; columns[1].title = u"Title Column 1"; columns[1].id = 1; columns[1].sortable = true; std::unique_ptr<TableView> table; // Run the tests using both default and non-default TableView construction. if (GetParam()) { table = std::make_unique<TableView>(); table->Init(model_.get(), columns, TEXT_ONLY, false); } else { table = std::make_unique<TableView>(model_.get(), columns, TEXT_ONLY, false); } table_ = table.get(); auto scroll_view = TableView::CreateScrollViewWithTable(std::move(table)); scroll_view->SetBounds(0, 0, 10000, 10000); helper_ = std::make_unique<TableViewTestHelper>(table_); widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 650, 650); params.delegate = GetWidgetDelegate(widget_.get()); widget_->Init(std::move(params)); test::RunScheduledLayout( widget_->GetRootView()->AddChildView(std::move(scroll_view))); widget_->Show(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } void ClickOnRow(int row, int flags) { ui::test::EventGenerator generator(GetRootWindow(widget_.get())); generator.set_flags(flags); generator.set_current_screen_location(GetPointForRow(row)); generator.PressLeftButton(); } void TapOnRow(int row) { ui::test::EventGenerator generator(GetRootWindow(widget_.get())); generator.GestureTapAt(GetPointForRow(row)); } std::string SelectionStateAsString() const { return table_->selection_model().ToString(); } void PressKey(ui::KeyboardCode code) { PressKey(code, ui::EF_NONE); } void PressKey(ui::KeyboardCode code, int flags) { ui::test::EventGenerator generator(GetRootWindow(widget_.get())); generator.PressKey(code, flags); } void VerifyTableViewAndAXOrder(std::string expected_view_order) { VerifyAXRowIndexes(); // The table views should match the expected view order. EXPECT_EQ(expected_view_order, GetRowsInViewOrderAsString(table_)); // Update the expected view order to have header information if exists. if (helper_->header()) { expected_view_order = GetHeaderRowAsString(table_) + ", " + expected_view_order; } EXPECT_EQ(expected_view_order, GetRowsInVirtualViewAsString(table_)); } // Verifies that there is an unique, properly-indexed virtual row for every // row. void VerifyAXRowIndexes() { auto& virtual_children = table_->GetViewAccessibility().virtual_children(); // Makes sure the virtual row count factors in the presence of the header. const int first_row_index = helper_->header() ? 1 : 0; const int virtual_row_count = table_->GetRowCount() + first_row_index; EXPECT_EQ(virtual_row_count, static_cast<int>(virtual_children.size())); // Make sure every virtual row is valid. for (int index = first_row_index; index < virtual_row_count; index++) { const auto& row = virtual_children[index]; ASSERT_TRUE(row); // Normalize the row index to account for the presence of a header if // necessary. const int normalized_index = index - first_row_index; // Make sure the stored row index matches the row index in the table. const ui::AXNodeData& row_data = row->GetCustomData(); const int stored_index = row_data.GetIntAttribute(ax::mojom::IntAttribute::kTableRowIndex); EXPECT_EQ(stored_index, normalized_index); } } // Helper function for comparing the bounds of |table_|'s virtual // accessibility child rows and cells with a set of expected bounds. void VerifyTableAccChildrenBounds( const ViewAccessibility& view_accessibility, const std::vector<std::vector<gfx::Rect>>& expected_bounds) { auto& virtual_children = view_accessibility.virtual_children(); EXPECT_EQ(virtual_children.size(), expected_bounds.size()); EXPECT_EQ((size_t)(table_->GetRowCount()) + 1U, expected_bounds.size()); for (size_t row_index = 0; row_index < virtual_children.size(); row_index++) { const auto& row = virtual_children[row_index]; ASSERT_TRUE(row); const ui::AXNodeData& row_data = row->GetData(); EXPECT_EQ(ax::mojom::Role::kRow, row_data.role); ui::AXOffscreenResult offscreen_result = ui::AXOffscreenResult(); gfx::Rect row_custom_bounds = row->GetBoundsRect( ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kUnclipped, &offscreen_result); EXPECT_EQ(row_custom_bounds, expected_bounds[row_index][0]); EXPECT_EQ(row->children().size(), expected_bounds[row_index].size() - 1U); EXPECT_EQ(row->children().size(), helper_->visible_col_count()); for (size_t cell_index = 0; cell_index < row->children().size(); cell_index++) { const auto& cell = row->children()[cell_index]; ASSERT_TRUE(cell); const ui::AXNodeData& cell_data = cell->GetData(); if (row_index == 0) EXPECT_EQ(ax::mojom::Role::kColumnHeader, cell_data.role); else EXPECT_EQ(ax::mojom::Role::kCell, cell_data.role); // Add 1 to get the cell's index into |expected_bounds| since the first // entry is the row's bounds. const int expected_bounds_index = cell_index + 1; gfx::Rect cell_custom_bounds = cell->GetBoundsRect( ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kUnclipped, &offscreen_result); EXPECT_EQ(cell_custom_bounds, expected_bounds[row_index][expected_bounds_index]); } } } protected: virtual WidgetDelegate* GetWidgetDelegate(Widget* widget) { return nullptr; } std::unique_ptr<TestTableModel2> model_; // Owned by |parent_|. raw_ptr<TableView> table_ = nullptr; std::unique_ptr<TableViewTestHelper> helper_; UniqueWidgetPtr widget_; private: gfx::Point GetPointForRow(int row) { const int y = (row + 0.5) * table_->GetRowHeight(); return table_->GetBoundsInScreen().origin() + gfx::Vector2d(5, y); } }; INSTANTIATE_TEST_SUITE_P(All, TableViewTest, testing::Values(false, true)); // Verifies GetPaintRegion. TEST_P(TableViewTest, GetPaintRegion) { // Two columns should be visible. EXPECT_EQ(2u, helper_->visible_col_count()); EXPECT_EQ("rows=0 4 cols=0 2", helper_->GetPaintRegion(table_->bounds())); EXPECT_EQ("rows=0 4 cols=0 1", helper_->GetPaintRegion(gfx::Rect(0, 0, 1, table_->height()))); } TEST_P(TableViewTest, RebuildVirtualAccessibilityChildren) { const ViewAccessibility& view_accessibility = table_->GetViewAccessibility(); ui::AXNodeData data; view_accessibility.GetAccessibleNodeData(&data); EXPECT_EQ(ax::mojom::Role::kListGrid, data.role); EXPECT_TRUE(data.HasState(ax::mojom::State::kFocusable)); EXPECT_EQ(ax::mojom::Restriction::kReadOnly, data.GetRestriction()); EXPECT_EQ(table_->GetRowCount(), static_cast<size_t>( data.GetIntAttribute(ax::mojom::IntAttribute::kTableRowCount))); EXPECT_EQ(helper_->visible_col_count(), static_cast<size_t>(data.GetIntAttribute( ax::mojom::IntAttribute::kTableColumnCount))); // The header takes up another row. ASSERT_EQ(static_cast<size_t>(table_->GetRowCount() + 1), view_accessibility.virtual_children().size()); const auto& header = view_accessibility.virtual_children().front(); ASSERT_TRUE(header); EXPECT_EQ(ax::mojom::Role::kRow, header->GetData().role); ASSERT_EQ(helper_->visible_col_count(), header->children().size()); int j = 0; for (const auto& header_cell : header->children()) { ASSERT_TRUE(header_cell); const ui::AXNodeData& header_cell_data = header_cell->GetData(); EXPECT_EQ(ax::mojom::Role::kColumnHeader, header_cell_data.role); EXPECT_EQ(j++, header_cell_data.GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex)); } size_t i = 0; for (auto child_iter = view_accessibility.virtual_children().begin() + 1; i < table_->GetRowCount(); ++child_iter, ++i) { const auto& row = *child_iter; ASSERT_TRUE(row); const ui::AXNodeData& row_data = row->GetData(); EXPECT_EQ(ax::mojom::Role::kRow, row_data.role); EXPECT_EQ(i, static_cast<size_t>(row_data.GetIntAttribute( ax::mojom::IntAttribute::kTableRowIndex))); ASSERT_FALSE(row_data.HasState(ax::mojom::State::kInvisible)); ASSERT_EQ(helper_->visible_col_count(), row->children().size()); j = 0; for (const auto& cell : row->children()) { ASSERT_TRUE(cell); const ui::AXNodeData& cell_data = cell->GetData(); EXPECT_EQ(ax::mojom::Role::kCell, cell_data.role); EXPECT_EQ(i, static_cast<size_t>(cell_data.GetIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex))); EXPECT_EQ(j++, cell_data.GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex)); ASSERT_FALSE(cell_data.HasState(ax::mojom::State::kInvisible)); } } } // Verifies the bounding rect of each virtual accessibility child of the // TableView (rows and cells) is updated appropriately as the table changes. For // example, verifies that if a column is resized or hidden, the bounds are // updated. TEST_P(TableViewTest, UpdateVirtualAccessibilityChildrenBounds) { // Verify the bounds are updated correctly when the TableView and its widget // have been shown. Initially some widths would be 0 until the TableView's // bounds are fully set up, so make sure the virtual children bounds have been // updated and now match the expected bounds. auto expected_bounds = helper_->GenerateExpectedBounds(); VerifyTableAccChildrenBounds(table_->GetViewAccessibility(), expected_bounds); } TEST_P(TableViewTest, UpdateVirtualAccessibilityChildrenBoundsWithResize) { // Resize the first column 10 pixels smaller and check the bounds are updated. int x = table_->GetVisibleColumn(0).width; PressLeftMouseAt(helper_->header(), gfx::Point(x, 0)); DragLeftMouseTo(helper_->header(), gfx::Point(x - 10, 0)); auto expected_bounds_after_resize = helper_->GenerateExpectedBounds(); VerifyTableAccChildrenBounds(table_->GetViewAccessibility(), expected_bounds_after_resize); } TEST_P(TableViewTest, UpdateVirtualAccessibilityChildrenBoundsHideColumn) { // Hide 1 column and check the bounds are updated. table_->SetColumnVisibility(1, false); auto expected_bounds_after_hiding = helper_->GenerateExpectedBounds(); VerifyTableAccChildrenBounds(table_->GetViewAccessibility(), expected_bounds_after_hiding); } TEST_P(TableViewTest, GetVirtualAccessibilityBodyRow) { for (size_t i = 0; i < table_->GetRowCount(); ++i) { const AXVirtualView* row = helper_->GetVirtualAccessibilityBodyRow(i); ASSERT_TRUE(row); const ui::AXNodeData& row_data = row->GetData(); EXPECT_EQ(ax::mojom::Role::kRow, row_data.role); EXPECT_EQ(i, static_cast<size_t>(row_data.GetIntAttribute( ax::mojom::IntAttribute::kTableRowIndex))); } } TEST_P(TableViewTest, GetVirtualAccessibilityCell) { for (size_t i = 0; i < table_->GetRowCount(); ++i) { for (size_t j = 0; j < helper_->visible_col_count(); ++j) { const AXVirtualView* cell = helper_->GetVirtualAccessibilityCell(i, j); ASSERT_TRUE(cell); const ui::AXNodeData& cell_data = cell->GetData(); EXPECT_EQ(ax::mojom::Role::kCell, cell_data.role); EXPECT_EQ(i, static_cast<size_t>(cell_data.GetIntAttribute( ax::mojom::IntAttribute::kTableCellRowIndex))); EXPECT_EQ(j, static_cast<size_t>(cell_data.GetIntAttribute( ax::mojom::IntAttribute::kTableCellColumnIndex))); } } } TEST_P(TableViewTest, ChangingCellFiresAccessibilityEvent) { int text_changed_count = 0; table_->GetViewAccessibility().set_accessibility_events_callback( base::BindLambdaForTesting( [&](const ui::AXPlatformNodeDelegate*, const ax::mojom::Event event) { if (event == ax::mojom::Event::kTextChanged) ++text_changed_count; })); // A kTextChanged event is fired when a cell's data is accessed and // its computed accessible text isn't the same as the previously cached // value. Ensure that the cached value is correctly updated so that // retrieving the data multiple times doesn't result in firing additional // kTextChanged events. const AXVirtualView* cell = helper_->GetVirtualAccessibilityCell(0, 0); ASSERT_TRUE(cell); ui::AXNodeData cell_data; for (int i = 0; i < 100; ++i) cell_data = cell->GetData(); EXPECT_EQ(1, text_changed_count); } // Verifies SetColumnVisibility(). TEST_P(TableViewTest, ColumnVisibility) { // Two columns should be visible. EXPECT_EQ(2u, helper_->visible_col_count()); // Should do nothing (column already visible). table_->SetColumnVisibility(0, true); EXPECT_EQ(2u, helper_->visible_col_count()); // Hide the first column. table_->SetColumnVisibility(0, false); ASSERT_EQ(1u, helper_->visible_col_count()); EXPECT_EQ(1, table_->GetVisibleColumn(0).column.id); EXPECT_EQ("rows=0 4 cols=0 1", helper_->GetPaintRegion(table_->bounds())); // Hide the second column. table_->SetColumnVisibility(1, false); EXPECT_EQ(0u, helper_->visible_col_count()); // Show the second column. table_->SetColumnVisibility(1, true); ASSERT_EQ(1u, helper_->visible_col_count()); EXPECT_EQ(1, table_->GetVisibleColumn(0).column.id); EXPECT_EQ("rows=0 4 cols=0 1", helper_->GetPaintRegion(table_->bounds())); // Show the first column. table_->SetColumnVisibility(0, true); ASSERT_EQ(2u, helper_->visible_col_count()); EXPECT_EQ(1, table_->GetVisibleColumn(0).column.id); EXPECT_EQ(0, table_->GetVisibleColumn(1).column.id); EXPECT_EQ("rows=0 4 cols=0 2", helper_->GetPaintRegion(table_->bounds())); } // Regression tests for https://crbug.com/1283805, and // https://crbug.com/1283807. TEST_P(TableViewTest, NoCrashesWithAllColumnsHidden) { // Set both initially visible columns hidden. table_->SetColumnVisibility(0, false); table_->SetColumnVisibility(1, false); EXPECT_EQ(0u, helper_->visible_col_count()); // Remove and add rows in this state, there should be no crashes. model_->RemoveRow(0); model_->AddRows(1, 2, /*value_multiplier=*/10); } // Verifies resizing a column using the mouse works. TEST_P(TableViewTest, Resize) { const int x = table_->GetVisibleColumn(0).width; EXPECT_NE(0, x); // Drag the mouse 1 pixel to the left. PressLeftMouseAt(helper_->header(), gfx::Point(x, 0)); DragLeftMouseTo(helper_->header(), gfx::Point(x - 1, 0)); // This should shrink the first column and pull the second column in. EXPECT_EQ(x - 1, table_->GetVisibleColumn(0).width); EXPECT_EQ(x - 1, table_->GetVisibleColumn(1).x); } // Verifies resizing a column works with a gesture. TEST_P(TableViewTest, ResizeViaGesture) { const int x = table_->GetVisibleColumn(0).width; EXPECT_NE(0, x); // Drag the mouse 1 pixel to the left. ui::GestureEvent scroll_begin( x, 0, 0, base::TimeTicks(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN)); helper_->header()->OnGestureEvent(&scroll_begin); ui::GestureEvent scroll_update( x - 1, 0, 0, base::TimeTicks(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); helper_->header()->OnGestureEvent(&scroll_update); // This should shrink the first column and pull the second column in. EXPECT_EQ(x - 1, table_->GetVisibleColumn(0).width); EXPECT_EQ(x - 1, table_->GetVisibleColumn(1).x); } // Verifies resizing a column works with the keyboard. // The resize keyboard amount is 5 pixels. TEST_P(TableViewTest, ResizeViaKeyboard) { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return; table_->RequestFocus(); const int x = table_->GetVisibleColumn(0).width; EXPECT_NE(0, x); // Table starts off with no visible column being active. ASSERT_FALSE(helper_->GetActiveVisibleColumnIndex().has_value()); ui::ListSelectionModel new_selection; new_selection.SetSelectedIndex(1); helper_->SetSelectionModel(new_selection); ASSERT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); PressKey(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); // This should shrink the first column and pull the second column in. EXPECT_EQ(x - 5, table_->GetVisibleColumn(0).width); EXPECT_EQ(x - 5, table_->GetVisibleColumn(1).x); PressKey(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); // This should restore the columns to their original sizes. EXPECT_EQ(x, table_->GetVisibleColumn(0).width); EXPECT_EQ(x, table_->GetVisibleColumn(1).x); PressKey(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); // This should expand the first column and push the second column out. EXPECT_EQ(x + 5, table_->GetVisibleColumn(0).width); EXPECT_EQ(x + 5, table_->GetVisibleColumn(1).x); } // Verifies resizing a column won't reduce the column width below the width of // the column's title text. TEST_P(TableViewTest, ResizeHonorsMinimum) { TableViewTestHelper helper(table_); const int x = table_->GetVisibleColumn(0).width; EXPECT_NE(0, x); PressLeftMouseAt(helper_->header(), gfx::Point(x, 0)); DragLeftMouseTo(helper_->header(), gfx::Point(20, 0)); int title_width = gfx::GetStringWidth( table_->GetVisibleColumn(0).column.title, helper.font_list()); EXPECT_LT(title_width, table_->GetVisibleColumn(0).width); int old_width = table_->GetVisibleColumn(0).width; DragLeftMouseTo(helper_->header(), gfx::Point(old_width + 10, 0)); EXPECT_EQ(old_width + 10, table_->GetVisibleColumn(0).width); } // Assertions for table sorting. TEST_P(TableViewTest, Sort) { // Initial ordering. EXPECT_TRUE(table_->sort_descriptors().empty()); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[0, 1], [1, 1], [2, 2], [3, 0]"); // Toggle the sort order of the first column, shouldn't change anything. table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[0, 1], [1, 1], [2, 2], [3, 0]"); // Toggle the sort (first column descending). table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("3 2 1 0", GetViewToModelAsString(table_)); EXPECT_EQ("3 2 1 0", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[3, 0], [2, 2], [1, 1], [0, 1]"); // Change the [3, 0] cell to [-1, 0]. This should move it to the back of // the current sort order. model_->ChangeRow(3, -1, 0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("2 1 0 3", GetViewToModelAsString(table_)); EXPECT_EQ("2 1 0 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[2, 2], [1, 1], [0, 1], [-1, 0]"); // Toggle the sort again, to clear the sort and restore the model ordering. table_->ToggleSortOrder(0); EXPECT_TRUE(table_->sort_descriptors().empty()); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[0, 1], [1, 1], [2, 2], [-1, 0]"); // Toggle the sort again (first column ascending). table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("3 0 1 2", GetViewToModelAsString(table_)); EXPECT_EQ("1 2 3 0", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[-1, 0], [0, 1], [1, 1], [2, 2]"); // Add two rows that's second in the model order, but last in the active sort // order. model_->AddRows(1, 2, 10 /* Multiplier */); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("5 0 3 4 1 2", GetViewToModelAsString(table_)); EXPECT_EQ("1 4 5 2 3 0", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder( "[-1, 0], [0, 1], [1, 1], [2, 2], [11, 11], [12, 12]"); // Add a row that's last in the model order but second in the the active sort // order. model_->AddRow(5, -1, 20); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("5 6 0 3 4 1 2", GetViewToModelAsString(table_)); EXPECT_EQ("2 5 6 3 4 0 1", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder( "[-1, 20], [-1, 0], [0, 1], [1, 1], [2, 2], [11, 11], [12, 12]"); // Click the first column again, then click the second column. This should // yield an ordering of second column ascending, with the first column // descending as a tiebreaker. table_->ToggleSortOrder(0); table_->ToggleSortOrder(1); ASSERT_EQ(2u, table_->sort_descriptors().size()); EXPECT_EQ(1, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ(0, table_->sort_descriptors()[1].column_id); EXPECT_FALSE(table_->sort_descriptors()[1].ascending); EXPECT_EQ("6 3 0 4 1 2 5", GetViewToModelAsString(table_)); EXPECT_EQ("2 4 5 1 3 6 0", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder( "[-1, 0], [1, 1], [0, 1], [2, 2], [11, 11], [12, 12], [-1, 20]"); // Toggle the current column to change from ascending to descending. This // should result in an almost-reversal of the previous order, except for the // two rows with the same value for the second column. table_->ToggleSortOrder(1); ASSERT_EQ(2u, table_->sort_descriptors().size()); EXPECT_EQ(1, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ(0, table_->sort_descriptors()[1].column_id); EXPECT_FALSE(table_->sort_descriptors()[1].ascending); EXPECT_EQ("5 2 1 4 3 0 6", GetViewToModelAsString(table_)); EXPECT_EQ("5 2 1 4 3 0 6", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder( "[-1, 20], [12, 12], [11, 11], [2, 2], [1, 1], [0, 1], [-1, 0]"); // Delete the [0, 1] row from the model. It's at model index zero. model_->RemoveRow(0); ASSERT_EQ(2u, table_->sort_descriptors().size()); EXPECT_EQ(1, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ(0, table_->sort_descriptors()[1].column_id); EXPECT_FALSE(table_->sort_descriptors()[1].ascending); EXPECT_EQ("4 1 0 3 2 5", GetViewToModelAsString(table_)); EXPECT_EQ("2 1 4 3 0 5", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder( "[-1, 20], [12, 12], [11, 11], [2, 2], [1, 1], [-1, 0]"); // Delete [-1, 20] and [10, 11] from the model. model_->RemoveRows(1, 2); ASSERT_EQ(2u, table_->sort_descriptors().size()); EXPECT_EQ(1, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ(0, table_->sort_descriptors()[1].column_id); EXPECT_FALSE(table_->sort_descriptors()[1].ascending); EXPECT_EQ("2 0 1 3", GetViewToModelAsString(table_)); EXPECT_EQ("1 2 0 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[-1, 20], [11, 11], [2, 2], [-1, 0]"); // Toggle the current sort column again. This should clear both the primary // and secondary sort descriptor. table_->ToggleSortOrder(1); EXPECT_TRUE(table_->sort_descriptors().empty()); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); VerifyTableViewAndAXOrder("[11, 11], [2, 2], [-1, 20], [-1, 0]"); } // Verifies clicking on the header sorts. TEST_P(TableViewTest, SortOnMouse) { EXPECT_TRUE(table_->sort_descriptors().empty()); const int x = table_->GetVisibleColumn(0).width / 2; EXPECT_NE(0, x); // Press and release the mouse. // The header must return true, else it won't normally get the release. EXPECT_TRUE(PressLeftMouseAt(helper_->header(), gfx::Point(x, 0))); ReleaseLeftMouseAt(helper_->header(), gfx::Point(x, 0)); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); } // Verifies that pressing the space bar when a particular visible column is // active will sort by that column. TEST_P(TableViewTest, SortOnSpaceBar) { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return; table_->RequestFocus(); ASSERT_TRUE(table_->sort_descriptors().empty()); // Table starts off with no visible column being active. ASSERT_FALSE(helper_->GetActiveVisibleColumnIndex().has_value()); ui::ListSelectionModel new_selection; new_selection.SetSelectedIndex(1); helper_->SetSelectionModel(new_selection); ASSERT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); PressKey(ui::VKEY_SPACE); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); PressKey(ui::VKEY_SPACE); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); PressKey(ui::VKEY_RIGHT); ASSERT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); PressKey(ui::VKEY_SPACE); ASSERT_EQ(2u, table_->sort_descriptors().size()); EXPECT_EQ(1, table_->sort_descriptors()[0].column_id); EXPECT_EQ(0, table_->sort_descriptors()[1].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_FALSE(table_->sort_descriptors()[1].ascending); } TEST_P(TableViewTest, ActiveCellBoundsFollowColumnSorting) { table_->RequestFocus(); ASSERT_TRUE(table_->sort_descriptors().empty()); ui::ListSelectionModel new_selection; new_selection.SetSelectedIndex(1); helper_->SetSelectionModel(new_selection); // Toggle the sort order of the first column. Shouldn't change the order. table_->ToggleSortOrder(0); ClickOnRow(0, 0); EXPECT_EQ(helper_->GetCellBounds(0, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(0u, table_->ViewToModel(0)); ClickOnRow(1, 0); EXPECT_EQ(helper_->GetCellBounds(1, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(1u, table_->ViewToModel(1)); ClickOnRow(2, 0); EXPECT_EQ(helper_->GetCellBounds(2, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(2u, table_->ViewToModel(2)); // Toggle the sort order of the second column. The active row will stay in // sync with the view index, meanwhile the model's change which shows that // the list order has changed. table_->ToggleSortOrder(1); ClickOnRow(0, 0); EXPECT_EQ(helper_->GetCellBounds(0, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(3u, table_->ViewToModel(0)); ClickOnRow(1, 0); EXPECT_EQ(helper_->GetCellBounds(1, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(0u, table_->ViewToModel(1)); ClickOnRow(2, 0); EXPECT_EQ(helper_->GetCellBounds(2, 0), helper_->GetActiveCellBounds()); EXPECT_EQ(1u, table_->ViewToModel(2)); // Verifying invalid active indexes return an empty rect. new_selection.Clear(); helper_->SetSelectionModel(new_selection); EXPECT_EQ(gfx::Rect(), helper_->GetActiveCellBounds()); } TEST_P(TableViewTest, Tooltip) { // Column 0 uses the TableModel's GetTooltipText override for tooltips. table_->SetVisibleColumnWidth(0, 10); auto local_point_for_row = [&](int row) { return gfx::Point(5, (row + 0.5) * table_->GetRowHeight()); }; auto expected = [](int row) { return u"Tooltip" + base::NumberToString16(row); }; EXPECT_EQ(expected(0), table_->GetTooltipText(local_point_for_row(0))); EXPECT_EQ(expected(1), table_->GetTooltipText(local_point_for_row(1))); EXPECT_EQ(expected(2), table_->GetTooltipText(local_point_for_row(2))); // Hovering another column will return that cell's text instead. const gfx::Point point(15, local_point_for_row(0).y()); EXPECT_EQ(model_->GetText(0, 1), table_->GetTooltipText(point)); } namespace { class TableGrouperImpl : public TableGrouper { public: TableGrouperImpl() = default; TableGrouperImpl(const TableGrouperImpl&) = delete; TableGrouperImpl& operator=(const TableGrouperImpl&) = delete; void SetRanges(const std::vector<size_t>& ranges) { ranges_ = ranges; } // TableGrouper overrides: void GetGroupRange(size_t model_index, GroupRange* range) override { size_t offset = 0; size_t range_index = 0; for (; range_index < ranges_.size() && offset < model_index; ++range_index) offset += ranges_[range_index]; if (offset == model_index) { range->start = model_index; range->length = ranges_[range_index]; } else { range->start = offset - ranges_[range_index - 1]; range->length = ranges_[range_index - 1]; } } private: std::vector<size_t> ranges_; }; } // namespace // Assertions around grouping. TEST_P(TableViewTest, Grouping) { // Configure the grouper so that there are two groups: // A 0 // 1 // B 2 // 3 TableGrouperImpl grouper; grouper.SetRanges({2, 2}); table_->SetGrouper(&grouper); // Toggle the sort order of the first column, shouldn't change anything. table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); // Sort descending, resulting: // B 2 // 3 // A 0 // 1 table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); // Change the entry in the 4th row to -1. The model now becomes: // A 0 // 1 // B 2 // -1 // Since the first entry in the range didn't change the sort isn't impacted. model_->ChangeRow(3, -1, 0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); // Change the entry in the 3rd row to -1. The model now becomes: // A 0 // 1 // B -1 // -1 model_->ChangeRow(2, -1, 0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); // Toggle to clear the sort. table_->ToggleSortOrder(0); EXPECT_TRUE(table_->sort_descriptors().empty()); EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); // Toggle again to effect an ascending sort. table_->ToggleSortOrder(0); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_TRUE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); } namespace { class TableViewObserverImpl : public TableViewObserver { public: TableViewObserverImpl() = default; TableViewObserverImpl(const TableViewObserverImpl&) = delete; TableViewObserverImpl& operator=(const TableViewObserverImpl&) = delete; int GetChangedCountAndClear() { const int count = selection_changed_count_; selection_changed_count_ = 0; return count; } // TableViewObserver overrides: void OnSelectionChanged() override { selection_changed_count_++; } private: int selection_changed_count_ = 0; }; } // namespace // Assertions around changing the selection. TEST_P(TableViewTest, Selection) { TableViewObserverImpl observer; table_->set_observer(&observer); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); // Select the last row. table_->Select(3); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Change sort, shouldn't notify of change (toggle twice so that order // actually changes). table_->ToggleSortOrder(0); table_->ToggleSortOrder(0); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Remove the selected row, this should notify of a change and update the // selection. model_->RemoveRow(3); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Insert a row, since the selection in terms of the original model hasn't // changed the observer is not notified. model_->AddRow(0, 1, 2); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Swap the first two rows. This shouldn't affect selection. model_->MoveRows(0, 1, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Move the first row to after the selection. This will change the selection // state. model_->MoveRows(0, 1, 3); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Move the first two rows to be after the selection. This will change the // selection state. model_->MoveRows(0, 2, 2); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); // Move some rows after the selection. model_->MoveRows(2, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); // Move the selection itself. model_->MoveRows(0, 1, 3); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Move-left a range that ends at the selection model_->MoveRows(2, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Move-right a range that ends at the selection model_->MoveRows(1, 2, 2); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Add a row at the end. model_->AddRow(4, 7, 9); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Move-left a range that includes the selection. model_->MoveRows(2, 3, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Move-right a range that includes the selection. model_->MoveRows(0, 4, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Insert two rows to the selection. model_->AddRows(2, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=5 anchor=5 selection=5", SelectionStateAsString()); // Remove two rows which include the selection. model_->RemoveRows(4, 2); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); table_->set_observer(nullptr); } TEST_P(TableViewTest, SelectAll) { TableViewObserverImpl observer; table_->set_observer(&observer); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); table_->SetSelectionAll(/*select=*/true); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=0 1 2 3", SelectionStateAsString()); table_->Select(2); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); table_->SetSelectionAll(/*select=*/true); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=0 1 2 3", SelectionStateAsString()); table_->SetSelectionAll(/*select=*/false); EXPECT_EQ("active=2 anchor=2 selection=", SelectionStateAsString()); } TEST_P(TableViewTest, RemoveUnselectedRows) { TableViewObserverImpl observer; table_->set_observer(&observer); // Select a middle row. table_->Select(2); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Remove the last row. This should notify of a change. model_->RemoveRow(3); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Remove the first row. This should also notify of a change. model_->RemoveRow(0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); } TEST_P(TableViewTest, AddingRemovingMultipleRows) { TableViewObserverImpl observer; table_->set_observer(&observer); VerifyTableViewAndAXOrder("[0, 1], [1, 1], [2, 2], [3, 0]"); model_->AddRows(0, 3, 10); VerifyTableViewAndAXOrder( "[10, 10], [11, 11], [12, 12], [0, 1], [1, 1], [2, 2], [3, 0]"); model_->RemoveRows(4, 3); VerifyTableViewAndAXOrder("[10, 10], [11, 11], [12, 12], [0, 1]"); } // 0 1 2 3: // select 3 -> 0 1 2 [3] // remove 3 -> 0 1 2 (none selected) // select 1 -> 0 [1] 2 // remove 1 -> 0 1 (none selected) // select 0 -> [0] 1 // remove 0 -> 0 (none selected) TEST_P(TableViewTest, SelectionNoSelectOnRemove) { TableViewObserverImpl observer; table_->set_observer(&observer); table_->SetSelectOnRemove(false); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); // Select row 3. table_->Select(3); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); // Remove the selected row, this should notify of a change and since the // select_on_remove_ is set false, and the removed item is the previously // selected item, so no item is selected. model_->RemoveRow(3); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); // Select row 1. table_->Select(1); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); // Remove the selected row. model_->RemoveRow(1); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); // Select row 0. table_->Select(0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); // Remove the selected row. model_->RemoveRow(0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); table_->set_observer(nullptr); } // No touch on desktop Mac. Tracked in http://crbug.com/445520. #if !BUILDFLAG(IS_MAC) // Verifies selection works by way of a gesture. TEST_P(TableViewTest, SelectOnTap) { // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); TableViewObserverImpl observer; table_->set_observer(&observer); // Tap on the first row, should select it and focus the table. EXPECT_FALSE(table_->HasFocus()); TapOnRow(0); EXPECT_TRUE(table_->HasFocus()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); table_->set_observer(nullptr); } #endif // Verifies up/down correctly navigate through groups. TEST_P(TableViewTest, KeyUpDown) { // Configure the grouper so that there are three groups: // A 0 // 1 // B 5 // C 2 // 3 model_->AddRow(2, 5, 0); TableGrouperImpl grouper; grouper.SetRanges({2, 1, 2}); table_->SetGrouper(&grouper); TableViewObserverImpl observer; table_->set_observer(&observer); table_->RequestFocus(); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_UP); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); PressKey(ui::VKEY_UP); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_UP); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); // Key up at this point will clear selection and navigate into the header. EXPECT_FALSE(table_->header_row_is_active()); PressKey(ui::VKEY_UP); EXPECT_TRUE(table_->header_row_is_active()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); // Sort the table descending by column 1, view now looks like: // B 5 model: 2 // C 2 3 // 3 4 // A 0 0 // 1 1 table_->ToggleSortOrder(0); table_->ToggleSortOrder(0); EXPECT_EQ("2 3 4 0 1", GetViewToModelAsString(table_)); table_->Select(absl::nullopt); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); observer.GetChangedCountAndClear(); // Up with nothing selected moves selection into the table's header. EXPECT_FALSE(table_->header_row_is_active()); PressKey(ui::VKEY_UP); EXPECT_TRUE(table_->header_row_is_active()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_DOWN); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_UP); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_UP); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); // Key up at this point will clear selection and navigate into the header. EXPECT_FALSE(table_->header_row_is_active()); PressKey(ui::VKEY_UP); EXPECT_TRUE(table_->header_row_is_active()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); table_->set_observer(nullptr); } // Verifies left/right correctly navigate through visible columns. TEST_P(TableViewTest, KeyLeftRight) { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return; TableViewObserverImpl observer; table_->set_observer(&observer); table_->RequestFocus(); // Initially no active visible column. EXPECT_FALSE(helper_->GetActiveVisibleColumnIndex().has_value()); PressKey(ui::VKEY_RIGHT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); helper_->SetSelectionModel(ui::ListSelectionModel()); EXPECT_FALSE(helper_->GetActiveVisibleColumnIndex().has_value()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); PressKey(ui::VKEY_LEFT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); PressKey(ui::VKEY_RIGHT); EXPECT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); PressKey(ui::VKEY_RIGHT); EXPECT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); ui::ListSelectionModel new_selection; new_selection.SetSelectedIndex(1); helper_->SetSelectionModel(new_selection); EXPECT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); PressKey(ui::VKEY_LEFT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); PressKey(ui::VKEY_LEFT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); table_->SetColumnVisibility(0, false); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); // Since the first column was hidden, the active visible column should not // advance. PressKey(ui::VKEY_RIGHT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); // If visibility to the first column is restored, the active visible column // should be unchanged because columns are always added to the end. table_->SetColumnVisibility(0, true); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); PressKey(ui::VKEY_RIGHT); EXPECT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); // If visibility to the first column is removed, the active visible column // should be decreased by one. table_->SetColumnVisibility(0, false); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); PressKey(ui::VKEY_LEFT); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); table_->SetColumnVisibility(0, true); EXPECT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); PressKey(ui::VKEY_RIGHT); EXPECT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); table_->set_observer(nullptr); } // Verifies home/end do the right thing. TEST_P(TableViewTest, HomeEnd) { // Configure the grouper so that there are three groups: // A 0 // 1 // B 5 // C 2 // 3 model_->AddRow(2, 5, 0); TableGrouperImpl grouper; grouper.SetRanges({2, 1, 2}); table_->SetGrouper(&grouper); TableViewObserverImpl observer; table_->set_observer(&observer); table_->RequestFocus(); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); PressKey(ui::VKEY_HOME); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); PressKey(ui::VKEY_END); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); PressKey(ui::VKEY_HOME); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); table_->set_observer(nullptr); } // Verifies multiple selection gestures work (control-click, shift-click ...). TEST_P(TableViewTest, Multiselection) { // Configure the grouper so that there are three groups: // A 0 // 1 // B 5 // C 2 // 3 model_->AddRow(2, 5, 0); TableGrouperImpl grouper; grouper.SetRanges({2, 1, 2}); table_->SetGrouper(&grouper); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); TableViewObserverImpl observer; table_->set_observer(&observer); // Click on the first row, should select it and the second row. ClickOnRow(0, 0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); // Click on the last row, should select it and the row before it. ClickOnRow(4, 0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); // Shift click on the third row, should extend selection to it. ClickOnRow(2, ui::EF_SHIFT_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=4 selection=2 3 4", SelectionStateAsString()); // Control click on third row, should toggle it. ClickOnRow(2, kCtrlOrCmdMask); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=3 4", SelectionStateAsString()); // Control-shift click on second row, should extend selection to it. ClickOnRow(1, kCtrlOrCmdMask | ui::EF_SHIFT_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=2 selection=0 1 2 3 4", SelectionStateAsString()); // Click on last row again. ClickOnRow(4, 0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); table_->set_observer(nullptr); } // Verifies multiple selection gestures work when sorted. TEST_P(TableViewTest, MultiselectionWithSort) { // Configure the grouper so that there are three groups: // A 0 // 1 // B 5 // C 2 // 3 model_->AddRow(2, 5, 0); TableGrouperImpl grouper; grouper.SetRanges({2, 1, 2}); table_->SetGrouper(&grouper); // Sort the table descending by column 1, view now looks like: // B 5 model: 2 // C 2 3 // 3 4 // A 0 0 // 1 1 table_->ToggleSortOrder(0); table_->ToggleSortOrder(0); // Initially no selection. EXPECT_EQ("active=<none> anchor=<none> selection=", SelectionStateAsString()); TableViewObserverImpl observer; table_->set_observer(&observer); // Click on the third row, should select it and the second row. ClickOnRow(2, 0); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); // Extend selection to first row. ClickOnRow(0, ui::EF_SHIFT_DOWN); EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=4 selection=2 3 4", SelectionStateAsString()); } TEST_P(TableViewTest, MoveRowsWithMultipleSelection) { model_->AddRow(3, 77, 0); // Hide column 1. table_->SetColumnVisibility(1, false); TableViewObserverImpl observer; table_->set_observer(&observer); // Select three rows. ClickOnRow(2, 0); ClickOnRow(4, ui::EF_SHIFT_DOWN); EXPECT_EQ(2, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=2 selection=2 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[0], [1], [2], [77], [3]"); // Move the unselected rows to the middle of the current selection. None of // the move operations should affect the view order. model_->MoveRows(0, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[2], [0], [1], [77], [3]"); // Move the unselected rows to the end of the current selection. model_->MoveRows(1, 2, 3); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=0 selection=0 1 2", SelectionStateAsString()); VerifyTableViewAndAXOrder("[2], [77], [3], [0], [1]"); // Move the unselected rows back to the middle of the selection. model_->MoveRows(3, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[2], [0], [1], [77], [3]"); // Swap the unselected rows. model_->MoveRows(1, 1, 2); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[2], [1], [0], [77], [3]"); // Move the second unselected row to be between two selected rows. model_->MoveRows(2, 1, 3); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=0 selection=0 2 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[2], [1], [77], [0], [3]"); // Move the three middle rows to the beginning, including one selected row. model_->MoveRows(1, 3, 0); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=3 selection=1 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder("[1], [77], [0], [2], [3]"); table_->set_observer(nullptr); } TEST_P(TableViewTest, MoveRowsWithMultipleSelectionAndSort) { model_->AddRow(3, 77, 0); // Sort ascending by column 0, and hide column 1. The view order should not // change during this test. table_->ToggleSortOrder(0); table_->SetColumnVisibility(1, false); const char* kViewOrder = "[0], [1], [2], [3], [77]"; VerifyTableViewAndAXOrder(kViewOrder); TableViewObserverImpl observer; table_->set_observer(&observer); // Select three rows. ClickOnRow(2, 0); ClickOnRow(4, ui::EF_SHIFT_DOWN); EXPECT_EQ(2, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=2 selection=2 3 4", SelectionStateAsString()); // Move the unselected rows to the middle of the current selection. None of // the move operations should affect the view order. model_->MoveRows(0, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); // Move the unselected rows to the end of the current selection. model_->MoveRows(1, 2, 3); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=0 selection=0 1 2", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); // Move the unselected rows back to the middle of the selection. model_->MoveRows(3, 2, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); // Swap the unselected rows. model_->MoveRows(1, 1, 2); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); // Swap the unselected rows again. model_->MoveRows(2, 1, 1); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=0 selection=0 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); // Move the unselected rows back to the beginning. model_->MoveRows(1, 2, 0); EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=2 selection=2 3 4", SelectionStateAsString()); VerifyTableViewAndAXOrder(kViewOrder); table_->set_observer(nullptr); } // Verifies we don't crash after removing the selected row when there is // sorting and the anchor/active index also match the selected row. TEST_P(TableViewTest, FocusAfterRemovingAnchor) { table_->ToggleSortOrder(0); ui::ListSelectionModel new_selection; new_selection.AddIndexToSelection(0); new_selection.AddIndexToSelection(1); new_selection.set_active(0); new_selection.set_anchor(0); helper_->SetSelectionModel(new_selection); model_->RemoveRow(0); table_->RequestFocus(); } // OnItemsRemoved() should ensure view-model mappings are updated in response to // the table model change before these view-model mappings are used. // Test for (https://crbug.com/1173373). TEST_P(TableViewTest, RemovingSortedRowsDoesNotCauseOverflow) { // Ensure the table has a sort descriptor set so that `view_to_model_` and // `model_to_view_` mappings are established and are in descending order. Do // this so the first view row maps to the last model row. table_->ToggleSortOrder(0); table_->ToggleSortOrder(0); ASSERT_TRUE(table_->GetIsSorted()); ASSERT_EQ(1u, table_->sort_descriptors().size()); EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); EXPECT_FALSE(table_->sort_descriptors()[0].ascending); EXPECT_EQ("3 2 1 0", GetViewToModelAsString(table_)); EXPECT_EQ("3 2 1 0", GetModelToViewAsString(table_)); // Removing rows can result in callbacks to GetTooltipText(). Above mappings // will cause TableView to try to access the text for the first view row and // consequently attempt to access the last element in the model via the // `view_to_model_` mapping. This will result in a crash if the view-model // mappings have not been appropriately updated. model_->SetTooltip(u""); model_->RemoveRow(0); model_->RemoveRow(0); model_->RemoveRow(0); model_->RemoveRow(0); } // Ensure that the TableView's header row is keyboard accessible. // Tests for crbug.com/1189851. TEST_P(TableViewTest, TableHeaderRowAccessibleViewFocusable) { ASSERT_NE(nullptr, helper_->header()); table_->RequestFocus(); RunPendingMessages(); // If no table body row has selection the TableView itself is focused and // there is no focused virtual view. EXPECT_TRUE(table_->HasFocus()); EXPECT_FALSE(table_->header_row_is_active()); EXPECT_EQ(nullptr, table_->GetViewAccessibility().FocusedVirtualChild()); // Hitting the up arrow key should give the header focus and make it active. PressKey(ui::VKEY_UP); RunPendingMessages(); EXPECT_TRUE(table_->HasFocus()); EXPECT_TRUE(table_->header_row_is_active()); EXPECT_EQ(helper_->GetVirtualAccessibilityHeaderRow(), table_->GetViewAccessibility().FocusedVirtualChild()); // Hitting the down arrow key should move focus back into the body. PressKey(ui::VKEY_DOWN); RunPendingMessages(); EXPECT_TRUE(table_->HasFocus()); EXPECT_FALSE(table_->header_row_is_active()); EXPECT_NE(helper_->GetVirtualAccessibilityHeaderRow(), table_->GetViewAccessibility().FocusedVirtualChild()); } // Ensure that the TableView's header columns are keyboard accessible. // Tests for crbug.com/1189851. TEST_P(TableViewTest, TableHeaderColumnAccessibleViewsFocusable) { if (!PlatformStyle::kTableViewSupportsKeyboardNavigationByCell) return; ASSERT_NE(nullptr, helper_->header()); table_->RequestFocus(); RunPendingMessages(); // Hitting the up arrow key should give the header focus and make it active. auto& view_accessibility = table_->GetViewAccessibility(); PressKey(ui::VKEY_UP); RunPendingMessages(); EXPECT_TRUE(table_->HasFocus()); EXPECT_TRUE(table_->header_row_is_active()); EXPECT_EQ(helper_->GetVirtualAccessibilityHeaderRow(), view_accessibility.FocusedVirtualChild()); // Navigating with arrow keys should move focus between TableView header // columns. PressKey(ui::VKEY_RIGHT); RunPendingMessages(); ASSERT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(helper_->GetVirtualAccessibilityHeaderCell(0), view_accessibility.FocusedVirtualChild()); PressKey(ui::VKEY_RIGHT); RunPendingMessages(); ASSERT_EQ(1u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(helper_->GetVirtualAccessibilityHeaderCell(1), view_accessibility.FocusedVirtualChild()); PressKey(ui::VKEY_LEFT); RunPendingMessages(); ASSERT_EQ(0u, helper_->GetActiveVisibleColumnIndex()); EXPECT_EQ(helper_->GetVirtualAccessibilityHeaderCell(0), view_accessibility.FocusedVirtualChild()); } namespace { class RemoveFocusChangeListenerDelegate : public WidgetDelegate { public: explicit RemoveFocusChangeListenerDelegate(Widget* widget) : listener_(nullptr) { RegisterDeleteDelegateCallback(base::BindOnce( [](Widget* widget, RemoveFocusChangeListenerDelegate* delegate) { widget->GetFocusManager()->RemoveFocusChangeListener( delegate->listener_); }, base::Unretained(widget), base::Unretained(this))); } RemoveFocusChangeListenerDelegate(const RemoveFocusChangeListenerDelegate&) = delete; RemoveFocusChangeListenerDelegate& operator=( const RemoveFocusChangeListenerDelegate&) = delete; ~RemoveFocusChangeListenerDelegate() override = default; void SetFocusChangeListener(FocusChangeListener* listener); private: raw_ptr<FocusChangeListener> listener_; }; void RemoveFocusChangeListenerDelegate::SetFocusChangeListener( FocusChangeListener* listener) { listener_ = listener; } } // namespace class TableViewFocusTest : public TableViewTest { public: TableViewFocusTest() = default; TableViewFocusTest(const TableViewFocusTest&) = delete; TableViewFocusTest& operator=(const TableViewFocusTest&) = delete; protected: WidgetDelegate* GetWidgetDelegate(Widget* widget) override; RemoveFocusChangeListenerDelegate* GetFocusChangeListenerDelegate() { return delegate_.get(); } private: std::unique_ptr<RemoveFocusChangeListenerDelegate> delegate_; }; WidgetDelegate* TableViewFocusTest::GetWidgetDelegate(Widget* widget) { delegate_ = std::make_unique<RemoveFocusChangeListenerDelegate>(widget); return delegate_.get(); } INSTANTIATE_TEST_SUITE_P(All, TableViewFocusTest, testing::Values(false, true)); // Verifies that the active focus is cleared when the widget is destroyed. // In MD mode, if that doesn't happen a DCHECK in View::DoRemoveChildView(...) // will trigger due to an attempt to modify the child view list while iterating. TEST_P(TableViewFocusTest, FocusClearedDuringWidgetDestruction) { TestFocusChangeListener listener; GetFocusChangeListenerDelegate()->SetFocusChangeListener(&listener); widget_->GetFocusManager()->AddFocusChangeListener(&listener); table_->RequestFocus(); ASSERT_EQ(1u, listener.focus_changes().size()); EXPECT_EQ(listener.focus_changes()[0], ViewPair(nullptr, table_)); listener.ClearFocusChanges(); // Now destroy the widget. This should *not* cause a DCHECK in // View::DoRemoveChildView(...). widget_.reset(); ASSERT_EQ(1u, listener.focus_changes().size()); EXPECT_EQ(listener.focus_changes()[0], ViewPair(table_, nullptr)); } class TableViewDefaultConstructabilityTest : public ViewsTestBase { public: TableViewDefaultConstructabilityTest() = default; TableViewDefaultConstructabilityTest( const TableViewDefaultConstructabilityTest&) = delete; TableViewDefaultConstructabilityTest& operator=( const TableViewDefaultConstructabilityTest&) = delete; ~TableViewDefaultConstructabilityTest() override = default; void SetUp() override { ViewsTestBase::SetUp(); widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 650, 650); widget_->Init(std::move(params)); widget_->Show(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } Widget* widget() { return widget_.get(); } private: UniqueWidgetPtr widget_; }; TEST_F(TableViewDefaultConstructabilityTest, TestFunctionalWithoutModel) { auto scroll_view = TableView::CreateScrollViewWithTable(std::make_unique<TableView>()); scroll_view->SetBounds(0, 0, 10000, 10000); widget()->client_view()->AddChildView(std::move(scroll_view)); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/table_view_unittest.cc
C++
unknown
80,541
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/table/test_table_model.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/models/image_model.h" #include "ui/base/models/table_model_observer.h" #include "ui/gfx/image/image_skia.h" TestTableModel::TestTableModel(size_t row_count) : row_count_(row_count), observer_(nullptr) {} TestTableModel::~TestTableModel() = default; size_t TestTableModel::RowCount() { return row_count_; } std::u16string TestTableModel::GetText(size_t row, int column_id) { return base::ASCIIToUTF16(base::NumberToString(row) + "x" + base::NumberToString(column_id)); } ui::ImageModel TestTableModel::GetIcon(size_t row) { SkBitmap bitmap; bitmap.setInfo(SkImageInfo::MakeN32Premul(16, 16)); return ui::ImageModel::FromImageSkia( gfx::ImageSkia::CreateFrom1xBitmap(bitmap)); } void TestTableModel::SetObserver(ui::TableModelObserver* observer) { observer_ = observer; }
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/test_table_model.cc
C++
unknown
1,196
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_ #define UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_ #include "base/memory/raw_ptr.h" #include "ui/base/models/table_model.h" class TestTableModel : public ui::TableModel { public: explicit TestTableModel(size_t row_count); TestTableModel(const TestTableModel&) = delete; TestTableModel& operator=(const TestTableModel&) = delete; ~TestTableModel() override; // ui::TableModel overrides: size_t RowCount() override; std::u16string GetText(size_t row, int column_id) override; ui::ImageModel GetIcon(size_t row) override; void SetObserver(ui::TableModelObserver* observer) override; private: size_t row_count_; raw_ptr<ui::TableModelObserver> observer_; }; #endif // UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/table/test_table_model.h
C++
unknown
937
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textarea/textarea.h" #include "base/logging.h" #include "ui/base/ime/text_edit_commands.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" namespace views { Textarea::Textarea() { set_placeholder_text_draw_flags(placeholder_text_draw_flags() | gfx::Canvas::MULTI_LINE); GetRenderText()->SetMultiline(true); GetRenderText()->SetVerticalAlignment(gfx::ALIGN_TOP); GetRenderText()->SetWordWrapBehavior(gfx::WRAP_LONG_WORDS); SetTextInputType(ui::TextInputType::TEXT_INPUT_TYPE_TEXT_AREA); } size_t Textarea::GetNumLines() { return GetRenderText()->GetNumLines(); } bool Textarea::OnMouseWheel(const ui::MouseWheelEvent& event) { GetRenderText()->SetDisplayOffset(GetRenderText()->GetUpdatedDisplayOffset() + gfx::Vector2d(0, event.y_offset())); UpdateCursorViewPosition(); UpdateCursorVisibility(); SchedulePaint(); return true; } Textfield::EditCommandResult Textarea::DoExecuteTextEditCommand( ui::TextEditCommand command) { bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; gfx::VisualCursorDirection begin = rtl ? gfx::CURSOR_RIGHT : gfx::CURSOR_LEFT; gfx::VisualCursorDirection end = rtl ? gfx::CURSOR_LEFT : gfx::CURSOR_RIGHT; switch (command) { case ui::TextEditCommand::MOVE_UP: textfield_model()->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_UP, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_DOWN: textfield_model()->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_DOWN, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_UP_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_UP, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_DOWN_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_DOWN, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::FIELD_BREAK, begin, kPageSelectionBehavior); break; case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_PARAGRAPH_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::FIELD_BREAK, begin, kMoveParagraphSelectionBehavior); break; case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::FIELD_BREAK, end, kPageSelectionBehavior); break; case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH_AND_MODIFY_SELECTION: textfield_model()->MoveCursor(gfx::FIELD_BREAK, end, kMoveParagraphSelectionBehavior); break; default: return Textfield::DoExecuteTextEditCommand(command); } // TODO(jongkwon.lee): Return |cursor_changed| with actual value. It's okay // for now because |cursor_changed| is detected afterward in // |Textfield::ExecuteTextEditCommand|. return {false, false}; } bool Textarea::PreHandleKeyPressed(const ui::KeyEvent& event) { if (event.key_code() == ui::VKEY_RETURN) { DoInsertChar('\n'); return true; } return false; } ui::TextEditCommand Textarea::GetCommandForKeyEvent(const ui::KeyEvent& event) { if (event.type() != ui::ET_KEY_PRESSED || event.IsUnicodeKeyCode()) return Textfield::GetCommandForKeyEvent(event); const bool shift = event.IsShiftDown(); switch (event.key_code()) { case ui::VKEY_UP: return shift ? ui::TextEditCommand::MOVE_UP_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_UP; case ui::VKEY_DOWN: return shift ? ui::TextEditCommand::MOVE_DOWN_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_DOWN; default: return Textfield::GetCommandForKeyEvent(event); } } BEGIN_METADATA(Textarea, Textfield) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textarea/textarea.cc
C++
unknown
4,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_CONTROLS_TEXTAREA_TEXTAREA_H_ #define UI_VIEWS_CONTROLS_TEXTAREA_TEXTAREA_H_ #include "ui/views/controls/textfield/textfield.h" namespace views { // A multiline textfield implementation. class VIEWS_EXPORT Textarea : public Textfield { public: METADATA_HEADER(Textarea); Textarea(); ~Textarea() override = default; // Returns the number of lines of the text. size_t GetNumLines(); // Textfield: bool OnMouseWheel(const ui::MouseWheelEvent& event) override; protected: // Textfield: Textfield::EditCommandResult DoExecuteTextEditCommand( ui::TextEditCommand command) override; bool PreHandleKeyPressed(const ui::KeyEvent& event) override; ui::TextEditCommand GetCommandForKeyEvent(const ui::KeyEvent& event) override; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TEXTAREA_TEXTAREA_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textarea/textarea.h
C++
unknown
992
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textarea/textarea.h" #include <memory> #include <string> #include <vector> #include "base/format_macros.h" #include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/events/event.h" #include "ui/gfx/render_text.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/textfield/textfield_test_api.h" #include "ui/views/controls/textfield/textfield_unittest.h" #include "ui/views/style/platform_style.h" #include "ui/views/widget/widget.h" namespace { const char16_t kHebrewLetterSamekh = 0x05E1; } // namespace namespace views { namespace { class TextareaTest : public test::TextfieldTest { public: TextareaTest() = default; TextareaTest(const TextareaTest&) = delete; TextareaTest& operator=(const TextareaTest&) = delete; ~TextareaTest() override = default; // TextfieldTest: void SetUp() override { TextfieldTest::SetUp(); ASSERT_FALSE(textarea_); textarea_ = PrepareTextfields(0, std::make_unique<Textarea>(), gfx::Rect(100, 100, 800, 100)); } protected: void RunMoveUpDownTest(int start_index, ui::KeyboardCode key_code, std::vector<int> expected) { DCHECK(key_code == ui::VKEY_UP || key_code == ui::VKEY_DOWN); textarea_->SetSelectedRange(gfx::Range(start_index)); for (size_t i = 0; i < expected.size(); ++i) { SCOPED_TRACE(testing::Message() << (key_code == ui::VKEY_UP ? "MOVE UP " : "MOVE DOWN ") << i + 1 << " times from Range " << start_index); SendKeyEvent(key_code); EXPECT_EQ(gfx::Range(expected[i]), textarea_->GetSelectedRange()); } } size_t GetCursorLine() const { return test_api_->GetRenderText()->GetLineContainingCaret( textarea_->GetSelectionModel()); } // TextfieldTest: void SendHomeEvent(bool shift) override { SendKeyEvent(ui::VKEY_HOME, shift, TestingNativeMac()); } // TextfieldTest: void SendEndEvent(bool shift) override { SendKeyEvent(ui::VKEY_END, shift, TestingNativeMac()); } raw_ptr<Textarea> textarea_ = nullptr; }; } // namespace // Disabled when using XKB for crbug.com/1171828. #if BUILDFLAG(USE_XKBCOMMON) #define MAYBE_InsertNewlineTest DISABLED_InsertNewlineTest #else #define MAYBE_InsertNewlineTest InsertNewlineTest #endif // BUILDFLAG(USE_XKBCOMMON) TEST_F(TextareaTest, MAYBE_InsertNewlineTest) { for (size_t i = 0; i < 5; i++) { SendKeyEvent(static_cast<ui::KeyboardCode>(ui::VKEY_A + i)); SendKeyEvent(ui::VKEY_RETURN); } EXPECT_EQ(u"a\nb\nc\nd\ne\n", textarea_->GetText()); } TEST_F(TextareaTest, PasteNewlineTest) { const std::u16string kText = u"abc\n \n"; textarea_->SetText(kText); textarea_->SelectAll(false); textarea_->ExecuteCommand(Textfield::kCopy, 0); textarea_->SetText(std::u16string()); textarea_->ExecuteCommand(Textfield::kPaste, 0); EXPECT_EQ(kText, textarea_->GetText()); } // Re-enable when crbug.com/1163587 is fixed. TEST_F(TextareaTest, DISABLED_CursorMovement) { textarea_->SetText(u"one\n\ntwo three"); // Move Up/Down at the front of the line. RunMoveUpDownTest(0, ui::VKEY_DOWN, {4, 5, 14}); RunMoveUpDownTest(5, ui::VKEY_UP, {4, 0, 0}); // Move Up/Down at the end of the line. RunMoveUpDownTest(3, ui::VKEY_DOWN, {4, 8, 14}); RunMoveUpDownTest(14, ui::VKEY_UP, {4, 3, 0}); // Move Up/Down at the middle position. RunMoveUpDownTest(2, ui::VKEY_DOWN, {4, 7, 14}); RunMoveUpDownTest(7, ui::VKEY_UP, {4, 2, 0}); // Test Home/End key on each lines. textarea_->SetSelectedRange(gfx::Range(2)); // First line. SendHomeEvent(false); EXPECT_EQ(gfx::Range(0), textarea_->GetSelectedRange()); SendEndEvent(false); EXPECT_EQ(gfx::Range(3), textarea_->GetSelectedRange()); textarea_->SetSelectedRange(gfx::Range(4)); // 2nd line. SendHomeEvent(false); EXPECT_EQ(gfx::Range(4), textarea_->GetSelectedRange()); SendEndEvent(false); EXPECT_EQ(gfx::Range(4), textarea_->GetSelectedRange()); textarea_->SetSelectedRange(gfx::Range(7)); // 3rd line. SendHomeEvent(false); EXPECT_EQ(gfx::Range(5), textarea_->GetSelectedRange()); SendEndEvent(false); EXPECT_EQ(gfx::Range(14), textarea_->GetSelectedRange()); } // Ensure cursor view is always inside display rect. TEST_F(TextareaTest, CursorViewBounds) { textarea_->SetBounds(0, 0, 100, 31); for (size_t i = 0; i < 10; ++i) { SCOPED_TRACE(base::StringPrintf("VKEY_RETURN %" PRIuS " times", i + 1)); SendKeyEvent(ui::VKEY_RETURN); ASSERT_TRUE(textarea_->GetVisibleBounds().Contains(GetCursorViewRect())); ASSERT_FALSE(GetCursorViewRect().size().IsEmpty()); } for (size_t i = 0; i < 10; ++i) { SCOPED_TRACE(base::StringPrintf("VKEY_UP %" PRIuS " times", i + 1)); SendKeyEvent(ui::VKEY_UP); ASSERT_TRUE(textarea_->GetVisibleBounds().Contains(GetCursorViewRect())); ASSERT_FALSE(GetCursorViewRect().size().IsEmpty()); } } TEST_F(TextareaTest, LineSelection) { textarea_->SetText(u"12\n34567 89"); // Place the cursor after "5". textarea_->SetEditableSelectionRange(gfx::Range(6)); // Select line towards right. SendEndEvent(true); EXPECT_EQ(u"67 89", textarea_->GetSelectedText()); // Select line towards left. On Mac, the existing selection should be extended // to cover the whole line. SendHomeEvent(true); if (Textarea::kLineSelectionBehavior == gfx::SELECTION_EXTEND) EXPECT_EQ(u"34567 89", textarea_->GetSelectedText()); else EXPECT_EQ(u"345", textarea_->GetSelectedText()); EXPECT_TRUE(textarea_->GetSelectedRange().is_reversed()); // Select line towards right. SendEndEvent(true); if (Textarea::kLineSelectionBehavior == gfx::SELECTION_EXTEND) EXPECT_EQ(u"34567 89", textarea_->GetSelectedText()); else EXPECT_EQ(u"67 89", textarea_->GetSelectedText()); EXPECT_FALSE(textarea_->GetSelectedRange().is_reversed()); } // Disabled on Mac for crbug.com/1171826. #if BUILDFLAG(IS_MAC) #define MAYBE_MoveUpDownAndModifySelection DISABLED_MoveUpDownAndModifySelection #else #define MAYBE_MoveUpDownAndModifySelection MoveUpDownAndModifySelection #endif // BUILDFLAG(IS_MAC) TEST_F(TextareaTest, MAYBE_MoveUpDownAndModifySelection) { textarea_->SetText(u"12\n34567 89"); textarea_->SetEditableSelectionRange(gfx::Range(6)); EXPECT_EQ(1U, GetCursorLine()); // Up key should place the cursor after "2" not after newline to place the // cursor on the first line. SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(0U, GetCursorLine()); EXPECT_EQ(gfx::Range(2), textarea_->GetSelectedRange()); // Down key after Up key should select the same range as the previous one. SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(1U, GetCursorLine()); EXPECT_EQ(gfx::Range(6), textarea_->GetSelectedRange()); // Shift+Up should select the text to the upper line position including // the newline character. SendKeyEvent(ui::VKEY_UP, true /* shift */, false /* command */); EXPECT_EQ(gfx::Range(6, 2), textarea_->GetSelectedRange()); // Shift+Down should collapse the selection. SendKeyEvent(ui::VKEY_DOWN, true /* shift */, false /* command */); EXPECT_EQ(gfx::Range(6), textarea_->GetSelectedRange()); // Shift+Down again should select the text to the end of the last line. SendKeyEvent(ui::VKEY_DOWN, true /* shift */, false /* command */); EXPECT_EQ(gfx::Range(6, 11), textarea_->GetSelectedRange()); } TEST_F(TextareaTest, MovePageUpDownAndModifySelection) { textarea_->SetText(u"12\n34567 89"); textarea_->SetEditableSelectionRange(gfx::Range(6)); EXPECT_TRUE( textarea_->IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_PAGE_UP)); EXPECT_TRUE( textarea_->IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_PAGE_DOWN)); EXPECT_TRUE(textarea_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION)); EXPECT_TRUE(textarea_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION)); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_PAGE_UP); EXPECT_EQ(gfx::Range(0), textarea_->GetSelectedRange()); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_PAGE_DOWN); EXPECT_EQ(gfx::Range(11), textarea_->GetSelectedRange()); textarea_->SetEditableSelectionRange(gfx::Range(6)); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(6, 0), textarea_->GetSelectedRange()); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION); if (Textarea::kLineSelectionBehavior == gfx::SELECTION_EXTEND) EXPECT_EQ(gfx::Range(0, 11), textarea_->GetSelectedRange()); else EXPECT_EQ(gfx::Range(6, 11), textarea_->GetSelectedRange()); } // Ensure the textarea breaks the long word and scrolls on overflow. TEST_F(TextareaTest, OverflowTest) { const size_t count = 50U; textarea_->SetBounds(0, 0, 60, 40); textarea_->SetText(std::u16string(count, 'a')); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); textarea_->SetText(std::u16string(count, kHebrewLetterSamekh)); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); } TEST_F(TextareaTest, OverflowInRTLTest) { const size_t count = 50U; textarea_->SetBounds(0, 0, 60, 40); std::string locale = base::i18n::GetConfiguredLocale(); base::i18n::SetICUDefaultLocale("he"); textarea_->SetText(std::u16string(count, 'a')); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); textarea_->SetText(std::u16string(count, kHebrewLetterSamekh)); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); // Reset locale. base::i18n::SetICUDefaultLocale(locale); } TEST_F(TextareaTest, OnBlurTest) { const std::string& kText = "abcdef"; textarea_->SetText(base::ASCIIToUTF16(kText)); SendEndEvent(false); EXPECT_EQ(kText.size(), textarea_->GetCursorPosition()); // A focus loss should not change the cursor position. textarea_->OnBlur(); EXPECT_EQ(kText.size(), textarea_->GetCursorPosition()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textarea/textarea_unittest.cc
C++
unknown
10,322
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield.h" #include <algorithm> #include <set> #include <string> #include <utility> #include "base/auto_reset.h" #include "base/command_line.h" #include "base/functional/bind.h" #include "base/metrics/histogram_functions.h" #include "base/ranges/algorithm.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/base/cursor/cursor.h" #include "ui/base/data_transfer_policy/data_transfer_endpoint.h" #include "ui/base/default_style.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h" #include "ui/base/ime/constants.h" #include "ui/base/ime/input_method.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" #include "ui/base/ui_base_switches_util.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/compositor/canvas_painter.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/display/display.h" #include "ui/display/screen.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/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/selection_bound.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/background.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/focusable_border.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/controls/views_text_services_context_menu.h" #include "ui/views/drag_utils.h" #include "ui/views/layout/layout_provider.h" #include "ui/views/painter.h" #include "ui/views/style/platform_style.h" #include "ui/views/views_delegate.h" #include "ui/views/views_features.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" #if BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/base/ime/linux/text_edit_command_auralinux.h" #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/aura/window.h" #include "ui/wm/core/ime_util_chromeos.h" #endif #if BUILDFLAG(IS_MAC) #include "ui/base/cocoa/defaults_utils.h" #include "ui/base/cocoa/secure_password_input.h" #endif #if BUILDFLAG(IS_OZONE) #include "ui/ozone/public/ozone_platform.h" #include "ui/ozone/public/platform_gl_egl_utility.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/base/ime/ash/extension_ime_util.h" #include "ui/base/ime/ash/input_method_manager.h" #endif namespace views { namespace { using ::ui::mojom::DragOperation; // An enum giving different model properties unique keys for the // OnPropertyChanged call. enum TextfieldPropertyKey { kTextfieldText = 1, kTextfieldTextColor, kTextfieldSelectionTextColor, kTextfieldBackgroundColor, kTextfieldSelectionBackgroundColor, kTextfieldCursorEnabled, kTextfieldHorizontalAlignment, kTextfieldSelectedRange, }; // Returns the ui::TextEditCommand corresponding to the |command_id| menu // action. |has_selection| is true if the textfield has an active selection. // Keep in sync with UpdateContextMenu. ui::TextEditCommand GetTextEditCommandFromMenuCommand(int command_id, bool has_selection) { switch (command_id) { case Textfield::kUndo: return ui::TextEditCommand::UNDO; case Textfield::kCut: return ui::TextEditCommand::CUT; case Textfield::kCopy: return ui::TextEditCommand::COPY; case Textfield::kPaste: return ui::TextEditCommand::PASTE; case Textfield::kDelete: // The DELETE menu action only works in case of an active selection. if (has_selection) return ui::TextEditCommand::DELETE_FORWARD; break; case Textfield::kSelectAll: return ui::TextEditCommand::SELECT_ALL; case Textfield::kSelectWord: return ui::TextEditCommand::SELECT_WORD; } return ui::TextEditCommand::INVALID_COMMAND; } base::TimeDelta GetPasswordRevealDuration(const ui::KeyEvent& event) { // The key event may carries the property that indicates it was from the // virtual keyboard and mirroring is not occurring // In that case, reveal the password characters for 1 second. auto* properties = event.properties(); bool from_vk = properties && properties->find(ui::kPropertyFromVK) != properties->end(); if (from_vk) { std::vector<uint8_t> fromVKPropertyArray = properties->find(ui::kPropertyFromVK)->second; DCHECK_GT(fromVKPropertyArray.size(), ui::kPropertyFromVKIsMirroringIndex); uint8_t is_mirroring = fromVKPropertyArray[ui::kPropertyFromVKIsMirroringIndex]; if (!is_mirroring) return base::Seconds(1); } return base::TimeDelta(); } bool IsControlKeyModifier(int flags) { // XKB layout doesn't natively generate printable characters from a // Control-modified key combination, but we cannot extend it to other platforms // as Control has different meanings and behaviors. // https://crrev.com/2580483002/#msg46 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) return flags & ui::EF_CONTROL_DOWN; #else return false; #endif } bool IsValidCharToInsert(const char16_t& ch) { // Filter out all control characters, including tab and new line characters. return (ch >= 0x20 && ch < 0x7F) || ch > 0x9F; } bool CanUseTransparentBackgroundForDragImage() { #if BUILDFLAG(IS_OZONE) const auto* const egl_utility = ui::OzonePlatform::GetInstance()->GetPlatformGLEGLUtility(); return egl_utility ? egl_utility->IsTransparentBackgroundSupported() : false; #else // Other platforms allow this. return true; #endif } #if BUILDFLAG(IS_MAC) const float kAlmostTransparent = 1.0 / 255.0; const float kOpaque = 1.0; #endif } // namespace // static base::TimeDelta Textfield::GetCaretBlinkInterval() { #if BUILDFLAG(IS_WIN) static const size_t system_value = ::GetCaretBlinkTime(); if (system_value != 0) { return (system_value == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_value); } #elif BUILDFLAG(IS_MAC) // If there's insertion point flash rate info in NSUserDefaults, use the // blink period derived from that. absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #endif return base::Milliseconds(500); } // static const gfx::FontList& Textfield::GetDefaultFontList() { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); return rb.GetFontListWithDelta(ui::kLabelFontSizeDelta); } Textfield::Textfield() : model_(new TextfieldModel(this)), placeholder_text_draw_flags_(gfx::Canvas::DefaultCanvasTextAlignment()), selection_controller_(this) { set_context_menu_controller(this); set_drag_controller(this); auto cursor_view = std::make_unique<View>(); cursor_view->SetPaintToLayer(ui::LAYER_SOLID_COLOR); cursor_view->GetViewAccessibility().OverrideIsIgnored(true); cursor_view_ = AddChildView(std::move(cursor_view)); GetRenderText()->SetFontList(GetDefaultFontList()); UpdateBorder(); SetFocusBehavior(FocusBehavior::ALWAYS); views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(), GetCornerRadius()); FocusRing::Install(this); FocusRing::Get(this)->SetOutsetFocusRingDisabled(true); #if !BUILDFLAG(IS_MAC) // Do not map accelerators on Mac. E.g. They might not reflect custom // keybindings that a user has set. But also on Mac, these commands dispatch // via the "responder chain" when the OS searches through menu items in the // menu bar. The menu then sends e.g., a "cut:" command to NativeWidgetMac, // which will pass it to Textfield via OnKeyEvent() after associating the // correct edit command. // These allow BrowserView to pass edit commands from the Chrome menu to us // when we're focused by simply asking the FocusManager to // ProcessAccelerator() with the relevant accelerators. AddAccelerator(ui::Accelerator(ui::VKEY_X, ui::EF_CONTROL_DOWN)); AddAccelerator(ui::Accelerator(ui::VKEY_C, ui::EF_CONTROL_DOWN)); AddAccelerator(ui::Accelerator(ui::VKEY_V, ui::EF_CONTROL_DOWN)); #endif SetAccessibilityProperties(ax::mojom::Role::kTextField); // Sometimes there are additional ignored views, such as the View representing // the cursor, inside the text field. These should always be ignored by // accessibility since a plain text field should always be a leaf node in the // accessibility trees of all the platforms we support. GetViewAccessibility().OverrideIsLeaf(true); } Textfield::~Textfield() { if (GetInputMethod()) { // The textfield should have been blurred before destroy. DCHECK(this != GetInputMethod()->GetTextInputClient()); } } void Textfield::SetController(TextfieldController* controller) { controller_ = controller; } bool Textfield::GetReadOnly() const { return read_only_; } void Textfield::SetReadOnly(bool read_only) { if (read_only_ == read_only) return; // Update read-only without changing the focusable state (or active, etc.). read_only_ = read_only; if (GetInputMethod()) GetInputMethod()->OnTextInputTypeChanged(this); if (GetWidget()) { SetColor(GetTextColor()); UpdateBackgroundColor(); } OnPropertyChanged(&read_only_, kPropertyEffectsPaint); } void Textfield::SetTextInputType(ui::TextInputType type) { if (text_input_type_ == type) return; GetRenderText()->SetObscured(type == ui::TEXT_INPUT_TYPE_PASSWORD); text_input_type_ = type; if (GetInputMethod()) GetInputMethod()->OnTextInputTypeChanged(this); OnCaretBoundsChanged(); OnPropertyChanged(&text_input_type_, kPropertyEffectsPaint); } void Textfield::SetTextInputFlags(int flags) { if (text_input_flags_ == flags) return; text_input_flags_ = flags; OnPropertyChanged(&text_input_flags_, kPropertyEffectsNone); } const std::u16string& Textfield::GetText() const { return model_->text(); } void Textfield::SetText(const std::u16string& new_text) { SetTextWithoutCaretBoundsChangeNotification(new_text, new_text.length()); // The above call already notified for the text change; fire notifications // etc. for the cursor changes as well. UpdateAfterChange(TextChangeType::kNone, true); } void Textfield::SetTextWithoutCaretBoundsChangeNotification( const std::u16string& text, size_t cursor_position) { model_->SetText(text, cursor_position); UpdateAfterChange(TextChangeType::kInternal, false, false); } void Textfield::Scroll(const std::vector<size_t>& positions) { for (const auto position : positions) { model_->MoveCursorTo(position); GetRenderText()->GetUpdatedCursorBounds(); } } void Textfield::AppendText(const std::u16string& new_text) { if (new_text.empty()) return; model_->Append(new_text); UpdateAfterChange(TextChangeType::kInternal, false); } void Textfield::InsertOrReplaceText(const std::u16string& new_text) { if (new_text.empty()) return; model_->InsertText(new_text); UpdateAfterChange(TextChangeType::kUserTriggered, true); } std::u16string Textfield::GetSelectedText() const { return model_->GetSelectedText(); } void Textfield::SelectAll(bool reversed) { model_->SelectAll(reversed); if (HasSelection() && performing_user_action_) UpdateSelectionClipboard(); UpdateAfterChange(TextChangeType::kNone, true); } void Textfield::SelectWord() { model_->SelectWord(); if (HasSelection() && performing_user_action_) { UpdateSelectionClipboard(); } UpdateAfterChange(TextChangeType::kNone, true); } void Textfield::SelectWordAt(const gfx::Point& point) { model_->MoveCursorTo(point, false); model_->SelectWord(); UpdateAfterChange(TextChangeType::kNone, true); } void Textfield::ClearSelection() { model_->ClearSelection(); UpdateAfterChange(TextChangeType::kNone, true); } bool Textfield::HasSelection(bool primary_only) const { return model_->HasSelection(primary_only); } SkColor Textfield::GetTextColor() const { return text_color_.value_or(GetColorProvider()->GetColor( style::GetColorId(style::CONTEXT_TEXTFIELD, GetTextStyle()))); } void Textfield::SetTextColor(SkColor color) { text_color_ = color; if (GetWidget()) SetColor(color); } SkColor Textfield::GetBackgroundColor() const { return background_color_.value_or(GetColorProvider()->GetColor( GetReadOnly() || !GetEnabled() ? ui::kColorTextfieldBackgroundDisabled : ui::kColorTextfieldBackground)); } void Textfield::SetBackgroundColor(SkColor color) { background_color_ = color; if (GetWidget()) UpdateBackgroundColor(); } SkColor Textfield::GetSelectionTextColor() const { return selection_text_color_.value_or( GetColorProvider()->GetColor(ui::kColorTextfieldSelectionForeground)); } void Textfield::SetSelectionTextColor(SkColor color) { selection_text_color_ = color; UpdateSelectionTextColor(); } SkColor Textfield::GetSelectionBackgroundColor() const { return selection_background_color_.value_or( GetColorProvider()->GetColor(ui::kColorTextfieldSelectionBackground)); } void Textfield::SetSelectionBackgroundColor(SkColor color) { selection_background_color_ = color; UpdateSelectionBackgroundColor(); } bool Textfield::GetCursorEnabled() const { return GetRenderText()->cursor_enabled(); } void Textfield::SetCursorEnabled(bool enabled) { if (GetRenderText()->cursor_enabled() == enabled) return; GetRenderText()->SetCursorEnabled(enabled); UpdateAfterChange(TextChangeType::kNone, true, false); OnPropertyChanged(&model_ + kTextfieldCursorEnabled, kPropertyEffectsPaint); } const gfx::FontList& Textfield::GetFontList() const { return GetRenderText()->font_list(); } void Textfield::SetFontList(const gfx::FontList& font_list) { GetRenderText()->SetFontList(font_list); OnCaretBoundsChanged(); PreferredSizeChanged(); } void Textfield::SetDefaultWidthInChars(int default_width) { DCHECK_GE(default_width, 0); default_width_in_chars_ = default_width; } void Textfield::SetMinimumWidthInChars(int minimum_width) { DCHECK_GE(minimum_width, -1); minimum_width_in_chars_ = minimum_width; } std::u16string Textfield::GetPlaceholderText() const { return placeholder_text_; } void Textfield::SetPlaceholderText(const std::u16string& text) { if (placeholder_text_ == text) return; placeholder_text_ = text; OnPropertyChanged(&placeholder_text_, kPropertyEffectsPaint); } gfx::HorizontalAlignment Textfield::GetHorizontalAlignment() const { return GetRenderText()->horizontal_alignment(); } void Textfield::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { GetRenderText()->SetHorizontalAlignment(alignment); OnPropertyChanged(&model_ + kTextfieldHorizontalAlignment, kPropertyEffectsNone); } void Textfield::ShowVirtualKeyboardIfEnabled() { // GetInputMethod() may return nullptr in tests. if (GetEnabled() && !GetReadOnly() && GetInputMethod()) GetInputMethod()->SetVirtualKeyboardVisibilityIfEnabled(true); } bool Textfield::IsIMEComposing() const { return model_->HasCompositionText(); } const gfx::Range& Textfield::GetSelectedRange() const { return GetRenderText()->selection(); } void Textfield::SetSelectedRange(const gfx::Range& range) { model_->SelectRange(range); UpdateAfterChange(TextChangeType::kNone, true); OnPropertyChanged(&model_ + kTextfieldSelectedRange, kPropertyEffectsPaint); } void Textfield::AddSecondarySelectedRange(const gfx::Range& range) { model_->SelectRange(range, false); OnPropertyChanged(&model_ + kTextfieldSelectedRange, kPropertyEffectsPaint); } const gfx::SelectionModel& Textfield::GetSelectionModel() const { return GetRenderText()->selection_model(); } void Textfield::SelectSelectionModel(const gfx::SelectionModel& sel) { model_->SelectSelectionModel(sel); UpdateAfterChange(TextChangeType::kNone, true); } size_t Textfield::GetCursorPosition() const { return model_->GetCursorPosition(); } void Textfield::SetColor(SkColor value) { GetRenderText()->SetColor(value); cursor_view_->layer()->SetColor(value); OnPropertyChanged(&model_ + kTextfieldTextColor, kPropertyEffectsPaint); } void Textfield::ApplyColor(SkColor value, const gfx::Range& range) { GetRenderText()->ApplyColor(value, range); SchedulePaint(); } void Textfield::SetStyle(gfx::TextStyle style, bool value) { GetRenderText()->SetStyle(style, value); SchedulePaint(); } void Textfield::ApplyStyle(gfx::TextStyle style, bool value, const gfx::Range& range) { GetRenderText()->ApplyStyle(style, value, range); SchedulePaint(); } bool Textfield::GetInvalid() const { return invalid_; } void Textfield::SetInvalid(bool invalid) { if (invalid == invalid_) return; invalid_ = invalid; UpdateBorder(); if (FocusRing::Get(this)) FocusRing::Get(this)->SetInvalid(invalid); OnPropertyChanged(&invalid_, kPropertyEffectsNone); } void Textfield::ClearEditHistory() { model_->ClearEditHistory(); } void Textfield::SetObscuredGlyphSpacing(int spacing) { GetRenderText()->SetObscuredGlyphSpacing(spacing); } void Textfield::SetExtraInsets(const gfx::Insets& insets) { extra_insets_ = insets; UpdateBorder(); } void Textfield::FitToLocalBounds() { // Textfield insets include a reasonable amount of whitespace on all sides of // the default font list. Fallback fonts with larger heights may paint over // the vertical whitespace as needed. Alternate solutions involve undesirable // behavior like changing the default font size, shrinking some fallback fonts // beyond their legibility, or enlarging controls dynamically with content. gfx::Rect bounds = GetLocalBounds(); const gfx::Insets insets = GetInsets(); if (GetRenderText()->multiline()) { bounds.Inset(insets); } else { // The text will draw with the correct vertical alignment if we don't apply // the vertical insets. bounds.Inset(gfx::Insets::TLBR(0, insets.left(), 0, insets.right())); } bounds.set_x(GetMirroredXForRect(bounds)); GetRenderText()->SetDisplayRect(bounds); UpdateAfterChange(TextChangeType::kNone, true); } //////////////////////////////////////////////////////////////////////////////// // Textfield, View overrides: int Textfield::GetBaseline() const { return GetInsets().top() + GetRenderText()->GetBaseline(); } gfx::Size Textfield::CalculatePreferredSize() const { DCHECK_GE(default_width_in_chars_, minimum_width_in_chars_); return gfx::Size( CharsToDips(default_width_in_chars_), LayoutProvider::GetControlHeightForFont(style::CONTEXT_TEXTFIELD, GetTextStyle(), GetFontList())); } gfx::Size Textfield::GetMinimumSize() const { DCHECK_LE(minimum_width_in_chars_, default_width_in_chars_); gfx::Size minimum_size = View::GetMinimumSize(); if (minimum_width_in_chars_ >= 0) minimum_size.set_width(CharsToDips(minimum_width_in_chars_)); return minimum_size; } void Textfield::SetBorder(std::unique_ptr<Border> b) { FocusRing::Remove(this); View::SetBorder(std::move(b)); } ui::Cursor Textfield::GetCursor(const ui::MouseEvent& event) { bool platform_arrow = PlatformStyle::kTextfieldUsesDragCursorWhenDraggable; bool in_selection = GetRenderText()->IsPointInSelection(event.location()); bool drag_event = event.type() == ui::ET_MOUSE_DRAGGED; bool text_cursor = !initiating_drag_ && (drag_event || !in_selection || !platform_arrow); return text_cursor ? ui::mojom::CursorType::kIBeam : ui::Cursor(); } bool Textfield::OnMousePressed(const ui::MouseEvent& event) { const bool had_focus = HasFocus(); bool handled = controller_ && controller_->HandleMouseEvent(this, event); // If the controller triggered the focus, then record the focus reason as // other. if (!had_focus && HasFocus()) focus_reason_ = ui::TextInputClient::FOCUS_REASON_OTHER; if (!handled && (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton())) { if (!had_focus) RequestFocusWithPointer(ui::EventPointerType::kMouse); #if !BUILDFLAG(IS_WIN) ShowVirtualKeyboardIfEnabled(); #endif } if (ui::Clipboard::IsSupportedClipboardBuffer( ui::ClipboardBuffer::kSelection)) { if (!handled && !had_focus && event.IsOnlyMiddleMouseButton()) RequestFocusWithPointer(ui::EventPointerType::kMouse); } return selection_controller_.OnMousePressed( event, handled, had_focus ? SelectionController::InitialFocusStateOnMousePress::kFocused : SelectionController::InitialFocusStateOnMousePress::kUnFocused); } bool Textfield::OnMouseDragged(const ui::MouseEvent& event) { return selection_controller_.OnMouseDragged(event); } void Textfield::OnMouseReleased(const ui::MouseEvent& event) { if (controller_) controller_->HandleMouseEvent(this, event); selection_controller_.OnMouseReleased(event); } void Textfield::OnMouseCaptureLost() { selection_controller_.OnMouseCaptureLost(); } bool Textfield::OnMouseWheel(const ui::MouseWheelEvent& event) { return controller_ && controller_->HandleMouseEvent(this, event); } WordLookupClient* Textfield::GetWordLookupClient() { return this; } bool Textfield::OnKeyPressed(const ui::KeyEvent& event) { if (PreHandleKeyPressed(event)) return true; ui::TextEditCommand edit_command = scheduled_text_edit_command_; scheduled_text_edit_command_ = ui::TextEditCommand::INVALID_COMMAND; // Since HandleKeyEvent() might destroy |this|, get a weak pointer and verify // it isn't null before proceeding. base::WeakPtr<Textfield> textfield(weak_ptr_factory_.GetWeakPtr()); bool handled = controller_ && controller_->HandleKeyEvent(this, event); if (!textfield) return handled; #if BUILDFLAG(IS_LINUX) auto* linux_ui = ui::LinuxUi::instance(); std::vector<ui::TextEditCommandAuraLinux> commands; if (!handled && linux_ui && linux_ui->GetTextEditCommandsForEvent(event, &commands)) { for (const auto& command : commands) { if (IsTextEditCommandEnabled(command.command())) { ExecuteTextEditCommand(command.command()); handled = true; } } return handled; } #endif base::AutoReset<bool> show_rejection_ui(&show_rejection_ui_if_any_, true); if (edit_command == ui::TextEditCommand::INVALID_COMMAND) edit_command = GetCommandForKeyEvent(event); if (!handled && IsTextEditCommandEnabled(edit_command)) { ExecuteTextEditCommand(edit_command); handled = true; } return handled; } bool Textfield::OnKeyReleased(const ui::KeyEvent& event) { return controller_ && controller_->HandleKeyEvent(this, event); } void Textfield::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP: { RequestFocusForGesture(event->details()); if (controller_ && controller_->HandleGestureEvent(this, *event)) { selection_dragging_state_ = SelectionDraggingState::kNone; event->SetHandled(); return; } const size_t tap_pos = GetRenderText()->FindCursorPosition(event->location()).caret_pos(); const bool should_toggle_menu = event->details().tap_count() == 1 && GetSelectedRange() == gfx::Range(tap_pos); if (selection_dragging_state_ != SelectionDraggingState::kNone) { // Selection has already been set in the preceding ET_GESTURE_TAP_DOWN // event, so handles should be shown without changing the selection. // Just need to cancel selection dragging. selection_dragging_state_ = SelectionDraggingState::kNone; } else if (event->details().tap_count() == 1) { // If tap is on the selection and touch handles are not present, // handles should be shown without changing selection. Otherwise, // cursor should be moved to the tap location. if (touch_selection_controller_ || !GetRenderText()->IsPointInSelection(event->location())) { OnBeforeUserAction(); MoveCursorTo(event->location(), false); OnAfterUserAction(); } } else if (event->details().tap_count() == 2) { OnBeforeUserAction(); SelectWordAt(event->location()); OnAfterUserAction(); } else { OnBeforeUserAction(); SelectAll(false); OnAfterUserAction(); } CreateTouchSelectionControllerAndNotifyIt(); if (touch_selection_controller_ && should_toggle_menu) { touch_selection_controller_->ToggleQuickMenu(); } event->SetHandled(); break; } case ui::ET_GESTURE_TAP_DOWN: { if (::features::IsTouchTextEditingRedesignEnabled() && HasFocus()) { if (event->details().tap_down_count() == 2) { OnBeforeUserAction(); SelectWordAt(event->location()); OnAfterUserAction(); } else if (event->details().tap_down_count() == 3) { OnBeforeUserAction(); SelectAll(false); OnAfterUserAction(); } else { break; } DestroyTouchSelection(); selection_dragging_state_ = SelectionDraggingState::kDraggingSelectionExtent; event->SetHandled(); } break; } case ui::ET_GESTURE_LONG_PRESS: if (!GetRenderText()->IsPointInSelection(event->location())) { // If long-press happens outside selection, select word and try to // activate touch selection. OnBeforeUserAction(); SelectWordAt(event->location()); OnAfterUserAction(); CreateTouchSelectionControllerAndNotifyIt(); if (::features::IsTouchTextEditingRedesignEnabled()) { selection_dragging_state_ = SelectionDraggingState::kDraggingSelectionExtent; } // If touch selection activated successfully, mark event as handled // so that the regular context menu is not shown. if (touch_selection_controller_) event->SetHandled(); } else { // If long-press happens on the selection, deactivate touch // selection and try to initiate drag-drop. If drag-drop is not // enabled, context menu will be shown. Event is not marked as // handled to let Views handle drag-drop or context menu. DestroyTouchSelection(); initiating_drag_ = switches::IsTouchDragDropEnabled(); } break; case ui::ET_GESTURE_LONG_TAP: selection_dragging_state_ = SelectionDraggingState::kNone; // If touch selection is enabled, the context menu on long tap will be // shown by the |touch_selection_controller_|, hence we mark the event // handled so Views does not try to show context menu on it. if (touch_selection_controller_) event->SetHandled(); break; case ui::ET_GESTURE_SCROLL_BEGIN: if (HasFocus()) { if (::features::IsTouchTextEditingRedesignEnabled()) { MaybeStartSelectionDragging(event); } if (selection_dragging_state_ == SelectionDraggingState::kNone) { drag_start_location_x_ = event->location().x(); drag_start_display_offset_ = GetRenderText()->GetUpdatedDisplayOffset().x(); show_touch_handles_after_scroll_ = touch_selection_controller_ != nullptr; } else { show_touch_handles_after_scroll_ = true; } // Deactivate touch selection handles when scrolling or selection // dragging. DestroyTouchSelection(); event->SetHandled(); } break; case ui::ET_GESTURE_SCROLL_UPDATE: if (HasFocus()) { // Switch from selection dragging to default scrolling behaviour if // scroll update has multiple touch points. if (selection_dragging_state_ != SelectionDraggingState::kNone && event->details().touch_points() > 1) { selection_dragging_state_ = SelectionDraggingState::kNone; drag_start_location_x_ = event->location().x(); drag_start_display_offset_ = GetRenderText()->GetUpdatedDisplayOffset().x(); show_touch_handles_after_scroll_ = true; } switch (selection_dragging_state_) { case SelectionDraggingState::kDraggingSelectionExtent: MoveRangeSelectionExtent(event->location() + selection_dragging_offset_); break; case SelectionDraggingState::kDraggingCursor: MoveCursorTo(event->location(), false); break; case SelectionDraggingState::kNone: { int new_display_offset = drag_start_display_offset_ + event->location().x() - drag_start_location_x_; GetRenderText()->SetDisplayOffset(new_display_offset); SchedulePaint(); break; } } event->SetHandled(); } break; case ui::ET_GESTURE_SCROLL_END: case ui::ET_SCROLL_FLING_START: if (HasFocus()) { if (show_touch_handles_after_scroll_) { CreateTouchSelectionControllerAndNotifyIt(); show_touch_handles_after_scroll_ = false; } selection_dragging_state_ = SelectionDraggingState::kNone; event->SetHandled(); } break; case ui::ET_GESTURE_END: selection_dragging_state_ = SelectionDraggingState::kNone; break; default: return; } } // This function is called by BrowserView to execute clipboard commands. bool Textfield::AcceleratorPressed(const ui::Accelerator& accelerator) { ui::KeyEvent event( accelerator.key_state() == ui::Accelerator::KeyState::PRESSED ? ui::ET_KEY_PRESSED : ui::ET_KEY_RELEASED, accelerator.key_code(), accelerator.modifiers()); ExecuteTextEditCommand(GetCommandForKeyEvent(event)); return true; } bool Textfield::CanHandleAccelerators() const { return GetRenderText()->focused() && View::CanHandleAccelerators(); } void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) { SelectAll(false); } bool Textfield::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { #if BUILDFLAG(IS_LINUX) // Skip any accelerator handling that conflicts with custom keybindings. auto* linux_ui = ui::LinuxUi::instance(); std::vector<ui::TextEditCommandAuraLinux> commands; if (linux_ui && linux_ui->GetTextEditCommandsForEvent(event, &commands)) { const auto is_enabled = [this](const auto& command) { return IsTextEditCommandEnabled(command.command()); }; if (base::ranges::any_of(commands, is_enabled)) return true; } #endif // Skip backspace accelerator handling; editable textfields handle this key. // Also skip processing Windows [Alt]+<num-pad digit> Unicode alt-codes. const bool is_backspace = event.key_code() == ui::VKEY_BACK; return (is_backspace && !GetReadOnly()) || event.IsUnicodeKeyCode(); } bool Textfield::GetDropFormats( int* formats, std::set<ui::ClipboardFormatType>* format_types) { if (!GetEnabled() || GetReadOnly()) return false; // TODO(msw): Can we support URL, FILENAME, etc.? *formats = ui::OSExchangeData::STRING; if (controller_) controller_->AppendDropFormats(formats, format_types); return true; } bool Textfield::CanDrop(const OSExchangeData& data) { int formats; std::set<ui::ClipboardFormatType> format_types; GetDropFormats(&formats, &format_types); return GetEnabled() && !GetReadOnly() && data.HasAnyFormat(formats, format_types); } int Textfield::OnDragUpdated(const ui::DropTargetEvent& event) { DCHECK(CanDrop(event.data())); gfx::RenderText* render_text = GetRenderText(); const gfx::Range& selection = render_text->selection(); drop_cursor_position_ = render_text->FindCursorPosition(event.location()); bool in_selection = !selection.is_empty() && selection.Contains(gfx::Range(drop_cursor_position_.caret_pos())); drop_cursor_visible_ = !in_selection; // TODO(msw): Pan over text when the user drags to the visible text edge. OnCaretBoundsChanged(); SchedulePaint(); StopBlinkingCursor(); if (initiating_drag_) { if (in_selection) return ui::DragDropTypes::DRAG_NONE; return event.IsControlDown() ? ui::DragDropTypes::DRAG_COPY : ui::DragDropTypes::DRAG_MOVE; } return ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE; } void Textfield::OnDragExited() { drop_cursor_visible_ = false; if (ShouldBlinkCursor()) StartBlinkingCursor(); SchedulePaint(); } views::View::DropCallback Textfield::GetDropCallback( const ui::DropTargetEvent& event) { DCHECK(CanDrop(event.data())); drop_cursor_visible_ = false; if (controller_) { auto cb = controller_->CreateDropCallback(event); if (!cb.is_null()) return cb; } DCHECK(!initiating_drag_ || !GetRenderText()->IsPointInSelection(event.location())); return base::BindOnce(&Textfield::DropDraggedText, drop_weak_ptr_factory_.GetWeakPtr()); } void Textfield::OnDragDone() { initiating_drag_ = false; drop_cursor_visible_ = false; } void Textfield::GetAccessibleNodeData(ui::AXNodeData* node_data) { View::GetAccessibleNodeData(node_data); // Editable state indicates support of editable interface, and is always set // for a textfield, even if disabled or readonly. node_data->AddState(ax::mojom::State::kEditable); if (GetEnabled()) { node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kActivate); // Only readonly if enabled. Don't overwrite the disabled restriction. if (GetReadOnly()) node_data->SetRestriction(ax::mojom::Restriction::kReadOnly); } if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD) { node_data->AddState(ax::mojom::State::kProtected); node_data->SetValue(std::u16string( GetText().size(), gfx::RenderText::kPasswordReplacementChar)); } else { node_data->SetValue(GetText()); } node_data->AddStringAttribute(ax::mojom::StringAttribute::kPlaceholder, base::UTF16ToUTF8(GetPlaceholderText())); const gfx::Range range = GetSelectedRange(); node_data->AddIntAttribute(ax::mojom::IntAttribute::kTextSelStart, base::checked_cast<int32_t>(range.start())); node_data->AddIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, base::checked_cast<int32_t>(range.end())); } bool Textfield::HandleAccessibleAction(const ui::AXActionData& action_data) { if (action_data.action == ax::mojom::Action::kSetSelection) { DCHECK_EQ(action_data.anchor_node_id, action_data.focus_node_id); const gfx::Range range(static_cast<size_t>(action_data.anchor_offset), static_cast<size_t>(action_data.focus_offset)); return SetEditableSelectionRange(range); } // Remaining actions cannot be performed on readonly fields. if (GetReadOnly()) return View::HandleAccessibleAction(action_data); if (action_data.action == ax::mojom::Action::kSetValue) { SetText(base::UTF8ToUTF16(action_data.value)); ClearSelection(); return true; } else if (action_data.action == ax::mojom::Action::kReplaceSelectedText) { InsertOrReplaceText(base::UTF8ToUTF16(action_data.value)); ClearSelection(); return true; } return View::HandleAccessibleAction(action_data); } void Textfield::OnBoundsChanged(const gfx::Rect& previous_bounds) { FitToLocalBounds(); } bool Textfield::GetNeedsNotificationWhenVisibleBoundsChange() const { return true; } void Textfield::OnVisibleBoundsChanged() { if (touch_selection_controller_) touch_selection_controller_->SelectionChanged(); } void Textfield::OnPaint(gfx::Canvas* canvas) { OnPaintBackground(canvas); PaintTextAndCursor(canvas); OnPaintBorder(canvas); } void Textfield::OnFocus() { // Set focus reason if focused was gained without mouse or touch input. if (focus_reason_ == ui::TextInputClient::FOCUS_REASON_NONE) focus_reason_ = ui::TextInputClient::FOCUS_REASON_OTHER; #if BUILDFLAG(IS_MAC) if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD) password_input_enabler_ = std::make_unique<ui::ScopedPasswordInputEnabler>(); #endif // BUILDFLAG(IS_MAC) GetRenderText()->set_focused(true); if (GetInputMethod()) GetInputMethod()->SetFocusedTextInputClient(this); UpdateAfterChange(TextChangeType::kNone, true); View::OnFocus(); } void Textfield::OnBlur() { focus_reason_ = ui::TextInputClient::FOCUS_REASON_NONE; gfx::RenderText* render_text = GetRenderText(); render_text->set_focused(false); if (GetInputMethod()) { GetInputMethod()->DetachTextInputClient(this); #if BUILDFLAG(IS_CHROMEOS_ASH) wm::RestoreWindowBoundsOnClientFocusLost( GetNativeView()->GetToplevelWindow()); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } StopBlinkingCursor(); cursor_view_->SetVisible(false); DestroyTouchSelection(); SchedulePaint(); View::OnBlur(); #if BUILDFLAG(IS_MAC) password_input_enabler_.reset(); #endif // BUILDFLAG(IS_MAC) } gfx::Point Textfield::GetKeyboardContextMenuLocation() { return GetCaretBounds().bottom_right(); } void Textfield::OnThemeChanged() { View::OnThemeChanged(); gfx::RenderText* render_text = GetRenderText(); SetColor(GetTextColor()); UpdateBackgroundColor(); render_text->set_selection_color(GetSelectionTextColor()); render_text->set_selection_background_focused_color( GetSelectionBackgroundColor()); cursor_view_->layer()->SetColor(GetTextColor()); } //////////////////////////////////////////////////////////////////////////////// // Textfield, TextfieldModel::Delegate overrides: void Textfield::OnCompositionTextConfirmedOrCleared() { if (!skip_input_method_cancel_composition_) GetInputMethod()->CancelComposition(this); } void Textfield::OnTextChanged() { OnPropertyChanged(&model_ + kTextfieldText, kPropertyEffectsPaint); drop_weak_ptr_factory_.InvalidateWeakPtrs(); } //////////////////////////////////////////////////////////////////////////////// // Textfield, ContextMenuController overrides: void Textfield::ShowContextMenuForViewImpl(View* source, const gfx::Point& point, ui::MenuSourceType source_type) { UpdateContextMenu(); context_menu_runner_->RunMenuAt(GetWidget(), nullptr, gfx::Rect(point, gfx::Size()), MenuAnchorPosition::kTopLeft, source_type); } //////////////////////////////////////////////////////////////////////////////// // Textfield, DragController overrides: void Textfield::WriteDragDataForView(View* sender, const gfx::Point& press_pt, OSExchangeData* data) { const std::u16string& selected_text(GetSelectedText()); data->SetString(selected_text); Label label(selected_text, {GetFontList()}); label.SetBackgroundColor(GetBackgroundColor()); label.SetSubpixelRenderingEnabled(false); gfx::Size size(label.GetPreferredSize()); gfx::NativeView native_view = GetWidget()->GetNativeView(); display::Display display = display::Screen::GetScreen()->GetDisplayNearestView(native_view); size.SetToMin(gfx::Size(display.size().width(), height())); label.SetBoundsRect(gfx::Rect(size)); label.SetEnabledColor(GetTextColor()); SkBitmap bitmap; float raster_scale = ScaleFactorForDragFromWidget(GetWidget()); SkColor color = CanUseTransparentBackgroundForDragImage() ? SK_ColorTRANSPARENT : GetBackgroundColor(); label.Paint(PaintInfo::CreateRootPaintInfo( ui::CanvasPainter(&bitmap, label.size(), raster_scale, color, GetWidget()->GetCompositor()->is_pixel_canvas()) .context(), label.size())); constexpr gfx::Vector2d kOffset(-15, 0); gfx::ImageSkia image = gfx::ImageSkia::CreateFromBitmap(bitmap, raster_scale); data->provider().SetDragImage(image, kOffset); if (controller_) controller_->OnWriteDragData(data); } int Textfield::GetDragOperationsForView(View* sender, const gfx::Point& p) { int drag_operations = ui::DragDropTypes::DRAG_COPY; if (!GetEnabled() || text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD || !GetRenderText()->IsPointInSelection(p)) { drag_operations = ui::DragDropTypes::DRAG_NONE; } else if (sender == this && !GetReadOnly()) { drag_operations = ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY; } if (controller_) controller_->OnGetDragOperationsForTextfield(&drag_operations); return drag_operations; } bool Textfield::CanStartDragForView(View* sender, const gfx::Point& press_pt, const gfx::Point& p) { return initiating_drag_ && GetRenderText()->IsPointInSelection(press_pt); } //////////////////////////////////////////////////////////////////////////////// // Textfield, WordLookupClient overrides: bool Textfield::GetWordLookupDataAtPoint(const gfx::Point& point, gfx::DecoratedText* decorated_word, gfx::Point* baseline_point) { return GetRenderText()->GetWordLookupDataAtPoint(point, decorated_word, baseline_point); } bool Textfield::GetWordLookupDataFromSelection( gfx::DecoratedText* decorated_text, gfx::Point* baseline_point) { return GetRenderText()->GetLookupDataForRange(GetRenderText()->selection(), decorated_text, baseline_point); } //////////////////////////////////////////////////////////////////////////////// // Textfield, SelectionControllerDelegate overrides: bool Textfield::HasTextBeingDragged() const { return initiating_drag_; } //////////////////////////////////////////////////////////////////////////////// // Textfield, ui::TouchEditable overrides: void Textfield::MoveCaret(const gfx::Point& position) { SelectBetweenCoordinates(position, position); } void Textfield::MoveRangeSelectionExtent(const gfx::Point& extent) { if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) { return; } gfx::SelectionModel new_extent_caret = GetRenderText()->FindCursorPosition(extent); size_t new_extent_pos = new_extent_caret.caret_pos(); size_t extent_pos = extent_caret_.caret_pos(); if (new_extent_pos == extent_pos) { return; } gfx::SelectionModel base_caret = GetRenderText()->GetSelectionModelForSelectionStart(); size_t base_pos = base_caret.caret_pos(); size_t end_pos = new_extent_pos; gfx::LogicalCursorDirection cursor_direction = new_extent_pos > base_pos ? gfx::CURSOR_FORWARD : gfx::CURSOR_BACKWARD; bool selection_shrinking = cursor_direction == gfx::CURSOR_FORWARD ? new_extent_pos < extent_pos : new_extent_pos > extent_pos; gfx::Range word_range = GetRenderText()->ExpandRangeToWordBoundary(gfx::Range(extent_pos)); bool extent_moved_past_next_word_boundary = (cursor_direction == gfx::CURSOR_BACKWARD && new_extent_pos <= word_range.start()) || (cursor_direction == gfx::CURSOR_FORWARD && new_extent_pos >= word_range.end()); if (::features::IsTouchTextEditingRedesignEnabled()) { if (selection_shrinking) { break_type_ = gfx::CHARACTER_BREAK; } else if (extent_moved_past_next_word_boundary) { // Switch to using word breaks only after the selection has expanded past // a word boundary. This ensures that the selection can be adjusted by // character when adjusting within a word after the selection has shrunk. break_type_ = gfx::WORD_BREAK; } } if (break_type_ == gfx::WORD_BREAK) { // Compute the closest word boundary to the new extent position. gfx::Range new_word_range = GetRenderText()->ExpandRangeToWordBoundary(gfx::Range(new_extent_pos)); DCHECK(new_extent_pos >= new_word_range.start() && new_extent_pos <= new_word_range.end()); end_pos = new_extent_pos - new_word_range.start() < new_word_range.end() - new_extent_pos ? new_word_range.start() : new_word_range.end(); } gfx::SelectionModel selection(gfx::Range(base_pos, end_pos), cursor_direction); OnBeforeUserAction(); SelectSelectionModel(selection); OnAfterUserAction(); extent_caret_ = new_extent_caret; } void Textfield::SelectBetweenCoordinates(const gfx::Point& base, const gfx::Point& extent) { if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) { return; } gfx::SelectionModel base_caret = GetRenderText()->FindCursorPosition(base); gfx::SelectionModel extent_caret = GetRenderText()->FindCursorPosition(extent); gfx::SelectionModel selection( gfx::Range(base_caret.caret_pos(), extent_caret.caret_pos()), extent_caret.caret_affinity()); OnBeforeUserAction(); SelectSelectionModel(selection); OnAfterUserAction(); extent_caret_ = extent_caret; break_type_ = gfx::CHARACTER_BREAK; } void Textfield::GetSelectionEndPoints(gfx::SelectionBound* anchor, gfx::SelectionBound* focus) { gfx::RenderText* render_text = GetRenderText(); const gfx::SelectionModel& sel = render_text->selection_model(); gfx::SelectionModel start_sel = render_text->GetSelectionModelForSelectionStart(); gfx::Rect r1 = render_text->GetCursorBounds(start_sel, true); gfx::Rect r2 = render_text->GetCursorBounds(sel, true); anchor->SetEdge(gfx::PointF(r1.origin()), gfx::PointF(r1.bottom_left())); focus->SetEdge(gfx::PointF(r2.origin()), gfx::PointF(r2.bottom_left())); // Determine the SelectionBound's type for focus and anchor. // TODO(mfomitchev): Ideally we should have different logical directions for // start and end to support proper handle direction for mixed LTR/RTL text. const bool ltr = GetTextDirection() != base::i18n::RIGHT_TO_LEFT; size_t anchor_position_index = sel.selection().start(); size_t focus_position_index = sel.selection().end(); if (anchor_position_index == focus_position_index) { anchor->set_type(gfx::SelectionBound::CENTER); focus->set_type(gfx::SelectionBound::CENTER); } else if ((ltr && anchor_position_index < focus_position_index) || (!ltr && anchor_position_index > focus_position_index)) { anchor->set_type(gfx::SelectionBound::LEFT); focus->set_type(gfx::SelectionBound::RIGHT); } else { anchor->set_type(gfx::SelectionBound::RIGHT); focus->set_type(gfx::SelectionBound::LEFT); } } gfx::Rect Textfield::GetBounds() { return GetLocalBounds(); } gfx::NativeView Textfield::GetNativeView() const { return GetWidget()->GetNativeView(); } void Textfield::ConvertPointToScreen(gfx::Point* point) { View::ConvertPointToScreen(this, point); } void Textfield::ConvertPointFromScreen(gfx::Point* point) { View::ConvertPointFromScreen(this, point); } void Textfield::OpenContextMenu(const gfx::Point& anchor) { DestroyTouchSelection(); ShowContextMenu(anchor, ui::MENU_SOURCE_TOUCH_EDIT_MENU); } void Textfield::DestroyTouchSelection() { touch_selection_controller_.reset(); } //////////////////////////////////////////////////////////////////////////////// // Textfield, ui::SimpleMenuModel::Delegate overrides: bool Textfield::IsCommandIdChecked(int command_id) const { if (text_services_context_menu_ && text_services_context_menu_->SupportsCommand(command_id)) { return text_services_context_menu_->IsCommandIdChecked(command_id); } return true; } bool Textfield::IsCommandIdEnabled(int command_id) const { if (text_services_context_menu_ && text_services_context_menu_->SupportsCommand(command_id)) { return text_services_context_menu_->IsCommandIdEnabled(command_id); } return IsTextEditCommandEnabled( GetTextEditCommandFromMenuCommand(command_id, HasSelection())); } bool Textfield::GetAcceleratorForCommandId(int command_id, ui::Accelerator* accelerator) const { switch (command_id) { case kUndo: *accelerator = ui::Accelerator(ui::VKEY_Z, ui::EF_PLATFORM_ACCELERATOR); return true; case kCut: *accelerator = ui::Accelerator(ui::VKEY_X, ui::EF_PLATFORM_ACCELERATOR); return true; case kCopy: *accelerator = ui::Accelerator(ui::VKEY_C, ui::EF_PLATFORM_ACCELERATOR); return true; case kPaste: *accelerator = ui::Accelerator(ui::VKEY_V, ui::EF_PLATFORM_ACCELERATOR); return true; case kSelectAll: *accelerator = ui::Accelerator(ui::VKEY_A, ui::EF_PLATFORM_ACCELERATOR); return true; default: return text_services_context_menu_->GetAcceleratorForCommandId( command_id, accelerator); } } void Textfield::ExecuteCommand(int command_id, int event_flags) { if (text_services_context_menu_ && text_services_context_menu_->SupportsCommand(command_id)) { text_services_context_menu_->ExecuteCommand(command_id, event_flags); return; } Textfield::ExecuteTextEditCommand( GetTextEditCommandFromMenuCommand(command_id, HasSelection())); if (::features::IsTouchTextEditingRedesignEnabled() && (event_flags & ui::EF_FROM_TOUCH) && (command_id == Textfield::kSelectAll || command_id == Textfield::kSelectWord)) { CreateTouchSelectionControllerAndNotifyIt(); } } //////////////////////////////////////////////////////////////////////////////// // Textfield, ui::TextInputClient overrides: void Textfield::SetCompositionText(const ui::CompositionText& composition) { if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) return; OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; model_->SetCompositionText(composition); skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); } size_t Textfield::ConfirmCompositionText(bool keep_selection) { // TODO(b/134473433) Modify this function so that when keep_selection is // true, the selection is not changed when text committed if (keep_selection) { NOTIMPLEMENTED_LOG_ONCE(); } if (!model_->HasCompositionText()) return 0; OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; const size_t confirmed_text_length = model_->ConfirmCompositionText(); skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); return confirmed_text_length; } void Textfield::ClearCompositionText() { if (!model_->HasCompositionText()) return; OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; model_->CancelCompositionText(); skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); } void Textfield::InsertText(const std::u16string& new_text, InsertTextCursorBehavior cursor_behavior) { std::u16string filtered_new_text; base::ranges::copy_if(new_text, std::back_inserter(filtered_new_text), IsValidCharToInsert); if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE || filtered_new_text.empty()) return; // TODO(crbug.com/1155331): Handle |cursor_behavior| correctly. OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; model_->InsertText(filtered_new_text); skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); } void Textfield::InsertChar(const ui::KeyEvent& event) { if (GetReadOnly()) { OnEditFailed(); return; } // Filter all invalid chars and all characters with Alt modifier (and Search // on ChromeOS, Ctrl on Linux). But allow characters with the AltGr modifier. // On Windows AltGr is represented by Alt+Ctrl or Right Alt, and on Linux it's // a different flag that we don't care about. const char16_t ch = event.GetCharacter(); const bool should_insert_char = IsValidCharToInsert(ch) && !ui::IsSystemKeyModifier(event.flags()) && !IsControlKeyModifier(event.flags()); if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE || !should_insert_char) return; DoInsertChar(ch); if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD) { password_char_reveal_index_ = absl::nullopt; base::TimeDelta duration = GetPasswordRevealDuration(event); if (!duration.is_zero()) { const size_t change_offset = model_->GetCursorPosition(); DCHECK_GT(change_offset, 0u); RevealPasswordChar(change_offset - 1, duration); } } } ui::TextInputType Textfield::GetTextInputType() const { if (GetReadOnly() || !GetEnabled()) return ui::TEXT_INPUT_TYPE_NONE; return text_input_type_; } ui::TextInputMode Textfield::GetTextInputMode() const { return ui::TEXT_INPUT_MODE_DEFAULT; } base::i18n::TextDirection Textfield::GetTextDirection() const { return GetRenderText()->GetDisplayTextDirection(); } int Textfield::GetTextInputFlags() const { return text_input_flags_; } bool Textfield::CanComposeInline() const { return true; } // TODO(mbid): GetCaretBounds is const but calls // RenderText::GetUpdatedCursorBounds, which is not const and in fact mutates // internal state. (Is it at least logically const?) Violation of const // correctness? gfx::Rect Textfield::GetCaretBounds() const { gfx::Rect rect = GetRenderText()->GetUpdatedCursorBounds(); ConvertRectToScreen(this, &rect); return rect; } gfx::Rect Textfield::GetSelectionBoundingBox() const { NOTIMPLEMENTED_LOG_ONCE(); return gfx::Rect(); } bool Textfield::GetCompositionCharacterBounds(size_t index, gfx::Rect* rect) const { DCHECK(rect); if (!HasCompositionText()) return false; gfx::Range composition_range; model_->GetCompositionTextRange(&composition_range); DCHECK(!composition_range.is_empty()); size_t text_index = composition_range.start() + index; if (composition_range.end() <= text_index) return false; gfx::RenderText* render_text = GetRenderText(); if (!render_text->IsValidCursorIndex(text_index)) { text_index = render_text->IndexOfAdjacentGrapheme(text_index, gfx::CURSOR_BACKWARD); } if (text_index < composition_range.start()) return false; const gfx::SelectionModel caret(text_index, gfx::CURSOR_BACKWARD); *rect = render_text->GetCursorBounds(caret, false); ConvertRectToScreen(this, rect); return true; } bool Textfield::HasCompositionText() const { return model_->HasCompositionText(); } ui::TextInputClient::FocusReason Textfield::GetFocusReason() const { return focus_reason_; } bool Textfield::GetTextRange(gfx::Range* range) const { if (!ImeEditingAllowed()) return false; model_->GetTextRange(range); return true; } bool Textfield::GetCompositionTextRange(gfx::Range* range) const { if (!ImeEditingAllowed()) return false; model_->GetCompositionTextRange(range); return true; } bool Textfield::GetEditableSelectionRange(gfx::Range* range) const { if (!ImeEditingAllowed()) return false; *range = GetRenderText()->selection(); return true; } bool Textfield::SetEditableSelectionRange(const gfx::Range& range) { if (!ImeEditingAllowed() || !range.IsValid()) return false; OnBeforeUserAction(); SetSelectedRange(range); OnAfterUserAction(); return true; } bool Textfield::DeleteRange(const gfx::Range& range) { if (!ImeEditingAllowed() || range.is_empty()) return false; OnBeforeUserAction(); model_->SelectRange(range); if (model_->HasSelection()) { model_->DeleteSelection(); UpdateAfterChange(TextChangeType::kUserTriggered, true); } OnAfterUserAction(); return true; } bool Textfield::GetTextFromRange(const gfx::Range& range, std::u16string* range_text) const { if (!ImeEditingAllowed() || !range.IsValid()) return false; gfx::Range text_range; if (!GetTextRange(&text_range) || !range.IsBoundedBy(text_range)) return false; *range_text = model_->GetTextFromRange(range); return true; } void Textfield::OnInputMethodChanged() {} bool Textfield::ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) { DCHECK_NE(direction, base::i18n::UNKNOWN_DIRECTION); // Restore text directionality mode when the indicated direction matches the // current forced mode; otherwise, force the mode indicated. This helps users // manage BiDi text layout without getting stuck in forced LTR or RTL modes. const bool default_rtl = direction == base::i18n::RIGHT_TO_LEFT; const auto new_mode = default_rtl ? gfx::DIRECTIONALITY_FORCE_RTL : gfx::DIRECTIONALITY_FORCE_LTR; auto* render_text = GetRenderText(); const bool modes_match = new_mode == render_text->directionality_mode(); render_text->SetDirectionalityMode(modes_match ? gfx::DIRECTIONALITY_FROM_TEXT : new_mode); // Do not reset horizontal alignment to left/right if it has been set to // center, or if it depends on the text direction and that direction has not // been modified. bool dir_from_text = modes_match && GetHorizontalAlignment() == gfx::ALIGN_TO_HEAD; if (!dir_from_text && GetHorizontalAlignment() != gfx::ALIGN_CENTER) SetHorizontalAlignment(default_rtl ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT); SchedulePaint(); return true; } void Textfield::ExtendSelectionAndDelete(size_t before, size_t after) { gfx::Range range = GetRenderText()->selection(); // Discard out-of-bound operations. // TODO(crbug.com/1344096): this is a temporary fix to prevent the // checked_cast failure in gfx::Range. There does not seem to be any // observable bad behaviors before checked_cast was added. However, range // clipping or dropping should be the last resort because a checkfail // indicates that we run into bad states somewhere earlier on the stack. if (range.start() < before) return; range.set_start(range.start() - before); range.set_end(range.end() + after); gfx::Range text_range; if (GetTextRange(&text_range) && text_range.Contains(range)) DeleteRange(range); } void Textfield::EnsureCaretNotInRect(const gfx::Rect& rect_in_screen) { #if BUILDFLAG(IS_CHROMEOS_ASH) aura::Window* top_level_window = GetNativeView()->GetToplevelWindow(); wm::EnsureWindowNotInRect(top_level_window, rect_in_screen); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } bool Textfield::IsTextEditCommandEnabled(ui::TextEditCommand command) const { std::u16string result; bool editable = !GetReadOnly(); bool readable = text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD; switch (command) { case ui::TextEditCommand::DELETE_BACKWARD: case ui::TextEditCommand::DELETE_FORWARD: case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE: case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH: case ui::TextEditCommand::DELETE_TO_END_OF_LINE: case ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH: case ui::TextEditCommand::DELETE_WORD_BACKWARD: case ui::TextEditCommand::DELETE_WORD_FORWARD: return editable; case ui::TextEditCommand::MOVE_BACKWARD: case ui::TextEditCommand::MOVE_BACKWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_FORWARD: case ui::TextEditCommand::MOVE_FORWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_LEFT: case ui::TextEditCommand::MOVE_LEFT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_RIGHT: case ui::TextEditCommand::MOVE_RIGHT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT: case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE: case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_PARAGRAPH: case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_PARAGRAPH_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT: case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_END_OF_LINE: case ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH: case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_WORD_BACKWARD: case ui::TextEditCommand::MOVE_WORD_BACKWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_WORD_FORWARD: case ui::TextEditCommand::MOVE_WORD_FORWARD_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_WORD_LEFT: case ui::TextEditCommand::MOVE_WORD_LEFT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_WORD_RIGHT: case ui::TextEditCommand::MOVE_WORD_RIGHT_AND_MODIFY_SELECTION: return true; case ui::TextEditCommand::UNDO: return editable && model_->CanUndo(); case ui::TextEditCommand::REDO: return editable && model_->CanRedo(); case ui::TextEditCommand::CUT: return editable && readable && HasSelection(); case ui::TextEditCommand::COPY: return readable && HasSelection(); case ui::TextEditCommand::PASTE: { ui::DataTransferEndpoint data_dst(ui::EndpointType::kDefault, show_rejection_ui_if_any_); ui::Clipboard::GetForCurrentThread()->ReadText( ui::ClipboardBuffer::kCopyPaste, &data_dst, &result); } return editable && !result.empty(); case ui::TextEditCommand::SELECT_ALL: return !GetText().empty() && GetSelectedRange().length() != GetText().length(); case ui::TextEditCommand::SELECT_WORD: return readable && !GetText().empty() && !HasSelection(); case ui::TextEditCommand::TRANSPOSE: return editable && !HasSelection() && !model_->HasCompositionText(); case ui::TextEditCommand::YANK: return editable; case ui::TextEditCommand::MOVE_DOWN: case ui::TextEditCommand::MOVE_DOWN_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PAGE_DOWN: case ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_PAGE_UP: case ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_UP: case ui::TextEditCommand::MOVE_UP_AND_MODIFY_SELECTION: case ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT: case ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT: case ui::TextEditCommand::SCROLL_PAGE_DOWN: case ui::TextEditCommand::SCROLL_PAGE_UP: // On Mac, the textfield should respond to Up/Down arrows keys and // PageUp/PageDown. #if BUILDFLAG(IS_MAC) return true; #else return GetRenderText()->multiline(); #endif case ui::TextEditCommand::INSERT_TEXT: case ui::TextEditCommand::SET_MARK: case ui::TextEditCommand::UNSELECT: case ui::TextEditCommand::INVALID_COMMAND: return false; } NOTREACHED_NORETURN(); } void Textfield::SetTextEditCommandForNextKeyEvent(ui::TextEditCommand command) { DCHECK_EQ(ui::TextEditCommand::INVALID_COMMAND, scheduled_text_edit_command_); scheduled_text_edit_command_ = command; } ukm::SourceId Textfield::GetClientSourceForMetrics() const { // TODO(shend): Implement this method. NOTIMPLEMENTED_LOG_ONCE(); return ukm::SourceId(); } bool Textfield::ShouldDoLearning() { if (should_do_learning_.has_value()) return should_do_learning_.value(); NOTIMPLEMENTED_LOG_ONCE(); DVLOG(1) << "This Textfield instance does not support ShouldDoLearning"; return false; } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // TODO(https://crbug.com/952355): Implement this method to support Korean IME // reconversion feature on native text fields (e.g. find bar). bool Textfield::SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) { // TODO(https://crbug.com/952355): Support custom text spans. DCHECK(!model_->HasCompositionText()); OnBeforeUserAction(); model_->SetCompositionFromExistingText(range); SchedulePaint(); OnAfterUserAction(); return true; } #endif #if BUILDFLAG(IS_CHROMEOS) gfx::Range Textfield::GetAutocorrectRange() const { return model_->autocorrect_range(); } gfx::Rect Textfield::GetAutocorrectCharacterBounds() const { gfx::Range autocorrect_range = model_->autocorrect_range(); if (autocorrect_range.is_empty()) return gfx::Rect(); gfx::RenderText* render_text = GetRenderText(); const gfx::SelectionModel caret(autocorrect_range, gfx::CURSOR_BACKWARD); gfx::Rect rect; rect = render_text->GetCursorBounds(caret, false); ConvertRectToScreen(this, &rect); return rect; } bool Textfield::SetAutocorrectRange(const gfx::Range& range) { if (!range.is_empty()) { base::UmaHistogramEnumeration("InputMethod.Assistive.Autocorrect.Count", TextInputClient::SubClass::kTextField); #if BUILDFLAG(IS_CHROMEOS_ASH) auto* input_method_manager = ash::input_method::InputMethodManager::Get(); if (input_method_manager && ash::extension_ime_util::IsExperimentalMultilingual( input_method_manager->GetActiveIMEState() ->GetCurrentInputMethod() .id())) { base::UmaHistogramEnumeration( "InputMethod.MultilingualExperiment.Autocorrect.Count", TextInputClient::SubClass::kTextField); } #endif } return model_->SetAutocorrectRange(range); } bool Textfield::AddGrammarFragments( const std::vector<ui::GrammarFragment>& fragments) { if (!fragments.empty()) { base::UmaHistogramEnumeration("InputMethod.Assistive.Grammar.Count", TextInputClient::SubClass::kTextField); } // TODO(crbug/1201454): Implement this method for CrOS Grammar. NOTIMPLEMENTED_LOG_ONCE(); return false; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS) void Textfield::GetActiveTextInputControlLayoutBounds( absl::optional<gfx::Rect>* control_bounds, absl::optional<gfx::Rect>* selection_bounds) { gfx::Rect origin = GetContentsBounds(); ConvertRectToScreen(this, &origin); *control_bounds = origin; } #endif #if BUILDFLAG(IS_WIN) // TODO(https://crbug.com/952355): Implement this method once TSF supports // reconversion features on native text fields. void Textfield::SetActiveCompositionForAccessibility( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) {} #endif //////////////////////////////////////////////////////////////////////////////// // Textfield, protected: void Textfield::DoInsertChar(char16_t ch) { OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; model_->InsertChar(ch); skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); } gfx::RenderText* Textfield::GetRenderText() const { return model_->render_text(); } gfx::Point Textfield::GetLastClickRootLocation() const { return selection_controller_.last_click_root_location(); } std::u16string Textfield::GetSelectionClipboardText() const { std::u16string selection_clipboard_text; ui::Clipboard::GetForCurrentThread()->ReadText( ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr, &selection_clipboard_text); return selection_clipboard_text; } void Textfield::ExecuteTextEditCommand(ui::TextEditCommand command) { DestroyTouchSelection(); // We only execute the commands enabled in Textfield::IsTextEditCommandEnabled // below. Hence don't do a virtual IsTextEditCommandEnabled call. if (!IsTextEditCommandEnabled(command)) return; OnBeforeUserAction(); gfx::SelectionModel selection_model = GetSelectionModel(); auto [text_changed, cursor_changed] = DoExecuteTextEditCommand(command); cursor_changed |= (GetSelectionModel() != selection_model); if (cursor_changed && HasSelection()) UpdateSelectionClipboard(); UpdateAfterChange( text_changed ? TextChangeType::kUserTriggered : TextChangeType::kNone, cursor_changed); OnAfterUserAction(); } Textfield::EditCommandResult Textfield::DoExecuteTextEditCommand( ui::TextEditCommand command) { bool changed = false; bool cursor_changed = false; bool add_to_kill_buffer = false; base::AutoReset<bool> show_rejection_ui(&show_rejection_ui_if_any_, true); // Some codepaths may bypass GetCommandForKeyEvent, so any selection-dependent // modifications of the command should happen here. switch (command) { case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE: case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH: case ui::TextEditCommand::DELETE_TO_END_OF_LINE: case ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH: add_to_kill_buffer = text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD; [[fallthrough]]; case ui::TextEditCommand::DELETE_WORD_BACKWARD: case ui::TextEditCommand::DELETE_WORD_FORWARD: if (HasSelection()) command = ui::TextEditCommand::DELETE_FORWARD; break; default: break; } bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; gfx::VisualCursorDirection begin = rtl ? gfx::CURSOR_RIGHT : gfx::CURSOR_LEFT; gfx::VisualCursorDirection end = rtl ? gfx::CURSOR_LEFT : gfx::CURSOR_RIGHT; switch (command) { case ui::TextEditCommand::DELETE_BACKWARD: changed = cursor_changed = model_->Backspace(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_FORWARD: changed = cursor_changed = model_->Delete(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE: model_->MoveCursor(gfx::LINE_BREAK, begin, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Backspace(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH: model_->MoveCursor(gfx::FIELD_BREAK, begin, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Backspace(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_TO_END_OF_LINE: model_->MoveCursor(gfx::LINE_BREAK, end, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Delete(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH: model_->MoveCursor(gfx::FIELD_BREAK, end, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Delete(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_WORD_BACKWARD: model_->MoveCursor(gfx::WORD_BREAK, begin, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Backspace(add_to_kill_buffer); break; case ui::TextEditCommand::DELETE_WORD_FORWARD: model_->MoveCursor(gfx::WORD_BREAK, end, gfx::SELECTION_RETAIN); changed = cursor_changed = model_->Delete(add_to_kill_buffer); break; case ui::TextEditCommand::MOVE_BACKWARD: model_->MoveCursor(gfx::CHARACTER_BREAK, begin, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_BACKWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::CHARACTER_BREAK, begin, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_FORWARD: model_->MoveCursor(gfx::CHARACTER_BREAK, end, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_FORWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::CHARACTER_BREAK, end, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_LEFT: model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_LEFT_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_RIGHT: model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_RIGHT_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE: model_->MoveCursor(gfx::LINE_BREAK, begin, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT: case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_PARAGRAPH: case ui::TextEditCommand::MOVE_UP: case ui::TextEditCommand::MOVE_PAGE_UP: case ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT: case ui::TextEditCommand::SCROLL_PAGE_UP: model_->MoveCursor(gfx::FIELD_BREAK, begin, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::LINE_BREAK, begin, kLineSelectionBehavior); break; case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_PARAGRAPH_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, begin, kLineSelectionBehavior); break; case ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_UP_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, begin, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_TO_END_OF_LINE: model_->MoveCursor(gfx::LINE_BREAK, end, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT: case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH: case ui::TextEditCommand::MOVE_DOWN: case ui::TextEditCommand::MOVE_PAGE_DOWN: case ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT: case ui::TextEditCommand::SCROLL_PAGE_DOWN: model_->MoveCursor(gfx::FIELD_BREAK, end, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::LINE_BREAK, end, kLineSelectionBehavior); break; case ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_TO_END_OF_PARAGRAPH_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, end, kLineSelectionBehavior); break; case ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION: case ui::TextEditCommand::MOVE_DOWN_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, end, gfx::SELECTION_RETAIN); break; case ui::TextEditCommand::MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, begin, kMoveParagraphSelectionBehavior); break; case ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::FIELD_BREAK, end, kMoveParagraphSelectionBehavior); break; case ui::TextEditCommand::MOVE_WORD_BACKWARD: model_->MoveCursor(gfx::WORD_BREAK, begin, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_WORD_BACKWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::WORD_BREAK, begin, kWordSelectionBehavior); break; case ui::TextEditCommand::MOVE_WORD_FORWARD: model_->MoveCursor(gfx::WORD_BREAK, end, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_WORD_FORWARD_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::WORD_BREAK, end, kWordSelectionBehavior); break; case ui::TextEditCommand::MOVE_WORD_LEFT: model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_WORD_LEFT_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, kWordSelectionBehavior); break; case ui::TextEditCommand::MOVE_WORD_RIGHT: model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); break; case ui::TextEditCommand::MOVE_WORD_RIGHT_AND_MODIFY_SELECTION: model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, kWordSelectionBehavior); break; case ui::TextEditCommand::UNDO: changed = cursor_changed = model_->Undo(); break; case ui::TextEditCommand::REDO: changed = cursor_changed = model_->Redo(); break; case ui::TextEditCommand::CUT: changed = cursor_changed = Cut(); break; case ui::TextEditCommand::COPY: Copy(); break; case ui::TextEditCommand::PASTE: changed = cursor_changed = Paste(); break; case ui::TextEditCommand::SELECT_ALL: SelectAll(false); break; case ui::TextEditCommand::SELECT_WORD: SelectWord(); break; case ui::TextEditCommand::TRANSPOSE: changed = cursor_changed = model_->Transpose(); break; case ui::TextEditCommand::YANK: changed = cursor_changed = model_->Yank(); break; case ui::TextEditCommand::INSERT_TEXT: case ui::TextEditCommand::SET_MARK: case ui::TextEditCommand::UNSELECT: case ui::TextEditCommand::INVALID_COMMAND: NOTREACHED_NORETURN(); } return {changed, cursor_changed}; } void Textfield::OffsetDoubleClickWord(size_t offset) { selection_controller_.OffsetDoubleClickWord(offset); } bool Textfield::IsDropCursorForInsertion() const { return true; } bool Textfield::ShouldShowPlaceholderText() const { return GetText().empty() && !GetPlaceholderText().empty(); } void Textfield::RequestFocusWithPointer(ui::EventPointerType pointer_type) { if (HasFocus()) return; switch (pointer_type) { case ui::EventPointerType::kMouse: focus_reason_ = ui::TextInputClient::FOCUS_REASON_MOUSE; break; case ui::EventPointerType::kPen: focus_reason_ = ui::TextInputClient::FOCUS_REASON_PEN; break; case ui::EventPointerType::kTouch: focus_reason_ = ui::TextInputClient::FOCUS_REASON_TOUCH; break; default: focus_reason_ = ui::TextInputClient::FOCUS_REASON_OTHER; break; } View::RequestFocus(); } void Textfield::RequestFocusForGesture(const ui::GestureEventDetails& details) { bool show_virtual_keyboard = true; #if BUILDFLAG(IS_WIN) show_virtual_keyboard = details.primary_pointer_type() == ui::EventPointerType::kTouch || details.primary_pointer_type() == ui::EventPointerType::kPen; #endif RequestFocusWithPointer(details.primary_pointer_type()); if (show_virtual_keyboard) ShowVirtualKeyboardIfEnabled(); } base::CallbackListSubscription Textfield::AddTextChangedCallback( views::PropertyChangedCallback callback) { return AddPropertyChangedCallback(&model_ + kTextfieldText, std::move(callback)); } bool Textfield::PreHandleKeyPressed(const ui::KeyEvent& event) { return false; } ui::TextEditCommand Textfield::GetCommandForKeyEvent( const ui::KeyEvent& event) { if (event.type() != ui::ET_KEY_PRESSED || event.IsUnicodeKeyCode()) return ui::TextEditCommand::INVALID_COMMAND; const bool shift = event.IsShiftDown(); #if BUILDFLAG(IS_MAC) const bool command = event.IsCommandDown(); #endif const bool control = event.IsControlDown() || event.IsCommandDown(); const bool alt = event.IsAltDown() || event.IsAltGrDown(); switch (event.key_code()) { case ui::VKEY_Z: if (control && !shift && !alt) return ui::TextEditCommand::UNDO; return (control && shift && !alt) ? ui::TextEditCommand::REDO : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_Y: return (control && !alt) ? ui::TextEditCommand::REDO : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_A: return (control && !alt) ? ui::TextEditCommand::SELECT_ALL : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_X: return (control && !alt) ? ui::TextEditCommand::CUT : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_C: return (control && !alt) ? ui::TextEditCommand::COPY : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_V: return (control && !alt) ? ui::TextEditCommand::PASTE : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_RIGHT: // Ignore alt+right, which may be a browser navigation shortcut. if (alt) return ui::TextEditCommand::INVALID_COMMAND; if (!shift) { return control ? ui::TextEditCommand::MOVE_WORD_RIGHT : ui::TextEditCommand::MOVE_RIGHT; } return control ? ui::TextEditCommand::MOVE_WORD_RIGHT_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_RIGHT_AND_MODIFY_SELECTION; case ui::VKEY_LEFT: // Ignore alt+left, which may be a browser navigation shortcut. if (alt) return ui::TextEditCommand::INVALID_COMMAND; if (!shift) { return control ? ui::TextEditCommand::MOVE_WORD_LEFT : ui::TextEditCommand::MOVE_LEFT; } return control ? ui::TextEditCommand::MOVE_WORD_LEFT_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_LEFT_AND_MODIFY_SELECTION; case ui::VKEY_HOME: if (shift) { return ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION; } #if BUILDFLAG(IS_MAC) return ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT; #else return ui::TextEditCommand::MOVE_TO_BEGINNING_OF_LINE; #endif case ui::VKEY_END: if (shift) return ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION; #if BUILDFLAG(IS_MAC) return ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT; #else return ui::TextEditCommand::MOVE_TO_END_OF_LINE; #endif case ui::VKEY_UP: #if BUILDFLAG(IS_MAC) if (control && shift) { return ui::TextEditCommand:: MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION; } if (command) return ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT; return shift ? ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_UP; #else return shift ? ui::TextEditCommand:: MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION : ui::TextEditCommand::INVALID_COMMAND; #endif case ui::VKEY_DOWN: #if BUILDFLAG(IS_MAC) if (control && shift) { return ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION; } if (command) return ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT; return shift ? ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION : ui::TextEditCommand::MOVE_DOWN; #else return shift ? ui::TextEditCommand::MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION : ui::TextEditCommand::INVALID_COMMAND; #endif case ui::VKEY_BACK: if (!control) { #if BUILDFLAG(IS_WIN) if (alt) return shift ? ui::TextEditCommand::REDO : ui::TextEditCommand::UNDO; #endif return ui::TextEditCommand::DELETE_BACKWARD; } #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Only erase by line break on Linux and ChromeOS. if (shift) return ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE; #endif return ui::TextEditCommand::DELETE_WORD_BACKWARD; case ui::VKEY_DELETE: #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Only erase by line break on Linux and ChromeOS. if (shift && control) return ui::TextEditCommand::DELETE_TO_END_OF_LINE; #endif if (control) return ui::TextEditCommand::DELETE_WORD_FORWARD; return shift ? ui::TextEditCommand::CUT : ui::TextEditCommand::DELETE_FORWARD; case ui::VKEY_INSERT: if (control && !shift) return ui::TextEditCommand::COPY; return (shift && !control) ? ui::TextEditCommand::PASTE : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_PRIOR: return control ? ui::TextEditCommand::SCROLL_PAGE_UP : ui::TextEditCommand::INVALID_COMMAND; case ui::VKEY_NEXT: return control ? ui::TextEditCommand::SCROLL_PAGE_DOWN : ui::TextEditCommand::INVALID_COMMAND; default: return ui::TextEditCommand::INVALID_COMMAND; } } //////////////////////////////////////////////////////////////////////////////// // Textfield, private: //////////////////////////////////////////////////////////////////////////////// // Textfield, SelectionControllerDelegate overrides: gfx::RenderText* Textfield::GetRenderTextForSelectionController() { return GetRenderText(); } bool Textfield::IsReadOnly() const { return GetReadOnly(); } bool Textfield::SupportsDrag() const { return true; } void Textfield::SetTextBeingDragged(bool value) { initiating_drag_ = value; } int Textfield::GetViewHeight() const { return height(); } int Textfield::GetViewWidth() const { return width(); } int Textfield::GetDragSelectionDelay() const { if (ui::ScopedAnimationDurationScaleMode::duration_multiplier() == ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION) { // NON_ZERO_DURATION is 1/20 by default, but we want 1/100 here. return 1; } return ui::ScopedAnimationDurationScaleMode::duration_multiplier() * 100; } void Textfield::OnBeforePointerAction() { OnBeforeUserAction(); if (model_->HasCompositionText()) model_->ConfirmCompositionText(); } void Textfield::OnAfterPointerAction(bool text_changed, bool selection_changed) { OnAfterUserAction(); const auto text_change_type = text_changed ? TextChangeType::kUserTriggered : TextChangeType::kNone; UpdateAfterChange(text_change_type, selection_changed); } bool Textfield::PasteSelectionClipboard() { DCHECK(performing_user_action_); DCHECK(!GetReadOnly()); const std::u16string selection_clipboard_text = GetSelectionClipboardText(); if (selection_clipboard_text.empty()) return false; model_->InsertText(selection_clipboard_text); return true; } void Textfield::UpdateSelectionClipboard() { if (ui::Clipboard::IsSupportedClipboardBuffer( ui::ClipboardBuffer::kSelection)) { if (text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD) { ui::ScopedClipboardWriter(ui::ClipboardBuffer::kSelection) .WriteText(GetSelectedText()); if (controller_) controller_->OnAfterCutOrCopy(ui::ClipboardBuffer::kSelection); } } } void Textfield::UpdateBackgroundColor() { const SkColor color = GetBackgroundColor(); SetBackground(CreateBackgroundFromPainter( Painter::CreateSolidRoundRectPainter(color, GetCornerRadius()))); // Disable subpixel rendering when the background color is not opaque because // it draws incorrect colors around the glyphs in that case. // See crbug.com/115198 GetRenderText()->set_subpixel_rendering_suppressed(SkColorGetA(color) != SK_AlphaOPAQUE); OnPropertyChanged(&model_ + kTextfieldBackgroundColor, kPropertyEffectsPaint); } void Textfield::UpdateBorder() { auto border = std::make_unique<views::FocusableBorder>(); const LayoutProvider* provider = LayoutProvider::Get(); border->SetColorId(ui::kColorTextfieldOutline); border->SetInsets(gfx::Insets::TLBR( extra_insets_.top() + provider->GetDistanceMetric(DISTANCE_CONTROL_VERTICAL_TEXT_PADDING), extra_insets_.left() + provider->GetDistanceMetric( DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING), extra_insets_.bottom() + provider->GetDistanceMetric(DISTANCE_CONTROL_VERTICAL_TEXT_PADDING), extra_insets_.right() + provider->GetDistanceMetric( DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING))); if (invalid_) { border->SetColorId(ui::kColorTextfieldInvalidOutline); } else if (!GetEnabled() || GetReadOnly()) { border->SetColorId(ui::kColorTextfieldDisabledOutline); } border->SetCornerRadius(GetCornerRadius()); View::SetBorder(std::move(border)); } void Textfield::UpdateSelectionTextColor() { GetRenderText()->set_selection_color(GetSelectionTextColor()); OnPropertyChanged(&model_ + kTextfieldSelectionTextColor, kPropertyEffectsPaint); } void Textfield::UpdateSelectionBackgroundColor() { GetRenderText()->set_selection_background_focused_color( GetSelectionBackgroundColor()); OnPropertyChanged(&model_ + kTextfieldSelectionBackgroundColor, kPropertyEffectsPaint); } void Textfield::UpdateAfterChange( TextChangeType text_change_type, bool cursor_changed, absl::optional<bool> notify_caret_bounds_changed) { if (text_change_type != TextChangeType::kNone) { if ((text_change_type == TextChangeType::kUserTriggered) && controller_) controller_->ContentsChanged(this, GetText()); NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true); } if (cursor_changed) { UpdateCursorViewPosition(); UpdateCursorVisibility(); } const bool anything_changed = (text_change_type != TextChangeType::kNone) || cursor_changed; if (notify_caret_bounds_changed.value_or(anything_changed)) OnCaretBoundsChanged(); if (anything_changed) SchedulePaint(); } void Textfield::UpdateCursorVisibility() { cursor_view_->SetVisible(ShouldShowCursor()); #if BUILDFLAG(IS_MAC) // If we called SetVisible(true) above we want the cursor layer to be opaque. // If we called SetVisible(false), making the layer opaque has no effect on // its visibility. cursor_view_->layer()->SetOpacity(kOpaque); #endif if (ShouldBlinkCursor()) StartBlinkingCursor(); else StopBlinkingCursor(); } gfx::Rect Textfield::CalculateCursorViewBounds() const { gfx::Rect location(GetRenderText()->GetUpdatedCursorBounds()); location.set_x(GetMirroredXForRect(location)); return location; } void Textfield::UpdateCursorViewPosition() { cursor_view_->SetBoundsRect(CalculateCursorViewBounds()); } int Textfield::GetTextStyle() const { if (GetReadOnly() || !GetEnabled()) { return style::STYLE_DISABLED; } else if (GetInvalid()) { return style::STYLE_INVALID; } else { return style::STYLE_PRIMARY; } } void Textfield::PaintTextAndCursor(gfx::Canvas* canvas) { TRACE_EVENT0("views", "Textfield::PaintTextAndCursor"); canvas->Save(); // Draw placeholder text if needed. gfx::RenderText* render_text = GetRenderText(); if (ShouldShowPlaceholderText()) { // Disable subpixel rendering when the background color is not opaque // because it draws incorrect colors around the glyphs in that case. // See crbug.com/786343 int placeholder_text_draw_flags = placeholder_text_draw_flags_; if (SkColorGetA(GetBackgroundColor()) != SK_AlphaOPAQUE) placeholder_text_draw_flags |= gfx::Canvas::NO_SUBPIXEL_RENDERING; canvas->DrawStringRectWithFlags( GetPlaceholderText(), placeholder_font_list_.value_or(GetFontList()), placeholder_text_color_.value_or( GetColorProvider()->GetColor(style::GetColorId( style::CONTEXT_TEXTFIELD_PLACEHOLDER, GetInvalid() ? style::STYLE_INVALID : style::STYLE_PRIMARY))), render_text->display_rect(), placeholder_text_draw_flags); } // If drop cursor is active, draw |render_text| with its text selected. const bool select_all = drop_cursor_visible_ && !IsDropCursorForInsertion(); render_text->Draw(canvas, select_all); if (drop_cursor_visible_ && IsDropCursorForInsertion()) { // Draw a drop cursor that marks where the text will be dropped/inserted. canvas->FillRect(render_text->GetCursorBounds(drop_cursor_position_, true), GetTextColor()); } canvas->Restore(); } void Textfield::MoveCursorTo(const gfx::Point& point, bool select) { if (model_->MoveCursorTo(point, select)) UpdateAfterChange(TextChangeType::kNone, true); } void Textfield::OnCaretBoundsChanged() { if (GetInputMethod()) GetInputMethod()->OnCaretBoundsChanged(this); if (touch_selection_controller_) touch_selection_controller_->SelectionChanged(); // Screen reader users don't expect notifications about unfocused textfields. if (HasFocus()) NotifyAccessibilityEvent(ax::mojom::Event::kTextSelectionChanged, true); UpdateCursorViewPosition(); } void Textfield::OnBeforeUserAction() { DCHECK(!performing_user_action_); performing_user_action_ = true; if (controller_) controller_->OnBeforeUserAction(this); } void Textfield::OnAfterUserAction() { if (controller_) controller_->OnAfterUserAction(this); DCHECK(performing_user_action_); performing_user_action_ = false; } bool Textfield::Cut() { if (!GetReadOnly() && text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD && model_->Cut()) { if (controller_) controller_->OnAfterCutOrCopy(ui::ClipboardBuffer::kCopyPaste); return true; } return false; } bool Textfield::Copy() { if (text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD && model_->Copy()) { if (controller_) controller_->OnAfterCutOrCopy(ui::ClipboardBuffer::kCopyPaste); return true; } return false; } bool Textfield::Paste() { if (!GetReadOnly() && model_->Paste()) { if (controller_) controller_->OnAfterPaste(); return true; } return false; } void Textfield::UpdateContextMenu() { // TextfieldController may modify Textfield's menu, so the menu should be // recreated each time it's shown. Destroy the existing objects in the reverse // order of creation. context_menu_runner_.reset(); context_menu_contents_.reset(); context_menu_contents_ = std::make_unique<ui::SimpleMenuModel>(this); context_menu_contents_->AddItemWithStringId(kUndo, IDS_APP_UNDO); context_menu_contents_->AddSeparator(ui::NORMAL_SEPARATOR); context_menu_contents_->AddItemWithStringId(kCut, IDS_APP_CUT); context_menu_contents_->AddItemWithStringId(kCopy, IDS_APP_COPY); context_menu_contents_->AddItemWithStringId(kPaste, IDS_APP_PASTE); context_menu_contents_->AddItemWithStringId(kDelete, IDS_APP_DELETE); context_menu_contents_->AddSeparator(ui::NORMAL_SEPARATOR); context_menu_contents_->AddItemWithStringId(kSelectAll, IDS_APP_SELECT_ALL); // If the controller adds menu commands, also override ExecuteCommand() and // IsCommandIdEnabled() as appropriate, for the commands added. if (controller_) controller_->UpdateContextMenu(context_menu_contents_.get()); text_services_context_menu_ = ViewsTextServicesContextMenu::Create(context_menu_contents_.get(), this); context_menu_runner_ = std::make_unique<MenuRunner>( context_menu_contents_.get(), MenuRunner::HAS_MNEMONICS | MenuRunner::CONTEXT_MENU); } bool Textfield::ImeEditingAllowed() const { // Disallow input method editing of password fields. ui::TextInputType t = GetTextInputType(); return (t != ui::TEXT_INPUT_TYPE_NONE && t != ui::TEXT_INPUT_TYPE_PASSWORD); } void Textfield::RevealPasswordChar(absl::optional<size_t> index, base::TimeDelta duration) { GetRenderText()->SetObscuredRevealIndex(index); SchedulePaint(); password_char_reveal_index_ = index; UpdateCursorViewPosition(); if (index.has_value()) { password_reveal_timer_.Start(FROM_HERE, duration, base::BindOnce(&Textfield::RevealPasswordChar, weak_ptr_factory_.GetWeakPtr(), absl::nullopt, duration)); } } void Textfield::CreateTouchSelectionControllerAndNotifyIt() { if (!HasFocus()) return; if (!touch_selection_controller_) { touch_selection_controller_.reset( ui::TouchEditingControllerDeprecated::Create(this)); } if (touch_selection_controller_) touch_selection_controller_->SelectionChanged(); } void Textfield::OnEditFailed() { PlatformStyle::OnTextfieldEditFailed(); } bool Textfield::ShouldShowCursor() const { // Show the cursor when the primary selected range is empty; secondary // selections do not affect cursor visibility. // TODO(crbug.com/1434319): The cursor will be entirely hidden if partially // occluded. It would be better if only the occluded part is hidden. return HasFocus() && !HasSelection(true) && GetEnabled() && !GetReadOnly() && !drop_cursor_visible_ && GetRenderText()->cursor_enabled() && GetLocalBounds().Contains(cursor_view_->bounds()); } int Textfield::CharsToDips(int width_in_chars) const { // Use a subset of the conditions in ShouldShowCursor() that are unlikely to // change dynamically. Dynamic changes can result in glitchy-looking visual // effects like find boxes on different tabs being 1 DIP different width. const int cursor_width = (!GetReadOnly() && GetRenderText()->cursor_enabled()) ? 1 : 0; return GetFontList().GetExpectedTextWidth(width_in_chars) + cursor_width + GetInsets().width(); } bool Textfield::ShouldBlinkCursor() const { return ShouldShowCursor() && !Textfield::GetCaretBlinkInterval().is_zero(); } void Textfield::StartBlinkingCursor() { DCHECK(ShouldBlinkCursor()); cursor_blink_timer_.Start(FROM_HERE, Textfield::GetCaretBlinkInterval(), this, &Textfield::OnCursorBlinkTimerFired); } void Textfield::StopBlinkingCursor() { cursor_blink_timer_.Stop(); } void Textfield::OnCursorBlinkTimerFired() { DCHECK(ShouldBlinkCursor()); // TODO(crbug.com/1294712): The cursor position is not updated appropriately // when locale changes from a left-to-right script to a right-to-left script. // Thus the cursor is displayed at a wrong position immediately after the // locale change. As a band-aid solution, we update the cursor here, so that // the cursor can be at the wrong position only up until the next blink. It // would be better to detect locale change explicitly (how?) and update // there. UpdateCursorViewPosition(); #if BUILDFLAG(IS_MAC) // https://crbug.com/1311416 . The cursor is a solid color Layer which we make // flash by toggling the Layer's visibility. A bug in the CARendererLayerTree // causes all Layers that come after the cursor in the Layer tree (the // bookmarks bar, for example) to be pushed to the screen with each // appearance and disappearance of the cursor, consuming unnecessary CPU in // the window server. The same also happens if we leave the cursor visible // but make its color or layer 100% transparent (there's an optimization // somewhere that removes completely transparent layers from the hierarchy). // Until this bug is fixed, flash the cursor by alternating the cursor // layer's opacity between opaque and "almost" transparent. Once // https://crbug.com/1313999 is fixed, this Mac-specific code and its tests // can be removed. float new_opacity = cursor_view_->layer()->opacity() != kOpaque ? kOpaque : kAlmostTransparent; cursor_view_->layer()->SetOpacity(new_opacity); #else cursor_view_->SetVisible(!cursor_view_->GetVisible()); #endif } void Textfield::OnEnabledChanged() { if (GetInputMethod()) GetInputMethod()->OnTextInputTypeChanged(this); } void Textfield::DropDraggedText( const ui::DropTargetEvent& event, ui::mojom::DragOperation& output_drag_op, std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) { DCHECK(CanDrop(event.data())); gfx::RenderText* render_text = GetRenderText(); OnBeforeUserAction(); skip_input_method_cancel_composition_ = true; gfx::SelectionModel drop_destination_model = render_text->FindCursorPosition(event.location()); std::u16string new_text; event.data().GetString(&new_text); // Delete the current selection for a drag and drop within this view. const bool move = initiating_drag_ && !event.IsControlDown() && event.source_operations() & ui::DragDropTypes::DRAG_MOVE; if (move) { // Adjust the drop destination if it is on or after the current selection. size_t pos = drop_destination_model.caret_pos(); pos -= render_text->selection().Intersect(gfx::Range(0, pos)).length(); model_->DeletePrimarySelectionAndInsertTextAt(new_text, pos); } else { model_->MoveCursorTo(drop_destination_model); // Drop always inserts text even if the textfield is not in insert mode. model_->InsertText(new_text); } skip_input_method_cancel_composition_ = false; UpdateAfterChange(TextChangeType::kUserTriggered, true); OnAfterUserAction(); output_drag_op = move ? DragOperation::kMove : DragOperation::kCopy; } float Textfield::GetCornerRadius() { return LayoutProvider::Get()->GetCornerRadiusMetric( ShapeContextTokens::kTextfieldRadius, size()); } void Textfield::MaybeStartSelectionDragging(ui::GestureEvent* event) { DCHECK_EQ(event->type(), ui::ET_GESTURE_SCROLL_BEGIN); // Only start selection dragging if scrolling with one touch point. if (event->details().touch_points() > 1) { selection_dragging_state_ = SelectionDraggingState::kNone; return; } const float delta_x = event->details().scroll_x_hint(); const float delta_y = event->details().scroll_y_hint(); if (selection_dragging_state_ == SelectionDraggingState::kDraggingSelectionExtent) { gfx::RenderText* render_text = GetRenderText(); gfx::SelectionModel start_sel = render_text->GetSelectionModelForSelectionStart(); const gfx::SelectionModel& sel = render_text->selection_model(); gfx::Point selection_start = render_text->GetCursorBounds(start_sel, true).CenterPoint(); gfx::Point selection_end = render_text->GetCursorBounds(sel, true).CenterPoint(); gfx::LogicalCursorDirection drag_direction = gfx::CURSOR_FORWARD; if (std::fabs(delta_y) > std::fabs(delta_x)) { // If the initial dragging motion is up/down, extend the // selection backwards/forwards. drag_direction = delta_y < 0 ? gfx::CURSOR_BACKWARD : gfx::CURSOR_FORWARD; } else { // Otherwise, extend the selection in the direction of // horizontal movement. drag_direction = delta_x * (selection_end.x() - selection_start.x()) < 0 ? gfx::CURSOR_BACKWARD : gfx::CURSOR_FORWARD; } gfx::Point base = drag_direction == gfx::CURSOR_FORWARD ? selection_start : selection_end; gfx::Point extent = drag_direction == gfx::CURSOR_FORWARD ? selection_end : selection_start; SelectBetweenCoordinates(base, extent); selection_dragging_offset_ = extent - event->location(); } else if (std::fabs(delta_x) >= std::fabs(delta_y)) { // Use the scroll sequence for cursor placement if it begins in a // horizontal direction and is not already being used for dragging // the selection. selection_dragging_state_ = SelectionDraggingState::kDraggingCursor; } } BEGIN_METADATA(Textfield, View) ADD_PROPERTY_METADATA(bool, ReadOnly) ADD_PROPERTY_METADATA(std::u16string, Text) ADD_PROPERTY_METADATA(ui::TextInputType, TextInputType) ADD_PROPERTY_METADATA(int, TextInputFlags) ADD_PROPERTY_METADATA(SkColor, TextColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(SkColor, SelectionTextColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(SkColor, BackgroundColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(SkColor, SelectionBackgroundColor, ui::metadata::SkColorConverter) ADD_PROPERTY_METADATA(bool, CursorEnabled) ADD_PROPERTY_METADATA(std::u16string, PlaceholderText) ADD_PROPERTY_METADATA(bool, Invalid) ADD_PROPERTY_METADATA(gfx::HorizontalAlignment, HorizontalAlignment) ADD_PROPERTY_METADATA(gfx::Range, SelectedRange) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield.cc
C++
unknown
106,060
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_ #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_ #include <stddef.h> #include <stdint.h> #include <memory> #include <set> #include <string> #include <utility> #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/ime/text_edit_commands.h" #include "ui/base/ime/text_input_client.h" #include "ui/base/ime/text_input_type.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/pointer/touch_editing_controller.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/events/gesture_event_details.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/range/range.h" #include "ui/gfx/selection_model.h" #include "ui/gfx/text_constants.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/textfield/textfield_model.h" #include "ui/views/drag_controller.h" #include "ui/views/metadata/view_factory.h" #include "ui/views/selection_controller.h" #include "ui/views/selection_controller_delegate.h" #include "ui/views/view.h" #include "ui/views/word_lookup_client.h" #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) #include <vector> #endif namespace base { class TimeDelta; } #if BUILDFLAG(IS_MAC) namespace ui { class ScopedPasswordInputEnabler; } #endif // BUILDFLAG(IS_MAC) namespace views { class MenuRunner; class TextfieldController; class ViewsTextServicesContextMenu; // A views/skia textfield implementation. No platform-specific code is used. class VIEWS_EXPORT Textfield : public View, public TextfieldModel::Delegate, public ContextMenuController, public DragController, public WordLookupClient, public SelectionControllerDelegate, public ui::TouchEditable, public ui::TextInputClient { public: METADATA_HEADER(Textfield); enum MenuCommands { kUndo = kLastTouchEditableCommandId + 1, kDelete, kLastCommandId = kDelete, }; #if BUILDFLAG(IS_MAC) static constexpr gfx::SelectionBehavior kLineSelectionBehavior = gfx::SELECTION_EXTEND; static constexpr gfx::SelectionBehavior kWordSelectionBehavior = gfx::SELECTION_CARET; static constexpr gfx::SelectionBehavior kMoveParagraphSelectionBehavior = gfx::SELECTION_CARET; static constexpr gfx::SelectionBehavior kPageSelectionBehavior = gfx::SELECTION_EXTEND; #else static constexpr gfx::SelectionBehavior kLineSelectionBehavior = gfx::SELECTION_RETAIN; static constexpr gfx::SelectionBehavior kWordSelectionBehavior = gfx::SELECTION_RETAIN; static constexpr gfx::SelectionBehavior kMoveParagraphSelectionBehavior = gfx::SELECTION_RETAIN; static constexpr gfx::SelectionBehavior kPageSelectionBehavior = gfx::SELECTION_RETAIN; #endif // Pair of |text_changed|, |cursor_changed|. using EditCommandResult = std::pair<bool, bool>; // Returns the text cursor blink time, or 0 for no blinking. static base::TimeDelta GetCaretBlinkInterval(); // Returns the default FontList used by all textfields. static const gfx::FontList& GetDefaultFontList(); Textfield(); Textfield(const Textfield&) = delete; Textfield& operator=(const Textfield&) = delete; ~Textfield() override; // Set the controller for this textfield. void set_controller(TextfieldController* controller) { controller_ = controller; } // TODD (kylixrd): Remove set_controller and refactor codebase. void SetController(TextfieldController* controller); // Gets/Sets whether or not the Textfield is read-only. bool GetReadOnly() const; void SetReadOnly(bool read_only); // Sets the input type; displays only asterisks for TEXT_INPUT_TYPE_PASSWORD. void SetTextInputType(ui::TextInputType type); // Sets the input flags so that the system input methods can turn on/off some // features. The flags is the bit map of ui::TextInputFlags. void SetTextInputFlags(int flags); // Gets the text for the Textfield. // NOTE: Call sites should take care to not reveal the text for a password // textfield. const std::u16string& GetText() const; // Sets the text currently displayed in the Textfield. void SetText(const std::u16string& new_text); // Sets the text currently displayed in the Textfield and the cursor position. // Does not fire notifications about the caret bounds changing. This is // intended for low-level use, where callers need precise control over what // notifications are fired when, e.g. to avoid firing duplicate accessibility // notifications, which can cause issues for accessibility tools. Updating the // selection or cursor separately afterwards does not update the edit history, // i.e. the cursor position after redoing this change will be determined by // |cursor_position| and not by subsequent calls to e.g. SetSelectedRange(). void SetTextWithoutCaretBoundsChangeNotification(const std::u16string& text, size_t cursor_position); // Scrolls all of |scroll_positions| into view, if possible. For each // position, the minimum scrolling change necessary to just bring the position // into view is applied. |scroll_positions| are applied in order, so later // positions will have priority over earlier positions if not all can be // visible simultaneously. // NOTE: Unlike MoveCursorTo(), this will not fire any accessibility // notifications. void Scroll(const std::vector<size_t>& scroll_positions); // Appends the given string to the previously-existing text in the field. void AppendText(const std::u16string& new_text); // Inserts |new_text| at the cursor position, replacing any selected text. // This method is used to handle user input via paths Textfield doesn't // normally handle, so it calls UpdateAfterChange() and notifies observers of // changes. void InsertOrReplaceText(const std::u16string& new_text); // Returns the text that is currently selected. // NOTE: Call sites should take care to not reveal the text for a password // textfield. std::u16string GetSelectedText() const; // Select the entire text range. If |reversed| is true, the range will end at // the logical beginning of the text; this generally shows the leading portion // of text that overflows its display area. void SelectAll(bool reversed); // Selects the word at which the cursor is currently positioned. If there is a // non-empty selection, the selection bounds are extended to their nearest // word boundaries. void SelectWord(); // A convenience method to select the word closest to |point|. void SelectWordAt(const gfx::Point& point); // Clears the selection within the edit field and sets the caret to the end. void ClearSelection(); // Checks if there is any selected text. |primary_only| indicates whether // secondary selections should also be considered. bool HasSelection(bool primary_only = false) const; // Gets/sets the text color to be used when painting the Textfield. SkColor GetTextColor() const; void SetTextColor(SkColor color); // Gets/sets the background color to be used when painting the Textfield. SkColor GetBackgroundColor() const; void SetBackgroundColor(SkColor color); // Gets/sets the selection text color to be used when painting the Textfield. SkColor GetSelectionTextColor() const; void SetSelectionTextColor(SkColor color); // Gets/sets the selection background color to be used when painting the // Textfield. SkColor GetSelectionBackgroundColor() const; void SetSelectionBackgroundColor(SkColor color); // Gets/Sets whether or not the cursor is enabled. bool GetCursorEnabled() const; void SetCursorEnabled(bool enabled); // Gets/Sets the fonts used when rendering the text within the Textfield. const gfx::FontList& GetFontList() const; void SetFontList(const gfx::FontList& font_list); // Sets the default width of the text control. See default_width_in_chars_. void SetDefaultWidthInChars(int default_width); // Sets the minimum width of the text control. See minimum_width_in_chars_. void SetMinimumWidthInChars(int minimum_width); // Gets/Sets the text to display when empty. std::u16string GetPlaceholderText() const; void SetPlaceholderText(const std::u16string& text); void set_placeholder_text_color(SkColor color) { placeholder_text_color_ = color; } void set_placeholder_font_list(const gfx::FontList& font_list) { placeholder_font_list_ = font_list; } int placeholder_text_draw_flags() const { return placeholder_text_draw_flags_; } void set_placeholder_text_draw_flags(int flags) { placeholder_text_draw_flags_ = flags; } bool force_text_directionality() const { return force_text_directionality_; } void set_force_text_directionality(bool force) { force_text_directionality_ = force; } bool drop_cursor_visible() const { return drop_cursor_visible_; } // Gets/Sets whether to indicate the textfield has invalid content. bool GetInvalid() const; void SetInvalid(bool invalid); // Get or set the horizontal alignment used for the button from the underlying // RenderText object. gfx::HorizontalAlignment GetHorizontalAlignment() const; void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); // Displays a virtual keyboard or alternate input view if enabled. void ShowVirtualKeyboardIfEnabled(); // Returns whether or not an IME is composing text. bool IsIMEComposing() const; // Gets the selected logical text range. const gfx::Range& GetSelectedRange() const; // Selects the specified logical text range. void SetSelectedRange(const gfx::Range& range); // Without clearing the current selected range, adds |range| as an additional // selection. // NOTE: Unlike SetSelectedRange(), this will not fire any accessibility // notifications. void AddSecondarySelectedRange(const gfx::Range& range); // Gets the text selection model. const gfx::SelectionModel& GetSelectionModel() const; // Sets the specified text selection model. void SelectSelectionModel(const gfx::SelectionModel& sel); // Returns the current cursor position. size_t GetCursorPosition() const; // Set the text color over the entire text or a logical character range. // Empty and invalid ranges are ignored. void SetColor(SkColor value); void ApplyColor(SkColor value, const gfx::Range& range); // Set various text styles over the entire text or a logical character range. // The respective |style| is applied if |value| is true, or removed if false. // Empty and invalid ranges are ignored. void SetStyle(gfx::TextStyle style, bool value); void ApplyStyle(gfx::TextStyle style, bool value, const gfx::Range& range); // Clears Edit history. void ClearEditHistory(); // Set extra spacing placed between glyphs; used for obscured text styling. void SetObscuredGlyphSpacing(int spacing); absl::optional<size_t> GetPasswordCharRevealIndex() const { return password_char_reveal_index_; } void SetExtraInsets(const gfx::Insets& insets); // Fits the textfield to the local bounds, applying internal padding and // updating the cursor position and visibility. void FitToLocalBounds(); // View overrides: int GetBaseline() const override; gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; void SetBorder(std::unique_ptr<Border> b) override; ui::Cursor GetCursor(const ui::MouseEvent& event) override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void OnMouseCaptureLost() override; bool OnMouseWheel(const ui::MouseWheelEvent& event) override; WordLookupClient* GetWordLookupClient() override; void OnGestureEvent(ui::GestureEvent* event) override; bool AcceleratorPressed(const ui::Accelerator& accelerator) override; bool CanHandleAccelerators() const override; void AboutToRequestFocusFromTabTraversal(bool reverse) override; bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override; bool GetDropFormats(int* formats, std::set<ui::ClipboardFormatType>* format_types) override; bool CanDrop(const ui::OSExchangeData& data) override; int OnDragUpdated(const ui::DropTargetEvent& event) override; void OnDragExited() override; views::View::DropCallback GetDropCallback( const ui::DropTargetEvent& event) override; void OnDragDone() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; void OnBoundsChanged(const gfx::Rect& previous_bounds) override; bool GetNeedsNotificationWhenVisibleBoundsChange() const override; void OnVisibleBoundsChanged() override; void OnPaint(gfx::Canvas* canvas) override; void OnFocus() override; void OnBlur() override; gfx::Point GetKeyboardContextMenuLocation() override; void OnThemeChanged() override; // TextfieldModel::Delegate overrides: void OnCompositionTextConfirmedOrCleared() override; void OnTextChanged() override; // ContextMenuController overrides: void ShowContextMenuForViewImpl(View* source, const gfx::Point& point, ui::MenuSourceType source_type) override; // DragController overrides: 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; // WordLookupClient overrides: bool GetWordLookupDataAtPoint(const gfx::Point& point, gfx::DecoratedText* decorated_word, gfx::Point* baseline_point) override; bool GetWordLookupDataFromSelection(gfx::DecoratedText* decorated_text, gfx::Point* baseline_point) override; // SelectionControllerDelegate overrides: bool HasTextBeingDragged() const override; // ui::TouchEditable overrides: void MoveCaret(const gfx::Point& position) override; void MoveRangeSelectionExtent(const gfx::Point& extent) override; void SelectBetweenCoordinates(const gfx::Point& base, const gfx::Point& extent) override; void GetSelectionEndPoints(gfx::SelectionBound* anchor, gfx::SelectionBound* focus) override; gfx::Rect GetBounds() override; gfx::NativeView GetNativeView() const override; void ConvertPointToScreen(gfx::Point* point) override; void ConvertPointFromScreen(gfx::Point* point) override; void OpenContextMenu(const gfx::Point& anchor) override; void DestroyTouchSelection() override; // ui::SimpleMenuModel::Delegate overrides: bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; bool GetAcceleratorForCommandId(int command_id, ui::Accelerator* accelerator) const override; void ExecuteCommand(int command_id, int event_flags) override; // ui::TextInputClient overrides: void SetCompositionText(const ui::CompositionText& composition) override; size_t ConfirmCompositionText(bool keep_selection) override; void ClearCompositionText() override; void InsertText(const std::u16string& text, InsertTextCursorBehavior cursor_behavior) override; void InsertChar(const ui::KeyEvent& event) override; ui::TextInputType GetTextInputType() const override; ui::TextInputMode GetTextInputMode() const override; base::i18n::TextDirection GetTextDirection() const override; int GetTextInputFlags() const override; bool CanComposeInline() const override; gfx::Rect GetCaretBounds() const override; gfx::Rect GetSelectionBoundingBox() const override; bool GetCompositionCharacterBounds(size_t index, gfx::Rect* rect) const override; bool HasCompositionText() const override; FocusReason GetFocusReason() const override; bool GetTextRange(gfx::Range* range) const override; bool GetCompositionTextRange(gfx::Range* range) const override; bool GetEditableSelectionRange(gfx::Range* range) const override; bool SetEditableSelectionRange(const gfx::Range& range) override; #if BUILDFLAG(IS_MAC) bool DeleteRange(const gfx::Range& range) override; #else bool DeleteRange(const gfx::Range& range); #endif bool GetTextFromRange(const gfx::Range& range, std::u16string* text) const override; void OnInputMethodChanged() override; bool ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) override; void ExtendSelectionAndDelete(size_t before, size_t after) override; void EnsureCaretNotInRect(const gfx::Rect& rect) override; bool IsTextEditCommandEnabled(ui::TextEditCommand command) const override; void SetTextEditCommandForNextKeyEvent(ui::TextEditCommand command) override; ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; // Set whether the text should be used to improve typing suggestions. void SetShouldDoLearning(bool value) { should_do_learning_ = value; } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override; #endif #if BUILDFLAG(IS_CHROMEOS) gfx::Range GetAutocorrectRange() const override; gfx::Rect GetAutocorrectCharacterBounds() const override; bool SetAutocorrectRange(const gfx::Range& range) override; bool AddGrammarFragments( const std::vector<ui::GrammarFragment>& fragments) override; #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS) void GetActiveTextInputControlLayoutBounds( absl::optional<gfx::Rect>* control_bounds, absl::optional<gfx::Rect>* selection_bounds) override; #endif #if BUILDFLAG(IS_WIN) void SetActiveCompositionForAccessibility( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) override; #endif [[nodiscard]] base::CallbackListSubscription AddTextChangedCallback( views::PropertyChangedCallback callback); protected: TextfieldModel* textfield_model() { return model_.get(); } // Inserts or appends a character in response to an IME operation. virtual void DoInsertChar(char16_t ch); // Returns the TextfieldModel's text/cursor/selection rendering model. gfx::RenderText* GetRenderText() const; // Returns the last click root location (relative to the root window). gfx::Point GetLastClickRootLocation() const; // Get the text from the selection clipboard. virtual std::u16string GetSelectionClipboardText() const; // Executes the given |command|. virtual void ExecuteTextEditCommand(ui::TextEditCommand command); // 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); // Returns true if the drop cursor is for insertion at a target text location, // the standard behavior/style. Returns false when drop will do something // else (like replace the text entirely). virtual bool IsDropCursorForInsertion() const; // Returns true if the placeholder text should be shown. Subclasses may // override this to customize when the placeholder text is shown. virtual bool ShouldShowPlaceholderText() const; // Like RequestFocus, but explicitly states that the focus is triggered by // a pointer event. void RequestFocusWithPointer(ui::EventPointerType pointer_type); // Like RequestFocus, but explicitly states that the focus is triggered by a // gesture event. void RequestFocusForGesture(const ui::GestureEventDetails& details); virtual Textfield::EditCommandResult DoExecuteTextEditCommand( ui::TextEditCommand command); // Handles key press event ahead of OnKeyPressed(). This is used for Textarea // to handle the return key. Use TextfieldController::HandleKeyEvent to // intercept the key event in other cases. virtual bool PreHandleKeyPressed(const ui::KeyEvent& event); // Get the default command for a given key |event|. virtual ui::TextEditCommand GetCommandForKeyEvent(const ui::KeyEvent& event); // Update the cursor position in the text field. void UpdateCursorViewPosition(); // A callback function to periodically update the cursor node_data. void UpdateCursorVisibility(); private: friend class TextfieldTestApi; enum class TextChangeType { kNone, kInternal, kUserTriggered }; // View overrides: // Declared final since overriding by subclasses would interfere with the // accounting related to the scheduled text edit command. Subclasses should // use TextfieldController::HandleKeyEvent, to intercept the key event. bool OnKeyPressed(const ui::KeyEvent& event) final; bool OnKeyReleased(const ui::KeyEvent& event) final; // SelectionControllerDelegate overrides: gfx::RenderText* GetRenderTextForSelectionController() override; bool IsReadOnly() const override; bool SupportsDrag() const override; void SetTextBeingDragged(bool value) override; int GetViewHeight() const override; int GetViewWidth() const override; int GetDragSelectionDelay() const override; void OnBeforePointerAction() override; void OnAfterPointerAction(bool text_changed, bool selection_changed) override; // Callers within Textfield should call UpdateAfterChange depending on the // return value. bool PasteSelectionClipboard() override; void UpdateSelectionClipboard() override; // Updates the painted background color. void UpdateBackgroundColor(); // Updates the border per the state of |invalid_|. void UpdateBorder(); // Updates the selection text color. void UpdateSelectionTextColor(); // Updates the selection background color. void UpdateSelectionBackgroundColor(); // Does necessary updates when the text and/or cursor position changes. // If |notify_caret_bounds_changed| is not explicitly set, it will be computed // based on whether either of the other arguments is set. void UpdateAfterChange( TextChangeType text_change_type, bool cursor_changed, absl::optional<bool> notify_caret_bounds_changed = absl::nullopt); // Updates cursor visibility and blinks the cursor if needed. void ShowCursor(); // Gets the style::TextStyle that should be used. int GetTextStyle() const; void PaintTextAndCursor(gfx::Canvas* canvas); // Helper function to call MoveCursorTo on the TextfieldModel. void MoveCursorTo(const gfx::Point& point, bool select); // Recalculates cursor view bounds based on model_. gfx::Rect CalculateCursorViewBounds() const; // Convenience method to notify the InputMethod and TouchSelectionController. void OnCaretBoundsChanged(); // Convenience method to call TextfieldController::OnBeforeUserAction(); void OnBeforeUserAction(); // Convenience method to call TextfieldController::OnAfterUserAction(); void OnAfterUserAction(); // Calls |model_->Cut()| and notifies TextfieldController on success. bool Cut(); // Calls |model_->Copy()| and notifies TextfieldController on success. bool Copy(); // Calls |model_->Paste()| and calls TextfieldController::ContentsChanged() // explicitly if paste succeeded. bool Paste(); // Utility function to prepare the context menu. void UpdateContextMenu(); // Returns true if the current text input type allows access by the IME. bool ImeEditingAllowed() const; // Reveals the password character at |index| for a set duration. // If |index| is nullopt, the existing revealed character will be reset. // |duration| is the time to remain the password char to be visible. void RevealPasswordChar(absl::optional<size_t> index, base::TimeDelta duration); void CreateTouchSelectionControllerAndNotifyIt(); // Called when editing a textfield fails because the textfield is readonly. void OnEditFailed(); // Returns true if an insertion cursor should be visible (a vertical bar, // placed at the point new text will be inserted). bool ShouldShowCursor() const; // Converts a textfield width in "average characters" to the required number // of DIPs, accounting for insets and cursor. int CharsToDips(int width_in_chars) const; // Returns true if an insertion cursor should be visible and blinking. bool ShouldBlinkCursor() const; // Starts and stops blinking the cursor, respectively. These are both // idempotent if the cursor is already blinking/not blinking. void StartBlinkingCursor(); void StopBlinkingCursor(); // Callback for the cursor blink timer. Called every // Textfield::GetCaretBlinkMs(). void OnCursorBlinkTimerFired(); void OnEnabledChanged(); // Drops the dragged text. void DropDraggedText( const ui::DropTargetEvent& event, ui::mojom::DragOperation& output_drag_op, std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner); // Returns the corner radius of the text field. float GetCornerRadius(); // Checks and updates the selection dragging state for the upcoming scroll // sequence, if required. If the scroll sequence starts while long pressing, // it will be used for adjusting the text selection. Otherwise, if the scroll // begins horizontally it will be used for cursor placement. Otherwise, the // scroll sequence won't be used for selection dragging. void MaybeStartSelectionDragging(ui::GestureEvent* event); // The text model. std::unique_ptr<TextfieldModel> model_; // This is the current listener for events from this Textfield. raw_ptr<TextfieldController, DanglingUntriaged> controller_ = nullptr; // An edit command to execute on the next key event. When set to a valid // value, the key event is still passed to |controller_|, but otherwise // ignored in favor of the edit command. Set via // SetTextEditCommandForNextKeyEvent() during dispatch of that key event (see // comment in TextInputClient). ui::TextEditCommand scheduled_text_edit_command_ = ui::TextEditCommand::INVALID_COMMAND; // True if this Textfield cannot accept input and is read-only. bool read_only_ = false; // The default number of average characters for the width of this text field. // This will be reported as the "desired size". Must be set to >= // minimum_width_in_chars_. Defaults to 0. int default_width_in_chars_ = 0; // The minimum allowed width of this text field in average characters. This // will be reported as the minimum size. Must be set to <= // default_width_in_chars_. Setting this to -1 will cause GetMinimumSize() to // return View::GetMinimumSize(). Defaults to -1. int minimum_width_in_chars_ = -1; // Colors which override default system colors. absl::optional<SkColor> text_color_; absl::optional<SkColor> background_color_; absl::optional<SkColor> selection_text_color_; absl::optional<SkColor> selection_background_color_; // Text to display when empty. std::u16string placeholder_text_; // Placeholder text color. // TODO(newcomer): Use NativeTheme to define different default placeholder // text colors for chrome/CrOS when harmony is enabled by default // (https://crbug.com/803279). absl::optional<SkColor> placeholder_text_color_; // The draw flags specified for |placeholder_text_|. int placeholder_text_draw_flags_; // The font used for the placeholder text. If this value is null, the // placeholder text uses the same font list as the underlying RenderText. absl::optional<gfx::FontList> placeholder_font_list_; // True when the contents are deemed unacceptable and should be indicated as // such. bool invalid_ = false; // The input type of this text field. ui::TextInputType text_input_type_ = ui::TEXT_INPUT_TYPE_TEXT; // The input flags of this text field. int text_input_flags_ = 0; // The timer to reveal the last typed password character. base::OneShotTimer password_reveal_timer_; // Tracks whether a user action is being performed which may change the // textfield; i.e. OnBeforeUserAction() has been called, but // OnAfterUserAction() has not yet been called. bool performing_user_action_ = false; // True if InputMethod::CancelComposition() should not be called. bool skip_input_method_cancel_composition_ = false; // Insertion cursor repaint timer and visibility. base::RepeatingTimer cursor_blink_timer_; // The drop cursor is a visual cue for where dragged text will be dropped. bool drop_cursor_visible_ = false; gfx::SelectionModel drop_cursor_position_; // Is the user potentially dragging and dropping from this view? bool initiating_drag_ = false; std::unique_ptr<ui::TouchEditingControllerDeprecated> touch_selection_controller_; SelectionController selection_controller_; // Tracks when the current scroll sequence should be used for cursor placement // or adjusting the text selection. enum class SelectionDraggingState { kNone, kDraggingCursor, kDraggingSelectionExtent }; SelectionDraggingState selection_dragging_state_ = SelectionDraggingState::kNone; // The offset applied to the touch drag location when determining selection // updates. gfx::Vector2d selection_dragging_offset_; // Used to track touch drag starting location and offset to enable touch // scrolling. int drag_start_location_x_; int drag_start_display_offset_ = 0; // Tracks the selection extent, which is used to determine the logical end of // the selection. Roughly, this corresponds to the last drag position of the // touch handle used to update the selection range. Note that the extent may // be different to the logical end of the selection due to "expand by word, // shrink by character" behaviour, in which the selection end can move to the // next word boundary from the extent when expanding. gfx::SelectionModel extent_caret_; // Break type which selection endpoints can be moved to when updating the // selection extent. For "expand by word, shrink by character" behaviour, the // break type is set to WORD_BREAK if the selection has expanded past the // current word boundary and back to CHARACTER_BREAK if the selection is // shrinking. gfx::BreakType break_type_ = gfx::CHARACTER_BREAK; // Whether touch selection handles should be shown once the current scroll // sequence ends. Handles should be shown if touch editing handles were hidden // while scrolling or if part of the scroll sequence was used for cursor // placement or adjusting the text selection. bool show_touch_handles_after_scroll_ = false; // Whether the user should be notified if the clipboard is restricted. bool show_rejection_ui_if_any_ = false; // Whether the text should be used to improve typing suggestions. absl::optional<bool> should_do_learning_; // Context menu related members. std::unique_ptr<ui::SimpleMenuModel> context_menu_contents_; std::unique_ptr<ViewsTextServicesContextMenu> text_services_context_menu_; std::unique_ptr<views::MenuRunner> context_menu_runner_; // View containing the text cursor. raw_ptr<View, DanglingUntriaged> cursor_view_ = nullptr; #if BUILDFLAG(IS_MAC) // Used to track active password input sessions. std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_; #endif // BUILDFLAG(IS_MAC) // How this textfield was focused. ui::TextInputClient::FocusReason focus_reason_ = ui::TextInputClient::FOCUS_REASON_NONE; // The password char reveal index, for testing only. absl::optional<size_t> password_char_reveal_index_; // Extra insets, useful to make room for a button for example. gfx::Insets extra_insets_ = gfx::Insets(); // Whether the client forces a specific text directionality for this // textfield, which should inhibit the user's ability to control the // directionality. bool force_text_directionality_ = false; // Holds the subscription object for the enabled changed callback. base::CallbackListSubscription enabled_changed_subscription_ = AddEnabledChangedCallback( base::BindRepeating(&Textfield::OnEnabledChanged, base::Unretained(this))); // Used to bind callback functions to this object. base::WeakPtrFactory<Textfield> weak_ptr_factory_{this}; // Used to bind drop callback functions to this object. base::WeakPtrFactory<Textfield> drop_weak_ptr_factory_{this}; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Textfield, View) VIEW_BUILDER_PROPERTY(SkColor, BackgroundColor) VIEW_BUILDER_PROPERTY(TextfieldController*, Controller) VIEW_BUILDER_PROPERTY(bool, CursorEnabled) VIEW_BUILDER_PROPERTY(int, DefaultWidthInChars) VIEW_BUILDER_PROPERTY(gfx::HorizontalAlignment, HorizontalAlignment) VIEW_BUILDER_PROPERTY(bool, Invalid) VIEW_BUILDER_PROPERTY(int, MinimumWidthInChars) VIEW_BUILDER_PROPERTY(std::u16string, PlaceholderText) VIEW_BUILDER_PROPERTY(bool, ReadOnly) VIEW_BUILDER_PROPERTY(gfx::Range, SelectedRange) VIEW_BUILDER_PROPERTY(SkColor, SelectionBackgroundColor) VIEW_BUILDER_PROPERTY(SkColor, SelectionTextColor) VIEW_BUILDER_PROPERTY(std::u16string, Text) VIEW_BUILDER_PROPERTY(SkColor, TextColor) VIEW_BUILDER_PROPERTY(int, TextInputFlags) VIEW_BUILDER_PROPERTY(ui::TextInputType, TextInputType) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Textfield) #endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield.h
C++
unknown
34,626
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield_controller.h" #include "base/functional/callback_helpers.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h" #include "ui/events/event.h" namespace views { bool TextfieldController::HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) { return false; } bool TextfieldController::HandleMouseEvent(Textfield* sender, const ui::MouseEvent& mouse_event) { return false; } bool TextfieldController::HandleGestureEvent( Textfield* sender, const ui::GestureEvent& gesture_event) { return false; } ui::mojom::DragOperation TextfieldController::OnDrop( const ui::DropTargetEvent& event) { return ui::mojom::DragOperation::kNone; } views::View::DropCallback TextfieldController::CreateDropCallback( const ui::DropTargetEvent& event) { return base::NullCallback(); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_controller.cc
C++
unknown
1,109
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_ #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_ #include <set> #include <string> #include "ui/base/clipboard/clipboard_buffer.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/views/view.h" #include "ui/views/views_export.h" namespace ui { class KeyEvent; class MouseEvent; class GestureEvent; class SimpleMenuModel; } // namespace ui namespace views { class Textfield; // This defines the callback interface for other code to be notified of changes // in the state of a text field. class VIEWS_EXPORT TextfieldController { public: // This method is called whenever the text in the field is changed by the // user. It won't be called if the text is changed by calling // Textfield::SetText() or Textfield::AppendText(). virtual void ContentsChanged(Textfield* sender, const std::u16string& new_contents) {} // Called to get notified about keystrokes in the edit. // Returns true if the message was handled and should not be processed // further. If it returns false the processing continues. virtual bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event); // Called to get notified about mouse events in the edit. // Returns true if the message was handled and should not be processed // further. Currently, only mouse down events and mouse wheel events are sent // here. virtual bool HandleMouseEvent(Textfield* sender, const ui::MouseEvent& mouse_event); // Called to get notified about gesture events in the edit. // Returns true if the message was handled and should not be processed // further. Currently, only tap events are sent here. virtual bool HandleGestureEvent(Textfield* sender, const ui::GestureEvent& gesture_event); // Called before performing a user action that may change the textfield. // It's currently only supported by Views implementation. virtual void OnBeforeUserAction(Textfield* sender) {} // Called after performing a user action that may change the textfield. // It's currently only supported by Views implementation. virtual void OnAfterUserAction(Textfield* sender) {} // Called after performing a Cut or Copy operation. virtual void OnAfterCutOrCopy(ui::ClipboardBuffer clipboard_buffer) {} // Called after performing a Paste operation. virtual void OnAfterPaste() {} // Called after the textfield has written drag data to give the controller a // chance to modify the drag data. virtual void OnWriteDragData(ui::OSExchangeData* data) {} // Called after the textfield has set default drag operations to give the // controller a chance to update them. virtual void OnGetDragOperationsForTextfield(int* drag_operations) {} // Enables the controller to append to the accepted drop formats. virtual void AppendDropFormats( int* formats, std::set<ui::ClipboardFormatType>* format_types) {} // Called when a drop of dragged data happens on the textfield. This method is // called before regular handling of the drop. If this returns a drag // operation other than `ui::mojom::DragOperation::kNone`, regular handling is // skipped. virtual ui::mojom::DragOperation OnDrop(const ui::DropTargetEvent& event); // Called to get async drop callback to be run later. virtual views::View::DropCallback CreateDropCallback( const ui::DropTargetEvent& event); // Gives the controller a chance to modify the context menu contents. virtual void UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {} protected: virtual ~TextfieldController() = default; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_controller.h
C++
unknown
4,050
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield_model.h" #include <algorithm> #include <utility> #include "base/check_op.h" #include "base/no_destructor.h" #include "base/ranges/algorithm.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "build/chromeos_buildflags.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/range/range.h" #include "ui/gfx/utf16_indexing.h" #include "ui/views/style/platform_style.h" namespace { // Orders ranges decreasing with respect to their min index. This is useful for // applying text edits such that an edit doesn't offset the positions of later // edits. It should be reversed when undoing edits. void order_ranges(std::vector<gfx::Range>* ranges) { std::sort(ranges->begin(), ranges->end(), [](const auto& r1, const auto& r2) { return r1.GetMin() > r2.GetMin(); }); } // Adjusts |position| for the deletion of |ranges|. E.g., if |position| is 10, // and |ranges| is {{1, 3}, {15, 18}, and {6, 13}}, this will return 4, // subtracting 2 (3-1), 0 (15>10), and 4 (10-6) for each range respectively. size_t adjust_position_for_removals(size_t position, std::vector<gfx::Range> ranges) { size_t adjustment = 0; for (auto range : ranges) adjustment += range.Intersect(gfx::Range(0, position)).length(); return position - adjustment; } } // namespace namespace views { namespace internal { // Edit holds state information to undo/redo editing changes. Editing operations // are merged when possible, like when characters are typed in sequence. Calling // Commit() marks an edit as an independent operation that shouldn't be merged. class Edit { public: enum class Type { kInsert, kDelete, kReplace, }; Edit(const Edit&) = delete; Edit& operator=(const Edit&) = delete; virtual ~Edit() = default; // Revert the change made by this edit in |model|. void Undo(TextfieldModel* model) { // Insertions must be applied in order of increasing indices since |Redo| // applies them in decreasing order. auto insertion_texts = old_texts_; std::reverse(insertion_texts.begin(), insertion_texts.end()); auto insertion_text_starts = old_text_starts_; std::reverse(insertion_text_starts.begin(), insertion_text_starts.end()); model->ModifyText({{static_cast<uint32_t>(new_text_start_), static_cast<uint32_t>(new_text_end())}}, insertion_texts, insertion_text_starts, old_primary_selection_, old_secondary_selections_); } // Apply the change of this edit to the |model|. void Redo(TextfieldModel* model) { std::vector<gfx::Range> deletions; for (size_t i = 0; i < old_texts_.size(); ++i) { deletions.emplace_back(old_text_starts_[i], old_text_starts_[i] + old_texts_[i].length()); } model->ModifyText(deletions, {new_text_}, {new_text_start_}, {static_cast<uint32_t>(new_cursor_pos_), static_cast<uint32_t>(new_cursor_pos_)}, {}); } // Try to merge the |edit| into this edit and returns true on success. The // merged edit will be deleted after redo and should not be reused. bool Merge(const Edit* edit) { // Don't merge if previous edit is DELETE. This happens when a // user deletes characters then hits return. In this case, the // delete should be treated as separate edit that can be undone // and should not be merged with the replace edit. if (type_ != Type::kDelete && edit->force_merge()) { MergeReplace(edit); return true; } return mergeable() && edit->mergeable() && DoMerge(edit); } // Commits the edit and marks as un-mergeable. void Commit() { merge_type_ = MergeType::kDoNotMerge; } private: friend class InsertEdit; friend class ReplaceEdit; friend class DeleteEdit; Edit(Type type, MergeType merge_type, std::vector<std::u16string> old_texts, std::vector<size_t> old_text_starts, gfx::Range old_primary_selection, std::vector<gfx::Range> old_secondary_selections, bool delete_backward, size_t new_cursor_pos, const std::u16string& new_text, size_t new_text_start) : type_(type), merge_type_(merge_type), old_texts_(old_texts), old_text_starts_(old_text_starts), old_primary_selection_(old_primary_selection), old_secondary_selections_(old_secondary_selections), delete_backward_(delete_backward), new_cursor_pos_(new_cursor_pos), new_text_(new_text), new_text_start_(new_text_start) {} // Each type of edit provides its own specific merge implementation. Assumes // |edit| occurs after |this|. virtual bool DoMerge(const Edit* edit) = 0; Type type() const { return type_; } // Can this edit be merged? bool mergeable() const { return merge_type_ == MergeType::kMergeable; } // Should this edit be forcibly merged with the previous edit? bool force_merge() const { return merge_type_ == MergeType::kForceMerge; } // Returns the end index of the |new_text_|. size_t new_text_end() const { return new_text_start_ + new_text_.length(); } // Merge the replace edit into the current edit. This handles the special case // where an omnibox autocomplete string is set after a new character is typed. void MergeReplace(const Edit* edit) { CHECK_EQ(Type::kReplace, edit->type_); CHECK_EQ(1U, edit->old_text_starts_.size()); CHECK_EQ(0U, edit->old_text_starts_[0]); CHECK_EQ(0U, edit->new_text_start_); // We need to compute the merged edit's |old_texts_| by undoing this edit. // Otherwise, |old_texts_| would be the autocompleted text following the // user input. E.g., given goo|[gle.com], when the user types 'g', the text // updates to goog|[le.com]. If we leave old_texts_ unchanged as 'gle.com', // then undoing will result in 'gle.com' instead of 'goo|[gle.com]' std::u16string old_texts = edit->old_texts_[0]; // Remove |new_text_|. old_texts.erase(new_text_start_, new_text_.length()); // Add |old_texts_| in reverse order since we're undoing an edit. for (size_t i = old_texts_.size(); i != 0; i--) old_texts.insert(old_text_starts_[i - 1], old_texts_[i - 1]); merge_type_ = MergeType::kDoNotMerge; old_texts_ = {old_texts}; old_text_starts_ = {0}; delete_backward_ = false; new_cursor_pos_ = edit->new_cursor_pos_; new_text_ = edit->new_text_; new_text_start_ = 0; } Type type_; // The type of merging allowed. MergeType merge_type_; // Deleted texts ordered with decreasing indices. std::vector<std::u16string> old_texts_; // The indices of |old_texts_|. std::vector<size_t> old_text_starts_; // The text selection ranges prior to the edit. |old_primary_selection_| // represents the selection associated with the cursor. gfx::Range old_primary_selection_; std::vector<gfx::Range> old_secondary_selections_; // True if the deletion is made backward. bool delete_backward_; // New cursor position. size_t new_cursor_pos_; // Added text. std::u16string new_text_; // The index of |new_text_| size_t new_text_start_; }; // Insert text at a given position. Assumes 1) no previous selection and 2) the // insertion is at the cursor, which will advance by the insertion length. class InsertEdit : public Edit { public: InsertEdit(bool mergeable, const std::u16string& new_text, size_t at) : Edit(Type::kInsert, mergeable ? MergeType::kMergeable : MergeType::kDoNotMerge, {} /* old_texts */, {} /* old_text_starts */, {gfx::Range(at, at)} /* old_primary_selection */, {} /* old_secondary_selections */, false /* delete_backward */, at + new_text.length() /* new_cursor_pos */, new_text /* new_text */, at /* new_text_start */) {} // Merge if |edit| is an insertion continuing forward where |this| ended. E.g. // If |this| changed "ab|c" to "abX|c", an edit to "abXY|c" can be merged. bool DoMerge(const Edit* edit) override { // Reject other edit types, and inserts starting somewhere other than where // this insert ended. if (edit->type() != Type::kInsert || new_text_end() != edit->new_text_start_) return false; new_text_ += edit->new_text_; new_cursor_pos_ = edit->new_cursor_pos_; return true; } }; // Delete one or more ranges and do a single insertion. The insertion need not // be adjacent to the deletions (e.g. drag & drop). class ReplaceEdit : public Edit { public: ReplaceEdit(MergeType merge_type, std::vector<std::u16string> old_texts, std::vector<size_t> old_text_starts, gfx::Range old_primary_selection, std::vector<gfx::Range> old_secondary_selections, bool backward, size_t new_cursor_pos, const std::u16string& new_text, size_t new_text_start) : Edit(Type::kReplace, merge_type, old_texts, old_text_starts, old_primary_selection, old_secondary_selections, backward, new_cursor_pos, new_text, new_text_start) {} // Merge if |edit| is an insertion or replacement continuing forward where // |this| ended. E.g. If |this| changed "a|bc" to "aX|c", edits to "aXY|" or // "aXYc" can be merged. Drag and drops are marked kDoNotMerge and should not // get here. bool DoMerge(const Edit* edit) override { // Reject deletions, replacements deleting multiple ranges, and edits // inserting or deleting text somewhere other than where this edit ended. if (edit->type() == Type::kDelete || edit->old_texts_.size() > 1 || new_text_end() != edit->new_text_start_ || (!edit->old_text_starts_.empty() && new_text_end() != edit->old_text_starts_[0])) return false; if (edit->old_texts_.size() == 1) old_texts_[0] += edit->old_texts_[0]; new_text_ += edit->new_text_; new_cursor_pos_ = edit->new_cursor_pos_; return true; } }; // Delete possibly multiple texts. class DeleteEdit : public Edit { public: DeleteEdit(bool mergeable, std::vector<std::u16string> texts, std::vector<size_t> text_starts, gfx::Range old_primary_selection, std::vector<gfx::Range> old_secondary_selections, bool backward, size_t new_cursor_pos) : Edit(Type::kDelete, mergeable ? MergeType::kMergeable : MergeType::kDoNotMerge, texts, text_starts, old_primary_selection, old_secondary_selections, backward, new_cursor_pos, std::u16string() /* new_text */, 0 /* new_text_start */) {} // Merge if |edit| is a deletion continuing in the same direction and position // where |this| ended. E.g. If |this| changed "ab|c" to "a|c" an edit to "|c" // can be merged. bool DoMerge(const Edit* edit) override { if (edit->type() != Type::kDelete) return false; // Deletions with selections are marked kDoNotMerge and should not get here. DCHECK(old_secondary_selections_.empty()); DCHECK(old_primary_selection_.is_empty()); DCHECK(edit->old_secondary_selections_.empty()); DCHECK(edit->old_primary_selection_.is_empty()); if (delete_backward_) { // Backspace can be merged only with backspace at the same position. if (!edit->delete_backward_ || old_text_starts_[0] != edit->old_text_starts_[0] + edit->old_texts_[0].length()) return false; old_text_starts_[0] = edit->old_text_starts_[0]; old_texts_[0] = edit->old_texts_[0] + old_texts_[0]; new_cursor_pos_ = edit->new_cursor_pos_; } else { // Delete can be merged only with delete at the same position. if (edit->delete_backward_ || old_text_starts_[0] != edit->old_text_starts_[0]) return false; old_texts_[0] += edit->old_texts_[0]; } return true; } }; } // namespace internal namespace { // Returns the first segment that is visually emphasized. Usually it's used for // representing the target clause (on Windows). Returns an invalid range if // there is no such a range. gfx::Range GetFirstEmphasizedRange(const ui::CompositionText& composition) { for (const auto& underline : composition.ime_text_spans) { if (underline.thickness == ui::ImeTextSpan::Thickness::kThick) return gfx::Range(underline.start_offset, underline.end_offset); } return gfx::Range::InvalidRange(); } // Returns a pointer to the kill buffer which holds the text to be inserted on // executing yank command. Singleton since it needs to be persisted across // multiple textfields. // On Mac, the size of the kill ring (no. of buffers) is controlled by // NSTextKillRingSize, a text system default. However to keep things simple, // the default kill ring size of 1 (i.e. a single buffer) is assumed. std::u16string* GetKillBuffer() { static base::NoDestructor<std::u16string> kill_buffer; DCHECK(base::CurrentUIThread::IsSet()); return kill_buffer.get(); } // Helper method to set the kill buffer. void SetKillBuffer(const std::u16string& buffer) { std::u16string* kill_buffer = GetKillBuffer(); *kill_buffer = buffer; } void SelectRangeInCompositionText(gfx::RenderText* render_text, size_t cursor, const gfx::Range& range) { DCHECK(render_text); DCHECK(range.IsValid()); size_t start = range.GetMin(); size_t end = range.GetMax(); #if BUILDFLAG(IS_CHROMEOS_ASH) // Swap |start| and |end| so that GetCaretBounds() can always return the same // value during conversion. // TODO(yusukes): Check if this works for other platforms. If it is, use this // on all platforms. std::swap(start, end); #endif render_text->SelectRange(gfx::Range(cursor + start, cursor + end)); } } // namespace ///////////////////////////////////////////////////////////////// // TextfieldModel: public TextfieldModel::Delegate::~Delegate() = default; TextfieldModel::TextfieldModel(Delegate* delegate) : delegate_(delegate), render_text_(gfx::RenderText::CreateRenderText()), current_edit_(edit_history_.end()) {} TextfieldModel::~TextfieldModel() { ClearEditHistory(); ClearComposition(); } bool TextfieldModel::SetText(const std::u16string& new_text, size_t cursor_position) { using MergeType = internal::MergeType; bool changed = false; if (HasCompositionText()) { ConfirmCompositionText(); changed = true; } if (text() != new_text) { if (changed) // No need to remember composition. Undo(); // If there is a composition text, don't merge with previous edit. // Otherwise, force merge the edits. ExecuteAndRecordReplace( changed ? MergeType::kDoNotMerge : MergeType::kForceMerge, {gfx::Range(0, text().length())}, cursor_position, new_text, 0U); } ClearSelection(); return changed; } void TextfieldModel::Append(const std::u16string& new_text) { if (HasCompositionText()) ConfirmCompositionText(); size_t save = GetCursorPosition(); MoveCursor(gfx::LINE_BREAK, render_text_->GetVisualDirectionOfLogicalEnd(), gfx::SELECTION_NONE); InsertText(new_text); render_text_->SetCursorPosition(save); ClearSelection(); } bool TextfieldModel::Delete(bool add_to_kill_buffer) { // |add_to_kill_buffer| should never be true for an obscured textfield. DCHECK(!add_to_kill_buffer || !render_text_->obscured()); if (HasCompositionText()) { // No undo/redo for composition text. CancelCompositionText(); return true; } if (HasSelection()) { if (add_to_kill_buffer) SetKillBuffer(GetSelectedText()); DeleteSelection(); return true; } const size_t cursor_position = GetCursorPosition(); if (cursor_position < text().length()) { size_t next_grapheme_index = render_text_->IndexOfAdjacentGrapheme( cursor_position, gfx::CURSOR_FORWARD); gfx::Range range_to_delete(cursor_position, next_grapheme_index); if (add_to_kill_buffer) SetKillBuffer(GetTextFromRange(range_to_delete)); ExecuteAndRecordDelete({range_to_delete}, true); return true; } return false; } bool TextfieldModel::Backspace(bool add_to_kill_buffer) { // |add_to_kill_buffer| should never be true for an obscured textfield. DCHECK(!add_to_kill_buffer || !render_text_->obscured()); if (HasCompositionText()) { // No undo/redo for composition text. CancelCompositionText(); return true; } if (HasSelection()) { if (add_to_kill_buffer) SetKillBuffer(GetSelectedText()); DeleteSelection(); return true; } const size_t cursor_position = GetCursorPosition(); if (cursor_position > 0) { gfx::Range range_to_delete( PlatformStyle::RangeToDeleteBackwards(text(), cursor_position)); if (add_to_kill_buffer) SetKillBuffer(GetTextFromRange(range_to_delete)); ExecuteAndRecordDelete({range_to_delete}, true); return true; } return false; } size_t TextfieldModel::GetCursorPosition() const { return render_text_->cursor_position(); } void TextfieldModel::MoveCursor(gfx::BreakType break_type, gfx::VisualCursorDirection direction, gfx::SelectionBehavior selection_behavior) { if (HasCompositionText()) ConfirmCompositionText(); render_text_->MoveCursor(break_type, direction, selection_behavior); } bool TextfieldModel::MoveCursorTo(const gfx::SelectionModel& cursor) { if (HasCompositionText()) { ConfirmCompositionText(); // ConfirmCompositionText() updates cursor position. Need to reflect it in // the SelectionModel parameter of MoveCursorTo(). gfx::Range range(render_text_->selection().start(), cursor.caret_pos()); if (!range.is_empty()) return render_text_->SelectRange(range); return render_text_->SetSelection( gfx::SelectionModel(cursor.caret_pos(), cursor.caret_affinity())); } return render_text_->SetSelection(cursor); } bool TextfieldModel::MoveCursorTo(size_t pos) { return MoveCursorTo(gfx::SelectionModel(pos, gfx::CURSOR_FORWARD)); } bool TextfieldModel::MoveCursorTo(const gfx::Point& point, bool select) { if (HasCompositionText()) ConfirmCompositionText(); return render_text_->MoveCursorToPoint(point, select); } std::u16string TextfieldModel::GetSelectedText() const { return GetTextFromRange(render_text_->selection()); } void TextfieldModel::SelectRange(const gfx::Range& range, bool primary) { if (HasCompositionText()) ConfirmCompositionText(); render_text_->SelectRange(range, primary); } void TextfieldModel::SelectSelectionModel(const gfx::SelectionModel& sel) { if (HasCompositionText()) ConfirmCompositionText(); render_text_->SetSelection(sel); } void TextfieldModel::SelectAll(bool reversed) { if (HasCompositionText()) ConfirmCompositionText(); render_text_->SelectAll(reversed); } void TextfieldModel::SelectWord() { if (HasCompositionText()) ConfirmCompositionText(); render_text_->SelectWord(); } void TextfieldModel::ClearSelection() { if (HasCompositionText()) ConfirmCompositionText(); render_text_->ClearSelection(); } bool TextfieldModel::CanUndo() { return edit_history_.size() && current_edit_ != edit_history_.end(); } bool TextfieldModel::CanRedo() { if (edit_history_.empty()) return false; // There is no redo iff the current edit is the last element in the history. auto iter = current_edit_; return iter == edit_history_.end() || // at the top. ++iter != edit_history_.end(); } bool TextfieldModel::Undo() { if (!CanUndo()) return false; DCHECK(!HasCompositionText()); if (HasCompositionText()) CancelCompositionText(); std::u16string old = text(); size_t old_cursor = GetCursorPosition(); (*current_edit_)->Commit(); (*current_edit_)->Undo(this); if (current_edit_ == edit_history_.begin()) current_edit_ = edit_history_.end(); else --current_edit_; return old != text() || old_cursor != GetCursorPosition(); } bool TextfieldModel::Redo() { if (!CanRedo()) return false; DCHECK(!HasCompositionText()); if (HasCompositionText()) CancelCompositionText(); if (current_edit_ == edit_history_.end()) current_edit_ = edit_history_.begin(); else ++current_edit_; std::u16string old = text(); size_t old_cursor = GetCursorPosition(); (*current_edit_)->Redo(this); return old != text() || old_cursor != GetCursorPosition(); } bool TextfieldModel::Cut() { if (!HasCompositionText() && HasSelection(true) && !render_text_->obscured()) { ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(GetSelectedText()); DeleteSelection(); return true; } return false; } bool TextfieldModel::Copy() { if (!HasCompositionText() && HasSelection(true) && !render_text_->obscured()) { ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(GetSelectedText()); return true; } return false; } bool TextfieldModel::Paste() { std::u16string text; ui::Clipboard::GetForCurrentThread()->ReadText( ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &text); if (text.empty()) return false; if (render_text()->multiline()) { InsertTextInternal(text, false); return true; } // Leading/trailing whitespace is often selected accidentally, and is rarely // critical to include (e.g. when pasting into a find bar). Trim it. By // contrast, whitespace in the middle of the string may need exact // preservation to avoid changing the effect (e.g. converting a full-width // space to a regular space), so don't call a more aggressive function like // CollapseWhitespace(). base::TrimWhitespace(text, base::TRIM_ALL, &text); // If the clipboard contains all whitespace then paste a single space. if (text.empty()) text = u" "; InsertTextInternal(text, false); return true; } bool TextfieldModel::Transpose() { if (HasCompositionText() || HasSelection()) return false; size_t cur = GetCursorPosition(); size_t next = render_text_->IndexOfAdjacentGrapheme(cur, gfx::CURSOR_FORWARD); size_t prev = render_text_->IndexOfAdjacentGrapheme(cur, gfx::CURSOR_BACKWARD); // At the end of the line, the last two characters should be transposed. if (cur == text().length()) { DCHECK_EQ(cur, next); cur = prev; prev = render_text_->IndexOfAdjacentGrapheme(prev, gfx::CURSOR_BACKWARD); } // This happens at the beginning of the line or when the line has less than // two graphemes. if (gfx::UTF16IndexToOffset(text(), prev, next) != 2) return false; SelectRange(gfx::Range(prev, next)); std::u16string text = GetSelectedText(); std::u16string transposed_text = text.substr(cur - prev) + text.substr(0, cur - prev); InsertTextInternal(transposed_text, false); return true; } bool TextfieldModel::Yank() { const std::u16string* kill_buffer = GetKillBuffer(); if (!kill_buffer->empty() || HasSelection()) { InsertTextInternal(*kill_buffer, false); return true; } return false; } bool TextfieldModel::HasSelection(bool primary_only) const { if (primary_only) return !render_text_->selection().is_empty(); return base::ranges::any_of( render_text_->GetAllSelections(), [](const auto& selection) { return !selection.is_empty(); }); } void TextfieldModel::DeleteSelection() { DCHECK(!HasCompositionText()); DCHECK(HasSelection()); ExecuteAndRecordDelete(render_text_->GetAllSelections(), false); } void TextfieldModel::DeletePrimarySelectionAndInsertTextAt( const std::u16string& new_text, size_t position) { using MergeType = internal::MergeType; if (HasCompositionText()) CancelCompositionText(); // We don't use |ExecuteAndRecordReplaceSelection| because that assumes the // insertion occurs at the cursor. ExecuteAndRecordReplace(MergeType::kDoNotMerge, {render_text_->selection()}, position + new_text.length(), new_text, position); } std::u16string TextfieldModel::GetTextFromRange(const gfx::Range& range) const { return render_text_->GetTextFromRange(range); } void TextfieldModel::GetTextRange(gfx::Range* range) const { *range = gfx::Range(0, text().length()); } void TextfieldModel::SetCompositionText( const ui::CompositionText& composition) { if (HasCompositionText()) CancelCompositionText(); else if (HasSelection()) DeleteSelection(); if (composition.text.empty()) return; size_t cursor = GetCursorPosition(); std::u16string new_text = text(); SetRenderTextText(new_text.insert(cursor, composition.text)); composition_range_ = gfx::Range(cursor, cursor + composition.text.length()); // Don't render IME spans with thickness "kNone". if (composition.ime_text_spans.size() > 0 && composition.ime_text_spans[0].thickness != ui::ImeTextSpan::Thickness::kNone) render_text_->SetCompositionRange(composition_range_); else render_text_->SetCompositionRange(gfx::Range::InvalidRange()); gfx::Range emphasized_range = GetFirstEmphasizedRange(composition); if (emphasized_range.IsValid()) { // This is a workaround due to the lack of support in RenderText to draw // a thick underline. In a composition returned from an IME, the segment // emphasized by a thick underline usually represents the target clause. // Because the target clause is more important than the actual selection // range (or caret position) in the composition here we use a selection-like // marker instead to show this range. // TODO(yukawa, msw): Support thick underlines and remove this workaround. SelectRangeInCompositionText(render_text_.get(), cursor, emphasized_range); } else if (!composition.selection.is_empty()) { SelectRangeInCompositionText(render_text_.get(), cursor, composition.selection); } else { render_text_->SetCursorPosition(cursor + composition.selection.end()); } } #if BUILDFLAG(IS_CHROMEOS) bool TextfieldModel::SetAutocorrectRange(const gfx::Range& range) { if (range.GetMax() > render_text()->text().length()) { return false; } autocorrect_range_ = range; // TODO(b/161490813): Update |autocorrect_range_| and show underline. // Autocorrect range needs to be updated based on user text inputs and an // underline should be shown for the range. NOTIMPLEMENTED_LOG_ONCE(); return false; } #endif void TextfieldModel::SetCompositionFromExistingText(const gfx::Range& range) { if (range.is_empty() || !gfx::Range(0, text().length()).Contains(range)) { ClearComposition(); return; } composition_range_ = range; render_text_->SetCompositionRange(range); } size_t TextfieldModel::ConfirmCompositionText() { DCHECK(HasCompositionText()); std::u16string composition = text().substr(composition_range_.start(), composition_range_.length()); size_t composition_length = composition_range_.length(); // TODO(oshima): current behavior on ChromeOS is a bit weird and not // sure exactly how this should work. Find out and fix if necessary. AddOrMergeEditHistory(std::make_unique<internal::InsertEdit>( false, composition, composition_range_.start())); render_text_->SetCursorPosition(composition_range_.end()); ClearComposition(); if (delegate_) delegate_->OnCompositionTextConfirmedOrCleared(); return composition_length; } void TextfieldModel::CancelCompositionText() { DCHECK(HasCompositionText()); gfx::Range range = composition_range_; ClearComposition(); std::u16string new_text = text(); SetRenderTextText(new_text.erase(range.start(), range.length())); render_text_->SetCursorPosition(range.start()); if (delegate_) delegate_->OnCompositionTextConfirmedOrCleared(); } void TextfieldModel::ClearComposition() { composition_range_ = gfx::Range::InvalidRange(); render_text_->SetCompositionRange(composition_range_); } void TextfieldModel::GetCompositionTextRange(gfx::Range* range) const { *range = composition_range_; } bool TextfieldModel::HasCompositionText() const { return !composition_range_.is_empty(); } void TextfieldModel::ClearEditHistory() { edit_history_.clear(); current_edit_ = edit_history_.end(); } ///////////////////////////////////////////////////////////////// // TextfieldModel: private void TextfieldModel::InsertTextInternal(const std::u16string& new_text, bool mergeable) { using MergeType = internal::MergeType; if (HasCompositionText()) { CancelCompositionText(); ExecuteAndRecordInsert(new_text, mergeable); } else if (HasSelection()) { ExecuteAndRecordReplaceSelection( mergeable ? MergeType::kMergeable : MergeType::kDoNotMerge, new_text); } else { ExecuteAndRecordInsert(new_text, mergeable); } } void TextfieldModel::ReplaceTextInternal(const std::u16string& new_text, bool mergeable) { if (HasCompositionText()) { CancelCompositionText(); } else if (!HasSelection()) { size_t cursor = GetCursorPosition(); const gfx::SelectionModel& model = render_text_->selection_model(); // When there is no selection, the default is to replace the next grapheme // with |new_text|. So, need to find the index of next grapheme first. size_t next = render_text_->IndexOfAdjacentGrapheme(cursor, gfx::CURSOR_FORWARD); if (next == model.caret_pos()) render_text_->SetSelection(model); else render_text_->SelectRange(gfx::Range(next, model.caret_pos())); } // Edit history is recorded in InsertText. InsertTextInternal(new_text, mergeable); } void TextfieldModel::ClearRedoHistory() { if (edit_history_.begin() == edit_history_.end()) return; if (current_edit_ == edit_history_.end()) { ClearEditHistory(); return; } auto delete_start = current_edit_; ++delete_start; edit_history_.erase(delete_start, edit_history_.end()); } void TextfieldModel::ExecuteAndRecordDelete(std::vector<gfx::Range> ranges, bool mergeable) { // We need only check replacement_ranges[0] as |delete_backwards_| is // irrelevant for multi-range deletions which can't be merged anyways. const bool backward = ranges[0].is_reversed(); order_ranges(&ranges); std::vector<std::u16string> old_texts; std::vector<size_t> old_text_starts; for (const auto& range : ranges) { old_texts.push_back(GetTextFromRange(range)); old_text_starts.push_back(range.GetMin()); } size_t cursor_pos = adjust_position_for_removals(GetCursorPosition(), ranges); auto edit = std::make_unique<internal::DeleteEdit>( mergeable, old_texts, old_text_starts, render_text_->selection(), render_text_->secondary_selections(), backward, cursor_pos); edit->Redo(this); AddOrMergeEditHistory(std::move(edit)); } void TextfieldModel::ExecuteAndRecordReplaceSelection( internal::MergeType merge_type, const std::u16string& new_text) { auto replacement_ranges = render_text_->GetAllSelections(); size_t new_text_start = adjust_position_for_removals(GetCursorPosition(), replacement_ranges); size_t new_cursor_pos = new_text_start + new_text.length(); ExecuteAndRecordReplace(merge_type, replacement_ranges, new_cursor_pos, new_text, new_text_start); } void TextfieldModel::ExecuteAndRecordReplace( internal::MergeType merge_type, std::vector<gfx::Range> replacement_ranges, size_t new_cursor_pos, const std::u16string& new_text, size_t new_text_start) { // We need only check replacement_ranges[0] as |delete_backwards_| is // irrelevant for multi-range deletions which can't be merged anyways. const bool backward = replacement_ranges[0].is_reversed(); order_ranges(&replacement_ranges); std::vector<std::u16string> old_texts; std::vector<size_t> old_text_starts; for (const auto& range : replacement_ranges) { old_texts.push_back(GetTextFromRange(range)); old_text_starts.push_back(range.GetMin()); } auto edit = std::make_unique<internal::ReplaceEdit>( merge_type, old_texts, old_text_starts, render_text_->selection(), render_text_->secondary_selections(), backward, new_cursor_pos, new_text, new_text_start); edit->Redo(this); AddOrMergeEditHistory(std::move(edit)); } void TextfieldModel::ExecuteAndRecordInsert(const std::u16string& new_text, bool mergeable) { auto edit = std::make_unique<internal::InsertEdit>(mergeable, new_text, GetCursorPosition()); edit->Redo(this); AddOrMergeEditHistory(std::move(edit)); } void TextfieldModel::AddOrMergeEditHistory( std::unique_ptr<internal::Edit> edit) { ClearRedoHistory(); if (current_edit_ != edit_history_.end() && (*current_edit_)->Merge(edit.get())) { // If the new edit was successfully merged with an old one, don't add it to // the history. return; } edit_history_.push_back(std::move(edit)); if (current_edit_ == edit_history_.end()) { // If there is no redoable edit, this is the 1st edit because RedoHistory // has been already deleted. DCHECK_EQ(1u, edit_history_.size()); current_edit_ = edit_history_.begin(); } else { ++current_edit_; } } void TextfieldModel::ModifyText( const std::vector<gfx::Range>& deletions, const std::vector<std::u16string>& insertion_texts, const std::vector<size_t>& insertion_positions, const gfx::Range& primary_selection, const std::vector<gfx::Range>& secondary_selections) { DCHECK_EQ(insertion_texts.size(), insertion_positions.size()); std::u16string old_text = text(); ClearComposition(); for (auto deletion : deletions) old_text.erase(deletion.start(), deletion.length()); for (size_t i = 0; i < insertion_texts.size(); ++i) old_text.insert(insertion_positions[i], insertion_texts[i]); SetRenderTextText(old_text); if (primary_selection.start() == primary_selection.end()) render_text_->SetCursorPosition(primary_selection.start()); else render_text_->SelectRange(primary_selection); for (auto secondary_selection : secondary_selections) render_text_->SelectRange(secondary_selection, false); } void TextfieldModel::SetRenderTextText(const std::u16string& text) { render_text_->SetText(text); if (delegate_) delegate_->OnTextChanged(); } // static void TextfieldModel::ClearKillBuffer() { SetKillBuffer(std::u16string()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_model.cc
C++
unknown
35,314
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_ #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_ #include <stddef.h> #include <list> #include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "build/chromeos_buildflags.h" #include "ui/base/ime/composition_text.h" #include "ui/gfx/render_text.h" #include "ui/gfx/text_constants.h" #include "ui/views/views_export.h" namespace views { namespace internal { // Internal Edit class that keeps track of edits for undo/redo. class Edit; // The types of merge behavior implemented by Edit operations. enum class MergeType { // The edit should not usually be merged with next edit. kDoNotMerge, // The edit should be merged with next edit when possible. kMergeable, // The edit should be merged with the prior edit, even if marked kDoNotMerge. kForceMerge, }; } // namespace internal namespace test { class BridgedNativeWidgetTest; class TextfieldTest; } // namespace test // A model that represents text content for a views::Textfield. // It supports editing, selection and cursor manipulation. class VIEWS_EXPORT TextfieldModel { public: // Delegate interface implemented by the textfield view class to provide // additional functionalities required by the model. class VIEWS_EXPORT Delegate { public: // Called when the current composition text is confirmed or cleared. virtual void OnCompositionTextConfirmedOrCleared() = 0; // Called any time that the text property is modified in TextfieldModel virtual void OnTextChanged() {} protected: virtual ~Delegate(); }; explicit TextfieldModel(Delegate* delegate); TextfieldModel(const TextfieldModel&) = delete; TextfieldModel& operator=(const TextfieldModel&) = delete; virtual ~TextfieldModel(); // Edit related methods. const std::u16string& text() const { return render_text_->text(); } // Sets the text. Returns true if the text was modified. The current // composition text will be confirmed first. Setting the same text, even with // an updated |cursor_position|, will neither add edit history nor change the // cursor because it's neither a user visible change nor user-initiated // change. This allows clients to set the same text multiple times without // messing up edit history. The resulting history edit will have // |new_cursor_pos| set to |cursor_position|. This is important even if // subsequent calls will override the cursor position because updating the // cursor alone won't update the edit history. I.e. the cursor position after // applying or redoing the edit will be determined by |cursor_position|. bool SetText(const std::u16string& new_text, size_t cursor_position); gfx::RenderText* render_text() { return render_text_.get(); } // Inserts given |new_text| at the current cursor position. // The current composition text will be cleared. void InsertText(const std::u16string& new_text) { InsertTextInternal(new_text, false); } // Inserts a character at the current cursor position. void InsertChar(char16_t c) { InsertTextInternal(std::u16string(&c, 1), true); } // Replaces characters at the current position with characters in given text. // The current composition text will be cleared. void ReplaceText(const std::u16string& new_text) { ReplaceTextInternal(new_text, false); } // Replaces the char at the current position with given character. void ReplaceChar(char16_t c) { ReplaceTextInternal(std::u16string(&c, 1), true); } // Appends the text. // The current composition text will be confirmed. void Append(const std::u16string& new_text); // Deletes the first character after the current cursor position (as if, the // the user has pressed delete key in the textfield). Returns true if // the deletion is successful. If |add_to_kill_buffer| is true, the deleted // text is copied to the kill buffer. // If there is composition text, it'll be deleted instead. bool Delete(bool add_to_kill_buffer = false); // Deletes the first character before the current cursor position (as if, the // the user has pressed backspace key in the textfield). Returns true if // the removal is successful. If |add_to_kill_buffer| is true, the deleted // text is copied to the kill buffer. // If there is composition text, it'll be deleted instead. bool Backspace(bool add_to_kill_buffer = false); // Cursor related methods. // Returns the current cursor position. size_t GetCursorPosition() const; // Moves the cursor, see RenderText for additional details. // The current composition text will be confirmed. void MoveCursor(gfx::BreakType break_type, gfx::VisualCursorDirection direction, gfx::SelectionBehavior selection_behavior); // Updates the cursor to the specified selection model. Any composition text // will be confirmed, which may alter the specified selection range start. bool MoveCursorTo(const gfx::SelectionModel& cursor); // Sugar for MoveCursorTo({0, CURSOR_FORWARD}). bool MoveCursorTo(size_t pos); // Calls the corresponding function on the associated RenderText instance. Any // composition text will be confirmed. bool MoveCursorTo(const gfx::Point& point, bool select); // Selection related methods. // Returns the primary selected text associated with the cursor. Does not // return secondary selections. std::u16string GetSelectedText() const; // The current composition text will be confirmed. If |primary| is true, the // selection starts with the range's start position and ends with the range's // end position; therefore the cursor position becomes the end position. If // |primary| is false, then the selection is not associated with the cursor. void SelectRange(const gfx::Range& range, bool primary = true); // The current composition text will be confirmed. // render_text_'s selection model is set to |sel|. void SelectSelectionModel(const gfx::SelectionModel& sel); // Select the entire text range. If |reversed| is true, the range will end at // the logical beginning of the text; this generally shows the leading portion // of text that overflows its display area. // The current composition text will be confirmed. void SelectAll(bool reversed); // Selects the word at which the cursor is currently positioned. If there is a // non-empty selection, the selection bounds are extended to their nearest // word boundaries. // The current composition text will be confirmed. void SelectWord(); // Clears selection. // The current composition text will be confirmed. void ClearSelection(); // Returns true if there is an undoable edit. bool CanUndo(); // Returns true if there is an redoable edit. bool CanRedo(); // Undo edit. Returns true if undo changed the text. bool Undo(); // Redo edit. Returns true if redo changed the text. bool Redo(); // Cuts the currently selected text and puts it to clipboard. Returns true // if text has changed after cutting. bool Cut(); // Copies the currently selected text and puts it to clipboard. Returns true // if something was copied to the clipboard. bool Copy(); // Pastes text from the clipboard at current cursor position. Returns true // if any text is pasted. bool Paste(); // Transposes the characters to either side of the insertion point and // advances the insertion point past both of them. Returns true if text is // changed. bool Transpose(); // Pastes text from the kill buffer at the current cursor position. Returns // true if the text has changed after yanking. bool Yank(); // Tells if any text is selected, even if the selection is in composition // text. |primary_only| indicates whether secondary selections should also be // considered. bool HasSelection(bool primary_only = false) const; // Deletes the selected text. This method shouldn't be called with // composition text. void DeleteSelection(); // Deletes the selected text (if any) and insert text at given position. void DeletePrimarySelectionAndInsertTextAt(const std::u16string& new_text, size_t position); // Retrieves the text content in a given range. std::u16string GetTextFromRange(const gfx::Range& range) const; // Retrieves the range containing all text in the model. void GetTextRange(gfx::Range* range) const; // Sets composition text and attributes. If there is composition text already, // it'll be replaced by the new one. Otherwise, current selection will be // replaced. If there is no selection, the composition text will be inserted // at the insertion point. // Any changes to the model except text insertion will confirm the current // composition text. void SetCompositionText(const ui::CompositionText& composition); #if BUILDFLAG(IS_CHROMEOS) // Return the text range corresponding to the autocorrected text. const gfx::Range& autocorrect_range() const { return autocorrect_range_; } // Sets the autocorrect range to |range|. If |range| is empty, then the // autocorrect range is cleared. Returns true if the range was set or cleared // successfully. bool SetAutocorrectRange(const gfx::Range& range); #endif // Puts the text in the specified range into composition mode. // This method should not be called with composition text or an invalid range. // The provided range is checked against the string's length, if |range| is // out of bounds, the composition will be cleared. void SetCompositionFromExistingText(const gfx::Range& range); // Converts current composition text into final content and returns the // length of the text committed. size_t ConfirmCompositionText(); // Removes current composition text. void CancelCompositionText(); // Retrieves the range of current composition text. void GetCompositionTextRange(gfx::Range* range) const; // Returns true if there is composition text. bool HasCompositionText() const; // Clears all edit history. void ClearEditHistory(); private: friend class internal::Edit; friend class test::BridgedNativeWidgetTest; friend class TextfieldModelTest; friend class test::TextfieldTest; FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_BasicTest); FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_CutCopyPasteTest); FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_ReplaceTest); // Insert the given |new_text| at the cursor. |mergeable| indicates if this // operation can be merged with previous edits in the history. Will delete any // selected text. void InsertTextInternal(const std::u16string& new_text, bool mergeable); // Replace the current selected text with the given |new_text|. |mergeable| // indicates if this operation can be merged with previous edits in the // history. void ReplaceTextInternal(const std::u16string& new_text, bool mergeable); // Clears redo history. void ClearRedoHistory(); // Executes and records edit operations. void ExecuteAndRecordDelete(std::vector<gfx::Range> ranges, bool mergeable); void ExecuteAndRecordReplaceSelection(internal::MergeType merge_type, const std::u16string& new_text); void ExecuteAndRecordReplace(internal::MergeType merge_type, std::vector<gfx::Range> replacement_range, size_t new_cursor_pos, const std::u16string& new_text, size_t new_text_start); void ExecuteAndRecordInsert(const std::u16string& new_text, bool mergeable); // Adds or merges |edit| into the edit history. void AddOrMergeEditHistory(std::unique_ptr<internal::Edit> edit); // Modify the text buffer in following way: // 1) Delete the |deletions|. // 2) Insert the |insertion_texts| at the |insertion_positions|. // 3) Select |primary_selection| and |secondary_selections|. // Deletions and insertions are applied in order and affect later edit // indices. E.g., given 'xyz', inserting 'A' at 1 and 'B' at 2 will result in // 'xAByz', not 'xAyBz'. On the other hand, inserting 'B' at 2 then 'A' at 1 // will result in 'xAyBz'. Thus, for applying or redoing edits, they should be // ordered with increasing indices; while for undoing edits, they should be // ordered decreasing. void ModifyText(const std::vector<gfx::Range>& deletions, const std::vector<std::u16string>& insertion_texts, const std::vector<size_t>& insertion_positions, const gfx::Range& primary_selection, const std::vector<gfx::Range>& secondary_selections); // Calls render_text->SetText() and delegate's callback. void SetRenderTextText(const std::u16string& text); void ClearComposition(); // Clears the kill buffer. Used to clear global state between tests. static void ClearKillBuffer(); // The TextfieldModel::Delegate instance should be provided by the owner. raw_ptr<Delegate> delegate_; // The stylized text, cursor, selection, and the visual layout model. std::unique_ptr<gfx::RenderText> render_text_; gfx::Range composition_range_; #if BUILDFLAG(IS_CHROMEOS) gfx::Range autocorrect_range_; #endif // The list of Edits. The oldest Edits are at the front of the list, and the // newest ones are at the back of the list. using EditHistory = std::list<std::unique_ptr<internal::Edit>>; EditHistory edit_history_; // An iterator that points to the current edit that can be undone. // This iterator moves from the |end()|, meaning no edit to undo, // to the last element (one before |end()|), meaning no edit to redo. // // There is no edit to undo (== end()) when: // 1) in initial state. (nothing to undo) // 2) very 1st edit is undone. // 3) all edit history is removed. // There is no edit to redo (== last element or no element) when: // 1) in initial state. (nothing to redo) // 2) new edit is added. (redo history is cleared) // 3) redone all undone edits. EditHistory::iterator current_edit_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_model.h
C++
unknown
14,469
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield_model.h" #include <stddef.h> #include <memory> #include <string> #include <vector> #include "base/auto_reset.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/range/range.h" #include "ui/gfx/render_text.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/test/test_views_delegate.h" #include "ui/views/test/views_test_base.h" namespace { struct WordAndCursor { WordAndCursor(const wchar_t* w, size_t c) : word(w), cursor(c) {} const wchar_t* word; size_t cursor; }; } // namespace namespace views { class TextfieldModelTest : public ViewsTestBase, public TextfieldModel::Delegate { public: TextfieldModelTest() = default; TextfieldModelTest(const TextfieldModelTest&) = delete; TextfieldModelTest& operator=(const TextfieldModelTest&) = delete; // ::testing::Test: void TearDown() override { // Clear kill buffer used for "Yank" text editing command so that no state // persists between tests. TextfieldModel::ClearKillBuffer(); ViewsTestBase::TearDown(); } void OnCompositionTextConfirmedOrCleared() override { composition_text_confirmed_or_cleared_ = true; } protected: void ResetModel(TextfieldModel* model) const { model->SetText(std::u16string(), 0); model->ClearEditHistory(); } const std::vector<std::u16string> GetAllSelectionTexts( TextfieldModel* model) const { std::vector<std::u16string> selected_texts; for (auto range : model->render_text()->GetAllSelections()) selected_texts.push_back(model->GetTextFromRange(range)); return selected_texts; } void VerifyAllSelectionTexts( TextfieldModel* model, std::vector<std::u16string> expected_selected_texts) const { std::vector<std::u16string> selected_texts = GetAllSelectionTexts(model); EXPECT_EQ(expected_selected_texts.size(), selected_texts.size()); for (size_t i = 0; i < selected_texts.size(); ++i) EXPECT_EQ(expected_selected_texts[i], selected_texts[i]); } bool composition_text_confirmed_or_cleared_ = false; }; TEST_F(TextfieldModelTest, EditString) { TextfieldModel model(nullptr); // Append two strings. model.Append(u"HILL"); EXPECT_EQ(u"HILL", model.text()); model.Append(u"WORLD"); EXPECT_EQ(u"HILLWORLD", model.text()); // Insert "E" and replace "I" with "L" to make "HELLO". model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.InsertChar('E'); EXPECT_EQ(u"HEILLWORLD", model.text()); model.ReplaceChar('L'); EXPECT_EQ(u"HELLLWORLD", model.text()); model.ReplaceChar('L'); model.ReplaceChar('O'); EXPECT_EQ(u"HELLOWORLD", model.text()); // Delete 6th char "W", then delete 5th char "O". EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"HELLOORLD", model.text()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(4U, model.GetCursorPosition()); EXPECT_EQ(u"HELLORLD", model.text()); // Move the cursor to start; backspace should fail. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_FALSE(model.Backspace()); EXPECT_EQ(u"HELLORLD", model.text()); // Move the cursor to the end; delete should fail, but backspace should work. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_FALSE(model.Delete()); EXPECT_EQ(u"HELLORLD", model.text()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"HELLORL", model.text()); model.MoveCursorTo(5); model.ReplaceText(u" WOR"); EXPECT_EQ(u"HELLO WORL", model.text()); } TEST_F(TextfieldModelTest, EditString_SimpleRTL) { TextfieldModel model(nullptr); // Append two strings. model.Append(u"\x05d0\x05d1\x05d2"); EXPECT_EQ(u"\x05d0\x05d1\x05d2", model.text()); model.Append(u"\x05e0\x05e1\x05e2"); EXPECT_EQ(u"\x05d0\x05d1\x05d2\x05e0\x05e1\x05e2", model.text()); // Insert "\x05f0". model.MoveCursorTo(1); model.InsertChar(0x05f0); EXPECT_EQ(u"\x05d0\x05f0\x05d1\x05d2\x05e0\x05e1\x05e2", model.text()); // Replace "\x05d1" with "\x05f1". model.ReplaceChar(0x05f1); EXPECT_EQ(u"\x05d0\x05f0\x5f1\x05d2\x05e0\x05e1\x05e2", model.text()); // Test Delete and backspace. EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"\x05d0\x05f0\x5f1\x05e0\x05e1\x05e2", model.text()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_EQ(u"\x05d0\x05f0\x05e0\x05e1\x05e2", model.text()); } TEST_F(TextfieldModelTest, EditString_ComplexScript) { TextfieldModel model(nullptr); // Append two Hindi strings. model.Append(u"\x0915\x093f\x0915\x094d\x0915"); EXPECT_EQ(u"\x0915\x093f\x0915\x094d\x0915", model.text()); model.Append(u"\x0915\x094d\x092e\x094d"); EXPECT_EQ(u"\x0915\x093f\x0915\x094d\x0915\x0915\x094d\x092e\x094d", model.text()); // Ensure the cursor cannot be placed in the middle of a grapheme. model.MoveCursorTo(1); EXPECT_EQ(0U, model.GetCursorPosition()); model.MoveCursorTo(2); EXPECT_EQ(2U, model.GetCursorPosition()); model.InsertChar('a'); EXPECT_EQ(u"\x0915\x093f\x0061\x0915\x094d\x0915\x0915\x094d\x092e\x094d", model.text()); // ReplaceChar will replace the whole grapheme. model.ReplaceChar('b'); // TODO(xji): temporarily disable in platform Win since the complex script // characters turned into empty square due to font regression. So, not able // to test 2 characters belong to the same grapheme. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) EXPECT_EQ(u"\x0915\x093f\x0061\x0062\x0915\x094d\x092e\x094d", model.text()); #endif EXPECT_EQ(4U, model.GetCursorPosition()); // Delete should delete the whole grapheme. model.MoveCursorTo(0); // TODO(xji): temporarily disable in platform Win since the complex script // characters turned into empty square due to font regression. So, not able // to test 2 characters belong to the same grapheme. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"\x0061\x0062\x0915\x094d\x092e\x094d", model.text()); model.MoveCursorTo(model.text().length()); EXPECT_EQ(model.text().length(), model.GetCursorPosition()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"\x0061\x0062\x0915\x094d\x092e", model.text()); #endif // Test cursor position and deletion for Hindi Virama. model.SetText(u"\x0D38\x0D4D\x0D15\x0D16\x0D2E", 0); model.MoveCursorTo(0); EXPECT_EQ(0U, model.GetCursorPosition()); model.MoveCursorTo(1); EXPECT_EQ(0U, model.GetCursorPosition()); model.MoveCursorTo(3); EXPECT_EQ(3U, model.GetCursorPosition()); // TODO(asvitkine): Temporarily disable the following check on Windows. It // seems Windows treats "\x0D38\x0D4D\x0D15" as a single grapheme. #if !BUILDFLAG(IS_WIN) model.MoveCursorTo(2); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"\x0D38\x0D4D\x0D16\x0D2E", model.text()); #endif model.SetText(u"\x05d5\x05b7\x05D9\x05B0\x05D4\x05B4\x05D9", 0); model.MoveCursorTo(0); EXPECT_TRUE(model.Delete()); EXPECT_TRUE(model.Delete()); EXPECT_TRUE(model.Delete()); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"", model.text()); // The first 2 characters are not strong directionality characters. model.SetText(u"\x002C\x0020\x05D1\x05BC\x05B7\x05E9\x05BC", 0); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"\x002C\x0020\x05D1\x05BC\x05B7\x05E9", model.text()); // Halfwidth katakana ダ: // "HALFWIDTH KATAKANA LETTER TA" + "HALFWIDTH KATAKANA VOICED SOUND MARK" // ("ABC" prefix as sanity check that the entire string isn't deleted). model.SetText(u"ABC\xFF80\xFF9E", 0); model.MoveCursorTo(model.text().length()); model.Backspace(); #if BUILDFLAG(IS_MAC) // On Mac, the entire cluster should be deleted to match // NSTextField behavior. EXPECT_EQ(u"ABC", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); #else EXPECT_EQ(u"ABC\xFF80", model.text()); EXPECT_EQ(4U, model.GetCursorPosition()); #endif // Emoji with Fitzpatrick modifier: // 'BOY' + 'EMOJI MODIFIER FITZPATRICK TYPE-5' model.SetText(u"\U0001F466\U0001F3FE", 0); model.MoveCursorTo(model.text().length()); model.Backspace(); #if BUILDFLAG(IS_MAC) // On Mac, the entire emoji should be deleted to match NSTextField // behavior. EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); #else // https://crbug.com/829040 EXPECT_EQ(u"\U0001F466", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); #endif } TEST_F(TextfieldModelTest, EmptyString) { TextfieldModel model(nullptr); EXPECT_EQ(std::u16string(), model.text()); EXPECT_EQ(std::u16string(), model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(0U, model.GetCursorPosition()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_EQ(std::u16string(), model.GetSelectedText()); EXPECT_FALSE(model.Delete()); EXPECT_FALSE(model.Backspace()); } TEST_F(TextfieldModelTest, Selection) { TextfieldModel model(nullptr); model.Append(u"HELLO"); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"E", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"EL", model.GetSelectedText()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"H", model.GetSelectedText()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"ELLO", model.GetSelectedText()); model.ClearSelection(); EXPECT_EQ(std::u16string(), model.GetSelectedText()); // SelectAll(false) selects towards the end. model.SelectAll(false); EXPECT_EQ(u"HELLO", model.GetSelectedText()); EXPECT_EQ(gfx::Range(0, 5), model.render_text()->selection()); // SelectAll(true) selects towards the beginning. model.SelectAll(true); EXPECT_EQ(u"HELLO", model.GetSelectedText()); EXPECT_EQ(gfx::Range(5, 0), model.render_text()->selection()); // Select and move cursor. model.SelectRange(gfx::Range(1U, 3U)); EXPECT_EQ(u"EL", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_EQ(1U, model.GetCursorPosition()); model.SelectRange(gfx::Range(1U, 3U)); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(3U, model.GetCursorPosition()); // Select multiple ranges and move cursor. model.SelectRange(gfx::Range(1U, 3U)); model.SelectRange(gfx::Range(5U, 4U), false); EXPECT_EQ(u"EL", model.GetSelectedText()); EXPECT_EQ(3U, model.GetCursorPosition()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); model.SelectRange(gfx::Range(1U, 3U)); model.SelectRange(gfx::Range(4U, 5U), false); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Select all and move cursor. model.SelectAll(false); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_EQ(0U, model.GetCursorPosition()); model.SelectAll(false); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(5U, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, Selection_BidiWithNonSpacingMarks) { // Selection is a logical operation. And it should work with the arrow // keys doing visual movements, while the selection is logical between // the (logical) start and end points. Selection is simply defined as // the portion of text between the logical positions of the start and end // caret positions. TextfieldModel model(nullptr); // TODO(xji): temporarily disable in platform Win since the complex script // characters turned into empty square due to font regression. So, not able // to test 2 characters belong to the same grapheme. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) model.Append( u"abc\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" u"def"); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(gfx::Range(2, 3), model.render_text()->selection()); EXPECT_EQ(u"c", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(gfx::Range(2, 7), model.render_text()->selection()); EXPECT_EQ(u"c\x05E9\x05BC\x05C1\x05B8", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(gfx::Range(2, 3), model.render_text()->selection()); EXPECT_EQ(u"c", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(gfx::Range(2, 10), model.render_text()->selection()); EXPECT_EQ( u"c\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" u"d", model.GetSelectedText()); model.ClearSelection(); EXPECT_EQ(std::u16string(), model.GetSelectedText()); model.SelectAll(false); EXPECT_EQ( u"abc\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" u"def", model.GetSelectedText()); #endif // In case of "aBc", this test shows how to select "aB" or "Bc", assume 'B' is // an RTL character. model.SetText( u"a\x05E9" u"b", 0); model.MoveCursorTo(0); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"a", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"a", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ( u"a\x05E9" u"b", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(3U, model.GetCursorPosition()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"b", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"b", model.GetSelectedText()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ( u"a\x05E9" u"b", model.GetSelectedText()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"a\x05E9", model.GetSelectedText()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ( u"\x05E9" u"b", model.GetSelectedText()); model.ClearSelection(); EXPECT_EQ(std::u16string(), model.GetSelectedText()); model.SelectAll(false); EXPECT_EQ( u"a\x05E9" u"b", model.GetSelectedText()); } TEST_F(TextfieldModelTest, SelectionAndEdit) { TextfieldModel model(nullptr); model.Append(u"HELLO"); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); // "EL" EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"HLO", model.text()); model.Append(u"ILL"); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); // "LO" EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"HILL", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); // "I" model.InsertChar('E'); EXPECT_EQ(u"HELL", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); // "H" model.ReplaceChar('B'); EXPECT_EQ(u"BELL", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); // "ELL" model.ReplaceChar('E'); EXPECT_EQ(u"BEE", model.text()); } TEST_F(TextfieldModelTest, SelectionAndEdit_WithSecondarySelection) { // Backspace TextfieldModel model(nullptr); model.Append(u"asynchronous promises make the moon spin?"); model.SelectRange(gfx::Range(0U, 4U)); model.SelectRange(gfx::Range(17U, 19U), false); model.SelectRange(gfx::Range(15U, 7U), false); model.SelectRange(gfx::Range(41U, 20U), false); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"chrome", model.text()); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Delete with an empty primary selection model.Append(u" is constructor overloading bad?"); model.SelectRange(gfx::Range(1U, 1U)); model.SelectRange(gfx::Range(22U, 12U), false); model.SelectRange(gfx::Range(26U, 23U), false); model.SelectRange(gfx::Range(27U, 38U), false); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"chrome is cool", model.text()); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Insert model.Append(u" are inherited classes heavy?"); model.SelectRange(gfx::Range(27U, 16U)); model.SelectRange(gfx::Range(41U, 34U), false); model.SelectRange(gfx::Range(42U, 43U), false); model.InsertChar('n'); EXPECT_EQ(u"chrome is cool and classy", model.text()); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(17U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Replace model.Append(u"help! why can't i instantiate an abstract sun!?"); model.SelectRange(gfx::Range(71U, 72U)); model.SelectRange(gfx::Range(30U, 70U), false); model.SelectRange(gfx::Range(29U, 25U), false); model.ReplaceChar('!'); EXPECT_EQ(u"chrome is cool and classy!!!", model.text()); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_EQ(28U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); } TEST_F(TextfieldModelTest, Word) { TextfieldModel model(nullptr); model.Append(u"The answer to Life, the Universe, and Everything"); #if BUILDFLAG(IS_WIN) // Move right by word includes space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(4U, model.GetCursorPosition()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(11U, model.GetCursorPosition()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); // Should pass the non word chars ', ' and be at the start of "the". EXPECT_EQ(20U, model.GetCursorPosition()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(24U, model.GetCursorPosition()); EXPECT_EQ(u"the ", model.GetSelectedText()); // Move to the end. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"the Universe, and Everything", model.GetSelectedText()); // Should be safe to go next word at the end. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"the Universe, and Everything", model.GetSelectedText()); model.InsertChar('2'); EXPECT_EQ(21U, model.GetCursorPosition()); // Now backwards. model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); // leave 2. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(14U, model.GetCursorPosition()); EXPECT_EQ(u"Life, ", model.GetSelectedText()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"to Life, ", model.GetSelectedText()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); // Now at start. EXPECT_EQ(u"The answer to Life, ", model.GetSelectedText()); // Should be safe to go to the previous word at the beginning. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"The answer to Life, ", model.GetSelectedText()); model.ReplaceChar('4'); EXPECT_EQ(std::u16string(), model.GetSelectedText()); EXPECT_EQ(u"42", model.text()); #else // Non-Windows: move right by word does NOT include space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(3U, model.GetCursorPosition()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(10U, model.GetCursorPosition()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(18U, model.GetCursorPosition()); // Should passes the non word char ',' model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(23U, model.GetCursorPosition()); EXPECT_EQ(u", the", model.GetSelectedText()); // Move to the end. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u", the Universe, and Everything", model.GetSelectedText()); // Should be safe to go next word at the end. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); EXPECT_EQ(u", the Universe, and Everything", model.GetSelectedText()); model.InsertChar('2'); EXPECT_EQ(19U, model.GetCursorPosition()); // Now backwards. model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); // leave 2. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(14U, model.GetCursorPosition()); EXPECT_EQ(u"Life", model.GetSelectedText()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"to Life", model.GetSelectedText()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); // Now at start. EXPECT_EQ(u"The answer to Life", model.GetSelectedText()); // Should be safe to go to the previous word at the beginning. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"The answer to Life", model.GetSelectedText()); model.ReplaceChar('4'); EXPECT_EQ(std::u16string(), model.GetSelectedText()); EXPECT_EQ(u"42", model.text()); #endif } TEST_F(TextfieldModelTest, SetText) { TextfieldModel model(nullptr); model.Append(u"HELLO"); // SetText moves cursor to the indicated position. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SetText(u"GOODBYE", 6); EXPECT_EQ(u"GOODBYE", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); model.SetText(u"SUNSET", 6); EXPECT_EQ(u"SUNSET", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); model.SelectAll(false); EXPECT_EQ(u"SUNSET", model.GetSelectedText()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(6U, model.GetCursorPosition()); // Setting text to the current text should not modify the cursor position. model.SetText(u"SUNSET", 3); EXPECT_EQ(u"SUNSET", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); // Setting text that's shorter than the indicated cursor moves the cursor to // the text end. model.SetText(u"BYE", 5); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_EQ(std::u16string(), model.GetSelectedText()); // SetText with empty string. model.SetText(std::u16string(), 0); EXPECT_EQ(0U, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, Clipboard) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); const std::u16string initial_clipboard_text = u"initial text"; ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(initial_clipboard_text); std::u16string clipboard_text; TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); // Cut with an empty selection should do nothing. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_FALSE(model.Cut()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(initial_clipboard_text, clipboard_text); EXPECT_EQ(u"HELLO WORLD", model.text()); EXPECT_EQ(11U, model.GetCursorPosition()); // Copy with an empty selection should do nothing. EXPECT_FALSE(model.Copy()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(initial_clipboard_text, clipboard_text); EXPECT_EQ(u"HELLO WORLD", model.text()); EXPECT_EQ(11U, model.GetCursorPosition()); // Cut on obscured (password) text should do nothing. model.render_text()->SetObscured(true); model.SelectAll(false); EXPECT_FALSE(model.Cut()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(initial_clipboard_text, clipboard_text); EXPECT_EQ(u"HELLO WORLD", model.text()); EXPECT_EQ(u"HELLO WORLD", model.GetSelectedText()); // Copy on obscured (password) text should do nothing. model.SelectAll(false); EXPECT_FALSE(model.Copy()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(initial_clipboard_text, clipboard_text); EXPECT_EQ(u"HELLO WORLD", model.text()); EXPECT_EQ(u"HELLO WORLD", model.GetSelectedText()); // Cut with non-empty selection. model.render_text()->SetObscured(false); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_TRUE(model.Cut()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"WORLD", clipboard_text); EXPECT_EQ(u"HELLO ", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); // Copy with non-empty selection. model.SelectAll(false); EXPECT_TRUE(model.Copy()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"HELLO ", clipboard_text); EXPECT_EQ(u"HELLO ", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); // Test that paste works regardless of the obscured bit. Please note that // trailing spaces and tabs in clipboard strings will be stripped. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"HELLO HELLO", model.text()); EXPECT_EQ(11U, model.GetCursorPosition()); model.render_text()->SetObscured(true); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"HELLO HELLOHELLO", model.text()); EXPECT_EQ(16U, model.GetCursorPosition()); // Paste should replace the selection. model.render_text()->SetObscured(false); model.SetText(u"It's time to say goodbye.", 0); model.SelectRange({17, 24}); EXPECT_TRUE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"HELLO ", clipboard_text); EXPECT_EQ(u"It's time to say HELLO.", model.text()); EXPECT_EQ(22U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Paste with an empty clipboard should not replace the selection. ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); model.SelectRange({5, 8}); EXPECT_FALSE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_TRUE(clipboard_text.empty()); EXPECT_EQ(u"It's time to say HELLO.", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_EQ(u"tim", model.GetSelectedText()); } TEST_F(TextfieldModelTest, Clipboard_WithSecondarySelections) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); const std::u16string initial_clipboard_text = u"initial text"; ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(initial_clipboard_text); std::u16string clipboard_text; TextfieldModel model(nullptr); model.Append(u"It's time to say HELLO."); // Cut with multiple selections should copy only the primary selection but // delete all selections. model.SelectRange({0, 5}); model.SelectRange({13, 17}, false); EXPECT_TRUE(model.Cut()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"It's ", clipboard_text); EXPECT_EQ(u"time to HELLO.", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Copy with multiple selections should copy only the primary selection and // retain multiple selections. model.SelectRange({13, 8}); model.SelectRange({0, 4}, false); EXPECT_TRUE(model.Copy()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"HELLO", clipboard_text); EXPECT_EQ(u"time to HELLO.", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_TRUE(model.HasSelection()); VerifyAllSelectionTexts(&model, {u"HELLO", u"time"}); // Paste with multiple selections should paste at the primary selection and // delete all selections. model.SelectRange({0, 1}); model.SelectRange({5, 8}, false); model.SelectRange({14, 14}, false); EXPECT_TRUE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"HELLO", clipboard_text); EXPECT_EQ(u"HELLOime HELLO.", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.render_text()->secondary_selections().empty()); // Paste with multiple selections and an empty clipboard should not change the // text or selections. ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); model.SelectRange({1, 2}); model.SelectRange({4, 5}, false); EXPECT_FALSE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_TRUE(clipboard_text.empty()); EXPECT_EQ(u"HELLOime HELLO.", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"E", u"O"}); // Cut with an empty primary selection and nonempty secondary selections // should neither delete the secondary selection nor replace the clipboard. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(initial_clipboard_text); model.SelectRange({2, 2}); model.SelectRange({4, 5}, false); EXPECT_FALSE(model.Cut()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"initial text", clipboard_text); EXPECT_EQ(u"HELLOime HELLO.", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"", u"O"}); // Copy with an empty primary selection and nonempty secondary selections // should not replace the clipboard. EXPECT_FALSE(model.Copy()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"initial text", clipboard_text); EXPECT_EQ(u"HELLOime HELLO.", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"", u"O"}); // Paste with an empty primary selection, nonempty secondary selection, and // empty clipboard should change neither the text nor the selections. ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); EXPECT_FALSE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_TRUE(clipboard_text.empty()); EXPECT_EQ(u"HELLOime HELLO.", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"", u"O"}); // Paste with an empty primary selection and nonempty secondary selections // should paste at the primary selection and delete the secondary selections. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(initial_clipboard_text); EXPECT_TRUE(model.Paste()); clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr, &clipboard_text); EXPECT_EQ(u"initial text", clipboard_text); EXPECT_EQ(u"HEinitial textLLime HELLO.", model.text()); EXPECT_EQ(14U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); } static void SelectWordTestVerifier( const TextfieldModel& model, const std::u16string& expected_selected_string, size_t expected_cursor_pos) { EXPECT_EQ(expected_selected_string, model.GetSelectedText()); EXPECT_EQ(expected_cursor_pos, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, SelectWordTest) { TextfieldModel model(nullptr); model.Append(u" HELLO !! WO RLD "); // Test when cursor is at the beginning. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.SelectWord(); SelectWordTestVerifier(model, u" ", 2U); // Test when cursor is at the beginning of a word. model.MoveCursorTo(2); model.SelectWord(); SelectWordTestVerifier(model, u"HELLO", 7U); // Test when cursor is at the end of a word. model.MoveCursorTo(15); model.SelectWord(); SelectWordTestVerifier(model, u" ", 20U); // Test when cursor is somewhere in a non-alpha-numeric fragment. for (size_t cursor_pos = 8; cursor_pos < 13U; cursor_pos++) { model.MoveCursorTo(cursor_pos); model.SelectWord(); SelectWordTestVerifier(model, u" !! ", 13U); } // Test when cursor is somewhere in a whitespace fragment. model.MoveCursorTo(17); model.SelectWord(); SelectWordTestVerifier(model, u" ", 20U); // Test when cursor is at the end. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SelectWord(); SelectWordTestVerifier(model, u" ", 24U); } // TODO(xji): temporarily disable in platform Win since the complex script // characters and Chinese characters are turned into empty square due to font // regression. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) TEST_F(TextfieldModelTest, SelectWordTest_MixScripts) { TextfieldModel model(nullptr); std::vector<WordAndCursor> word_and_cursor; word_and_cursor.emplace_back(L"a\x05d0", 2); word_and_cursor.emplace_back(L"a\x05d0", 2); word_and_cursor.emplace_back(L"\x05d1\x05d2", 5); word_and_cursor.emplace_back(L"\x05d1\x05d2", 5); word_and_cursor.emplace_back(L" ", 3); word_and_cursor.emplace_back(L"a\x05d0", 2); word_and_cursor.emplace_back(L"\x0915\x094d\x0915", 9); word_and_cursor.emplace_back(L" ", 10); word_and_cursor.emplace_back(L"\x4E2D\x56FD", 12); word_and_cursor.emplace_back(L"\x4E2D\x56FD", 12); word_and_cursor.emplace_back(L"\x82B1", 13); word_and_cursor.emplace_back(L"\x5929", 14); // The text consists of Ascii, Hebrew, Hindi with Virama sign, and Chinese. model.SetText( u"a\x05d0 \x05d1\x05d2 \x0915\x094d\x0915 " u"\x4E2D\x56FD\x82B1\x5929", 0); for (size_t i = 0; i < word_and_cursor.size(); ++i) { model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); for (size_t j = 0; j < i; ++j) model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SelectWord(); SelectWordTestVerifier(model, base::WideToUTF16(word_and_cursor[i].word), word_and_cursor[i].cursor); } } #endif TEST_F(TextfieldModelTest, RangeTest) { TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); gfx::Range range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); #if BUILDFLAG(IS_WIN) // Move/select right by word includes space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_FALSE(range.is_reversed()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(6U, range.end()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(5U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); // now from the end. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(11U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_TRUE(range.is_reversed()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(6U, range.end()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_TRUE(range.is_reversed()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(7U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(11U, range.end()); #else // Non-Windows: move/select right by word does NOT include space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_FALSE(range.is_reversed()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(5U, range.end()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(4U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); // now from the end. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(11U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_TRUE(range.is_reversed()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(6U, range.end()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_TRUE(range.is_reversed()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(7U, range.end()); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_TRUE(range.is_empty()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(11U, range.end()); #endif // Select All model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); range = model.render_text()->selection(); EXPECT_FALSE(range.is_empty()); EXPECT_TRUE(range.is_reversed()); EXPECT_EQ(11U, range.start()); EXPECT_EQ(0U, range.end()); } TEST_F(TextfieldModelTest, SelectRangeTest) { TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); gfx::Range range(0, 6); EXPECT_FALSE(range.is_reversed()); model.SelectRange(range); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"HELLO ", model.GetSelectedText()); range = gfx::Range(6, 1); EXPECT_TRUE(range.is_reversed()); model.SelectRange(range); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"ELLO ", model.GetSelectedText()); range = gfx::Range(2, 1000); EXPECT_FALSE(range.is_reversed()); model.SelectRange(range); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"LLO WORLD", model.GetSelectedText()); range = gfx::Range(1000, 3); EXPECT_TRUE(range.is_reversed()); model.SelectRange(range); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"LO WORLD", model.GetSelectedText()); range = gfx::Range(0, 0); EXPECT_TRUE(range.is_empty()); model.SelectRange(range); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.GetSelectedText().empty()); range = gfx::Range(3, 3); EXPECT_TRUE(range.is_empty()); model.SelectRange(range); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.GetSelectedText().empty()); range = gfx::Range(1000, 100); EXPECT_FALSE(range.is_empty()); model.SelectRange(range); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.GetSelectedText().empty()); range = gfx::Range(1000, 1000); EXPECT_TRUE(range.is_empty()); model.SelectRange(range); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.GetSelectedText().empty()); EXPECT_TRUE(range.is_empty()); model.SelectRange({1, 5}); model.SelectRange({100, 7}, false); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"ELLO", model.GetSelectedText()); VerifyAllSelectionTexts(&model, {u"ELLO", u"ORLD"}); } TEST_F(TextfieldModelTest, SelectionTest) { TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); gfx::Range selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0), selection); #if BUILDFLAG(IS_WIN) // Select word right includes trailing space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0, 6), selection); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0, 5), selection); #else // Non-Windows: select word right does NOT include space/punctuation. model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0, 5), selection); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0, 4), selection); #endif model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(0), selection); // now from the end. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(11), selection); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(11, 6), selection); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(11, 7), selection); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(11), selection); // Select All model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); selection = model.render_text()->selection(); EXPECT_EQ(gfx::Range(11, 0), selection); } TEST_F(TextfieldModelTest, SelectSelectionModelTest) { TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); model.SelectSelectionModel( gfx::SelectionModel(gfx::Range(0, 6), gfx::CURSOR_BACKWARD)); EXPECT_EQ(u"HELLO ", model.GetSelectedText()); model.SelectSelectionModel( gfx::SelectionModel(gfx::Range(6, 1), gfx::CURSOR_FORWARD)); EXPECT_EQ(u"ELLO ", model.GetSelectedText()); model.SelectSelectionModel( gfx::SelectionModel(gfx::Range(2, 1000), gfx::CURSOR_BACKWARD)); EXPECT_EQ(u"LLO WORLD", model.GetSelectedText()); model.SelectSelectionModel( gfx::SelectionModel(gfx::Range(1000, 3), gfx::CURSOR_FORWARD)); EXPECT_EQ(u"LO WORLD", model.GetSelectedText()); model.SelectSelectionModel(gfx::SelectionModel(0, gfx::CURSOR_FORWARD)); EXPECT_TRUE(model.GetSelectedText().empty()); model.SelectSelectionModel(gfx::SelectionModel(3, gfx::CURSOR_FORWARD)); EXPECT_TRUE(model.GetSelectedText().empty()); model.SelectSelectionModel( gfx::SelectionModel(gfx::Range(1000, 100), gfx::CURSOR_FORWARD)); EXPECT_TRUE(model.GetSelectedText().empty()); model.SelectSelectionModel(gfx::SelectionModel(1000, gfx::CURSOR_BACKWARD)); EXPECT_TRUE(model.GetSelectedText().empty()); gfx::SelectionModel mutliselection_selection_model{{2, 3}, gfx::CURSOR_BACKWARD}; mutliselection_selection_model.AddSecondarySelection({5, 4}); mutliselection_selection_model.AddSecondarySelection({1, 0}); mutliselection_selection_model.AddSecondarySelection({20, 9}); mutliselection_selection_model.AddSecondarySelection({6, 6}); model.SelectSelectionModel(mutliselection_selection_model); EXPECT_EQ(u"L", model.GetSelectedText()); VerifyAllSelectionTexts(&model, {u"L", u"O", u"H", u"LD", u""}); } TEST_F(TextfieldModelTest, CompositionTextTest) { TextfieldModel model(this); model.Append(u"1234590"); model.SelectRange(gfx::Range(5, 5)); EXPECT_FALSE(model.HasSelection()); EXPECT_EQ(5U, model.GetCursorPosition()); gfx::Range range; model.GetTextRange(&range); EXPECT_EQ(gfx::Range(0, 7), range); ui::CompositionText composition; composition.text = u"678"; composition.ime_text_spans.emplace_back(ui::ImeTextSpan::Type::kComposition, 0, 3, ui::ImeTextSpan::Thickness::kThin); // Cursor should be at the end of composition when characters are just typed. composition.selection = gfx::Range(3, 3); model.SetCompositionText(composition); EXPECT_TRUE(model.HasCompositionText()); EXPECT_FALSE(model.HasSelection()); // Cancel the composition. model.CancelCompositionText(); composition_text_confirmed_or_cleared_ = false; // Restart composition with targeting "67" in "678". composition.selection = gfx::Range(1, 3); composition.ime_text_spans.clear(); composition.ime_text_spans.emplace_back(ui::ImeTextSpan::Type::kComposition, 0, 2, ui::ImeTextSpan::Thickness::kThick); composition.ime_text_spans.emplace_back(ui::ImeTextSpan::Type::kComposition, 2, 3, ui::ImeTextSpan::Thickness::kThin); model.SetCompositionText(composition); EXPECT_TRUE(model.HasCompositionText()); EXPECT_TRUE(model.HasSelection()); #if !BUILDFLAG(IS_CHROMEOS_ASH) // |composition.selection| is ignored because SetCompositionText checks // if a thick underline exists first. EXPECT_EQ(gfx::Range(5, 7), model.render_text()->selection()); EXPECT_EQ(7U, model.render_text()->cursor_position()); #else // See SelectRangeInCompositionText(). EXPECT_EQ(gfx::Range(7, 5), model.render_text()->selection()); EXPECT_EQ(5U, model.render_text()->cursor_position()); #endif model.GetTextRange(&range); EXPECT_EQ(10U, range.end()); EXPECT_EQ(u"1234567890", model.text()); model.GetCompositionTextRange(&range); EXPECT_EQ(gfx::Range(5, 8), range); // Check the composition text. EXPECT_EQ(u"456", model.GetTextFromRange(gfx::Range(3, 6))); EXPECT_FALSE(composition_text_confirmed_or_cleared_); model.CancelCompositionText(); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_FALSE(model.HasCompositionText()); EXPECT_FALSE(model.HasSelection()); EXPECT_EQ(5U, model.GetCursorPosition()); model.SetCompositionText(composition); EXPECT_EQ(u"1234567890", model.text()); EXPECT_TRUE(model.SetText(u"1234567890", 0)); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); // Also test the case where a selection exists but a thick underline doesn't. composition.selection = gfx::Range(0, 1); composition.ime_text_spans.clear(); model.SetCompositionText(composition); EXPECT_EQ(u"1234567890678", model.text()); EXPECT_TRUE(model.HasSelection()); #if !BUILDFLAG(IS_CHROMEOS_ASH) EXPECT_EQ(gfx::Range(10, 11), model.render_text()->selection()); EXPECT_EQ(11U, model.render_text()->cursor_position()); #else // See SelectRangeInCompositionText(). EXPECT_EQ(gfx::Range(11, 10), model.render_text()->selection()); EXPECT_EQ(10U, model.render_text()->cursor_position()); #endif model.InsertText(u"-"); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"1234567890-", model.text()); EXPECT_FALSE(model.HasCompositionText()); EXPECT_FALSE(model.HasSelection()); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_EQ(u"-", model.GetSelectedText()); model.SetCompositionText(composition); EXPECT_EQ(u"1234567890678", model.text()); model.ReplaceText(u"-"); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"1234567890-", model.text()); EXPECT_FALSE(model.HasCompositionText()); EXPECT_FALSE(model.HasSelection()); model.SetCompositionText(composition); model.Append(u"-"); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"1234567890-678-", model.text()); model.SetCompositionText(composition); model.Delete(); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"1234567890-678-", model.text()); model.SetCompositionText(composition); model.Backspace(); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"1234567890-678-", model.text()); model.SetText(std::u16string(), 0); model.SetCompositionText(composition); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); model.SetCompositionText(composition); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"676788", model.text()); EXPECT_EQ(6U, model.GetCursorPosition()); model.SetCompositionText(composition); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"676788678", model.text()); model.SetText(std::u16string(), 0); model.SetCompositionText(composition); model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; model.SetCompositionText(composition); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_RETAIN); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678678", model.text()); model.SetCompositionText(composition); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678", model.text()); model.SetCompositionText(composition); gfx::SelectionModel sel( gfx::Range(model.render_text()->selection().start(), 0), gfx::CURSOR_FORWARD); model.MoveCursorTo(sel); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678678", model.text()); model.SetCompositionText(composition); model.SelectRange(gfx::Range(0, 3)); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678", model.text()); model.SetCompositionText(composition); model.SelectAll(false); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678", model.text()); model.SetCompositionText(composition); model.SelectWord(); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; EXPECT_EQ(u"678", model.text()); model.SetCompositionText(composition); model.ClearSelection(); EXPECT_TRUE(composition_text_confirmed_or_cleared_); composition_text_confirmed_or_cleared_ = false; model.SetCompositionText(composition); EXPECT_FALSE(model.Cut()); EXPECT_FALSE(composition_text_confirmed_or_cleared_); } TEST_F(TextfieldModelTest, UndoRedo_BasicTest) { TextfieldModel model(nullptr); model.InsertChar('a'); EXPECT_FALSE(model.Redo()); // There is nothing to redo. EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"a", model.text()); // Continuous inserts are treated as one edit. model.InsertChar('b'); model.InsertChar('c'); EXPECT_EQ(u"abc", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"a", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); // Undoing further shouldn't change the text. EXPECT_FALSE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_FALSE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); // Redoing to the latest text. EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"a", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"abc", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); // Backspace =============================== EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"ab", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"abc", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ab", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); // Continous backspaces are treated as one edit. EXPECT_TRUE(model.Backspace()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"", model.text()); // Extra backspace shouldn't affect the history. EXPECT_FALSE(model.Backspace()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ab", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"abc", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"a", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); // Clear history model.ClearEditHistory(); EXPECT_FALSE(model.Undo()); EXPECT_FALSE(model.Redo()); EXPECT_EQ(u"a", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); // Delete =============================== model.SetText(u"ABCDE", 0); model.ClearEditHistory(); model.MoveCursorTo(2); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"ABDE", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"BDE", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABDE", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABDE", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); // Continous deletes are treated as one edit. EXPECT_TRUE(model.Delete()); EXPECT_TRUE(model.Delete()); EXPECT_EQ(u"AB", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABDE", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"AB", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, UndoRedo_SetText) { // This is to test the undo/redo behavior of omnibox. TextfieldModel model(nullptr); // Simulate typing www.y while www.google.com and www.youtube.com are // autocompleted. model.InsertChar('w'); // w| EXPECT_EQ(u"w", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); model.SetText(u"www.google.com", 1); // w|ww.google.com model.SelectRange(gfx::Range(14, 1)); // w[ww.google.com] EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_EQ(u"www.google.com", model.text()); model.InsertChar('w'); // ww| EXPECT_EQ(u"ww", model.text()); model.SetText(u"www.google.com", 2); // ww|w.google.com model.SelectRange(gfx::Range(14, 2)); // ww[w.google.com] model.InsertChar('w'); // www| EXPECT_EQ(u"www", model.text()); model.SetText(u"www.google.com", 3); // www|.google.com model.SelectRange(gfx::Range(14, 3)); // www[.google.com] model.InsertChar('.'); // www.| EXPECT_EQ(u"www.", model.text()); model.SetText(u"www.google.com", 4); // www.|google.com model.SelectRange(gfx::Range(14, 4)); // www.[google.com] model.InsertChar('y'); // www.y| EXPECT_EQ(u"www.y", model.text()); model.SetText(u"www.youtube.com", 5); // www.y|outube.com EXPECT_EQ(u"www.youtube.com", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); // Undo until the initial edit. EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(4U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_FALSE(model.Undo()); // Redo until the last edit. EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(4U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"www.youtube.com", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_FALSE(model.Redo()); } TEST_F(TextfieldModelTest, UndoRedo_BackspaceThenSetText) { // This is to test the undo/redo behavior of omnibox. TextfieldModel model(nullptr); model.InsertChar('w'); EXPECT_EQ(u"w", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); model.SetText(u"www.google.com", 1); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(14U, model.GetCursorPosition()); EXPECT_TRUE(model.Backspace()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"www.google.c", model.text()); // Autocomplete sets the text. model.SetText(u"www.google.com/search=www.google.c", 12); EXPECT_EQ(u"www.google.com/search=www.google.c", model.text()); EXPECT_EQ(12U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.c", model.text()); EXPECT_EQ(12U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"www.google.com", model.text()); EXPECT_EQ(14U, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, UndoRedo_CutCopyPasteTest) { TextfieldModel model(nullptr); model.SetText(u"ABCDE", 5); EXPECT_FALSE(model.Redo()); // There is nothing to redo. // Test Cut. model.SelectRange(gfx::Range(1, 3)); // A[BC]DE EXPECT_EQ(3U, model.GetCursorPosition()); model.Cut(); // A|DE EXPECT_EQ(u"ADE", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // A[BC]DE EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->selection().EqualsIgnoringDirection( gfx::Range(1, 3))); EXPECT_TRUE(model.Undo()); // | EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_FALSE(model.Undo()); // There is no more to undo. | EXPECT_EQ(u"", model.text()); EXPECT_TRUE(model.Redo()); // ABCDE| EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // A|DE EXPECT_EQ(u"ADE", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_FALSE(model.Redo()); // There is no more to redo. A|DE EXPECT_EQ(u"ADE", model.text()); model.Paste(); // ABC|DE model.Paste(); // ABCBC|DE model.Paste(); // ABCBCBC|DE EXPECT_EQ(u"ABCBCBCDE", model.text()); EXPECT_EQ(7U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // ABCBC|DE EXPECT_EQ(u"ABCBCDE", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // ABC|DE EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // A|DE EXPECT_EQ(u"ADE", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // A[BC]DE EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->selection().EqualsIgnoringDirection( gfx::Range(1, 3))); EXPECT_TRUE(model.Undo()); // | EXPECT_EQ(u"", model.text()); EXPECT_EQ(0U, model.GetCursorPosition()); EXPECT_FALSE(model.Undo()); // | EXPECT_EQ(u"", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABCDE", model.text()); // ABCDE| EXPECT_EQ(5U, model.GetCursorPosition()); // Test Redo. EXPECT_TRUE(model.Redo()); // A|DE EXPECT_EQ(u"ADE", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // ABC|DE EXPECT_EQ(u"ABCDE", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // ABCBC|DE EXPECT_EQ(u"ABCBCDE", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // ABCBCBC|DE EXPECT_EQ(u"ABCBCBCDE", model.text()); EXPECT_EQ(7U, model.GetCursorPosition()); EXPECT_FALSE(model.Redo()); // ABCBCBC|DE // Test using SelectRange. model.SelectRange(gfx::Range(1, 3)); // A[BC]BCBCDE EXPECT_TRUE(model.Cut()); // A|BCBCDE EXPECT_EQ(u"ABCBCDE", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); model.SelectRange(gfx::Range(1, 1)); // A|BCBCDE EXPECT_FALSE(model.Cut()); // A|BCBCDE model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); // ABCBCDE| EXPECT_TRUE(model.Paste()); // ABCBCDEBC| EXPECT_EQ(u"ABCBCDEBC", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // ABCBCDE| EXPECT_EQ(u"ABCBCDE", model.text()); EXPECT_EQ(7U, model.GetCursorPosition()); // An empty cut shouldn't create an edit. EXPECT_TRUE(model.Undo()); // ABC|BCBCDE EXPECT_EQ(u"ABCBCBCDE", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->selection().EqualsIgnoringDirection( gfx::Range(1, 3))); // Test Copy. ResetModel(&model); model.SetText(u"12345", 5); // 12345| EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); model.SelectRange(gfx::Range(1, 3)); // 1[23]45 model.Copy(); // Copy "23". // 1[23]45 EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); model.Paste(); // Paste "23" into "23". // 123|45 EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); model.Paste(); // 12323|45 EXPECT_EQ(u"1232345", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // 123|45 EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); // TODO(oshima): Change the return type from bool to enum. EXPECT_FALSE(model.Undo()); // No text change. 1[23]45 EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.render_text()->selection().EqualsIgnoringDirection( gfx::Range(1, 3))); EXPECT_TRUE(model.Undo()); // | EXPECT_EQ(u"", model.text()); EXPECT_FALSE(model.Undo()); // | // Test Redo. EXPECT_TRUE(model.Redo()); // 12345| EXPECT_EQ(u"12345", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // 12|345 EXPECT_EQ(u"12345", model.text()); // For 1st paste EXPECT_EQ(3U, model.GetCursorPosition()); EXPECT_TRUE(model.Redo()); // 12323|45 EXPECT_EQ(u"1232345", model.text()); EXPECT_EQ(5U, model.GetCursorPosition()); EXPECT_FALSE(model.Redo()); // 12323|45 EXPECT_EQ(u"1232345", model.text()); // Test using SelectRange. model.SelectRange(gfx::Range(1, 3)); // 1[23]2345 model.Copy(); // 1[23]2345 EXPECT_EQ(u"1232345", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); // 1232345| EXPECT_TRUE(model.Paste()); // 123234523| EXPECT_EQ(u"123234523", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_TRUE(model.Undo()); // 1232345| EXPECT_EQ(u"1232345", model.text()); EXPECT_EQ(7U, model.GetCursorPosition()); } TEST_F(TextfieldModelTest, UndoRedo_CursorTest) { TextfieldModel model(nullptr); model.InsertChar('a'); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.InsertChar('b'); // Moving the cursor shouldn't create a new edit. EXPECT_EQ(u"ab", model.text()); EXPECT_FALSE(model.Redo()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_FALSE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ab", model.text()); EXPECT_EQ(2U, model.GetCursorPosition()); EXPECT_FALSE(model.Redo()); } TEST_F(TextfieldModelTest, Undo_SelectionTest) { gfx::Range range = gfx::Range(2, 4); TextfieldModel model(nullptr); model.SetText(u"abcdef", 0); model.SelectRange(range); EXPECT_EQ(model.render_text()->selection(), range); // Deleting the selected text should change the text and the range. EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"abef", model.text()); EXPECT_EQ(model.render_text()->selection(), gfx::Range(2, 2)); // Undoing the deletion should restore the former range. EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"abcdef", model.text()); EXPECT_EQ(model.render_text()->selection(), range); // When range.start = range.end, nothing is selected and // range.start = range.end = cursor position model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); EXPECT_EQ(model.render_text()->selection(), gfx::Range(2, 2)); // Deleting a single character should change the text and cursor location. EXPECT_TRUE(model.Backspace()); EXPECT_EQ(u"acdef", model.text()); EXPECT_EQ(model.render_text()->selection(), gfx::Range(1, 1)); // Undoing the deletion should restore the former range. EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"abcdef", model.text()); EXPECT_EQ(model.render_text()->selection(), gfx::Range(2, 2)); model.MoveCursorTo(model.text().length()); EXPECT_TRUE(model.Backspace()); model.SelectRange(gfx::Range(1, 3)); model.SetText(u"[set]", 0); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"abcde", model.text()); EXPECT_EQ(model.render_text()->selection(), gfx::Range(1, 3)); } void RunInsertReplaceTest(TextfieldModel* model) { const bool reverse = model->render_text()->selection().is_reversed(); model->InsertChar('1'); model->InsertChar('2'); model->InsertChar('3'); EXPECT_EQ(u"a123d", model->text()); EXPECT_EQ(4U, model->GetCursorPosition()); EXPECT_TRUE(model->Undo()); EXPECT_EQ(u"abcd", model->text()); EXPECT_EQ(reverse ? 1U : 3U, model->GetCursorPosition()); EXPECT_TRUE(model->Undo()); EXPECT_EQ(u"", model->text()); EXPECT_EQ(0U, model->GetCursorPosition()); EXPECT_FALSE(model->Undo()); EXPECT_TRUE(model->Redo()); EXPECT_EQ(u"abcd", model->text()); EXPECT_EQ(4U, model->GetCursorPosition()); EXPECT_TRUE(model->Redo()); EXPECT_EQ(u"a123d", model->text()); EXPECT_EQ(4U, model->GetCursorPosition()); EXPECT_FALSE(model->Redo()); } void RunOverwriteReplaceTest(TextfieldModel* model) { const bool reverse = model->render_text()->selection().is_reversed(); model->ReplaceChar('1'); model->ReplaceChar('2'); model->ReplaceChar('3'); model->ReplaceChar('4'); EXPECT_EQ(u"a1234", model->text()); EXPECT_EQ(5U, model->GetCursorPosition()); EXPECT_TRUE(model->Undo()); EXPECT_EQ(u"abcd", model->text()); EXPECT_EQ(reverse ? 1U : 3U, model->GetCursorPosition()); EXPECT_TRUE(model->Undo()); EXPECT_EQ(u"", model->text()); EXPECT_EQ(0U, model->GetCursorPosition()); EXPECT_FALSE(model->Undo()); EXPECT_TRUE(model->Redo()); EXPECT_EQ(u"abcd", model->text()); EXPECT_EQ(4U, model->GetCursorPosition()); EXPECT_TRUE(model->Redo()); EXPECT_EQ(u"a1234", model->text()); EXPECT_EQ(5U, model->GetCursorPosition()); EXPECT_FALSE(model->Redo()); } TEST_F(TextfieldModelTest, UndoRedo_ReplaceTest) { { SCOPED_TRACE("Select forwards and insert."); TextfieldModel model(nullptr); model.SetText(u"abcd", 4); model.SelectRange(gfx::Range(1, 3)); RunInsertReplaceTest(&model); } { SCOPED_TRACE("Select reversed and insert."); TextfieldModel model(nullptr); model.SetText(u"abcd", 4); model.SelectRange(gfx::Range(3, 1)); RunInsertReplaceTest(&model); } { SCOPED_TRACE("Select forwards and overwrite."); TextfieldModel model(nullptr); model.SetText(u"abcd", 4); model.SelectRange(gfx::Range(1, 3)); RunOverwriteReplaceTest(&model); } { SCOPED_TRACE("Select reversed and overwrite."); TextfieldModel model(nullptr); model.SetText(u"abcd", 4); model.SelectRange(gfx::Range(3, 1)); RunOverwriteReplaceTest(&model); } } TEST_F(TextfieldModelTest, UndoRedo_CompositionText) { TextfieldModel model(nullptr); ui::CompositionText composition; composition.text = u"abc"; composition.ime_text_spans.emplace_back(ui::ImeTextSpan::Type::kComposition, 0, 3, ui::ImeTextSpan::Thickness::kThin); composition.selection = gfx::Range(2, 3); model.SetText(u"ABCDE", 0); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.InsertChar('x'); EXPECT_EQ(u"ABCDEx", model.text()); EXPECT_TRUE(model.Undo()); // set composition should forget undone edit. model.SetCompositionText(composition); EXPECT_TRUE(model.HasCompositionText()); EXPECT_TRUE(model.HasSelection()); EXPECT_EQ(u"ABCDEabc", model.text()); // Confirm the composition. size_t composition_text_length = model.ConfirmCompositionText(); EXPECT_EQ(composition_text_length, 3u); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_FALSE(model.Redo()); // Cancel the composition. model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.SetCompositionText(composition); EXPECT_EQ(u"abcABCDEabc", model.text()); model.CancelCompositionText(); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_FALSE(model.Redo()); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_FALSE(model.Redo()); // Call SetText with the same text as the result. ResetModel(&model); model.SetText(u"ABCDE", 0); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SetCompositionText(composition); EXPECT_EQ(u"ABCDEabc", model.text()); model.SetText(u"ABCDEabc", 0); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"ABCDEabc", model.text()); EXPECT_FALSE(model.Redo()); // Call SetText with a different result; the composition should be forgotten. ResetModel(&model); model.SetText(u"ABCDE", 0); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SetCompositionText(composition); EXPECT_EQ(u"ABCDEabc", model.text()); model.SetText(u"1234", 0); EXPECT_EQ(u"1234", model.text()); EXPECT_TRUE(model.Undo()); EXPECT_EQ(u"ABCDE", model.text()); EXPECT_TRUE(model.Redo()); EXPECT_EQ(u"1234", model.text()); EXPECT_FALSE(model.Redo()); // TODO(oshima): Test the behavior with an IME. } TEST_F(TextfieldModelTest, UndoRedo_TypingWithSecondarySelections) { TextfieldModel model(nullptr); // Type 'ab cd' as 'prefix ab xy suffix' and 'prefix ab cd suffix' are // autocompleted. // Type 'a', autocomplete [prefix ]a[b xy suffix] model.InsertChar('a'); model.SetText(u"prefix ab xy suffix", 8); model.SelectRange({19, 8}); model.SelectRange({0, 7}, false); // Type 'ab', autocomplete [prefix ]ab[ xy suffix] model.InsertChar('b'); model.SetText(u"prefix ab xy suffix", 9); model.SelectRange({19, 9}); model.SelectRange({0, 7}, false); // Type 'ab ', autocomplete [prefix ]ab [xy suffix] model.InsertChar(' '); model.SetText(u"prefix ab xy suffix", 10); model.SelectRange({19, 10}); model.SelectRange({0, 7}, false); // Type 'ab c', autocomplete changed to [prefix ]ab c[d suffix] model.InsertChar('c'); model.SetText(u"prefix ab cd suffix", 11); model.SelectRange({19, 11}); model.SelectRange({0, 7}, false); // Type 'ab cd', autocomplete [prefix ]ab cd[ suffix] model.InsertChar('d'); model.SetText(u"prefix ab cd suffix", 12); model.SelectRange({19, 12}); model.SelectRange({0, 7}, false); // Undo 3 times EXPECT_TRUE(model.Undo()); // [prefix ]ab c[d suffix] EXPECT_EQ(u"prefix ab cd suffix", model.text()); EXPECT_EQ(11U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"d suffix", u"prefix "}); EXPECT_TRUE(model.Undo()); // [prefix ]ab [xy suffix] EXPECT_EQ(u"prefix ab xy suffix", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"xy suffix", u"prefix "}); EXPECT_TRUE(model.Undo()); // [prefix ]ab[ xy suffix] EXPECT_EQ(u"prefix ab xy suffix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u" xy suffix", u"prefix "}); // Redo 3 times EXPECT_TRUE(model.Redo()); // [prefix ]ab [xy suffix] EXPECT_EQ(u"prefix ab xy suffix", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // [prefix ]ab c[d suffix] EXPECT_EQ(u"prefix ab cd suffix", model.text()); EXPECT_EQ(11U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // [prefix ]ab cd[ suffix] EXPECT_EQ(u"prefix ab cd suffix", model.text()); EXPECT_EQ(12U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); } TEST_F(TextfieldModelTest, UndoRedo_MergingEditsWithSecondarySelections) { TextfieldModel model(nullptr); // Test all possible merge combinations involving secondary selections. // I.e. an initial [replace or delete] edit with secondary selections, // followed by a second and third [insert, replace, or delete] edits, which // are [continuous and discontinuous] respectively. Some cases of the third, // discontinuous edit have been omitted when the the second edit would not // been merged anyways. // Note, the cursor and selections depend on whether we're traversing forward // or backwards through edit history. I.e., `undo(); redo();` can result in a // different outcome than `redo(); undo();`. In general, if our edit history // consists of 3 edits: A->B, C->D, & E->F, then undo will traverse // F->E->C->A, while redo will traverse A->B->D->F. Though, B & C and D & E // will have the same text, they can have different cursors and selections. // Replacement with secondary selections followed by insertions model.SetText(u"prefix infix suffix", 13); model.SelectRange({18, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [suffi]x // Replace model.InsertChar('1'); // p infix 1|x // Continuous insert (should merge) model.InsertChar('3'); // p infix 13|x // Discontinuous insert (should not merge) model.SelectRange({9, 9}); // p infix 1|3x model.InsertChar('2'); // p infix 12|3x EXPECT_EQ(u"p infix 123x", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [suffi]x -> p infix 13|x // p infix 1|3x -> p infix 12|3x // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix 1|3x EXPECT_EQ(u"p infix 13x", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Undo()); // p[refix] infix [suffi]x EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"suffi", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix 13|x EXPECT_EQ(u"p infix 13x", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix 12|3x EXPECT_EQ(u"p infix 123x", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); // Replacement with secondary selections followed by replacements model.SetText(u"prefix infix suffix", 13); model.SelectRange({15, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [su]ffix // Replace model.InsertChar('1'); // p infix 1|ffix // Continuous multiple characters, and backwards replace (should merge) model.SelectRange({11, 9}); // p infix 1[ff]ix model.InsertChar('3'); // p infix 13|ix // Discontinuous but adjacent replace (should not merge) model.SelectRange({10, 9}); // p infix 1[3]ix model.InsertChar('2'); // p infix 12|ix EXPECT_EQ(u"p infix 12ix", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [su]ffix -> p infix 13|ix // p infix 1[3]ix -> p infix 12|ix // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix 1[3]ix EXPECT_EQ(u"p infix 13ix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"3"}); EXPECT_TRUE(model.Undo()); // p[refix] infix [su]ffix EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"su", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix 13|ix EXPECT_EQ(u"p infix 13ix", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix 12|ix EXPECT_EQ(u"p infix 12ix", model.text()); EXPECT_EQ(10U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); // Replacement with secondary selections followed by deletion model.SetText(u"prefix infix suffix", 13); model.SelectRange({15, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [su]ffix // Replace model.InsertChar('1'); // p infix 1|ffix // Continuous delete (should not merge) model.Delete(false); // p infix 1|fix EXPECT_EQ(u"p infix 1fix", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [su]ffix -> p infix 1|ffix // p infix 1|ffix -> p infix 1|fix // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix 1|ffix EXPECT_EQ(u"p infix 1ffix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Undo()); // p[refix] infix [su]ffix EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"su", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix 1|ffix EXPECT_EQ(u"p infix 1ffix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix 1|fix EXPECT_EQ(u"p infix 1fix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); // Deletion with secondary selections followed by insertion model.SetText(u"prefix infix suffix", 13); model.SelectRange({15, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [su]ffix // Delete model.Delete(false); // p infix |ffix // Continuous insert (should not merge) model.InsertChar('1'); // p infix 1|ffix EXPECT_EQ(u"p infix 1ffix", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [su]ffix -> p infix |ffix // p infix |ffix -> p infix 1|ffix // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix |ffix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Undo()); // p[refix] infix [su]ffix EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"su", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix |ffix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix 1|ffix EXPECT_EQ(u"p infix 1ffix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); // Deletion with secondary selections followed by replacement model.SetText(u"prefix infix suffix", 13); model.SelectRange({15, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [su]ffix // Delete model.Delete(false); // p infix |ffix // Continuous replacement (should not merge) model.SelectRange({8, 9}); // p infix [f]fix model.InsertChar('1'); // p infix 1|fix EXPECT_EQ(u"p infix 1fix", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [su]ffix -> p infix |ffix // p infix [f]fix -> p infix 1|fix // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix [f]fix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"f"}); EXPECT_TRUE(model.Undo()); // p[refix] infix [su]ffix EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"su", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix |ffix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix 1|fix EXPECT_EQ(u"p infix 1fix", model.text()); EXPECT_EQ(9U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); // Deletion with secondary selections followed by deletion model.SetText(u"prefix infix suffix", 13); model.SelectRange({15, 13}); model.SelectRange({1, 6}, false); // p[refix] infix [su]ffix // Delete model.Delete(false); // p infix |ffix // Continuous delete (should not merge) model.Delete(false); // p infix |fix EXPECT_EQ(u"p infix fix", model.text()); EXPECT_FALSE(model.HasSelection()); // Edit history should be // p[refix] infix [su]ffix -> p infix |ffix // p infix |ffix -> p infix |fix // Undo 2 times EXPECT_TRUE(model.Undo()); // p infix |ffix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Undo()); // p[refix] infix [su]ffix EXPECT_EQ(u"prefix infix suffix", model.text()); EXPECT_EQ(13U, model.GetCursorPosition()); VerifyAllSelectionTexts(&model, {u"su", u"refix"}); // Redo 2 times EXPECT_TRUE(model.Redo()); // p infix |ffix EXPECT_EQ(u"p infix ffix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_TRUE(model.Redo()); // p infix |fix EXPECT_EQ(u"p infix fix", model.text()); EXPECT_EQ(8U, model.GetCursorPosition()); EXPECT_FALSE(model.HasSelection()); EXPECT_FALSE(model.Redo()); } // Tests that clipboard text with leading, trailing and interspersed tabs // spaces etc is pasted correctly. Leading and trailing tabs should be // stripped. Text separated by multiple tabs/spaces should be left alone. // Text with just tabs and spaces should be pasted as one space. TEST_F(TextfieldModelTest, Clipboard_WhiteSpaceStringTest) { // Test 1 // Clipboard text with a leading tab should be pasted with the tab stripped. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste).WriteText(u"\tB"); TextfieldModel model(nullptr); model.Append(u"HELLO WORLD"); EXPECT_EQ(u"HELLO WORLD", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(11U, model.GetCursorPosition()); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"HELLO WORLDB", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 2 // Clipboard text with multiple leading tabs and spaces should be pasted with // all tabs and spaces stripped. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u"\t\t\t B"); model.Append(u"HELLO WORLD"); EXPECT_EQ(u"HELLO WORLD", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(11U, model.GetCursorPosition()); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"HELLO WORLDB", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 3 // Clipboard text with multiple tabs separating the words should be pasted // as-is. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u"FOO \t\t BAR"); model.Append(u"HELLO WORLD"); EXPECT_EQ(u"HELLO WORLD", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); EXPECT_EQ(11U, model.GetCursorPosition()); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"HELLO WORLDFOO \t\t BAR", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 4 // Clipboard text with multiple leading tabs and multiple tabs separating // the words should be pasted with the leading tabs stripped. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u"\t\tFOO \t\t BAR"); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"FOO \t\t BAR", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 5 // Clipboard text with multiple trailing tabs should be pasted with all // trailing tabs stripped. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u"FOO BAR\t\t\t"); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"FOO BAR", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 6 // Clipboard text with only spaces and tabs should be pasted as a single // space. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u" \t\t"); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u" ", model.text()); model.SelectAll(false); model.DeleteSelection(); EXPECT_EQ(u"", model.text()); // Test 7 // Clipboard text with lots of spaces between words should be pasted as-is. ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste) .WriteText(u"FOO BAR"); EXPECT_TRUE(model.Paste()); EXPECT_EQ(u"FOO BAR", model.text()); } TEST_F(TextfieldModelTest, Transpose) { const std::u16string ltr = u"12"; const std::u16string rtl = u"\x0634\x0632"; const std::u16string ltr_transposed = u"21"; const std::u16string rtl_transposed = u"\x0632\x0634"; // This is a string with an 'a' between two emojis. const std::u16string surrogate_pairs({0xD83D, 0xDE07, 'a', 0xD83D, 0xDE0E}); const std::u16string test_strings[] = {ltr, rtl, surrogate_pairs}; struct TestCase { gfx::Range range; std::u16string expected_text; gfx::Range expected_selection; }; std::vector<TestCase> ltr_tests = { {gfx::Range(0), ltr, gfx::Range(0)}, {gfx::Range(1), ltr_transposed, gfx::Range(2)}, {gfx::Range(2), ltr_transposed, gfx::Range(2)}, {gfx::Range(0, 2), ltr, gfx::Range(0, 2)}}; std::vector<TestCase> rtl_tests = { {gfx::Range(0), rtl, gfx::Range(0)}, {gfx::Range(1), rtl_transposed, gfx::Range(2)}, {gfx::Range(2), rtl_transposed, gfx::Range(2)}, {gfx::Range(0, 1), rtl, gfx::Range(0, 1)}}; // Only test at valid grapheme boundaries. std::vector<TestCase> surrogate_pairs_test = { {gfx::Range(0), surrogate_pairs, gfx::Range(0)}, {gfx::Range(2), std::u16string({'a', 0xD83D, 0xDE07, 0xD83D, 0xDE0E}), gfx::Range(3)}, {gfx::Range(3), std::u16string({0xD83D, 0xDE07, 0xD83D, 0xDE0E, 'a'}), gfx::Range(5)}, {gfx::Range(5), std::u16string({0xD83D, 0xDE07, 0xD83D, 0xDE0E, 'a'}), gfx::Range(5)}, {gfx::Range(3, 5), surrogate_pairs, gfx::Range(3, 5)}}; std::vector<std::vector<TestCase>> all_tests = {ltr_tests, rtl_tests, surrogate_pairs_test}; TextfieldModel model(nullptr); EXPECT_EQ(all_tests.size(), std::size(test_strings)); for (size_t i = 0; i < std::size(test_strings); i++) { for (size_t j = 0; j < all_tests[i].size(); j++) { SCOPED_TRACE(testing::Message() << "Testing case " << i << ", " << j << " with string " << test_strings[i]); const TestCase& test_case = all_tests[i][j]; model.SetText(test_strings[i], 0); model.SelectRange(test_case.range); EXPECT_EQ(test_case.range, model.render_text()->selection()); model.Transpose(); EXPECT_EQ(test_case.expected_text, model.text()); EXPECT_EQ(test_case.expected_selection, model.render_text()->selection()); } } } TEST_F(TextfieldModelTest, Yank) { TextfieldModel model(nullptr); model.SetText(u"abcdefgh", 0); model.SelectRange(gfx::Range(1, 3)); // Delete selection but don't add to kill buffer. model.Delete(false); EXPECT_EQ(u"adefgh", model.text()); // Since the kill buffer is empty, yank should cause no change. EXPECT_FALSE(model.Yank()); EXPECT_EQ(u"adefgh", model.text()); // With a nonempty selection and an empty kill buffer, yank should delete the // selection. model.SelectRange(gfx::Range(4, 5)); EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"adefh", model.text()); // With multiple selections and an empty kill buffer, yank should delete the // selections. model.SelectRange(gfx::Range(2, 3)); model.SelectRange(gfx::Range(4, 5), false); EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"adf", model.text()); // The kill buffer should remain empty after yanking without a kill buffer. EXPECT_FALSE(model.Yank()); EXPECT_EQ(u"adf", model.text()); // Delete selection and add to kill buffer. model.SelectRange(gfx::Range(0, 1)); model.Delete(true); EXPECT_EQ(u"df", model.text()); // Yank twice. EXPECT_TRUE(model.Yank()); EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"aadf", model.text()); // Ensure an empty deletion does not modify the kill buffer. model.SelectRange(gfx::Range(4)); model.Delete(true); EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"aadfa", model.text()); // Backspace twice but don't add to kill buffer. model.Backspace(false); model.Backspace(false); EXPECT_EQ(u"aad", model.text()); // Ensure kill buffer is not modified. EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"aada", model.text()); // Backspace twice, each time modifying the kill buffer. model.Backspace(true); model.Backspace(true); EXPECT_EQ(u"aa", model.text()); // Ensure yanking inserts the modified kill buffer text. EXPECT_TRUE(model.Yank()); EXPECT_EQ(u"aad", model.text()); } TEST_F(TextfieldModelTest, SetCompositionFromExistingText) { TextfieldModel model(nullptr); model.SetText(u"abcde", 0); model.SetCompositionFromExistingText(gfx::Range(0, 1)); EXPECT_TRUE(model.HasCompositionText()); model.SetCompositionFromExistingText(gfx::Range(1, 3)); EXPECT_TRUE(model.HasCompositionText()); ui::CompositionText composition; composition.text = u"123"; model.SetCompositionText(composition); EXPECT_EQ(u"a123de", model.text()); } TEST_F(TextfieldModelTest, SetCompositionFromExistingText_Empty) { TextfieldModel model(nullptr); model.SetText(u"abc", 0); model.SetCompositionFromExistingText(gfx::Range(0, 2)); EXPECT_TRUE(model.HasCompositionText()); model.SetCompositionFromExistingText(gfx::Range(1, 1)); EXPECT_FALSE(model.HasCompositionText()); EXPECT_EQ(u"abc", model.text()); } TEST_F(TextfieldModelTest, SetCompositionFromExistingText_OutOfBounds) { TextfieldModel model(nullptr); model.SetText(std::u16string(), 0); model.SetCompositionFromExistingText(gfx::Range(0, 2)); EXPECT_FALSE(model.HasCompositionText()); model.SetText(u"abc", 0); model.SetCompositionFromExistingText(gfx::Range(1, 4)); EXPECT_FALSE(model.HasCompositionText()); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_model_unittest.cc
C++
unknown
101,386
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield_test_api.h" #include "ui/gfx/geometry/rect.h" namespace views { TextfieldTestApi::TextfieldTestApi(Textfield* textfield) : textfield_(textfield) { DCHECK(textfield); } void TextfieldTestApi::UpdateContextMenu() { textfield_->UpdateContextMenu(); } gfx::RenderText* TextfieldTestApi::GetRenderText() const { return textfield_->GetRenderText(); } void TextfieldTestApi::CreateTouchSelectionControllerAndNotifyIt() { textfield_->CreateTouchSelectionControllerAndNotifyIt(); } void TextfieldTestApi::ResetTouchSelectionController() { textfield_->touch_selection_controller_.reset(); } void TextfieldTestApi::SetCursorViewRect(gfx::Rect bounds) { textfield_->cursor_view_->SetBoundsRect(bounds); } bool TextfieldTestApi::ShouldShowCursor() const { return textfield_->ShouldShowCursor(); } int TextfieldTestApi::GetDisplayOffsetX() const { return GetRenderText()->GetUpdatedDisplayOffset().x(); } void TextfieldTestApi::SetDisplayOffsetX(int x) const { return GetRenderText()->SetDisplayOffset(x); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_test_api.cc
C++
unknown
1,242
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_ #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_ #include "base/memory/raw_ptr.h" #include "ui/compositor/layer.h" #include "ui/views/controls/textfield/textfield.h" namespace views { // Helper class to access internal state of Textfield in tests. class TextfieldTestApi { public: explicit TextfieldTestApi(Textfield* textfield); TextfieldTestApi(const TextfieldTestApi&) = delete; TextfieldTestApi& operator=(const TextfieldTestApi&) = delete; ~TextfieldTestApi() = default; void UpdateContextMenu(); gfx::RenderText* GetRenderText() const; void CreateTouchSelectionControllerAndNotifyIt(); void ResetTouchSelectionController(); TextfieldModel* model() const { return textfield_->model_.get(); } void ExecuteTextEditCommand(ui::TextEditCommand command) { textfield_->ExecuteTextEditCommand(command); } ui::MenuModel* context_menu_contents() const { return textfield_->context_menu_contents_.get(); } ui::TouchEditingControllerDeprecated* touch_selection_controller() const { return textfield_->touch_selection_controller_.get(); } ui::TextEditCommand scheduled_text_edit_command() const { return textfield_->scheduled_text_edit_command_; } bool IsCursorBlinkTimerRunning() const { return textfield_->cursor_blink_timer_.IsRunning(); } gfx::Rect GetCursorViewRect() { return textfield_->cursor_view_->bounds(); } void SetCursorViewRect(gfx::Rect bounds); bool IsCursorVisible() const { return textfield_->cursor_view_->GetVisible(); } bool ShouldShowCursor() const; float CursorLayerOpacity() { return textfield_->cursor_view_->layer()->opacity(); } void SetCursorLayerOpacity(float opacity) { textfield_->cursor_view_->layer()->SetOpacity(opacity); } void UpdateCursorVisibility() { textfield_->UpdateCursorVisibility(); } void FlashCursor() { textfield_->OnCursorBlinkTimerFired(); } int GetDisplayOffsetX() const; void SetDisplayOffsetX(int x) const; private: raw_ptr<Textfield> textfield_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_test_api.h
C++
unknown
2,315
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/textfield/textfield_unittest.h" #include <stddef.h> #include <stdint.h> #include <set> #include <string> #include <vector> #include "base/command_line.h" #include "base/format_macros.h" #include "base/i18n/rtl.h" #include "base/memory/raw_ptr.h" #include "base/pickle.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/base/clipboard/test/test_clipboard.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h" #include "ui/base/emoji/emoji_panel_helper.h" #include "ui/base/ime/constants.h" #include "ui/base/ime/ime_key_event_dispatcher.h" #include "ui/base/ime/init/input_method_factory.h" #include "ui/base/ime/input_method_base.h" #include "ui/base/ime/text_edit_commands.h" #include "ui/base/ime/text_input_client.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" #include "ui/base/ui_base_switches_util.h" #include "ui/events/event.h" #include "ui/events/event_processor.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/test/event_generator.h" #include "ui/events/test/keyboard_layout.h" #include "ui/gfx/render_text.h" #include "ui/gfx/render_text_test_api.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/controls/textfield/textfield_model.h" #include "ui/views/controls/textfield/textfield_test_api.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/style/platform_style.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/test_views_delegate.h" #include "ui/views/test/widget_test.h" #include "ui/views/views_features.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_utils.h" #include "url/gurl.h" #if BUILDFLAG(IS_WIN) #include "base/win/windows_version.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/fake_linux_ui.h" #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/aura/window.h" #include "ui/wm/core/ime_util_chromeos.h" #endif #if BUILDFLAG(IS_MAC) #include "ui/base/cocoa/secure_password_input.h" #include "ui/base/cocoa/text_services_context_menu.h" #endif #if BUILDFLAG(IS_OZONE) #include "ui/events/ozone/layout/keyboard_layout_engine_test_utils.h" #endif namespace views::test { const char16_t kHebrewLetterSamekh = 0x05E1; // Convenience to make constructing a GestureEvent simpler. ui::GestureEvent CreateTestGestureEvent(int x, int y, const ui::GestureEventDetails& details) { return ui::GestureEvent(x, y, ui::EF_NONE, base::TimeTicks(), details); } // This controller will happily destroy the target field passed on // construction when a key event is triggered. class TextfieldDestroyerController : public TextfieldController { public: explicit TextfieldDestroyerController(Textfield* target) : target_(target) { target_->set_controller(this); } TextfieldDestroyerController(const TextfieldDestroyerController&) = delete; TextfieldDestroyerController& operator=(const TextfieldDestroyerController&) = delete; Textfield* target() { return target_.get(); } // TextfieldController: bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) override { if (target_) target_->OnBlur(); target_.reset(); return false; } private: std::unique_ptr<Textfield> target_; }; // Class that focuses a textfield when it sees a KeyDown event. class TextfieldFocuser : public View { public: explicit TextfieldFocuser(Textfield* textfield) : textfield_(textfield) { SetFocusBehavior(FocusBehavior::ALWAYS); } TextfieldFocuser(const TextfieldFocuser&) = delete; TextfieldFocuser& operator=(const TextfieldFocuser&) = delete; void set_consume(bool consume) { consume_ = consume; } // View: bool OnKeyPressed(const ui::KeyEvent& event) override { textfield_->RequestFocus(); return consume_; } private: bool consume_ = true; raw_ptr<Textfield> textfield_; }; class MockInputMethod : public ui::InputMethodBase { public: MockInputMethod(); MockInputMethod(const MockInputMethod&) = delete; MockInputMethod& operator=(const MockInputMethod&) = delete; ~MockInputMethod() override; // InputMethod: ui::EventDispatchDetails DispatchKeyEvent(ui::KeyEvent* key) override; void OnTextInputTypeChanged(ui::TextInputClient* client) override; void OnCaretBoundsChanged(const ui::TextInputClient* client) override {} void CancelComposition(const ui::TextInputClient* client) override; bool IsCandidatePopupOpen() const override; void SetVirtualKeyboardVisibilityIfEnabled(bool visibility) override { if (visibility) count_show_virtual_keyboard_++; } #if BUILDFLAG(IS_WIN) bool OnUntranslatedIMEMessage( const CHROME_MSG event, InputMethod::NativeEventResult* result) override { return false; } void OnInputLocaleChanged() override {} bool IsInputLocaleCJK() const override { return false; } #endif bool untranslated_ime_message_called() const { return untranslated_ime_message_called_; } bool text_input_type_changed() const { return text_input_type_changed_; } bool cancel_composition_called() const { return cancel_composition_called_; } int count_show_virtual_keyboard() const { return count_show_virtual_keyboard_; } // Clears all internal states and result. void Clear(); void SetCompositionTextForNextKey(const ui::CompositionText& composition); void SetResultTextForNextKey(const std::u16string& result); private: // Overridden from InputMethodBase. void OnWillChangeFocusedClient(ui::TextInputClient* focused_before, ui::TextInputClient* focused) override; // Clears boolean states defined below. void ClearStates(); // Whether a mock composition or result is scheduled for the next key event. bool HasComposition(); // Clears only composition information and result text. void ClearComposition(); // Composition information for the next key event. It'll be cleared // automatically after dispatching the next key event. ui::CompositionText composition_; // Result text for the next key event. It'll be cleared automatically after // dispatching the next key event. std::u16string result_text_; // Record call state of corresponding methods. They will be set to false // automatically before dispatching a key event. bool untranslated_ime_message_called_ = false; bool text_input_type_changed_ = false; bool cancel_composition_called_ = false; int count_show_virtual_keyboard_ = 0; }; MockInputMethod::MockInputMethod() : ui::InputMethodBase(nullptr) {} MockInputMethod::~MockInputMethod() = default; ui::EventDispatchDetails MockInputMethod::DispatchKeyEvent(ui::KeyEvent* key) { // On Mac, emulate InputMethodMac behavior for character events. Composition // still needs to be mocked, since it's not possible to generate test events // which trigger the appropriate NSResponder action messages for composition. #if BUILDFLAG(IS_MAC) if (key->is_char()) return DispatchKeyEventPostIME(key); #endif // Checks whether the key event is from EventGenerator on Windows which will // generate key event for WM_CHAR. // The MockInputMethod will insert char on WM_KEYDOWN so ignore WM_CHAR here. if (key->is_char() && key->HasNativeEvent()) { key->SetHandled(); return ui::EventDispatchDetails(); } ui::EventDispatchDetails dispatch_details; bool handled = !IsTextInputTypeNone() && HasComposition(); ClearStates(); if (handled) { DCHECK(!key->is_char()); ui::KeyEvent mock_key(ui::ET_KEY_PRESSED, ui::VKEY_PROCESSKEY, key->flags()); dispatch_details = DispatchKeyEventPostIME(&mock_key); } else { dispatch_details = DispatchKeyEventPostIME(key); } if (key->handled() || dispatch_details.dispatcher_destroyed) return dispatch_details; ui::TextInputClient* client = GetTextInputClient(); if (client) { if (handled) { if (result_text_.length()) client->InsertText(result_text_, ui::TextInputClient::InsertTextCursorBehavior:: kMoveCursorAfterText); if (composition_.text.length()) client->SetCompositionText(composition_); else client->ClearCompositionText(); } else if (key->type() == ui::ET_KEY_PRESSED) { char16_t ch = key->GetCharacter(); if (ch) client->InsertChar(*key); } } ClearComposition(); return dispatch_details; } void MockInputMethod::OnTextInputTypeChanged(ui::TextInputClient* client) { if (IsTextInputClientFocused(client)) text_input_type_changed_ = true; InputMethodBase::OnTextInputTypeChanged(client); } void MockInputMethod::CancelComposition(const ui::TextInputClient* client) { if (IsTextInputClientFocused(client)) { cancel_composition_called_ = true; ClearComposition(); } } bool MockInputMethod::IsCandidatePopupOpen() const { return false; } void MockInputMethod::OnWillChangeFocusedClient( ui::TextInputClient* focused_before, ui::TextInputClient* focused) { ui::TextInputClient* client = GetTextInputClient(); if (client && client->HasCompositionText()) client->ConfirmCompositionText(/* keep_selection */ false); ClearComposition(); } void MockInputMethod::Clear() { ClearStates(); ClearComposition(); } void MockInputMethod::SetCompositionTextForNextKey( const ui::CompositionText& composition) { composition_ = composition; } void MockInputMethod::SetResultTextForNextKey(const std::u16string& result) { result_text_ = result; } void MockInputMethod::ClearStates() { untranslated_ime_message_called_ = false; text_input_type_changed_ = false; cancel_composition_called_ = false; } bool MockInputMethod::HasComposition() { return composition_.text.length() || result_text_.length(); } void MockInputMethod::ClearComposition() { composition_ = ui::CompositionText(); result_text_.clear(); } // A Textfield wrapper to intercept OnKey[Pressed|Released]() results. class TestTextfield : public views::Textfield { public: TestTextfield() = default; TestTextfield(const TestTextfield&) = delete; TestTextfield& operator=(const TestTextfield&) = delete; ~TestTextfield() override = default; // ui::TextInputClient: void InsertChar(const ui::KeyEvent& e) override { views::Textfield::InsertChar(e); #if BUILDFLAG(IS_MAC) // On Mac, characters are inserted directly rather than attempting to get a // unicode character from the ui::KeyEvent (which isn't always possible). key_received_ = true; #endif } bool key_handled() const { return key_handled_; } bool key_received() const { return key_received_; } int event_flags() const { return event_flags_; } void clear() { key_received_ = key_handled_ = false; event_flags_ = 0; } void OnAccessibilityEvent(ax::mojom::Event event_type) override { if (event_type == ax::mojom::Event::kTextSelectionChanged) ++accessibility_selection_fired_count_; } int GetAccessibilitySelectionFiredCount() { return accessibility_selection_fired_count_; } private: // views::View: void OnKeyEvent(ui::KeyEvent* event) override { key_received_ = true; event_flags_ = event->flags(); // Since Textfield::OnKeyPressed() might destroy |this|, get a weak pointer // and verify it isn't null before writing the bool value to key_handled_. base::WeakPtr<TestTextfield> textfield(weak_ptr_factory_.GetWeakPtr()); views::View::OnKeyEvent(event); if (!textfield) return; key_handled_ = event->handled(); // Currently, Textfield::OnKeyReleased always returns false. if (event->type() == ui::ET_KEY_RELEASED) EXPECT_FALSE(key_handled_); } bool key_handled_ = false; bool key_received_ = false; int event_flags_ = 0; int accessibility_selection_fired_count_ = 0; base::WeakPtrFactory<TestTextfield> weak_ptr_factory_{this}; }; TextfieldTest::TextfieldTest() { input_method_ = new MockInputMethod(); ui::SetUpInputMethodForTesting(input_method_); } TextfieldTest::~TextfieldTest() = default; void TextfieldTest::SetUp() { // OS clipboard is a global resource, which causes flakiness when unit tests // run in parallel. So, use a per-instance test clipboard. ui::Clipboard::SetClipboardForCurrentThread( std::make_unique<ui::TestClipboard>()); ViewsTestBase::SetUp(); #if BUILDFLAG(IS_OZONE) // Setting up the keyboard layout engine depends on the implementation and may // be asynchronous. We ensure that it is ready to use so that tests could // handle key events properly. ui::WaitUntilLayoutEngineIsReadyForTest(); #endif } void TextfieldTest::TearDown() { if (widget_) widget_->Close(); // Clear kill buffer used for "Yank" text editing command so that no state // persists between tests. TextfieldModel::ClearKillBuffer(); ViewsTestBase::TearDown(); } ui::ClipboardBuffer TextfieldTest::GetAndResetCopiedToClipboard() { return std::exchange(copied_to_clipboard_, ui::ClipboardBuffer::kMaxValue); } std::u16string TextfieldTest::GetClipboardText( ui::ClipboardBuffer clipboard_buffer) { std::u16string text; ui::Clipboard::GetForCurrentThread()->ReadText( clipboard_buffer, /* data_dst = */ nullptr, &text); return text; } void TextfieldTest::SetClipboardText(ui::ClipboardBuffer clipboard_buffer, const std::u16string& text) { ui::ScopedClipboardWriter(clipboard_buffer).WriteText(text); } void TextfieldTest::ContentsChanged(Textfield* sender, const std::u16string& new_contents) { // Paste calls TextfieldController::ContentsChanged() explicitly even if the // paste action did not change the content. So |new_contents| may match // |last_contents_|. For more info, see http://crbug.com/79002 last_contents_ = new_contents; } void TextfieldTest::OnBeforeUserAction(Textfield* sender) { ++on_before_user_action_; } void TextfieldTest::OnAfterUserAction(Textfield* sender) { ++on_after_user_action_; } void TextfieldTest::OnAfterCutOrCopy(ui::ClipboardBuffer clipboard_type) { copied_to_clipboard_ = clipboard_type; } void TextfieldTest::InitTextfield(int count) { ASSERT_FALSE(textfield_); textfield_ = PrepareTextfields(count, std::make_unique<TestTextfield>(), gfx::Rect(100, 100, 200, 200)); } void TextfieldTest::PrepareTextfieldsInternal(int count, Textfield* textfield, View* container, gfx::Rect bounds) { input_method_->SetImeKeyEventDispatcher( test::WidgetTest::GetImeKeyEventDispatcherForWidget(widget_.get())); textfield->set_controller(this); textfield->SetBoundsRect(bounds); textfield->SetID(1); test_api_ = std::make_unique<TextfieldTestApi>(textfield); for (int i = 1; i < count; ++i) { Textfield* child = container->AddChildView(std::make_unique<Textfield>()); child->SetID(i + 1); } model_ = test_api_->model(); model_->ClearEditHistory(); // Since the window type is activatable, showing the widget will also // activate it. Calling Activate directly is insufficient, since that does // not also _focus_ an aura::Window (i.e. using the FocusClient). Both the // widget and the textfield must have focus to properly handle input. widget_->Show(); textfield->RequestFocus(); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_.get())); event_generator_->set_target(ui::test::EventGenerator::Target::WINDOW); event_target_ = textfield; } ui::MenuModel* TextfieldTest::GetContextMenuModel() { test_api_->UpdateContextMenu(); return test_api_->context_menu_contents(); } bool TextfieldTest::TestingNativeMac() const { #if BUILDFLAG(IS_MAC) return true; #else return false; #endif } bool TextfieldTest::TestingNativeCrOs() const { #if BUILDFLAG(IS_CHROMEOS_ASH) return true; #else return false; #endif // BUILDFLAG(IS_CHROMEOS_ASH) } void TextfieldTest::SendKeyPress(ui::KeyboardCode key_code, int flags) { event_generator_->PressKey(key_code, flags); } void TextfieldTest::SendKeyEvent(ui::KeyboardCode key_code, bool alt, bool shift, bool control_or_command, bool caps_lock) { bool control = control_or_command; bool command = false; // By default, swap control and command for native events on Mac. This // handles most cases. if (TestingNativeMac()) std::swap(control, command); int flags = (shift ? ui::EF_SHIFT_DOWN : 0) | (control ? ui::EF_CONTROL_DOWN : 0) | (alt ? ui::EF_ALT_DOWN : 0) | (command ? ui::EF_COMMAND_DOWN : 0) | (caps_lock ? ui::EF_CAPS_LOCK_ON : 0); SendKeyPress(key_code, flags); } void TextfieldTest::SendKeyEvent(ui::KeyboardCode key_code, bool shift, bool control_or_command) { SendKeyEvent(key_code, false, shift, control_or_command, false); } void TextfieldTest::SendKeyEvent(ui::KeyboardCode key_code) { SendKeyEvent(key_code, false, false); } void TextfieldTest::SendKeyEvent(char16_t ch) { SendKeyEvent(ch, ui::EF_NONE, false); } void TextfieldTest::SendKeyEvent(char16_t ch, int flags) { SendKeyEvent(ch, flags, false); } void TextfieldTest::SendKeyEvent(char16_t ch, int flags, bool from_vk) { if (ch < 0x80) { ui::KeyboardCode code = ch == ' ' ? ui::VKEY_SPACE : static_cast<ui::KeyboardCode>(ui::VKEY_A + ch - 'a'); SendKeyPress(code, flags); } else { // For unicode characters, assume they come from IME rather than the // keyboard. So they are dispatched directly to the input method. But on // Mac, key events don't pass through InputMethod. Hence they are // dispatched regularly. ui::KeyEvent event(ch, ui::VKEY_UNKNOWN, ui::DomCode::NONE, flags); if (from_vk) { ui::Event::Properties properties; properties[ui::kPropertyFromVK] = std::vector<uint8_t>(ui::kPropertyFromVKSize); event.SetProperties(properties); } #if BUILDFLAG(IS_MAC) event_generator_->Dispatch(&event); #else input_method_->DispatchKeyEvent(&event); #endif } } void TextfieldTest::DispatchMockInputMethodKeyEvent() { // Send a key to trigger MockInputMethod::DispatchKeyEvent(). Note the // specific VKEY isn't used (MockInputMethod will mock a ui::VKEY_PROCESSKEY // whenever it has a test composition). However, on Mac, it can't be a letter // (e.g. VKEY_A) since all native character events on Mac are unicode events // and don't have a meaningful ui::KeyEvent that would trigger // DispatchKeyEvent(). It also can't be VKEY_ENTER, since those key events may // need to be suppressed when interacting with real system IME. SendKeyEvent(ui::VKEY_INSERT); } // Sends a platform-specific move (and select) to the logical start of line. // Eg. this should move (and select) to the right end of line for RTL text. void TextfieldTest::SendHomeEvent(bool shift) { if (TestingNativeMac()) { // [NSResponder moveToBeginningOfLine:] is the correct way to do this on // Mac, but that doesn't have a default key binding. Since // views::Textfield doesn't currently support multiple lines, the same // effect can be achieved by Cmd+Up which maps to // [NSResponder moveToBeginningOfDocument:]. SendKeyEvent(ui::VKEY_UP, shift /* shift */, true /* command */); return; } SendKeyEvent(ui::VKEY_HOME, shift /* shift */, false /* control */); } // Sends a platform-specific move (and select) to the logical end of line. void TextfieldTest::SendEndEvent(bool shift) { if (TestingNativeMac()) { SendKeyEvent(ui::VKEY_DOWN, shift, true); // Cmd+Down. return; } SendKeyEvent(ui::VKEY_END, shift, false); } // Sends {delete, move, select} word {forward, backward}. void TextfieldTest::SendWordEvent(ui::KeyboardCode key, bool shift) { bool alt = false; bool control = true; bool caps = false; if (TestingNativeMac()) { // Use Alt+Left/Right/Backspace on native Mac. alt = true; control = false; } SendKeyEvent(key, alt, shift, control, caps); } // Sends Shift+Delete if supported, otherwise Cmd+X again. void TextfieldTest::SendAlternateCut() { if (TestingNativeMac()) SendKeyEvent(ui::VKEY_X, false, true); else SendKeyEvent(ui::VKEY_DELETE, true, false); } // Sends Ctrl+Insert if supported, otherwise Cmd+C again. void TextfieldTest::SendAlternateCopy() { if (TestingNativeMac()) SendKeyEvent(ui::VKEY_C, false, true); else SendKeyEvent(ui::VKEY_INSERT, false, true); } // Sends Shift+Insert if supported, otherwise Cmd+V again. void TextfieldTest::SendAlternatePaste() { if (TestingNativeMac()) SendKeyEvent(ui::VKEY_V, false, true); else SendKeyEvent(ui::VKEY_INSERT, true, false); } View* TextfieldTest::GetFocusedView() { return widget_->GetFocusManager()->GetFocusedView(); } int TextfieldTest::GetCursorPositionX(int cursor_pos) { return test_api_->GetRenderText() ->GetCursorBounds(gfx::SelectionModel(cursor_pos, gfx::CURSOR_FORWARD), false) .x(); } int TextfieldTest::GetCursorYForTesting() { return test_api_->GetRenderText()->GetLineOffset(0).y() + 1; } gfx::Rect TextfieldTest::GetCursorBounds() { return test_api_->GetRenderText()->GetUpdatedCursorBounds(); } // Gets the cursor bounds of |sel|. gfx::Rect TextfieldTest::GetCursorBounds(const gfx::SelectionModel& sel) { return test_api_->GetRenderText()->GetCursorBounds(sel, true); } gfx::Rect TextfieldTest::GetDisplayRect() { return test_api_->GetRenderText()->display_rect(); } gfx::Rect TextfieldTest::GetCursorViewRect() { return test_api_->GetCursorViewRect(); } // Performs a mouse click on the point whose x-axis is |bound|'s x plus // |x_offset| and y-axis is in the middle of |bound|'s vertical range. void TextfieldTest::MouseClick(const gfx::Rect bound, int x_offset) { gfx::Point point(bound.x() + x_offset, bound.y() + bound.height() / 2); ui::MouseEvent click(ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); event_target_->OnMousePressed(click); ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); event_target_->OnMouseReleased(release); } // This is to avoid double/triple click. void TextfieldTest::NonClientMouseClick() { ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), int{ui::EF_LEFT_MOUSE_BUTTON} | ui::EF_IS_NON_CLIENT, ui::EF_LEFT_MOUSE_BUTTON); event_target_->OnMousePressed(click); ui::MouseEvent release(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), int{ui::EF_LEFT_MOUSE_BUTTON} | ui::EF_IS_NON_CLIENT, ui::EF_LEFT_MOUSE_BUTTON); event_target_->OnMouseReleased(release); } void TextfieldTest::VerifyTextfieldContextMenuContents( bool textfield_has_selection, bool can_undo, ui::MenuModel* menu) { const auto& text = textfield_->GetText(); const bool is_all_selected = !text.empty() && textfield_->GetSelectedRange().length() == text.length(); int menu_index = 0; #if BUILDFLAG(IS_MAC) if (textfield_has_selection) { EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* Look Up "Selection" */)); EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* Separator */)); } #endif if (ui::IsEmojiPanelSupported()) { EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* EMOJI */)); EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* Separator */)); } EXPECT_EQ(can_undo, menu->IsEnabledAt(menu_index++ /* UNDO */)); EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* Separator */)); EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(menu_index++ /* CUT */)); EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(menu_index++ /* COPY */)); EXPECT_NE(GetClipboardText(ui::ClipboardBuffer::kCopyPaste).empty(), menu->IsEnabledAt(menu_index++ /* PASTE */)); EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(menu_index++ /* DELETE */)); EXPECT_TRUE(menu->IsEnabledAt(menu_index++ /* Separator */)); EXPECT_EQ(!is_all_selected, menu->IsEnabledAt(menu_index++ /* SELECT ALL */)); } void TextfieldTest::PressMouseButton(ui::EventFlags mouse_button_flags) { ui::MouseEvent press(ui::ET_MOUSE_PRESSED, mouse_position_, mouse_position_, ui::EventTimeForNow(), mouse_button_flags, mouse_button_flags); event_target_->OnMousePressed(press); } void TextfieldTest::ReleaseMouseButton(ui::EventFlags mouse_button_flags) { ui::MouseEvent release(ui::ET_MOUSE_RELEASED, mouse_position_, mouse_position_, ui::EventTimeForNow(), mouse_button_flags, mouse_button_flags); event_target_->OnMouseReleased(release); } void TextfieldTest::PressLeftMouseButton() { PressMouseButton(ui::EF_LEFT_MOUSE_BUTTON); } void TextfieldTest::ReleaseLeftMouseButton() { ReleaseMouseButton(ui::EF_LEFT_MOUSE_BUTTON); } void TextfieldTest::ClickLeftMouseButton() { PressLeftMouseButton(); ReleaseLeftMouseButton(); } void TextfieldTest::ClickRightMouseButton() { PressMouseButton(ui::EF_RIGHT_MOUSE_BUTTON); ReleaseMouseButton(ui::EF_RIGHT_MOUSE_BUTTON); } void TextfieldTest::DragMouseTo(const gfx::Point& where) { mouse_position_ = where; ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, where, where, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); event_target_->OnMouseDragged(drag); } void TextfieldTest::MoveMouseTo(const gfx::Point& where) { mouse_position_ = where; } // Taps on the textfield. void TextfieldTest::TapAtCursor(ui::EventPointerType pointer_type) { ui::GestureEventDetails tap_down_details(ui::ET_GESTURE_TAP_DOWN); tap_down_details.set_primary_pointer_type(pointer_type); ui::GestureEvent tap_down = CreateTestGestureEvent(GetCursorPositionX(0), 0, tap_down_details); textfield_->OnGestureEvent(&tap_down); ui::GestureEventDetails tap_up_details(ui::ET_GESTURE_TAP); tap_up_details.set_primary_pointer_type(pointer_type); ui::GestureEvent tap_up = CreateTestGestureEvent(GetCursorPositionX(0), 0, tap_up_details); textfield_->OnGestureEvent(&tap_up); } TEST_F(TextfieldTest, ModelChangesTest) { InitTextfield(); // TextfieldController::ContentsChanged() shouldn't be called when changing // text programmatically. last_contents_.clear(); textfield_->SetText(u"this is"); EXPECT_EQ(u"this is", model_->text()); EXPECT_EQ(u"this is", textfield_->GetText()); EXPECT_TRUE(last_contents_.empty()); textfield_->AppendText(u" a test"); EXPECT_EQ(u"this is a test", model_->text()); EXPECT_EQ(u"this is a test", textfield_->GetText()); EXPECT_TRUE(last_contents_.empty()); EXPECT_EQ(std::u16string(), textfield_->GetSelectedText()); textfield_->SelectAll(false); EXPECT_EQ(u"this is a test", textfield_->GetSelectedText()); EXPECT_TRUE(last_contents_.empty()); textfield_->SetTextWithoutCaretBoundsChangeNotification(u"another test", 3); EXPECT_EQ(u"another test", model_->text()); EXPECT_EQ(u"another test", textfield_->GetText()); EXPECT_EQ(textfield_->GetCursorPosition(), 3u); EXPECT_TRUE(last_contents_.empty()); } TEST_F(TextfieldTest, Scroll) { InitTextfield(); // Size the textfield wide enough to hold 10 characters. gfx::test::RenderTextTestApi render_text_test_api(test_api_->GetRenderText()); constexpr int kGlyphWidth = 10; render_text_test_api.SetGlyphWidth(kGlyphWidth); constexpr int kCursorWidth = 1; test_api_->GetRenderText()->SetDisplayRect( gfx::Rect(kGlyphWidth * 10 + kCursorWidth, 20)); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 0); test_api_->SetDisplayOffsetX(0); // Empty Scroll() call should have no effect. textfield_->Scroll({}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), 0); // Selected range should scroll cursor into view. textfield_->SetSelectedRange({0, 20}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -100); // Selected range should override new cursor position. test_api_->SetDisplayOffsetX(0); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 30); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -100); // Scroll positions should affect scroll. textfield_->SetSelectedRange(gfx::Range()); test_api_->SetDisplayOffsetX(0); textfield_->Scroll({30}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -200); // Should scroll right no more than necessary. test_api_->SetDisplayOffsetX(0); textfield_->Scroll({15}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -50); // Should scroll left no more than necessary. test_api_->SetDisplayOffsetX(-200); // Scroll all the way right. textfield_->Scroll({15}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -150); // Should not scroll if position is already in view. test_api_->SetDisplayOffsetX(-100); // Scroll the middle 10 chars into view. textfield_->Scroll({15}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -100); // With multiple scroll positions, the Last scroll position takes priority. test_api_->SetDisplayOffsetX(0); textfield_->Scroll({30, 0}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), 0); textfield_->Scroll({30, 0, 20}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -100); // With multiple scroll positions, the previous scroll positions should be // scrolled to anyways. test_api_->SetDisplayOffsetX(0); textfield_->Scroll({30, 20}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -200); // Only the selection end should affect scrolling. test_api_->SetDisplayOffsetX(0); textfield_->Scroll({20}); textfield_->SetSelectedRange({30, 20}); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -100); } TEST_F(TextfieldTest, SetTextWithoutCaretBoundsChangeNotification_ModelEditHistory) { InitTextfield(); // The cursor and selected range should reflect the selected range. textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 20); textfield_->SetSelectedRange({10, 15}); EXPECT_EQ(textfield_->GetCursorPosition(), 15u); EXPECT_EQ(textfield_->GetSelectedRange(), gfx::Range(10, 15)); // After undo, the cursor and selected range should reflect the state prior to // the edit. textfield_->InsertOrReplaceText(u"xyz"); // 2nd edit SendKeyEvent(ui::VKEY_Z, false, true); // Undo 2nd edit EXPECT_EQ(textfield_->GetCursorPosition(), 15u); EXPECT_EQ(textfield_->GetSelectedRange(), gfx::Range(10, 15)); // After redo, the cursor and selected range should reflect the // |cursor_position| parameter. SendKeyEvent(ui::VKEY_Z, false, true); // Undo 2nd edit SendKeyEvent(ui::VKEY_Z, false, true); // Undo 1st edit SendKeyEvent(ui::VKEY_Z, true, true); // Redo 1st edit EXPECT_EQ(textfield_->GetCursorPosition(), 20u); EXPECT_EQ(textfield_->GetSelectedRange(), gfx::Range(20, 20)); // After undo, the cursor and selected range should reflect the state prior to // the edit, even if that differs than the state after the current (1st) edit. textfield_->InsertOrReplaceText(u"xyz"); // (2')nd edit SendKeyEvent(ui::VKEY_Z, false, true); // Undo (2')nd edit EXPECT_EQ(textfield_->GetCursorPosition(), 20u); EXPECT_EQ(textfield_->GetSelectedRange(), gfx::Range(20, 20)); } TEST_F(TextfieldTest, KeyTest) { InitTextfield(); // Event flags: key, alt, shift, ctrl, caps-lock. SendKeyEvent(ui::VKEY_T, false, true, false, false); SendKeyEvent(ui::VKEY_E, false, false, false, false); SendKeyEvent(ui::VKEY_X, false, true, false, true); SendKeyEvent(ui::VKEY_T, false, false, false, true); SendKeyEvent(ui::VKEY_1, false, true, false, false); SendKeyEvent(ui::VKEY_1, false, false, false, false); SendKeyEvent(ui::VKEY_1, false, true, false, true); SendKeyEvent(ui::VKEY_1, false, false, false, true); // On Mac, Caps+Shift remains uppercase. if (TestingNativeMac()) EXPECT_EQ(u"TeXT!1!1", textfield_->GetText()); else EXPECT_EQ(u"TexT!1!1", textfield_->GetText()); } #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // Control key shouldn't generate a printable character on Linux. TEST_F(TextfieldTest, KeyTestControlModifier) { InitTextfield(); // 0x0448 is for 'CYRILLIC SMALL LETTER SHA'. SendKeyEvent(0x0448, 0); SendKeyEvent(0x0448, ui::EF_CONTROL_DOWN); // 0x044C is for 'CYRILLIC SMALL LETTER FRONT YER'. SendKeyEvent(0x044C, 0); SendKeyEvent(0x044C, ui::EF_CONTROL_DOWN); SendKeyEvent('i', 0); SendKeyEvent('i', ui::EF_CONTROL_DOWN); SendKeyEvent('m', 0); SendKeyEvent('m', ui::EF_CONTROL_DOWN); EXPECT_EQ( u"\x0448\x044C" u"im", textfield_->GetText()); } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) #define MAYBE_KeysWithModifiersTest KeysWithModifiersTest #else // TODO(crbug.com/645104): Implement keyboard layout changing for other // platforms. #define MAYBE_KeysWithModifiersTest DISABLED_KeysWithModifiersTest #endif TEST_F(TextfieldTest, MAYBE_KeysWithModifiersTest) { // Activate U.S. English keyboard layout. Modifier keys in other layouts may // change the text inserted into a texfield and cause this test to fail. ui::ScopedKeyboardLayout keyboard_layout(ui::KEYBOARD_LAYOUT_ENGLISH_US); InitTextfield(); const int ctrl = ui::EF_CONTROL_DOWN; const int alt = ui::EF_ALT_DOWN; const int command = ui::EF_COMMAND_DOWN; const int altgr = ui::EF_ALTGR_DOWN; const int shift = ui::EF_SHIFT_DOWN; SendKeyPress(ui::VKEY_T, shift | alt | altgr); SendKeyPress(ui::VKEY_H, alt); SendKeyPress(ui::VKEY_E, altgr); SendKeyPress(ui::VKEY_T, shift); SendKeyPress(ui::VKEY_E, shift | altgr); SendKeyPress(ui::VKEY_X, 0); SendKeyPress(ui::VKEY_T, ctrl); // This causes transpose on Mac. SendKeyPress(ui::VKEY_1, alt); SendKeyPress(ui::VKEY_2, command); SendKeyPress(ui::VKEY_3, 0); SendKeyPress(ui::VKEY_4, 0); SendKeyPress(ui::VKEY_OEM_PLUS, ctrl); SendKeyPress(ui::VKEY_OEM_PLUS, ctrl | shift); SendKeyPress(ui::VKEY_OEM_MINUS, ctrl); SendKeyPress(ui::VKEY_OEM_MINUS, ctrl | shift); if (TestingNativeCrOs()) EXPECT_EQ(u"TeTEx34", textfield_->GetText()); else if (TestingNativeMac()) EXPECT_EQ(u"TheTxE134", textfield_->GetText()); else EXPECT_EQ(u"TeTEx234", textfield_->GetText()); } TEST_F(TextfieldTest, ControlAndSelectTest) { // Insert a test string in a textfield. InitTextfield(); textfield_->SetText(u"one two three"); SendHomeEvent(false); SendKeyEvent(ui::VKEY_RIGHT, true, false); SendKeyEvent(ui::VKEY_RIGHT, true, false); SendKeyEvent(ui::VKEY_RIGHT, true, false); EXPECT_EQ(u"one", textfield_->GetSelectedText()); // Test word select. SendWordEvent(ui::VKEY_RIGHT, true); #if BUILDFLAG(IS_WIN) // Windows breaks on word starts and includes spaces. EXPECT_EQ(u"one ", textfield_->GetSelectedText()); SendWordEvent(ui::VKEY_RIGHT, true); EXPECT_EQ(u"one two ", textfield_->GetSelectedText()); #else // Non-Windows breaks on word ends and does NOT include spaces. EXPECT_EQ(u"one two", textfield_->GetSelectedText()); #endif SendWordEvent(ui::VKEY_RIGHT, true); EXPECT_EQ(u"one two three", textfield_->GetSelectedText()); SendWordEvent(ui::VKEY_LEFT, true); EXPECT_EQ(u"one two ", textfield_->GetSelectedText()); SendWordEvent(ui::VKEY_LEFT, true); EXPECT_EQ(u"one ", textfield_->GetSelectedText()); // Replace the selected text. SendKeyEvent(ui::VKEY_Z, true, false); SendKeyEvent(ui::VKEY_E, true, false); SendKeyEvent(ui::VKEY_R, true, false); SendKeyEvent(ui::VKEY_O, true, false); SendKeyEvent(ui::VKEY_SPACE, false, false); EXPECT_EQ(u"ZERO two three", textfield_->GetText()); SendEndEvent(true); EXPECT_EQ(u"two three", textfield_->GetSelectedText()); SendHomeEvent(true); // On Mac, the existing selection should be extended. #if BUILDFLAG(IS_MAC) EXPECT_EQ(u"ZERO two three", textfield_->GetSelectedText()); #else EXPECT_EQ(u"ZERO ", textfield_->GetSelectedText()); #endif } TEST_F(TextfieldTest, WordSelection) { InitTextfield(); textfield_->SetText(u"12 34567 89"); // Place the cursor after "5". textfield_->SetEditableSelectionRange(gfx::Range(6)); // Select word towards right. SendWordEvent(ui::VKEY_RIGHT, true); #if BUILDFLAG(IS_WIN) // Select word right includes space/punctuation. EXPECT_EQ(u"67 ", textfield_->GetSelectedText()); #else // Non-Win: select word right does NOT include space/punctuation. EXPECT_EQ(u"67", textfield_->GetSelectedText()); #endif SendWordEvent(ui::VKEY_RIGHT, true); EXPECT_EQ(u"67 89", textfield_->GetSelectedText()); // Select word towards left. SendWordEvent(ui::VKEY_LEFT, true); EXPECT_EQ(u"67 ", textfield_->GetSelectedText()); SendWordEvent(ui::VKEY_LEFT, true); // On Mac, the selection should reduce to a caret when the selection direction // changes for a word selection. #if BUILDFLAG(IS_MAC) EXPECT_EQ(gfx::Range(6), textfield_->GetSelectedRange()); #else EXPECT_EQ(u"345", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(6, 3), textfield_->GetSelectedRange()); #endif SendWordEvent(ui::VKEY_LEFT, true); #if BUILDFLAG(IS_MAC) EXPECT_EQ(u"345", textfield_->GetSelectedText()); #else EXPECT_EQ(u"12 345", textfield_->GetSelectedText()); #endif EXPECT_TRUE(textfield_->GetSelectedRange().is_reversed()); SendWordEvent(ui::VKEY_LEFT, true); EXPECT_EQ(u"12 345", textfield_->GetSelectedText()); } TEST_F(TextfieldTest, LineSelection) { InitTextfield(); textfield_->SetText(u"12 34567 89"); // Place the cursor after "5". textfield_->SetEditableSelectionRange(gfx::Range(6)); // Select line towards right. SendEndEvent(true); EXPECT_EQ(u"67 89", textfield_->GetSelectedText()); // Select line towards left. On Mac, the existing selection should be extended // to cover the whole line. SendHomeEvent(true); #if BUILDFLAG(IS_MAC) EXPECT_EQ(textfield_->GetText(), textfield_->GetSelectedText()); #else EXPECT_EQ(u"12 345", textfield_->GetSelectedText()); #endif EXPECT_TRUE(textfield_->GetSelectedRange().is_reversed()); // Select line towards right. SendEndEvent(true); #if BUILDFLAG(IS_MAC) EXPECT_EQ(textfield_->GetText(), textfield_->GetSelectedText()); #else EXPECT_EQ(u"67 89", textfield_->GetSelectedText()); #endif EXPECT_FALSE(textfield_->GetSelectedRange().is_reversed()); } TEST_F(TextfieldTest, MoveUpDownAndModifySelection) { InitTextfield(); textfield_->SetText(u"12 34567 89"); textfield_->SetEditableSelectionRange(gfx::Range(6)); // Up/Down keys won't be handled except on Mac where they map to move // commands. SendKeyEvent(ui::VKEY_UP); EXPECT_TRUE(textfield_->key_received()); #if BUILDFLAG(IS_MAC) EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(gfx::Range(0), textfield_->GetSelectedRange()); #else EXPECT_FALSE(textfield_->key_handled()); #endif textfield_->clear(); SendKeyEvent(ui::VKEY_DOWN); EXPECT_TRUE(textfield_->key_received()); #if BUILDFLAG(IS_MAC) EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(gfx::Range(11), textfield_->GetSelectedRange()); #else EXPECT_FALSE(textfield_->key_handled()); #endif textfield_->clear(); textfield_->SetEditableSelectionRange(gfx::Range(6)); // Shift+[Up/Down] should select the text to the beginning and end of the // line, respectively. SendKeyEvent(ui::VKEY_UP, true /* shift */, false /* command */); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(gfx::Range(6, 0), textfield_->GetSelectedRange()); textfield_->clear(); SendKeyEvent(ui::VKEY_DOWN, true /* shift */, false /* command */); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(gfx::Range(6, 11), textfield_->GetSelectedRange()); textfield_->clear(); } TEST_F(TextfieldTest, MovePageUpDownAndModifySelection) { InitTextfield(); // MOVE_PAGE_[UP/DOWN] and the associated selection commands should only be // enabled on Mac. #if BUILDFLAG(IS_MAC) textfield_->SetText(u"12 34567 89"); textfield_->SetEditableSelectionRange(gfx::Range(6)); EXPECT_TRUE( textfield_->IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_PAGE_UP)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_DOWN)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION)); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_PAGE_UP); EXPECT_EQ(gfx::Range(0), textfield_->GetSelectedRange()); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_PAGE_DOWN); EXPECT_EQ(gfx::Range(11), textfield_->GetSelectedRange()); textfield_->SetEditableSelectionRange(gfx::Range(6)); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(6, 0), textfield_->GetSelectedRange()); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(6, 11), textfield_->GetSelectedRange()); #else EXPECT_FALSE( textfield_->IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_PAGE_UP)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_DOWN)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_UP_AND_MODIFY_SELECTION)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::MOVE_PAGE_DOWN_AND_MODIFY_SELECTION)); #endif } TEST_F(TextfieldTest, MoveParagraphForwardBackwardAndModifySelection) { InitTextfield(); textfield_->SetText(u"12 34567 89"); textfield_->SetEditableSelectionRange(gfx::Range(6)); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(6, 11), textfield_->GetSelectedRange()); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION); // On Mac, the selection should reduce to a caret when the selection direction // is reversed for MOVE_PARAGRAPH_[FORWARD/BACKWARD]_AND_MODIFY_SELECTION. #if BUILDFLAG(IS_MAC) EXPECT_EQ(gfx::Range(6), textfield_->GetSelectedRange()); #else EXPECT_EQ(gfx::Range(6, 0), textfield_->GetSelectedRange()); #endif test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PARAGRAPH_BACKWARD_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(6, 0), textfield_->GetSelectedRange()); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_PARAGRAPH_FORWARD_AND_MODIFY_SELECTION); #if BUILDFLAG(IS_MAC) EXPECT_EQ(gfx::Range(6), textfield_->GetSelectedRange()); #else EXPECT_EQ(gfx::Range(6, 11), textfield_->GetSelectedRange()); #endif } TEST_F(TextfieldTest, ModifySelectionWithMultipleSelections) { InitTextfield(); textfield_->SetText(u"0123456 89"); textfield_->SetSelectedRange(gfx::Range(3, 5)); textfield_->AddSecondarySelectedRange(gfx::Range(8, 9)); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::MOVE_RIGHT_AND_MODIFY_SELECTION); EXPECT_EQ(gfx::Range(3, 6), textfield_->GetSelectedRange()); EXPECT_EQ(6U, textfield_->GetCursorPosition()); EXPECT_EQ(0U, textfield_->GetSelectionModel().secondary_selections().size()); } TEST_F(TextfieldTest, InsertionDeletionTest) { // Insert a test string in a textfield. InitTextfield(); for (size_t i = 0; i < 10; ++i) SendKeyEvent(static_cast<ui::KeyboardCode>(ui::VKEY_A + i)); EXPECT_EQ(u"abcdefghij", textfield_->GetText()); // Test the delete and backspace keys. textfield_->SetSelectedRange(gfx::Range(5)); for (size_t i = 0; i < 3; ++i) SendKeyEvent(ui::VKEY_BACK); EXPECT_EQ(u"abfghij", textfield_->GetText()); for (size_t i = 0; i < 3; ++i) SendKeyEvent(ui::VKEY_DELETE); EXPECT_EQ(u"abij", textfield_->GetText()); // Select all and replace with "k". textfield_->SelectAll(false); SendKeyEvent(ui::VKEY_K); EXPECT_EQ(u"k", textfield_->GetText()); // Delete the previous word from cursor. bool shift = false; textfield_->SetText(u"one two three four"); SendEndEvent(shift); SendWordEvent(ui::VKEY_BACK, shift); EXPECT_EQ(u"one two three ", textfield_->GetText()); // Delete to a line break on Linux and ChromeOS, to a word break on Windows // and Mac. SendWordEvent(ui::VKEY_LEFT, shift); shift = true; SendWordEvent(ui::VKEY_BACK, shift); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) EXPECT_EQ(u"three ", textfield_->GetText()); #else EXPECT_EQ(u"one three ", textfield_->GetText()); #endif // Delete the next word from cursor. textfield_->SetText(u"one two three four"); shift = false; SendHomeEvent(shift); SendWordEvent(ui::VKEY_DELETE, shift); #if BUILDFLAG(IS_WIN) // Delete word incldes space/punctuation. EXPECT_EQ(u"two three four", textfield_->GetText()); #else // Non-Windows: delete word does NOT include space/punctuation. EXPECT_EQ(u" two three four", textfield_->GetText()); #endif // Delete to a line break on Linux and ChromeOS, to a word break on Windows // and Mac. SendWordEvent(ui::VKEY_RIGHT, shift); shift = true; SendWordEvent(ui::VKEY_DELETE, shift); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) EXPECT_EQ(u" two", textfield_->GetText()); #elif BUILDFLAG(IS_WIN) EXPECT_EQ(u"two four", textfield_->GetText()); #else EXPECT_EQ(u" two four", textfield_->GetText()); #endif } // Test that deletion operations behave correctly with an active selection. TEST_F(TextfieldTest, DeletionWithSelection) { struct { ui::KeyboardCode key; bool shift; } cases[] = { {ui::VKEY_BACK, false}, {ui::VKEY_BACK, true}, {ui::VKEY_DELETE, false}, {ui::VKEY_DELETE, true}, }; InitTextfield(); // [Ctrl] ([Alt] on Mac) + [Delete]/[Backspace] should delete the active // selection, regardless of [Shift]. for (size_t i = 0; i < std::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i)); textfield_->SetText(u"one two three"); textfield_->SetSelectedRange(gfx::Range(2, 6)); // Make selection as - on|e tw|o three. SendWordEvent(cases[i].key, cases[i].shift); // Verify state is on|o three. EXPECT_EQ(u"ono three", textfield_->GetText()); EXPECT_EQ(gfx::Range(2), textfield_->GetSelectedRange()); } } // Test that deletion operations behave correctly with multiple selections. TEST_F(TextfieldTest, DeletionWithMultipleSelections) { struct { ui::KeyboardCode key; bool shift; } cases[] = { {ui::VKEY_BACK, false}, {ui::VKEY_BACK, true}, {ui::VKEY_DELETE, false}, {ui::VKEY_DELETE, true}, }; InitTextfield(); // [Ctrl] ([Alt] on Mac) + [Delete]/[Backspace] should delete the active // selection, regardless of [Shift]. for (size_t i = 0; i < std::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i)); textfield_->SetText(u"one two three"); // Select: o[ne] [two] th[re]e textfield_->SetSelectedRange(gfx::Range(4, 7)); textfield_->AddSecondarySelectedRange(gfx::Range(10, 12)); textfield_->AddSecondarySelectedRange(gfx::Range(1, 3)); SendWordEvent(cases[i].key, cases[i].shift); EXPECT_EQ(u"o the", textfield_->GetText()); EXPECT_EQ(gfx::Range(2), textfield_->GetSelectedRange()); EXPECT_EQ(0U, textfield_->GetSelectionModel().secondary_selections().size()); } } // Test deletions not covered by other tests with key events. TEST_F(TextfieldTest, DeletionWithEditCommands) { struct { ui::TextEditCommand command; const char16_t* expected; } cases[] = { {ui::TextEditCommand::DELETE_TO_BEGINNING_OF_LINE, u"two three"}, {ui::TextEditCommand::DELETE_TO_BEGINNING_OF_PARAGRAPH, u"two three"}, {ui::TextEditCommand::DELETE_TO_END_OF_LINE, u"one "}, {ui::TextEditCommand::DELETE_TO_END_OF_PARAGRAPH, u"one "}, }; InitTextfield(); for (size_t i = 0; i < std::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i)); textfield_->SetText(u"one two three"); textfield_->SetSelectedRange(gfx::Range(4)); test_api_->ExecuteTextEditCommand(cases[i].command); EXPECT_EQ(cases[i].expected, textfield_->GetText()); } } TEST_F(TextfieldTest, PasswordTest) { InitTextfield(); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); EXPECT_TRUE(textfield_->GetEnabled()); EXPECT_TRUE(textfield_->IsFocusable()); last_contents_.clear(); textfield_->SetText(u"password"); // Ensure GetText() and the callback returns the actual text instead of "*". EXPECT_EQ(u"password", textfield_->GetText()); EXPECT_TRUE(last_contents_.empty()); model_->SelectAll(false); SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"foo"); // Cut and copy should be disabled. EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kCut)); textfield_->ExecuteCommand(Textfield::kCut, 0); SendKeyEvent(ui::VKEY_X, false, true); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kCopy)); textfield_->ExecuteCommand(Textfield::kCopy, 0); SendKeyEvent(ui::VKEY_C, false, true); SendAlternateCopy(); EXPECT_EQ(u"foo", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"password", textfield_->GetText()); // [Shift]+[Delete] should just delete without copying text to the clipboard. textfield_->SelectAll(false); SendKeyEvent(ui::VKEY_DELETE, true, false); // Paste should work normally. EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kPaste)); textfield_->ExecuteCommand(Textfield::kPaste, 0); SendKeyEvent(ui::VKEY_V, false, true); SendAlternatePaste(); EXPECT_EQ(u"foo", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"foofoofoo", textfield_->GetText()); } TEST_F(TextfieldTest, PasswordSelectWordTest) { InitTextfield(); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); textfield_->SetText(u"password word test"); // Select word command should be disabled. textfield_->SetEditableSelectionRange(gfx::Range(2)); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); textfield_->ExecuteCommand(Textfield::kPaste, 0); EXPECT_EQ(u"", textfield_->GetSelectedText()); // Select word should select whole text instead of the nearest word. textfield_->SelectWord(); EXPECT_EQ(u"password word test", textfield_->GetSelectedText()); } // Check that text insertion works appropriately for password and read-only // textfields. TEST_F(TextfieldTest, TextInputType_InsertionTest) { InitTextfield(); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); SendKeyEvent(ui::VKEY_A); EXPECT_FALSE(textfield_->GetPasswordCharRevealIndex().has_value()); SendKeyEvent(kHebrewLetterSamekh, ui::EF_NONE, true /* from_vk */); #if !BUILDFLAG(IS_MAC) // Don't verifies the password character reveal on MacOS, because on MacOS, // the text insertion is not done through TextInputClient::InsertChar(). EXPECT_EQ(1u, textfield_->GetPasswordCharRevealIndex()); #endif SendKeyEvent(ui::VKEY_B); EXPECT_FALSE(textfield_->GetPasswordCharRevealIndex().has_value()); EXPECT_EQ( u"a\x05E1" u"b", textfield_->GetText()); textfield_->SetReadOnly(true); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, textfield_->GetTextInputType()); SendKeyEvent(ui::VKEY_C); // No text should be inserted for read only textfields. EXPECT_EQ( u"a\x05E1" u"b", textfield_->GetText()); } TEST_F(TextfieldTest, ShouldDoLearning) { InitTextfield(); // Defaults to false. EXPECT_EQ(false, textfield_->ShouldDoLearning()); // The value can be set. textfield_->SetShouldDoLearning(true); EXPECT_EQ(true, textfield_->ShouldDoLearning()); } TEST_F(TextfieldTest, TextInputType) { InitTextfield(); // Defaults to TEXT EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, textfield_->GetTextInputType()); // And can be set. textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_URL); EXPECT_EQ(ui::TEXT_INPUT_TYPE_URL, textfield_->GetTextInputType()); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); // Readonly textfields have type NONE textfield_->SetReadOnly(true); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, textfield_->GetTextInputType()); textfield_->SetReadOnly(false); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); // As do disabled textfields textfield_->SetEnabled(false); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, textfield_->GetTextInputType()); textfield_->SetEnabled(true); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); } TEST_F(TextfieldTest, OnKeyPress) { InitTextfield(); // Character keys are handled by the input method. SendKeyEvent(ui::VKEY_A); EXPECT_TRUE(textfield_->key_received()); EXPECT_FALSE(textfield_->key_handled()); textfield_->clear(); // Arrow keys and home/end are handled by the textfield. SendKeyEvent(ui::VKEY_LEFT); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); textfield_->clear(); SendKeyEvent(ui::VKEY_RIGHT); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); textfield_->clear(); const bool shift = false; SendHomeEvent(shift); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); textfield_->clear(); SendEndEvent(shift); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); textfield_->clear(); // F20 key won't be handled. SendKeyEvent(ui::VKEY_F20); EXPECT_TRUE(textfield_->key_received()); EXPECT_FALSE(textfield_->key_handled()); textfield_->clear(); } // Tests that default key bindings are handled even with a delegate installed. TEST_F(TextfieldTest, OnKeyPressBinding) { InitTextfield(); #if BUILDFLAG(IS_LINUX) // Install a TextEditKeyBindingsDelegateAuraLinux that does nothing. class TestDelegate : public ui::FakeLinuxUi { public: TestDelegate() = default; TestDelegate(const TestDelegate&) = delete; TestDelegate& operator=(const TestDelegate&) = delete; ~TestDelegate() override = default; bool GetTextEditCommandsForEvent( const ui::Event& event, std::vector<ui::TextEditCommandAuraLinux>* commands) override { return false; } }; auto test_delegate = std::make_unique<TestDelegate>(); auto* old_linux_ui = ui::LinuxUi::SetInstance(test_delegate.get()); #endif SendKeyEvent(ui::VKEY_A, false, false); EXPECT_EQ(u"a", textfield_->GetText()); textfield_->clear(); // Undo/Redo command keys are handled by the textfield. SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); EXPECT_TRUE(textfield_->GetText().empty()); textfield_->clear(); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(u"a", textfield_->GetText()); textfield_->clear(); #if BUILDFLAG(IS_LINUX) ui::LinuxUi::SetInstance(old_linux_ui); #endif } TEST_F(TextfieldTest, CursorMovement) { InitTextfield(); // Test with trailing whitespace. textfield_->SetText(u"one two hre "); // Send the cursor at the end. SendKeyEvent(ui::VKEY_END); // Ctrl+Left should move the cursor just before the last word. const bool shift = false; SendWordEvent(ui::VKEY_LEFT, shift); SendKeyEvent(ui::VKEY_T); EXPECT_EQ(u"one two thre ", textfield_->GetText()); EXPECT_EQ(u"one two thre ", last_contents_); #if BUILDFLAG(IS_WIN) // Move right by word includes space/punctuation. // Ctrl+Right should move the cursor to the end of the last word. SendWordEvent(ui::VKEY_RIGHT, shift); SendKeyEvent(ui::VKEY_E); EXPECT_EQ(u"one two thre e", textfield_->GetText()); EXPECT_EQ(u"one two thre e", last_contents_); // Ctrl+Right again should not move the cursor, because // it is aleady at the end. SendWordEvent(ui::VKEY_RIGHT, shift); SendKeyEvent(ui::VKEY_BACK); EXPECT_EQ(u"one two thre ", textfield_->GetText()); EXPECT_EQ(u"one two thre ", last_contents_); #else // Non-Windows: move right by word does NOT include space/punctuation. // Ctrl+Right should move the cursor to the end of the last word. SendWordEvent(ui::VKEY_RIGHT, shift); SendKeyEvent(ui::VKEY_E); EXPECT_EQ(u"one two three ", textfield_->GetText()); EXPECT_EQ(u"one two three ", last_contents_); // Ctrl+Right again should move the cursor to the end. SendWordEvent(ui::VKEY_RIGHT, shift); SendKeyEvent(ui::VKEY_BACK); EXPECT_EQ(u"one two three", textfield_->GetText()); EXPECT_EQ(u"one two three", last_contents_); #endif // Test with leading whitespace. textfield_->SetText(u" ne two"); // Send the cursor at the beginning. SendHomeEvent(shift); // Ctrl+Right, then Ctrl+Left should move the cursor to the beginning of the // first word. SendWordEvent(ui::VKEY_RIGHT, shift); #if BUILDFLAG(IS_WIN) // Windows breaks on word start, move further to pass // "ne". SendWordEvent(ui::VKEY_RIGHT, shift); #endif SendWordEvent(ui::VKEY_LEFT, shift); SendKeyEvent(ui::VKEY_O); EXPECT_EQ(u" one two", textfield_->GetText()); EXPECT_EQ(u" one two", last_contents_); // Ctrl+Left to move the cursor to the beginning of the first word. SendWordEvent(ui::VKEY_LEFT, shift); // Ctrl+Left again should move the cursor back to the very beginning. SendWordEvent(ui::VKEY_LEFT, shift); SendKeyEvent(ui::VKEY_DELETE); EXPECT_EQ(u"one two", textfield_->GetText()); EXPECT_EQ(u"one two", last_contents_); } TEST_F(TextfieldTest, CursorMovementWithMultipleSelections) { InitTextfield(); textfield_->SetText(u"012 456 890 234 678"); // [p] [s] textfield_->SetSelectedRange({4, 7}); textfield_->AddSecondarySelectedRange({12, 15}); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_LEFT); EXPECT_EQ(gfx::Range(4, 4), textfield_->GetSelectedRange()); EXPECT_EQ(0U, textfield_->GetSelectionModel().secondary_selections().size()); textfield_->SetSelectedRange({4, 7}); textfield_->AddSecondarySelectedRange({12, 15}); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::MOVE_RIGHT); EXPECT_EQ(gfx::Range(7, 7), textfield_->GetSelectedRange()); EXPECT_EQ(0U, textfield_->GetSelectionModel().secondary_selections().size()); } TEST_F(TextfieldTest, ShouldShowCursor) { InitTextfield(); textfield_->SetText(u"word1 word2"); // should show cursor when there's no primary selection textfield_->SetSelectedRange({4, 4}); EXPECT_TRUE(test_api_->ShouldShowCursor()); textfield_->AddSecondarySelectedRange({1, 3}); EXPECT_TRUE(test_api_->ShouldShowCursor()); // should not show cursor when there's a primary selection textfield_->SetSelectedRange({4, 7}); EXPECT_FALSE(test_api_->ShouldShowCursor()); textfield_->AddSecondarySelectedRange({1, 3}); EXPECT_FALSE(test_api_->ShouldShowCursor()); } #if BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, MacCursorAlphaTest) { InitTextfield(); const int cursor_y = GetCursorYForTesting(); MoveMouseTo(gfx::Point(GetCursorPositionX(0), cursor_y)); ClickRightMouseButton(); EXPECT_TRUE(textfield_->HasFocus()); const float kOpaque = 1.0; EXPECT_FLOAT_EQ(kOpaque, test_api_->CursorLayerOpacity()); test_api_->FlashCursor(); const float kAlmostTransparent = 1.0 / 255.0; EXPECT_FLOAT_EQ(kAlmostTransparent, test_api_->CursorLayerOpacity()); test_api_->FlashCursor(); EXPECT_FLOAT_EQ(kOpaque, test_api_->CursorLayerOpacity()); const float kTransparent = 0.0; test_api_->SetCursorLayerOpacity(kTransparent); ASSERT_FLOAT_EQ(kTransparent, test_api_->CursorLayerOpacity()); test_api_->UpdateCursorVisibility(); EXPECT_FLOAT_EQ(kOpaque, test_api_->CursorLayerOpacity()); } #endif TEST_F(TextfieldTest, FocusTraversalTest) { InitTextfield(3); textfield_->RequestFocus(); EXPECT_EQ(1, GetFocusedView()->GetID()); widget_->GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(2, GetFocusedView()->GetID()); widget_->GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(3, GetFocusedView()->GetID()); // Cycle back to the first textfield. widget_->GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(1, GetFocusedView()->GetID()); widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(3, GetFocusedView()->GetID()); widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(2, GetFocusedView()->GetID()); widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(1, GetFocusedView()->GetID()); // Cycle back to the last textfield. widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(3, GetFocusedView()->GetID()); // Request focus should still work. textfield_->RequestFocus(); EXPECT_EQ(1, GetFocusedView()->GetID()); // Test if clicking on textfield view sets the focus. widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(3, GetFocusedView()->GetID()); MoveMouseTo(gfx::Point(0, GetCursorYForTesting())); ClickLeftMouseButton(); EXPECT_EQ(1, GetFocusedView()->GetID()); // Tab/Shift+Tab should also cycle focus, not insert a tab character. SendKeyEvent(ui::VKEY_TAB, false, false); EXPECT_EQ(2, GetFocusedView()->GetID()); SendKeyEvent(ui::VKEY_TAB, false, false); EXPECT_EQ(3, GetFocusedView()->GetID()); // Cycle back to the first textfield. SendKeyEvent(ui::VKEY_TAB, false, false); EXPECT_EQ(1, GetFocusedView()->GetID()); SendKeyEvent(ui::VKEY_TAB, true, false); EXPECT_EQ(3, GetFocusedView()->GetID()); SendKeyEvent(ui::VKEY_TAB, true, false); EXPECT_EQ(2, GetFocusedView()->GetID()); SendKeyEvent(ui::VKEY_TAB, true, false); EXPECT_EQ(1, GetFocusedView()->GetID()); // Cycle back to the last textfield. SendKeyEvent(ui::VKEY_TAB, true, false); EXPECT_EQ(3, GetFocusedView()->GetID()); } TEST_F(TextfieldTest, ContextMenuDisplayTest) { InitTextfield(); EXPECT_TRUE(textfield_->context_menu_controller()); textfield_->SetText(u"hello world"); ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); textfield_->ClearEditHistory(); EXPECT_TRUE(GetContextMenuModel()); VerifyTextfieldContextMenuContents(false, false, GetContextMenuModel()); textfield_->SelectAll(false); VerifyTextfieldContextMenuContents(true, false, GetContextMenuModel()); SendKeyEvent(ui::VKEY_T); VerifyTextfieldContextMenuContents(false, true, GetContextMenuModel()); textfield_->SelectAll(false); VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); // Exercise the "paste enabled?" check in the verifier. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); } TEST_F(TextfieldTest, DoubleAndTripleClickTest) { InitTextfield(); textfield_->SetText(u"hello world"); // Test for double click. MoveMouseTo(gfx::Point(0, GetCursorYForTesting())); ClickLeftMouseButton(); EXPECT_TRUE(textfield_->GetSelectedText().empty()); ClickLeftMouseButton(); EXPECT_EQ(u"hello", textfield_->GetSelectedText()); // Test for triple click. ClickLeftMouseButton(); EXPECT_EQ(u"hello world", textfield_->GetSelectedText()); // Another click should reset back to double click. ClickLeftMouseButton(); EXPECT_EQ(u"hello", textfield_->GetSelectedText()); } // Tests text selection behavior on a right click. TEST_F(TextfieldTest, SelectionOnRightClick) { InitTextfield(); textfield_->SetText(u"hello world"); // Verify right clicking within the selection does not alter the selection. textfield_->SetSelectedRange(gfx::Range(1, 5)); EXPECT_EQ(u"ello", textfield_->GetSelectedText()); const int cursor_y = GetCursorYForTesting(); MoveMouseTo(gfx::Point(GetCursorPositionX(3), cursor_y)); ClickRightMouseButton(); EXPECT_EQ(u"ello", textfield_->GetSelectedText()); // Verify right clicking outside the selection, selects the word under the // cursor on platforms where this is expected. MoveMouseTo(gfx::Point(GetCursorPositionX(8), cursor_y)); const char16_t* expected_right_click_word = PlatformStyle::kSelectWordOnRightClick ? u"world" : u"ello"; ClickRightMouseButton(); EXPECT_EQ(expected_right_click_word, textfield_->GetSelectedText()); // Verify right clicking inside an unfocused textfield selects all the text on // platforms where this is expected. Else the older selection is retained. widget_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(textfield_->HasFocus()); MoveMouseTo(gfx::Point(GetCursorPositionX(0), cursor_y)); ClickRightMouseButton(); EXPECT_TRUE(textfield_->HasFocus()); const char16_t* expected_right_click_unfocused = PlatformStyle::kSelectAllOnRightClickWhenUnfocused ? u"hello world" : expected_right_click_word; EXPECT_EQ(expected_right_click_unfocused, textfield_->GetSelectedText()); } TEST_F(TextfieldTest, DragToSelect) { InitTextfield(); textfield_->SetText(u"hello world"); const int kStart = GetCursorPositionX(5); const int kEnd = 500; const int cursor_y = GetCursorYForTesting(); gfx::Point start_point(kStart, cursor_y); gfx::Point end_point(kEnd, cursor_y); MoveMouseTo(start_point); PressLeftMouseButton(); EXPECT_TRUE(textfield_->GetSelectedText().empty()); // Check that dragging left selects the beginning of the string. DragMouseTo(gfx::Point(0, cursor_y)); std::u16string text_left = textfield_->GetSelectedText(); EXPECT_EQ(u"hello", text_left); // Check that dragging right selects the rest of the string. DragMouseTo(end_point); std::u16string text_right = textfield_->GetSelectedText(); EXPECT_EQ(u" world", text_right); // Check that releasing in the same location does not alter the selection. ReleaseLeftMouseButton(); EXPECT_EQ(text_right, textfield_->GetSelectedText()); // Check that dragging from beyond the text length works too. MoveMouseTo(end_point); PressLeftMouseButton(); DragMouseTo(gfx::Point(0, cursor_y)); ReleaseLeftMouseButton(); EXPECT_EQ(textfield_->GetText(), textfield_->GetSelectedText()); } // Ensures dragging above or below the textfield extends a selection to either // end, depending on the relative x offsets of the text and mouse cursors. TEST_F(TextfieldTest, DragUpOrDownSelectsToEnd) { InitTextfield(); textfield_->SetText(u"hello world"); const std::u16string expected_left = gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? u"hello" : u"lo"; const std::u16string expected_right = gfx::RenderText::kDragToEndIfOutsideVerticalBounds ? u" world" : u" w"; const int right_x = GetCursorPositionX(7); const int left_x = GetCursorPositionX(3); // All drags start from here. MoveMouseTo(gfx::Point(GetCursorPositionX(5), GetCursorYForTesting())); PressLeftMouseButton(); // Perform one continuous drag, checking the selection at various points. DragMouseTo(gfx::Point(left_x, -500)); EXPECT_EQ(expected_left, textfield_->GetSelectedText()); // NW. DragMouseTo(gfx::Point(right_x, -500)); EXPECT_EQ(expected_right, textfield_->GetSelectedText()); // NE. DragMouseTo(gfx::Point(right_x, 500)); EXPECT_EQ(expected_right, textfield_->GetSelectedText()); // SE. DragMouseTo(gfx::Point(left_x, 500)); EXPECT_EQ(expected_left, textfield_->GetSelectedText()); // SW. } #if BUILDFLAG(IS_WIN) TEST_F(TextfieldTest, DragAndDrop_AcceptDrop) { InitTextfield(); textfield_->SetText(u"hello world"); ui::OSExchangeData data; std::u16string string(u"string "); data.SetString(string); int formats = 0; std::set<ui::ClipboardFormatType> format_types; // Ensure that disabled textfields do not accept drops. textfield_->SetEnabled(false); EXPECT_FALSE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(0, formats); EXPECT_TRUE(format_types.empty()); EXPECT_FALSE(textfield_->CanDrop(data)); textfield_->SetEnabled(true); // Ensure that read-only textfields do not accept drops. textfield_->SetReadOnly(true); EXPECT_FALSE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(0, formats); EXPECT_TRUE(format_types.empty()); EXPECT_FALSE(textfield_->CanDrop(data)); textfield_->SetReadOnly(false); // Ensure that enabled and editable textfields do accept drops. EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(ui::OSExchangeData::STRING, formats); EXPECT_TRUE(format_types.empty()); EXPECT_TRUE(textfield_->CanDrop(data)); gfx::PointF drop_point(GetCursorPositionX(6), 0); ui::DropTargetEvent drop( data, drop_point, drop_point, ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE); EXPECT_EQ(ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop)); ui::mojom::DragOperation output_drag_op = ui::mojom::DragOperation::kNone; auto cb = textfield_->GetDropCallback(drop); std::move(cb).Run(drop, output_drag_op, /*drag_image_layer_owner=*/nullptr); EXPECT_EQ(ui::mojom::DragOperation::kCopy, output_drag_op); EXPECT_EQ(u"hello string world", textfield_->GetText()); // Ensure that textfields do not accept non-OSExchangeData::STRING types. ui::OSExchangeData bad_data; bad_data.SetFilename(base::FilePath(FILE_PATH_LITERAL("x"))); ui::ClipboardFormatType fmt = ui::ClipboardFormatType::BitmapType(); bad_data.SetPickledData(fmt, base::Pickle()); bad_data.SetFileContents(base::FilePath(L"x"), "x"); bad_data.SetHtml(std::u16string(u"x"), GURL("x.org")); ui::DownloadFileInfo download(base::FilePath(), nullptr); bad_data.provider().SetDownloadFileInfo(&download); EXPECT_FALSE(textfield_->CanDrop(bad_data)); } #endif TEST_F(TextfieldTest, DragAndDrop_InitiateDrag) { InitTextfield(); textfield_->SetText(u"hello string world"); // Ensure the textfield will provide selected text for drag data. std::u16string string; ui::OSExchangeData data; const gfx::Range kStringRange(6, 12); textfield_->SetSelectedRange(kStringRange); const gfx::Point kStringPoint(GetCursorPositionX(9), GetCursorYForTesting()); textfield_->WriteDragDataForView(nullptr, kStringPoint, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); // Ensure that disabled textfields do not support drag operations. textfield_->SetEnabled(false); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SetEnabled(true); // Ensure that textfields without selections do not support drag operations. textfield_->ClearSelection(); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SetSelectedRange(kStringRange); // Ensure that password textfields do not support drag operations. textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT); MoveMouseTo(kStringPoint); PressLeftMouseButton(); // Ensure that textfields only initiate drag operations inside the selection. EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(nullptr, gfx::Point())); EXPECT_FALSE( textfield_->CanStartDragForView(nullptr, gfx::Point(), gfx::Point())); EXPECT_EQ(ui::DragDropTypes::DRAG_COPY, textfield_->GetDragOperationsForView(nullptr, kStringPoint)); EXPECT_TRUE( textfield_->CanStartDragForView(nullptr, kStringPoint, gfx::Point())); // Ensure that textfields support local moves. EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, textfield_->GetDragOperationsForView(textfield_, kStringPoint)); } TEST_F(TextfieldTest, DragAndDrop_ToTheRight) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); std::u16string string; ui::OSExchangeData data; int formats = 0; int operations = 0; std::set<ui::ClipboardFormatType> format_types; // Start dragging "ello". textfield_->SetSelectedRange(gfx::Range(1, 5)); gfx::Point point(GetCursorPositionX(3), cursor_y); MoveMouseTo(point); PressLeftMouseButton(); EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, point, point)); operations = textfield_->GetDragOperationsForView(textfield_, point); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, operations); textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(ui::OSExchangeData::STRING, formats); EXPECT_TRUE(format_types.empty()); // Drop "ello" after "w". const gfx::PointF kDropPoint(GetCursorPositionX(7), cursor_y); EXPECT_TRUE(textfield_->CanDrop(data)); ui::DropTargetEvent drop_a(data, kDropPoint, kDropPoint, operations); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop_a)); ui::mojom::DragOperation output_drag_op = ui::mojom::DragOperation::kNone; auto cb = textfield_->GetDropCallback(drop_a); std::move(cb).Run(drop_a, output_drag_op, /*drag_image_layer_owner=*/nullptr); EXPECT_EQ(ui::mojom::DragOperation::kMove, output_drag_op); EXPECT_EQ(u"h welloorld", textfield_->GetText()); textfield_->OnDragDone(); // Undo/Redo the drag&drop change. SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"hello world", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"hello world", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"h welloorld", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"h welloorld", textfield_->GetText()); } TEST_F(TextfieldTest, DragAndDrop_ToTheLeft) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); std::u16string string; ui::OSExchangeData data; int formats = 0; int operations = 0; std::set<ui::ClipboardFormatType> format_types; // Start dragging " worl". textfield_->SetSelectedRange(gfx::Range(5, 10)); gfx::Point point(GetCursorPositionX(7), cursor_y); MoveMouseTo(point); PressLeftMouseButton(); EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, point, gfx::Point())); operations = textfield_->GetDragOperationsForView(textfield_, point); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, operations); textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(ui::OSExchangeData::STRING, formats); EXPECT_TRUE(format_types.empty()); // Drop " worl" after "h". EXPECT_TRUE(textfield_->CanDrop(data)); gfx::PointF drop_point(GetCursorPositionX(1), cursor_y); ui::DropTargetEvent drop_a(data, drop_point, drop_point, operations); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop_a)); ui::mojom::DragOperation output_drag_op = ui::mojom::DragOperation::kNone; auto cb = textfield_->GetDropCallback(drop_a); std::move(cb).Run(drop_a, output_drag_op, /*drag_image_layer_owner=*/nullptr); EXPECT_EQ(ui::mojom::DragOperation::kMove, output_drag_op); EXPECT_EQ(u"h worlellod", textfield_->GetText()); textfield_->OnDragDone(); // Undo/Redo the drag&drop change. SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"hello world", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"hello world", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"h worlellod", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"h worlellod", textfield_->GetText()); } TEST_F(TextfieldTest, DropCallbackCancelled) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); std::u16string string; ui::OSExchangeData data; int formats = 0; int operations = 0; std::set<ui::ClipboardFormatType> format_types; // Start dragging "hello". textfield_->SetSelectedRange(gfx::Range(0, 5)); gfx::Point point(GetCursorPositionX(3), cursor_y); MoveMouseTo(point); PressLeftMouseButton(); EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, point, gfx::Point())); operations = textfield_->GetDragOperationsForView(textfield_, point); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, operations); textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); EXPECT_EQ(ui::OSExchangeData::STRING, formats); EXPECT_TRUE(format_types.empty()); // Drop "hello" after "d". The drop callback should do nothing because // `textfield_` is mutated before the callback is run. EXPECT_TRUE(textfield_->CanDrop(data)); gfx::PointF drop_point(GetCursorPositionX(11), cursor_y); ui::DropTargetEvent drop_a(data, drop_point, drop_point, operations); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop_a)); ui::mojom::DragOperation output_drag_op = ui::mojom::DragOperation::kNone; auto cb = textfield_->GetDropCallback(drop_a); textfield_->AppendText(u"new text"); std::move(cb).Run(drop_a, output_drag_op, /*drag_image_layer_owner=*/nullptr); EXPECT_EQ(ui::mojom::DragOperation::kNone, output_drag_op); EXPECT_EQ(u"hello worldnew text", textfield_->GetText()); } TEST_F(TextfieldTest, DragAndDrop_Canceled) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); // Start dragging "worl". textfield_->SetSelectedRange(gfx::Range(6, 10)); gfx::Point point(GetCursorPositionX(8), cursor_y); MoveMouseTo(point); PressLeftMouseButton(); ui::OSExchangeData data; textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(textfield_->CanDrop(data)); // Drag the text over somewhere valid, outside the current selection. gfx::PointF drop_point(GetCursorPositionX(2), cursor_y); ui::DropTargetEvent drop(data, drop_point, drop_point, ui::DragDropTypes::DRAG_MOVE); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop)); // "Cancel" the drag, via move and release over the selection, and OnDragDone. gfx::Point drag_point(GetCursorPositionX(9), cursor_y); DragMouseTo(drag_point); ReleaseLeftMouseButton(); EXPECT_EQ(u"hello world", textfield_->GetText()); } TEST_F(TextfieldTest, ReadOnlyTest) { InitTextfield(); textfield_->SetText(u"read only"); textfield_->SetReadOnly(true); EXPECT_TRUE(textfield_->GetEnabled()); EXPECT_TRUE(textfield_->IsFocusable()); bool shift = false; SendHomeEvent(shift); EXPECT_EQ(0U, textfield_->GetCursorPosition()); SendEndEvent(shift); EXPECT_EQ(9U, textfield_->GetCursorPosition()); SendKeyEvent(ui::VKEY_LEFT, shift, false); EXPECT_EQ(8U, textfield_->GetCursorPosition()); SendWordEvent(ui::VKEY_LEFT, shift); EXPECT_EQ(5U, textfield_->GetCursorPosition()); shift = true; SendWordEvent(ui::VKEY_LEFT, shift); EXPECT_EQ(0U, textfield_->GetCursorPosition()); EXPECT_EQ(u"read ", textfield_->GetSelectedText()); textfield_->SelectAll(false); EXPECT_EQ(u"read only", textfield_->GetSelectedText()); // Cut should be disabled. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kCut)); textfield_->ExecuteCommand(Textfield::kCut, 0); SendKeyEvent(ui::VKEY_X, false, true); SendAlternateCut(); EXPECT_EQ(u"Test", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"read only", textfield_->GetText()); // Paste should be disabled. EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kPaste)); textfield_->ExecuteCommand(Textfield::kPaste, 0); SendKeyEvent(ui::VKEY_V, false, true); SendAlternatePaste(); EXPECT_EQ(u"read only", textfield_->GetText()); // Copy should work normally. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kCopy)); textfield_->ExecuteCommand(Textfield::kCopy, 0); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); SendKeyEvent(ui::VKEY_C, false, true); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"Test"); SendAlternateCopy(); EXPECT_EQ(u"read only", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); // SetText should work even in read only mode. textfield_->SetText(u" four five six "); EXPECT_EQ(u" four five six ", textfield_->GetText()); textfield_->SelectAll(false); EXPECT_EQ(u" four five six ", textfield_->GetSelectedText()); // Text field is unmodifiable and selection shouldn't change. SendKeyEvent(ui::VKEY_DELETE); EXPECT_EQ(u" four five six ", textfield_->GetSelectedText()); SendKeyEvent(ui::VKEY_BACK); EXPECT_EQ(u" four five six ", textfield_->GetSelectedText()); SendKeyEvent(ui::VKEY_T); EXPECT_EQ(u" four five six ", textfield_->GetSelectedText()); } TEST_F(TextfieldTest, TextInputClientTest) { InitTextfield(); ui::TextInputClient* client = textfield_; EXPECT_TRUE(client); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, client->GetTextInputType()); textfield_->SetText(u"0123456789"); gfx::Range range; EXPECT_TRUE(client->GetTextRange(&range)); EXPECT_EQ(0U, range.start()); EXPECT_EQ(10U, range.end()); EXPECT_TRUE(client->SetEditableSelectionRange(gfx::Range(1, 4))); EXPECT_TRUE(client->GetEditableSelectionRange(&range)); EXPECT_EQ(gfx::Range(1, 4), range); std::u16string substring; EXPECT_TRUE(client->GetTextFromRange(range, &substring)); EXPECT_EQ(u"123", substring); #if BUILDFLAG(IS_MAC) EXPECT_TRUE(client->DeleteRange(range)); EXPECT_EQ(u"0456789", textfield_->GetText()); #endif ui::CompositionText composition; composition.text = u"321"; // Set composition through input method. input_method_->Clear(); input_method_->SetCompositionTextForNextKey(composition); textfield_->clear(); on_before_user_action_ = on_after_user_action_ = 0; DispatchMockInputMethodKeyEvent(); EXPECT_TRUE(textfield_->key_received()); EXPECT_FALSE(textfield_->key_handled()); EXPECT_TRUE(client->HasCompositionText()); EXPECT_TRUE(client->GetCompositionTextRange(&range)); EXPECT_EQ(u"0321456789", textfield_->GetText()); EXPECT_EQ(gfx::Range(1, 4), range); EXPECT_EQ(1, on_before_user_action_); EXPECT_EQ(1, on_after_user_action_); input_method_->SetResultTextForNextKey(u"123"); on_before_user_action_ = on_after_user_action_ = 0; textfield_->clear(); DispatchMockInputMethodKeyEvent(); EXPECT_TRUE(textfield_->key_received()); EXPECT_FALSE(textfield_->key_handled()); EXPECT_FALSE(client->HasCompositionText()); EXPECT_FALSE(input_method_->cancel_composition_called()); EXPECT_EQ(u"0123456789", textfield_->GetText()); EXPECT_EQ(1, on_before_user_action_); EXPECT_EQ(1, on_after_user_action_); input_method_->Clear(); input_method_->SetCompositionTextForNextKey(composition); textfield_->clear(); DispatchMockInputMethodKeyEvent(); EXPECT_TRUE(client->HasCompositionText()); EXPECT_EQ(u"0123321456789", textfield_->GetText()); on_before_user_action_ = on_after_user_action_ = 0; textfield_->clear(); SendKeyEvent(ui::VKEY_RIGHT); EXPECT_FALSE(client->HasCompositionText()); EXPECT_TRUE(input_method_->cancel_composition_called()); EXPECT_TRUE(textfield_->key_received()); EXPECT_TRUE(textfield_->key_handled()); EXPECT_EQ(u"0123321456789", textfield_->GetText()); EXPECT_EQ(8U, textfield_->GetCursorPosition()); EXPECT_EQ(1, on_before_user_action_); EXPECT_EQ(1, on_after_user_action_); textfield_->clear(); textfield_->SetText(u"0123456789"); EXPECT_TRUE(client->SetEditableSelectionRange(gfx::Range(5, 5))); client->ExtendSelectionAndDelete(4, 2); EXPECT_EQ(u"0789", textfield_->GetText()); // On{Before,After}UserAction should be called by whatever user action // triggers clearing or setting a selection if appropriate. on_before_user_action_ = on_after_user_action_ = 0; textfield_->clear(); textfield_->ClearSelection(); textfield_->SelectAll(false); EXPECT_EQ(0, on_before_user_action_); EXPECT_EQ(0, on_after_user_action_); input_method_->Clear(); // Changing the Textfield to readonly shouldn't change the input client, since // it's still required for selections and clipboard copy. ui::TextInputClient* text_input_client = textfield_; EXPECT_TRUE(text_input_client); EXPECT_NE(ui::TEXT_INPUT_TYPE_NONE, text_input_client->GetTextInputType()); textfield_->SetReadOnly(true); EXPECT_TRUE(input_method_->text_input_type_changed()); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, text_input_client->GetTextInputType()); input_method_->Clear(); textfield_->SetReadOnly(false); EXPECT_TRUE(input_method_->text_input_type_changed()); EXPECT_NE(ui::TEXT_INPUT_TYPE_NONE, text_input_client->GetTextInputType()); input_method_->Clear(); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_TRUE(input_method_->text_input_type_changed()); } TEST_F(TextfieldTest, UndoRedoTest) { InitTextfield(); SendKeyEvent(ui::VKEY_A); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"a", textfield_->GetText()); // AppendText textfield_->AppendText(u"b"); last_contents_.clear(); // AppendText doesn't call ContentsChanged. EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"ab", textfield_->GetText()); // SetText SendKeyEvent(ui::VKEY_C); // Undo'ing append moves the cursor to the end for now. // A no-op SetText won't add a new edit; see TextfieldModel::SetText. EXPECT_EQ(u"abc", textfield_->GetText()); textfield_->SetText(u"abc"); EXPECT_EQ(u"abc", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"abc", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"abc", textfield_->GetText()); textfield_->SetText(u"123"); textfield_->SetText(u"123"); EXPECT_EQ(u"123", textfield_->GetText()); SendKeyEvent(ui::VKEY_END, false, false); SendKeyEvent(ui::VKEY_4, false, false); EXPECT_EQ(u"1234", textfield_->GetText()); last_contents_.clear(); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"123", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); // the insert edit "c" and set edit "123" are merged to single edit, // so text becomes "ab" after undo. EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"123", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"1234", textfield_->GetText()); // Undoing to the same text shouldn't call ContentsChanged. SendKeyEvent(ui::VKEY_A, false, true); // select all SendKeyEvent(ui::VKEY_A); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_B); SendKeyEvent(ui::VKEY_C); EXPECT_EQ(u"abc", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"1234", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"abc", textfield_->GetText()); // Delete/Backspace SendKeyEvent(ui::VKEY_BACK); EXPECT_EQ(u"ab", textfield_->GetText()); SendHomeEvent(false); SendKeyEvent(ui::VKEY_DELETE); EXPECT_EQ(u"b", textfield_->GetText()); SendKeyEvent(ui::VKEY_A, false, true); SendKeyEvent(ui::VKEY_DELETE); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"b", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"abc", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"ab", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"b", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"", textfield_->GetText()); } // Most platforms support Ctrl+Y as an alternative to Ctrl+Shift+Z, but on Mac // Ctrl+Y is bound to "Yank" and Cmd+Y is bound to "Show full history". So, on // Mac, Cmd+Shift+Z is sent for the tests above and the Ctrl+Y test below is // skipped. #if !BUILDFLAG(IS_MAC) // Test that Ctrl+Y works for Redo, as well as Ctrl+Shift+Z. TEST_F(TextfieldTest, RedoWithCtrlY) { InitTextfield(); SendKeyEvent(ui::VKEY_A); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Y, false, true); EXPECT_EQ(u"a", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_EQ(u"", textfield_->GetText()); SendKeyEvent(ui::VKEY_Z, true, true); EXPECT_EQ(u"a", textfield_->GetText()); } #endif // !BUILDFLAG(IS_MAC) // Non-Mac platforms don't have a key binding for Yank. Since this test is only // run on Mac, it uses some Mac specific key bindings. #if BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, Yank) { InitTextfield(2); textfield_->SetText(u"abcdef"); textfield_->SetSelectedRange(gfx::Range(2, 4)); // Press Ctrl+Y to yank. SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); // Initially the kill buffer should be empty. Hence yanking should delete the // selected text. EXPECT_EQ(u"abef", textfield_->GetText()); EXPECT_EQ(gfx::Range(2), textfield_->GetSelectedRange()); // Press Ctrl+K to delete to end of paragraph. This should place the deleted // text in the kill buffer. SendKeyPress(ui::VKEY_K, ui::EF_CONTROL_DOWN); EXPECT_EQ(u"ab", textfield_->GetText()); EXPECT_EQ(gfx::Range(2), textfield_->GetSelectedRange()); // Yank twice. SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); EXPECT_EQ(u"abefef", textfield_->GetText()); EXPECT_EQ(gfx::Range(6), textfield_->GetSelectedRange()); // Verify pressing backspace does not modify the kill buffer. SendKeyEvent(ui::VKEY_BACK); SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); EXPECT_EQ(u"abefeef", textfield_->GetText()); EXPECT_EQ(gfx::Range(7), textfield_->GetSelectedRange()); // Move focus to next textfield. widget_->GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(2, GetFocusedView()->GetID()); Textfield* textfield2 = static_cast<Textfield*>(GetFocusedView()); EXPECT_TRUE(textfield2->GetText().empty()); // Verify yanked text persists across multiple textfields and that yanking // into a password textfield works. textfield2->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); EXPECT_EQ(u"ef", textfield2->GetText()); EXPECT_EQ(gfx::Range(2), textfield2->GetSelectedRange()); // Verify deletion in a password textfield does not modify the kill buffer. textfield2->SetText(u"hello"); textfield2->SetSelectedRange(gfx::Range(0)); SendKeyPress(ui::VKEY_K, ui::EF_CONTROL_DOWN); EXPECT_TRUE(textfield2->GetText().empty()); textfield_->RequestFocus(); textfield_->SetSelectedRange(gfx::Range(0)); SendKeyPress(ui::VKEY_Y, ui::EF_CONTROL_DOWN); EXPECT_EQ(u"efabefeef", textfield_->GetText()); } #endif // BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, CutCopyPaste) { InitTextfield(); // Ensure kCut cuts. textfield_->SetText(u"123"); textfield_->SelectAll(false); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kCut)); textfield_->ExecuteCommand(Textfield::kCut, 0); EXPECT_EQ(u"123", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Ensure [Ctrl]+[x] cuts and [Ctrl]+[Alt][x] does nothing. textfield_->SetText(u"456"); textfield_->SelectAll(false); SendKeyEvent(ui::VKEY_X, true, false, true, false); EXPECT_EQ(u"123", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"456", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); SendKeyEvent(ui::VKEY_X, false, true); EXPECT_EQ(u"456", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Ensure [Shift]+[Delete] cuts. textfield_->SetText(u"123"); textfield_->SelectAll(false); SendAlternateCut(); EXPECT_EQ(u"123", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Reset clipboard text. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u""); // Ensure [Shift]+[Delete] is a no-op in case there is no selection. textfield_->SetText(u"123"); textfield_->SetSelectedRange(gfx::Range(0)); SendAlternateCut(); EXPECT_EQ(u"", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"123", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); // Ensure kCopy copies. textfield_->SetText(u"789"); textfield_->SelectAll(false); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kCopy)); textfield_->ExecuteCommand(Textfield::kCopy, 0); EXPECT_EQ(u"789", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Ensure [Ctrl]+[c] copies and [Ctrl]+[Alt][c] does nothing. textfield_->SetText(u"012"); textfield_->SelectAll(false); SendKeyEvent(ui::VKEY_C, true, false, true, false); EXPECT_EQ(u"789", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); SendKeyEvent(ui::VKEY_C, false, true); EXPECT_EQ(u"012", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Ensure [Ctrl]+[Insert] copies. textfield_->SetText(u"345"); textfield_->SelectAll(false); SendAlternateCopy(); EXPECT_EQ(u"345", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"345", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kCopyPaste, GetAndResetCopiedToClipboard()); // Ensure kPaste, [Ctrl]+[V], and [Shift]+[Insert] pastes; // also ensure that [Ctrl]+[Alt]+[V] does nothing. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"abc"); textfield_->SetText(std::u16string()); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kPaste)); textfield_->ExecuteCommand(Textfield::kPaste, 0); EXPECT_EQ(u"abc", textfield_->GetText()); SendKeyEvent(ui::VKEY_V, false, true); EXPECT_EQ(u"abcabc", textfield_->GetText()); SendAlternatePaste(); EXPECT_EQ(u"abcabcabc", textfield_->GetText()); SendKeyEvent(ui::VKEY_V, true, false, true, false); EXPECT_EQ(u"abcabcabc", textfield_->GetText()); // Ensure [Ctrl]+[Shift]+[Insert] is a no-op. textfield_->SelectAll(false); SendKeyEvent(ui::VKEY_INSERT, true, true); EXPECT_EQ(u"abc", GetClipboardText(ui::ClipboardBuffer::kCopyPaste)); EXPECT_EQ(u"abcabcabc", textfield_->GetText()); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); } TEST_F(TextfieldTest, CutCopyPasteWithEditCommand) { InitTextfield(); // Target the "WIDGET". This means that, on Mac, keystrokes will be sent to a // dummy 'Edit' menu which will dispatch into the responder chain as a "cut:" // selector rather than a keydown. This has no effect on other platforms // (events elsewhere always dispatch via a ui::EventProcessor, which is // responsible for finding targets). event_generator_->set_target(ui::test::EventGenerator::Target::WIDGET); SendKeyEvent(ui::VKEY_O, false, false); // Type "o". SendKeyEvent(ui::VKEY_A, false, true); // Select it. SendKeyEvent(ui::VKEY_C, false, true); // Copy it. SendKeyEvent(ui::VKEY_RIGHT, false, false); // Deselect and navigate to end. EXPECT_EQ(u"o", textfield_->GetText()); SendKeyEvent(ui::VKEY_V, false, true); // Paste it. EXPECT_EQ(u"oo", textfield_->GetText()); SendKeyEvent(ui::VKEY_H, false, false); // Type "h". EXPECT_EQ(u"ooh", textfield_->GetText()); SendKeyEvent(ui::VKEY_LEFT, true, false); // Select "h". SendKeyEvent(ui::VKEY_X, false, true); // Cut it. EXPECT_EQ(u"oo", textfield_->GetText()); } TEST_F(TextfieldTest, SelectWordFromEmptySelection) { InitTextfield(); textfield_->SetText(u"ab cde.123 4"); // Place the cursor at the beginning of the text. textfield_->SetEditableSelectionRange(gfx::Range(0)); textfield_->SelectWord(); EXPECT_EQ(u"ab", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(0, 2), textfield_->GetSelectedRange()); // Place the cursor after "c". textfield_->SetEditableSelectionRange(gfx::Range(4)); textfield_->SelectWord(); EXPECT_EQ(u"cde", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(3, 6), textfield_->GetSelectedRange()); // Place the cursor after "2". textfield_->SetEditableSelectionRange(gfx::Range(9)); textfield_->SelectWord(); EXPECT_EQ(u"123", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(7, 10), textfield_->GetSelectedRange()); // Place the cursor at the end of the text. textfield_->SetEditableSelectionRange(gfx::Range(12)); textfield_->SelectWord(); EXPECT_EQ(u"4", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(11, 12), textfield_->GetSelectedRange()); } TEST_F(TextfieldTest, SelectWordFromNonEmptySelection) { InitTextfield(); textfield_->SetText(u"ab cde.123 4"); // Select "b". textfield_->SetEditableSelectionRange(gfx::Range(1, 2)); textfield_->SelectWord(); EXPECT_EQ(u"ab", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(0, 2), textfield_->GetSelectedRange()); // Select "b c" textfield_->SetEditableSelectionRange(gfx::Range(1, 4)); textfield_->SelectWord(); EXPECT_EQ(u"ab cde", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(0, 6), textfield_->GetSelectedRange()); // Select "e." textfield_->SetEditableSelectionRange(gfx::Range(5, 7)); textfield_->SelectWord(); EXPECT_EQ(u"cde.", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(3, 7), textfield_->GetSelectedRange()); // Select "e.1" textfield_->SetEditableSelectionRange(gfx::Range(5, 8)); textfield_->SelectWord(); EXPECT_EQ(u"cde.123", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(3, 10), textfield_->GetSelectedRange()); } TEST_F(TextfieldTest, SelectWordFromNonAlphaNumericFragment) { InitTextfield(); textfield_->SetText(u" HELLO !! WO RLD"); // Place the cursor within " !! ". textfield_->SetEditableSelectionRange(gfx::Range(8)); textfield_->SelectWord(); EXPECT_EQ(u" !! ", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(7, 13), textfield_->GetSelectedRange()); textfield_->SetEditableSelectionRange(gfx::Range(10)); textfield_->SelectWord(); EXPECT_EQ(u" !! ", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(7, 13), textfield_->GetSelectedRange()); } TEST_F(TextfieldTest, SelectWordFromWhitespaceFragment) { InitTextfield(); textfield_->SetText(u" HELLO !! WO RLD"); textfield_->SetEditableSelectionRange(gfx::Range(17)); textfield_->SelectWord(); EXPECT_EQ(u" ", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(15, 20), textfield_->GetSelectedRange()); } TEST_F(TextfieldTest, SelectCommands) { InitTextfield(); textfield_->SetText(u"hello string world"); // Select all and select word commands should both be enabled when there is no // selection. textfield_->SetEditableSelectionRange(gfx::Range(8)); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_FALSE(test_api_->touch_selection_controller()); // Select word at current position. Select word command should now be disabled // since there is already a selection. textfield_->ExecuteCommand(Textfield::kSelectWord, 0); EXPECT_EQ(u"string", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(6, 12), textfield_->GetSelectedRange()); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_FALSE(test_api_->touch_selection_controller()); // Select all text. Select all and select word commands should now both be // disabled. textfield_->ExecuteCommand(Textfield::kSelectAll, 0); EXPECT_EQ(u"hello string world", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(0, 18), textfield_->GetSelectedRange()); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_FALSE(test_api_->touch_selection_controller()); } // No touch on desktop Mac. #if !BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, SelectCommandsFromTouchEvent) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"hello string world"); // Select all and select word commands should both be enabled when there is no // selection. textfield_->SetEditableSelectionRange(gfx::Range(8)); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_FALSE(test_api_->touch_selection_controller()); // Select word at current position. Select word command should now be disabled // since there is already a selection. textfield_->ExecuteCommand(Textfield::kSelectWord, ui::EF_FROM_TOUCH); EXPECT_EQ(u"string", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(6, 12), textfield_->GetSelectedRange()); EXPECT_TRUE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_TRUE(test_api_->touch_selection_controller()); // Select all text. Select all and select word commands should now both be // disabled. textfield_->ExecuteCommand(Textfield::kSelectAll, ui::EF_FROM_TOUCH); EXPECT_EQ(u"hello string world", textfield_->GetSelectedText()); EXPECT_EQ(gfx::Range(0, 18), textfield_->GetSelectedRange()); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectAll)); EXPECT_FALSE(textfield_->IsCommandIdEnabled(Textfield::kSelectWord)); EXPECT_TRUE(test_api_->touch_selection_controller()); } #endif TEST_F(TextfieldTest, OvertypeMode) { InitTextfield(); // Overtype mode should be disabled (no-op [Insert]). textfield_->SetText(u"2"); const bool shift = false; SendHomeEvent(shift); // Note: On Mac, there is no insert key. Insert sends kVK_Help. Currently, // since there is no overtype on toolkit-views, the behavior happens to match. // However, there's no enable-overtype equivalent key combination on OSX. SendKeyEvent(ui::VKEY_INSERT); SendKeyEvent(ui::VKEY_1, false, false); EXPECT_EQ(u"12", textfield_->GetText()); } TEST_F(TextfieldTest, TextCursorDisplayTest) { InitTextfield(); // LTR-RTL string in LTR context. SendKeyEvent('a'); EXPECT_EQ(u"a", textfield_->GetText()); int x = GetCursorBounds().x(); int prev_x = x; SendKeyEvent('b'); EXPECT_EQ(u"ab", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_LT(prev_x, x); prev_x = x; SendKeyEvent(0x05E1); EXPECT_EQ(u"ab\x05E1", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); SendKeyEvent(0x05E2); EXPECT_EQ(u"ab\x05E1\x5E2", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); // Clear text. SendKeyEvent(ui::VKEY_A, false, true); SendKeyEvent(ui::VKEY_DELETE); // RTL-LTR string in LTR context. SendKeyEvent(0x05E1); EXPECT_EQ(u"\x05E1", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_EQ(GetDisplayRect().x(), x); prev_x = x; SendKeyEvent(0x05E2); EXPECT_EQ(u"\x05E1\x05E2", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); SendKeyEvent('a'); EXPECT_EQ( u"\x05E1\x5E2" u"a", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_LT(prev_x, x); prev_x = x; SendKeyEvent('b'); EXPECT_EQ( u"\x05E1\x5E2" u"ab", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_LT(prev_x, x); } TEST_F(TextfieldTest, TextCursorDisplayInRTLTest) { std::string locale = base::i18n::GetConfiguredLocale(); base::i18n::SetICUDefaultLocale("he"); InitTextfield(); // LTR-RTL string in RTL context. SendKeyEvent('a'); EXPECT_EQ(u"a", textfield_->GetText()); int x = GetCursorBounds().x(); EXPECT_EQ(GetDisplayRect().right() - 1, x); int prev_x = x; SendKeyEvent('b'); EXPECT_EQ(u"ab", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); SendKeyEvent(0x05E1); EXPECT_EQ(u"ab\x05E1", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GT(prev_x, x); prev_x = x; SendKeyEvent(0x05E2); EXPECT_EQ(u"ab\x05E1\x5E2", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GT(prev_x, x); // Clear text. SendKeyEvent(ui::VKEY_A, false, true); SendKeyEvent(ui::VKEY_DELETE); // RTL-LTR string in RTL context. SendKeyEvent(0x05E1); EXPECT_EQ(u"\x05E1", textfield_->GetText()); x = GetCursorBounds().x(); prev_x = x; SendKeyEvent(0x05E2); EXPECT_EQ(u"\x05E1\x05E2", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GT(prev_x, x); prev_x = x; SendKeyEvent('a'); EXPECT_EQ( u"\x05E1\x5E2" u"a", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); prev_x = x; SendKeyEvent('b'); EXPECT_EQ( u"\x05E1\x5E2" u"ab", textfield_->GetText()); x = GetCursorBounds().x(); EXPECT_GE(1, std::abs(x - prev_x)); // Reset locale. base::i18n::SetICUDefaultLocale(locale); } TEST_F(TextfieldTest, TextCursorPositionInRTLTest) { std::string locale = base::i18n::GetConfiguredLocale(); base::i18n::SetICUDefaultLocale("he"); InitTextfield(); // LTR-RTL string in RTL context. int text_cursor_position_prev = test_api_->GetCursorViewRect().x(); SendKeyEvent('a'); SendKeyEvent('b'); EXPECT_EQ(u"ab", textfield_->GetText()); int text_cursor_position_new = test_api_->GetCursorViewRect().x(); // Text cursor stays at same place after inserting new charactors in RTL mode. EXPECT_EQ(text_cursor_position_prev, text_cursor_position_new); // Reset locale. base::i18n::SetICUDefaultLocale(locale); } TEST_F(TextfieldTest, TextCursorPositionInLTRTest) { InitTextfield(); // LTR-RTL string in LTR context. int text_cursor_position_prev = test_api_->GetCursorViewRect().x(); SendKeyEvent('a'); SendKeyEvent('b'); EXPECT_EQ(u"ab", textfield_->GetText()); int text_cursor_position_new = test_api_->GetCursorViewRect().x(); // Text cursor moves to right after inserting new charactors in LTR mode. EXPECT_LT(text_cursor_position_prev, text_cursor_position_new); } TEST_F(TextfieldTest, HitInsideTextAreaTest) { InitTextfield(); textfield_->SetText(u"ab\x05E1\x5E2"); std::vector<gfx::Rect> cursor_bounds; // Save each cursor bound. gfx::SelectionModel sel(0, gfx::CURSOR_FORWARD); cursor_bounds.push_back(GetCursorBounds(sel)); sel = gfx::SelectionModel(1, gfx::CURSOR_BACKWARD); gfx::Rect bound = GetCursorBounds(sel); sel = gfx::SelectionModel(1, gfx::CURSOR_FORWARD); EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); cursor_bounds.push_back(bound); // Check that a cursor at the end of the Latin portion of the text is at the // same position as a cursor placed at the end of the RTL Hebrew portion. sel = gfx::SelectionModel(2, gfx::CURSOR_BACKWARD); bound = GetCursorBounds(sel); sel = gfx::SelectionModel(4, gfx::CURSOR_BACKWARD); EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); cursor_bounds.push_back(bound); sel = gfx::SelectionModel(3, gfx::CURSOR_BACKWARD); bound = GetCursorBounds(sel); sel = gfx::SelectionModel(3, gfx::CURSOR_FORWARD); EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); cursor_bounds.push_back(bound); sel = gfx::SelectionModel(2, gfx::CURSOR_FORWARD); bound = GetCursorBounds(sel); sel = gfx::SelectionModel(4, gfx::CURSOR_FORWARD); EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); cursor_bounds.push_back(bound); // Expected cursor position when clicking left and right of each character. size_t cursor_pos_expected[] = {0, 1, 1, 2, 4, 3, 3, 2}; int index = 0; for (size_t i = 0; i < cursor_bounds.size() - 1; ++i) { int half_width = (cursor_bounds[i + 1].x() - cursor_bounds[i].x()) / 2; MouseClick(cursor_bounds[i], half_width / 2); EXPECT_EQ(cursor_pos_expected[index++], textfield_->GetCursorPosition()); // To avoid trigger double click. Not using sleep() since it takes longer // for the test to run if using sleep(). NonClientMouseClick(); MouseClick(cursor_bounds[i + 1], -(half_width / 2)); EXPECT_EQ(cursor_pos_expected[index++], textfield_->GetCursorPosition()); NonClientMouseClick(); } } TEST_F(TextfieldTest, HitOutsideTextAreaTest) { InitTextfield(); // LTR-RTL string in LTR context. textfield_->SetText(u"ab\x05E1\x5E2"); const bool shift = false; SendHomeEvent(shift); gfx::Rect bound = GetCursorBounds(); MouseClick(bound, -10); EXPECT_EQ(bound, GetCursorBounds()); SendEndEvent(shift); bound = GetCursorBounds(); MouseClick(bound, 10); EXPECT_EQ(bound, GetCursorBounds()); NonClientMouseClick(); // RTL-LTR string in LTR context. textfield_->SetText( u"\x05E1\x5E2" u"ab"); SendHomeEvent(shift); bound = GetCursorBounds(); MouseClick(bound, 10); EXPECT_EQ(bound, GetCursorBounds()); SendEndEvent(shift); bound = GetCursorBounds(); MouseClick(bound, -10); EXPECT_EQ(bound, GetCursorBounds()); } TEST_F(TextfieldTest, HitOutsideTextAreaInRTLTest) { std::string locale = base::i18n::GetConfiguredLocale(); base::i18n::SetICUDefaultLocale("he"); InitTextfield(); // RTL-LTR string in RTL context. textfield_->SetText( u"\x05E1\x5E2" u"ab"); const bool shift = false; SendHomeEvent(shift); gfx::Rect bound = GetCursorBounds(); MouseClick(bound, 10); EXPECT_EQ(bound, GetCursorBounds()); SendEndEvent(shift); bound = GetCursorBounds(); MouseClick(bound, -10); EXPECT_EQ(bound, GetCursorBounds()); NonClientMouseClick(); // LTR-RTL string in RTL context. textfield_->SetText(u"ab\x05E1\x5E2"); SendHomeEvent(shift); bound = GetCursorBounds(); MouseClick(bound, -10); EXPECT_EQ(bound, GetCursorBounds()); SendEndEvent(shift); bound = GetCursorBounds(); MouseClick(bound, 10); EXPECT_EQ(bound, GetCursorBounds()); // Reset locale. base::i18n::SetICUDefaultLocale(locale); } TEST_F(TextfieldTest, OverflowTest) { InitTextfield(); std::u16string str; for (size_t i = 0; i < 500; ++i) SendKeyEvent('a'); SendKeyEvent(kHebrewLetterSamekh); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); // Test mouse pointing. MouseClick(GetCursorBounds(), -1); EXPECT_EQ(500U, textfield_->GetCursorPosition()); // Clear text. SendKeyEvent(ui::VKEY_A, false, true); SendKeyEvent(ui::VKEY_DELETE); for (size_t i = 0; i < 500; ++i) SendKeyEvent(kHebrewLetterSamekh); SendKeyEvent('a'); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); MouseClick(GetCursorBounds(), -1); EXPECT_EQ(501U, textfield_->GetCursorPosition()); } TEST_F(TextfieldTest, OverflowInRTLTest) { std::string locale = base::i18n::GetConfiguredLocale(); base::i18n::SetICUDefaultLocale("he"); InitTextfield(); std::u16string str; for (size_t i = 0; i < 500; ++i) SendKeyEvent('a'); SendKeyEvent(kHebrewLetterSamekh); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); MouseClick(GetCursorBounds(), 1); EXPECT_EQ(501U, textfield_->GetCursorPosition()); // Clear text. SendKeyEvent(ui::VKEY_A, false, true); SendKeyEvent(ui::VKEY_DELETE); for (size_t i = 0; i < 500; ++i) SendKeyEvent(kHebrewLetterSamekh); SendKeyEvent('a'); EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); MouseClick(GetCursorBounds(), 1); EXPECT_EQ(500U, textfield_->GetCursorPosition()); // Reset locale. base::i18n::SetICUDefaultLocale(locale); } TEST_F(TextfieldTest, CommitComposingTextTest) { InitTextfield(); ui::CompositionText composition; composition.text = u"abc123"; textfield_->SetCompositionText(composition); size_t composed_text_length = textfield_->ConfirmCompositionText(/* keep_selection */ false); EXPECT_EQ(composed_text_length, 6u); } TEST_F(TextfieldTest, CommitEmptyComposingTextTest) { InitTextfield(); ui::CompositionText composition; composition.text = u""; textfield_->SetCompositionText(composition); size_t composed_text_length = textfield_->ConfirmCompositionText(/* keep_selection */ false); EXPECT_EQ(composed_text_length, 0u); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // SetCompositionFromExistingText is only available on Windows and Chrome OS. TEST_F(TextfieldTest, SetCompositionFromExistingTextTest) { InitTextfield(); textfield_->SetText(u"abc"); textfield_->SetCompositionFromExistingText(gfx::Range(1, 3), {}); gfx::Range actual_range; EXPECT_TRUE(textfield_->HasCompositionText()); EXPECT_TRUE(textfield_->GetCompositionTextRange(&actual_range)); EXPECT_EQ(actual_range, gfx::Range(1, 3)); } #endif TEST_F(TextfieldTest, GetCompositionCharacterBoundsTest) { InitTextfield(); ui::CompositionText composition; composition.text = u"abc123"; const uint32_t char_count = static_cast<uint32_t>(composition.text.length()); // Compare the composition character bounds with surrounding cursor bounds. for (uint32_t i = 0; i < char_count; ++i) { composition.selection = gfx::Range(i); textfield_->SetCompositionText(composition); gfx::Point cursor_origin = GetCursorBounds().origin(); views::View::ConvertPointToScreen(textfield_, &cursor_origin); composition.selection = gfx::Range(i + 1); textfield_->SetCompositionText(composition); gfx::Point next_cursor_bottom_left = GetCursorBounds().bottom_left(); views::View::ConvertPointToScreen(textfield_, &next_cursor_bottom_left); gfx::Rect character; EXPECT_TRUE(textfield_->GetCompositionCharacterBounds(i, &character)); EXPECT_EQ(character.origin(), cursor_origin) << " i=" << i; EXPECT_EQ(character.bottom_right(), next_cursor_bottom_left) << " i=" << i; } // Return false if the index is out of range. gfx::Rect rect; EXPECT_FALSE(textfield_->GetCompositionCharacterBounds(char_count, &rect)); EXPECT_FALSE( textfield_->GetCompositionCharacterBounds(char_count + 1, &rect)); EXPECT_FALSE( textfield_->GetCompositionCharacterBounds(char_count + 100, &rect)); } TEST_F(TextfieldTest, GetCompositionCharacterBounds_ComplexText) { InitTextfield(); const char16_t kUtf16Chars[] = { // U+0020 SPACE 0x0020, // U+1F408 (CAT) as surrogate pair 0xd83d, 0xdc08, // U+5642 as Ideographic Variation Sequences 0x5642, 0xDB40, 0xDD00, // U+260E (BLACK TELEPHONE) as Emoji Variation Sequences 0x260E, 0xFE0F, // U+0020 SPACE 0x0020, }; const size_t kUtf16CharsCount = std::size(kUtf16Chars); ui::CompositionText composition; composition.text.assign(kUtf16Chars, kUtf16Chars + kUtf16CharsCount); textfield_->SetCompositionText(composition); // Make sure GetCompositionCharacterBounds never fails for index. gfx::Rect rects[kUtf16CharsCount]; for (uint32_t i = 0; i < kUtf16CharsCount; ++i) EXPECT_TRUE(textfield_->GetCompositionCharacterBounds(i, &rects[i])); // Here we might expect the following results but it actually depends on how // Uniscribe or HarfBuzz treats them with given font. // - rects[1] == rects[2] // - rects[3] == rects[4] == rects[5] // - rects[6] == rects[7] } #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(TextfieldTest, SetAutocorrectRange) { InitTextfield(); textfield_->SetText(u"abc def ghi"); textfield_->SetAutocorrectRange(gfx::Range(4, 7)); gfx::Range autocorrect_range = textfield_->GetAutocorrectRange(); EXPECT_EQ(autocorrect_range, gfx::Range(4, 7)); } TEST_F(TextfieldTest, DoesNotSetAutocorrectRangeWhenRangeGivenIsInvalid) { InitTextfield(); textfield_->SetText(u"abc"); EXPECT_FALSE(textfield_->SetAutocorrectRange(gfx::Range(8, 11))); EXPECT_TRUE(textfield_->GetAutocorrectRange().is_empty()); } TEST_F(TextfieldTest, ClearsAutocorrectRangeWhenSetAutocorrectRangeWithEmptyRange) { InitTextfield(); textfield_->SetText(u"abc"); // TODO(b/161490813): Change to EXPECT_TRUE after fixing set range. EXPECT_FALSE(textfield_->SetAutocorrectRange(gfx::Range())); EXPECT_TRUE(textfield_->GetAutocorrectRange().is_empty()); } TEST_F(TextfieldTest, GetAutocorrectCharacterBoundsTest) { InitTextfield(); textfield_->InsertText( u"hello placeholder text", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); textfield_->SetAutocorrectRange(gfx::Range(3, 10)); EXPECT_EQ(textfield_->GetAutocorrectRange(), gfx::Range(3, 10)); gfx::Rect rect_for_long_text = textfield_->GetAutocorrectCharacterBounds(); textfield_->clear(); textfield_->InsertText( u"hello placeholder text", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); textfield_->SetAutocorrectRange(gfx::Range(3, 8)); EXPECT_EQ(textfield_->GetAutocorrectRange(), gfx::Range(3, 8)); gfx::Rect rect_for_short_text = textfield_->GetAutocorrectCharacterBounds(); EXPECT_LT(rect_for_short_text.x(), rect_for_long_text.x()); EXPECT_EQ(rect_for_short_text.y(), rect_for_long_text.y()); EXPECT_EQ(rect_for_short_text.height(), rect_for_long_text.height()); // TODO(crbug.com/1108170): Investigate why the rectangle width is wrong. // The value seems to be wrong due to the incorrect value being returned from // RenderText::GetCursorBounds(). Unfortuantly, that is tricky to fix, since // RenderText is used in other parts of the codebase. // When fixed, the following EXPECT statement should pass. // EXPECT_LT(rect_for_short_text.width(), rect_for_long_text.width()); } // TODO(crbug.com/1108170): Add a test to check that when the composition / // surrounding text is updated, the AutocorrectRange is updated accordingly. #endif // BUILDFLAG(IS_CHROMEOS_ASH) // The word we select by double clicking should remain selected regardless of // where we drag the mouse afterwards without releasing the left button. TEST_F(TextfieldTest, KeepInitiallySelectedWord) { InitTextfield(); textfield_->SetText(u"abc def ghi"); textfield_->SetSelectedRange(gfx::Range(5, 5)); const gfx::Rect middle_cursor = GetCursorBounds(); textfield_->SetSelectedRange(gfx::Range(0, 0)); const gfx::Point beginning = GetCursorBounds().origin(); // Double click, but do not release the left button. MouseClick(middle_cursor, 0); const gfx::Point middle(middle_cursor.x(), middle_cursor.y() + middle_cursor.height() / 2); MoveMouseTo(middle); PressLeftMouseButton(); EXPECT_EQ(gfx::Range(4, 7), textfield_->GetSelectedRange()); // Drag the mouse to the beginning of the textfield. DragMouseTo(beginning); EXPECT_EQ(gfx::Range(7, 0), textfield_->GetSelectedRange()); } // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch // of lacros-chrome is complete. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) TEST_F(TextfieldTest, SelectionClipboard) { InitTextfield(); textfield_->SetText(u"0123"); const int cursor_y = GetCursorYForTesting(); gfx::Point point_1(GetCursorPositionX(1), cursor_y); gfx::Point point_2(GetCursorPositionX(2), cursor_y); gfx::Point point_3(GetCursorPositionX(3), cursor_y); gfx::Point point_4(GetCursorPositionX(4), cursor_y); // Text selected by the mouse should be placed on the selection clipboard. ui::MouseEvent press(ui::ET_MOUSE_PRESSED, point_1, point_1, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMousePressed(press); ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, point_3, point_3, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMouseDragged(drag); ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point_3, point_3, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMouseReleased(release); EXPECT_EQ(gfx::Range(1, 3), textfield_->GetSelectedRange()); EXPECT_EQ(u"12", GetClipboardText(ui::ClipboardBuffer::kSelection)); // Select-all should update the selection clipboard. SendKeyEvent(ui::VKEY_A, false, true); EXPECT_EQ(gfx::Range(0, 4), textfield_->GetSelectedRange()); EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); // Shift-click selection modifications should update the clipboard. NonClientMouseClick(); ui::MouseEvent press_2(ui::ET_MOUSE_PRESSED, point_2, point_2, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); press_2.set_flags(press_2.flags() | ui::EF_SHIFT_DOWN); textfield_->OnMousePressed(press_2); ui::MouseEvent release_2(ui::ET_MOUSE_RELEASED, point_2, point_2, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMouseReleased(release_2); EXPECT_EQ(gfx::Range(0, 2), textfield_->GetSelectedRange()); EXPECT_EQ(u"01", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); // Shift-Left/Right should update the selection clipboard. SendKeyEvent(ui::VKEY_RIGHT, true, false); EXPECT_EQ(u"012", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); SendKeyEvent(ui::VKEY_LEFT, true, false); EXPECT_EQ(u"01", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); SendKeyEvent(ui::VKEY_RIGHT, true, true); EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); // Moving the cursor without a selection should not change the clipboard. SendKeyEvent(ui::VKEY_LEFT, false, false); EXPECT_EQ(gfx::Range(0, 0), textfield_->GetSelectedRange()); EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); // Middle clicking should paste at the mouse (not cursor) location. // The cursor should be placed at the end of the pasted text. ui::MouseEvent middle(ui::ET_MOUSE_PRESSED, point_4, point_4, ui::EventTimeForNow(), ui::EF_MIDDLE_MOUSE_BUTTON, ui::EF_MIDDLE_MOUSE_BUTTON); textfield_->OnMousePressed(middle); EXPECT_EQ(u"01230123", textfield_->GetText()); EXPECT_EQ(gfx::Range(8, 8), textfield_->GetSelectedRange()); EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); // Middle clicking on an unfocused textfield should focus it and paste. textfield_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(textfield_->HasFocus()); textfield_->OnMousePressed(middle); EXPECT_TRUE(textfield_->HasFocus()); EXPECT_EQ(u"012301230123", textfield_->GetText()); EXPECT_EQ(gfx::Range(8, 8), textfield_->GetSelectedRange()); EXPECT_EQ(u"0123", GetClipboardText(ui::ClipboardBuffer::kSelection)); // Middle clicking with an empty selection clipboard should still focus. SetClipboardText(ui::ClipboardBuffer::kSelection, std::u16string()); textfield_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(textfield_->HasFocus()); textfield_->OnMousePressed(middle); EXPECT_TRUE(textfield_->HasFocus()); EXPECT_EQ(u"012301230123", textfield_->GetText()); EXPECT_EQ(gfx::Range(4, 4), textfield_->GetSelectedRange()); EXPECT_TRUE(GetClipboardText(ui::ClipboardBuffer::kSelection).empty()); // Middle clicking in the selection should insert the selection clipboard // contents into the middle of the selection, and move the cursor to the end // of the pasted content. SetClipboardText(ui::ClipboardBuffer::kCopyPaste, u"foo"); textfield_->SetSelectedRange(gfx::Range(2, 6)); textfield_->OnMousePressed(middle); EXPECT_EQ(u"0123foo01230123", textfield_->GetText()); EXPECT_EQ(gfx::Range(7, 7), textfield_->GetSelectedRange()); EXPECT_EQ(u"foo", GetClipboardText(ui::ClipboardBuffer::kSelection)); // Double and triple clicking should update the clipboard contents. textfield_->SetText(u"ab cd ef"); gfx::Point word(GetCursorPositionX(4), cursor_y); ui::MouseEvent press_word(ui::ET_MOUSE_PRESSED, word, word, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMousePressed(press_word); ui::MouseEvent release_word(ui::ET_MOUSE_RELEASED, word, word, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMouseReleased(release_word); ui::MouseEvent double_click(ui::ET_MOUSE_PRESSED, word, word, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_DOUBLE_CLICK, ui::EF_LEFT_MOUSE_BUTTON); textfield_->OnMousePressed(double_click); textfield_->OnMouseReleased(release_word); EXPECT_EQ(gfx::Range(3, 5), textfield_->GetSelectedRange()); EXPECT_EQ(u"cd", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); textfield_->OnMousePressed(press_word); textfield_->OnMouseReleased(release_word); EXPECT_EQ(gfx::Range(0, 8), textfield_->GetSelectedRange()); EXPECT_EQ(u"ab cd ef", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); // Selecting a range of text without any user interaction should not change // the clipboard content. textfield_->SetSelectedRange(gfx::Range(0, 3)); EXPECT_EQ(u"ab ", textfield_->GetSelectedText()); EXPECT_EQ(u"ab cd ef", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); SetClipboardText(ui::ClipboardBuffer::kSelection, u"other"); textfield_->SelectAll(false); EXPECT_EQ(u"other", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); } // Verify that the selection clipboard is not updated for selections on a // password textfield. TEST_F(TextfieldTest, SelectionClipboard_Password) { InitTextfield(2); textfield_->SetText(u"abcd"); // Select-all should update the selection clipboard for a non-password // textfield. SendKeyEvent(ui::VKEY_A, false, true); EXPECT_EQ(gfx::Range(0, 4), textfield_->GetSelectedRange()); EXPECT_EQ(u"abcd", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kSelection, GetAndResetCopiedToClipboard()); // Move focus to the next textfield. widget_->GetFocusManager()->AdvanceFocus(false); EXPECT_EQ(2, GetFocusedView()->GetID()); Textfield* textfield2 = static_cast<Textfield*>(GetFocusedView()); // Select-all should not modify the selection clipboard for a password // textfield. textfield2->SetText(u"1234"); textfield2->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); SendKeyEvent(ui::VKEY_A, false, true); EXPECT_EQ(gfx::Range(0, 4), textfield2->GetSelectedRange()); EXPECT_EQ(u"abcd", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); // Shift-Left/Right should not modify the selection clipboard for a password // textfield. SendKeyEvent(ui::VKEY_LEFT, true, false); EXPECT_EQ(gfx::Range(0, 3), textfield2->GetSelectedRange()); EXPECT_EQ(u"abcd", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); SendKeyEvent(ui::VKEY_RIGHT, true, false); EXPECT_EQ(gfx::Range(0, 4), textfield2->GetSelectedRange()); EXPECT_EQ(u"abcd", GetClipboardText(ui::ClipboardBuffer::kSelection)); EXPECT_EQ(ui::ClipboardBuffer::kMaxValue, GetAndResetCopiedToClipboard()); } #endif // Long_Press gesture in Textfield can initiate a drag and drop now. TEST_F(TextfieldTest, TestLongPressInitiatesDragDrop) { InitTextfield(); textfield_->SetText(u"Hello string world"); // Ensure the textfield will provide selected text for drag data. textfield_->SetSelectedRange(gfx::Range(6, 12)); const gfx::Point kStringPoint(GetCursorPositionX(9), GetCursorYForTesting()); // Enable touch-drag-drop to make long press effective. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableTouchDragDrop); // Create a long press event in the selected region should start a drag. ui::GestureEvent long_press = CreateTestGestureEvent( kStringPoint.x(), kStringPoint.y(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); EXPECT_TRUE( textfield_->CanStartDragForView(nullptr, kStringPoint, kStringPoint)); } // No touch on desktop Mac. #if !BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, ScrollToAdjustDisplayOffset) { InitTextfield(); // Size the textfield wide enough to hold 10 characters. gfx::test::RenderTextTestApi render_text_test_api(test_api_->GetRenderText()); constexpr int kGlyphWidth = 10; render_text_test_api.SetGlyphWidth(kGlyphWidth); constexpr int kCursorWidth = 1; test_api_->GetRenderText()->SetDisplayRect( gfx::Rect(kGlyphWidth * 10 + kCursorWidth, 20)); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 0); test_api_->SetDisplayOffsetX(0); constexpr gfx::Range kSelectionRange(2, 7); textfield_->SetEditableSelectionRange(kSelectionRange); // Scroll starting at a vertical angle to adjust the display offset. constexpr int kDisplayOffsetXAdjustment = -30; const gfx::Point kScrollStart = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(5), GetCursorYForTesting()}); const gfx::Point kScrollEnd = kScrollStart + gfx::Vector2d(kDisplayOffsetXAdjustment, 60); event_generator_->GestureScrollSequence(kScrollStart, kScrollEnd, /*duration=*/base::Milliseconds(50), /*steps=*/5); // Display offset should have updated without the selection changing. gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, kSelectionRange); EXPECT_FALSE(test_api_->touch_selection_controller()); EXPECT_EQ(test_api_->GetDisplayOffsetX(), kDisplayOffsetXAdjustment); } TEST_F(TextfieldTest, TwoFingerScroll) { InitTextfield(); // Size the textfield wide enough to hold 10 characters. gfx::test::RenderTextTestApi render_text_test_api(test_api_->GetRenderText()); constexpr int kGlyphWidth = 10; render_text_test_api.SetGlyphWidth(kGlyphWidth); constexpr int kCursorWidth = 1; test_api_->GetRenderText()->SetDisplayRect( gfx::Rect(kGlyphWidth * 10 + kCursorWidth, 20)); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 0); test_api_->SetDisplayOffsetX(0); constexpr gfx::Range kSelectionRange(2, 7); textfield_->SetEditableSelectionRange(kSelectionRange); // Scroll with two fingers to adjust the display offset. constexpr int kDisplayOffsetXAdjustment = -30; const gfx::Point kStart1 = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(5), GetCursorYForTesting()}); const gfx::Point kStart2 = kStart1 + gfx::Vector2d(20, 0); const gfx::Point kStart[] = {kStart1, kStart2}; event_generator_->GestureMultiFingerScroll( /*count=*/2, kStart, /*event_separation_time_ms=*/50, /*steps=*/5, /*move_x=*/kDisplayOffsetXAdjustment, /*move_y=*/0); // Display offset should have updated without the selection changing. gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, kSelectionRange); EXPECT_FALSE(test_api_->touch_selection_controller()); EXPECT_EQ(test_api_->GetDisplayOffsetX(), kDisplayOffsetXAdjustment); } TEST_F(TextfieldTest, ScrollToPlaceCursor) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); // Scroll in a horizontal direction to move the cursor. constexpr int kCursorStartPos = 2; constexpr int kCursorEndPos = 15; const gfx::Point kScrollStart = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(kCursorStartPos), GetCursorYForTesting()}); const gfx::Point kScrollEnd = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(kCursorEndPos), GetCursorYForTesting()}); event_generator_->GestureScrollSequence(kScrollStart, kScrollEnd, /*duration=*/base::Milliseconds(50), /*steps=*/5); gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(kCursorEndPos)); } TEST_F(TextfieldTest, ScrollToPlaceCursorShowsTouchHandles) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); // Scroll in a horizontal direction to move the cursor. const gfx::Point kScrollStart = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(2), GetCursorYForTesting()}); const gfx::Point kScrollEnd = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(15), GetCursorYForTesting()}); event_generator_->GestureScrollSequenceWithCallback( kScrollStart, kScrollEnd, /*duration=*/base::Milliseconds(50), /*steps=*/5, base::BindLambdaForTesting( [&](ui::EventType event_type, const gfx::Vector2dF& offset) { if (event_type != ui::ET_GESTURE_SCROLL_UPDATE) { return; } // Touch handles should be hidden during scroll. EXPECT_FALSE(test_api_->touch_selection_controller()); })); // Touch handles should be shown after scroll ends. EXPECT_TRUE(test_api_->touch_selection_controller()); } TEST_F(TextfieldTest, ScrollToPlaceCursorAdjustsDisplayOffset) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); // Size the textfield wide enough to hold 10 characters. gfx::test::RenderTextTestApi render_text_test_api(test_api_->GetRenderText()); constexpr int kGlyphWidth = 10; render_text_test_api.SetGlyphWidth(kGlyphWidth); constexpr int kCursorWidth = 1; test_api_->GetRenderText()->SetDisplayRect( gfx::Rect(kGlyphWidth * 10 + kCursorWidth, 20)); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 0); test_api_->SetDisplayOffsetX(0); // Scroll in a horizontal direction to move the cursor. const gfx::Point kScrollStart = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(2), GetCursorYForTesting()}); const gfx::Point kScrollEnd = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(30), GetCursorYForTesting()}); event_generator_->GestureScrollSequence(kScrollStart, kScrollEnd, /*duration=*/base::Milliseconds(50), /*steps=*/5); // Cursor should have moved and display should be offset so that the cursor is // visible in the textfield. gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(30)); EXPECT_EQ(test_api_->GetDisplayOffsetX(), -200); } TEST_F(TextfieldTest, TwoFingerScrollUpdate) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); // Size the textfield wide enough to hold 10 characters. gfx::test::RenderTextTestApi render_text_test_api(test_api_->GetRenderText()); constexpr int kGlyphWidth = 10; render_text_test_api.SetGlyphWidth(kGlyphWidth); constexpr int kCursorWidth = 1; test_api_->GetRenderText()->SetDisplayRect( gfx::Rect(kGlyphWidth * 10 + kCursorWidth, 20)); textfield_->SetTextWithoutCaretBoundsChangeNotification( u"0123456789_123456789_123456789", 0); test_api_->SetDisplayOffsetX(0); textfield_->SetEditableSelectionRange(gfx::Range(2, 7)); // Perform a scroll which starts with one finger then adds another finger // after a delay. const gfx::Point kStart1 = views::View::ConvertPointToScreen( textfield_, {GetCursorPositionX(8), GetCursorYForTesting()}); const gfx::Point kStart2 = kStart1 + gfx::Vector2d(20, 0); const gfx::Point kStart[] = {kStart1, kStart2}; constexpr gfx::Vector2d kDelta[] = { gfx::Vector2d(-50, 0), gfx::Vector2d(-30, 0), }; constexpr int kDelayAddingFingerMs[] = {0, 40}; constexpr int kDelayReleasingFingerMs[] = {150, 150}; event_generator_->GestureMultiFingerScrollWithDelays( /*count=*/2, kStart, kDelta, kDelayAddingFingerMs, kDelayReleasingFingerMs, /*event_separation_time_ms=*/20, /*steps=*/5); // Since the scroll started with one finger, the cursor should have moved. gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6)); EXPECT_TRUE(test_api_->touch_selection_controller()); // Since a second finger was added, the display should also be slightly // offset. EXPECT_LT(test_api_->GetDisplayOffsetX(), 0); } TEST_F(TextfieldTest, LongPressDragLTR_Forward) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); gfx::Range range; // Long press should select the word at the pressed location. ui::GestureEvent long_press = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 12)); // Dragging right while long pressing should expand the selection forwards. ui::GestureEvent scroll_begin = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, 1, 0)); textfield_->OnGestureEvent(&scroll_begin); EXPECT_EQ(range, gfx::Range(6, 12)); ui::GestureEvent scroll_update = CreateTestGestureEvent( GetCursorPositionX(16), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); textfield_->OnGestureEvent(&scroll_update); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 18)); } TEST_F(TextfieldTest, LongPressDragLTR_Backward) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); gfx::Range range; // Long press should select the word at the pressed location. ui::GestureEvent long_press = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 12)); // Dragging left while long pressing should expand the selection backwards. ui::GestureEvent scroll_begin = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, -1, 0)); textfield_->OnGestureEvent(&scroll_begin); textfield_->GetEditableSelectionRange(&range); // Selection range is reversed since the left endpoint should move while the // right endpoint should stay fixed. EXPECT_EQ(range, gfx::Range(12, 6)); ui::GestureEvent scroll_update = CreateTestGestureEvent( GetCursorPositionX(3), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); textfield_->OnGestureEvent(&scroll_update); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(12, 0)); } TEST_F(TextfieldTest, LongPressDragRTL_Forward) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"مرحبا بالعالم مرحبا"); gfx::Range range; // Long press should select the word at the pressed location. ui::GestureEvent long_press = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 13)); // Dragging left while long pressing should expand the selection forwards. ui::GestureEvent scroll_begin = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, -1, 0)); textfield_->OnGestureEvent(&scroll_begin); EXPECT_EQ(range, gfx::Range(6, 13)); ui::GestureEvent scroll_update = CreateTestGestureEvent( GetCursorPositionX(18), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); textfield_->OnGestureEvent(&scroll_update); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 19)); } TEST_F(TextfieldTest, LongPressDragRTL_Backward) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"مرحبا بالعالم مرحبا"); gfx::Range range; // Long press should select the word at the pressed location. ui::GestureEvent long_press = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(6, 13)); // Dragging right while long pressing should expand the selection backwards. ui::GestureEvent scroll_begin = CreateTestGestureEvent( GetCursorPositionX(9), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, 1, 0)); textfield_->OnGestureEvent(&scroll_begin); textfield_->GetEditableSelectionRange(&range); // Selection range is reversed since the right endpoint should move while the // left endpoint should stay fixed. EXPECT_EQ(range, gfx::Range(13, 6)); ui::GestureEvent scroll_update = CreateTestGestureEvent( GetCursorPositionX(3), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); textfield_->OnGestureEvent(&scroll_update); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(13, 0)); } TEST_F(TextfieldTest, DoubleTapDown) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); gfx::Range range; // Second tap down in a repeated tap sequence should select word but not show // touch selection handles. ui::GestureEventDetails tap_down_details(ui::ET_GESTURE_TAP_DOWN); tap_down_details.set_tap_down_count(2); ui::GestureEvent tap_down = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), tap_down_details); textfield_->OnGestureEvent(&tap_down); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 5)); EXPECT_FALSE(test_api_->touch_selection_controller()); // After tap, word should still be selected and touch selection handles should // appear. ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); tap_details.set_tap_count(2); ui::GestureEvent tap = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), tap_details); textfield_->OnGestureEvent(&tap); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 5)); EXPECT_TRUE(test_api_->touch_selection_controller()); } TEST_F(TextfieldTest, TripleTapDown) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); gfx::Range range; // Third tap down in a repeated tap sequence should select all text. ui::GestureEventDetails tap_down_details(ui::ET_GESTURE_TAP_DOWN); tap_down_details.set_tap_down_count(3); ui::GestureEvent tap_down = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), tap_down_details); textfield_->OnGestureEvent(&tap_down); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 18)); EXPECT_FALSE(test_api_->touch_selection_controller()); // After tap, text should still be selected and touch selection handles should // appear. ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); tap_details.set_tap_count(3); ui::GestureEvent tap = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), tap_details); textfield_->OnGestureEvent(&tap); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 18)); EXPECT_TRUE(test_api_->touch_selection_controller()); } // TODO(b/271058426): Rewrite these gesture tests using // ui::test::EventGenerator. TEST_F(TextfieldTest, DoubleTapDrag) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"Hello string world"); gfx::Range range; // Second tap down in a repeated tap sequence should select word. ui::GestureEventDetails tap_down_details(ui::ET_GESTURE_TAP_DOWN); tap_down_details.set_tap_down_count(2); ui::GestureEvent tap_down = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), tap_down_details); textfield_->OnGestureEvent(&tap_down); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 5)); // Dragging should expand the selection. ui::GestureEvent scroll_begin = CreateTestGestureEvent( GetCursorPositionX(2), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, 1, 0)); textfield_->OnGestureEvent(&scroll_begin); EXPECT_EQ(range, gfx::Range(0, 5)); ui::GestureEvent scroll_update = CreateTestGestureEvent( GetCursorPositionX(10), GetCursorYForTesting(), ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); textfield_->OnGestureEvent(&scroll_update); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 12)); } #endif TEST_F(TextfieldTest, GetTextfieldBaseline_FontFallbackTest) { InitTextfield(); textfield_->SetText(u"abc"); const int old_baseline = textfield_->GetBaseline(); // Set text which may fall back to a font which has taller baseline than // the default font. textfield_->SetText(u"๑"); const int new_baseline = textfield_->GetBaseline(); // Regardless of the text, the baseline must be the same. EXPECT_EQ(new_baseline, old_baseline); } // Tests that a textfield view can be destroyed from OnKeyEvent() on its // controller and it does not crash. TEST_F(TextfieldTest, DestroyingTextfieldFromOnKeyEvent) { InitTextfield(); // The controller assumes ownership of the textfield. TextfieldDestroyerController controller(textfield_); EXPECT_TRUE(controller.target()); // Send a key to trigger OnKeyEvent(). SendKeyEvent(ui::VKEY_RETURN); EXPECT_FALSE(controller.target()); } TEST_F(TextfieldTest, CursorBlinkRestartsOnInsertOrReplace) { InitTextfield(); textfield_->SetText(u"abc"); EXPECT_TRUE(test_api_->IsCursorBlinkTimerRunning()); textfield_->SetSelectedRange(gfx::Range(1, 2)); EXPECT_FALSE(test_api_->IsCursorBlinkTimerRunning()); textfield_->InsertOrReplaceText(u"foo"); EXPECT_TRUE(test_api_->IsCursorBlinkTimerRunning()); } // Verifies setting the accessible name will call NotifyAccessibilityEvent. TEST_F(TextfieldTest, SetAccessibleNameNotifiesAccessibilityEvent) { InitTextfield(); std::u16string test_tooltip_text = u"Test Accessible Name"; test::AXEventCounter counter(views::AXEventManager::Get()); EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kTextChanged)); textfield_->SetAccessibleName(test_tooltip_text); EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kTextChanged)); EXPECT_EQ(test_tooltip_text, textfield_->GetAccessibleName()); ui::AXNodeData data; textfield_->GetAccessibleNodeData(&data); const std::string& name = data.GetStringAttribute(ax::mojom::StringAttribute::kName); EXPECT_EQ(test_tooltip_text, base::ASCIIToUTF16(name)); // `NameFrom::kAttribute` is appropriate when the name is explicitly set to // a developer-provided string (rather than a label, tooltip, or placeholder // for which there are other `NameFrom` values). `NameFrom::kContents` is // typically not an appropriate value. EXPECT_EQ(data.GetNameFrom(), ax::mojom::NameFrom::kAttribute); } TEST_F(TextfieldTest, AccessibleNameFromLabel) { InitTextfield(); const std::u16string label_text = u"Some label"; View label; label.SetAccessibleName(label_text); textfield_->SetAccessibleName(&label); // Use `ViewAccessibility::GetAccessibleNodeData` so that we can get the // label's accessible id to compare with the textfield's labelled-by id. ui::AXNodeData label_data; label.GetViewAccessibility().GetAccessibleNodeData(&label_data); ui::AXNodeData textfield_data; textfield_->GetAccessibleNodeData(&textfield_data); EXPECT_EQ( textfield_data.GetString16Attribute(ax::mojom::StringAttribute::kName), label_text); EXPECT_EQ(textfield_->GetAccessibleName(), label_text); EXPECT_EQ(textfield_data.GetNameFrom(), ax::mojom::NameFrom::kRelatedElement); EXPECT_EQ(textfield_data.GetIntListAttribute( ax::mojom::IntListAttribute::kLabelledbyIds)[0], label_data.id); } #if BUILDFLAG(IS_CHROMEOS_ASH) // Check that when accessibility virtual keyboard is enabled, windows are // shifted up when focused and restored when focus is lost. TEST_F(TextfieldTest, VirtualKeyboardFocusEnsureCaretNotInRect) { InitTextfield(); aura::Window* root_window = GetRootWindow(widget_.get()); int keyboard_height = 200; gfx::Rect root_bounds = root_window->bounds(); gfx::Rect orig_widget_bounds = gfx::Rect(0, 300, 400, 200); gfx::Rect shifted_widget_bounds = gfx::Rect(0, 200, 400, 200); gfx::Rect keyboard_view_bounds = gfx::Rect(0, root_bounds.height() - keyboard_height, root_bounds.width(), keyboard_height); // Focus the window. widget_->SetBounds(orig_widget_bounds); input_method_->SetFocusedTextInputClient(textfield_); EXPECT_EQ(widget_->GetNativeView()->bounds(), orig_widget_bounds); // Simulate virtual keyboard. input_method_->SetVirtualKeyboardBounds(keyboard_view_bounds); // Window should be shifted. EXPECT_EQ(widget_->GetNativeView()->bounds(), shifted_widget_bounds); // Detach the textfield from the IME input_method_->DetachTextInputClient(textfield_); wm::RestoreWindowBoundsOnClientFocusLost( widget_->GetNativeView()->GetToplevelWindow()); // Window should be restored. EXPECT_EQ(widget_->GetNativeView()->bounds(), orig_widget_bounds); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) class TextfieldTouchSelectionTest : public TextfieldTest { protected: // Simulates a complete tap. void Tap(const gfx::Point& point) { ui::GestureEvent begin = CreateTestGestureEvent( point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_BEGIN)); textfield_->OnGestureEvent(&begin); ui::GestureEvent tap_down = CreateTestGestureEvent( point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); textfield_->OnGestureEvent(&tap_down); ui::GestureEvent show_press = CreateTestGestureEvent( point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_SHOW_PRESS)); textfield_->OnGestureEvent(&show_press); ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); tap_details.set_tap_count(1); ui::GestureEvent tap = CreateTestGestureEvent(point.x(), point.y(), tap_details); textfield_->OnGestureEvent(&tap); ui::GestureEvent end = CreateTestGestureEvent( point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_END)); textfield_->OnGestureEvent(&end); } }; // Touch selection and dragging currently only works for chromeos. #if BUILDFLAG(IS_CHROMEOS_ASH) TEST_F(TextfieldTouchSelectionTest, TouchSelectionAndDraggingTest) { InitTextfield(); textfield_->SetText(u"hello world"); EXPECT_FALSE(test_api_->touch_selection_controller()); const int x = GetCursorPositionX(2); // Tapping on the textfield should turn on the TouchSelectionController. ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); tap_details.set_tap_count(1); ui::GestureEvent tap = CreateTestGestureEvent(x, 0, tap_details); textfield_->OnGestureEvent(&tap); EXPECT_TRUE(test_api_->touch_selection_controller()); // Un-focusing the textfield should reset the TouchSelectionController textfield_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(test_api_->touch_selection_controller()); textfield_->RequestFocus(); // With touch editing enabled, long press should not show context menu. // Instead, select word and invoke TouchSelectionController. ui::GestureEvent long_press_1 = CreateTestGestureEvent( x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press_1); EXPECT_EQ(u"hello", textfield_->GetSelectedText()); EXPECT_TRUE(test_api_->touch_selection_controller()); EXPECT_TRUE(long_press_1.handled()); // With touch drag drop enabled, long pressing in the selected region should // start a drag and remove TouchSelectionController. ASSERT_TRUE(switches::IsTouchDragDropEnabled()); ui::GestureEvent long_press_2 = CreateTestGestureEvent( x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press_2); EXPECT_EQ(u"hello", textfield_->GetSelectedText()); EXPECT_FALSE(test_api_->touch_selection_controller()); EXPECT_FALSE(long_press_2.handled()); // After disabling touch drag drop, long pressing again in the selection // region should not do anything. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisableTouchDragDrop); ASSERT_FALSE(switches::IsTouchDragDropEnabled()); ui::GestureEvent long_press_3 = CreateTestGestureEvent( x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press_3); EXPECT_EQ(u"hello", textfield_->GetSelectedText()); EXPECT_FALSE(test_api_->touch_selection_controller()); EXPECT_FALSE(long_press_3.handled()); } #endif TEST_F(TextfieldTouchSelectionTest, TouchSelectionInUnfocusableTextfield) { InitTextfield(); textfield_->SetText(u"hello world"); gfx::Point touch_point(GetCursorPositionX(2), 0); // Disable textfield and tap on it. Touch text selection should not get // activated. textfield_->SetEnabled(false); Tap(touch_point); EXPECT_FALSE(test_api_->touch_selection_controller()); textfield_->SetEnabled(true); // Make textfield unfocusable and tap on it. Touch text selection should not // get activated. textfield_->SetFocusBehavior(View::FocusBehavior::NEVER); Tap(touch_point); EXPECT_FALSE(textfield_->HasFocus()); EXPECT_FALSE(test_api_->touch_selection_controller()); textfield_->SetFocusBehavior(View::FocusBehavior::ALWAYS); } // No touch on desktop Mac. Tracked in http://crbug.com/445520. #if BUILDFLAG(IS_MAC) #define MAYBE_TapOnSelection DISABLED_TapOnSelection #else #define MAYBE_TapOnSelection TapOnSelection #endif TEST_F(TextfieldTouchSelectionTest, MAYBE_TapOnSelection) { InitTextfield(); textfield_->SetText(u"hello world"); gfx::Range sel_range(2, 7); gfx::Range tap_range(5, 5); gfx::Rect tap_rect = GetCursorBounds(gfx::SelectionModel(tap_range, gfx::CURSOR_FORWARD)); gfx::Point tap_point = tap_rect.CenterPoint(); // Select range |sel_range| and check if touch selection handles are not // present and correct range is selected. textfield_->SetEditableSelectionRange(sel_range); gfx::Range range; textfield_->GetEditableSelectionRange(&range); EXPECT_FALSE(test_api_->touch_selection_controller()); EXPECT_EQ(sel_range, range); // Tap on selection and check if touch selectoin handles are shown, but // selection range is not modified. Tap(tap_point); textfield_->GetEditableSelectionRange(&range); EXPECT_TRUE(test_api_->touch_selection_controller()); EXPECT_EQ(sel_range, range); // Tap again on selection and check if touch selection handles are still // present and selection is changed to a cursor at tap location. Tap(tap_point); textfield_->GetEditableSelectionRange(&range); EXPECT_TRUE(test_api_->touch_selection_controller()); EXPECT_EQ(tap_range, range); } TEST_F(TextfieldTest, MoveCaret) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->MoveCaret(gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(3)); textfield_->MoveCaret(gfx::Point(GetCursorPositionX(0), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0)); textfield_->MoveCaret(gfx::Point(GetCursorPositionX(11), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(11)); } TEST_F(TextfieldTest, MoveRangeSelectionExtent) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(2), cursor_y), gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(5), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 5)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(0), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 0)); } TEST_F(TextfieldTest, MoveRangeSelectionExtentToTextEnd) { InitTextfield(); textfield_->SetText(u"hello world a"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(2), cursor_y), gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(13), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 13)); } TEST_F(TextfieldTest, MoveRangeSelectionExtentByCharacter) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{}, /*disabled_features=*/{::features::kTouchTextEditingRedesign}); InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(2), cursor_y), gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(4), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 4)); EXPECT_EQ(textfield_->GetSelectedText(), u"ll"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(8), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 8)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo wo"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(1), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 1)); EXPECT_EQ(textfield_->GetSelectedText(), u"e"); } TEST_F(TextfieldTest, MoveRangeSelectionExtentExpandByWord) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(2), cursor_y), gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(9), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 11)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo world"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(10), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 11)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo world"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(5), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 5)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(7), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 6)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo "); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(9), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 11)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo world"); } TEST_F(TextfieldTest, MoveRangeSelectionExtentShrinkByCharacter) { base::test::ScopedFeatureList feature_list; feature_list.InitWithFeatures( /*enabled_features=*/{::features::kTouchTextEditingRedesign}, /*disabled_features=*/{}); InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(2), cursor_y), gfx::Point(GetCursorPositionX(3), cursor_y)); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(11), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 11)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo world"); textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(9), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 9)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo wor"); // Check that selection can be adjusted by character within a word after the // selection has shrunk. textfield_->MoveRangeSelectionExtent( gfx::Point(GetCursorPositionX(10), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(2, 10)); EXPECT_EQ(textfield_->GetSelectedText(), u"llo worl"); } TEST_F(TextfieldTest, SelectBetweenCoordinates) { InitTextfield(); textfield_->SetText(u"hello world"); const int cursor_y = GetCursorYForTesting(); gfx::Range range; textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(1), cursor_y), gfx::Point(GetCursorPositionX(2), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(1, 2)); textfield_->SelectBetweenCoordinates( gfx::Point(GetCursorPositionX(0), cursor_y), gfx::Point(GetCursorPositionX(11), cursor_y)); textfield_->GetEditableSelectionRange(&range); EXPECT_EQ(range, gfx::Range(0, 11)); } TEST_F(TextfieldTest, AccessiblePasswordTest) { InitTextfield(); textfield_->SetText(u"password"); ui::AXNodeData node_data_regular; textfield_->GetAccessibleNodeData(&node_data_regular); EXPECT_EQ(ax::mojom::Role::kTextField, node_data_regular.role); EXPECT_EQ(u"password", node_data_regular.GetString16Attribute( ax::mojom::StringAttribute::kValue)); EXPECT_FALSE(node_data_regular.HasState(ax::mojom::State::kProtected)); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); ui::AXNodeData node_data_protected; textfield_->GetAccessibleNodeData(&node_data_protected); EXPECT_EQ(ax::mojom::Role::kTextField, node_data_protected.role); EXPECT_EQ(u"••••••••", node_data_protected.GetString16Attribute( ax::mojom::StringAttribute::kValue)); EXPECT_TRUE(node_data_protected.HasState(ax::mojom::State::kProtected)); } TEST_F(TextfieldTest, AccessibleRole) { InitTextfield(); ui::AXNodeData data; textfield_->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kTextField); EXPECT_EQ(textfield_->GetAccessibleRole(), ax::mojom::Role::kTextField); textfield_->SetAccessibleRole(ax::mojom::Role::kSearchBox); data = ui::AXNodeData(); textfield_->GetAccessibleNodeData(&data); EXPECT_EQ(data.role, ax::mojom::Role::kSearchBox); EXPECT_EQ(textfield_->GetAccessibleRole(), ax::mojom::Role::kSearchBox); } // Verify that cursor visibility is controlled by SetCursorEnabled. TEST_F(TextfieldTest, CursorVisibility) { InitTextfield(); textfield_->SetCursorEnabled(false); EXPECT_FALSE(test_api_->IsCursorVisible()); textfield_->SetCursorEnabled(true); EXPECT_TRUE(test_api_->IsCursorVisible()); } // Tests that Textfield::FitToLocalBounds() sets the RenderText's display rect // to the view's bounds, taking the border into account. TEST_F(TextfieldTest, FitToLocalBounds) { const int kDisplayRectWidth = 100; const int kBorderWidth = 5; InitTextfield(); textfield_->SetBounds(0, 0, kDisplayRectWidth, 100); textfield_->SetBorder(views::CreateEmptyBorder(kBorderWidth)); test_api_->GetRenderText()->SetDisplayRect(gfx::Rect(20, 20)); ASSERT_EQ(20, test_api_->GetRenderText()->display_rect().width()); textfield_->FitToLocalBounds(); EXPECT_EQ(kDisplayRectWidth - 2 * kBorderWidth, test_api_->GetRenderText()->display_rect().width()); } // Verify that cursor view height does not exceed the textfield height. TEST_F(TextfieldTest, CursorViewHeight) { InitTextfield(); textfield_->SetBounds(0, 0, 100, 100); textfield_->SetCursorEnabled(true); SendKeyEvent('a'); EXPECT_TRUE(test_api_->IsCursorVisible()); EXPECT_GT(textfield_->GetVisibleBounds().height(), test_api_->GetCursorViewRect().height()); EXPECT_LE(test_api_->GetCursorViewRect().height(), GetCursorBounds().height()); // set the cursor height to be higher than the textfield height, verify that // UpdateCursorViewPosition update cursor view height currectly. gfx::Rect cursor_bound(test_api_->GetCursorViewRect()); cursor_bound.set_height(150); test_api_->SetCursorViewRect(cursor_bound); SendKeyEvent('b'); EXPECT_GT(textfield_->GetVisibleBounds().height(), test_api_->GetCursorViewRect().height()); EXPECT_LE(test_api_->GetCursorViewRect().height(), GetCursorBounds().height()); } // Verify that cursor view height is independent of its parent view height. TEST_F(TextfieldTest, CursorViewHeightAtDiffDSF) { InitTextfield(); textfield_->SetBounds(0, 0, 100, 100); textfield_->SetCursorEnabled(true); SendKeyEvent('a'); EXPECT_TRUE(test_api_->IsCursorVisible()); int height = test_api_->GetCursorViewRect().height(); // update the size of its parent view size and verify that the height of the // cursor view stays the same. View* parent = textfield_->parent(); parent->SetBounds(0, 0, 50, height - 2); SendKeyEvent('b'); EXPECT_EQ(height, test_api_->GetCursorViewRect().height()); } // Check if the text cursor is always at the end of the textfield after the // text overflows from the textfield. If the textfield size changes, check if // the text cursor's location is updated accordingly. TEST_F(TextfieldTest, TextfieldBoundsChangeTest) { InitTextfield(); gfx::Size new_size = gfx::Size(30, 100); textfield_->SetSize(new_size); // Insert chars in |textfield_| to make it overflow. SendKeyEvent('a'); SendKeyEvent('a'); SendKeyEvent('a'); SendKeyEvent('a'); SendKeyEvent('a'); SendKeyEvent('a'); SendKeyEvent('a'); // Check if the cursor continues pointing to the end of the textfield. int prev_x = GetCursorBounds().x(); SendKeyEvent('a'); EXPECT_EQ(prev_x, GetCursorBounds().x()); EXPECT_TRUE(test_api_->IsCursorVisible()); // Increase the textfield size and check if the cursor moves to the new end. textfield_->SetSize(gfx::Size(40, 100)); EXPECT_LT(prev_x, GetCursorBounds().x()); prev_x = GetCursorBounds().x(); // Decrease the textfield size and check if the cursor moves to the new end. textfield_->SetSize(gfx::Size(30, 100)); EXPECT_GT(prev_x, GetCursorBounds().x()); } // Verify that after creating a new Textfield, the Textfield doesn't // automatically receive focus and the text cursor is not visible. TEST_F(TextfieldTest, TextfieldInitialization) { std::unique_ptr<Widget> widget = CreateTestWidget(); View* container = widget->SetContentsView(std::make_unique<View>()); TestTextfield* new_textfield = container->AddChildView(std::make_unique<TestTextfield>()); new_textfield->set_controller(this); new_textfield->SetBoundsRect(gfx::Rect(100, 100, 100, 100)); new_textfield->SetID(1); test_api_ = std::make_unique<TextfieldTestApi>(new_textfield); widget->Show(); EXPECT_FALSE(new_textfield->HasFocus()); EXPECT_FALSE(test_api_->IsCursorVisible()); new_textfield->RequestFocus(); EXPECT_TRUE(test_api_->IsCursorVisible()); widget->Close(); } // Verify that if a textfield gains focus during key dispatch that an edit // command only results when the event is not consumed. TEST_F(TextfieldTest, SwitchFocusInKeyDown) { InitTextfield(); TextfieldFocuser* focuser = new TextfieldFocuser(textfield_); widget_->GetContentsView()->AddChildView(focuser); focuser->RequestFocus(); EXPECT_EQ(focuser, GetFocusedView()); SendKeyPress(ui::VKEY_SPACE, 0); EXPECT_EQ(textfield_, GetFocusedView()); EXPECT_EQ(std::u16string(), textfield_->GetText()); focuser->set_consume(false); focuser->RequestFocus(); EXPECT_EQ(focuser, GetFocusedView()); SendKeyPress(ui::VKEY_SPACE, 0); EXPECT_EQ(textfield_, GetFocusedView()); EXPECT_EQ(u" ", textfield_->GetText()); } TEST_F(TextfieldTest, SendingDeletePreservesShiftFlag) { InitTextfield(); SendKeyPress(ui::VKEY_DELETE, 0); EXPECT_EQ(0, textfield_->event_flags()); textfield_->clear(); // Ensure the shift modifier propagates for keys that may be subject to native // key mappings. E.g., on Mac, Delete and Shift+Delete are both // deleteForward:, but the shift modifier should propagate. SendKeyPress(ui::VKEY_DELETE, ui::EF_SHIFT_DOWN); EXPECT_EQ(ui::EF_SHIFT_DOWN, textfield_->event_flags()); } TEST_F(TextfieldTest, EmojiItem_EmptyField) { InitTextfield(); EXPECT_TRUE(textfield_->context_menu_controller()); // A normal empty field may show the Emoji option (if supported). ui::MenuModel* context_menu = GetContextMenuModel(); EXPECT_TRUE(context_menu); EXPECT_GT(context_menu->GetItemCount(), 0u); // Not all OS/versions support the emoji menu. EXPECT_EQ(ui::IsEmojiPanelSupported(), context_menu->GetLabelAt(0) == l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_EMOJI)); } TEST_F(TextfieldTest, EmojiItem_ReadonlyField) { InitTextfield(); EXPECT_TRUE(textfield_->context_menu_controller()); textfield_->SetReadOnly(true); // In no case is the emoji option showing on a read-only field. ui::MenuModel* context_menu = GetContextMenuModel(); EXPECT_TRUE(context_menu); EXPECT_GT(context_menu->GetItemCount(), 0u); EXPECT_NE(context_menu->GetLabelAt(0), l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_EMOJI)); } TEST_F(TextfieldTest, EmojiItem_FieldWithText) { InitTextfield(); EXPECT_TRUE(textfield_->context_menu_controller()); #if BUILDFLAG(IS_MAC) // On Mac, when there is text, the "Look up" item (+ separator) takes the top // position, and emoji comes after. constexpr int kExpectedEmojiIndex = 2; #else constexpr int kExpectedEmojiIndex = 0; #endif // A field with text may still show the Emoji option (if supported). textfield_->SetText(u"some text"); textfield_->SelectAll(false); ui::MenuModel* context_menu = GetContextMenuModel(); EXPECT_TRUE(context_menu); EXPECT_GT(context_menu->GetItemCount(), 0u); // Not all OS/versions support the emoji menu. EXPECT_EQ(ui::IsEmojiPanelSupported(), context_menu->GetLabelAt(kExpectedEmojiIndex) == l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_EMOJI)); } #if BUILDFLAG(IS_MAC) // Tests to see if the BiDi submenu items are updated correctly when the // textfield's text direction is changed. TEST_F(TextfieldTest, TextServicesContextMenuTextDirectionTest) { InitTextfield(); EXPECT_TRUE(textfield_->context_menu_controller()); EXPECT_TRUE(GetContextMenuModel()); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::LEFT_TO_RIGHT); test_api_->UpdateContextMenu(); EXPECT_FALSE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionDefault)); EXPECT_TRUE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionLtr)); EXPECT_FALSE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionRtl)); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::RIGHT_TO_LEFT); test_api_->UpdateContextMenu(); EXPECT_FALSE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionDefault)); EXPECT_FALSE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionLtr)); EXPECT_TRUE(textfield_->IsCommandIdChecked( ui::TextServicesContextMenu::kWritingDirectionRtl)); } // Tests to see if the look up item is hidden for password fields. TEST_F(TextfieldTest, LookUpPassword) { InitTextfield(); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); const std::u16string kText = u"Willie Wagtail"; textfield_->SetText(kText); textfield_->SelectAll(false); ui::MenuModel* context_menu = GetContextMenuModel(); EXPECT_TRUE(context_menu); EXPECT_GT(context_menu->GetItemCount(), 0u); EXPECT_NE(context_menu->GetCommandIdAt(0), IDS_CONTENT_CONTEXT_LOOK_UP); EXPECT_NE(context_menu->GetLabelAt(0), l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_LOOK_UP, kText)); } TEST_F(TextfieldTest, SecurePasswordInput) { InitTextfield(); ASSERT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled()); // Shouldn't enable secure input if it's not a password textfield. textfield_->OnFocus(); EXPECT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled()); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); // Single matched calls immediately update IsPasswordInputEnabled(). textfield_->OnFocus(); EXPECT_TRUE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled()); textfield_->OnBlur(); EXPECT_FALSE(ui::ScopedPasswordInputEnabler::IsPasswordInputEnabled()); } #endif // BUILDFLAG(IS_MAC) TEST_F(TextfieldTest, AccessibilitySelectionEvents) { const std::u16string kText = u"abcdef"; InitTextfield(); textfield_->SetText(kText); EXPECT_TRUE(textfield_->HasFocus()); int previous_selection_fired_count = textfield_->GetAccessibilitySelectionFiredCount(); textfield_->SelectAll(false); EXPECT_LT(previous_selection_fired_count, textfield_->GetAccessibilitySelectionFiredCount()); previous_selection_fired_count = textfield_->GetAccessibilitySelectionFiredCount(); // No selection event when textfield blurred, even though text is // deselected. widget_->GetFocusManager()->ClearFocus(); EXPECT_FALSE(textfield_->HasFocus()); textfield_->ClearSelection(); EXPECT_FALSE(textfield_->HasSelection()); // Has not changed. EXPECT_EQ(previous_selection_fired_count, textfield_->GetAccessibilitySelectionFiredCount()); } TEST_F(TextfieldTest, FocusReasonMouse) { InitTextfield(); widget_->GetFocusManager()->ClearFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_NONE, textfield_->GetFocusReason()); const auto& bounds = textfield_->bounds(); MouseClick(bounds, 10); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_MOUSE, textfield_->GetFocusReason()); } TEST_F(TextfieldTest, FocusReasonTouchTap) { InitTextfield(); widget_->GetFocusManager()->ClearFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_NONE, textfield_->GetFocusReason()); TapAtCursor(ui::EventPointerType::kTouch); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_TOUCH, textfield_->GetFocusReason()); } TEST_F(TextfieldTest, FocusReasonPenTap) { InitTextfield(); widget_->GetFocusManager()->ClearFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_NONE, textfield_->GetFocusReason()); TapAtCursor(ui::EventPointerType::kPen); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_PEN, textfield_->GetFocusReason()); } TEST_F(TextfieldTest, FocusReasonMultipleEvents) { InitTextfield(); widget_->GetFocusManager()->ClearFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_NONE, textfield_->GetFocusReason()); // Pen tap, followed by a touch tap. TapAtCursor(ui::EventPointerType::kPen); TapAtCursor(ui::EventPointerType::kTouch); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_PEN, textfield_->GetFocusReason()); } TEST_F(TextfieldTest, FocusReasonFocusBlurFocus) { InitTextfield(); widget_->GetFocusManager()->ClearFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_NONE, textfield_->GetFocusReason()); // Pen tap, blur, then programmatic focus. TapAtCursor(ui::EventPointerType::kPen); widget_->GetFocusManager()->ClearFocus(); textfield_->RequestFocus(); EXPECT_EQ(ui::TextInputClient::FOCUS_REASON_OTHER, textfield_->GetFocusReason()); } TEST_F(TextfieldTest, KeyboardObserverForPenInput) { InitTextfield(); TapAtCursor(ui::EventPointerType::kPen); EXPECT_EQ(1, input_method_->count_show_virtual_keyboard()); } TEST_F(TextfieldTest, ChangeTextDirectionAndLayoutAlignmentTest) { InitTextfield(); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::RIGHT_TO_LEFT); EXPECT_EQ(textfield_->GetTextDirection(), base::i18n::TextDirection::RIGHT_TO_LEFT); EXPECT_EQ(textfield_->GetHorizontalAlignment(), gfx::HorizontalAlignment::ALIGN_RIGHT); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::RIGHT_TO_LEFT); const std::u16string& text = test_api_->GetRenderText()->GetDisplayText(); base::i18n::TextDirection text_direction = base::i18n::GetFirstStrongCharacterDirection(text); EXPECT_EQ(textfield_->GetTextDirection(), text_direction); EXPECT_EQ(textfield_->GetHorizontalAlignment(), gfx::HorizontalAlignment::ALIGN_RIGHT); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::LEFT_TO_RIGHT); EXPECT_EQ(textfield_->GetTextDirection(), base::i18n::TextDirection::LEFT_TO_RIGHT); EXPECT_EQ(textfield_->GetHorizontalAlignment(), gfx::HorizontalAlignment::ALIGN_LEFT); // If the text is center-aligned, only the text direction should change. textfield_->SetHorizontalAlignment(gfx::ALIGN_CENTER); textfield_->ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection::RIGHT_TO_LEFT); EXPECT_EQ(textfield_->GetTextDirection(), base::i18n::TextDirection::RIGHT_TO_LEFT); EXPECT_EQ(textfield_->GetHorizontalAlignment(), gfx::HorizontalAlignment::ALIGN_CENTER); // If the text is aligned to the text direction, its alignment should change // iff the text direction changes. We test both scenarios. auto dir = base::i18n::TextDirection::RIGHT_TO_LEFT; auto opposite_dir = base::i18n::TextDirection::LEFT_TO_RIGHT; EXPECT_EQ(textfield_->GetTextDirection(), dir); textfield_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); textfield_->ChangeTextDirectionAndLayoutAlignment(opposite_dir); EXPECT_EQ(textfield_->GetTextDirection(), opposite_dir); EXPECT_NE(textfield_->GetHorizontalAlignment(), gfx::ALIGN_TO_HEAD); dir = base::i18n::TextDirection::LEFT_TO_RIGHT; EXPECT_EQ(textfield_->GetTextDirection(), dir); textfield_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); textfield_->ChangeTextDirectionAndLayoutAlignment(dir); EXPECT_EQ(textfield_->GetTextDirection(), dir); EXPECT_EQ(textfield_->GetHorizontalAlignment(), gfx::ALIGN_TO_HEAD); } TEST_F(TextfieldTest, TextChangedCallbackTest) { InitTextfield(); bool text_changed = false; auto subscription = textfield_->AddTextChangedCallback(base::BindRepeating( [](bool* text_changed) { *text_changed = true; }, &text_changed)); textfield_->SetText(u"abc"); EXPECT_TRUE(text_changed); text_changed = false; textfield_->AppendText(u"def"); EXPECT_TRUE(text_changed); // Undo should still cause callback. text_changed = false; SendKeyEvent(ui::VKEY_Z, false, true); EXPECT_TRUE(text_changed); text_changed = false; SendKeyEvent(ui::VKEY_BACK); EXPECT_TRUE(text_changed); } // Tests that invalid characters like non-displayable characters are filtered // out when inserted into the text field. TEST_F(TextfieldTest, InsertInvalidCharsTest) { InitTextfield(); textfield_->InsertText( u"\babc\ndef\t", ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText); EXPECT_EQ(textfield_->GetText(), u"abcdef"); } TEST_F(TextfieldTest, ScrollCommands) { InitTextfield(); // Scroll commands are only available on Mac. #if BUILDFLAG(IS_MAC) textfield_->SetText(u"12 34567 89"); textfield_->SetEditableSelectionRange(gfx::Range(6)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_PAGE_UP)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_PAGE_DOWN)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT)); EXPECT_TRUE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT)); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::SCROLL_PAGE_UP); EXPECT_EQ(textfield_->GetCursorPosition(), 0u); test_api_->ExecuteTextEditCommand(ui::TextEditCommand::SCROLL_PAGE_DOWN); EXPECT_EQ(textfield_->GetCursorPosition(), 11u); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT); EXPECT_EQ(textfield_->GetCursorPosition(), 0u); test_api_->ExecuteTextEditCommand( ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT); EXPECT_EQ(textfield_->GetCursorPosition(), 11u); #else EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_PAGE_UP)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_PAGE_DOWN)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_TO_BEGINNING_OF_DOCUMENT)); EXPECT_FALSE(textfield_->IsTextEditCommandEnabled( ui::TextEditCommand::SCROLL_TO_END_OF_DOCUMENT)); #endif } } // namespace views::test
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_unittest.cc
C++
unknown
188,638
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_UNITTEST_H_ #define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_UNITTEST_H_ #include "ui/views/controls/textfield/textfield.h" #include <memory> #include <string> #include <utility> #include "base/memory/raw_ptr.h" #include "ui/base/clipboard/clipboard.h" #include "ui/events/event_constants.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/test/views_test_base.h" namespace ui::test { class EventGenerator; } // namespace ui::test namespace views { class TextfieldTestApi; namespace test { class MockInputMethod; class TestTextfield; class TextfieldTest : public ViewsTestBase, public TextfieldController { public: TextfieldTest(); ~TextfieldTest() override; // ViewsTestBase: void SetUp() override; void TearDown() override; ui::ClipboardBuffer GetAndResetCopiedToClipboard(); std::u16string GetClipboardText(ui::ClipboardBuffer type); void SetClipboardText(ui::ClipboardBuffer type, const std::u16string& text); // TextfieldController: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; void OnBeforeUserAction(Textfield* sender) override; void OnAfterUserAction(Textfield* sender) override; void OnAfterCutOrCopy(ui::ClipboardBuffer clipboard_type) override; void InitTextfield(int count = 1); ui::MenuModel* GetContextMenuModel(); bool TestingNativeMac() const; bool TestingNativeCrOs() const; template <typename T> T* PrepareTextfields(int count, std::unique_ptr<T> textfield_owned, gfx::Rect bounds) { widget_ = CreateTestWidget(); widget_->SetBounds(bounds); View* container = widget_->SetContentsView(std::make_unique<View>()); T* textfield = container->AddChildView(std::move(textfield_owned)); PrepareTextfieldsInternal(count, textfield, container, bounds); return textfield; } protected: void PrepareTextfieldsInternal(int count, Textfield* textfield, View* view, gfx::Rect bounds); void SendKeyPress(ui::KeyboardCode key_code, int flags); void SendKeyEvent(ui::KeyboardCode key_code, bool alt, bool shift, bool control_or_command, bool caps_lock); void SendKeyEvent(ui::KeyboardCode key_code, bool shift, bool control_or_command); void SendKeyEvent(ui::KeyboardCode key_code); void SendKeyEvent(char16_t ch); void SendKeyEvent(char16_t ch, int flags); void SendKeyEvent(char16_t ch, int flags, bool from_vk); void DispatchMockInputMethodKeyEvent(); // Sends a platform-specific move (and select) to the logical start of line. // Eg. this should move (and select) to the right end of line for RTL text. virtual void SendHomeEvent(bool shift); // Sends a platform-specific move (and select) to the logical end of line. virtual void SendEndEvent(bool shift); // Sends {delete, move, select} word {forward, backward}. void SendWordEvent(ui::KeyboardCode key, bool shift); // Sends Shift+Delete if supported, otherwise Cmd+X again. void SendAlternateCut(); // Sends Ctrl+Insert if supported, otherwise Cmd+C again. void SendAlternateCopy(); // Sends Shift+Insert if supported, otherwise Cmd+V again. void SendAlternatePaste(); View* GetFocusedView(); int GetCursorPositionX(int cursor_pos); int GetCursorYForTesting(); // Get the current cursor bounds. gfx::Rect GetCursorBounds(); // Get the cursor bounds of |sel|. gfx::Rect GetCursorBounds(const gfx::SelectionModel& sel); gfx::Rect GetDisplayRect(); gfx::Rect GetCursorViewRect(); // Mouse click on the point whose x-axis is |bound|'s x plus |x_offset| and // y-axis is in the middle of |bound|'s vertical range. void MouseClick(const gfx::Rect bound, int x_offset); // This is to avoid double/triple click. void NonClientMouseClick(); void VerifyTextfieldContextMenuContents(bool textfield_has_selection, bool can_undo, ui::MenuModel* menu); void PressMouseButton(ui::EventFlags mouse_button_flags); void ReleaseMouseButton(ui::EventFlags mouse_button_flags); void PressLeftMouseButton(); void ReleaseLeftMouseButton(); void ClickLeftMouseButton(); void ClickRightMouseButton(); void DragMouseTo(const gfx::Point& where); // Textfield does not listen to OnMouseMoved, so this function does not send // an event when it updates the cursor position. void MoveMouseTo(const gfx::Point& where); void TapAtCursor(ui::EventPointerType pointer_type); // We need widget to populate wrapper class. std::unique_ptr<Widget> widget_; raw_ptr<TestTextfield> textfield_ = nullptr; std::unique_ptr<TextfieldTestApi> test_api_; raw_ptr<TextfieldModel> model_ = nullptr; // The string from Controller::ContentsChanged callback. std::u16string last_contents_; // For testing input method related behaviors. raw_ptr<MockInputMethod> input_method_ = nullptr; // Indicates how many times OnBeforeUserAction() is called. int on_before_user_action_ = 0; // Indicates how many times OnAfterUserAction() is called. int on_after_user_action_ = 0; // Position of the mouse for synthetic mouse events. gfx::Point mouse_position_; ui::ClipboardBuffer copied_to_clipboard_ = ui::ClipboardBuffer::kMaxValue; std::unique_ptr<ui::test::EventGenerator> event_generator_; raw_ptr<View> event_target_ = nullptr; }; } // namespace test } // namespace views #endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_UNITTEST_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/textfield/textfield_unittest.h
C++
unknown
5,916
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/theme_tracking_image_view.h" #include "base/functional/callback.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/models/image_model.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image_skia.h" #include "ui/native_theme/native_theme.h" namespace views { ThemeTrackingImageView::ThemeTrackingImageView( const ui::ImageModel& light_image_model, const ui::ImageModel& dark_image_model, const base::RepeatingCallback<SkColor()>& get_background_color_callback) : light_image_model_(light_image_model), dark_image_model_(dark_image_model), get_background_color_callback_(get_background_color_callback) { DCHECK_EQ(light_image_model_.Size(), dark_image_model_.Size()); SetImage(light_image_model_); } ThemeTrackingImageView::ThemeTrackingImageView( const gfx::ImageSkia& light_image, const gfx::ImageSkia& dark_image, const base::RepeatingCallback<SkColor()>& get_background_color_callback) : light_image_model_(ui::ImageModel::FromImageSkia(light_image)), dark_image_model_(ui::ImageModel::FromImageSkia(dark_image)), get_background_color_callback_(get_background_color_callback) { DCHECK_EQ(light_image_model_.Size(), dark_image_model_.Size()); SetImage(light_image_model_); } ThemeTrackingImageView::~ThemeTrackingImageView() = default; void ThemeTrackingImageView::OnThemeChanged() { ImageView::OnThemeChanged(); SetImage(color_utils::IsDark(get_background_color_callback_.Run()) ? dark_image_model_ : light_image_model_); } void ThemeTrackingImageView::SetLightImage( const ui::ImageModel& light_image_model) { light_image_model_ = light_image_model; if (!color_utils::IsDark(get_background_color_callback_.Run())) SetImage(light_image_model_); } void ThemeTrackingImageView::SetDarkImage( const ui::ImageModel& dark_image_model) { dark_image_model_ = dark_image_model; if (color_utils::IsDark(get_background_color_callback_.Run())) SetImage(dark_image_model_); } BEGIN_METADATA(ThemeTrackingImageView, views::ImageView) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/theme_tracking_image_view.cc
C++
unknown
2,291
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_THEME_TRACKING_IMAGE_VIEW_H_ #define UI_VIEWS_CONTROLS_THEME_TRACKING_IMAGE_VIEW_H_ #include "base/functional/callback.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/image_view.h" namespace views { // An ImageView that displays either `light_image` or `dark_image` based on the // current background color returned by `get_background_color_callback`. Tracks // theme changes so the image is always the correct version. `light_image` and // `dark_image` must be of the same size. The `light_image` is set by default // upon construction. class VIEWS_EXPORT ThemeTrackingImageView : public ImageView { public: METADATA_HEADER(ThemeTrackingImageView); ThemeTrackingImageView( const ui::ImageModel& light_image_model, const ui::ImageModel& dark_image_model, const base::RepeatingCallback<SkColor()>& get_background_color_callback); // TODO(crbug.com/1366871): Remove this constructor and migrate existing // callers to `ImageModel`. ThemeTrackingImageView( const gfx::ImageSkia& light_image, const gfx::ImageSkia& dark_image, const base::RepeatingCallback<SkColor()>& get_background_color_callback); ThemeTrackingImageView(const ThemeTrackingImageView&) = delete; ThemeTrackingImageView& operator=(const ThemeTrackingImageView&) = delete; ~ThemeTrackingImageView() override; void SetLightImage(const ui::ImageModel& light_image_model); void SetDarkImage(const ui::ImageModel& dark_image_model); // ImageView: void OnThemeChanged() override; private: // The underlying light and dark mode image models. ui::ImageModel light_image_model_; ui::ImageModel dark_image_model_; base::RepeatingCallback<SkColor()> get_background_color_callback_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_THEME_TRACKING_IMAGE_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/theme_tracking_image_view.h
C++
unknown
2,030
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/theme_tracking_image_view.h" #include <memory> #include <utility> #include "base/functional/bind.h" #include "components/vector_icons/vector_icons.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/models/image_model.h" #include "ui/color/color_id.h" #include "ui/gfx/image/image_unittest_util.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" namespace views { namespace { constexpr int kImageSize = 16; gfx::ImageSkia CreateTestImage(SkColor color) { SkBitmap bitmap; bitmap.allocN32Pixels(kImageSize, kImageSize); bitmap.eraseColor(color); return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); } } // namespace class ThemeTrackingImageViewTest : public ViewsTestBase { public: void SetUp() override { ViewsTestBase::SetUp(); widget_ = CreateTestWidget(); } void TearDown() override { widget_.reset(); ViewsTestBase::TearDown(); } SkColor GetSimulatedBackgroundColor() const { return is_dark_ ? SK_ColorBLACK : SK_ColorWHITE; } protected: bool IsDarkMode() const { return is_dark_; } void SetIsDarkMode(bool is_dark) { is_dark_ = is_dark; if (view_) view_->OnThemeChanged(); } void SetView(std::unique_ptr<ThemeTrackingImageView> view) { view_ = widget_->SetContentsView(std::move(view)); view_->SetBounds(0, 0, kImageSize, kImageSize); } ThemeTrackingImageView* view() { return view_; } Widget* widget() { return widget_.get(); } private: std::unique_ptr<Widget> widget_; raw_ptr<ThemeTrackingImageView> view_ = nullptr; bool is_dark_ = false; }; TEST_F(ThemeTrackingImageViewTest, CreateWithImageSkia) { gfx::ImageSkia light_image{CreateTestImage(SK_ColorRED)}; gfx::ImageSkia dark_image{CreateTestImage(SK_ColorBLUE)}; SetView(std::make_unique<ThemeTrackingImageView>( light_image, dark_image, base::BindRepeating( &ThemeTrackingImageViewTest::GetSimulatedBackgroundColor, base::Unretained(this)))); ASSERT_FALSE(IsDarkMode()); EXPECT_TRUE(gfx::test::AreBitmapsEqual(*view()->GetImage().bitmap(), *light_image.bitmap())); SetIsDarkMode(true); EXPECT_FALSE(gfx::test::AreBitmapsEqual(*view()->GetImage().bitmap(), *light_image.bitmap())); EXPECT_TRUE(gfx::test::AreBitmapsEqual(*view()->GetImage().bitmap(), *dark_image.bitmap())); } TEST_F(ThemeTrackingImageViewTest, CreateWithImageModel) { ui::ImageModel light_model{ui::ImageModel::FromVectorIcon( vector_icons::kSyncIcon, ui::kColorMenuIcon, kImageSize)}; ui::ImageModel dark_model{ui::ImageModel::FromVectorIcon( vector_icons::kCallIcon, ui::kColorMenuIcon, kImageSize)}; SetView(std::make_unique<ThemeTrackingImageView>( light_model, dark_model, base::BindRepeating( &ThemeTrackingImageViewTest::GetSimulatedBackgroundColor, base::Unretained(this)))); ASSERT_FALSE(IsDarkMode()); EXPECT_EQ(view()->GetImageModel(), light_model); SetIsDarkMode(true); EXPECT_NE(view()->GetImageModel(), light_model); EXPECT_EQ(view()->GetImageModel(), dark_model); } TEST_F(ThemeTrackingImageViewTest, SetLightImage) { ui::ImageModel light_model1{ui::ImageModel::FromVectorIcon( vector_icons::kSyncIcon, ui::kColorMenuIcon, kImageSize)}; ui::ImageModel light_model2{ui::ImageModel::FromVectorIcon( vector_icons::kUsbIcon, ui::kColorMenuIcon, kImageSize)}; ui::ImageModel dark_model{ui::ImageModel::FromVectorIcon( vector_icons::kCallIcon, ui::kColorMenuIcon, kImageSize)}; SetView(std::make_unique<ThemeTrackingImageView>( light_model1, dark_model, base::BindRepeating( &ThemeTrackingImageViewTest::GetSimulatedBackgroundColor, base::Unretained(this)))); ASSERT_FALSE(IsDarkMode()); EXPECT_EQ(view()->GetImageModel(), light_model1); SetIsDarkMode(true); view()->SetLightImage(light_model2); // The image remains the one for dark mode. EXPECT_EQ(view()->GetImageModel(), dark_model); // Upon switching, the image is updated. SetIsDarkMode(false); EXPECT_EQ(view()->GetImageModel(), light_model2); // If light mode is currently on, the image is updated immediately. view()->SetLightImage(light_model1); EXPECT_EQ(view()->GetImageModel(), light_model1); } TEST_F(ThemeTrackingImageViewTest, SetDarkImage) { ui::ImageModel light_model{ui::ImageModel::FromVectorIcon( vector_icons::kSyncIcon, ui::kColorMenuIcon, kImageSize)}; ui::ImageModel dark_model1{ui::ImageModel::FromVectorIcon( vector_icons::kUsbIcon, ui::kColorMenuIcon, kImageSize)}; ui::ImageModel dark_model2{ui::ImageModel::FromVectorIcon( vector_icons::kCallIcon, ui::kColorMenuIcon, kImageSize)}; SetView(std::make_unique<ThemeTrackingImageView>( light_model, dark_model1, base::BindRepeating( &ThemeTrackingImageViewTest::GetSimulatedBackgroundColor, base::Unretained(this)))); ASSERT_FALSE(IsDarkMode()); EXPECT_EQ(view()->GetImageModel(), light_model); SetIsDarkMode(true); EXPECT_EQ(view()->GetImageModel(), dark_model1); SetIsDarkMode(false); view()->SetDarkImage(dark_model2); EXPECT_EQ(view()->GetImageModel(), light_model); SetIsDarkMode(true); EXPECT_EQ(view()->GetImageModel(), dark_model2); view()->SetDarkImage(dark_model1); EXPECT_EQ(view()->GetImageModel(), dark_model1); } } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/theme_tracking_image_view_unittest.cc
C++
unknown
5,751
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/throbber.h" #include "base/functional/bind.h" #include "base/location.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/paint_throbber.h" #include "ui/gfx/paint_vector_icon.h" namespace views { // The default diameter of a Throbber. If you change this, also change // kCheckmarkDipSize. constexpr int kDefaultDiameter = 16; // The size of the checkmark, in DIP. This magic number matches the default // diameter plus padding inherent in the checkmark SVG. constexpr int kCheckmarkDipSize = kDefaultDiameter + 2; Throbber::Throbber() = default; Throbber::~Throbber() { Stop(); } void Throbber::Start() { if (IsRunning()) return; start_time_ = base::TimeTicks::Now(); timer_.Start( FROM_HERE, base::Milliseconds(30), base::BindRepeating(&Throbber::SchedulePaint, base::Unretained(this))); SchedulePaint(); // paint right away } void Throbber::Stop() { if (!IsRunning()) return; timer_.Stop(); SchedulePaint(); } bool Throbber::GetChecked() const { return checked_; } void Throbber::SetChecked(bool checked) { if (checked == checked_) return; checked_ = checked; OnPropertyChanged(&checked_, kPropertyEffectsPaint); } gfx::Size Throbber::CalculatePreferredSize() const { return gfx::Size(kDefaultDiameter, kDefaultDiameter); } void Throbber::OnPaint(gfx::Canvas* canvas) { SkColor color = GetColorProvider()->GetColor(ui::kColorThrobber); if (!IsRunning()) { if (checked_) { canvas->Translate(gfx::Vector2d((width() - kCheckmarkDipSize) / 2, (height() - kCheckmarkDipSize) / 2)); gfx::PaintVectorIcon(canvas, vector_icons::kCheckCircleIcon, kCheckmarkDipSize, color); } return; } base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time_; gfx::PaintThrobberSpinning(canvas, GetContentsBounds(), color, elapsed_time); } bool Throbber::IsRunning() const { return timer_.IsRunning(); } BEGIN_METADATA(Throbber, View) ADD_PROPERTY_METADATA(bool, Checked) END_METADATA // Smoothed throbber --------------------------------------------------------- SmoothedThrobber::SmoothedThrobber() : start_delay_(base::Milliseconds(200)), stop_delay_(base::Milliseconds(50)) {} SmoothedThrobber::~SmoothedThrobber() = default; void SmoothedThrobber::Start() { stop_timer_.Stop(); if (!IsRunning() && !start_timer_.IsRunning()) { start_timer_.Start(FROM_HERE, start_delay_, this, &SmoothedThrobber::StartDelayOver); } } void SmoothedThrobber::StartDelayOver() { Throbber::Start(); } void SmoothedThrobber::Stop() { if (!IsRunning()) start_timer_.Stop(); stop_timer_.Stop(); stop_timer_.Start(FROM_HERE, stop_delay_, this, &SmoothedThrobber::StopDelayOver); } base::TimeDelta SmoothedThrobber::GetStartDelay() const { return start_delay_; } void SmoothedThrobber::SetStartDelay(const base::TimeDelta& start_delay) { if (start_delay == start_delay_) return; start_delay_ = start_delay; OnPropertyChanged(&start_delay_, kPropertyEffectsNone); } base::TimeDelta SmoothedThrobber::GetStopDelay() const { return stop_delay_; } void SmoothedThrobber::SetStopDelay(const base::TimeDelta& stop_delay) { if (stop_delay == stop_delay_) return; stop_delay_ = stop_delay; OnPropertyChanged(&stop_delay_, kPropertyEffectsNone); } void SmoothedThrobber::StopDelayOver() { Throbber::Stop(); } BEGIN_METADATA(SmoothedThrobber, Throbber) ADD_PROPERTY_METADATA(base::TimeDelta, StartDelay) ADD_PROPERTY_METADATA(base::TimeDelta, StopDelay) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/throbber.cc
C++
unknown
4,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. #ifndef UI_VIEWS_CONTROLS_THROBBER_H_ #define UI_VIEWS_CONTROLS_THROBBER_H_ #include "base/time/time.h" #include "base/timer/timer.h" #include "ui/views/view.h" namespace views { // Throbbers display an animation, usually used as a status indicator. class VIEWS_EXPORT Throbber : public View { public: METADATA_HEADER(Throbber); Throbber(); Throbber(const Throbber&) = delete; Throbber& operator=(const Throbber&) = delete; ~Throbber() override; // Start and stop the throbber animation. virtual void Start(); virtual void Stop(); // Gets/Sets checked. For SetChecked, stop spinning and, if // checked is true, display a checkmark. bool GetChecked() const; void SetChecked(bool checked); // Overridden from View: gfx::Size CalculatePreferredSize() const override; void OnPaint(gfx::Canvas* canvas) override; protected: // Specifies whether the throbber is currently animating or not bool IsRunning() const; private: base::TimeTicks start_time_; // Time when Start was called. base::RepeatingTimer timer_; // Used to schedule Run calls. // Whether or not we should display a checkmark. bool checked_ = false; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, Throbber, View) VIEW_BUILDER_PROPERTY(bool, Checked) END_VIEW_BUILDER // A SmoothedThrobber is a throbber that is representing potentially short // and nonoverlapping bursts of work. SmoothedThrobber ignores small // pauses in the work stops and starts, and only starts its throbber after // a small amount of work time has passed. class VIEWS_EXPORT SmoothedThrobber : public Throbber { public: METADATA_HEADER(SmoothedThrobber); SmoothedThrobber(); SmoothedThrobber(const SmoothedThrobber&) = delete; SmoothedThrobber& operator=(const SmoothedThrobber&) = delete; ~SmoothedThrobber() override; void Start() override; void Stop() override; base::TimeDelta GetStartDelay() const; void SetStartDelay(const base::TimeDelta& start_delay); base::TimeDelta GetStopDelay() const; void SetStopDelay(const base::TimeDelta& stop_delay); private: // Called when the startup-delay timer fires // This function starts the actual throbbing. void StartDelayOver(); // Called when the shutdown-delay timer fires. // This function stops the actual throbbing. void StopDelayOver(); // Delay after work starts before starting throbber. base::TimeDelta start_delay_; // Delay after work stops before stopping. base::TimeDelta stop_delay_; base::OneShotTimer start_timer_; base::OneShotTimer stop_timer_; }; BEGIN_VIEW_BUILDER(VIEWS_EXPORT, SmoothedThrobber, Throbber) VIEW_BUILDER_PROPERTY(const base::TimeDelta&, StartDelay) VIEW_BUILDER_PROPERTY(const base::TimeDelta&, StopDelay) END_VIEW_BUILDER } // namespace views DEFINE_VIEW_BUILDER(VIEWS_EXPORT, Throbber) DEFINE_VIEW_BUILDER(VIEWS_EXPORT, SmoothedThrobber) #endif // UI_VIEWS_CONTROLS_THROBBER_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/throbber.h
C++
unknown
3,052
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/tree/tree_view.h" #include <algorithm> #include <utility> #include "base/containers/adapters.h" #include "base/i18n/rtl.h" #include "base/memory/ptr_util.h" #include "build/build_config.h" #include "components/vector_icons/vector_icons.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/ime/input_method.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/models/image_model.h" #include "ui/base/resource/resource_bundle.h" #include "ui/color/color_id.h" #include "ui/color/color_provider.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/scoped_canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/accessibility/ax_virtual_view.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/border.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/prefix_selector.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/tree/tree_view_controller.h" #include "ui/views/style/platform_style.h" #include "ui/views/widget/widget.h" using ui::TreeModel; using ui::TreeModelNode; namespace views { // Insets around the view. static constexpr int kHorizontalInset = 2; // Padding before/after the image. static constexpr int kImagePadding = 4; // Size of the arrow region. static constexpr int kArrowRegionSize = 12; // Padding around the text (on each side). static constexpr int kTextVerticalPadding = 3; static constexpr int kTextHorizontalPadding = 2; // Padding between the auxiliary text and the end of the line, handles RTL. static constexpr int kAuxiliaryTextLineEndPadding = 5; // How much children are indented from their parent. static constexpr int kIndent = 20; namespace { void PaintRowIcon(gfx::Canvas* canvas, const gfx::ImageSkia& icon, int x, const gfx::Rect& rect) { canvas->DrawImageInt(icon, rect.x() + x, rect.y() + (rect.height() - icon.height()) / 2); } bool EventIsDoubleTapOrClick(const ui::LocatedEvent& event) { if (event.type() == ui::ET_GESTURE_TAP) return event.AsGestureEvent()->details().tap_count() == 2; return !!(event.flags() & ui::EF_IS_DOUBLE_CLICK); } int GetSpaceThicknessForFocusRing() { static const int kSpaceThicknessForFocusRing = FocusRing::kDefaultHaloThickness - FocusRing::kDefaultHaloInset; return kSpaceThicknessForFocusRing; } } // namespace TreeView::TreeView() : row_height_(font_list_.GetHeight() + kTextVerticalPadding * 2), drawing_provider_(std::make_unique<TreeViewDrawingProvider>()) { // Always focusable, even on Mac (consistent with NSOutlineView). SetFocusBehavior(FocusBehavior::ALWAYS); #if BUILDFLAG(IS_MAC) constexpr bool kUseMdIcons = true; #else constexpr bool kUseMdIcons = false; #endif if (kUseMdIcons) { closed_icon_ = open_icon_ = ui::ImageModel::FromVectorIcon( vector_icons::kFolderIcon, ui::kColorIcon); } else { // TODO(ellyjones): if the pre-Harmony codepath goes away, merge // closed_icon_ and open_icon_. closed_icon_ = ui::ImageModel::FromImage( ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_FOLDER_CLOSED)); open_icon_ = ui::ImageModel::FromImage( ui::ResourceBundle::GetSharedInstance().GetImageNamed(IDR_FOLDER_OPEN)); } text_offset_ = closed_icon_.Size().width() + kImagePadding + kImagePadding + kArrowRegionSize; } TreeView::~TreeView() { if (model_) model_->RemoveObserver(this); if (GetInputMethod() && selector_.get()) { // TreeView should have been blurred before destroy. DCHECK(selector_.get() != GetInputMethod()->GetTextInputClient()); } if (focus_manager_) { focus_manager_->RemoveFocusChangeListener(this); focus_manager_ = nullptr; } } // static std::unique_ptr<ScrollView> TreeView::CreateScrollViewWithTree( std::unique_ptr<TreeView> tree) { auto scroll_view = ScrollView::CreateScrollViewWithBorder(); scroll_view->SetContents(std::move(tree)); return scroll_view; } void TreeView::SetModel(TreeModel* model) { if (model == model_) return; if (model_) model_->RemoveObserver(this); CancelEdit(); model_ = model; selected_node_ = nullptr; active_node_ = nullptr; icons_.clear(); if (model_) { model_->AddObserver(this); model_->GetIcons(&icons_); GetViewAccessibility().RemoveAllVirtualChildViews(); root_.DeleteAll(); ConfigureInternalNode(model_->GetRoot(), &root_); std::unique_ptr<AXVirtualView> ax_root_view = CreateAndSetAccessibilityView(&root_); GetViewAccessibility().AddVirtualChildView(std::move(ax_root_view)); LoadChildren(&root_); root_.set_is_expanded(true); if (root_shown_) SetSelectedNode(root_.model_node()); else if (!root_.children().empty()) SetSelectedNode(root_.children().front().get()->model_node()); } DrawnNodesChanged(); } void TreeView::SetEditable(bool editable) { if (editable == editable_) return; editable_ = editable; CancelEdit(); } void TreeView::StartEditing(TreeModelNode* node) { DCHECK(node); // Cancel the current edit. CancelEdit(); // Make sure all ancestors are expanded. if (model_->GetParent(node)) Expand(model_->GetParent(node)); // Select the node, else if the user commits the edit the selection reverts. SetSelectedNode(node); if (GetSelectedNode() != node) return; // Selection failed for some reason, don't start editing. DCHECK(!editing_); editing_ = true; if (!editor_) { editor_ = new Textfield; // Add the editor immediately as GetPreferredSize returns the wrong thing if // not parented. AddChildView(editor_.get()); editor_->SetFontList(font_list_); empty_editor_size_ = editor_->GetPreferredSize(); editor_->set_controller(this); } editor_->SetText(selected_node_->model_node()->GetTitle()); // TODO(crbug.com/1345828): Investigate whether accessible name should stay in // sync during editing. editor_->SetAccessibleName( selected_node_->model_node()->GetAccessibleTitle()); LayoutEditor(); editor_->SetVisible(true); SchedulePaintForNode(selected_node_); editor_->RequestFocus(); editor_->SelectAll(false); // Listen for focus changes so that we can cancel editing. focus_manager_ = GetFocusManager(); if (focus_manager_) focus_manager_->AddFocusChangeListener(this); // Accelerators to commit/cancel edit. AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE)); AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); } void TreeView::CancelEdit() { if (!editing_) return; // WARNING: don't touch |selected_node_|, it may be bogus. editing_ = false; if (focus_manager_) { focus_manager_->RemoveFocusChangeListener(this); focus_manager_ = nullptr; } editor_->SetVisible(false); SchedulePaint(); RemoveAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE)); RemoveAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); } void TreeView::CommitEdit() { if (!editing_) return; DCHECK(selected_node_); const bool editor_has_focus = editor_->HasFocus(); model_->SetTitle(GetSelectedNode(), editor_->GetText()); editor_->SetAccessibleName(GetSelectedNode()->GetAccessibleTitle()); CancelEdit(); if (editor_has_focus) RequestFocus(); } TreeModelNode* TreeView::GetEditingNode() { return editing_ ? selected_node_->model_node() : nullptr; } void TreeView::SetSelectedNode(TreeModelNode* model_node) { UpdateSelection(model_node, SelectionType::kActiveAndSelected); } const TreeModelNode* TreeView::GetSelectedNode() const { return selected_node_ ? selected_node_->model_node() : nullptr; } void TreeView::SetActiveNode(TreeModelNode* model_node) { UpdateSelection(model_node, SelectionType::kActive); } const TreeModelNode* TreeView::GetActiveNode() const { return active_node_ ? active_node_->model_node() : nullptr; } void TreeView::Collapse(ui::TreeModelNode* model_node) { // Don't collapse the root if the root isn't shown, otherwise nothing is // displayed. if (model_node == root_.model_node() && !root_shown_) return; InternalNode* node = GetInternalNodeForModelNode(model_node, DONT_CREATE_IF_NOT_LOADED); if (!node) return; bool was_expanded = IsExpanded(model_node); if (node->is_expanded()) { if (selected_node_ && selected_node_->HasAncestor(node)) UpdateSelection(model_node, SelectionType::kActiveAndSelected); else if (active_node_ && active_node_->HasAncestor(node)) UpdateSelection(model_node, SelectionType::kActive); node->set_is_expanded(false); } if (was_expanded) { DrawnNodesChanged(); AXVirtualView* ax_view = node->accessibility_view(); if (ax_view) { ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kExpandedChanged); ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kRowCollapsed); } NotifyAccessibilityEvent(ax::mojom::Event::kRowCountChanged, true); } } void TreeView::Expand(TreeModelNode* node) { if (ExpandImpl(node)) { DrawnNodesChanged(); InternalNode* internal_node = GetInternalNodeForModelNode(node, DONT_CREATE_IF_NOT_LOADED); AXVirtualView* ax_view = internal_node ? internal_node->accessibility_view() : nullptr; if (ax_view) { ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kExpandedChanged); ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kRowExpanded); } NotifyAccessibilityEvent(ax::mojom::Event::kRowCountChanged, true); } // TODO(sky): need to support auto_expand_children_. } void TreeView::ExpandAll(TreeModelNode* node) { DCHECK(node); // Expand the node. bool expanded_at_least_one = ExpandImpl(node); // And recursively expand all the children. const auto& children = model_->GetChildren(node); for (TreeModelNode* child : base::Reversed(children)) { if (ExpandImpl(child)) expanded_at_least_one = true; } if (expanded_at_least_one) { DrawnNodesChanged(); InternalNode* internal_node = GetInternalNodeForModelNode(node, DONT_CREATE_IF_NOT_LOADED); AXVirtualView* ax_view = internal_node ? internal_node->accessibility_view() : nullptr; if (ax_view) { ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kExpandedChanged); ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kRowExpanded); } NotifyAccessibilityEvent(ax::mojom::Event::kRowCountChanged, true); } } bool TreeView::IsExpanded(TreeModelNode* model_node) { if (!model_node) { // NULL check primarily for convenience for uses in this class so don't have // to add NULL checks every where we look up the parent. return true; } InternalNode* node = GetInternalNodeForModelNode(model_node, DONT_CREATE_IF_NOT_LOADED); if (!node) return false; while (node) { if (!node->is_expanded()) return false; node = node->parent(); } return true; } void TreeView::SetRootShown(bool root_shown) { if (root_shown_ == root_shown) return; root_shown_ = root_shown; if (!root_shown_ && (selected_node_ == &root_ || active_node_ == &root_)) { const auto& children = model_->GetChildren(root_.model_node()); TreeModelNode* first_child = children.empty() ? nullptr : children.front(); if (selected_node_ == &root_) UpdateSelection(first_child, SelectionType::kActiveAndSelected); else if (active_node_ == &root_) UpdateSelection(first_child, SelectionType::kActive); } AXVirtualView* ax_view = root_.accessibility_view(); // There should always be a virtual accessibility view for the root, unless // someone calls this method before setting a model. if (ax_view) ax_view->NotifyAccessibilityEvent(ax::mojom::Event::kStateChanged); DrawnNodesChanged(); } ui::TreeModelNode* TreeView::GetNodeForRow(int row) { int depth = 0; InternalNode* node = GetNodeByRow(row, &depth); return node ? node->model_node() : nullptr; } int TreeView::GetRowForNode(ui::TreeModelNode* node) { InternalNode* internal_node = GetInternalNodeForModelNode(node, DONT_CREATE_IF_NOT_LOADED); if (!internal_node) return -1; int depth = 0; return GetRowForInternalNode(internal_node, &depth); } void TreeView::SetDrawingProvider( std::unique_ptr<TreeViewDrawingProvider> provider) { drawing_provider_ = std::move(provider); } void TreeView::Layout() { int width = preferred_size_.width(); int height = preferred_size_.height(); if (parent()) { width = std::max(parent()->width(), width); height = std::max(parent()->height(), height); } SetBounds(x(), y(), width, height); LayoutEditor(); } gfx::Size TreeView::CalculatePreferredSize() const { return preferred_size_; } bool TreeView::AcceleratorPressed(const ui::Accelerator& accelerator) { if (accelerator.key_code() == ui::VKEY_RETURN) { CommitEdit(); } else { DCHECK_EQ(ui::VKEY_ESCAPE, accelerator.key_code()); CancelEdit(); RequestFocus(); } return true; } bool TreeView::OnMousePressed(const ui::MouseEvent& event) { return OnClickOrTap(event); } void TreeView::OnGestureEvent(ui::GestureEvent* event) { if (event->type() == ui::ET_GESTURE_TAP) { if (OnClickOrTap(*event)) event->SetHandled(); } } void TreeView::ShowContextMenu(const gfx::Point& p, ui::MenuSourceType source_type) { if (!model_) return; if (source_type == ui::MENU_SOURCE_MOUSE) { // Only invoke View's implementation (which notifies the // ContextMenuController) if over a node. gfx::Point local_point(p); ConvertPointFromScreen(this, &local_point); if (!GetNodeAtPoint(local_point)) return; } View::ShowContextMenu(p, source_type); } void TreeView::GetAccessibleNodeData(ui::AXNodeData* node_data) { // ID, class name and relative bounds are added by ViewAccessibility for all // non-virtual views, so we don't need to add them here. node_data->role = ax::mojom::Role::kTree; node_data->AddState(ax::mojom::State::kVertical); node_data->SetRestriction(ax::mojom::Restriction::kReadOnly); node_data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kActivate); node_data->SetNameExplicitlyEmpty(); } bool TreeView::HandleAccessibleAction(const ui::AXActionData& action_data) { if (!model_) return false; AXVirtualView* ax_view = AXVirtualView::GetFromId(action_data.target_node_id); InternalNode* node = ax_view ? GetInternalNodeForVirtualView(ax_view) : nullptr; if (!node) { switch (action_data.action) { case ax::mojom::Action::kFocus: if (active_node_) return false; if (!HasFocus()) RequestFocus(); return true; case ax::mojom::Action::kBlur: case ax::mojom::Action::kScrollToMakeVisible: return View::HandleAccessibleAction(action_data); default: return false; } } switch (action_data.action) { case ax::mojom::Action::kDoDefault: SetSelectedNode(node->model_node()); if (!HasFocus()) RequestFocus(); if (IsExpanded(node->model_node())) Collapse(node->model_node()); else Expand(node->model_node()); break; case ax::mojom::Action::kFocus: SetSelectedNode(node->model_node()); if (!HasFocus()) RequestFocus(); break; case ax::mojom::Action::kScrollToMakeVisible: // GetForegroundBoundsForNode() returns RTL-flipped coordinates for paint. // Un-flip before passing to ScrollRectToVisible(), which uses layout // coordinates. ScrollRectToVisible(GetMirroredRect(GetForegroundBoundsForNode(node))); break; case ax::mojom::Action::kShowContextMenu: SetSelectedNode(node->model_node()); if (!HasFocus()) RequestFocus(); ShowContextMenu(GetBoundsInScreen().CenterPoint(), ui::MENU_SOURCE_KEYBOARD); break; default: return false; } return true; } void TreeView::TreeNodesAdded(TreeModel* model, TreeModelNode* parent, size_t start, size_t count) { InternalNode* parent_node = GetInternalNodeForModelNode(parent, DONT_CREATE_IF_NOT_LOADED); if (!parent_node || !parent_node->loaded_children()) return; const auto& children = model_->GetChildren(parent); for (size_t i = start; i < start + count; ++i) { auto child = std::make_unique<InternalNode>(); ConfigureInternalNode(children[i], child.get()); std::unique_ptr<AXVirtualView> ax_view = CreateAndSetAccessibilityView(child.get()); parent_node->Add(std::move(child), i); DCHECK_LE(i, parent_node->accessibility_view()->GetChildCount()); parent_node->accessibility_view()->AddChildViewAt(std::move(ax_view), i); } if (IsExpanded(parent)) { NotifyAccessibilityEvent(ax::mojom::Event::kRowCountChanged, true); DrawnNodesChanged(); } } void TreeView::TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, size_t start, size_t count) { InternalNode* parent_node = GetInternalNodeForModelNode(parent, DONT_CREATE_IF_NOT_LOADED); if (!parent_node || !parent_node->loaded_children()) return; bool reset_selected_node = false; bool reset_active_node = false; for (size_t i = 0; i < count; ++i) { InternalNode* child_removing = parent_node->children()[start].get(); if (selected_node_ && selected_node_->HasAncestor(child_removing)) reset_selected_node = true; if (active_node_ && active_node_->HasAncestor(child_removing)) reset_active_node = true; DCHECK(parent_node->accessibility_view()->Contains( child_removing->accessibility_view())); parent_node->accessibility_view()->RemoveChildView( child_removing->accessibility_view()); child_removing->set_accessibility_view(nullptr); parent_node->Remove(start); } if (reset_selected_node || reset_active_node) { // selected_node_ or active_node_ or both were no longer valid (i.e. the // model_node() was likely deleted by the time we entered this function). // Explicitly set to nullptr before continuing; otherwise, we might try to // use a deleted value. if (reset_selected_node) selected_node_ = nullptr; if (reset_active_node) active_node_ = nullptr; // Replace invalidated states with the nearest valid node. const auto& children = model_->GetChildren(parent); TreeModelNode* nearest_node = nullptr; if (!children.empty()) { nearest_node = children[std::min(start, children.size() - 1)]; } else if (parent != root_.model_node() || root_shown_) { nearest_node = parent; } if (reset_selected_node) UpdateSelection(nearest_node, SelectionType::kActiveAndSelected); else if (reset_active_node) UpdateSelection(nearest_node, SelectionType::kActive); } if (IsExpanded(parent)) { NotifyAccessibilityEvent(ax::mojom::Event::kRowCountChanged, true); DrawnNodesChanged(); } } void TreeView::TreeNodeChanged(TreeModel* model, TreeModelNode* model_node) { InternalNode* node = GetInternalNodeForModelNode(model_node, DONT_CREATE_IF_NOT_LOADED); if (!node) return; int old_width = node->text_width(); UpdateNodeTextWidth(node); if (old_width != node->text_width() && ((node == &root_ && root_shown_) || (node != &root_ && IsExpanded(node->parent()->model_node())))) { node->accessibility_view()->NotifyAccessibilityEvent( ax::mojom::Event::kLocationChanged); DrawnNodesChanged(); } } void TreeView::ContentsChanged(Textfield* sender, const std::u16string& new_contents) {} bool TreeView::HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) { if (key_event.type() != ui::ET_KEY_PRESSED) return false; switch (key_event.key_code()) { case ui::VKEY_RETURN: CommitEdit(); return true; case ui::VKEY_ESCAPE: CancelEdit(); RequestFocus(); return true; default: return false; } } void TreeView::OnWillChangeFocus(View* focused_before, View* focused_now) {} void TreeView::OnDidChangeFocus(View* focused_before, View* focused_now) { CommitEdit(); } size_t TreeView::GetRowCount() { size_t row_count = root_.NumExpandedNodes(); if (!root_shown_) row_count--; return row_count; } absl::optional<size_t> TreeView::GetSelectedRow() { // Type-ahead searches should be relative to the active node, so return the // row of the active node for |PrefixSelector|. ui::TreeModelNode* model_node = GetActiveNode(); if (!model_node) return absl::nullopt; const int row = GetRowForNode(model_node); return (row == -1) ? absl::nullopt : absl::make_optional(static_cast<size_t>(row)); } void TreeView::SetSelectedRow(absl::optional<size_t> row) { // Type-ahead manipulates selection because active node is synced to selected // node, so call SetSelectedNode() instead of SetActiveNode(). // TODO(crbug.com/1080944): Decouple active node from selected node by adding // new keyboard affordances. SetSelectedNode( GetNodeForRow(row.has_value() ? static_cast<int>(row.value()) : -1)); } std::u16string TreeView::GetTextForRow(size_t row) { return GetNodeForRow(static_cast<int>(row))->GetTitle(); } gfx::Point TreeView::GetKeyboardContextMenuLocation() { gfx::Rect vis_bounds(GetVisibleBounds()); int x = 0; int y = 0; if (active_node_) { gfx::Rect node_bounds(GetForegroundBoundsForNode(active_node_)); if (node_bounds.Intersects(vis_bounds)) node_bounds.Intersect(vis_bounds); gfx::Point menu_point(node_bounds.CenterPoint()); x = std::clamp(menu_point.x(), vis_bounds.x(), vis_bounds.right()); y = std::clamp(menu_point.y(), vis_bounds.y(), vis_bounds.bottom()); } gfx::Point screen_loc(x, y); if (base::i18n::IsRTL()) screen_loc.set_x(vis_bounds.width() - screen_loc.x()); ConvertPointToScreen(this, &screen_loc); return screen_loc; } bool TreeView::OnKeyPressed(const ui::KeyEvent& event) { if (!HasFocus()) return false; switch (event.key_code()) { case ui::VKEY_F2: if (!editing_) { TreeModelNode* active_node = GetActiveNode(); if (active_node && (!controller_ || controller_->CanEdit(this, active_node))) { StartEditing(active_node); } } return true; case ui::VKEY_UP: case ui::VKEY_DOWN: IncrementSelection(event.key_code() == ui::VKEY_UP ? IncrementType::kPrevious : IncrementType::kNext); return true; case ui::VKEY_LEFT: if (base::i18n::IsRTL()) ExpandOrSelectChild(); else CollapseOrSelectParent(); return true; case ui::VKEY_RIGHT: if (base::i18n::IsRTL()) CollapseOrSelectParent(); else ExpandOrSelectChild(); return true; default: break; } return false; } void TreeView::OnPaint(gfx::Canvas* canvas) { // Don't invoke View::OnPaint so that we can render our own focus border. canvas->DrawColor(GetColorProvider()->GetColor(ui::kColorTreeBackground)); int min_y, max_y; { SkRect sk_clip_rect; if (canvas->sk_canvas()->getLocalClipBounds(&sk_clip_rect)) { // Pixels partially inside the clip rect should be included. gfx::Rect clip_rect = gfx::ToEnclosingRect(gfx::SkRectToRectF(sk_clip_rect)); min_y = clip_rect.y(); max_y = clip_rect.bottom(); } else { gfx::Rect vis_bounds = GetVisibleBounds(); min_y = vis_bounds.y(); max_y = vis_bounds.bottom(); } } int min_row = std::max(0, min_y / row_height_); int max_row = max_y / row_height_; if (max_y % row_height_ != 0) max_row++; int current_row = root_row(); PaintRows(canvas, min_row, max_row, &root_, root_depth(), &current_row); } void TreeView::OnFocus() { if (GetInputMethod()) GetInputMethod()->SetFocusedTextInputClient(GetPrefixSelector()); View::OnFocus(); SchedulePaintForNode(selected_node_); // Notify the InputMethod so that it knows to query the TextInputClient. if (GetInputMethod()) GetInputMethod()->OnCaretBoundsChanged(GetPrefixSelector()); SetHasFocusIndicator(true); } void TreeView::OnBlur() { if (GetInputMethod()) GetInputMethod()->DetachTextInputClient(GetPrefixSelector()); SchedulePaintForNode(selected_node_); if (selector_) selector_->OnViewBlur(); SetHasFocusIndicator(false); } void TreeView::UpdateSelection(TreeModelNode* model_node, SelectionType selection_type) { CancelEdit(); if (model_node && model_->GetParent(model_node)) Expand(model_->GetParent(model_node)); if (model_node && model_node == root_.model_node() && !root_shown_) return; // Ignore requests for the root when not shown. InternalNode* node = model_node ? GetInternalNodeForModelNode(model_node, CREATE_IF_NOT_LOADED) : nullptr; // Force update if old value was nullptr to handle case of TreeNodesRemoved // explicitly resetting selected_node_ or active_node_ before invoking this. bool active_changed = (!active_node_ || active_node_ != node); bool selection_changed = (selection_type == SelectionType::kActiveAndSelected && (!selected_node_ || selected_node_ != node)); // Update tree view states to new values. if (active_changed) active_node_ = node; if (selection_changed) { SchedulePaintForNode(selected_node_); selected_node_ = node; SchedulePaintForNode(selected_node_); } if (active_changed && node) { // GetForegroundBoundsForNode() returns RTL-flipped coordinates for paint. // Un-flip before passing to ScrollRectToVisible(), which uses layout // coordinates. // TODO(crbug.com/1267807): We should not be doing synchronous layout here // but instead we should call into this asynchronously after the Views // tree has processed a layout pass which happens asynchronously. if (auto* widget = GetWidget()) widget->LayoutRootViewIfNecessary(); ScrollRectToVisible(GetMirroredRect(GetForegroundBoundsForNode(node))); } // Notify assistive technologies of state changes. if (active_changed) { // Update |ViewAccessibility| so that focus lands directly on this node when // |FocusManager| gives focus to the tree view. This update also fires an // accessible focus event. GetViewAccessibility().OverrideFocus(node ? node->accessibility_view() : nullptr); } if (selection_changed) { AXVirtualView* ax_selected_view = node ? node->accessibility_view() : nullptr; if (ax_selected_view) ax_selected_view->NotifyAccessibilityEvent(ax::mojom::Event::kSelection); else NotifyAccessibilityEvent(ax::mojom::Event::kSelection, true); } // Notify controller of state changes. if (selection_changed && controller_) controller_->OnTreeViewSelectionChanged(this); } bool TreeView::OnClickOrTap(const ui::LocatedEvent& event) { CommitEdit(); InternalNode* node = GetNodeAtPoint(event.location()); if (node) { bool hits_arrow = IsPointInExpandControl(node, event.location()); if (!hits_arrow) SetSelectedNode(node->model_node()); if (hits_arrow || EventIsDoubleTapOrClick(event)) { if (node->is_expanded()) Collapse(node->model_node()); else Expand(node->model_node()); } } if (!HasFocus()) RequestFocus(); return true; } void TreeView::LoadChildren(InternalNode* node) { DCHECK(node->children().empty()); DCHECK(!node->loaded_children()); node->set_loaded_children(true); for (auto* model_child : model_->GetChildren(node->model_node())) { std::unique_ptr<InternalNode> child = std::make_unique<InternalNode>(); ConfigureInternalNode(model_child, child.get()); std::unique_ptr<AXVirtualView> ax_view = CreateAndSetAccessibilityView(child.get()); node->Add(std::move(child)); node->accessibility_view()->AddChildView(std::move(ax_view)); } } void TreeView::ConfigureInternalNode(TreeModelNode* model_node, InternalNode* node) { node->Reset(model_node); UpdateNodeTextWidth(node); } bool TreeView::IsRoot(const InternalNode* node) const { return node == &root_; } void TreeView::UpdateNodeTextWidth(InternalNode* node) { int width = 0, height = 0; gfx::Canvas::SizeStringInt(node->model_node()->GetTitle(), font_list_, &width, &height, 0, gfx::Canvas::NO_ELLIPSIS); node->set_text_width(width); } std::unique_ptr<AXVirtualView> TreeView::CreateAndSetAccessibilityView( InternalNode* node) { DCHECK(node); auto ax_view = std::make_unique<AXVirtualView>(); ui::AXNodeData& node_data = ax_view->GetCustomData(); node_data.role = ax::mojom::Role::kTreeItem; if (base::i18n::IsRTL()) node_data.SetTextDirection(ax::mojom::WritingDirection::kRtl); base::RepeatingCallback<void(ui::AXNodeData*)> selected_callback = base::BindRepeating(&TreeView::PopulateAccessibilityData, base::Unretained(this), node); ax_view->SetPopulateDataCallback(std::move(selected_callback)); node->set_accessibility_view(ax_view.get()); return ax_view; } void TreeView::PopulateAccessibilityData(InternalNode* node, ui::AXNodeData* data) { DCHECK(node); TreeModelNode* selected_model_node = GetSelectedNode(); InternalNode* selected_node = selected_model_node ? GetInternalNodeForModelNode( selected_model_node, DONT_CREATE_IF_NOT_LOADED) : nullptr; const bool selected = (node == selected_node); data->AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, selected); data->SetDefaultActionVerb(ax::mojom::DefaultActionVerb::kSelect); if (node->is_expanded()) data->AddState(ax::mojom::State::kExpanded); else data->AddState(ax::mojom::State::kCollapsed); DCHECK(node->model_node()) << "InternalNode must be initialized. Did you " "forget to call ConfigureInternalNode(node)?"; data->SetName(node->model_node()->GetTitle()); // "AXVirtualView" will by default add the "invisible" state to any // virtual views that are not attached to a parent view. if (!IsRoot(node) && !node->parent()) return; // The node hasn't been added to the tree yet. int row = -1; if (IsRoot(node)) { const int depth = root_depth(); if (depth >= 0) { row = 1; data->AddIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel, int32_t{depth + 1}); data->AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, 1); data->AddIntAttribute(ax::mojom::IntAttribute::kSetSize, 1); } } else { // !IsRoot(node)) && node->parent() != nullptr. if (IsExpanded(node->parent()->model_node())) { int depth = 0; row = GetRowForInternalNode(node, &depth); if (depth >= 0) { data->AddIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel, int32_t{depth + 1}); } } // Per the ARIA Spec, aria-posinset and aria-setsize are 1-based // not 0-based. size_t pos_in_parent = node->parent()->GetIndexOf(node).value() + 1; size_t sibling_size = node->parent()->children().size(); data->AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, static_cast<int32_t>(pos_in_parent)); data->AddIntAttribute(ax::mojom::IntAttribute::kSetSize, static_cast<int32_t>(sibling_size)); } int ignored_depth; const bool is_visible_or_offscreen = row >= 0 && GetNodeByRow(row, &ignored_depth) == node; if (is_visible_or_offscreen) { data->AddState(ax::mojom::State::kFocusable); data->AddAction(ax::mojom::Action::kFocus); data->AddAction(ax::mojom::Action::kScrollToMakeVisible); gfx::Rect node_bounds = GetBackgroundBoundsForNode(node); data->relative_bounds.bounds = gfx::RectF(node_bounds); } else { data->AddState(node != &root_ || root_shown_ ? ax::mojom::State::kInvisible : ax::mojom::State::kIgnored); } } void TreeView::DrawnNodesChanged() { UpdatePreferredSize(); PreferredSizeChanged(); SchedulePaint(); } void TreeView::UpdatePreferredSize() { preferred_size_ = gfx::Size(); if (!model_) return; preferred_size_.SetSize( root_.GetMaxWidth(this, text_offset_, root_shown_ ? 1 : 0) + kTextHorizontalPadding * 2, row_height_ * base::checked_cast<int>(GetRowCount())); // When the editor is visible, more space is needed beyond the regular row, // such as for drawing the focus ring. // If this tree view is scrolled through layers, there is contension for // updating layer bounds and scroll within the same layout call. So an // extra row's height is added as the buffer space. int horizontal_space = GetSpaceThicknessForFocusRing(); int vertical_space = std::max(0, (empty_editor_size_.height() - font_list_.GetHeight()) / 2 - kTextVerticalPadding) + GetSpaceThicknessForFocusRing() + row_height_; preferred_size_.Enlarge(horizontal_space, vertical_space); } void TreeView::LayoutEditor() { if (!editing_) return; DCHECK(selected_node_); // Position the editor so that its text aligns with the text we drew. gfx::Rect row_bounds = GetForegroundBoundsForNode(selected_node_); // GetForegroundBoundsForNode() returns a "flipped" x for painting. First, un- // flip it for the following calculations and ScrollRectToVisible(). row_bounds.set_x( GetMirroredXWithWidthInView(row_bounds.x(), row_bounds.width())); row_bounds.set_x(row_bounds.x() + text_offset_); row_bounds.set_width(row_bounds.width() - text_offset_); row_bounds.Inset( gfx::Insets::VH(kTextVerticalPadding, kTextHorizontalPadding)); row_bounds.Inset(gfx::Insets::VH( -(empty_editor_size_.height() - font_list_.GetHeight()) / 2, -empty_editor_size_.width() / 2)); // Give a little extra space for editing. row_bounds.set_width(row_bounds.width() + 50); // If contained within a ScrollView, make sure the editor doesn't extend past // the viewport bounds. ScrollView* scroll_view = ScrollView::GetScrollViewForContents(this); if (scroll_view) { gfx::Rect content_bounds = scroll_view->GetContentsBounds(); row_bounds.set_size( gfx::Size(std::min(row_bounds.width(), content_bounds.width()), std::min(row_bounds.height(), content_bounds.height()))); } // The visible bounds should include the focus ring which is outside the // |row_bounds|. gfx::Rect outter_bounds = row_bounds; outter_bounds.Inset(-GetSpaceThicknessForFocusRing()); // Scroll as necessary to ensure that the editor is visible. ScrollRectToVisible(outter_bounds); editor_->SetBoundsRect(row_bounds); editor_->Layout(); } void TreeView::SchedulePaintForNode(InternalNode* node) { if (!node) return; // Explicitly allow NULL to be passed in. SchedulePaintInRect(GetBoundsForNode(node)); } void TreeView::PaintRows(gfx::Canvas* canvas, int min_row, int max_row, InternalNode* node, int depth, int* row) { if (*row >= max_row) return; if (*row >= min_row && *row < max_row) PaintRow(canvas, node, *row, depth); (*row)++; if (!node->is_expanded()) return; depth++; for (size_t i = 0; i < node->children().size() && *row < max_row; ++i) PaintRows(canvas, min_row, max_row, node->children()[i].get(), depth, row); } void TreeView::PaintRow(gfx::Canvas* canvas, InternalNode* node, int row, int depth) { gfx::Rect bounds(GetForegroundBoundsForNodeImpl(node, row, depth)); const SkColor selected_row_bg_color = drawing_provider()->GetBackgroundColorForNode(this, node->model_node()); // Paint the row background. if (PlatformStyle::kTreeViewSelectionPaintsEntireRow && selected_node_ == node) { canvas->FillRect(GetBackgroundBoundsForNode(node), selected_row_bg_color); } if (!model_->GetChildren(node->model_node()).empty()) PaintExpandControl(canvas, bounds, node->is_expanded()); if (drawing_provider()->ShouldDrawIconForNode(this, node->model_node())) PaintNodeIcon(canvas, node, bounds); // Paint the text background and text. In edit mode, the selected node is a // separate editing control, so it does not need to be painted here. if (editing_ && selected_node_ == node) return; gfx::Rect text_bounds(GetTextBoundsForNode(node)); if (base::i18n::IsRTL()) text_bounds.set_x(bounds.x()); // Paint the background on the selected row. if (!PlatformStyle::kTreeViewSelectionPaintsEntireRow && node == selected_node_) { canvas->FillRect(text_bounds, selected_row_bg_color); } // Paint the auxiliary text. std::u16string aux_text = drawing_provider()->GetAuxiliaryTextForNode(this, node->model_node()); if (!aux_text.empty()) { gfx::Rect aux_text_bounds = GetAuxiliaryTextBoundsForNode(node); // Only draw if there's actually some space left for the auxiliary text. if (!aux_text_bounds.IsEmpty()) { int align = base::i18n::IsRTL() ? gfx::Canvas::TEXT_ALIGN_LEFT : gfx::Canvas::TEXT_ALIGN_RIGHT; canvas->DrawStringRectWithFlags( aux_text, font_list_, drawing_provider()->GetAuxiliaryTextColorForNode(this, node->model_node()), aux_text_bounds, align); } } // Paint the text. const gfx::Rect internal_bounds( text_bounds.x() + kTextHorizontalPadding, text_bounds.y() + kTextVerticalPadding, text_bounds.width() - kTextHorizontalPadding * 2, text_bounds.height() - kTextVerticalPadding * 2); canvas->DrawStringRect( node->model_node()->GetTitle(), font_list_, drawing_provider()->GetTextColorForNode(this, node->model_node()), internal_bounds); } void TreeView::PaintExpandControl(gfx::Canvas* canvas, const gfx::Rect& node_bounds, bool expanded) { gfx::ImageSkia arrow = gfx::CreateVectorIcon( vector_icons::kSubmenuArrowIcon, color_utils::DeriveDefaultIconColor( drawing_provider()->GetTextColorForNode(this, nullptr))); if (expanded) { arrow = gfx::ImageSkiaOperations::CreateRotatedImage( arrow, base::i18n::IsRTL() ? SkBitmapOperations::ROTATION_270_CW : SkBitmapOperations::ROTATION_90_CW); } gfx::Rect arrow_bounds = node_bounds; arrow_bounds.Inset( gfx::Insets::VH((node_bounds.height() - arrow.height()) / 2, (kArrowRegionSize - arrow.width()) / 2)); canvas->DrawImageInt(arrow, base::i18n::IsRTL() ? arrow_bounds.right() - arrow.width() : arrow_bounds.x(), arrow_bounds.y()); } void TreeView::PaintNodeIcon(gfx::Canvas* canvas, InternalNode* node, const gfx::Rect& bounds) { absl::optional<size_t> icon_index = model_->GetIconIndex(node->model_node()); int icon_x = kArrowRegionSize + kImagePadding; if (!icon_index.has_value()) { // Flip just the |bounds| region of |canvas|. gfx::ScopedCanvas scoped_canvas(canvas); canvas->Translate(gfx::Vector2d(bounds.x(), 0)); scoped_canvas.FlipIfRTL(bounds.width()); // Now paint the icon local to that flipped region. PaintRowIcon(canvas, (node->is_expanded() ? open_icon_ : closed_icon_) .Rasterize(GetColorProvider()), icon_x, gfx::Rect(0, bounds.y(), bounds.width(), bounds.height())); } else { const gfx::ImageSkia& icon = icons_[icon_index.value()].Rasterize(GetColorProvider()); icon_x += (open_icon_.Size().width() - icon.width()) / 2; if (base::i18n::IsRTL()) icon_x = bounds.width() - icon_x - icon.width(); PaintRowIcon(canvas, icon, icon_x, bounds); } } TreeView::InternalNode* TreeView::GetInternalNodeForModelNode( ui::TreeModelNode* model_node, GetInternalNodeCreateType create_type) { if (model_node == root_.model_node()) return &root_; InternalNode* parent_internal_node = GetInternalNodeForModelNode(model_->GetParent(model_node), create_type); if (!parent_internal_node) return nullptr; if (!parent_internal_node->loaded_children()) { if (create_type == DONT_CREATE_IF_NOT_LOADED) return nullptr; LoadChildren(parent_internal_node); } size_t index = model_->GetIndexOf(parent_internal_node->model_node(), model_node) .value(); return parent_internal_node->children()[index].get(); } TreeView::InternalNode* TreeView::GetInternalNodeForVirtualView( AXVirtualView* ax_view) { if (ax_view == root_.accessibility_view()) return &root_; DCHECK(ax_view); InternalNode* parent_internal_node = GetInternalNodeForVirtualView(ax_view->virtual_parent_view()); if (!parent_internal_node) return nullptr; DCHECK(parent_internal_node->loaded_children()); AXVirtualView* parent_ax_view = parent_internal_node->accessibility_view(); DCHECK(parent_ax_view); auto index = parent_ax_view->GetIndexOf(ax_view); return parent_internal_node->children()[index.value()].get(); } gfx::Rect TreeView::GetBoundsForNode(InternalNode* node) { int row, ignored_depth; row = GetRowForInternalNode(node, &ignored_depth); return gfx::Rect(0, row * row_height_, width(), row_height_); } gfx::Rect TreeView::GetBackgroundBoundsForNode(InternalNode* node) { return PlatformStyle::kTreeViewSelectionPaintsEntireRow ? GetBoundsForNode(node) : GetForegroundBoundsForNode(node); } gfx::Rect TreeView::GetForegroundBoundsForNode(InternalNode* node) { int row, depth; row = GetRowForInternalNode(node, &depth); return GetForegroundBoundsForNodeImpl(node, row, depth); } gfx::Rect TreeView::GetTextBoundsForNode(InternalNode* node) { gfx::Rect bounds(GetForegroundBoundsForNode(node)); if (drawing_provider()->ShouldDrawIconForNode(this, node->model_node())) bounds.Inset(gfx::Insets::TLBR(0, text_offset_, 0, 0)); else bounds.Inset(gfx::Insets::TLBR(0, kArrowRegionSize, 0, 0)); return bounds; } // The auxiliary text for a node can use all the parts of the row's bounds that // are logical-after the row's text, and is aligned opposite to the row's text - // that is, in LTR locales it is trailing aligned, and in RTL locales it is // leading aligned. gfx::Rect TreeView::GetAuxiliaryTextBoundsForNode(InternalNode* node) { gfx::Rect text_bounds = GetTextBoundsForNode(node); int width = base::i18n::IsRTL() ? text_bounds.x() - kTextHorizontalPadding - kAuxiliaryTextLineEndPadding : bounds().width() - text_bounds.right() - kTextHorizontalPadding - kAuxiliaryTextLineEndPadding; if (width < 0) return gfx::Rect(); int x = base::i18n::IsRTL() ? kAuxiliaryTextLineEndPadding : bounds().right() - width - kAuxiliaryTextLineEndPadding; return gfx::Rect(x, text_bounds.y(), width, text_bounds.height()); } gfx::Rect TreeView::GetForegroundBoundsForNodeImpl(InternalNode* node, int row, int depth) { int width = drawing_provider()->ShouldDrawIconForNode(this, node->model_node()) ? text_offset_ + node->text_width() + kTextHorizontalPadding * 2 : kArrowRegionSize + node->text_width() + kTextHorizontalPadding * 2; gfx::Rect rect(depth * kIndent + kHorizontalInset, row * row_height_, width, row_height_); rect.set_x(GetMirroredXWithWidthInView(rect.x(), rect.width())); return rect; } int TreeView::GetRowForInternalNode(InternalNode* node, int* depth) { DCHECK(!node->parent() || IsExpanded(node->parent()->model_node())); *depth = -1; int row = -1; const InternalNode* tmp_node = node; while (tmp_node->parent()) { size_t index_in_parent = tmp_node->parent()->GetIndexOf(tmp_node).value(); (*depth)++; row++; // For node. for (size_t i = 0; i < index_in_parent; ++i) { row += static_cast<int>( tmp_node->parent()->children()[i]->NumExpandedNodes()); } tmp_node = tmp_node->parent(); } if (root_shown_) { (*depth)++; row++; } return row; } TreeView::InternalNode* TreeView::GetNodeAtPoint(const gfx::Point& point) { int row = point.y() / row_height_; int depth = -1; InternalNode* node = GetNodeByRow(row, &depth); if (!node) return nullptr; // If the entire row gets a selected background, clicking anywhere in the row // serves to hit this node. if (PlatformStyle::kTreeViewSelectionPaintsEntireRow) return node; gfx::Rect bounds(GetForegroundBoundsForNodeImpl(node, row, depth)); return bounds.Contains(point) ? node : nullptr; } TreeView::InternalNode* TreeView::GetNodeByRow(int row, int* depth) { int current_row = root_row(); *depth = 0; return GetNodeByRowImpl(&root_, row, root_depth(), &current_row, depth); } TreeView::InternalNode* TreeView::GetNodeByRowImpl(InternalNode* node, int target_row, int current_depth, int* current_row, int* node_depth) { if (*current_row == target_row) { *node_depth = current_depth; return node; } (*current_row)++; if (node->is_expanded()) { current_depth++; for (const auto& child : node->children()) { InternalNode* result = GetNodeByRowImpl( child.get(), target_row, current_depth, current_row, node_depth); if (result) return result; } } return nullptr; } void TreeView::IncrementSelection(IncrementType type) { if (!model_) return; if (!active_node_) { // If nothing is selected select the first or last node. if (root_.children().empty()) return; if (type == IncrementType::kPrevious) { size_t row_count = GetRowCount(); int depth = 0; DCHECK(row_count); InternalNode* node = GetNodeByRow(static_cast<int>(row_count - 1), &depth); SetSelectedNode(node->model_node()); } else if (root_shown_) { SetSelectedNode(root_.model_node()); } else { SetSelectedNode(root_.children().front()->model_node()); } return; } int depth = 0; int delta = type == IncrementType::kPrevious ? -1 : 1; int row = GetRowForInternalNode(active_node_, &depth); int new_row = std::clamp(row + delta, 0, base::checked_cast<int>(GetRowCount()) - 1); if (new_row == row) return; // At the end/beginning. SetSelectedNode(GetNodeByRow(new_row, &depth)->model_node()); } void TreeView::CollapseOrSelectParent() { if (active_node_) { if (active_node_->is_expanded()) Collapse(active_node_->model_node()); else if (active_node_->parent()) SetSelectedNode(active_node_->parent()->model_node()); } } void TreeView::ExpandOrSelectChild() { if (active_node_) { if (!active_node_->is_expanded()) Expand(active_node_->model_node()); else if (!active_node_->children().empty()) SetSelectedNode(active_node_->children().front()->model_node()); } } bool TreeView::ExpandImpl(TreeModelNode* model_node) { TreeModelNode* parent = model_->GetParent(model_node); if (!parent) { // Node should be the root. DCHECK_EQ(root_.model_node(), model_node); bool was_expanded = root_.is_expanded(); root_.set_is_expanded(true); return !was_expanded; } // Expand all the parents. bool return_value = ExpandImpl(parent); InternalNode* internal_node = GetInternalNodeForModelNode(model_node, CREATE_IF_NOT_LOADED); DCHECK(internal_node); if (!internal_node->is_expanded()) { if (!internal_node->loaded_children()) LoadChildren(internal_node); internal_node->set_is_expanded(true); return_value = true; } return return_value; } PrefixSelector* TreeView::GetPrefixSelector() { if (!selector_) selector_ = std::make_unique<PrefixSelector>(this, this); return selector_.get(); } bool TreeView::IsPointInExpandControl(InternalNode* node, const gfx::Point& point) { if (model_->GetChildren(node->model_node()).empty()) return false; int depth = -1; int row = GetRowForInternalNode(node, &depth); int arrow_dx = depth * kIndent + kHorizontalInset; gfx::Rect arrow_bounds(arrow_dx, row * row_height_, kArrowRegionSize, row_height_); if (base::i18n::IsRTL()) arrow_bounds.set_x(width() - arrow_dx - kArrowRegionSize); return arrow_bounds.Contains(point); } void TreeView::SetHasFocusIndicator(bool shows) { // If this View is the grandchild of a ScrollView, use the grandparent // ScrollView for the focus ring instead of this View so that the focus ring // won't be scrolled. ScrollView* scroll_view = ScrollView::GetScrollViewForContents(this); if (scroll_view) scroll_view->SetHasFocusIndicator(shows); } // InternalNode ---------------------------------------------------------------- TreeView::InternalNode::InternalNode() = default; TreeView::InternalNode::~InternalNode() = default; void TreeView::InternalNode::Reset(ui::TreeModelNode* node) { model_node_ = node; loaded_children_ = false; is_expanded_ = false; text_width_ = 0; accessibility_view_ = nullptr; } size_t TreeView::InternalNode::NumExpandedNodes() const { size_t result = 1; // For this. if (!is_expanded_) return result; for (const auto& child : children()) result += child->NumExpandedNodes(); return result; } int TreeView::InternalNode::GetMaxWidth(TreeView* tree, int indent, int depth) { bool has_icon = tree->drawing_provider()->ShouldDrawIconForNode(tree, model_node()); int max_width = (has_icon ? text_width_ : kArrowRegionSize) + indent * depth; if (!is_expanded_) return max_width; for (const auto& child : children()) { max_width = std::max(max_width, child->GetMaxWidth(tree, indent, depth + 1)); } return max_width; } BEGIN_METADATA(TreeView, View) END_METADATA } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/tree/tree_view.cc
C++
unknown
51,887
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_CONTROLS_TREE_TREE_VIEW_H_ #define UI_VIEWS_CONTROLS_TREE_TREE_VIEW_H_ #include <memory> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/base/models/image_model.h" #include "ui/base/models/tree_node_model.h" #include "ui/gfx/font_list.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/prefix_delegate.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/controls/tree/tree_view_drawing_provider.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" namespace ui { struct AXActionData; struct AXNodeData; } // namespace ui namespace gfx { class Rect; } // namespace gfx namespace views { class AXVirtualView; class PrefixSelector; class ScrollView; class Textfield; class TreeViewController; // TreeView displays hierarchical data as returned from a TreeModel. The user // can expand, collapse and edit the items. A Controller may be attached to // receive notification of selection changes and restrict editing. // // In addition to tracking selection, TreeView also tracks the active node, // which is the item that receives keyboard input when the tree has focus. // Active/focus is like a pointer for keyboard navigation, and operations such // as selection are performed at the point of focus. The active node is synced // to the selected node. When the active node is nullptr, the TreeView itself is // the target of keyboard input. // // Note on implementation. This implementation doesn't scale well. In particular // it does not store any row information, but instead calculates it as // necessary. But it's more than adequate for current uses. class VIEWS_EXPORT TreeView : public View, public ui::TreeModelObserver, public TextfieldController, public FocusChangeListener, public PrefixDelegate { public: METADATA_HEADER(TreeView); TreeView(); TreeView(const TreeView&) = delete; TreeView& operator=(const TreeView&) = delete; ~TreeView() override; // Returns a new ScrollView that contains the given |tree|. static std::unique_ptr<ScrollView> CreateScrollViewWithTree( std::unique_ptr<TreeView> tree); // Sets the model. TreeView does not take ownership of the model. void SetModel(ui::TreeModel* model); ui::TreeModel* model() const { return model_; } // Sets whether to automatically expand children when a parent node is // expanded. The default is false. If true, when a node in the tree is // expanded for the first time, its children are also automatically expanded. // If a node is subsequently collapsed and expanded again, the children // will not be automatically expanded. void set_auto_expand_children(bool auto_expand_children) { auto_expand_children_ = auto_expand_children; } // Sets whether the user can edit the nodes. The default is true. If true, // the Controller is queried to determine if a particular node can be edited. void SetEditable(bool editable); // Edits the specified node. This cancels the current edit and expands all // parents of node. void StartEditing(ui::TreeModelNode* node); // Cancels the current edit. Does nothing if not editing. void CancelEdit(); // Commits the current edit. Does nothing if not editing. void CommitEdit(); // If the user is editing a node, it is returned. If the user is not // editing a node, NULL is returned. ui::TreeModelNode* GetEditingNode(); // Selects the specified node. This expands all the parents of node. void SetSelectedNode(ui::TreeModelNode* model_node); // Returns the selected node, or nullptr if nothing is selected. ui::TreeModelNode* GetSelectedNode() { return const_cast<ui::TreeModelNode*>( const_cast<const TreeView*>(this)->GetSelectedNode()); } const ui::TreeModelNode* GetSelectedNode() const; // Marks the specified node as active, scrolls it into view, and reports a // keyboard focus update to ATs. Active node should be synced to the selected // node and should be nullptr when the tree is empty. // TODO(crbug.com/1080944): Decouple active node from selected node by adding // new keyboard affordances. void SetActiveNode(ui::TreeModelNode* model_node); // Returns the active node, or nullptr if nothing is active. ui::TreeModelNode* GetActiveNode() { return const_cast<ui::TreeModelNode*>( const_cast<const TreeView*>(this)->GetActiveNode()); } const ui::TreeModelNode* GetActiveNode() const; // Marks |model_node| as collapsed. This only effects the UI if node and all // its parents are expanded (IsExpanded(model_node) returns true). void Collapse(ui::TreeModelNode* model_node); // Make sure node and all its parents are expanded. void Expand(ui::TreeModelNode* node); // Invoked from ExpandAll(). Expands the supplied node and recursively // invokes itself with all children. void ExpandAll(ui::TreeModelNode* node); // Returns true if the specified node is expanded. bool IsExpanded(ui::TreeModelNode* model_node); // Sets whether the root is shown. If true, the root node of the tree is // shown, if false only the children of the root are shown. The default is // true. void SetRootShown(bool root_visible); // Sets the controller, which may be null. TreeView does not take ownership // of the controller. void SetController(TreeViewController* controller) { controller_ = controller; } // Returns the node for the specified row, or NULL for an invalid row index. ui::TreeModelNode* GetNodeForRow(int row); // Maps a node to a row, returns -1 if node is not valid. int GetRowForNode(ui::TreeModelNode* node); Textfield* editor() { return editor_; } // Replaces this TreeView's TreeViewDrawingProvider with |provider|. void SetDrawingProvider(std::unique_ptr<TreeViewDrawingProvider> provider); TreeViewDrawingProvider* drawing_provider() { return drawing_provider_.get(); } // View overrides: void Layout() override; gfx::Size CalculatePreferredSize() const override; bool AcceleratorPressed(const ui::Accelerator& accelerator) override; bool OnMousePressed(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; void ShowContextMenu(const gfx::Point& p, ui::MenuSourceType source_type) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; bool HandleAccessibleAction(const ui::AXActionData& action_data) override; // TreeModelObserver overrides: void TreeNodesAdded(ui::TreeModel* model, ui::TreeModelNode* parent, size_t start, size_t count) override; void TreeNodesRemoved(ui::TreeModel* model, ui::TreeModelNode* parent, size_t start, size_t count) override; void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* model_node) override; // TextfieldController overrides: void ContentsChanged(Textfield* sender, const std::u16string& new_contents) override; bool HandleKeyEvent(Textfield* sender, const ui::KeyEvent& key_event) override; // FocusChangeListener overrides: void OnWillChangeFocus(View* focused_before, View* focused_now) override; void OnDidChangeFocus(View* focused_before, View* focused_now) override; // PrefixDelegate overrides: size_t GetRowCount() override; absl::optional<size_t> GetSelectedRow() override; void SetSelectedRow(absl::optional<size_t> row) override; std::u16string GetTextForRow(size_t row) override; protected: // View overrides: gfx::Point GetKeyboardContextMenuLocation() override; bool OnKeyPressed(const ui::KeyEvent& event) override; void OnPaint(gfx::Canvas* canvas) override; void OnFocus() override; void OnBlur() override; private: friend class TreeViewTest; // Enumeration of possible changes to tree view state when the UI is updated. enum class SelectionType { // Active state is being set to a tree item. kActive, // Active and selected states are being set to a tree item. kActiveAndSelected, }; // Performs active node and selected node state transitions. Updates states // and scrolling before notifying assistive technologies and the controller. void UpdateSelection(ui::TreeModelNode* model_node, SelectionType selection_type); // Selects, expands or collapses nodes in the tree. Consistent behavior for // tap gesture and click events. bool OnClickOrTap(const ui::LocatedEvent& event); // InternalNode is used to track information about the set of nodes displayed // by TreeViewViews. class InternalNode : public ui::TreeNode<InternalNode> { public: InternalNode(); InternalNode(const InternalNode&) = delete; InternalNode& operator=(const InternalNode&) = delete; ~InternalNode() override; // Resets the state from |node|. void Reset(ui::TreeModelNode* node); // The model node this InternalNode represents. ui::TreeModelNode* model_node() { return model_node_; } // Gets or sets a virtual accessibility view that is used to expose // information about this node to assistive software. // // This is a weak pointer. This class doesn't own its virtual accessibility // view but the Views system does. void set_accessibility_view(AXVirtualView* accessibility_view) { accessibility_view_ = accessibility_view; } AXVirtualView* accessibility_view() const { return accessibility_view_; } // Whether the node is expanded. void set_is_expanded(bool expanded) { is_expanded_ = expanded; } bool is_expanded() const { return is_expanded_; } // Whether children have been loaded. void set_loaded_children(bool value) { loaded_children_ = value; } bool loaded_children() const { return loaded_children_; } // Width needed to display the string. void set_text_width(int width) { text_width_ = width; } int text_width() const { return text_width_; } // Returns the total number of descendants (including this node). size_t NumExpandedNodes() const; // Returns the max width of all descendants (including this node). |indent| // is how many pixels each child is indented and |depth| is the depth of // this node from its parent. The tree this node is being placed inside is // |tree|. int GetMaxWidth(TreeView* tree, int indent, int depth); private: // The node from the model. raw_ptr<ui::TreeModelNode, DanglingUntriaged> model_node_ = nullptr; // A virtual accessibility view that is used to expose information about // this node to assistive software. // // This is a weak pointer. This class doesn't own its virtual accessibility // view but the Views system does. raw_ptr<AXVirtualView, DanglingUntriaged> accessibility_view_ = nullptr; // Whether the children have been loaded. bool loaded_children_ = false; bool is_expanded_ = false; int text_width_ = 0; }; // Used by GetInternalNodeForModelNode. enum GetInternalNodeCreateType { // If an InternalNode hasn't been created yet, create it. CREATE_IF_NOT_LOADED, // Don't create an InternalNode if one hasn't been created yet. DONT_CREATE_IF_NOT_LOADED, }; // Used by IncrementSelection. enum class IncrementType { // Selects the next node. kNext, // Selects the previous node. kPrevious }; // Row of the root node. This varies depending upon whether the root is // visible. int root_row() const { return root_shown_ ? 0 : -1; } // Depth of the root node. int root_depth() const { return root_shown_ ? 0 : -1; } // Loads the children of the specified node. void LoadChildren(InternalNode* node); // Configures an InternalNode from a node from the model. This is used // when a node changes as well as when loading. void ConfigureInternalNode(ui::TreeModelNode* model_node, InternalNode* node); // Returns whether the given node is the root. bool IsRoot(const InternalNode* node) const; // Sets |node|s text_width. void UpdateNodeTextWidth(InternalNode* node); // Creates a virtual accessibility view that is used to expose information // about this node to assistive software. // // Also attaches the newly created virtual accessibility view to the internal // node. std::unique_ptr<AXVirtualView> CreateAndSetAccessibilityView( InternalNode* node); // Populates the accessibility data for a tree item. This is data that can // dynamically change, such as whether a tree item is expanded, and if it's // visible. void PopulateAccessibilityData(InternalNode* node, ui::AXNodeData* data); // Invoked when the set of drawn nodes changes. void DrawnNodesChanged(); // Updates |preferred_size_| from the state of the UI. void UpdatePreferredSize(); // Positions |editor_|. void LayoutEditor(); // Schedules a paint for |node|. void SchedulePaintForNode(InternalNode* node); // Recursively paints rows from |min_row| to |max_row|. |node| is the node for // the row |*row|. |row| is updated as this walks the tree. Depth is the depth // of |*row|. void PaintRows(gfx::Canvas* canvas, int min_row, int max_row, InternalNode* node, int depth, int* row); // Invoked to paint a single node. void PaintRow(gfx::Canvas* canvas, InternalNode* node, int row, int depth); // Paints the expand control given the specified nodes bounds. void PaintExpandControl(gfx::Canvas* canvas, const gfx::Rect& node_bounds, bool expanded); // Paints the icon for the specified |node| in |bounds| to |canvas|. void PaintNodeIcon(gfx::Canvas* canvas, InternalNode* node, const gfx::Rect& bounds); // Returns the InternalNode for a model node. |create_type| indicates whether // this should load InternalNode or not. InternalNode* GetInternalNodeForModelNode( ui::TreeModelNode* model_node, GetInternalNodeCreateType create_type); // Returns the InternalNode for a virtual view. InternalNode* GetInternalNodeForVirtualView(AXVirtualView* ax_view); // Returns the bounds for a node. This rectangle contains the node's icon, // text, arrow, and auxiliary text (if any). All of the other bounding // rectangles computed by the functions below lie inside this rectangle. gfx::Rect GetBoundsForNode(InternalNode* node); // Returns the bounds for a node's background. gfx::Rect GetBackgroundBoundsForNode(InternalNode* node); // Return the bounds for a node's foreground, which is the part containing the // expand/collapse symbol (if any), the icon (if any), and the text label. gfx::Rect GetForegroundBoundsForNode(InternalNode* node); // Returns the bounds for a node's text label. gfx::Rect GetTextBoundsForNode(InternalNode* node); // Returns the bounds of a node's auxiliary text label. gfx::Rect GetAuxiliaryTextBoundsForNode(InternalNode* node); // Implementation of GetTextBoundsForNode. Separated out as some callers // already know the row/depth. gfx::Rect GetForegroundBoundsForNodeImpl(InternalNode* node, int row, int depth); // Returns the row and depth of a node. int GetRowForInternalNode(InternalNode* node, int* depth); // Returns the InternalNode (if any) whose foreground bounds contain |point|. // If no node's foreground contains |point|, this function returns nullptr. InternalNode* GetNodeAtPoint(const gfx::Point& point); // Returns the row and depth of the specified node. InternalNode* GetNodeByRow(int row, int* depth); // Implementation of GetNodeByRow. |current_row| is updated as we iterate. InternalNode* GetNodeByRowImpl(InternalNode* node, int target_row, int current_depth, int* current_row, int* node_depth); // Increments the selection. Invoked in response to up/down arrow. void IncrementSelection(IncrementType type); // If the current node is expanded, it's collapsed, otherwise selection is // moved to the parent. void CollapseOrSelectParent(); // If the selected node is collapsed, it's expanded. Otherwise the first child // is selected. void ExpandOrSelectChild(); // Implementation of Expand(). Returns true if at least one node was expanded // that previously wasn't. bool ExpandImpl(ui::TreeModelNode* model_node); PrefixSelector* GetPrefixSelector(); // Returns whether |point| is in the bounds of |node|'s expand/collapse // control. bool IsPointInExpandControl(InternalNode* node, const gfx::Point& point); // Sets whether a focus indicator is visible on this control or not. void SetHasFocusIndicator(bool); // The model, may be null. raw_ptr<ui::TreeModel> model_ = nullptr; // Default icons for closed/open. ui::ImageModel closed_icon_; ui::ImageModel open_icon_; // Icons from the model. std::vector<ui::ImageModel> icons_; // The root node. InternalNode root_; // The selected node, may be null. raw_ptr<InternalNode, DanglingUntriaged> selected_node_ = nullptr; // The current active node, may be null. raw_ptr<InternalNode, DanglingUntriaged> active_node_ = nullptr; bool editing_ = false; // The editor; lazily created and never destroyed (well, until TreeView is // destroyed). Hidden when no longer editing. We do this to avoid destruction // problems. raw_ptr<Textfield> editor_ = nullptr; // Preferred size of |editor_| with no content. gfx::Size empty_editor_size_; // If non-NULL we've attached a listener to this focus manager. Used to know // when focus is changing to another view so that we can cancel the edit. raw_ptr<FocusManager> focus_manager_ = nullptr; // Whether to automatically expand children when a parent node is expanded. bool auto_expand_children_ = false; // Whether the user can edit the items. bool editable_ = true; // The controller. raw_ptr<TreeViewController> controller_ = nullptr; // Whether or not the root is shown in the tree. bool root_shown_ = true; // Cached preferred size. gfx::Size preferred_size_; // Font list used to display text. gfx::FontList font_list_; // Height of each row. Based on font and some padding. int row_height_; // Offset the text is drawn at. This accounts for the size of the expand // control, icon and offsets. int text_offset_; std::unique_ptr<PrefixSelector> selector_; // The current drawing provider for this TreeView. std::unique_ptr<TreeViewDrawingProvider> drawing_provider_; }; } // namespace views #endif // UI_VIEWS_CONTROLS_TREE_TREE_VIEW_H_
Zhao-PengFei35/chromium_src_4
ui/views/controls/tree/tree_view.h
C++
unknown
19,277
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/tree/tree_view_controller.h" #include "ui/base/models/tree_model.h" #include "ui/views/controls/tree/tree_view.h" namespace views { bool TreeViewController::CanEdit(TreeView* tree_view, ui::TreeModelNode* node) { return true; } TreeViewController::~TreeViewController() = default; } // namespace views
Zhao-PengFei35/chromium_src_4
ui/views/controls/tree/tree_view_controller.cc
C++
unknown
482