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.
#ifndef UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_
#define UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/views/views_export.h"
namespace ui {
class TreeModelNode;
}
namespace views {
class TreeView;
// TreeViewController ---------------------------------------------------------
// Controller for the treeview.
class VIEWS_EXPORT TreeViewController {
public:
// Notification that the selection of the tree view has changed. Use
// GetSelectedNode to find the current selection.
virtual void OnTreeViewSelectionChanged(TreeView* tree_view) = 0;
// Returns true if the node can be edited. This is only used if the
// TreeView is editable.
virtual bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node);
protected:
virtual ~TreeViewController();
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/tree/tree_view_controller.h | C++ | unknown | 1,065 |
// 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/tree/tree_view_drawing_provider.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/views/controls/tree/tree_view.h"
namespace views {
TreeViewDrawingProvider::TreeViewDrawingProvider() = default;
TreeViewDrawingProvider::~TreeViewDrawingProvider() = default;
SkColor TreeViewDrawingProvider::GetBackgroundColorForNode(
TreeView* tree_view,
ui::TreeModelNode* node) {
ui::ColorId color_id = (tree_view->HasFocus() || tree_view->GetEditingNode())
? ui::kColorTreeNodeBackgroundSelectedFocused
: ui::kColorTreeNodeBackgroundSelectedUnfocused;
return tree_view->GetColorProvider()->GetColor(color_id);
}
SkColor TreeViewDrawingProvider::GetTextColorForNode(TreeView* tree_view,
ui::TreeModelNode* node) {
ui::ColorId color_id = ui::kColorTreeNodeForeground;
if (tree_view->GetSelectedNode() == node) {
color_id = tree_view->HasFocus()
? ui::kColorTreeNodeForegroundSelectedFocused
: ui::kColorTreeNodeForegroundSelectedUnfocused;
}
return tree_view->GetColorProvider()->GetColor(color_id);
}
SkColor TreeViewDrawingProvider::GetAuxiliaryTextColorForNode(
TreeView* tree_view,
ui::TreeModelNode* node) {
// Default to using the same color as the primary text.
return GetTextColorForNode(tree_view, node);
}
std::u16string TreeViewDrawingProvider::GetAuxiliaryTextForNode(
TreeView* tree_view,
ui::TreeModelNode* node) {
return std::u16string();
}
bool TreeViewDrawingProvider::ShouldDrawIconForNode(TreeView* tree_view,
ui::TreeModelNode* node) {
return true;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/tree/tree_view_drawing_provider.cc | C++ | unknown | 1,942 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_TREE_TREE_VIEW_DRAWING_PROVIDER_H_
#define UI_VIEWS_CONTROLS_TREE_TREE_VIEW_DRAWING_PROVIDER_H_
#include <string>
#include "third_party/skia/include/core/SkColor.h"
#include "ui/views/views_export.h"
namespace ui {
class TreeModelNode;
}
namespace views {
class TreeView;
// This class is responsible for customizing the appearance of a TreeView.
// Install an instance of it into a TreeView using
// |TreeView::SetDrawingProvider|.
class VIEWS_EXPORT TreeViewDrawingProvider {
public:
TreeViewDrawingProvider();
virtual ~TreeViewDrawingProvider();
// These methods return the colors that should be used to draw specific parts
// of the node |node| in TreeView |tree_view|.
virtual SkColor GetBackgroundColorForNode(TreeView* tree_view,
ui::TreeModelNode* node);
virtual SkColor GetTextColorForNode(TreeView* tree_view,
ui::TreeModelNode* node);
virtual SkColor GetAuxiliaryTextColorForNode(TreeView* tree_view,
ui::TreeModelNode* node);
// The auxiliary text for a node is descriptive text drawn on the trailing end
// of the node's row in the treeview.
virtual std::u16string GetAuxiliaryTextForNode(TreeView* tree_view,
ui::TreeModelNode* node);
// This method returns whether the icon for |node| should be drawn.
virtual bool ShouldDrawIconForNode(TreeView* tree_view,
ui::TreeModelNode* node);
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_TREE_TREE_VIEW_DRAWING_PROVIDER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/tree/tree_view_drawing_provider.h | C++ | unknown | 1,809 |
// 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 <numeric>
#include <string>
#include <utility>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.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/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/base/models/tree_node_model.h"
#include "ui/compositor/canvas_painter.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include "ui/views/controls/prefix_selector.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/tree/tree_view_controller.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"
using ui::TreeModel;
using ui::TreeModelNode;
using ui::TreeNode;
using base::ASCIIToUTF16;
namespace views {
namespace {
std::string AccessibilityViewAsString(const AXVirtualView& view) {
std::string result =
view.GetData().GetStringAttribute(ax::mojom::StringAttribute::kName);
if (!view.GetChildCount() ||
view.GetData().HasState(ax::mojom::State::kCollapsed)) {
// We don't descend into collapsed nodes because they are invisible.
return result;
}
result += " [";
for (const auto& child_view : view.children()) {
result += AccessibilityViewAsString(*child_view) + " ";
}
result.pop_back();
result += "]";
return result;
}
} // namespace
class TestNode : public TreeNode<TestNode> {
public:
TestNode() = default;
TestNode(const TestNode&) = delete;
TestNode& operator=(const TestNode&) = delete;
~TestNode() override = default;
};
// Creates the following structure:
// 'root'
// 'a'
// 'b'
// 'b1'
// 'c'
class TreeViewTest : public ViewsTestBase {
public:
TreeViewTest() : model_(std::make_unique<TestNode>()) {
static_cast<TestNode*>(model_.GetRoot())->SetTitle(u"root");
Add(model_.GetRoot(), 0, "a");
Add(Add(model_.GetRoot(), 1, "b"), 0, "b1");
Add(model_.GetRoot(), 2, "c");
}
TreeViewTest(const TreeViewTest&) = delete;
TreeViewTest& operator=(const TreeViewTest&) = delete;
// ViewsTestBase
void SetUp() override;
void TearDown() override;
protected:
using AccessibilityEventsVector = std::vector<
std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>>;
const AccessibilityEventsVector accessibility_events() const {
return accessibility_events_;
}
void ClearAccessibilityEvents();
TestNode* Add(TestNode* parent, size_t index, const std::string& title);
std::string TreeViewContentsAsString();
std::string TreeViewAccessibilityContentsAsString() const;
// Gets the selected node from the tree view. The result can be compared with
// GetSelectedAccessibilityViewName() to check consistency between the tree
// view state and the accessibility data.
std::string GetSelectedNodeTitle();
// Finds the selected node via iterative depth first search over the internal
// accessibility tree, examining both ignored and unignored nodes. The result
// can be compared with GetSelectedNodeTitle() to check consistency between
// the tree view state and the accessibility data.
std::string GetSelectedAccessibilityViewName() const;
// Gets the active node from the tree view. The result can be compared with
// GetSelectedAccessibilityViewName() to check consistency between the tree
// view state and the accessibility data.
std::string GetActiveNodeTitle();
// Gets the active node from the tree view's |ViewAccessibility|. The result
// can be compared with GetSelectedNodeTitle() to check consistency between
// the tree view internal state and the accessibility data.
std::string GetActiveAccessibilityViewName() const;
std::string GetEditingNodeTitle();
AXVirtualView* GetRootAccessibilityView() const;
ViewAXPlatformNodeDelegate* GetTreeAccessibilityView() const;
TestNode* GetNodeByTitle(const std::string& title);
const AXVirtualView* GetAccessibilityViewByName(
const std::string& name) const;
void IncrementSelection(bool next);
void CollapseOrSelectParent();
void ExpandOrSelectChild();
size_t GetRowCount();
PrefixSelector* selector() { return tree_->GetPrefixSelector(); }
ui::TreeNodeModel<TestNode> model_;
raw_ptr<TreeView> tree_;
UniqueWidgetPtr widget_;
private:
std::string InternalNodeAsString(TreeView::InternalNode* node);
TestNode* GetNodeByTitleImpl(TestNode* node, const std::u16string& title);
// Keeps a record of all accessibility events that have been fired on the tree
// view.
AccessibilityEventsVector accessibility_events_;
};
void TreeViewTest::SetUp() {
ViewsTestBase::SetUp();
widget_ = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget_->Init(std::move(params));
tree_ = widget_->SetContentsView(std::make_unique<TreeView>());
tree_->RequestFocus();
ViewAccessibility::AccessibilityEventsCallback accessibility_events_callback =
base::BindRepeating(
[](std::vector<std::pair<const ui::AXPlatformNodeDelegate*,
const ax::mojom::Event>>*
accessibility_events,
const ui::AXPlatformNodeDelegate* delegate,
const ax::mojom::Event event_type) {
DCHECK(accessibility_events);
accessibility_events->push_back({delegate, event_type});
},
&accessibility_events_);
tree_->GetViewAccessibility().set_accessibility_events_callback(
std::move(accessibility_events_callback));
}
void TreeViewTest::TearDown() {
widget_.reset();
ViewsTestBase::TearDown();
}
void TreeViewTest::ClearAccessibilityEvents() {
accessibility_events_.clear();
}
TestNode* TreeViewTest::Add(TestNode* parent,
size_t index,
const std::string& title) {
std::unique_ptr<TestNode> new_node = std::make_unique<TestNode>();
new_node->SetTitle(ASCIIToUTF16(title));
return model_.Add(parent, std::move(new_node), index);
}
std::string TreeViewTest::TreeViewContentsAsString() {
return InternalNodeAsString(&tree_->root_);
}
std::string TreeViewTest::TreeViewAccessibilityContentsAsString() const {
AXVirtualView* ax_view = GetRootAccessibilityView();
if (!ax_view)
return "Empty";
return AccessibilityViewAsString(*ax_view);
}
std::string TreeViewTest::GetSelectedNodeTitle() {
TreeModelNode* model_node = tree_->GetSelectedNode();
return model_node ? base::UTF16ToASCII(model_node->GetTitle())
: std::string();
}
std::string TreeViewTest::GetSelectedAccessibilityViewName() const {
const AXVirtualView* ax_view = GetRootAccessibilityView();
while (ax_view) {
if (ax_view->GetData().GetBoolAttribute(
ax::mojom::BoolAttribute::kSelected)) {
return ax_view->GetData().GetStringAttribute(
ax::mojom::StringAttribute::kName);
}
if (ax_view->children().size()) {
ax_view = ax_view->children()[0].get();
continue;
}
const AXVirtualView* parent_view = ax_view->virtual_parent_view();
while (parent_view) {
size_t sibling_index_in_parent =
parent_view->GetIndexOf(ax_view).value() + 1;
if (sibling_index_in_parent < parent_view->children().size()) {
ax_view = parent_view->children()[sibling_index_in_parent].get();
break;
}
ax_view = parent_view;
parent_view = parent_view->virtual_parent_view();
}
if (!parent_view)
break;
}
return {};
}
std::string TreeViewTest::GetActiveNodeTitle() {
TreeModelNode* model_node = tree_->GetActiveNode();
return model_node ? base::UTF16ToASCII(model_node->GetTitle())
: std::string();
}
std::string TreeViewTest::GetActiveAccessibilityViewName() const {
const AXVirtualView* ax_view =
tree_->GetViewAccessibility().FocusedVirtualChild();
return ax_view ? ax_view->GetData().GetStringAttribute(
ax::mojom::StringAttribute::kName)
: std::string();
}
std::string TreeViewTest::GetEditingNodeTitle() {
TreeModelNode* model_node = tree_->GetEditingNode();
return model_node ? base::UTF16ToASCII(model_node->GetTitle())
: std::string();
}
AXVirtualView* TreeViewTest::GetRootAccessibilityView() const {
return tree_->root_.accessibility_view();
}
ViewAXPlatformNodeDelegate* TreeViewTest::GetTreeAccessibilityView() const {
#if !BUILDFLAG_INTERNAL_HAS_NATIVE_ACCESSIBILITY()
return nullptr; // ViewAXPlatformNodeDelegate is not used on this platform.
#else
return static_cast<ViewAXPlatformNodeDelegate*>(
&(tree_->GetViewAccessibility()));
#endif
}
TestNode* TreeViewTest::GetNodeByTitle(const std::string& title) {
return GetNodeByTitleImpl(model_.GetRoot(), ASCIIToUTF16(title));
}
const AXVirtualView* TreeViewTest::GetAccessibilityViewByName(
const std::string& name) const {
const AXVirtualView* ax_view = GetRootAccessibilityView();
while (ax_view) {
std::string ax_view_name;
if (ax_view->GetData().GetStringAttribute(ax::mojom::StringAttribute::kName,
&ax_view_name) &&
ax_view_name == name) {
return ax_view;
}
if (ax_view->children().size()) {
ax_view = ax_view->children()[0].get();
continue;
}
const AXVirtualView* parent_view = ax_view->virtual_parent_view();
while (parent_view) {
size_t sibling_index_in_parent =
parent_view->GetIndexOf(ax_view).value() + 1;
if (sibling_index_in_parent < parent_view->children().size()) {
ax_view = parent_view->children()[sibling_index_in_parent].get();
break;
}
ax_view = parent_view;
parent_view = parent_view->virtual_parent_view();
}
if (!parent_view)
break;
}
return nullptr;
}
void TreeViewTest::IncrementSelection(bool next) {
tree_->IncrementSelection(next ? TreeView::IncrementType::kNext
: TreeView::IncrementType::kPrevious);
}
void TreeViewTest::CollapseOrSelectParent() {
tree_->CollapseOrSelectParent();
}
void TreeViewTest::ExpandOrSelectChild() {
tree_->ExpandOrSelectChild();
}
size_t TreeViewTest::GetRowCount() {
return tree_->GetRowCount();
}
TestNode* TreeViewTest::GetNodeByTitleImpl(TestNode* node,
const std::u16string& title) {
if (node->GetTitle() == title)
return node;
for (auto& child : node->children()) {
TestNode* matching_node = GetNodeByTitleImpl(child.get(), title);
if (matching_node)
return matching_node;
}
return nullptr;
}
std::string TreeViewTest::InternalNodeAsString(TreeView::InternalNode* node) {
std::string result = base::UTF16ToASCII(node->model_node()->GetTitle());
if (node->is_expanded() && !node->children().empty()) {
result += std::accumulate(
node->children().cbegin() + 1, node->children().cend(),
" [" + InternalNodeAsString(node->children().front().get()),
[this](const std::string& str, const auto& child) {
return str + " " + InternalNodeAsString(child.get());
}) +
"]";
}
return result;
}
// Verify properties are accessible via metadata.
TEST_F(TreeViewTest, MetadataTest) {
tree_->SetModel(&model_);
test::TestViewMetadata(tree_);
}
TEST_F(TreeViewTest, TreeViewPaintCoverage) {
tree_->SetModel(&model_);
SkBitmap bitmap;
gfx::Size size = tree_->size();
ui::CanvasPainter canvas_painter(&bitmap, size, 1.f, SK_ColorTRANSPARENT,
false);
widget_->GetRootView()->Paint(
PaintInfo::CreateRootPaintInfo(canvas_painter.context(), size));
}
// Verifies setting model correctly updates internal state.
TEST_F(TreeViewTest, SetModel) {
tree_->SetModel(&model_);
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetRootAccessibilityView(), ax::mojom::Event::kFocus),
std::make_pair(GetRootAccessibilityView(),
ax::mojom::Event::kSelection)}),
accessibility_events());
}
// Verifies that SetSelectedNode works.
TEST_F(TreeViewTest, SetSelectedNode) {
tree_->SetModel(&model_);
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
// NULL should clear the selection.
tree_->SetSelectedNode(nullptr);
EXPECT_EQ(std::string(), GetSelectedNodeTitle());
EXPECT_EQ(std::string(), GetSelectedAccessibilityViewName());
// Select 'c'.
ClearAccessibilityEvents();
tree_->SetSelectedNode(GetNodeByTitle("c"));
EXPECT_EQ("c", GetSelectedNodeTitle());
EXPECT_EQ("c", GetSelectedAccessibilityViewName());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(GetAccessibilityViewByName("c"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("c"),
ax::mojom::Event::kSelection)}),
accessibility_events());
// Select 'b1', which should expand 'b'.
ClearAccessibilityEvents();
tree_->SetSelectedNode(GetNodeByTitle("b1"));
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
// Node "b" must have been expanded.
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kExpandedChanged),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kRowExpanded),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged),
std::make_pair(GetAccessibilityViewByName("b1"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("b1"),
ax::mojom::Event::kSelection)}),
accessibility_events());
}
// Makes sure SetRootShown doesn't blow up.
TEST_F(TreeViewTest, HideRoot) {
tree_->SetModel(&model_);
ClearAccessibilityEvents();
tree_->SetRootShown(false);
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ(3u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection),
std::make_pair(GetRootAccessibilityView(),
ax::mojom::Event::kStateChanged)}),
accessibility_events());
}
// Expands a node and verifies the children are loaded correctly.
TEST_F(TreeViewTest, Expand) {
tree_->SetModel(&model_);
ClearAccessibilityEvents();
tree_->Expand(GetNodeByTitle("b1"));
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(5u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("b1"),
ax::mojom::Event::kExpandedChanged),
std::make_pair(GetAccessibilityViewByName("b1"),
ax::mojom::Event::kRowExpanded),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
}
// Collapse a node and verifies state.
TEST_F(TreeViewTest, Collapse) {
tree_->SetModel(&model_);
tree_->Expand(GetNodeByTitle("b1"));
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ(5u, GetRowCount());
tree_->SetSelectedNode(GetNodeByTitle("b1"));
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
ClearAccessibilityEvents();
tree_->Collapse(GetNodeByTitle("b"));
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
// Selected node should have moved to 'b'
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kSelection),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kExpandedChanged),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kRowCollapsed),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
}
// Verifies that adding nodes works.
TEST_F(TreeViewTest, TreeNodesAdded) {
tree_->SetModel(&model_);
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
// Add a node between b and c.
ClearAccessibilityEvents();
Add(model_.GetRoot(), 2, "B");
EXPECT_EQ("root [a b B c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b B c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(5u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
// Add a child of b1, which hasn't been loaded and shouldn't do anything.
ClearAccessibilityEvents();
Add(GetNodeByTitle("b1"), 0, "b11");
EXPECT_EQ("root [a b B c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b B c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(5u, GetRowCount());
// Added node is not visible, hence no accessibility event needed.
EXPECT_EQ(AccessibilityEventsVector(), accessibility_events());
// Add a child of b, which isn't expanded yet, so it shouldn't effect
// anything.
ClearAccessibilityEvents();
Add(GetNodeByTitle("b"), 1, "b2");
EXPECT_EQ("root [a b B c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b B c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(5u, GetRowCount());
// Added node is not visible, hence no accessibility event needed.
EXPECT_EQ(AccessibilityEventsVector(), accessibility_events());
// Expand b and make sure b2 is there.
ClearAccessibilityEvents();
tree_->Expand(GetNodeByTitle("b"));
EXPECT_EQ("root [a b [b1 b2] B c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1 b2] B c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(7u, GetRowCount());
// Since the added node was not visible when it was added, no extra events
// other than the ones for expanding a node are needed.
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kExpandedChanged),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kRowExpanded),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
}
// Verifies that removing nodes works.
TEST_F(TreeViewTest, TreeNodesRemoved) {
// Add c1 as a child of c and c11 as a child of c1.
Add(Add(GetNodeByTitle("c"), 0, "c1"), 0, "c11");
tree_->SetModel(&model_);
// Remove c11, which shouldn't have any effect on the tree.
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
// Expand b1, then collapse it and remove its only child, b1. This shouldn't
// effect the tree.
tree_->Expand(GetNodeByTitle("b"));
tree_->Collapse(GetNodeByTitle("b"));
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("b1")->parent(), GetNodeByTitle("b1"));
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(
GetTreeAccessibilityView(), ax::mojom::Event::kChildrenChanged)}),
accessibility_events());
// Remove 'b'.
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b"));
EXPECT_EQ("root [a c]", TreeViewContentsAsString());
EXPECT_EQ("root [a c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(3u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(), ax::mojom::Event::kFocus),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
// Remove 'c11', shouldn't visually change anything.
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("c11")->parent(), GetNodeByTitle("c11"));
EXPECT_EQ("root [a c]", TreeViewContentsAsString());
EXPECT_EQ("root [a c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(3u, GetRowCount());
// Node "c11" is not visible, hence no accessibility event needed.
EXPECT_EQ(AccessibilityEventsVector(), accessibility_events());
// Select 'c1', remove 'c' and make sure selection changes.
tree_->SetSelectedNode(GetNodeByTitle("c1"));
EXPECT_EQ("c1", GetSelectedNodeTitle());
EXPECT_EQ("c1", GetSelectedAccessibilityViewName());
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("c")->parent(), GetNodeByTitle("c"));
EXPECT_EQ("root [a]", TreeViewContentsAsString());
EXPECT_EQ("root [a]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ(2u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(), ax::mojom::Event::kFocus),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
// Add 'c1', 'c2', 'c3', select 'c2', remove it and 'c3" should be selected.
Add(GetNodeByTitle("a"), 0, "c1");
Add(GetNodeByTitle("a"), 1, "c2");
Add(GetNodeByTitle("a"), 2, "c3");
tree_->SetSelectedNode(GetNodeByTitle("c2"));
model_.Remove(GetNodeByTitle("c2")->parent(), GetNodeByTitle("c2"));
EXPECT_EQ("root [a [c1 c3]]", TreeViewContentsAsString());
EXPECT_EQ("root [a [c1 c3]]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("c3", GetSelectedNodeTitle());
EXPECT_EQ("c3", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
// Now delete 'c3' and then 'c1' should be selected.
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("c3")->parent(), GetNodeByTitle("c3"));
EXPECT_EQ("root [a [c1]]", TreeViewContentsAsString());
EXPECT_EQ("root [a [c1]]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("c1", GetSelectedNodeTitle());
EXPECT_EQ("c1", GetSelectedAccessibilityViewName());
EXPECT_EQ(3u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(), ax::mojom::Event::kFocus),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("c1"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("c1"),
ax::mojom::Event::kSelection),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
// Finally delete 'c1' and then 'a' should be selected.
ClearAccessibilityEvents();
model_.Remove(GetNodeByTitle("c1")->parent(), GetNodeByTitle("c1"));
EXPECT_EQ("root [a]", TreeViewContentsAsString());
EXPECT_EQ("root [a]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ(2u, GetRowCount());
EXPECT_EQ(
(AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(), ax::mojom::Event::kFocus),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kRowCountChanged)}),
accessibility_events());
tree_->SetRootShown(false);
// Add 'b' and 'c', select 'b' and remove it. Selection should change to 'c'.
Add(GetNodeByTitle("root"), 1, "b");
Add(GetNodeByTitle("root"), 2, "c");
tree_->SetSelectedNode(GetNodeByTitle("b"));
model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b"));
EXPECT_EQ("root [a c]", TreeViewContentsAsString());
EXPECT_EQ("root [a c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("c", GetSelectedNodeTitle());
EXPECT_EQ("c", GetSelectedAccessibilityViewName());
EXPECT_EQ(2u, GetRowCount());
}
class TestController : public TreeViewController {
public:
void OnTreeViewSelectionChanged(TreeView* tree_view) override {
call_count_++;
}
bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node) override {
return true;
}
int selection_change_count() const { return call_count_; }
private:
int call_count_ = 0;
};
TEST_F(TreeViewTest, RemovingLastNodeNotifiesSelectionChanged) {
TestController controller;
tree_->SetController(&controller);
tree_->SetRootShown(false);
tree_->SetModel(&model_);
// Remove all but one node.
model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b"));
model_.Remove(GetNodeByTitle("c")->parent(), GetNodeByTitle("c"));
tree_->SetSelectedNode(GetNodeByTitle("a"));
EXPECT_EQ("root [a]", TreeViewContentsAsString());
EXPECT_EQ("root [a]", TreeViewAccessibilityContentsAsString());
const int prior_call_count = controller.selection_change_count();
// Remove the final node and expect
// |TestController::OnTreeViewSelectionChanged| to be called.
model_.Remove(GetNodeByTitle("a")->parent(), GetNodeByTitle("a"));
EXPECT_EQ(prior_call_count + 1, controller.selection_change_count());
}
// Verifies that changing a node title works.
TEST_F(TreeViewTest, TreeNodeChanged) {
// Add c1 as a child of c and c11 as a child of c1.
Add(Add(GetNodeByTitle("c"), 0, "c1"), 0, "c11");
tree_->SetModel(&model_);
ClearAccessibilityEvents();
// Change c11, shouldn't do anything.
model_.SetTitle(GetNodeByTitle("c11"), u"c11.new");
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ(AccessibilityEventsVector(), accessibility_events());
// Change 'b1', shouldn't do anything.
ClearAccessibilityEvents();
model_.SetTitle(GetNodeByTitle("b1"), u"b1.new");
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ(AccessibilityEventsVector(), accessibility_events());
// Change 'b'.
ClearAccessibilityEvents();
model_.SetTitle(GetNodeByTitle("b"), u"b.new");
EXPECT_EQ("root [a b.new c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b.new c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetAccessibilityViewByName("b.new"),
ax::mojom::Event::kLocationChanged)}),
accessibility_events());
}
// Verifies that IncrementSelection() works.
TEST_F(TreeViewTest, IncrementSelection) {
tree_->SetModel(&model_);
ClearAccessibilityEvents();
IncrementSelection(true);
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection)}),
accessibility_events());
IncrementSelection(true);
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
IncrementSelection(true);
tree_->Expand(GetNodeByTitle("b"));
IncrementSelection(false);
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
IncrementSelection(true);
EXPECT_EQ("c", GetSelectedNodeTitle());
EXPECT_EQ("c", GetSelectedAccessibilityViewName());
IncrementSelection(true);
EXPECT_EQ("c", GetSelectedNodeTitle());
EXPECT_EQ("c", GetSelectedAccessibilityViewName());
tree_->SetRootShown(false);
tree_->SetSelectedNode(GetNodeByTitle("a"));
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
IncrementSelection(false);
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
}
// Verifies that CollapseOrSelectParent works.
TEST_F(TreeViewTest, CollapseOrSelectParent) {
tree_->SetModel(&model_);
tree_->SetSelectedNode(GetNodeByTitle("root"));
CollapseOrSelectParent();
EXPECT_EQ("root", TreeViewContentsAsString());
EXPECT_EQ("root", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
// Hide the root, which should implicitly expand the root.
tree_->SetRootShown(false);
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
tree_->SetSelectedNode(GetNodeByTitle("b1"));
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
CollapseOrSelectParent();
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
CollapseOrSelectParent();
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
}
// Verifies that ExpandOrSelectChild works.
TEST_F(TreeViewTest, ExpandOrSelectChild) {
tree_->SetModel(&model_);
tree_->SetSelectedNode(GetNodeByTitle("root"));
ExpandOrSelectChild();
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
ExpandOrSelectChild();
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
tree_->SetSelectedNode(GetNodeByTitle("b"));
ExpandOrSelectChild();
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
ExpandOrSelectChild();
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
ExpandOrSelectChild();
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
}
// Verify that selection is properly updated on each keystroke.
TEST_F(TreeViewTest, SelectOnKeyStroke) {
tree_->SetModel(&model_);
tree_->ExpandAll(model_.GetRoot());
selector()->InsertText(
u"b",
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
selector()->InsertText(
u"1",
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
// Invoke OnViewBlur() to reset time.
selector()->OnViewBlur();
selector()->InsertText(
u"z",
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
EXPECT_EQ("b1", GetSelectedNodeTitle());
EXPECT_EQ("b1", GetSelectedAccessibilityViewName());
selector()->OnViewBlur();
selector()->InsertText(
u"a",
ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
}
// Verifies that edits are committed when focus is lost.
TEST_F(TreeViewTest, CommitOnFocusLost) {
tree_->SetModel(&model_);
tree_->SetSelectedNode(GetNodeByTitle("root"));
ExpandOrSelectChild();
tree_->SetEditable(true);
tree_->StartEditing(GetNodeByTitle("a"));
tree_->editor()->SetText(u"a changed");
tree_->OnDidChangeFocus(nullptr, nullptr);
EXPECT_TRUE(GetNodeByTitle("a changed") != nullptr);
ASSERT_NE(nullptr, GetRootAccessibilityView());
ASSERT_LE(1u, GetRootAccessibilityView()->children().size());
EXPECT_EQ(
"a changed",
GetRootAccessibilityView()->children()[0]->GetData().GetStringAttribute(
ax::mojom::StringAttribute::kName));
}
// Verifies that virtual accessible actions go to virtual view targets.
TEST_F(TreeViewTest, VirtualAccessibleAction) {
tree_->SetModel(&model_);
tree_->Expand(GetNodeByTitle("b1"));
EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b [b1] c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ(5u, GetRowCount());
// Set to nullptr should clear the selection.
tree_->SetSelectedNode(nullptr);
EXPECT_EQ(std::string(), GetActiveNodeTitle());
EXPECT_EQ(std::string(), GetActiveAccessibilityViewName());
EXPECT_EQ(std::string(), GetSelectedNodeTitle());
EXPECT_EQ(std::string(), GetSelectedAccessibilityViewName());
// Test using each virtual view as target.
ui::AXActionData data;
const std::string test_cases[] = {"root", "a", "b", "b1", "c"};
for (const std::string& name : test_cases) {
data.target_node_id = GetAccessibilityViewByName(name)->GetData().id;
data.action = ax::mojom::Action::kDoDefault;
EXPECT_TRUE(tree_->HandleAccessibleAction(data));
EXPECT_EQ(name, GetActiveNodeTitle());
EXPECT_EQ(name, GetActiveAccessibilityViewName());
EXPECT_EQ(name, GetSelectedNodeTitle());
EXPECT_EQ(name, GetSelectedAccessibilityViewName());
}
// Do nothing when a valid node id is not provided. This can happen if the
// actions target the owner view itself.
tree_->SetSelectedNode(GetNodeByTitle("b"));
data.target_node_id = -1;
data.action = ax::mojom::Action::kDoDefault;
EXPECT_FALSE(tree_->HandleAccessibleAction(data));
EXPECT_EQ("b", GetActiveNodeTitle());
EXPECT_EQ("b", GetActiveAccessibilityViewName());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
// Check that the active node is set if assistive technologies set focus.
tree_->SetSelectedNode(GetNodeByTitle("b"));
data.target_node_id = GetAccessibilityViewByName("a")->GetData().id;
data.action = ax::mojom::Action::kFocus;
EXPECT_TRUE(tree_->HandleAccessibleAction(data));
EXPECT_EQ("a", GetActiveNodeTitle());
EXPECT_EQ("a", GetActiveAccessibilityViewName());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
// Do not handle accessible actions when no node is selected.
tree_->SetSelectedNode(nullptr);
data.target_node_id = -1;
data.action = ax::mojom::Action::kDoDefault;
EXPECT_FALSE(tree_->HandleAccessibleAction(data));
EXPECT_EQ(std::string(), GetActiveNodeTitle());
EXPECT_EQ(std::string(), GetActiveAccessibilityViewName());
EXPECT_EQ(std::string(), GetSelectedNodeTitle());
EXPECT_EQ(std::string(), GetSelectedAccessibilityViewName());
}
// Verifies that accessibility focus events get fired for the correct nodes when
// the tree view is given focus.
TEST_F(TreeViewTest, OnFocusAccessibilityEvents) {
// Without keyboard focus, model changes should not fire focus events.
tree_->GetFocusManager()->ClearFocus();
EXPECT_FALSE(tree_->HasFocus());
tree_->SetModel(&model_);
EXPECT_EQ("root [a b c]", TreeViewContentsAsString());
EXPECT_EQ("root [a b c]", TreeViewAccessibilityContentsAsString());
EXPECT_EQ("root", GetSelectedNodeTitle());
EXPECT_EQ("root", GetSelectedAccessibilityViewName());
EXPECT_EQ(4u, GetRowCount());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetRootAccessibilityView(),
ax::mojom::Event::kSelection)}),
accessibility_events());
// The initial focus should fire a focus event for the active node
// (in this case, the root node).
ClearAccessibilityEvents();
tree_->RequestFocus();
EXPECT_TRUE(tree_->HasFocus());
EXPECT_EQ((AccessibilityEventsVector{std::make_pair(
GetRootAccessibilityView(), ax::mojom::Event::kFocus)}),
accessibility_events());
// Focus clear and restore should fire a focus event for the active node.
ClearAccessibilityEvents();
tree_->SetSelectedNode(GetNodeByTitle("b"));
tree_->SetActiveNode(GetNodeByTitle("a"));
EXPECT_EQ("a", GetActiveNodeTitle());
EXPECT_EQ("a", GetActiveAccessibilityViewName());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
tree_->GetFocusManager()->ClearFocus();
EXPECT_FALSE(tree_->HasFocus());
tree_->GetFocusManager()->RestoreFocusedView();
EXPECT_TRUE(tree_->HasFocus());
EXPECT_EQ("a", GetActiveNodeTitle());
EXPECT_EQ("a", GetActiveAccessibilityViewName());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kSelection),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus)}),
accessibility_events());
// Without keyboard focus, selection should not fire focus events.
ClearAccessibilityEvents();
tree_->GetFocusManager()->ClearFocus();
tree_->SetSelectedNode(GetNodeByTitle("a"));
EXPECT_FALSE(tree_->HasFocus());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection)}),
accessibility_events());
// A direct focus action on a tree item should give focus to the tree view but
// only fire a focus event for the target node.
ui::AXActionData data;
const std::string test_cases[] = {"root", "a", "b", "c"};
for (const std::string& name : test_cases) {
ClearAccessibilityEvents();
tree_->GetFocusManager()->ClearFocus();
EXPECT_FALSE(tree_->HasFocus());
data.target_node_id = GetAccessibilityViewByName(name)->GetData().id;
data.action = ax::mojom::Action::kFocus;
EXPECT_TRUE(tree_->HandleAccessibleAction(data));
EXPECT_TRUE(tree_->HasFocus());
EXPECT_EQ(name, GetActiveNodeTitle());
EXPECT_EQ(name, GetActiveAccessibilityViewName());
EXPECT_EQ(name, GetSelectedNodeTitle());
EXPECT_EQ(name, GetSelectedAccessibilityViewName());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetAccessibilityViewByName(name),
ax::mojom::Event::kSelection),
std::make_pair(GetAccessibilityViewByName(name),
ax::mojom::Event::kFocus)}),
accessibility_events());
}
// A direct focus action on the tree view itself with an active node should
// have no effect.
ClearAccessibilityEvents();
tree_->GetFocusManager()->ClearFocus();
tree_->SetSelectedNode(GetNodeByTitle("b"));
data.target_node_id = -1;
data.action = ax::mojom::Action::kFocus;
EXPECT_FALSE(tree_->HandleAccessibleAction(data));
EXPECT_FALSE(tree_->HasFocus());
EXPECT_EQ("b", GetActiveNodeTitle());
EXPECT_EQ("b", GetActiveAccessibilityViewName());
EXPECT_EQ("b", GetSelectedNodeTitle());
EXPECT_EQ("b", GetSelectedAccessibilityViewName());
EXPECT_EQ(
(AccessibilityEventsVector{std::make_pair(GetAccessibilityViewByName("b"),
ax::mojom::Event::kSelection)}),
accessibility_events());
// A direct focus action on a tree view without an active node (i.e. empty
// tree) should fire a focus event for the tree view.
ClearAccessibilityEvents();
tree_->GetFocusManager()->ClearFocus();
ui::TreeNodeModel<TestNode> empty_model(std::make_unique<TestNode>());
static_cast<TestNode*>(empty_model.GetRoot())->SetTitle(u"root");
tree_->SetModel(&empty_model);
tree_->SetRootShown(false);
data.target_node_id = -1;
data.action = ax::mojom::Action::kFocus;
EXPECT_TRUE(tree_->HandleAccessibleAction(data));
EXPECT_TRUE(tree_->HasFocus());
EXPECT_EQ(std::string(), GetActiveNodeTitle());
EXPECT_EQ(std::string(), GetActiveAccessibilityViewName());
EXPECT_EQ(std::string(), GetSelectedNodeTitle());
EXPECT_EQ(std::string(), GetSelectedAccessibilityViewName());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetRootAccessibilityView(),
ax::mojom::Event::kSelection),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kSelection),
std::make_pair(GetRootAccessibilityView(),
ax::mojom::Event::kStateChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kFocus)}),
accessibility_events());
// When a focused empty tree is populated with nodes, it should immediately
// hand off focus to one of them and select it.
ClearAccessibilityEvents();
tree_->SetModel(&model_);
EXPECT_EQ("a", GetActiveNodeTitle());
EXPECT_EQ("a", GetActiveAccessibilityViewName());
EXPECT_EQ("a", GetSelectedNodeTitle());
EXPECT_EQ("a", GetSelectedAccessibilityViewName());
EXPECT_EQ((AccessibilityEventsVector{
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetTreeAccessibilityView(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kFocus),
std::make_pair(GetAccessibilityViewByName("a"),
ax::mojom::Event::kSelection)}),
accessibility_events());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/tree/tree_view_unittest.cc | C++ | unknown | 48,999 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_H_
#define UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_H_
#include <memory>
#include "ui/base/models/simple_menu_model.h"
namespace views {
class Textfield;
// This class is used to add and handle text service items in the text context
// menu.
class ViewsTextServicesContextMenu : public ui::SimpleMenuModel::Delegate {
public:
// Creates a platform-specific ViewsTextServicesContextMenu object.
static std::unique_ptr<ViewsTextServicesContextMenu> Create(
ui::SimpleMenuModel* menu,
Textfield* textfield);
// Returns true if the given |command_id| is handled by the menu.
virtual bool SupportsCommand(int command_id) const = 0;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu.h | C++ | unknown | 959 |
// 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/views_text_services_context_menu_base.h"
#include <memory>
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/emoji/emoji_panel_helper.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
const char kViewsTextServicesContextMenuEmoji[] =
"ContextMenu.ViewsTextServices.Emoji";
} // namespace
ViewsTextServicesContextMenuBase::ViewsTextServicesContextMenuBase(
ui::SimpleMenuModel* menu,
Textfield* client)
: client_(client) {
DCHECK(client);
DCHECK(menu);
// Not inserted on read-only fields or if the OS/version doesn't support it.
if (!client_->GetReadOnly() && ui::IsEmojiPanelSupported()) {
menu->InsertSeparatorAt(0, ui::NORMAL_SEPARATOR);
menu->InsertItemWithStringIdAt(0, IDS_CONTENT_CONTEXT_EMOJI,
IDS_CONTENT_CONTEXT_EMOJI);
}
}
ViewsTextServicesContextMenuBase::~ViewsTextServicesContextMenuBase() = default;
bool ViewsTextServicesContextMenuBase::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) const {
if (command_id == IDS_CONTENT_CONTEXT_EMOJI) {
#if BUILDFLAG(IS_WIN)
*accelerator = ui::Accelerator(ui::VKEY_OEM_PERIOD, ui::EF_COMMAND_DOWN);
return true;
#elif BUILDFLAG(IS_MAC)
*accelerator = ui::Accelerator(ui::VKEY_SPACE,
ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN);
return true;
#elif BUILDFLAG(IS_CHROMEOS)
*accelerator = ui::Accelerator(ui::VKEY_SPACE,
ui::EF_SHIFT_DOWN | ui::EF_COMMAND_DOWN);
return true;
#else
return false;
#endif
}
return false;
}
bool ViewsTextServicesContextMenuBase::IsCommandIdChecked(
int command_id) const {
return false;
}
bool ViewsTextServicesContextMenuBase::IsCommandIdEnabled(
int command_id) const {
return command_id == IDS_CONTENT_CONTEXT_EMOJI;
}
void ViewsTextServicesContextMenuBase::ExecuteCommand(int command_id,
int event_flags) {
if (command_id == IDS_CONTENT_CONTEXT_EMOJI) {
client_->GetWidget()->ShowEmojiPanel();
UMA_HISTOGRAM_BOOLEAN(kViewsTextServicesContextMenuEmoji, true);
}
}
bool ViewsTextServicesContextMenuBase::SupportsCommand(int command_id) const {
return command_id == IDS_CONTENT_CONTEXT_EMOJI;
}
#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_CHROMEOS)
// static
std::unique_ptr<ViewsTextServicesContextMenu>
ViewsTextServicesContextMenu::Create(ui::SimpleMenuModel* menu,
Textfield* client) {
return std::make_unique<ViewsTextServicesContextMenuBase>(menu, client);
}
#endif
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu_base.cc | C++ | unknown | 3,143 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_BASE_H_
#define UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_BASE_H_
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/views/controls/views_text_services_context_menu.h"
#include "ui/views/views_export.h"
namespace views {
// This base class is used to add and handle text service items in the textfield
// context menu. Specific platforms may subclass and add additional items.
class VIEWS_EXPORT ViewsTextServicesContextMenuBase
: public ViewsTextServicesContextMenu {
public:
ViewsTextServicesContextMenuBase(ui::SimpleMenuModel* menu,
Textfield* client);
ViewsTextServicesContextMenuBase(const ViewsTextServicesContextMenuBase&) =
delete;
ViewsTextServicesContextMenuBase& operator=(
const ViewsTextServicesContextMenuBase&) = delete;
~ViewsTextServicesContextMenuBase() override;
// ViewsTextServicesContextMenu:
bool GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) const override;
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdEnabled(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
bool SupportsCommand(int command_id) const override;
protected:
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
Textfield* client() { return client_; }
const Textfield* client() const { return client_; }
#endif
private:
// The view associated with the menu. Weak. Owns |this|.
const raw_ptr<Textfield> client_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_BASE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu_base.h | C++ | unknown | 1,893 |
// 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/views_text_services_context_menu_chromeos.h"
#include <utility>
#include "base/no_destructor.h"
#include "ui/views/controls/views_text_services_context_menu_base.h"
namespace views {
namespace {
using ImplFactory = ViewsTextServicesContextMenuChromeos::ImplFactory;
ImplFactory& GetImplFactory() {
static base::NoDestructor<ImplFactory> impl_factory;
return *impl_factory;
}
} // namespace
// static
void ViewsTextServicesContextMenuChromeos::SetImplFactory(
ImplFactory impl_factory) {
GetImplFactory() = std::move(impl_factory);
}
ViewsTextServicesContextMenuChromeos::ViewsTextServicesContextMenuChromeos(
ui::SimpleMenuModel* menu,
Textfield* client) {
auto& impl_factory = GetImplFactory();
// In unit tests, `impl_factory` may not be set. Use
// `ViewTextServicesContextMenuBase` in that case.
if (impl_factory) {
impl_ = impl_factory.Run(menu, client);
} else {
impl_ = std::make_unique<ViewsTextServicesContextMenuBase>(menu, client);
}
}
ViewsTextServicesContextMenuChromeos::~ViewsTextServicesContextMenuChromeos() =
default;
bool ViewsTextServicesContextMenuChromeos::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) const {
return impl_->GetAcceleratorForCommandId(command_id, accelerator);
}
bool ViewsTextServicesContextMenuChromeos::IsCommandIdChecked(
int command_id) const {
return impl_->IsCommandIdChecked(command_id);
}
bool ViewsTextServicesContextMenuChromeos::IsCommandIdEnabled(
int command_id) const {
return impl_->IsCommandIdEnabled(command_id);
}
void ViewsTextServicesContextMenuChromeos::ExecuteCommand(int command_id,
int event_flags) {
return impl_->ExecuteCommand(command_id, event_flags);
}
bool ViewsTextServicesContextMenuChromeos::SupportsCommand(
int command_id) const {
return impl_->SupportsCommand(command_id);
}
// static
std::unique_ptr<ViewsTextServicesContextMenu>
ViewsTextServicesContextMenu::Create(ui::SimpleMenuModel* menu,
Textfield* client) {
return std::make_unique<ViewsTextServicesContextMenuChromeos>(menu, client);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu_chromeos.cc | C++ | unknown | 2,380 |
// 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_VIEWS_TEXT_SERVICES_CONTEXT_MENU_CHROMEOS_H_
#define UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_CHROMEOS_H_
#include <memory>
#include "ui/views/controls/views_text_services_context_menu.h"
#include "ui/views/views_export.h"
namespace views {
// This class is used to add and handle text service items in ChromeOS native UI
// textfield context menus. The implementation is specific to the platform (Ash
// or Lacros) where the textfield lives.
class VIEWS_EXPORT ViewsTextServicesContextMenuChromeos
: public ViewsTextServicesContextMenu {
public:
using ImplFactory = base::RepeatingCallback<std::unique_ptr<
ViewsTextServicesContextMenu>(ui::SimpleMenuModel*, Textfield*)>;
// Injects the method to construct `impl_`.
static void SetImplFactory(ImplFactory factory);
ViewsTextServicesContextMenuChromeos(ui::SimpleMenuModel* menu,
Textfield* client);
ViewsTextServicesContextMenuChromeos(
const ViewsTextServicesContextMenuChromeos&) = delete;
ViewsTextServicesContextMenuChromeos& operator=(
const ViewsTextServicesContextMenuChromeos&) = delete;
~ViewsTextServicesContextMenuChromeos() override;
// ViewsTextServicesContextMenu:
bool GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) const override;
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdEnabled(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
bool SupportsCommand(int command_id) const override;
private:
// ChromeOS functionality is provided by a platform-specific implementation.
// Function calls are forwarded to this instance, whose construction is
// controlled by `SetImplFactory()`.
std::unique_ptr<ViewsTextServicesContextMenu> impl_;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_VIEWS_TEXT_SERVICES_CONTEXT_MENU_CHROMEOS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu_chromeos.h | C++ | unknown | 2,121 |
// 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/views_text_services_context_menu.h"
#import <Cocoa/Cocoa.h>
#include "ui/base/cocoa/text_services_context_menu.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/decorated_text.h"
#import "ui/gfx/decorated_text_mac.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/views_text_services_context_menu_base.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// This class serves as a bridge to TextServicesContextMenu to add and handle
// text service items in the context menu. The items include Speech, Look Up
// and BiDi.
class ViewsTextServicesContextMenuMac
: public ViewsTextServicesContextMenuBase,
public ui::TextServicesContextMenu::Delegate {
public:
ViewsTextServicesContextMenuMac(ui::SimpleMenuModel* menu, Textfield* client);
ViewsTextServicesContextMenuMac(const ViewsTextServicesContextMenuMac&) =
delete;
ViewsTextServicesContextMenuMac& operator=(
const ViewsTextServicesContextMenuMac&) = delete;
~ViewsTextServicesContextMenuMac() override = default;
// ViewsTextServicesContextMenu:
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdEnabled(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
bool SupportsCommand(int command_id) const override;
// TextServicesContextMenu::Delegate:
std::u16string GetSelectedText() const override;
bool IsTextDirectionEnabled(
base::i18n::TextDirection direction) const override;
bool IsTextDirectionChecked(
base::i18n::TextDirection direction) const override;
void UpdateTextDirection(base::i18n::TextDirection direction) override;
private:
// Handler for the "Look Up" menu item.
void LookUpInDictionary();
ui::TextServicesContextMenu text_services_menu_{this};
};
ViewsTextServicesContextMenuMac::ViewsTextServicesContextMenuMac(
ui::SimpleMenuModel* menu,
Textfield* client)
: ViewsTextServicesContextMenuBase(menu, client) {
// Insert the "Look up" item in the first position.
const std::u16string text = GetSelectedText();
if (!text.empty()) {
menu->InsertSeparatorAt(0, ui::NORMAL_SEPARATOR);
menu->InsertItemAt(
0, IDS_CONTENT_CONTEXT_LOOK_UP,
l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_LOOK_UP, text));
text_services_menu_.AppendToContextMenu(menu);
}
text_services_menu_.AppendEditableItems(menu);
}
bool ViewsTextServicesContextMenuMac::IsCommandIdChecked(int command_id) const {
return text_services_menu_.SupportsCommand(command_id)
? text_services_menu_.IsCommandIdChecked(command_id)
: ViewsTextServicesContextMenuBase::IsCommandIdChecked(command_id);
}
bool ViewsTextServicesContextMenuMac::IsCommandIdEnabled(int command_id) const {
if (text_services_menu_.SupportsCommand(command_id))
return text_services_menu_.IsCommandIdEnabled(command_id);
return (command_id == IDS_CONTENT_CONTEXT_LOOK_UP) ||
ViewsTextServicesContextMenuBase::IsCommandIdEnabled(command_id);
}
void ViewsTextServicesContextMenuMac::ExecuteCommand(int command_id,
int event_flags) {
if (text_services_menu_.SupportsCommand(command_id))
text_services_menu_.ExecuteCommand(command_id, event_flags);
else if (command_id == IDS_CONTENT_CONTEXT_LOOK_UP)
LookUpInDictionary();
else
ViewsTextServicesContextMenuBase::ExecuteCommand(command_id, event_flags);
}
bool ViewsTextServicesContextMenuMac::SupportsCommand(int command_id) const {
return text_services_menu_.SupportsCommand(command_id) ||
command_id == IDS_CONTENT_CONTEXT_LOOK_UP ||
ViewsTextServicesContextMenuBase::SupportsCommand(command_id);
}
std::u16string ViewsTextServicesContextMenuMac::GetSelectedText() const {
return (client()->GetTextInputType() == ui::TEXT_INPUT_TYPE_PASSWORD)
? std::u16string()
: client()->GetSelectedText();
}
bool ViewsTextServicesContextMenuMac::IsTextDirectionEnabled(
base::i18n::TextDirection direction) const {
if (client()->force_text_directionality())
return false;
return direction != base::i18n::UNKNOWN_DIRECTION;
}
bool ViewsTextServicesContextMenuMac::IsTextDirectionChecked(
base::i18n::TextDirection direction) const {
if (client()->force_text_directionality())
return direction == base::i18n::UNKNOWN_DIRECTION;
return IsTextDirectionEnabled(direction) &&
client()->GetTextDirection() == direction;
}
void ViewsTextServicesContextMenuMac::UpdateTextDirection(
base::i18n::TextDirection direction) {
DCHECK(IsTextDirectionEnabled(direction));
client()->ChangeTextDirectionAndLayoutAlignment(direction);
}
void ViewsTextServicesContextMenuMac::LookUpInDictionary() {
gfx::DecoratedText text;
gfx::Point baseline_point;
if (client()->GetWordLookupDataFromSelection(&text, &baseline_point)) {
Widget* widget = client()->GetWidget();
views::View::ConvertPointToTarget(client(), widget->GetRootView(),
&baseline_point);
NSView* view = widget->GetNativeView().GetNativeNSView();
NSPoint lookup_point = NSMakePoint(
baseline_point.x(), NSHeight([view frame]) - baseline_point.y());
[view showDefinitionForAttributedString:
gfx::GetAttributedStringFromDecoratedText(text)
atPoint:lookup_point];
}
}
} // namespace
// static
std::unique_ptr<ViewsTextServicesContextMenu>
ViewsTextServicesContextMenu::Create(ui::SimpleMenuModel* menu,
Textfield* client) {
return std::make_unique<ViewsTextServicesContextMenuMac>(menu, client);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/views_text_services_context_menu_mac.mm | Objective-C++ | unknown | 6,071 |
include_rules = [
"+content/public",
"+content/test/test_content_browser_client.h",
"+content/test/test_web_contents.h",
"+third_party/blink/public/mojom/loader/resource_load_info.mojom.h",
"+ui/content_accelerators",
"+ui/views",
"+ui/web_dialogs",
]
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/DEPS | Python | unknown | 266 |
// 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/webview/unhandled_keyboard_event_handler.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/content_accelerators/accelerator_util.h"
#include "ui/views/focus/focus_manager.h"
namespace views {
UnhandledKeyboardEventHandler::UnhandledKeyboardEventHandler() = default;
UnhandledKeyboardEventHandler::~UnhandledKeyboardEventHandler() = default;
bool UnhandledKeyboardEventHandler::HandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager) {
CHECK(focus_manager);
// Previous calls to TranslateMessage can generate Char events as well as
// RawKeyDown events, even if the latter triggered an accelerator. In these
// cases, we discard the Char events.
if (event.GetType() == blink::WebInputEvent::Type::kChar &&
ignore_next_char_event_) {
ignore_next_char_event_ = false;
return false;
}
// It's necessary to reset this flag, because a RawKeyDown event may not
// always generate a Char event.
ignore_next_char_event_ = false;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) {
ui::Accelerator accelerator =
ui::GetAcceleratorFromNativeWebKeyboardEvent(event);
// This is tricky: we want to set ignore_next_char_event_ if
// ProcessAccelerator returns true. But ProcessAccelerator might delete
// |this| if the accelerator is a "close tab" one. So we speculatively
// set the flag and fix it if no event was handled.
ignore_next_char_event_ = true;
if (focus_manager->ProcessAccelerator(accelerator))
return true;
// ProcessAccelerator didn't handle the accelerator, so we know both
// that |this| is still valid, and that we didn't want to set the flag.
ignore_next_char_event_ = false;
}
if (event.os_event)
return HandleNativeKeyboardEvent(event, focus_manager);
return false;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler.cc | C++ | unknown | 2,072 |
// 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_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_
#define UI_VIEWS_CONTROLS_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/webview/webview_export.h"
namespace content {
struct NativeWebKeyboardEvent;
}
namespace views {
class FocusManager;
// This class handles unhandled keyboard messages coming back from the renderer
// process.
class WEBVIEW_EXPORT UnhandledKeyboardEventHandler {
public:
UnhandledKeyboardEventHandler();
UnhandledKeyboardEventHandler(const UnhandledKeyboardEventHandler&) = delete;
UnhandledKeyboardEventHandler& operator=(
const UnhandledKeyboardEventHandler&) = delete;
~UnhandledKeyboardEventHandler();
bool HandleKeyboardEvent(const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager);
private:
// Platform specific handling for unhandled keyboard events.
static bool HandleNativeKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager);
// Whether to ignore the next Char keyboard event.
// If a RawKeyDown event was handled as a shortcut key, then we're done
// handling it and should eat any Char event that the translate phase may
// have produced from it. (Handling this event may cause undesirable effects,
// such as a beep if DefWindowProc() has no default handling for the given
// Char.)
bool ignore_next_char_event_ = false;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler.h | C++ | unknown | 1,725 |
// 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/webview/unhandled_keyboard_event_handler.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/event.h"
#include "ui/views/focus/focus_manager.h"
namespace views {
// static
bool UnhandledKeyboardEventHandler::HandleNativeKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager) {
if (event.skip_in_browser)
return false;
return !focus_manager->OnKeyEvent(*(event.os_event->AsKeyEvent()));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler_default.cc | C++ | unknown | 671 |
// 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/webview/unhandled_keyboard_event_handler.h"
#include "content/public/browser/native_web_keyboard_event.h"
#import "ui/views/cocoa/native_widget_mac_ns_window_host.h"
namespace views {
// static
bool UnhandledKeyboardEventHandler::HandleNativeKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager) {
if (event.skip_in_browser)
return false;
auto os_event = event.os_event;
auto* host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow(
[os_event window]);
if (host)
return host->RedispatchKeyEvent(os_event);
return false;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler_mac.mm | Objective-C++ | unknown | 797 |
// 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/webview/unhandled_keyboard_event_handler.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/event.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_utils.h"
#include "ui/views/focus/focus_manager.h"
namespace views {
// static
bool UnhandledKeyboardEventHandler::HandleNativeKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager) {
auto& key_event = *event.os_event->AsKeyEvent();
if (!event.skip_in_browser) {
// Try to re-send via FocusManager.
// Note: FocusManager::OnKeyEvent returns true iff the given event
// needs to continue to propagated. So, negate the condition to calculate
// whether it is consumed.
if (!focus_manager->OnKeyEvent(key_event))
return true;
}
// Send it back to the platform via Ozone.
if (auto* util = ui::OzonePlatform::GetInstance()->GetPlatformUtils()) {
util->OnUnhandledKeyEvent(key_event);
return true;
}
return false;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler_ozone.cc | C++ | unknown | 1,215 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include <windows.h>
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/event.h"
namespace views {
// static
bool UnhandledKeyboardEventHandler::HandleNativeKeyboardEvent(
const content::NativeWebKeyboardEvent& event,
FocusManager* focus_manager) {
if (event.skip_in_browser)
return false;
// Any unhandled keyboard/character messages should be defproced.
// This allows stuff like F10, etc to work correctly.
const CHROME_MSG& message(event.os_event->native_event());
::DefWindowProc(message.hwnd, message.message, message.wParam,
message.lParam);
return true;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/unhandled_keyboard_event_handler_win.cc | C++ | unknown | 881 |
// 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/webview/web_contents_set_background_color.h"
#include "base/memory/ptr_util.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
namespace views {
// static
void WebContentsSetBackgroundColor::CreateForWebContentsWithColor(
content::WebContents* web_contents,
SkColor color) {
if (FromWebContents(web_contents))
return;
// SupportsUserData::Data takes ownership over the
// WebContentsSetBackgroundColor instance and will destroy it when the
// WebContents instance is destroyed.
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new WebContentsSetBackgroundColor(web_contents, color)));
}
WebContentsSetBackgroundColor::WebContentsSetBackgroundColor(
content::WebContents* web_contents,
SkColor color)
: content::WebContentsObserver(web_contents),
content::WebContentsUserData<WebContentsSetBackgroundColor>(
*web_contents),
color_(color) {}
WebContentsSetBackgroundColor::~WebContentsSetBackgroundColor() = default;
void WebContentsSetBackgroundColor::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
// We set the background color just on the outermost main frame's widget.
// Other frames that are local roots would have a widget of their own, but
// their background colors are part of, and controlled by, the webpage.
if (!render_frame_host->GetParentOrOuterDocument())
render_frame_host->GetView()->SetBackgroundColor(color_);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsSetBackgroundColor);
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/web_contents_set_background_color.cc | C++ | unknown | 1,833 |
// 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_WEBVIEW_WEB_CONTENTS_SET_BACKGROUND_COLOR_H_
#define UI_VIEWS_CONTROLS_WEBVIEW_WEB_CONTENTS_SET_BACKGROUND_COLOR_H_
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "ui/views/controls/webview/webview_export.h"
// Defined in SkColor.h (32-bit ARGB color).
using SkColor = unsigned int;
namespace views {
// Ensures that the background color of a given WebContents instance is always
// set to a given color value.
class WebContentsSetBackgroundColor
: public content::WebContentsObserver,
public content::WebContentsUserData<WebContentsSetBackgroundColor> {
public:
WEBVIEW_EXPORT static void CreateForWebContentsWithColor(
content::WebContents* web_contents,
SkColor color);
WebContentsSetBackgroundColor(const WebContentsSetBackgroundColor&) = delete;
WebContentsSetBackgroundColor& operator=(
const WebContentsSetBackgroundColor&) = delete;
~WebContentsSetBackgroundColor() override;
SkColor color() const { return color_; }
private:
friend class content::WebContentsUserData<WebContentsSetBackgroundColor>;
WebContentsSetBackgroundColor(content::WebContents* web_contents,
SkColor color);
// content::WebContentsObserver:
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
SkColor color_;
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEB_CONTENTS_SET_BACKGROUND_COLOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/web_contents_set_background_color.h | C++ | unknown | 1,698 |
// 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/webview/web_dialog_view.h"
#include <utility>
#include <vector>
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/events/event.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_ui.h"
using content::NativeWebKeyboardEvent;
using content::WebContents;
using content::WebUIMessageHandler;
using ui::WebDialogDelegate;
using ui::WebDialogUIBase;
using ui::WebDialogWebContentsDelegate;
namespace views {
ObservableWebView::ObservableWebView(content::BrowserContext* browser_context,
WebDialogDelegate* delegate)
: WebView(browser_context), delegate_(delegate) {}
ObservableWebView::~ObservableWebView() = default;
void ObservableWebView::DidFinishLoad(
content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
// Only listen to the primary main frame.
if (!render_frame_host->IsInPrimaryMainFrame())
return;
if (delegate_)
delegate_->OnWebContentsFinishedLoad();
}
void ObservableWebView::ResetDelegate() {
delegate_ = nullptr;
}
BEGIN_METADATA(ObservableWebView, WebView)
END_METADATA
////////////////////////////////////////////////////////////////////////////////
// WebDialogView, public:
WebDialogView::WebDialogView(content::BrowserContext* context,
WebDialogDelegate* delegate,
std::unique_ptr<WebContentsHandler> handler)
: ClientView(nullptr, nullptr),
WebDialogWebContentsDelegate(context, std::move(handler)),
delegate_(delegate),
web_view_(new ObservableWebView(context, delegate)) {
SetCanMinimize(!delegate_ || delegate_->can_minimize());
SetCanResize(!delegate_ || delegate_->can_resize());
SetModalType(GetDialogModalType());
web_view_->set_allow_accelerators(true);
AddChildView(web_view_.get());
set_contents_view(web_view_);
SetLayoutManager(std::make_unique<views::FillLayout>());
// Pressing the Escape key will close the dialog.
AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE));
if (delegate_) {
for (const auto& accelerator : delegate_->GetAccelerators())
AddAccelerator(accelerator);
RegisterWindowWillCloseCallback(base::BindOnce(
&WebDialogView::NotifyDialogWillClose, base::Unretained(this)));
}
}
WebDialogView::~WebDialogView() = default;
content::WebContents* WebDialogView::web_contents() {
return web_view_->web_contents();
}
////////////////////////////////////////////////////////////////////////////////
// WebDialogView, views::View implementation:
void WebDialogView::AddedToWidget() {
gfx::RoundedCornersF corner_radii(
delegate_ && delegate_->GetWebDialogFrameKind() ==
WebDialogDelegate::FrameKind::kDialog
? GetCornerRadius()
: 0);
web_view_->holder()->SetCornerRadii(corner_radii);
}
gfx::Size WebDialogView::CalculatePreferredSize() const {
gfx::Size out;
if (delegate_)
delegate_->GetDialogSize(&out);
return out;
}
gfx::Size WebDialogView::GetMinimumSize() const {
gfx::Size out;
if (delegate_)
delegate_->GetMinimumDialogSize(&out);
return out;
}
bool WebDialogView::AcceleratorPressed(const ui::Accelerator& accelerator) {
if (delegate_ && delegate_->AcceleratorPressed(accelerator))
return true;
DCHECK_EQ(ui::VKEY_ESCAPE, accelerator.key_code());
if (delegate_ && !delegate_->ShouldCloseDialogOnEscape())
return false;
// Pressing Escape closes the dialog.
if (GetWidget()) {
// Contents must be closed first, or the dialog will not close.
CloseContents(web_view_->web_contents());
GetWidget()->CloseWithReason(views::Widget::ClosedReason::kEscKeyPressed);
}
return true;
}
void WebDialogView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && GetWidget())
InitDialog();
}
views::CloseRequestResult WebDialogView::OnWindowCloseRequested() {
// Don't close UI if |delegate_| does not allow users to close it by
// clicking on "x" button or pressing Escape shortcut key on hosting
// dialog.
if (!is_attempting_close_dialog_ && !delegate_->OnDialogCloseRequested()) {
if (!close_contents_called_)
return views::CloseRequestResult::kCannotClose;
// This is a web dialog, if the WebContents has been closed, there is no
// reason to keep the dialog alive.
LOG(ERROR) << "delegate tries to stop closing when CloseContents() has "
"been called";
}
// If CloseContents() is called before CanClose(), which is called by
// RenderViewHostImpl::ClosePageIgnoringUnloadEvents, it indicates
// beforeunload event should not be fired during closing.
if ((is_attempting_close_dialog_ && before_unload_fired_) ||
close_contents_called_) {
is_attempting_close_dialog_ = false;
before_unload_fired_ = false;
return views::CloseRequestResult::kCanClose;
}
if (!is_attempting_close_dialog_) {
// Fire beforeunload event when user attempts to close the dialog.
is_attempting_close_dialog_ = true;
web_view_->web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
}
return views::CloseRequestResult::kCannotClose;
}
////////////////////////////////////////////////////////////////////////////////
// WebDialogView, views::WidgetDelegate implementation:
bool WebDialogView::CanMaximize() const {
if (delegate_)
return delegate_->CanMaximizeDialog();
return false;
}
std::u16string WebDialogView::GetWindowTitle() const {
if (delegate_)
return delegate_->GetDialogTitle();
return std::u16string();
}
std::u16string WebDialogView::GetAccessibleWindowTitle() const {
if (delegate_)
return delegate_->GetAccessibleDialogTitle();
return GetWindowTitle();
}
std::string WebDialogView::GetWindowName() const {
if (delegate_)
return delegate_->GetDialogName();
return std::string();
}
void WebDialogView::WindowClosing() {
// If we still have a delegate that means we haven't notified it of the
// dialog closing. This happens if the user clicks the Close button on the
// dialog.
if (delegate_)
OnDialogClosed("");
}
views::View* WebDialogView::GetContentsView() {
return this;
}
views::ClientView* WebDialogView::CreateClientView(views::Widget* widget) {
return this;
}
std::unique_ptr<NonClientFrameView> WebDialogView::CreateNonClientFrameView(
Widget* widget) {
if (!delegate_)
return WidgetDelegate::CreateNonClientFrameView(widget);
switch (delegate_->GetWebDialogFrameKind()) {
case WebDialogDelegate::FrameKind::kNonClient:
return WidgetDelegate::CreateNonClientFrameView(widget);
case WebDialogDelegate::FrameKind::kDialog:
return DialogDelegate::CreateDialogFrameView(widget);
default:
NOTREACHED_NORETURN() << "Unknown frame kind type enum specified.";
}
}
views::View* WebDialogView::GetInitiallyFocusedView() {
return web_view_;
}
bool WebDialogView::ShouldShowWindowTitle() const {
return ShouldShowDialogTitle();
}
views::Widget* WebDialogView::GetWidget() {
return View::GetWidget();
}
const views::Widget* WebDialogView::GetWidget() const {
return View::GetWidget();
}
////////////////////////////////////////////////////////////////////////////////
// WebDialogDelegate implementation:
ui::ModalType WebDialogView::GetDialogModalType() const {
if (delegate_)
return delegate_->GetDialogModalType();
return ui::MODAL_TYPE_NONE;
}
std::u16string WebDialogView::GetDialogTitle() const {
return GetWindowTitle();
}
GURL WebDialogView::GetDialogContentURL() const {
if (delegate_)
return delegate_->GetDialogContentURL();
return GURL();
}
void WebDialogView::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const {
if (delegate_)
delegate_->GetWebUIMessageHandlers(handlers);
}
void WebDialogView::GetDialogSize(gfx::Size* size) const {
if (delegate_)
delegate_->GetDialogSize(size);
}
void WebDialogView::GetMinimumDialogSize(gfx::Size* size) const {
if (delegate_)
delegate_->GetMinimumDialogSize(size);
}
std::string WebDialogView::GetDialogArgs() const {
if (delegate_)
return delegate_->GetDialogArgs();
return std::string();
}
void WebDialogView::OnDialogShown(content::WebUI* webui) {
if (delegate_)
delegate_->OnDialogShown(webui);
}
void WebDialogView::OnDialogClosed(const std::string& json_retval) {
Detach();
if (delegate_) {
// Store the dialog content area size.
delegate_->StoreDialogSize(GetContentsBounds().size());
}
if (GetWidget())
GetWidget()->Close();
if (delegate_) {
delegate_->OnDialogClosed(json_retval);
delegate_ = nullptr; // We will not communicate further with the delegate.
// Clear the copy of the delegate in |web_view_| too.
web_view_->ResetDelegate();
}
}
void WebDialogView::OnDialogCloseFromWebUI(const std::string& json_retval) {
closed_via_webui_ = true;
dialog_close_retval_ = json_retval;
if (GetWidget())
GetWidget()->Close();
}
void WebDialogView::OnCloseContents(WebContents* source,
bool* out_close_dialog) {
DCHECK(out_close_dialog);
if (delegate_)
delegate_->OnCloseContents(source, out_close_dialog);
}
bool WebDialogView::ShouldShowDialogTitle() const {
if (delegate_)
return delegate_->ShouldShowDialogTitle();
return true;
}
bool WebDialogView::ShouldCenterDialogTitleText() const {
if (delegate_)
return delegate_->ShouldCenterDialogTitleText();
return false;
}
bool WebDialogView::ShouldShowCloseButton() const {
if (delegate_)
return delegate_->ShouldShowCloseButton();
return true;
}
bool WebDialogView::HandleContextMenu(
content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
if (delegate_)
return delegate_->HandleContextMenu(render_frame_host, params);
return WebDialogWebContentsDelegate::HandleContextMenu(render_frame_host,
params);
}
////////////////////////////////////////////////////////////////////////////////
// content::WebContentsDelegate implementation:
void WebDialogView::SetContentsBounds(WebContents* source,
const gfx::Rect& bounds) {
// The contained web page wishes to resize itself. We let it do this because
// if it's a dialog we know about, we trust it not to be mean to the user.
GetWidget()->SetBounds(bounds);
}
// A simplified version of BrowserView::HandleKeyboardEvent().
// We don't handle global keyboard shortcuts here, but that's fine since
// they're all browser-specific. (This may change in the future.)
bool WebDialogView::HandleKeyboardEvent(content::WebContents* source,
const NativeWebKeyboardEvent& event) {
if (!event.os_event)
return false;
return unhandled_keyboard_event_handler_.HandleKeyboardEvent(
event, GetFocusManager());
}
void WebDialogView::CloseContents(WebContents* source) {
close_contents_called_ = true;
bool close_dialog = false;
OnCloseContents(source, &close_dialog);
if (close_dialog)
OnDialogClosed(closed_via_webui_ ? dialog_close_retval_ : std::string());
}
content::WebContents* WebDialogView::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
content::WebContents* new_contents = nullptr;
if (delegate_ &&
delegate_->HandleOpenURLFromTab(source, params, &new_contents)) {
return new_contents;
}
return WebDialogWebContentsDelegate::OpenURLFromTab(source, params);
}
void WebDialogView::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
WebDialogWebContentsDelegate::AddNewContents(
source, std::move(new_contents), target_url, disposition, window_features,
user_gesture, was_blocked);
}
void WebDialogView::LoadingStateChanged(content::WebContents* source,
bool should_show_loading_ui) {
if (delegate_)
delegate_->OnLoadingStateChanged(source);
}
void WebDialogView::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
before_unload_fired_ = true;
*proceed_to_fire_unload = proceed;
}
bool WebDialogView::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url) {
if (delegate_)
return delegate_->HandleShouldOverrideWebContentsCreation();
return false;
}
void WebDialogView::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
if (delegate_) {
delegate_->RequestMediaAccessPermission(web_contents, request,
std::move(callback));
}
}
bool WebDialogView::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
if (delegate_) {
return delegate_->CheckMediaAccessPermission(render_frame_host,
security_origin, type);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// WebDialogView, private:
void WebDialogView::InitDialog() {
content::WebContents* web_contents = web_view_->GetWebContents();
if (web_contents->GetDelegate() == this)
return;
web_contents->SetDelegate(this);
// Set the delegate. This must be done before loading the page. See
// the comment above WebDialogUI in its header file for why.
WebDialogUIBase::SetDelegate(web_contents, this);
if (!disable_url_load_for_test_)
web_view_->LoadInitialURL(GetDialogContentURL());
}
void WebDialogView::NotifyDialogWillClose() {
if (delegate_)
delegate_->OnDialogWillClose();
}
BEGIN_METADATA(WebDialogView, ClientView)
ADD_READONLY_PROPERTY_METADATA(ObservableWebView*, WebView);
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/web_dialog_view.cc | C++ | unknown | 15,441 |
// 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_WEBVIEW_WEB_DIALOG_VIEW_H_
#define UI_VIEWS_CONTROLS_WEBVIEW_WEB_DIALOG_VIEW_H_
#include <stdint.h>
#include <memory>
#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/size.h"
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/controls/webview/webview_export.h"
#include "ui/views/window/client_view.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_web_contents_delegate.h"
namespace content {
class BrowserContext;
class RenderFrameHost;
} // namespace content
namespace views {
// A kind of webview that can notify its delegate when its content is ready.
class ObservableWebView : public WebView {
public:
METADATA_HEADER(ObservableWebView);
ObservableWebView(content::BrowserContext* browser_context,
ui::WebDialogDelegate* delegate);
ObservableWebView(const ObservableWebView&) = delete;
ObservableWebView& operator=(const ObservableWebView&) = delete;
~ObservableWebView() override;
// content::WebContentsObserver
void DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) override;
// Resets the delegate. The delegate will no longer receive calls after this
// point.
void ResetDelegate();
private:
raw_ptr<ui::WebDialogDelegate, DanglingUntriaged> delegate_;
};
////////////////////////////////////////////////////////////////////////////////
//
// WebDialogView is a view used to display an web dialog to the user. The
// content of the dialogs is determined by the delegate
// (ui::WebDialogDelegate), but is basically a file URL along with a
// JSON input string. The HTML is supposed to show a UI to the user and is
// expected to send back a JSON file as a return value.
//
////////////////////////////////////////////////////////////////////////////////
//
// TODO(akalin): Make WebDialogView contain an WebDialogWebContentsDelegate
// instead of inheriting from it to avoid violating the "no multiple
// inheritance" rule.
class WEBVIEW_EXPORT WebDialogView : public ClientView,
public ui::WebDialogWebContentsDelegate,
public ui::WebDialogDelegate,
public DialogDelegate {
public:
METADATA_HEADER(WebDialogView);
// |handler| must not be nullptr.
// |use_dialog_frame| indicates whether to use dialog frame view for non
// client frame view.
WebDialogView(content::BrowserContext* context,
ui::WebDialogDelegate* delegate,
std::unique_ptr<WebContentsHandler> handler);
WebDialogView(const WebDialogView&) = delete;
WebDialogView& operator=(const WebDialogView&) = delete;
~WebDialogView() override;
content::WebContents* web_contents();
// ClientView:
void AddedToWidget() override;
gfx::Size CalculatePreferredSize() const override;
gfx::Size GetMinimumSize() const override;
bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
views::CloseRequestResult OnWindowCloseRequested() override;
// WidgetDelegate:
bool CanMaximize() const override;
std::u16string GetWindowTitle() const override;
std::u16string GetAccessibleWindowTitle() const override;
std::string GetWindowName() const override;
void WindowClosing() override;
View* GetContentsView() override;
ClientView* CreateClientView(Widget* widget) override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView(
Widget* widget) override;
View* GetInitiallyFocusedView() override;
bool ShouldShowWindowTitle() const override;
bool ShouldShowCloseButton() const override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
// ui::WebDialogDelegate:
ui::ModalType GetDialogModalType() const override;
std::u16string GetDialogTitle() const override;
GURL GetDialogContentURL() const override;
void GetWebUIMessageHandlers(
std::vector<content::WebUIMessageHandler*>* handlers) const override;
void GetDialogSize(gfx::Size* size) const override;
void GetMinimumDialogSize(gfx::Size* size) const override;
std::string GetDialogArgs() const override;
void OnDialogShown(content::WebUI* webui) override;
void OnDialogClosed(const std::string& json_retval) override;
void OnDialogCloseFromWebUI(const std::string& json_retval) override;
void OnCloseContents(content::WebContents* source,
bool* out_close_dialog) override;
bool ShouldShowDialogTitle() const override;
bool ShouldCenterDialogTitleText() const override;
bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override;
// content::WebContentsDelegate:
void SetContentsBounds(content::WebContents* source,
const gfx::Rect& bounds) override;
bool HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
void CloseContents(content::WebContents* source) override;
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override;
void LoadingStateChanged(content::WebContents* source,
bool should_show_loading_ui) override;
void BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override;
bool IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url) override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) override;
private:
friend class WebDialogViewUnitTest;
FRIEND_TEST_ALL_PREFIXES(WebDialogBrowserTest, WebContentRendered);
// Initializes the contents of the dialog.
void InitDialog();
// Accessor used by metadata only.
ObservableWebView* GetWebView() const { return web_view_; }
void NotifyDialogWillClose();
// This view is a delegate to the HTML content since it needs to get notified
// about when the dialog is closing. For all other actions (besides dialog
// closing) we delegate to the creator of this view, which we keep track of
// using this variable.
//
// TODO(ellyjones): Having WebDialogView implement all of WebDialogDelegate,
// and plumb all the calls through to |delegate_|, is a lot of code overhead
// to support having this view know about dialog closure. There is probably a
// lighter-weight way to achieve that.
raw_ptr<ui::WebDialogDelegate, DanglingUntriaged> delegate_;
raw_ptr<ObservableWebView> web_view_;
// Whether user is attempting to close the dialog and we are processing
// beforeunload event.
bool is_attempting_close_dialog_ = false;
// Whether beforeunload event has been fired and we have finished processing
// beforeunload event.
bool before_unload_fired_ = false;
// Whether the dialog is closed from WebUI in response to a "dialogClose"
// message.
bool closed_via_webui_ = false;
// A json string returned to WebUI from a "dialogClose" message.
std::string dialog_close_retval_;
// Whether CloseContents() has been called.
bool close_contents_called_ = false;
// Handler for unhandled key events from renderer.
UnhandledKeyboardEventHandler unhandled_keyboard_event_handler_;
bool disable_url_load_for_test_ = false;
};
} // namespace views
#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEB_DIALOG_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/web_dialog_view.h | C++ | unknown | 8,848 |
// 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/webview/web_dialog_view.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_client.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_renderer_host.h"
#include "content/test/test_content_browser_client.h"
#include "content/test/test_web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/views/test/view_metadata_test_utils.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/web_dialogs/test/test_web_contents_handler.h"
#include "ui/web_dialogs/test/test_web_dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_web_contents_delegate.h"
#include "url/gurl.h"
namespace views {
// Testing delegate configured for use in this test.
class TestWebDialogViewWebDialogDelegate
: public ui::test::TestWebDialogDelegate {
public:
TestWebDialogViewWebDialogDelegate()
: ui::test::TestWebDialogDelegate(GURL()) {}
void set_close_on_escape(bool close_on_escape) {
close_on_escape_ = close_on_escape;
}
// ui::WebDialogDelegate
bool OnDialogCloseRequested() override { return true; }
bool ShouldCloseDialogOnEscape() const override { return close_on_escape_; }
ui::ModalType GetDialogModalType() const override {
return ui::MODAL_TYPE_WINDOW;
}
private:
bool close_on_escape_ = true;
};
// Provides functionality to test a WebDialogView.
class WebDialogViewUnitTest : public views::test::WidgetTest {
public:
WebDialogViewUnitTest()
: views::test::WidgetTest(std::unique_ptr<base::test::TaskEnvironment>(
std::make_unique<content::BrowserTaskEnvironment>())) {}
WebDialogViewUnitTest(const WebDialogViewUnitTest&) = delete;
WebDialogViewUnitTest& operator=(const WebDialogViewUnitTest&) = delete;
~WebDialogViewUnitTest() override = default;
// testing::Test
void SetUp() override {
views::test::WidgetTest::SetUp();
browser_context_ = std::make_unique<content::TestBrowserContext>();
// Set the test content browser client to avoid pulling in needless
// dependencies from content.
SetBrowserClientForTesting(&test_browser_client_);
web_dialog_delegate_ =
std::make_unique<TestWebDialogViewWebDialogDelegate>();
web_contents_ = CreateWebContents();
web_dialog_view_ = new WebDialogView(
web_contents_->GetBrowserContext(), web_dialog_delegate_.get(),
std::make_unique<ui::test::TestWebContentsHandler>());
// This prevents the initialization of the dialog from navigating
// to the URL in the WebUI. This is needed because the WebUI
// loading code that would otherwise attempt to use our TestBrowserContext,
// but will fail because TestBrowserContext not an instance of
// Profile (i.e. TestingProfile). We cannot, however, create an instance of
// TestingProfile in this test due to dependency restrictions between the
// views code and the location of TestingProfile.
web_dialog_view_->disable_url_load_for_test_ = true;
widget_ = views::DialogDelegate::CreateDialogWidget(web_dialog_view_,
GetContext(), nullptr);
widget_->Show();
EXPECT_FALSE(widget_is_closed());
}
void TearDown() override {
widget_->CloseNow();
views::test::WidgetTest::TearDown();
}
bool widget_is_closed() { return widget_->IsClosed(); }
WebDialogView* web_dialog_view() { return web_dialog_view_; }
views::WebView* web_view() {
return web_dialog_view_ ? web_dialog_view_->web_view_.get() : nullptr;
}
ui::WebDialogDelegate* web_view_delegate() {
return web_dialog_view_ ? web_dialog_view_->delegate_.get() : nullptr;
}
TestWebDialogViewWebDialogDelegate* web_dialog_delegate() {
return web_dialog_delegate_.get();
}
void ResetWebDialogDelegate() { web_dialog_delegate_.reset(); }
protected:
std::unique_ptr<content::TestWebContents> CreateWebContents() const {
return base::WrapUnique<content::TestWebContents>(
content::TestWebContents::Create(
content::WebContents::CreateParams(browser_context_.get())));
}
void SimulateKeyEvent(const ui::KeyEvent& event) {
ASSERT_TRUE(web_dialog_view_->GetFocusManager() != nullptr);
ASSERT_TRUE(widget_ != nullptr);
ui::KeyEvent event_copy = event;
if (web_dialog_view_->GetFocusManager()->OnKeyEvent(event_copy))
widget_->OnKeyEvent(&event_copy);
}
private:
content::RenderViewHostTestEnabler test_render_host_factories_;
content::TestContentBrowserClient test_browser_client_;
std::unique_ptr<content::TestBrowserContext> browser_context_;
// These are raw pointers (vs unique pointers) because the views
// system does its own internal memory management.
raw_ptr<views::Widget> widget_ = nullptr;
raw_ptr<WebDialogView> web_dialog_view_ = nullptr;
base::RepeatingClosure quit_closure_;
std::unique_ptr<TestWebDialogViewWebDialogDelegate> web_dialog_delegate_;
std::unique_ptr<content::TestWebContents> web_contents_;
};
TEST_F(WebDialogViewUnitTest, WebDialogViewClosedOnEscape) {
web_dialog_delegate()->set_close_on_escape(true);
const ui::KeyEvent escape_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE,
ui::EF_NONE);
SimulateKeyEvent(escape_event);
// The Dialog Widget should be closed when escape is pressed.
EXPECT_TRUE(widget_is_closed());
}
TEST_F(WebDialogViewUnitTest, WebDialogViewNotClosedOnEscape) {
web_dialog_delegate()->set_close_on_escape(false);
const ui::KeyEvent escape_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE,
ui::EF_NONE);
SimulateKeyEvent(escape_event);
// The Dialog Widget should not be closed when escape is pressed.
EXPECT_FALSE(widget_is_closed());
}
TEST_F(WebDialogViewUnitTest, ObservableWebViewOnWebDialogViewClosed) {
// Close the widget by pressing ESC key.
web_dialog_delegate()->set_close_on_escape(true);
const ui::KeyEvent escape_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE,
ui::EF_NONE);
SimulateKeyEvent(escape_event);
// The Dialog Widget should be closed .
ASSERT_TRUE(widget_is_closed());
// The delegate should be nullified so no further communication with it.
EXPECT_FALSE(web_view_delegate());
ResetWebDialogDelegate();
}
TEST_F(WebDialogViewUnitTest, MetadataTest) {
test::TestViewMetadata(web_dialog_view());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/web_dialog_view_unittest.cc | C++ | unknown | 6,927 |
// 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/webview/webview.h"
#include <string>
#include <utility>
#include "base/no_destructor.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ipc/ipc_message.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/events/event.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/webview/web_contents_set_background_color.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/views_delegate.h"
namespace views {
namespace {
// A testing stub that creates web contents.
WebView::WebContentsCreator* GetCreatorForTesting() {
static base::NoDestructor<WebView::WebContentsCreator> creator;
return creator.get();
}
// Updates the parent accessible object on the NativeView. As WebView overrides
// GetNativeViewAccessible() to return the accessible from the WebContents, it
// needs to ensure the accessible from the parent is set on the NativeView.
void UpdateNativeViewHostAccessibleParent(NativeViewHost* holder,
View* parent) {
if (!parent)
return;
holder->SetParentAccessible(parent->GetNativeViewAccessible());
}
} // namespace
WebView::ScopedWebContentsCreatorForTesting::ScopedWebContentsCreatorForTesting(
WebContentsCreator creator) {
DCHECK(!*GetCreatorForTesting());
*GetCreatorForTesting() = creator;
}
WebView::ScopedWebContentsCreatorForTesting::
~ScopedWebContentsCreatorForTesting() {
*GetCreatorForTesting() = WebView::WebContentsCreator();
}
////////////////////////////////////////////////////////////////////////////////
// WebView, public:
WebView::WebView(content::BrowserContext* browser_context) {
set_suppress_default_focus_handling();
ui::AXPlatformNode::AddAXModeObserver(this);
SetBrowserContext(browser_context);
}
WebView::~WebView() {
ui::AXPlatformNode::RemoveAXModeObserver(this);
SetWebContents(nullptr); // Make sure all necessary tear-down takes place.
}
content::WebContents* WebView::GetWebContents(base::Location creator_location) {
if (!web_contents()) {
if (!browser_context_)
return nullptr;
wc_owner_ = CreateWebContents(browser_context_, creator_location);
wc_owner_->SetDelegate(this);
SetWebContents(wc_owner_.get());
}
return web_contents();
}
void WebView::SetWebContents(content::WebContents* replacement) {
TRACE_EVENT0("views", "WebView::SetWebContents");
if (replacement == web_contents())
return;
SetCrashedOverlayView(nullptr);
DetachWebContentsNativeView();
WebContentsObserver::Observe(replacement);
// Do not remove the observation of the previously hosted WebContents to allow
// the WebContents to continue to use the source for colors and receive update
// notifications when in the background and not directly part of a UI
// hierarchy. This avoids color pop-in if the WebContents is re-inserted into
// the same hierarchy at a later point in time.
if (replacement)
replacement->SetColorProviderSource(GetWidget());
// web_contents() now returns |replacement| from here onwards.
if (wc_owner_.get() != replacement)
wc_owner_.reset();
AttachWebContentsNativeView();
if (replacement && replacement->GetPrimaryMainFrame()->IsRenderFrameLive()) {
SetUpNewMainFrame(replacement->GetPrimaryMainFrame());
} else {
LostMainFrame();
}
}
content::BrowserContext* WebView::GetBrowserContext() {
return browser_context_;
}
void WebView::SetBrowserContext(content::BrowserContext* browser_context) {
browser_context_ = browser_context;
}
void WebView::LoadInitialURL(const GURL& url) {
// Loading requires a valid WebContents.
DCHECK(GetWebContents());
GetWebContents()->GetController().LoadURL(url, content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
std::string());
}
void WebView::SetFastResize(bool fast_resize) {
holder_->set_fast_resize(fast_resize);
}
void WebView::EnableSizingFromWebContents(const gfx::Size& min_size,
const gfx::Size& max_size) {
DCHECK(!max_size.IsEmpty());
min_size_ = min_size;
max_size_ = max_size;
if (web_contents() &&
web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive())
MaybeEnableAutoResize(web_contents()->GetPrimaryMainFrame());
}
void WebView::SetResizeBackgroundColor(SkColor resize_background_color) {
holder_->SetBackgroundColorWhenClipped(resize_background_color);
}
void WebView::SetCrashedOverlayView(View* crashed_overlay_view) {
if (crashed_overlay_view_ == crashed_overlay_view)
return;
if (crashed_overlay_view_) {
RemoveChildView(crashed_overlay_view_);
// Show the hosted web contents view iff the crashed
// overlay is NOT showing, to ensure hit testing is
// correct on Mac. See https://crbug.com/896508
holder_->SetVisible(true);
if (!crashed_overlay_view_->owned_by_client())
delete crashed_overlay_view_;
}
crashed_overlay_view_ = crashed_overlay_view;
if (crashed_overlay_view_) {
AddChildView(crashed_overlay_view_.get());
holder_->SetVisible(false);
crashed_overlay_view_->SetBoundsRect(gfx::Rect(size()));
}
UpdateCrashedOverlayView();
}
////////////////////////////////////////////////////////////////////////////////
// WebView, View overrides:
void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
if (crashed_overlay_view_)
crashed_overlay_view_->SetBoundsRect(gfx::Rect(size()));
// In most cases, the holder is simply sized to fill this WebView's bounds.
// Only WebContentses that are in fullscreen mode and being screen-captured
// will engage the special layout/sizing behavior.
gfx::Rect holder_bounds = GetContentsBounds();
if (!web_contents() || !web_contents()->IsBeingCaptured() ||
web_contents()->GetPreferredSize().IsEmpty() ||
!(web_contents()->GetDelegate() &&
web_contents()->GetDelegate()->IsFullscreenForTabOrPending(
web_contents()))) {
// Reset the native view size.
holder_->SetNativeViewSize(gfx::Size());
holder_->SetBoundsRect(holder_bounds);
if (is_letterboxing_) {
is_letterboxing_ = false;
OnLetterboxingChanged();
}
return;
}
// For screen-captured fullscreened content, scale the |holder_| to fit within
// this View and center it.
const gfx::Size capture_size = web_contents()->GetPreferredSize();
const int64_t x =
static_cast<int64_t>(capture_size.width()) * holder_bounds.height();
const int64_t y =
static_cast<int64_t>(capture_size.height()) * holder_bounds.width();
if (y < x) {
holder_bounds.ClampToCenteredSize(gfx::Size(
holder_bounds.width(), static_cast<int>(y / capture_size.width())));
} else {
holder_bounds.ClampToCenteredSize(gfx::Size(
static_cast<int>(x / capture_size.height()), holder_bounds.height()));
}
if (!is_letterboxing_) {
is_letterboxing_ = true;
OnLetterboxingChanged();
}
holder_->SetNativeViewSize(capture_size);
holder_->SetBoundsRect(holder_bounds);
}
void WebView::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
if (details.is_add)
AttachWebContentsNativeView();
}
bool WebView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
if (allow_accelerators_)
return FocusManager::IsTabTraversalKeyEvent(event);
// Don't look-up accelerators or tab-traversal if we are showing a non-crashed
// TabContents.
// We'll first give the page a chance to process the key events. If it does
// not process them, they'll be returned to us and we'll treat them as
// accelerators then.
return web_contents() && !web_contents()->IsCrashed();
}
bool WebView::OnMousePressed(const ui::MouseEvent& event) {
// A left-click within WebView is a request to focus. The area within the
// native view child is excluded since it will be handling mouse pressed
// events itself (http://crbug.com/436192).
if (event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) {
gfx::Point location_in_holder = event.location();
ConvertPointToTarget(this, holder_, &location_in_holder);
if (!holder_->HitTestPoint(location_in_holder)) {
RequestFocus();
return true;
}
}
return View::OnMousePressed(event);
}
void WebView::OnFocus() {
if (web_contents() && !web_contents()->IsCrashed())
web_contents()->Focus();
}
void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) {
if (web_contents() && !web_contents()->IsCrashed())
web_contents()->FocusThroughTabTraversal(reverse);
}
void WebView::AddedToWidget() {
if (!web_contents())
return;
web_contents()->SetColorProviderSource(GetWidget());
// If added to a widget hierarchy and |holder_| already has a NativeView
// attached, update the accessible parent here to support reparenting the
// WebView.
if (holder_->native_view())
UpdateNativeViewHostAccessibleParent(holder_, parent());
}
gfx::NativeViewAccessible WebView::GetNativeViewAccessible() {
if (web_contents() && !web_contents()->IsCrashed()) {
content::RenderWidgetHostView* host_view =
web_contents()->GetRenderWidgetHostView();
if (host_view) {
gfx::NativeViewAccessible accessible =
host_view->GetNativeViewAccessible();
// |accessible| needs to know whether this is the primary WebContents.
if (auto* ax_platform_node =
ui::AXPlatformNode::FromNativeViewAccessible(accessible)) {
ax_platform_node->SetIsPrimaryWebContentsForWindow(
is_primary_web_contents_for_window_);
}
return accessible;
}
}
return View::GetNativeViewAccessible();
}
void WebView::OnAXModeAdded(ui::AXMode mode) {
if (!GetWidget() || !web_contents())
return;
// Normally, it is set during AttachWebContentsNativeView when the WebView is
// created but this may not happen on some platforms as the accessible object
// may not have been present when this WebView was created. So, update it when
// AX mode is added.
UpdateNativeViewHostAccessibleParent(holder(), parent());
}
////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsDelegate implementation:
////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsObserver implementation:
void WebView::RenderFrameCreated(content::RenderFrameHost* render_frame_host) {
// Only handle the initial main frame, not speculative ones.
if (render_frame_host != web_contents()->GetPrimaryMainFrame())
return;
SetUpNewMainFrame(render_frame_host);
}
void WebView::RenderFrameDeleted(content::RenderFrameHost* render_frame_host) {
// Only handle the active main frame, not speculative ones.
if (render_frame_host != web_contents()->GetPrimaryMainFrame())
return;
LostMainFrame();
}
void WebView::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
// Since we skipped speculative main frames in RenderFrameCreated, we must
// watch for them being swapped in by watching for RenderFrameHostChanged().
if (new_host != web_contents()->GetPrimaryMainFrame())
return;
// Ignore the initial main frame host, as there's no renderer frame for it
// yet. If the DCHECK fires, then we would need to handle the initial main
// frame when it its renderer frame is created.
if (!old_host) {
DCHECK(!new_host->IsRenderFrameLive());
return;
}
SetUpNewMainFrame(new_host);
}
void WebView::DidToggleFullscreenModeForTab(bool entered_fullscreen,
bool will_cause_resize) {
// Notify a bounds change on fullscreen change even though it actually
// doesn't change. Cast needs this see https://crbug.com/1144255.
OnBoundsChanged(bounds());
NotifyAccessibilityWebContentsChanged();
}
void WebView::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
RequestFocus();
}
void WebView::AXTreeIDForMainFrameHasChanged() {
NotifyAccessibilityWebContentsChanged();
}
void WebView::WebContentsDestroyed() {
SetWebContents(nullptr);
}
void WebView::ResizeDueToAutoResize(content::WebContents* source,
const gfx::Size& new_size) {
if (source != web_contents())
return;
SetPreferredSize(new_size);
}
void WebView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kWebView;
// A webview does not need an accessible name as the document title is
// provided via other means. Providing it here would be redundant.
// Mark the name as explicitly empty so that accessibility_checks pass.
node_data->SetNameExplicitlyEmpty();
}
////////////////////////////////////////////////////////////////////////////////
// WebView, private:
void WebView::AttachWebContentsNativeView() {
TRACE_EVENT0("views", "WebView::AttachWebContentsNativeView");
// Prevents attachment if the WebView isn't already in a Widget, or it's
// already attached.
if (!GetWidget() || !web_contents())
return;
gfx::NativeView view_to_attach = web_contents()->GetNativeView();
OnBoundsChanged(bounds());
if (holder_->native_view() == view_to_attach)
return;
const auto* bg_color =
WebContentsSetBackgroundColor::FromWebContents(web_contents());
if (bg_color) {
holder_->SetBackgroundColorWhenClipped(bg_color->color());
} else {
holder_->SetBackgroundColorWhenClipped(absl::nullopt);
}
holder_->Attach(view_to_attach);
// We set the parent accessible of the native view to be our parent.
UpdateNativeViewHostAccessibleParent(holder(), parent());
// The WebContents is not focused automatically when attached, so we need to
// tell the WebContents it has focus if this has focus.
if (HasFocus())
OnFocus();
OnWebContentsAttached();
}
void WebView::DetachWebContentsNativeView() {
TRACE_EVENT0("views", "WebView::DetachWebContentsNativeView");
if (web_contents()) {
holder_->Detach();
}
}
void WebView::UpdateCrashedOverlayView() {
if (web_contents() && web_contents()->IsCrashed() && crashed_overlay_view_) {
SetFocusBehavior(FocusBehavior::NEVER);
crashed_overlay_view_->SetVisible(true);
return;
}
SetFocusBehavior(web_contents() ? FocusBehavior::ALWAYS
: FocusBehavior::NEVER);
if (crashed_overlay_view_)
crashed_overlay_view_->SetVisible(false);
}
void WebView::NotifyAccessibilityWebContentsChanged() {
content::RenderFrameHost* rfh =
web_contents() ? web_contents()->GetPrimaryMainFrame() : nullptr;
GetViewAccessibility().OverrideChildTreeID(rfh ? rfh->GetAXTreeID()
: ui::AXTreeIDUnknown());
NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, false);
}
std::unique_ptr<content::WebContents> WebView::CreateWebContents(
content::BrowserContext* browser_context,
base::Location creator_location) {
std::unique_ptr<content::WebContents> contents;
if (*GetCreatorForTesting()) {
contents = GetCreatorForTesting()->Run(browser_context);
}
if (!contents) {
content::WebContents::CreateParams create_params(browser_context,
creator_location);
return content::WebContents::Create(create_params);
}
return contents;
}
void WebView::SetUpNewMainFrame(content::RenderFrameHost* frame_host) {
MaybeEnableAutoResize(frame_host);
UpdateCrashedOverlayView();
NotifyAccessibilityWebContentsChanged();
if (HasFocus())
OnFocus();
}
void WebView::LostMainFrame() {
UpdateCrashedOverlayView();
NotifyAccessibilityWebContentsChanged();
}
void WebView::MaybeEnableAutoResize(content::RenderFrameHost* frame_host) {
DCHECK(frame_host->IsRenderFrameLive());
if (!max_size_.IsEmpty())
frame_host->GetView()->EnableAutoResize(min_size_, max_size_);
}
BEGIN_METADATA(WebView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/webview.cc | C++ | unknown | 16,748 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_
#define UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_
#include <stdint.h>
#include <memory>
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "ui/accessibility/ax_mode_observer.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/controls/webview/webview_export.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
namespace views {
// Provides a view of a WebContents instance. WebView can be used standalone,
// creating and displaying an internally-owned WebContents; or within a full
// browser where the browser swaps its own WebContents instances in/out (e.g.,
// for browser tabs).
//
// WebView creates and owns a single child view, a NativeViewHost, which will
// hold and display the native view provided by a WebContents.
//
// EmbedFullscreenWidgetMode: When enabled, WebView will observe for WebContents
// fullscreen changes and automatically swap the normal native view with the
// fullscreen native view (if different). In addition, if the WebContents is
// being screen-captured, the view will be centered within WebView, sized to
// the aspect ratio of the capture video resolution, and scaling will be avoided
// whenever possible.
class WEBVIEW_EXPORT WebView : public View,
public content::WebContentsDelegate,
public content::WebContentsObserver,
public ui::AXModeObserver {
public:
METADATA_HEADER(WebView);
explicit WebView(content::BrowserContext* browser_context = nullptr);
WebView(const WebView&) = delete;
WebView& operator=(const WebView&) = delete;
~WebView() override;
// This creates a WebContents if |browser_context_| has been set and there is
// not yet a WebContents associated with this WebView, otherwise it will
// return a nullptr.
content::WebContents* GetWebContents(
base::Location creator_location = base::Location::Current());
// WebView does not assume ownership of WebContents set via this method, only
// those it implicitly creates via GetWebContents() above.
void SetWebContents(content::WebContents* web_contents);
content::BrowserContext* GetBrowserContext();
void SetBrowserContext(content::BrowserContext* browser_context);
// Loads the initial URL to display in the attached WebContents. Creates the
// WebContents if none is attached yet. Note that this is intended as a
// convenience for loading the initial URL, and so URLs are navigated with
// PAGE_TRANSITION_AUTO_TOPLEVEL, so this is not intended as a general purpose
// navigation method - use WebContents' API directly.
void LoadInitialURL(const GURL& url);
// Controls how the attached WebContents is resized.
// false = WebContents' views' bounds are updated continuously as the
// WebView's bounds change (default).
// true = WebContents' views' position is updated continuously but its size
// is not (which may result in some clipping or under-painting) until
// a continuous size operation completes. This allows for smoother
// resizing performance during interactive resizes and animations.
void SetFastResize(bool fast_resize);
// If enabled, this will make the WebView's preferred size dependent on the
// WebContents' size.
void EnableSizingFromWebContents(const gfx::Size& min_size,
const gfx::Size& max_size);
// Set the background color to use while resizing with a clip. This is white
// by default.
void SetResizeBackgroundColor(SkColor resize_background_color);
// If provided, this View will be shown in place of the web contents
// when the web contents is in a crashed state. This is cleared automatically
// if the web contents is changed.
void SetCrashedOverlayView(View* crashed_overlay_view);
// Sets whether this is the primary web contents for the window.
void set_is_primary_web_contents_for_window(bool is_primary) {
is_primary_web_contents_for_window_ = is_primary;
}
// When used to host UI, we need to explicitly allow accelerators to be
// processed. Default is false.
void set_allow_accelerators(bool allow_accelerators) {
allow_accelerators_ = allow_accelerators;
}
// Overridden from content::WebContentsDelegate:
void ResizeDueToAutoResize(content::WebContents* source,
const gfx::Size& new_size) override;
NativeViewHost* holder() { return holder_; }
using WebContentsCreator =
base::RepeatingCallback<std::unique_ptr<content::WebContents>(
content::BrowserContext*)>;
// An instance of this class registers a WebContentsCreator on construction
// and deregisters the WebContentsCreator on destruction.
class WEBVIEW_EXPORT ScopedWebContentsCreatorForTesting {
public:
explicit ScopedWebContentsCreatorForTesting(WebContentsCreator creator);
ScopedWebContentsCreatorForTesting(
const ScopedWebContentsCreatorForTesting&) = delete;
ScopedWebContentsCreatorForTesting& operator=(
const ScopedWebContentsCreatorForTesting&) = delete;
~ScopedWebContentsCreatorForTesting();
};
// View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
protected:
// Called when the web contents is successfully attached.
virtual void OnWebContentsAttached() {}
// Called when letterboxing (scaling the native view to preserve aspect
// ratio) is enabled or disabled.
virtual void OnLetterboxingChanged() {}
bool is_letterboxing() const { return is_letterboxing_; }
const gfx::Size& min_size() const { return min_size_; }
const gfx::Size& max_size() const { return max_size_; }
// View:
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override;
bool OnMousePressed(const ui::MouseEvent& event) override;
void OnFocus() override;
void AboutToRequestFocusFromTabTraversal(bool reverse) override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void AddedToWidget() override;
// Overridden from content::WebContentsObserver:
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override;
void DidToggleFullscreenModeForTab(bool entered_fullscreen,
bool will_cause_resize) override;
void OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) override;
void AXTreeIDForMainFrameHasChanged() override;
void WebContentsDestroyed() override;
// Override from ui::AXModeObserver
void OnAXModeAdded(ui::AXMode mode) override;
private:
friend class WebViewUnitTest;
void AttachWebContentsNativeView();
void DetachWebContentsNativeView();
void UpdateCrashedOverlayView();
void NotifyAccessibilityWebContentsChanged();
// Called when the main frame in the renderer becomes present.
void SetUpNewMainFrame(content::RenderFrameHost* frame_host);
// Called when the main frame in the renderer is no longer present.
void LostMainFrame();
// Registers for ResizeDueToAutoResize() notifications from `frame_host`'s
// RenderWidgetHostView whenever it is created or changes, if
// EnableSizingFromWebContents() has been called. This should only be called
// for main frames; other frames can not have auto resize set.
void MaybeEnableAutoResize(content::RenderFrameHost* frame_host);
// Create a regular or test web contents (based on whether we're running
// in a unit test or not).
std::unique_ptr<content::WebContents> CreateWebContents(
content::BrowserContext* browser_context,
base::Location creator_location = base::Location::Current());
const raw_ptr<NativeViewHost> holder_ =
AddChildView(std::make_unique<NativeViewHost>());
// Non-NULL if |web_contents()| was created and is owned by this WebView.
std::unique_ptr<content::WebContents> wc_owner_;
// Set to true when |holder_| is letterboxed (scaled to be smaller than this
// view, to preserve its aspect ratio).
bool is_letterboxing_ = false;
raw_ptr<content::BrowserContext> browser_context_;
bool allow_accelerators_ = false;
raw_ptr<View> crashed_overlay_view_ = nullptr;
bool is_primary_web_contents_for_window_ = false;
// Minimum and maximum sizes to determine WebView bounds for auto-resizing.
// Empty if auto resize is not enabled.
gfx::Size min_size_;
gfx::Size max_size_;
};
BEGIN_VIEW_BUILDER(WEBVIEW_EXPORT, WebView, View)
VIEW_BUILDER_PROPERTY(content::BrowserContext*, BrowserContext)
VIEW_BUILDER_PROPERTY(content::WebContents*, WebContents)
VIEW_BUILDER_PROPERTY(bool, FastResize)
VIEW_BUILDER_METHOD(EnableSizingFromWebContents,
const gfx::Size&,
const gfx::Size&)
VIEW_BUILDER_PROPERTY(View*, CrashedOverlayView)
VIEW_BUILDER_METHOD(set_is_primary_web_contents_for_window, bool)
VIEW_BUILDER_METHOD(set_allow_accelerators, bool)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(WEBVIEW_EXPORT, WebView)
#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/webview.h | C++ | unknown | 9,764 |
// 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_WEBVIEW_WEBVIEW_EXPORT_H_
#define UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_EXPORT_H_
// Defines WEBVIEW_EXPORT so that functionality implemented by the webview
// module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(WEBVIEW_IMPLEMENTATION)
#define WEBVIEW_EXPORT __declspec(dllexport)
#else
#define WEBVIEW_EXPORT __declspec(dllimport)
#endif // defined(WEBVIEW_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(WEBVIEW_IMPLEMENTATION)
#define WEBVIEW_EXPORT __attribute__((visibility("default")))
#else
#define WEBVIEW_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define WEBVIEW_EXPORT
#endif
#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/webview_export.h | C | unknown | 878 |
// 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/webview/webview.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "content/test/test_content_browser_client.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/test/widget_test.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace views {
namespace {
// Provides functionality to observe events on a WebContents like
// OnVisibilityChanged/WebContentsDestroyed.
class WebViewTestWebContentsObserver : public content::WebContentsObserver {
public:
explicit WebViewTestWebContentsObserver(content::WebContents* web_contents)
: web_contents_(web_contents) {
content::WebContentsObserver::Observe(web_contents);
}
WebViewTestWebContentsObserver(const WebViewTestWebContentsObserver&) =
delete;
WebViewTestWebContentsObserver& operator=(
const WebViewTestWebContentsObserver&) = delete;
~WebViewTestWebContentsObserver() override {
if (web_contents_)
content::WebContentsObserver::Observe(nullptr);
}
void WebContentsDestroyed() override {
DCHECK(web_contents_);
content::WebContentsObserver::Observe(nullptr);
web_contents_ = nullptr;
}
void OnVisibilityChanged(content::Visibility visibility) override {
switch (visibility) {
case content::Visibility::VISIBLE: {
#if defined(USE_AURA)
valid_root_while_shown_ =
web_contents()->GetNativeView()->GetRootWindow() != nullptr;
#endif
was_shown_ = true;
++shown_count_;
break;
}
case content::Visibility::HIDDEN: {
was_shown_ = false;
++hidden_count_;
break;
}
default: {
ADD_FAILURE() << "Unexpected call to OnVisibilityChanged.";
break;
}
}
}
bool was_shown() const { return was_shown_; }
int shown_count() const { return shown_count_; }
int hidden_count() const { return hidden_count_; }
bool valid_root_while_shown() const { return valid_root_while_shown_; }
private:
raw_ptr<content::WebContents> web_contents_;
bool was_shown_ = false;
int32_t shown_count_ = 0;
int32_t hidden_count_ = 0;
// Set to true if the view containing the webcontents has a valid root window.
bool valid_root_while_shown_ = true;
};
// Fakes the fullscreen browser state reported to WebContents and WebView.
class WebViewTestWebContentsDelegate : public content::WebContentsDelegate {
public:
WebViewTestWebContentsDelegate() = default;
WebViewTestWebContentsDelegate(const WebViewTestWebContentsDelegate&) =
delete;
WebViewTestWebContentsDelegate& operator=(
const WebViewTestWebContentsDelegate&) = delete;
~WebViewTestWebContentsDelegate() override = default;
void set_is_fullscreened(bool fs) { is_fullscreened_ = fs; }
// content::WebContentsDelegate overrides.
bool IsFullscreenForTabOrPending(
const content::WebContents* ignored) override {
return is_fullscreened_;
}
private:
bool is_fullscreened_ = false;
};
} // namespace
// Provides functionality to test a WebView.
class WebViewUnitTest : public views::test::WidgetTest {
public:
WebViewUnitTest()
: views::test::WidgetTest(std::unique_ptr<base::test::TaskEnvironment>(
std::make_unique<content::BrowserTaskEnvironment>())) {}
WebViewUnitTest(const WebViewUnitTest&) = delete;
WebViewUnitTest& operator=(const WebViewUnitTest&) = delete;
~WebViewUnitTest() override = default;
std::unique_ptr<content::WebContents> CreateWebContentsForWebView(
content::BrowserContext* browser_context) {
return content::WebContentsTester::CreateTestWebContents(browser_context,
nullptr);
}
void SetUp() override {
rvh_enabler_ = std::make_unique<content::RenderViewHostTestEnabler>();
views::WebView::WebContentsCreator creator = base::BindRepeating(
&WebViewUnitTest::CreateWebContentsForWebView, base::Unretained(this));
scoped_web_contents_creator_ =
std::make_unique<views::WebView::ScopedWebContentsCreatorForTesting>(
creator);
browser_context_ = std::make_unique<content::TestBrowserContext>();
WidgetTest::SetUp();
// Set the test content browser client to avoid pulling in needless
// dependencies from content.
SetBrowserClientForTesting(&test_browser_client_);
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisableBackgroundingOccludedWindowsForTesting);
// Create a top level widget and add a child, and give it a WebView as a
// child.
top_level_widget_ = CreateTopLevelFramelessPlatformWidget();
top_level_widget_->SetBounds(gfx::Rect(0, 10, 100, 100));
View* const contents_view =
top_level_widget_->SetContentsView(std::make_unique<View>());
auto web_view = std::make_unique<WebView>(browser_context_.get());
web_view->SetBoundsRect(gfx::Rect(contents_view->size()));
web_view_ = contents_view->AddChildView(std::move(web_view));
top_level_widget_->Show();
ASSERT_EQ(gfx::Rect(0, 0, 100, 100), web_view_->bounds());
}
void TearDown() override {
scoped_web_contents_creator_.reset();
top_level_widget_->Close(); // Deletes all children and itself.
RunPendingMessages();
browser_context_.reset(nullptr);
// Flush the message loop to execute pending relase tasks as this would
// upset ASAN and Valgrind.
RunPendingMessages();
WidgetTest::TearDown();
}
protected:
Widget* top_level_widget() const { return top_level_widget_; }
WebView* web_view() const { return web_view_; }
NativeViewHost* holder() const { return web_view_->holder_; }
std::unique_ptr<content::WebContents> CreateWebContents() const {
return content::WebContents::Create(
content::WebContents::CreateParams(browser_context_.get()));
}
std::unique_ptr<content::WebContents> CreateTestWebContents() const {
return content::WebContentsTester::CreateTestWebContents(
browser_context_.get(), /*instance=*/nullptr);
}
void SetAXMode(ui::AXMode mode) { web_view()->OnAXModeAdded(mode); }
private:
std::unique_ptr<content::RenderViewHostTestEnabler> rvh_enabler_;
std::unique_ptr<content::TestBrowserContext> browser_context_;
content::TestContentBrowserClient test_browser_client_;
std::unique_ptr<views::WebView::ScopedWebContentsCreatorForTesting>
scoped_web_contents_creator_;
raw_ptr<Widget> top_level_widget_ = nullptr;
raw_ptr<WebView> web_view_ = nullptr;
};
// Tests that attaching and detaching a WebContents to a WebView makes the
// WebContents visible and hidden respectively.
TEST_F(WebViewUnitTest, TestWebViewAttachDetachWebContents) {
// Case 1: Create a new WebContents and set it in the webview via
// SetWebContents. This should make the WebContents visible.
const std::unique_ptr<content::WebContents> web_contents1(
CreateWebContents());
WebViewTestWebContentsObserver observer1(web_contents1.get());
EXPECT_FALSE(observer1.was_shown());
web_view()->SetWebContents(web_contents1.get());
// Layout is normally async, ensure it runs now so visibility is updated.
views::test::RunScheduledLayout(web_view());
EXPECT_TRUE(observer1.was_shown());
#if defined(USE_AURA)
EXPECT_TRUE(web_contents1->GetNativeView()->IsVisible());
#endif
EXPECT_EQ(observer1.shown_count(), 1);
EXPECT_EQ(observer1.hidden_count(), 0);
EXPECT_TRUE(observer1.valid_root_while_shown());
// Case 2: Create another WebContents and replace the current WebContents
// via SetWebContents(). This should hide the current WebContents and show
// the new one.
const std::unique_ptr<content::WebContents> web_contents2(
CreateWebContents());
WebViewTestWebContentsObserver observer2(web_contents2.get());
EXPECT_FALSE(observer2.was_shown());
// Setting the new WebContents should hide the existing one.
web_view()->SetWebContents(web_contents2.get());
// Layout is normally async, ensure it runs now so visibility is updated.
views::test::RunScheduledLayout(web_view());
EXPECT_FALSE(observer1.was_shown());
EXPECT_TRUE(observer2.was_shown());
EXPECT_TRUE(observer2.valid_root_while_shown());
// WebContents1 should not get stray show calls when WebContents2 is set.
EXPECT_EQ(observer1.shown_count(), 1);
EXPECT_EQ(observer1.hidden_count(), 1);
EXPECT_EQ(observer2.shown_count(), 1);
EXPECT_EQ(observer2.hidden_count(), 0);
// Case 3: Test that attaching to a hidden webview does not show the web
// contents.
web_view()->SetVisible(false);
EXPECT_EQ(1, observer2.hidden_count()); // Now hidden.
EXPECT_EQ(1, observer1.shown_count());
web_view()->SetWebContents(web_contents1.get());
// Layout is normally async, ensure it runs now so visibility is updated.
views::test::RunScheduledLayout(web_view());
EXPECT_EQ(1, observer1.shown_count());
// Nothing else should change.
EXPECT_EQ(1, observer1.hidden_count());
EXPECT_EQ(1, observer2.shown_count());
EXPECT_EQ(1, observer2.hidden_count());
#if defined(USE_AURA)
// Case 4: Test that making the webview visible when a window has an invisible
// parent does not make the web contents visible.
top_level_widget()->Hide();
web_view()->SetVisible(true);
EXPECT_EQ(1, observer1.shown_count());
top_level_widget()->Show();
EXPECT_EQ(2, observer1.shown_count());
top_level_widget()->Hide();
EXPECT_EQ(2, observer1.hidden_count());
#else
// On Mac, changes to window visibility do not trigger calls to WebContents::
// WasShown() or WasHidden(), since the OS does not provide good signals for
// window visibility. However, we can still test that moving a visible WebView
// whose WebContents is not currently showing to a new, visible window will
// show the WebContents. Simulate the "hide window with visible WebView" step
// simply by detaching the WebContents.
web_view()->SetVisible(true);
EXPECT_EQ(2, observer1.shown_count());
web_view()->holder()->Detach();
EXPECT_EQ(2, observer1.hidden_count());
#endif
// Case 5: Test that moving from a hidden parent to a visible parent makes the
// web contents visible.
Widget* parent2 = CreateTopLevelFramelessPlatformWidget();
parent2->SetBounds(gfx::Rect(0, 10, 100, 100));
parent2->Show();
EXPECT_EQ(2, observer1.shown_count());
// Note: that reparenting the windows directly, after the windows have been
// created, e.g., Widget::ReparentNativeView(widget, parent2), is not a
// supported use case. Instead, move the WebView over.
parent2->SetContentsView(web_view()->parent()->RemoveChildViewT(web_view()));
EXPECT_EQ(3, observer1.shown_count());
parent2->Close();
}
// Verifies that there is no crash in WebView destructor
// if WebView is already removed from Widget.
TEST_F(WebViewUnitTest, DetachedWebViewDestructor) {
// Init WebView with attached NativeView.
const std::unique_ptr<content::WebContents> web_contents =
CreateWebContents();
std::unique_ptr<WebView> webview(
new WebView(web_contents->GetBrowserContext()));
View* contents_view = top_level_widget()->GetContentsView();
contents_view->AddChildView(webview.get());
webview->SetWebContents(web_contents.get());
// Remove WebView from views hierarchy. NativeView should be detached
// from Widget.
contents_view->RemoveChildView(webview.get());
// Destroy WebView. NativeView should be detached secondary.
// There should be no crash.
webview.reset();
}
// Test that the specified crashed overlay view is shown when a WebContents
// is in a crashed state.
TEST_F(WebViewUnitTest, CrashedOverlayView) {
const std::unique_ptr<content::WebContents> web_contents =
CreateTestWebContents();
content::WebContentsTester* tester =
content::WebContentsTester::For(web_contents.get());
std::unique_ptr<WebView> web_view(
new WebView(web_contents->GetBrowserContext()));
View* contents_view = top_level_widget()->GetContentsView();
contents_view->AddChildView(web_view.get());
web_view->SetWebContents(web_contents.get());
View* crashed_overlay_view = new View();
web_view->SetCrashedOverlayView(crashed_overlay_view);
EXPECT_FALSE(crashed_overlay_view->IsDrawn());
// Normally when a renderer crashes, the WebView will learn about it
// automatically via WebContentsObserver. Since this is a test
// WebContents, simulate that by calling SetIsCrashed and then
// explicitly calling RenderFrameDeleted on the WebView to trigger it
// to swap in the crashed overlay view.
tester->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1);
EXPECT_TRUE(web_contents->IsCrashed());
static_cast<content::WebContentsObserver*>(web_view.get())
->RenderFrameDeleted(web_contents->GetPrimaryMainFrame());
EXPECT_TRUE(crashed_overlay_view->IsDrawn());
}
// Test that a crashed overlay view isn't deleted if it's owned by client.
TEST_F(WebViewUnitTest, CrashedOverlayViewOwnedbyClient) {
const std::unique_ptr<content::WebContents> web_contents =
CreateTestWebContents();
content::WebContentsTester* tester =
content::WebContentsTester::For(web_contents.get());
std::unique_ptr<WebView> web_view(
new WebView(web_contents->GetBrowserContext()));
View* contents_view = top_level_widget()->GetContentsView();
contents_view->AddChildView(web_view.get());
web_view->SetWebContents(web_contents.get());
View* crashed_overlay_view = new View();
crashed_overlay_view->set_owned_by_client();
web_view->SetCrashedOverlayView(crashed_overlay_view);
EXPECT_FALSE(crashed_overlay_view->IsDrawn());
// Simulate a renderer crash (see above).
tester->SetIsCrashed(base::TERMINATION_STATUS_PROCESS_CRASHED, -1);
EXPECT_TRUE(web_contents->IsCrashed());
static_cast<content::WebContentsObserver*>(web_view.get())
->RenderFrameDeleted(web_contents->GetPrimaryMainFrame());
EXPECT_TRUE(crashed_overlay_view->IsDrawn());
web_view->SetCrashedOverlayView(nullptr);
web_view.reset();
// This shouldn't crash, we still own this.
delete crashed_overlay_view;
}
// Tests to make sure we can default construct the WebView class and set the
// BrowserContext after construction.
TEST_F(WebViewUnitTest, DefaultConstructability) {
auto browser_context = std::make_unique<content::TestBrowserContext>();
auto web_view = std::make_unique<WebView>();
// Test to make sure the WebView returns a nullptr in the absence of an
// explicitly supplied WebContents and BrowserContext.
EXPECT_EQ(nullptr, web_view->GetWebContents());
web_view->SetBrowserContext(browser_context.get());
// WebView should be able to create a WebContents object from the previously
// set |browser_context|.
auto* web_contents = web_view->GetWebContents();
EXPECT_NE(nullptr, web_contents);
EXPECT_EQ(browser_context.get(), web_contents->GetBrowserContext());
}
// Tests that when a web view is reparented to a different widget hierarchy its
// holder's parent NativeViewAccessible matches that of its parent view's
// NativeViewAccessible.
TEST_F(WebViewUnitTest, ReparentingUpdatesParentAccessible) {
const std::unique_ptr<content::WebContents> web_contents =
CreateWebContents();
auto web_view = std::make_unique<WebView>(web_contents->GetBrowserContext());
web_view->SetWebContents(web_contents.get());
WidgetAutoclosePtr widget_1(CreateTopLevelPlatformWidget());
View* contents_view_1 = widget_1->GetContentsView();
WebView* added_web_view = contents_view_1->AddChildView(std::move(web_view));
// After being added to the widget hierarchy the holder's NativeViewAccessible
// should match that of the web view's parent view.
EXPECT_EQ(added_web_view->parent()->GetNativeViewAccessible(),
added_web_view->holder()->GetParentAccessible());
WidgetAutoclosePtr widget_2(CreateTopLevelPlatformWidget());
View* contents_view_2 = widget_2->GetContentsView();
// Reparent the web view.
added_web_view = contents_view_2->AddChildView(
contents_view_1->RemoveChildViewT(added_web_view));
// After reparenting the holder's NativeViewAccessible should match that of
// the web view's new parent view.
EXPECT_EQ(added_web_view->parent()->GetNativeViewAccessible(),
added_web_view->holder()->GetParentAccessible());
}
// This tests that we don't crash if WebView doesn't have a Widget or a
// Webcontents. https://crbug.com/1191999
TEST_F(WebViewUnitTest, ChangeAXMode) {
// Case 1: WebView has a Widget and no WebContents.
SetAXMode(ui::AXMode::kFirstModeFlag);
// Case 2: WebView has no Widget and a WebContents.
View* contents_view = top_level_widget()->GetContentsView();
contents_view->RemoveChildView(web_view());
const std::unique_ptr<content::WebContents> web_contents =
CreateWebContents();
web_view()->SetWebContents(web_contents.get());
SetAXMode(ui::AXMode::kFirstModeFlag);
// No crash.
}
// Tests to make sure the WebView clears away the reference to its hosted
// WebContents object when its deleted.
TEST_F(WebViewUnitTest, WebViewClearsWebContentsOnDestruction) {
std::unique_ptr<content::WebContents> web_contents = CreateWebContents();
web_view()->SetWebContents(web_contents.get());
EXPECT_EQ(web_contents.get(), web_view()->web_contents());
web_contents.reset();
EXPECT_EQ(nullptr, web_view()->web_contents());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/controls/webview/webview_unittest.cc | C++ | unknown | 18,284 |
# This code should not depend on Views.
include_rules = [
"-ui/views",
"+ui/views/buildflags.h",
"+ui/views/corewm",
"+ui/views/views_export.h",
"+ui/views/views_features.h"
]
# TODO: temporary, don't add more.
specific_include_rules = {
"tooltip_controller.cc": [
"+ui/views/widget/tooltip_manager.h",
],
"tooltip_aura.cc": [
"+ui/views/widget/widget.h",
],
"tooltip_view_aura.cc": [
"+ui/base/metadata/metadata_header_macros.h",
"+ui/base/metadata/metadata_impl_macros.h",
"+ui/views/background.h",
"+ui/views/border.h",
"+ui/views/painter.h",
],
"tooltip_lacros.cc": [
"+ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h",
],
"desktop_capture_controller_unittest.cc": [
"+ui/views/test/native_widget_factory.h",
"+ui/views/test/widget_test.h",
"+ui/views/view.h",
"+ui/views/widget/desktop_aura/desktop_native_widget_aura.h",
"+ui/views/widget/desktop_aura/desktop_screen_position_client.h",
"+ui/views/widget/root_view.h",
"+ui/views/widget/widget.h",
],
"tooltip_controller_unittest.cc": [
"+ui/views/test/desktop_test_views_delegate.h",
"+ui/views/test/native_widget_factory.h",
"+ui/views/test/test_views_delegate.h",
"+ui/views/test/views_test_base.h",
"+ui/views/view.h",
"+ui/views/widget/desktop_aura/desktop_native_widget_aura.h",
"+ui/views/widget/desktop_aura/desktop_screen.h",
"+ui/views/widget/tooltip_manager.h",
"+ui/views/widget/widget.h",
],
"tooltip_aura.h": [
"+ui/views/widget/widget_observer.h",
],
"tooltip_view_aura.h": [
"+ui/views/view.h",
],
"tooltip_controller_test_helper.h": [
"+ui/views/view.h",
],
"capture_controller_unittest.cc": [
"+ui/views/test/views_test_base.h",
"+ui/views/view.h",
"+ui/views/widget/desktop_aura/desktop_native_widget_aura.h",
"+ui/views/widget/desktop_aura/desktop_screen_position_client.h",
"+ui/views/widget/root_view.h",
"+ui/views/widget/widget.h",
],
}
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/DEPS | Python | unknown | 2,025 |
// 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 <memory>
#include "ui/aura/env.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/events/event.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/capture_controller.h"
// NOTE: these tests do native capture, so they have to be in
// interactive_ui_tests.
namespace views {
using DesktopCaptureControllerTest = test::DesktopWidgetTestInteractive;
// This class provides functionality to verify whether the View instance
// received the gesture event.
class DesktopViewInputTest : public View {
public:
DesktopViewInputTest() = default;
DesktopViewInputTest(const DesktopViewInputTest&) = delete;
DesktopViewInputTest& operator=(const DesktopViewInputTest&) = delete;
void OnGestureEvent(ui::GestureEvent* event) override {
received_gesture_event_ = true;
return View::OnGestureEvent(event);
}
// Resets state maintained by this class.
void Reset() { received_gesture_event_ = false; }
bool received_gesture_event() const { return received_gesture_event_; }
private:
bool received_gesture_event_ = false;
};
views::Widget* CreateWidget() {
views::Widget* widget = new views::Widget;
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
params.accept_events = true;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.native_widget = new DesktopNativeWidgetAura(widget);
params.bounds = gfx::Rect(0, 0, 200, 100);
widget->Init(std::move(params));
widget->Show();
return widget;
}
// Verifies mouse handlers are reset when a window gains capture. Specifically
// creates two widgets, does a mouse press in one, sets capture in the other and
// verifies state is reset in the first.
TEST_F(DesktopCaptureControllerTest, ResetMouseHandlers) {
std::unique_ptr<Widget> w1(CreateWidget());
std::unique_ptr<Widget> w2(CreateWidget());
ui::test::EventGenerator generator1(w1->GetNativeView()->GetRootWindow());
generator1.MoveMouseToCenterOf(w1->GetNativeView());
generator1.PressLeftButton();
EXPECT_FALSE(w1->HasCapture());
aura::WindowEventDispatcher* w1_dispatcher =
w1->GetNativeView()->GetHost()->dispatcher();
EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() != nullptr);
EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() != nullptr);
w2->SetCapture(w2->GetRootView());
EXPECT_TRUE(w2->HasCapture());
EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() == nullptr);
EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() == nullptr);
w2->ReleaseCapture();
RunPendingMessages();
}
// Tests aura::Window capture and whether gesture events are sent to the window
// which has capture.
// The test case creates two visible widgets and sets capture to the underlying
// aura::Windows one by one. It then sends a gesture event and validates whether
// the window which had capture receives the gesture.
// TODO(sky): move this test, it should be part of ScopedCaptureClient tests.
TEST_F(DesktopCaptureControllerTest, CaptureWindowInputEventTest) {
std::unique_ptr<aura::client::ScreenPositionClient> desktop_position_client1;
std::unique_ptr<aura::client::ScreenPositionClient> desktop_position_client2;
std::unique_ptr<Widget> widget1(new Widget());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
std::unique_ptr<wm::ScopedCaptureClient> scoped_capture_client(
new wm::ScopedCaptureClient(params.context->GetRootWindow()));
aura::client::CaptureClient* capture_client = wm::CaptureController::Get();
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
params.native_widget = test::CreatePlatformNativeWidgetImpl(
widget1.get(), test::kStubCapture, nullptr);
desktop_position_client1 = std::make_unique<DesktopScreenPositionClient>(
params.context->GetRootWindow());
widget1->Init(std::move(params));
internal::RootView* root1 =
static_cast<internal::RootView*>(widget1->GetRootView());
aura::client::SetScreenPositionClient(
widget1->GetNativeView()->GetRootWindow(),
desktop_position_client1.get());
DesktopViewInputTest* v1 = new DesktopViewInputTest();
v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
root1->AddChildView(v1);
widget1->Show();
std::unique_ptr<Widget> widget2(new Widget());
params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(50, 50, 650, 650);
params.native_widget = test::CreatePlatformNativeWidgetImpl(
widget2.get(), test::kStubCapture, nullptr);
desktop_position_client2 = std::make_unique<DesktopScreenPositionClient>(
params.context->GetRootWindow());
widget2->Init(std::move(params));
internal::RootView* root2 =
static_cast<internal::RootView*>(widget2->GetRootView());
aura::client::SetScreenPositionClient(
widget2->GetNativeView()->GetRootWindow(),
desktop_position_client2.get());
ui::EventDispatchDetails details;
DesktopViewInputTest* v2 = new DesktopViewInputTest();
v2->SetBoundsRect(gfx::Rect(0, 0, 300, 300));
root2->AddChildView(v2);
widget2->Show();
EXPECT_FALSE(widget1->GetNativeView()->HasCapture());
EXPECT_FALSE(widget2->GetNativeView()->HasCapture());
EXPECT_EQ(nullptr, capture_client->GetCaptureWindow());
widget1->GetNativeView()->SetCapture();
EXPECT_TRUE(widget1->GetNativeView()->HasCapture());
EXPECT_FALSE(widget2->GetNativeView()->HasCapture());
EXPECT_EQ(capture_client->GetCaptureWindow(), widget1->GetNativeView());
ui::GestureEvent g1(80, 80, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
details = root1->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_TRUE(v1->received_gesture_event());
EXPECT_FALSE(v2->received_gesture_event());
v1->Reset();
v2->Reset();
widget2->GetNativeView()->SetCapture();
EXPECT_FALSE(widget1->GetNativeView()->HasCapture());
EXPECT_TRUE(widget2->GetNativeView()->HasCapture());
EXPECT_EQ(capture_client->GetCaptureWindow(), widget2->GetNativeView());
details = root2->OnEventFromSource(&g1);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_FALSE(details.target_destroyed);
EXPECT_TRUE(v2->received_gesture_event());
EXPECT_FALSE(v1->received_gesture_event());
widget1->CloseNow();
widget2->CloseNow();
RunPendingMessages();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/desktop_capture_controller_unittest.cc | C++ | unknown | 7,100 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/corewm/test/tooltip_aura_test_api.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/render_text.h"
#include "ui/views/corewm/tooltip_aura.h"
namespace views::corewm::test {
const gfx::RenderText* TooltipAuraTestApi::GetRenderText() const {
return tooltip_aura_->GetRenderTextForTest();
}
void TooltipAuraTestApi::GetAccessibleNodeData(ui::AXNodeData* node_data) {
return tooltip_aura_->GetAccessibleNodeDataForTest(node_data);
}
gfx::Rect TooltipAuraTestApi::GetTooltipBounds(const gfx::Size& tooltip_size,
const gfx::Point& anchor_point,
const TooltipTrigger trigger) {
ui::OwnedWindowAnchor anchor;
return tooltip_aura_->GetTooltipBounds(tooltip_size, anchor_point, trigger,
&anchor);
}
} // namespace views::corewm::test
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/test/tooltip_aura_test_api.cc | C++ | unknown | 1,160 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_COREWM_TEST_TOOLTIP_AURA_TEST_API_H_
#define UI_VIEWS_COREWM_TEST_TOOLTIP_AURA_TEST_API_H_
#include <stddef.h>
#include "base/memory/raw_ptr.h"
namespace gfx {
class Point;
class Rect;
class RenderText;
class Size;
}
namespace ui {
struct AXNodeData;
}
namespace views::corewm {
class TooltipAura;
enum class TooltipTrigger;
namespace test {
class TooltipAuraTestApi {
public:
explicit TooltipAuraTestApi(TooltipAura* tooltip_aura)
: tooltip_aura_(tooltip_aura) {}
TooltipAuraTestApi(const TooltipAuraTestApi&) = delete;
TooltipAuraTestApi& operator=(const TooltipAuraTestApi&) = delete;
const gfx::RenderText* GetRenderText() const;
void GetAccessibleNodeData(ui::AXNodeData* node_data);
gfx::Rect GetTooltipBounds(const gfx::Size& tooltip_size,
const gfx::Point& anchor_point,
const TooltipTrigger trigger);
private:
raw_ptr<TooltipAura> tooltip_aura_;
};
} // namespace test
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TEST_TOOLTIP_AURA_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/test/tooltip_aura_test_api.h | C++ | unknown | 1,221 |
// 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_COREWM_TOOLTIP_H_
#define UI_VIEWS_COREWM_TOOLTIP_H_
#include <string>
#include "build/chromeos_buildflags.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
}
namespace base {
class TimeDelta;
}
namespace gfx {
class Point;
class Rect;
} // namespace gfx
namespace wm {
class TooltipObserver;
}
namespace views::corewm {
enum class TooltipTrigger {
kCursor,
kKeyboard,
};
// Tooltip is responsible for showing the tooltip in an appropriate manner.
// Tooltip is used by TooltipController.
class VIEWS_EXPORT Tooltip {
public:
virtual ~Tooltip() = default;
virtual void AddObserver(wm::TooltipObserver* observer) = 0;
virtual void RemoveObserver(wm::TooltipObserver* observer) = 0;
// Returns the max width of the tooltip when shown at the specified location.
virtual int GetMaxWidth(const gfx::Point& location) const = 0;
// Updates the text on the tooltip and resizes to fit.
// `position` is relative to `window` and in `window` coordinate space.
virtual void Update(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
const TooltipTrigger trigger) = 0;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// Sets show/hide delay. Only used for Lacros.
virtual void SetDelay(const base::TimeDelta& show_delay,
const base::TimeDelta& hide_delay) {}
// Called when tooltip is shown/hidden on server.
// Only used by Lacros.
virtual void OnTooltipShownOnServer(const std::u16string& text,
const gfx::Rect& bounds) {}
virtual void OnTooltipHiddenOnServer() {}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
// Shows the tooltip at the specified location (in screen coordinates).
virtual void Show() = 0;
// Hides the tooltip.
virtual void Hide() = 0;
// Is the tooltip visible?
virtual bool IsVisible() = 0;
protected:
// Max visual tooltip width. If a tooltip is greater than this width, it will
// be wrapped.
static constexpr int kTooltipMaxWidth = 800;
};
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TOOLTIP_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip.h | C++ | unknown | 2,317 |
// 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/corewm/tooltip_aura.h"
#include <algorithm>
#include <utility>
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_split.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/metadata/metadata_header_macros.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/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/text_utils.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/public/tooltip_observer.h"
namespace {
// TODO(varkha): Update if native widget can be transparent on Linux.
bool CanUseTranslucentTooltipWidget() {
// 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)) || BUILDFLAG(IS_WIN)
return false;
#else
return true;
#endif
}
} // namespace
namespace views::corewm {
// static
const char TooltipAura::kWidgetName[] = "TooltipAura";
TooltipAura::TooltipAura()
: TooltipAura(base::BindRepeating(
[]() { return std::make_unique<TooltipViewAura>(); })) {}
TooltipAura::TooltipAura(
const TooltipAura::TooltipViewFactory& tooltip_view_factory)
: tooltip_view_factory_(tooltip_view_factory) {}
TooltipAura::~TooltipAura() {
DestroyWidget();
CHECK(!IsInObserverList());
}
void TooltipAura::AddObserver(wm::TooltipObserver* observer) {
observers_.AddObserver(observer);
}
void TooltipAura::RemoveObserver(wm::TooltipObserver* observer) {
observers_.RemoveObserver(observer);
}
// static
void TooltipAura::AdjustToCursor(gfx::Rect* anchor_point) {
// TODO(crbug.com/1410707): Should adjust with actual cursor size.
anchor_point->Offset(kCursorOffsetX, kCursorOffsetY);
}
class TooltipAura::TooltipWidget : public Widget {
public:
TooltipWidget() = default;
~TooltipWidget() override = default;
TooltipViewAura* GetTooltipView() { return tooltip_view_; }
void SetTooltipView(std::unique_ptr<TooltipViewAura> tooltip_view) {
tooltip_view_ = SetContentsView(std::move(tooltip_view));
}
private:
raw_ptr<TooltipViewAura> tooltip_view_ = nullptr;
};
const gfx::RenderText* TooltipAura::GetRenderTextForTest() const {
DCHECK(widget_);
return widget_->GetTooltipView()->render_text();
}
void TooltipAura::GetAccessibleNodeDataForTest(ui::AXNodeData* node_data) {
DCHECK(widget_);
widget_->GetTooltipView()->GetAccessibleNodeData(node_data);
}
gfx::Rect TooltipAura::GetTooltipBounds(const gfx::Size& tooltip_size,
const gfx::Point& anchor_point,
const TooltipTrigger trigger,
ui::OwnedWindowAnchor* anchor) {
gfx::Rect tooltip_rect(anchor_point, tooltip_size);
// When the tooltip is showing up as a result of a cursor event, the tooltip
// needs to show up at the bottom-right corner of the cursor. When it's not,
// it has to be centered with the anchor point with pass it.
switch (trigger) {
case TooltipTrigger::kKeyboard:
tooltip_rect.Offset(-tooltip_size.width() / 2, 0);
break;
case TooltipTrigger::kCursor: {
const int x_offset =
base::i18n::IsRTL() ? -tooltip_size.width() : kCursorOffsetX;
tooltip_rect.Offset(x_offset, kCursorOffsetY);
break;
}
}
anchor->anchor_gravity = ui::OwnedWindowAnchorGravity::kBottomRight;
anchor->anchor_position = trigger == TooltipTrigger::kCursor
? ui::OwnedWindowAnchorPosition::kBottomRight
: ui::OwnedWindowAnchorPosition::kTop;
anchor->constraint_adjustment =
ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideX |
ui::OwnedWindowConstraintAdjustment::kAdjustmentSlideY |
ui::OwnedWindowConstraintAdjustment::kAdjustmentFlipY;
// TODO(msisov): handle RTL.
anchor->anchor_rect =
gfx::Rect(anchor_point, {kCursorOffsetX, kCursorOffsetY});
display::Screen* screen = display::Screen::GetScreen();
gfx::Rect display_bounds(
screen->GetDisplayNearestPoint(anchor_point).bounds());
// If tooltip is out of bounds on the x axis, we simply shift it
// horizontally by the offset variation.
if (tooltip_rect.x() < display_bounds.x()) {
int delta = tooltip_rect.x() - display_bounds.x();
tooltip_rect.Offset(delta, 0);
}
if (tooltip_rect.right() > display_bounds.right()) {
int delta = tooltip_rect.right() - display_bounds.right();
tooltip_rect.Offset(-delta, 0);
}
// If tooltip is out of bounds on the y axis, we flip it to appear above the
// mouse cursor instead of below.
if (tooltip_rect.bottom() > display_bounds.bottom())
tooltip_rect.set_y(anchor_point.y() - tooltip_size.height());
tooltip_rect.AdjustToFit(display_bounds);
return tooltip_rect;
}
void TooltipAura::CreateTooltipWidget(const gfx::Rect& bounds,
const ui::OwnedWindowAnchor& anchor) {
DCHECK(!widget_);
DCHECK(tooltip_window_);
widget_ = new TooltipWidget;
views::Widget::InitParams params;
// For aura, since we set the type to TYPE_TOOLTIP, the widget will get
// auto-parented to the right container.
params.type = views::Widget::InitParams::TYPE_TOOLTIP;
params.context = tooltip_window_;
DCHECK(params.context);
params.z_order = ui::ZOrderLevel::kFloatingUIElement;
params.accept_events = false;
params.bounds = bounds;
if (CanUseTranslucentTooltipWidget())
params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
params.shadow_type = views::Widget::InitParams::ShadowType::kNone;
// Use software compositing to avoid using unnecessary hardware resources
// which just amount to overkill for this UI.
params.force_software_compositing = true;
params.name = kWidgetName;
params.init_properties_container.SetProperty(aura::client::kOwnedWindowAnchor,
anchor);
widget_->Init(std::move(params));
}
void TooltipAura::DestroyWidget() {
if (widget_) {
widget_->RemoveObserver(this);
widget_->Close();
widget_ = nullptr;
}
}
int TooltipAura::GetMaxWidth(const gfx::Point& location) const {
display::Screen* screen = display::Screen::GetScreen();
gfx::Rect display_bounds(screen->GetDisplayNearestPoint(location).bounds());
return std::min(kTooltipMaxWidth, (display_bounds.width() + 1) / 2);
}
void TooltipAura::Update(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
const TooltipTrigger trigger) {
// Hide() must be called before showing the next tooltip. See also the
// comment in Hide().
DCHECK(!widget_);
tooltip_window_ = window;
auto new_tooltip_view = tooltip_view_factory_.Run();
// Convert `position` to screen coordinates.
gfx::Point anchor_point = position;
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(window->GetRootWindow());
screen_position_client->ConvertPointToScreen(window, &anchor_point);
new_tooltip_view->SetMaxWidth(GetMaxWidth(anchor_point));
new_tooltip_view->SetText(tooltip_text);
ui::OwnedWindowAnchor anchor;
auto bounds = GetTooltipBounds(new_tooltip_view->GetPreferredSize(),
anchor_point, trigger, &anchor);
CreateTooltipWidget(bounds, anchor);
widget_->SetTooltipView(std::move(new_tooltip_view));
widget_->AddObserver(this);
}
void TooltipAura::Show() {
if (widget_) {
widget_->Show();
if (!base::FeatureList::IsEnabled(views::features::kWidgetLayering))
widget_->StackAtTop();
widget_->GetTooltipView()->NotifyAccessibilityEvent(
ax::mojom::Event::kTooltipOpened, true);
// Add distance between `tooltip_window_` and its toplevel window to bounds
// to pass via NotifyTooltipShown() since client will use this bounds as
// relative to wayland toplevel window.
// TODO(crbug.com/1385219): Use `tooltip_window_` instead of its toplevel
// window when WaylandWindow on ozone becomes available.
aura::Window* toplevel_window = tooltip_window_->GetToplevelWindow();
// `tooltip_window_`'s toplevel window may be null for testing.
if (toplevel_window) {
gfx::Rect bounds = widget_->GetWindowBoundsInScreen();
aura::Window::ConvertRectToTarget(tooltip_window_, toplevel_window,
&bounds);
for (auto& observer : observers_) {
observer.OnTooltipShown(
toplevel_window, widget_->GetTooltipView()->render_text()->text(),
bounds);
}
}
}
}
void TooltipAura::Hide() {
if (widget_) {
// If we simply hide the widget there's a chance to briefly show outdated
// information on the next Show() because the text isn't updated until
// OnPaint() which happens asynchronously after the Show(). As a result,
// we can just destroy the widget and create a new one each time which
// guarantees we never show outdated information.
// TODO(http://crbug.com/998280): Figure out why the old content is
// displayed despite the size change.
widget_->GetTooltipView()->NotifyAccessibilityEvent(
ax::mojom::Event::kTooltipClosed, true);
// TODO(crbug.com/1385219): Use `tooltip_window_` instead of its toplevel
// window when WaylandWindow on ozone becomes available.
aura::Window* toplevel_window = tooltip_window_->GetToplevelWindow();
// `tooltip_window_`'s toplevel window may be null for testing.
if (toplevel_window) {
for (auto& observer : observers_)
observer.OnTooltipHidden(toplevel_window);
}
DestroyWidget();
}
tooltip_window_ = nullptr;
}
bool TooltipAura::IsVisible() {
return widget_ && widget_->IsVisible();
}
void TooltipAura::OnWidgetDestroying(views::Widget* widget) {
DCHECK_EQ(widget_, widget);
if (widget_)
widget_->RemoveObserver(this);
widget_ = nullptr;
tooltip_window_ = nullptr;
}
} // namespace views::corewm
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_aura.cc | C++ | unknown | 10,703 |
// 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_COREWM_TOOLTIP_AURA_H_
#define UI_VIEWS_COREWM_TOOLTIP_AURA_H_
#include <memory>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "ui/views/corewm/tooltip.h"
#include "ui/views/corewm/tooltip_view_aura.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/wm/public/tooltip_observer.h"
namespace gfx {
class RenderText;
class Size;
} // namespace gfx
namespace ui {
struct AXNodeData;
struct OwnedWindowAnchor;
} // namespace ui
namespace views {
class Widget;
namespace corewm {
namespace test {
class TooltipAuraTestApi;
}
// Implementation of Tooltip that shows the tooltip using a Widget and Label.
class VIEWS_EXPORT TooltipAura : public Tooltip, public WidgetObserver {
public:
static const char kWidgetName[];
// TODO(crbug.com/1410707): get cursor offset from actual cursor size.
static constexpr int kCursorOffsetX = 10;
static constexpr int kCursorOffsetY = 15;
using TooltipViewFactory =
base::RepeatingCallback<std::unique_ptr<TooltipViewAura>(void)>;
TooltipAura();
explicit TooltipAura(const TooltipViewFactory& tooltip_view_factory);
TooltipAura(const TooltipAura&) = delete;
TooltipAura& operator=(const TooltipAura&) = delete;
~TooltipAura() override;
void AddObserver(wm::TooltipObserver* observer) override;
void RemoveObserver(wm::TooltipObserver* observer) override;
// Adjusts `anchor_point` to the bottom left of the cursor.
static void AdjustToCursor(gfx::Rect* anchor_point);
private:
class TooltipWidget;
friend class test::TooltipAuraTestApi;
const gfx::RenderText* GetRenderTextForTest() const;
void GetAccessibleNodeDataForTest(ui::AXNodeData* node_data);
// Adjusts the bounds given by the arguments to fit inside the desktop
// and returns the adjusted bounds, and also sets anchor information to
// `anchor`.
// `anchor_point` is an absolute position, not relative to the window.
gfx::Rect GetTooltipBounds(const gfx::Size& tooltip_size,
const gfx::Point& anchor_point,
const TooltipTrigger trigger,
ui::OwnedWindowAnchor* anchor);
// Sets |widget_| to a new instance of TooltipWidget. Additional information
// that helps to position anchored windows in such backends as Wayland.
void CreateTooltipWidget(const gfx::Rect& bounds,
const ui::OwnedWindowAnchor& anchor);
// Destroys |widget_|.
void DestroyWidget();
// Tooltip:
int GetMaxWidth(const gfx::Point& location) const override;
void Update(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
const TooltipTrigger trigger) override;
void Show() override;
void Hide() override;
bool IsVisible() override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
// A callback to generate a `TooltipViewAura` instance.
const TooltipViewFactory tooltip_view_factory_;
// The widget containing the tooltip. May be NULL.
raw_ptr<TooltipWidget> widget_ = nullptr;
// The window we're showing the tooltip for. Never NULL and valid while
// showing.
raw_ptr<aura::Window> tooltip_window_ = nullptr;
// Observes tooltip state change.
base::ObserverList<wm::TooltipObserver> observers_;
};
} // namespace corewm
} // namespace views
#endif // UI_VIEWS_COREWM_TOOLTIP_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_aura.h | C++ | unknown | 3,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/corewm/tooltip_controller.h"
#include <stddef.h>
#include <utility>
#include <vector>
#include "base/time/time.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/capture_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_type.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/views/corewm/tooltip_state_manager.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/wm/public/activation_client.h"
#include "ui/wm/public/tooltip_observer.h"
namespace views::corewm {
namespace {
constexpr auto kDefaultShowTooltipDelay = base::Milliseconds(500);
constexpr auto kDefaultHideTooltipDelay = base::Seconds(10);
// Returns true if |target| is a valid window to get the tooltip from.
// |event_target| is the original target from the event and |target| the window
// at the same location.
bool IsValidTarget(aura::Window* event_target, aura::Window* target) {
if (!target || (event_target == target))
return true;
// If `target` is contained in `event_target`, it's valid.
// This case may happen on exo surfaces.
if (event_target->Contains(target) &&
event_target->GetBoundsInScreen().Contains(target->GetBoundsInScreen())) {
return true;
}
void* event_target_grouping_id = event_target->GetNativeWindowProperty(
TooltipManager::kGroupingPropertyKey);
auto* toplevel_of_target = target->GetToplevelWindow();
// Return true if grouping id is same for `target` and `event_target`.
// Also, check grouping id of target's toplevel window to allow the child
// window under `target`, because the menu window may have a child window.
return event_target_grouping_id &&
(event_target_grouping_id ==
target->GetNativeWindowProperty(
TooltipManager::kGroupingPropertyKey) ||
(toplevel_of_target &&
event_target_grouping_id ==
toplevel_of_target->GetNativeWindowProperty(
TooltipManager::kGroupingPropertyKey)));
}
// Returns the target (the Window tooltip text comes from) based on the event.
// If a Window other than event.target() is returned, |location| is adjusted
// to be in the coordinates of the returned Window.
aura::Window* GetTooltipTarget(const ui::MouseEvent& event,
gfx::Point* location) {
switch (event.type()) {
case ui::ET_MOUSE_CAPTURE_CHANGED:
// On windows we can get a capture changed without an exit. We need to
// reset state when this happens else the tooltip may incorrectly show.
return nullptr;
case ui::ET_MOUSE_EXITED:
return nullptr;
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED: {
aura::Window* event_target = static_cast<aura::Window*>(event.target());
if (!event_target)
return nullptr;
// If a window other than |event_target| has capture, ignore the event.
// This can happen when RootWindow creates events when showing/hiding, or
// the system generates an extra event. We have to check
// GetGlobalCaptureWindow() as Windows does not use a singleton
// CaptureClient.
if (!event_target->HasCapture()) {
aura::Window* root = event_target->GetRootWindow();
if (root) {
aura::client::CaptureClient* capture_client =
aura::client::GetCaptureClient(root);
if (capture_client) {
aura::Window* capture_window =
capture_client->GetGlobalCaptureWindow();
if (capture_window && event_target != capture_window)
return nullptr;
}
}
return event_target;
}
// If |target| has capture all events go to it, even if the mouse is
// really over another window. Find the real window the mouse is over.
const gfx::Point screen_loc = event.target()->GetScreenLocation(event);
display::Screen* screen = display::Screen::GetScreen();
aura::Window* target = screen->GetWindowAtScreenPoint(screen_loc);
if (!target)
return nullptr;
gfx::Point target_loc(screen_loc);
aura::client::GetScreenPositionClient(target->GetRootWindow())
->ConvertPointFromScreen(target, &target_loc);
aura::Window* screen_target = target->GetEventHandlerForPoint(target_loc);
if (!IsValidTarget(event_target, screen_target))
return nullptr;
aura::Window::ConvertPointToTarget(screen_target, target, &target_loc);
*location = target_loc;
return screen_target;
}
default:
NOTREACHED_NORETURN();
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// TooltipController public:
TooltipController::TooltipController(std::unique_ptr<Tooltip> tooltip,
wm::ActivationClient* activation_client)
: activation_client_(activation_client),
state_manager_(
std::make_unique<TooltipStateManager>(std::move(tooltip))) {
if (activation_client_)
activation_client_->AddObserver(this);
}
TooltipController::~TooltipController() {
if (observed_window_)
observed_window_->RemoveObserver(this);
if (activation_client_)
activation_client_->RemoveObserver(this);
}
void TooltipController::AddObserver(wm::TooltipObserver* observer) {
state_manager_->AddObserver(observer);
}
void TooltipController::RemoveObserver(wm::TooltipObserver* observer) {
state_manager_->RemoveObserver(observer);
}
int TooltipController::GetMaxWidth(const gfx::Point& location) const {
return state_manager_->GetMaxWidth(location);
}
void TooltipController::UpdateTooltip(aura::Window* target) {
// The |tooltip_parent_window_| is only set when the tooltip is visible or
// its |will_show_tooltip_timer_| is running.
if (target && observed_window_ == target) {
// This is either an update on an already (or about to be) visible tooltip
// or a call to UpdateIfRequired that will potentially trigger a tooltip
// caused by a tooltip text update.
//
// If there's no active tooltip, it's appropriate to assume that the trigger
// is kCursor because a tooltip text update triggered from the keyboard
// would always happen in UpdateTooltipFromKeyboard, not from here.
if (state_manager_->tooltip_parent_window())
UpdateIfRequired(state_manager_->tooltip_trigger());
else if (IsTooltipTextUpdateNeeded())
UpdateIfRequired(TooltipTrigger::kCursor);
}
ResetWindowAtMousePressedIfNeeded(target, /* force_reset */ false);
}
void TooltipController::UpdateTooltipFromKeyboard(const gfx::Rect& bounds,
aura::Window* target) {
UpdateTooltipFromKeyboardWithAnchorPoint(bounds.bottom_center(), target);
}
void TooltipController::UpdateTooltipFromKeyboardWithAnchorPoint(
const gfx::Point& anchor_point,
aura::Window* target) {
anchor_point_ = anchor_point;
SetObservedWindow(target);
// Update the position of the active but not yet visible keyboard triggered
// tooltip, if any.
if (state_manager_->tooltip_parent_window()) {
state_manager_->UpdatePositionIfNeeded(anchor_point_,
TooltipTrigger::kKeyboard);
}
// This function is always only called for keyboard-triggered tooltips.
UpdateIfRequired(TooltipTrigger::kKeyboard);
ResetWindowAtMousePressedIfNeeded(target, /* force_reset */ true);
}
bool TooltipController::IsTooltipSetFromKeyboard(aura::Window* target) {
return target && target == state_manager_->tooltip_parent_window() &&
state_manager_->tooltip_trigger() == TooltipTrigger::kKeyboard;
}
void TooltipController::SetHideTooltipTimeout(aura::Window* target,
base::TimeDelta timeout) {
hide_tooltip_timeout_map_[target] = timeout;
}
void TooltipController::SetTooltipsEnabled(bool enable) {
if (tooltips_enabled_ == enable)
return;
tooltips_enabled_ = enable;
UpdateTooltip(observed_window_);
}
void TooltipController::OnKeyEvent(ui::KeyEvent* event) {
if (event->type() != ui::ET_KEY_PRESSED)
return;
// Always hide a tooltip on a key press. Since this controller is a pre-target
// handler (i.e. the events are received here before the target act on them),
// hiding the tooltip will not cancel any action supposed to show it triggered
// by a key press.
HideAndReset();
}
void TooltipController::OnMouseEvent(ui::MouseEvent* event) {
// Ignore mouse events that coincide with the last touch event.
if (event->location() == last_touch_loc_) {
// If the tooltip is visible, SetObservedWindow will also hide it if needed.
SetObservedWindow(nullptr);
return;
}
switch (event->type()) {
case ui::ET_MOUSE_EXITED:
// TODO(bebeaudr): Keyboard-triggered tooltips that show up right where
// the cursor currently is are hidden as soon as they show up because of
// this event. Handle this case differently to fix the issue.
//
// Whenever a tooltip is closed, an ET_MOUSE_EXITED event is fired, even
// if the cursor is not in the tooltip's window. Make sure that these
// mouse exited events don't interfere with keyboard triggered tooltips by
// returning early.
if (state_manager_->tooltip_parent_window() &&
state_manager_->tooltip_trigger() == TooltipTrigger::kKeyboard) {
return;
}
SetObservedWindow(nullptr);
break;
case ui::ET_MOUSE_CAPTURE_CHANGED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED: {
// Synthesized mouse moves shouldn't cause us to show a tooltip. See
// https://crbug.com/1146981.
if (event->IsSynthesized())
break;
last_mouse_loc_ = event->location();
aura::Window* target = nullptr;
// Avoid a call to display::Screen::GetWindowAtScreenPoint() since it can
// be very expensive on X11 in cases when the tooltip is hidden anyway.
if (tooltips_enabled_ && !aura::Env::GetInstance()->IsMouseButtonDown() &&
!IsDragDropInProgress()) {
target = GetTooltipTarget(*event, &last_mouse_loc_);
}
// This needs to be called after the |last_mouse_loc_| is converted to the
// target's screen coordinates.
state_manager_->UpdatePositionIfNeeded(last_mouse_loc_,
TooltipTrigger::kCursor);
SetObservedWindow(target);
if (state_manager_->IsVisible() ||
(observed_window_ && IsTooltipTextUpdateNeeded())) {
UpdateIfRequired(TooltipTrigger::kCursor);
}
break;
}
case ui::ET_MOUSE_PRESSED:
if ((event->flags() & ui::EF_IS_NON_CLIENT) == 0) {
aura::Window* target = static_cast<aura::Window*>(event->target());
// We don't get a release for non-client areas.
tooltip_window_at_mouse_press_tracker_.RemoveAll();
if (target) {
tooltip_window_at_mouse_press_tracker_.Add(target);
tooltip_text_at_mouse_press_ = wm::GetTooltipText(target);
}
}
state_manager_->HideAndReset();
break;
case ui::ET_MOUSEWHEEL:
// Hide the tooltip for click, release, drag, wheel events.
if (state_manager_->IsVisible())
state_manager_->HideAndReset();
break;
default:
break;
}
}
void TooltipController::OnTouchEvent(ui::TouchEvent* event) {
// Hide the tooltip for touch events.
HideAndReset();
last_touch_loc_ = event->location();
}
void TooltipController::OnCancelMode(ui::CancelModeEvent* event) {
HideAndReset();
}
base::StringPiece TooltipController::GetLogContext() const {
return "TooltipController";
}
void TooltipController::OnCursorVisibilityChanged(bool is_visible) {
if (is_visible && !state_manager_->tooltip_parent_window()) {
// When there's no tooltip and the cursor becomes visible, the cursor might
// already be over an item that should trigger a tooltip. Update it to
// ensure we don't miss this case.
UpdateIfRequired(TooltipTrigger::kCursor);
} else if (!is_visible && state_manager_->tooltip_parent_window() &&
state_manager_->tooltip_trigger() == TooltipTrigger::kCursor) {
// When the cursor is hidden and we have an active tooltip that was
// triggered by the cursor, hide it.
HideAndReset();
}
}
void TooltipController::OnWindowVisibilityChanged(aura::Window* window,
bool visible) {
// If window is not drawn, skip modifying tooltip.
if (!visible && window->layer()->type() != ui::LAYER_NOT_DRAWN)
HideAndReset();
}
void TooltipController::OnWindowDestroyed(aura::Window* window) {
if (observed_window_ == window) {
RemoveTooltipDelayFromMap(observed_window_);
observed_window_ = nullptr;
}
if (state_manager_->tooltip_parent_window() == window)
HideAndReset();
}
void TooltipController::OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) {
if ((key == wm::kTooltipIdKey || key == wm::kTooltipTextKey) &&
wm::GetTooltipText(window) != std::u16string() &&
(IsTooltipTextUpdateNeeded() || IsTooltipIdUpdateNeeded())) {
UpdateIfRequired(state_manager_->tooltip_trigger());
}
}
void TooltipController::OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
// We want to hide tooltips whenever the client is losing user focus.
if (lost_active)
HideAndReset();
}
void TooltipController::SetShowTooltipDelay(aura::Window* target,
base::TimeDelta delay) {
show_tooltip_delay_map_[target] = delay;
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
void TooltipController::OnTooltipShownOnServer(aura::Window* window,
const std::u16string& text,
const gfx::Rect& bounds) {
state_manager_->OnTooltipShownOnServer(window, text, bounds);
}
void TooltipController::OnTooltipHiddenOnServer() {
state_manager_->OnTooltipHiddenOnServer();
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
////////////////////////////////////////////////////////////////////////////////
// TooltipController private:
void TooltipController::HideAndReset() {
state_manager_->HideAndReset();
SetObservedWindow(nullptr);
}
void TooltipController::UpdateIfRequired(TooltipTrigger trigger) {
if (!tooltips_enabled_ || aura::Env::GetInstance()->IsMouseButtonDown() ||
IsDragDropInProgress() ||
(trigger == TooltipTrigger::kCursor && !IsCursorVisible())) {
state_manager_->HideAndReset();
return;
}
// When a user press a mouse button, we want to hide the tooltip and prevent
// the tooltip from showing up again until the cursor moves to another view
// than the one that received the press event.
if (ShouldHideBecauseMouseWasOncePressed()) {
state_manager_->HideAndReset();
return;
}
tooltip_window_at_mouse_press_tracker_.RemoveAll();
if (trigger == TooltipTrigger::kCursor)
anchor_point_ = last_mouse_loc_;
// If the uniqueness indicator is different from the previously encountered
// one, we should force tooltip update
if (!state_manager_->IsVisible() || IsTooltipTextUpdateNeeded() ||
IsTooltipIdUpdateNeeded()) {
state_manager_->Show(observed_window_, wm::GetTooltipText(observed_window_),
anchor_point_, trigger, GetShowTooltipDelay(),
GetHideTooltipDelay());
}
}
bool TooltipController::IsDragDropInProgress() const {
if (!observed_window_)
return false;
aura::client::DragDropClient* client =
aura::client::GetDragDropClient(observed_window_->GetRootWindow());
return client && client->IsDragDropInProgress();
}
bool TooltipController::IsCursorVisible() const {
if (!observed_window_)
return false;
aura::Window* root = observed_window_->GetRootWindow();
if (!root)
return false;
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(root);
// |cursor_client| may be NULL in tests, treat NULL as always visible.
return !cursor_client || cursor_client->IsCursorVisible();
}
base::TimeDelta TooltipController::GetShowTooltipDelay() {
std::map<aura::Window*, base::TimeDelta>::const_iterator it =
show_tooltip_delay_map_.find(observed_window_);
if (it == show_tooltip_delay_map_.end()) {
return skip_show_delay_for_testing_ ? base::TimeDelta()
: kDefaultShowTooltipDelay;
}
return it->second;
}
base::TimeDelta TooltipController::GetHideTooltipDelay() {
std::map<aura::Window*, base::TimeDelta>::const_iterator it =
hide_tooltip_timeout_map_.find(observed_window_);
if (it == hide_tooltip_timeout_map_.end())
return kDefaultHideTooltipDelay;
return it->second;
}
void TooltipController::SetObservedWindow(aura::Window* target) {
if (observed_window_ == target)
return;
// When we are setting the |observed_window_| to nullptr, it is generally
// because the cursor is over a window not owned by Chromium. To prevent a
// tooltip from being shown after the cursor goes to another window not
// managed by us, hide the the tooltip and cancel all timers that would show
// the tooltip.
if (!target && state_manager_->tooltip_parent_window()) {
// Important: We can't call `TooltipController::HideAndReset` or we'd get an
// infinite loop here.
state_manager_->HideAndReset();
}
if (observed_window_)
observed_window_->RemoveObserver(this);
observed_window_ = target;
if (observed_window_)
observed_window_->AddObserver(this);
}
bool TooltipController::IsTooltipIdUpdateNeeded() const {
return state_manager_->tooltip_id() != wm::GetTooltipId(observed_window_);
}
bool TooltipController::IsTooltipTextUpdateNeeded() const {
return state_manager_->tooltip_text() != wm::GetTooltipText(observed_window_);
}
void TooltipController::RemoveTooltipDelayFromMap(aura::Window* window) {
show_tooltip_delay_map_.erase(window);
hide_tooltip_timeout_map_.erase(window);
}
void TooltipController::ResetWindowAtMousePressedIfNeeded(aura::Window* target,
bool force_reset) {
// Reset tooltip_window_at_mouse_press() if the cursor moved within the same
// window but over a region that has different tooltip text. This handles the
// case of clicking on a view, moving within the same window but over a
// different view, then back to the original view.
if (force_reset ||
(tooltip_window_at_mouse_press() &&
target == tooltip_window_at_mouse_press() &&
wm::GetTooltipText(target) != tooltip_text_at_mouse_press_)) {
tooltip_window_at_mouse_press_tracker_.RemoveAll();
}
}
// TODO(bebeaudr): This approach is less than ideal. It looks at the tooltip
// text at the moment the mouse was pressed to determine whether or not we are
// on the same tooltip as before. This cause problems when two elements are next
// to each other and have the same text - unlikely, but an issue nonetheless.
// However, this is currently the nearest we can get since we don't have an
// identifier of the renderer side element that triggered the tooltip. Could we
// pass a renderer element unique id alongside the tooltip text?
bool TooltipController::ShouldHideBecauseMouseWasOncePressed() {
// Skip hiding when tootlip text is empty as no need to hide again.
// This is required since client side tooltip appears as empty text on sever
// side so that the tooltip is overridden by empty text regardless of the
// actual text to show.
// TODO(crbug.com/1383844): Remove or update this special path when tooltip
// idetifier is implemented.
if (wm::GetTooltipText(observed_window_).empty())
return false;
return tooltip_window_at_mouse_press() &&
observed_window_ == tooltip_window_at_mouse_press() &&
wm::GetTooltipText(observed_window_) == tooltip_text_at_mouse_press_;
}
} // namespace views::corewm
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_controller.cc | C++ | unknown | 20,734 |
// 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_COREWM_TOOLTIP_CONTROLLER_H_
#define UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_H_
#include <map>
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "build/chromeos_buildflags.h"
#include "ui/aura/client/cursor_client_observer.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_tracker.h"
#include "ui/events/event_handler.h"
#include "ui/views/corewm/tooltip.h"
#include "ui/views/views_export.h"
#include "ui/wm/public/activation_change_observer.h"
#include "ui/wm/public/tooltip_client.h"
namespace aura {
class Window;
}
namespace base {
class TimeDelta;
}
namespace gfx {
class Point;
class Rect;
} // namespace gfx
namespace wm {
class ActivationClient;
class TooltipObserver;
}
namespace views::corewm {
class Tooltip;
class TooltipStateManager;
namespace test {
class TooltipControllerTestHelper;
} // namespace test
// TooltipController listens for events that can have an impact on the
// tooltip state.
class VIEWS_EXPORT TooltipController
: public wm::TooltipClient,
public ui::EventHandler,
public aura::client::CursorClientObserver,
public aura::WindowObserver,
public wm::ActivationChangeObserver {
public:
TooltipController(std::unique_ptr<Tooltip> tooltip,
wm::ActivationClient* activation_client);
TooltipController(const TooltipController&) = delete;
TooltipController& operator=(const TooltipController&) = delete;
~TooltipController() override;
void AddObserver(wm::TooltipObserver* observer);
void RemoveObserver(wm::TooltipObserver* observer);
// Overridden from wm::TooltipClient.
int GetMaxWidth(const gfx::Point& location) const override;
void UpdateTooltip(aura::Window* target) override;
void UpdateTooltipFromKeyboard(const gfx::Rect& bounds,
aura::Window* target) override;
bool IsTooltipSetFromKeyboard(aura::Window* target) override;
void SetHideTooltipTimeout(aura::Window* target,
base::TimeDelta timeout) override;
void SetTooltipsEnabled(bool enable) override;
// Overridden from ui::EventHandler.
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnTouchEvent(ui::TouchEvent* event) override;
void OnCancelMode(ui::CancelModeEvent* event) override;
base::StringPiece GetLogContext() const override;
// Overridden from aura::client::CursorClientObserver.
void OnCursorVisibilityChanged(bool is_visible) override;
// Overridden from aura::WindowObserver.
void OnWindowVisibilityChanged(aura::Window* window, bool visible) override;
void OnWindowDestroyed(aura::Window* window) override;
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
// Overridden from wm::ActivationChangeObserver.
void OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) override;
// Upddates tooltip triggered by keyboard with anchor_point value.
// This should be called instead of UpdateTooltipFromKeyboard() when the
// anchor point is already calculated (e.g. Exo).
void UpdateTooltipFromKeyboardWithAnchorPoint(const gfx::Point& anchor_point,
aura::Window* target);
// Sets show tooltip delay for `target` window.
void SetShowTooltipDelay(aura::Window* target, base::TimeDelta delay);
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// Called when tooltip is shown/hidden on server.
// This is only used for Lacros whose tooltip is handled on server-side.
void OnTooltipShownOnServer(aura::Window* window,
const std::u16string& text,
const gfx::Rect& bounds);
void OnTooltipHiddenOnServer();
#endif // BUILDFLA(IS_CHROMEOS_LACROS)
private:
friend class test::TooltipControllerTestHelper;
// Reset the window and calls `TooltipStateManager::HideAndReset`.
void HideAndReset();
// Updates the tooltip if required (if there is any change in the tooltip
// text, tooltip id or the aura::Window).
void UpdateIfRequired(TooltipTrigger trigger);
// Returns true if there's a drag-and-drop in progress.
bool IsDragDropInProgress() const;
// Returns true if the cursor is visible.
bool IsCursorVisible() const;
// Get the delay after which the tooltip should be shown/hidden.
base::TimeDelta GetShowTooltipDelay();
base::TimeDelta GetHideTooltipDelay();
// Sets observed window to |target| if it is different from existing window.
// Calls RemoveObserver on the existing window if it is not NULL.
// Calls AddObserver on the new window if it is not NULL.
void SetObservedWindow(aura::Window* target);
// Returns true if the tooltip id stored on the state manager and the one
// stored on the window are different.
bool IsTooltipIdUpdateNeeded() const;
// Returns true if the tooltip text stored on the state manager and the one
// stored on the window are different.
bool IsTooltipTextUpdateNeeded() const;
// Remove show/hide tooltip delay from `show_tooltip_delay_map_` and
// `hide_tooltip_timeout_map_`.
void RemoveTooltipDelayFromMap(aura::Window* window);
// Stop tracking the window on which the cursor was when the mouse was pressed
// if we're on another window or if a new tooltip is triggered by keyboard.
void ResetWindowAtMousePressedIfNeeded(aura::Window* target,
bool force_reset);
// To prevent the tooltip to show again after a mouse press event, we want
// to hide it until the cursor moves to another window.
bool ShouldHideBecauseMouseWasOncePressed();
aura::Window* tooltip_window_at_mouse_press() {
auto& windows = tooltip_window_at_mouse_press_tracker_.windows();
return windows.empty() ? nullptr : windows[0];
}
// The window on which we are currently listening for events. When there's a
// keyboard-triggered visible tooltip, its value is set to the tooltip parent
// window. Otherwise, it's following the cursor.
raw_ptr<aura::Window> observed_window_ = nullptr;
// This is the position our controller will use to position the tooltip. When
// the tooltip is triggered by a keyboard action resulting in a view gaining
// focus, the point is set from the bounds of the view that gained focus.
// When the tooltip is triggered by the cursor, the |anchor_point_| is set to
// the |last_mouse_loc_|.
gfx::Point anchor_point_;
// These fields are for tracking state when the user presses a mouse button.
// The tooltip should stay hidden after a mouse press event on the view until
// the cursor moves to another view.
std::u16string tooltip_text_at_mouse_press_;
// NOTE: this either has zero or one window.
aura::WindowTracker tooltip_window_at_mouse_press_tracker_;
// Location of the last events in |tooltip_window_|'s coordinates.
gfx::Point last_mouse_loc_;
gfx::Point last_touch_loc_;
// Whether tooltips can be displayed or not.
bool tooltips_enabled_ = true;
// Whether tooltip should be skip delay before showing.
// This may be set to true only for testing.
// Do NOT override this value except from TooltipControllerTestHelper.
bool skip_show_delay_for_testing_ = false;
// The show delay before showing tooltip may differ for external app's tooltip
// such as Lacros. This map specifies the show delay for each target window.
std::map<aura::Window*, base::TimeDelta> show_tooltip_delay_map_;
// Web content tooltips should be shown indefinitely and those added on Views
// should be hidden automatically after a timeout. This map stores the timeout
// value for each aura::Window.
// TODO(bebeaudr): Currently, all Views tooltips are hidden after the same
// timeout and all web content views should be shown indefinitely. If this
// general rule is always true, then we don't need a complex map here. A set
// of aura::Window* would be enough with an attribute named
// "disabled_hide_timeout_views_set_" or something like that.
std::map<aura::Window*, base::TimeDelta> hide_tooltip_timeout_map_;
// We want to hide tooltips whenever our client window loses focus. This will
// ensure that no tooltip stays visible when the user navigated away from
// our client.
raw_ptr<wm::ActivationClient> activation_client_;
// The TooltipStateManager is responsible for keeping track of the current
// tooltip state (its text, position, id, etc.) and to modify it when asked
// by the TooltipController or the show/hide timers.
std::unique_ptr<TooltipStateManager> state_manager_;
};
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_controller.h | C++ | unknown | 8,977 |
// 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/corewm/tooltip_controller_test_helper.h"
#include "base/time/time.h"
#include "ui/aura/window.h"
#include "ui/wm/public/activation_change_observer.h"
#include "ui/wm/public/tooltip_observer.h"
namespace views::corewm::test {
TooltipControllerTestHelper::TooltipControllerTestHelper(
TooltipController* controller)
: controller_(controller) {
SkipTooltipShowDelay(true);
}
TooltipControllerTestHelper::~TooltipControllerTestHelper() = default;
bool TooltipControllerTestHelper::UseServerSideTooltip() {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
return ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_tooltip;
#else
return false;
#endif
}
const std::u16string& TooltipControllerTestHelper::GetTooltipText() {
return state_manager()->tooltip_text();
}
aura::Window* TooltipControllerTestHelper::GetTooltipParentWindow() {
return state_manager()->tooltip_parent_window_;
}
const aura::Window* TooltipControllerTestHelper::GetObservedWindow() {
return controller_->observed_window_;
}
const gfx::Point& TooltipControllerTestHelper::GetTooltipPosition() {
return state_manager()->position_;
}
base::TimeDelta TooltipControllerTestHelper::GetShowTooltipDelay() {
return controller_->GetShowTooltipDelay();
}
void TooltipControllerTestHelper::HideAndReset() {
controller_->HideAndReset();
}
void TooltipControllerTestHelper::UpdateIfRequired(TooltipTrigger trigger) {
controller_->UpdateIfRequired(trigger);
}
void TooltipControllerTestHelper::FireHideTooltipTimer() {
state_manager()->HideAndReset();
}
void TooltipControllerTestHelper::AddObserver(wm::TooltipObserver* observer) {
controller_->AddObserver(observer);
}
void TooltipControllerTestHelper::RemoveObserver(
wm::TooltipObserver* observer) {
controller_->RemoveObserver(observer);
}
bool TooltipControllerTestHelper::IsWillShowTooltipTimerRunning() {
return state_manager()->IsWillShowTooltipTimerRunningForTesting();
}
bool TooltipControllerTestHelper::IsWillHideTooltipTimerRunning() {
return state_manager()->IsWillHideTooltipTimerRunningForTesting();
}
bool TooltipControllerTestHelper::IsTooltipVisible() {
return state_manager()->IsVisible();
}
void TooltipControllerTestHelper::SkipTooltipShowDelay(bool enable) {
controller_->skip_show_delay_for_testing_ = enable;
}
void TooltipControllerTestHelper::MockWindowActivated(aura::Window* window,
bool active) {
aura::Window* gained_active = active ? window : nullptr;
aura::Window* lost_active = active ? nullptr : window;
controller_->OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT,
gained_active, lost_active);
}
TooltipTestView::TooltipTestView() = default;
TooltipTestView::~TooltipTestView() = default;
std::u16string TooltipTestView::GetTooltipText(const gfx::Point& p) const {
return tooltip_text_;
}
} // namespace views::corewm::test
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_controller_test_helper.cc | C++ | unknown | 3,130 |
// 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_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_
#define UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "build/chromeos_buildflags.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/views/corewm/tooltip_state_manager.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
}
namespace base {
class TimeDelta;
}
namespace wm {
class TooltipObserver;
}
namespace views::corewm::test {
// TooltipControllerTestHelper provides access to TooltipControllers private
// state.
class TooltipControllerTestHelper {
public:
explicit TooltipControllerTestHelper(TooltipController* controller);
TooltipControllerTestHelper(const TooltipControllerTestHelper&) = delete;
TooltipControllerTestHelper& operator=(const TooltipControllerTestHelper&) =
delete;
~TooltipControllerTestHelper();
TooltipController* controller() { return controller_; }
TooltipStateManager* state_manager() {
return controller_->state_manager_.get();
}
// Returns true if server side tooltip is enabled. The server side means
// tooltip is handled on ash (server) and lacros is the client.
// Always returns false except for Lacros.
bool UseServerSideTooltip();
// These are mostly cover methods for TooltipController private methods.
const std::u16string& GetTooltipText();
aura::Window* GetTooltipParentWindow();
const aura::Window* GetObservedWindow();
const gfx::Point& GetTooltipPosition();
base::TimeDelta GetShowTooltipDelay();
void HideAndReset();
void UpdateIfRequired(TooltipTrigger trigger);
void FireHideTooltipTimer();
void AddObserver(wm::TooltipObserver* observer);
void RemoveObserver(wm::TooltipObserver* observer);
bool IsWillShowTooltipTimerRunning();
bool IsWillHideTooltipTimerRunning();
bool IsTooltipVisible();
void SkipTooltipShowDelay(bool enable);
void MockWindowActivated(aura::Window* window, bool active);
private:
raw_ptr<TooltipController, DanglingUntriaged> controller_;
};
// Trivial View subclass that lets you set the tooltip text.
class TooltipTestView : public views::View {
public:
TooltipTestView();
TooltipTestView(const TooltipTestView&) = delete;
TooltipTestView& operator=(const TooltipTestView&) = delete;
~TooltipTestView() override;
void set_tooltip_text(std::u16string tooltip_text) {
tooltip_text_ = tooltip_text;
}
// Overridden from views::View
std::u16string GetTooltipText(const gfx::Point& p) const override;
private:
std::u16string tooltip_text_;
};
} // namespace views::corewm::test
#endif // UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_controller_test_helper.h | C++ | unknown | 2,916 |
// 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/corewm/tooltip_controller.h"
#include <memory>
#include <utility>
#include "base/at_exit.h"
#include "base/memory/raw_ptr.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/window_types.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/font.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/render_text.h"
#include "ui/gfx/text_elider.h"
#include "ui/views/buildflags.h"
#include "ui/views/corewm/test/tooltip_aura_test_api.h"
#include "ui/views/corewm/tooltip_aura.h"
#include "ui/views/corewm/tooltip_controller_test_helper.h"
#include "ui/views/corewm/tooltip_state_manager.h"
#include "ui/views/test/desktop_test_views_delegate.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/public/activation_client.h"
#include "ui/wm/public/tooltip_client.h"
#include "ui/wm/public/tooltip_observer.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/scoped_ole_initializer.h"
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif
namespace views::corewm::test {
namespace {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
class TestTooltipLacros : public Tooltip {
public:
TestTooltipLacros() = default;
TestTooltipLacros(const TestTooltipLacros&) = delete;
TestTooltipLacros& operator=(const TestTooltipLacros&) = delete;
~TestTooltipLacros() override {
tooltip_parent_ = nullptr;
state_manager_ = nullptr;
}
void AddObserver(wm::TooltipObserver* observer) override {}
void RemoveObserver(wm::TooltipObserver* observer) override {}
const std::u16string& tooltip_text() const { return tooltip_text_; }
// Tooltip:
int GetMaxWidth(const gfx::Point& location) const override { return 100; }
void Update(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
const TooltipTrigger trigger) override {
tooltip_parent_ = window;
tooltip_text_ = tooltip_text;
anchor_point_ = position + window->GetBoundsInScreen().OffsetFromOrigin();
trigger_ = trigger;
}
void Show() override {
is_visible_ = true;
DCHECK(state_manager_);
state_manager_->OnTooltipShownOnServer(tooltip_parent_, tooltip_text_,
gfx::Rect());
}
void Hide() override {
is_visible_ = false;
DCHECK(state_manager_);
state_manager_->OnTooltipHiddenOnServer();
}
bool IsVisible() override { return is_visible_; }
void SetStateManager(TooltipStateManager* state_manager) {
state_manager_ = state_manager;
}
const gfx::Point& anchor_point() { return anchor_point_; }
TooltipTrigger trigger() { return trigger_; }
private:
bool is_visible_ = false;
raw_ptr<aura::Window> tooltip_parent_ = nullptr;
raw_ptr<TooltipStateManager> state_manager_ = nullptr; // not owned.
std::u16string tooltip_text_;
gfx::Point anchor_point_;
TooltipTrigger trigger_;
};
#endif
views::Widget* CreateWidget(aura::Window* root) {
views::Widget* widget = new views::Widget;
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
params.accept_events = true;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN)
params.parent = root;
#endif
params.bounds = gfx::Rect(0, 0, 200, 100);
widget->Init(std::move(params));
widget->Show();
return widget;
}
TooltipController* GetController(Widget* widget) {
return static_cast<TooltipController*>(
wm::GetTooltipClient(widget->GetNativeWindow()->GetRootWindow()));
}
} // namespace
class TooltipControllerTest : public ViewsTestBase {
public:
TooltipControllerTest() = default;
TooltipControllerTest(const TooltipControllerTest&) = delete;
TooltipControllerTest& operator=(const TooltipControllerTest&) = delete;
~TooltipControllerTest() override = default;
void SetUp() override {
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
set_native_widget_type(NativeWidgetType::kDesktop);
#endif
ViewsTestBase::SetUp();
aura::Window* root_window = GetContext();
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN)
if (root_window) {
tooltip_ = new views::corewm::TooltipAura();
controller_ = std::make_unique<TooltipController>(
std::unique_ptr<views::corewm::Tooltip>(tooltip_),
/* activation_client */ nullptr);
root_window->AddPreTargetHandler(controller_.get());
SetTooltipClient(root_window, controller_.get());
}
#endif
widget_.reset(CreateWidget(root_window));
widget_->SetContentsView(std::make_unique<View>());
view_ = new TooltipTestView;
widget_->GetContentsView()->AddChildView(view_.get());
view_->SetBoundsRect(widget_->GetContentsView()->GetLocalBounds());
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// Use TestTooltip instead of TooltipLacros to avoid using server side
// impl since it requires ui_controls which only works in
// interactive_ui_tests.
tooltip_ = new TestTooltipLacros();
controller_ = std::make_unique<TooltipController>(
std::unique_ptr<views::corewm::Tooltip>(tooltip_),
/*activation_client=*/nullptr);
widget_->GetNativeWindow()->GetRootWindow()->AddPreTargetHandler(
controller_.get());
// Set tooltip client after creating widget since tooltip controller is
// constructed and overriden inside CreateWidget() for Lacros.
SetTooltipClient(widget_->GetNativeWindow()->GetRootWindow(),
controller_.get());
#endif
helper_ = std::make_unique<TooltipControllerTestHelper>(
GetController(widget_.get()));
#if BUILDFLAG(IS_CHROMEOS_LACROS)
tooltip_->SetStateManager(helper_->state_manager());
#endif
generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow());
}
void TearDown() override {
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN) || \
BUILDFLAG(IS_CHROMEOS_LACROS)
aura::Window* root_window = GetContext();
if (root_window) {
root_window->RemovePreTargetHandler(controller_.get());
wm::SetTooltipClient(root_window, nullptr);
controller_.reset();
}
#endif
generator_.reset();
helper_.reset();
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
aura::Window* GetWindow() { return widget_->GetNativeWindow(); }
aura::Window* GetRootWindow() { return GetWindow()->GetRootWindow(); }
aura::Window* CreateNormalWindow(int id,
aura::Window* parent,
aura::WindowDelegate* delegate) {
aura::Window* window = new aura::Window(
delegate
? delegate
: aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate());
window->SetId(id);
window->Init(ui::LAYER_TEXTURED);
parent->AddChild(window);
window->SetBounds(gfx::Rect(0, 0, 100, 100));
window->Show();
return window;
}
TooltipTestView* PrepareSecondView() {
TooltipTestView* view2 = new TooltipTestView;
widget_->GetContentsView()->AddChildView(view2);
view_->SetBounds(0, 0, 100, 100);
view2->SetBounds(100, 0, 100, 100);
return view2;
}
std::unique_ptr<views::Widget> widget_;
raw_ptr<TooltipTestView> view_ = nullptr;
std::unique_ptr<TooltipControllerTestHelper> helper_;
std::unique_ptr<ui::test::EventGenerator> generator_;
protected:
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN)
raw_ptr<TooltipAura> tooltip_; // not owned.
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
raw_ptr<TestTooltipLacros> tooltip_; // not owned.
#endif
private:
std::unique_ptr<TooltipController> controller_;
#if BUILDFLAG(IS_WIN)
ui::ScopedOleInitializer ole_initializer_;
#endif
};
TEST_F(TooltipControllerTest, ViewTooltip) {
view_->set_tooltip_text(u"Tooltip Text");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseToCenterOf(GetWindow());
EXPECT_EQ(GetWindow(), GetRootWindow()->GetEventHandlerForPoint(
generator_->current_screen_location()));
std::u16string expected_tooltip = u"Tooltip Text";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
}
TEST_F(TooltipControllerTest, HideEmptyTooltip) {
view_->set_tooltip_text(u"Tooltip Text");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseToCenterOf(GetWindow());
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
view_->set_tooltip_text(u" ");
generator_->MoveMouseBy(1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
}
TEST_F(TooltipControllerTest, DontShowTooltipOnTouch) {
view_->set_tooltip_text(u"Tooltip Text");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->PressMoveAndReleaseTouchToCenterOf(GetWindow());
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseToCenterOf(GetWindow());
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
std::u16string expected_tooltip = u"Tooltip Text";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
}
#if !BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_WIN)
// crbug.com/664370.
TEST_F(TooltipControllerTest, MaxWidth) {
std::u16string text =
u"Really, really, really, really, really, really long tooltip that "
u"exceeds max width";
view_->set_tooltip_text(text);
gfx::Point center = GetWindow()->bounds().CenterPoint();
generator_->MoveMouseTo(center);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
const gfx::RenderText* render_text =
test::TooltipAuraTestApi(tooltip_).GetRenderText();
int max = helper_->controller()->GetMaxWidth(center);
EXPECT_EQ(max, render_text->display_rect().width());
}
TEST_F(TooltipControllerTest, AccessibleNodeData) {
std::u16string text = u"Tooltip Text";
view_->set_tooltip_text(text);
gfx::Point center = GetWindow()->bounds().CenterPoint();
generator_->MoveMouseTo(center);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
ui::AXNodeData node_data;
test::TooltipAuraTestApi(tooltip_).GetAccessibleNodeData(&node_data);
EXPECT_EQ(ax::mojom::Role::kTooltip, node_data.role);
EXPECT_EQ(text, base::ASCIIToUTF16(node_data.GetStringAttribute(
ax::mojom::StringAttribute::kName)));
}
TEST_F(TooltipControllerTest, TooltipBounds) {
// We don't need a real tootip. Let's just use a custom size and custom point
// to test this function.
gfx::Size tooltip_size(100, 40);
gfx::Rect display_bounds(display::Screen::GetScreen()
->GetDisplayNearestPoint(gfx::Point(0, 0))
.bounds());
gfx::Point anchor_point = display_bounds.CenterPoint();
// All tests here share the same expected y value.
int a_expected_y(anchor_point.y() + TooltipAura::kCursorOffsetY);
int b_expected_y(anchor_point.y());
// 1. The tooltip fits entirely in the window.
{
// A. When attached to the cursor, the tooltip should be positioned at the
// bottom-right corner of the cursor.
gfx::Rect bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kCursor);
gfx::Point expected_position(anchor_point.x() + TooltipAura::kCursorOffsetX,
a_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
// B. When not attached to the cursor, the tooltip should be horizontally
// centered with the anchor point.
bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kKeyboard);
expected_position =
gfx::Point(anchor_point.x() - tooltip_size.width() / 2, b_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
}
// 2. The tooltip overflows on the left side of the window.
{
anchor_point = display_bounds.left_center();
anchor_point.Offset(-TooltipAura::kCursorOffsetX - 10, 0);
// A. When attached to the cursor, the tooltip should be positioned at the
// bottom-right corner of the cursor.
gfx::Rect bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kCursor);
gfx::Point expected_position(0, a_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
// B. When not attached to the cursor, the tooltip should be horizontally
// centered with the anchor point.
bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kKeyboard);
expected_position = gfx::Point(0, b_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
}
// 3. The tooltip overflows on the right side of the window.
{
anchor_point = display_bounds.right_center();
anchor_point.Offset(10, 0);
// A. When attached to the cursor, the tooltip should be positioned at the
// bottom-right corner of the cursor.
gfx::Rect bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kCursor);
gfx::Point expected_position(display_bounds.right() - tooltip_size.width(),
a_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
// B. When not attached to the cursor, the tooltip should be horizontally
// centered with the anchor point.
bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kKeyboard);
expected_position =
gfx::Point(display_bounds.right() - tooltip_size.width(), b_expected_y);
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
}
// 4. The tooltip overflows on the bottom.
{
anchor_point = display_bounds.bottom_center();
// A. When attached to the cursor, the tooltip should be positioned at the
// bottom-right corner of the cursor.
gfx::Rect bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kCursor);
gfx::Point expected_position(anchor_point.x() + TooltipAura::kCursorOffsetX,
anchor_point.y() - tooltip_size.height());
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
// B. When not attached to the cursor, the tooltip should be horizontally
// centered with the anchor point.
bounds = test::TooltipAuraTestApi(tooltip_).GetTooltipBounds(
tooltip_size, anchor_point, TooltipTrigger::kKeyboard);
expected_position = gfx::Point(anchor_point.x() - tooltip_size.width() / 2,
anchor_point.y() - tooltip_size.height());
EXPECT_EQ(bounds, gfx::Rect(expected_position, tooltip_size));
}
}
#endif
TEST_F(TooltipControllerTest, TooltipsInMultipleViews) {
view_->set_tooltip_text(u"Tooltip Text");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
PrepareSecondView();
aura::Window* window = GetWindow();
aura::Window* root_window = GetRootWindow();
generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
for (int i = 0; i < 49; ++i) {
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(window, root_window->GetEventHandlerForPoint(
generator_->current_screen_location()));
std::u16string expected_tooltip = u"Tooltip Text";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetTooltipParentWindow());
}
for (int i = 0; i < 49; ++i) {
generator_->MoveMouseBy(1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_EQ(window, root_window->GetEventHandlerForPoint(
generator_->current_screen_location()));
std::u16string expected_tooltip; // = ""
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetTooltipParentWindow());
}
}
TEST_F(TooltipControllerTest, EnableOrDisableTooltips) {
view_->set_tooltip_text(u"Tooltip Text");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
// Disable tooltips and check again.
helper_->controller()->SetTooltipsEnabled(false);
EXPECT_FALSE(helper_->IsTooltipVisible());
helper_->UpdateIfRequired(TooltipTrigger::kCursor);
EXPECT_FALSE(helper_->IsTooltipVisible());
// Enable tooltips back and check again.
helper_->controller()->SetTooltipsEnabled(true);
EXPECT_FALSE(helper_->IsTooltipVisible());
helper_->UpdateIfRequired(TooltipTrigger::kCursor);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
}
// Verifies tooltip isn't shown if tooltip text consists entirely of whitespace.
TEST_F(TooltipControllerTest, DontShowEmptyTooltips) {
view_->set_tooltip_text(u" ");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint());
EXPECT_FALSE(helper_->IsTooltipVisible());
}
// Disabled on Lacros since TooltipLacros does not have tooltip timer on client
// side so cannot be tested on unittest.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_TooltipUpdateWhenTooltipDeferTimerIsRunning \
DISABLED_TooltipUpdateWhenTooltipDeferTimerIsRunning
#else
#define MAYBE_TooltipUpdateWhenTooltipDeferTimerIsRunning \
TooltipUpdateWhenTooltipDeferTimerIsRunning
#endif
TEST_F(TooltipControllerTest,
MAYBE_TooltipUpdateWhenTooltipDeferTimerIsRunning) {
view_->set_tooltip_text(u"Tooltip Text for view 1");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
TooltipTestView* view2 = PrepareSecondView();
view2->set_tooltip_text(u"Tooltip Text for view 2");
aura::Window* window = GetWindow();
// Tooltips show up with delay
helper_->SkipTooltipShowDelay(false);
// Tooltip 1 is scheduled and invisibled
generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
// Tooltip 2 is scheduled and invisible, the expected tooltip is tooltip 2
generator_->MoveMouseRelativeTo(window, view2->bounds().CenterPoint());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
std::u16string expected_tooltip = u"Tooltip Text for view 2";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetTooltipParentWindow());
helper_->SkipTooltipShowDelay(true);
}
TEST_F(TooltipControllerTest, TooltipHidesOnKeyPressAndStaysHiddenUntilChange) {
view_->set_tooltip_text(u"Tooltip Text for view 1");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
TooltipTestView* view2 = PrepareSecondView();
view2->set_tooltip_text(u"Tooltip Text for view 2");
aura::Window* window = GetWindow();
generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_TRUE(helper_->IsWillHideTooltipTimerRunning());
#endif
generator_->PressKey(ui::VKEY_1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
#endif
// Moving the mouse inside |view1| should not change the state of the tooltip
// or the timers.
for (int i = 0; i < 49; i++) {
generator_->MoveMouseBy(1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
#endif
EXPECT_EQ(window, GetRootWindow()->GetEventHandlerForPoint(
generator_->current_screen_location()));
std::u16string expected_tooltip = u"Tooltip Text for view 1";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetObservedWindow());
}
// Now we move the mouse on to |view2|. It should update the tooltip.
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_TRUE(helper_->IsWillHideTooltipTimerRunning());
#endif
std::u16string expected_tooltip = u"Tooltip Text for view 2";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetTooltipParentWindow());
}
TEST_F(TooltipControllerTest, TooltipStaysVisibleOnKeyRelease) {
view_->set_tooltip_text(u"my tooltip");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
// This shouldn't hide the tooltip.
generator_->ReleaseKey(ui::VKEY_1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
// This should hide the tooltip.
generator_->PressKey(ui::VKEY_1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
}
TEST_F(TooltipControllerTest, TooltipHidesOnTimeoutAndStaysHiddenUntilChange) {
view_->set_tooltip_text(u"Tooltip Text for view 1");
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
TooltipTestView* view2 = PrepareSecondView();
view2->set_tooltip_text(u"Tooltip Text for view 2");
aura::Window* window = GetWindow();
// Update tooltip so tooltip becomes visible.
generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_TRUE(helper_->IsWillHideTooltipTimerRunning());
#endif
helper_->FireHideTooltipTimer();
EXPECT_FALSE(helper_->IsTooltipVisible());
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
#endif
// Moving the mouse inside |view1| should not change the state of the tooltip
// or the timers.
for (int i = 0; i < 49; ++i) {
generator_->MoveMouseBy(1, 0);
EXPECT_FALSE(helper_->IsTooltipVisible());
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_FALSE(helper_->IsWillHideTooltipTimerRunning());
#endif
EXPECT_EQ(window, GetRootWindow()->GetEventHandlerForPoint(
generator_->current_screen_location()));
std::u16string expected_tooltip = u"Tooltip Text for view 1";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetObservedWindow());
}
// Now we move the mouse on to |view2|. It should update the tooltip.
generator_->MoveMouseBy(1, 0);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
#if !BUILDFLAG(IS_CHROMEOS_LACROS)
EXPECT_TRUE(helper_->IsWillHideTooltipTimerRunning());
#endif
std::u16string expected_tooltip = u"Tooltip Text for view 2";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(window));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(window, helper_->GetTooltipParentWindow());
}
// Verifies a mouse exit event hides the tooltips.
TEST_F(TooltipControllerTest, HideOnExit) {
view_->set_tooltip_text(u"Tooltip Text");
generator_->MoveMouseToCenterOf(GetWindow());
std::u16string expected_tooltip = u"Tooltip Text";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
generator_->SendMouseExit();
EXPECT_FALSE(helper_->IsTooltipVisible());
}
TEST_F(TooltipControllerTest, ReshowOnClickAfterEnterExit) {
// Owned by |view_|.
TooltipTestView* v1 = new TooltipTestView;
TooltipTestView* v2 = new TooltipTestView;
view_->AddChildView(v1);
view_->AddChildView(v2);
gfx::Rect view_bounds(view_->GetLocalBounds());
view_bounds.set_height(view_bounds.height() / 2);
v1->SetBoundsRect(view_bounds);
view_bounds.set_y(view_bounds.height());
v2->SetBoundsRect(view_bounds);
const std::u16string v1_tt(u"v1");
const std::u16string v2_tt(u"v2");
v1->set_tooltip_text(v1_tt);
v2->set_tooltip_text(v2_tt);
gfx::Point v1_point(1, 1);
View::ConvertPointToWidget(v1, &v1_point);
generator_->MoveMouseRelativeTo(GetWindow(), v1_point);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(v1_tt, helper_->GetTooltipText());
// Press the mouse, move to v2 and back to v1.
generator_->ClickLeftButton();
gfx::Point v2_point(1, 1);
View::ConvertPointToWidget(v2, &v2_point);
generator_->MoveMouseRelativeTo(GetWindow(), v2_point);
generator_->MoveMouseRelativeTo(GetWindow(), v1_point);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(v1_tt, helper_->GetTooltipText());
}
TEST_F(TooltipControllerTest, ShowAndHideTooltipTriggeredFromKeyboard) {
std::u16string expected_tooltip = u"Tooltip Text";
wm::SetTooltipText(GetWindow(), &expected_tooltip);
view_->set_tooltip_text(expected_tooltip);
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
helper_->controller()->UpdateTooltipFromKeyboard(
view_->ConvertRectToWidget(view_->bounds()), GetWindow());
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kKeyboard);
helper_->HideAndReset();
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
}
TEST_F(TooltipControllerTest,
KeyboardTriggeredTooltipStaysVisibleOnMouseExitedEvent) {
std::u16string expected_tooltip = u"Tooltip Text";
wm::SetTooltipText(GetWindow(), &expected_tooltip);
view_->set_tooltip_text(expected_tooltip);
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
// For this test to execute properly, make sure that the cursor location is
// somewhere out of the |view_|, different than (0, 0). This shouldn't show
// the tooltip.
gfx::Point off_view_point = view_->bounds().bottom_right();
off_view_point.Offset(1, 1);
generator_->MoveMouseRelativeTo(widget_->GetNativeWindow(), off_view_point);
EXPECT_FALSE(helper_->IsTooltipVisible());
// Trigger the tooltip from the keyboard.
helper_->controller()->UpdateTooltipFromKeyboard(
view_->ConvertRectToWidget(view_->bounds()), GetWindow());
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kKeyboard);
// Sending a mouse exited event shouldn't hide a keyboard triggered tooltip.
generator_->SendMouseExit();
EXPECT_TRUE(helper_->IsTooltipVisible());
helper_->HideAndReset();
expected_tooltip = u"Tooltip Text 2";
EXPECT_FALSE(helper_->IsTooltipVisible());
// However, a cursor triggered tooltip should still be hidden by a mouse
// exited event.
generator_->MoveMouseRelativeTo(widget_->GetNativeWindow(),
view_->bounds().CenterPoint());
EXPECT_TRUE(helper_->IsTooltipVisible());
generator_->SendMouseExit();
EXPECT_FALSE(helper_->IsTooltipVisible());
}
namespace {
// Returns the index of |window| in its parent's children.
int IndexInParent(const aura::Window* window) {
auto i = base::ranges::find(window->parent()->children(), window);
return i == window->parent()->children().end()
? -1
: static_cast<int>(i - window->parent()->children().begin());
}
} // namespace
// Verifies when capture is released the TooltipController resets state.
// Flaky on all builders. http://crbug.com/388268
TEST_F(TooltipControllerTest, DISABLED_CloseOnCaptureLost) {
view_->GetWidget()->SetCapture(view_);
RunPendingMessages();
view_->set_tooltip_text(u"Tooltip Text");
generator_->MoveMouseToCenterOf(GetWindow());
std::u16string expected_tooltip = u"Tooltip Text";
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
view_->GetWidget()->ReleaseCapture();
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->GetTooltipParentWindow() == nullptr);
}
// Disabled on Linux as X11ScreenOzone::GetAcceleratedWidgetAtScreenPoint
// and WaylandScreen::GetAcceleratedWidgetAtScreenPoint don't consider z-order.
// Disabled on Windows due to failing bots. http://crbug.com/604479
// Disabled on Lacros due to crash and flakiness.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_Capture DISABLED_Capture
#else
#define MAYBE_Capture Capture
#endif
// Verifies the correct window is found for tooltips when there is a capture.
TEST_F(TooltipControllerTest, MAYBE_Capture) {
const std::u16string tooltip_text(u"1");
const std::u16string tooltip_text2(u"2");
const std::u16string tooltip_text_child(u"child");
widget_->SetBounds(gfx::Rect(0, 0, 200, 200));
view_->set_tooltip_text(tooltip_text);
std::unique_ptr<views::Widget> widget2(CreateWidget(GetContext()));
widget2->SetContentsView(std::make_unique<View>());
TooltipTestView* view2 = new TooltipTestView;
widget2->GetContentsView()->AddChildView(view2);
view2->set_tooltip_text(tooltip_text2);
widget2->SetBounds(gfx::Rect(0, 0, 200, 200));
view2->SetBoundsRect(widget2->GetContentsView()->GetLocalBounds());
widget_->SetCapture(view_);
EXPECT_TRUE(widget_->HasCapture());
widget2->Show();
EXPECT_GE(IndexInParent(widget2->GetNativeWindow()),
IndexInParent(widget_->GetNativeWindow()));
generator_->MoveMouseRelativeTo(widget_->GetNativeWindow(),
view_->bounds().CenterPoint());
// Even though the mouse is over a window with a tooltip it shouldn't be
// picked up because the windows don't have the same value for
// |TooltipManager::kGroupingPropertyKey|.
EXPECT_TRUE(helper_->GetTooltipText().empty());
// Now make both the windows have same transient value for
// kGroupingPropertyKey. In this case the tooltip should be picked up from
// |widget2| (because the mouse is over it).
const int grouping_key = 1;
widget_->SetNativeWindowProperty(TooltipManager::kGroupingPropertyKey,
reinterpret_cast<void*>(grouping_key));
widget2->SetNativeWindowProperty(TooltipManager::kGroupingPropertyKey,
reinterpret_cast<void*>(grouping_key));
generator_->MoveMouseBy(1, 10);
EXPECT_EQ(tooltip_text2, helper_->GetTooltipText());
// Make child widget under widget2 and let the mouse be over the child widget.
// Even though the child widget does not have grouping property key, it should
// refer to its parent property. In this scenario, `widget_child`'s parent is
// `widget2` and it has the same kGroupingPropertyKey as `widget_`'s key, so
// `widget_child` should show tooltip when `widget_` has a capture.
std::unique_ptr<views::Widget> widget_child(CreateWidget(GetContext()));
widget_child->SetContentsView(std::make_unique<View>());
TooltipTestView* view_child = new TooltipTestView;
widget_child->GetContentsView()->AddChildView(view_child);
view_child->set_tooltip_text(tooltip_text_child);
widget_child->SetBounds(gfx::Rect(0, 0, 200, 200));
view_child->SetBoundsRect(widget_child->GetContentsView()->GetLocalBounds());
Widget::ReparentNativeView(widget_child->GetNativeView(),
widget2->GetNativeView());
widget_child->Show();
generator_->MoveMouseBy(1, 10);
EXPECT_EQ(tooltip_text_child, helper_->GetTooltipText());
widget2.reset();
}
TEST_F(TooltipControllerTest, ShowTooltipOnTooltipTextUpdate) {
std::u16string expected_tooltip;
wm::SetTooltipText(GetWindow(), &expected_tooltip);
// Create a mouse event. This event shouldn't trigger the tooltip to show
// since the tooltip text is empty, but should set the |observed_window_|
// correctly.
gfx::Point point(1, 1);
View::ConvertPointToWidget(view_, &point);
generator_->MoveMouseRelativeTo(GetWindow(), point);
EXPECT_EQ(std::u16string(), helper_->GetTooltipText());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
EXPECT_EQ(GetWindow(), helper_->GetObservedWindow());
EXPECT_FALSE(helper_->IsTooltipVisible());
// This is the heart of the test: we update the tooltip text and call
// UpdateTooltip. It should trigger the tooltip to show up because the
// |observed_window_| will be set to GetWindow() and the tooltip text on the
// window will be different than it previously was.
expected_tooltip = u"Tooltip text";
helper_->controller()->UpdateTooltip(GetWindow());
EXPECT_EQ(expected_tooltip, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_tooltip, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
helper_->HideAndReset();
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_EQ(nullptr, helper_->GetTooltipParentWindow());
}
// Disabled on Lacros since TooltipLacros does not have tooltip timer on client
// side so cannot be tested on unittest.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_TooltipPositionUpdatedWhenTimerRunning \
DISABLED_TooltipPositionUpdatedWhenTimerRunning
#else
#define MAYBE_TooltipPositionUpdatedWhenTimerRunning \
TooltipPositionUpdatedWhenTimerRunning
#endif
// This test validates that the TooltipController correctly triggers a position
// update for a tooltip that is about to be shown.
TEST_F(TooltipControllerTest, MAYBE_TooltipPositionUpdatedWhenTimerRunning) {
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(std::u16string(), helper_->state_manager()->tooltip_text());
std::u16string expected_text = u"Tooltip Text";
view_->set_tooltip_text(expected_text);
helper_->SkipTooltipShowDelay(false);
// Testing that the position will be updated when triggered from cursor.
{
gfx::Point position = view_->bounds().CenterPoint();
generator_->MoveMouseRelativeTo(GetWindow(), position);
EXPECT_EQ(expected_text, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_text, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(position, helper_->GetTooltipPosition());
// Since the |will_show_tooltip_timer_| is running, this should update the
// position of the already active tooltip.
generator_->MoveMouseBy(2, 0);
position.Offset(2, 0);
EXPECT_EQ(position, helper_->GetTooltipPosition());
helper_->HideAndReset();
}
// Testing that the position will be updated when triggered from cursor.
{
gfx::Rect bounds = view_->ConvertRectToWidget(view_->bounds());
helper_->controller()->UpdateTooltipFromKeyboard(bounds, GetWindow());
EXPECT_EQ(expected_text, wm::GetTooltipText(GetWindow()));
EXPECT_EQ(expected_text, helper_->GetTooltipText());
EXPECT_EQ(GetWindow(), helper_->GetTooltipParentWindow());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kKeyboard);
EXPECT_EQ(bounds.bottom_center(), helper_->GetTooltipPosition());
// Since the |will_show_tooltip_timer_| is running, this should update the
// position of the already active tooltip.
bounds.Offset(2, 0);
helper_->controller()->UpdateTooltipFromKeyboard(bounds, GetWindow());
EXPECT_EQ(bounds.bottom_center(), helper_->GetTooltipPosition());
helper_->HideAndReset();
}
helper_->SkipTooltipShowDelay(true);
}
// This test validates that tooltips are hidden when the currently active window
// loses focus to another window.
TEST_F(TooltipControllerTest, TooltipHiddenWhenWindowDeactivated) {
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(std::u16string(), helper_->state_manager()->tooltip_text());
view_->set_tooltip_text(u"Tooltip text 1");
// Start by showing the tooltip.
gfx::Point in_view_point = view_->bounds().CenterPoint();
generator_->MoveMouseRelativeTo(GetWindow(), in_view_point);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
// Then mock a window deactivation event.
helper_->MockWindowActivated(GetWindow(), /* active */ false);
// The previously visible tooltip should have been closed by that event.
EXPECT_FALSE(helper_->IsTooltipVisible());
// The tooltip should show up again if we move the cursor again.
view_->set_tooltip_text(u"Tooltip text 2");
generator_->MoveMouseBy(1, 1);
EXPECT_TRUE(helper_->IsTooltipVisible());
}
namespace {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
using TestTooltip = TestTooltipLacros;
#else
class TestTooltip : public Tooltip {
public:
TestTooltip() = default;
TestTooltip(const TestTooltip&) = delete;
TestTooltip& operator=(const TestTooltip&) = delete;
~TestTooltip() override = default;
void AddObserver(wm::TooltipObserver* observer) override {}
void RemoveObserver(wm::TooltipObserver* observer) override {}
const std::u16string& tooltip_text() const { return tooltip_text_; }
// Tooltip:
int GetMaxWidth(const gfx::Point& location) const override { return 100; }
void Update(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
const TooltipTrigger trigger) override {
tooltip_text_ = tooltip_text;
anchor_point_ = position + window->GetBoundsInScreen().OffsetFromOrigin();
trigger_ = trigger;
}
void Show() override { is_visible_ = true; }
void Hide() override { is_visible_ = false; }
bool IsVisible() override { return is_visible_; }
const gfx::Point& anchor_point() { return anchor_point_; }
TooltipTrigger trigger() { return trigger_; }
private:
bool is_visible_ = false;
std::u16string tooltip_text_;
gfx::Point anchor_point_;
TooltipTrigger trigger_;
};
#endif
} // namespace
// Use for tests that don't depend upon views.
class TooltipControllerTest2 : public aura::test::AuraTestBase {
public:
TooltipControllerTest2() : test_tooltip_(new TestTooltip) {}
TooltipControllerTest2(const TooltipControllerTest2&) = delete;
TooltipControllerTest2& operator=(const TooltipControllerTest2&) = delete;
~TooltipControllerTest2() override = default;
void SetUp() override {
at_exit_manager_ = std::make_unique<base::ShadowingAtExitManager>();
aura::test::AuraTestBase::SetUp();
controller_ = std::make_unique<TooltipController>(
std::unique_ptr<corewm::Tooltip>(test_tooltip_),
/* activation_client */ nullptr);
root_window()->AddPreTargetHandler(controller_.get());
SetTooltipClient(root_window(), controller_.get());
helper_ = std::make_unique<TooltipControllerTestHelper>(controller_.get());
#if BUILDFLAG(IS_CHROMEOS_LACROS)
test_tooltip_->SetStateManager(helper_->state_manager());
#endif
generator_ = std::make_unique<ui::test::EventGenerator>(root_window());
}
void TearDown() override {
root_window()->RemovePreTargetHandler(controller_.get());
wm::SetTooltipClient(root_window(), nullptr);
controller_.reset();
generator_.reset();
helper_.reset();
aura::test::AuraTestBase::TearDown();
at_exit_manager_.reset();
}
protected:
// Owned by |controller_|.
raw_ptr<TestTooltip> test_tooltip_;
std::unique_ptr<TooltipControllerTestHelper> helper_;
std::unique_ptr<ui::test::EventGenerator> generator_;
private:
// Needed to make sure the DeviceDataManager is cleaned up between test runs.
std::unique_ptr<base::ShadowingAtExitManager> at_exit_manager_;
std::unique_ptr<TooltipController> controller_;
};
TEST_F(TooltipControllerTest2, VerifyLeadingTrailingWhitespaceStripped) {
aura::test::TestWindowDelegate test_delegate;
std::unique_ptr<aura::Window> window(
CreateNormalWindow(100, root_window(), &test_delegate));
window->SetBounds(gfx::Rect(0, 0, 300, 300));
std::u16string tooltip_text(u" \nx ");
wm::SetTooltipText(window.get(), &tooltip_text);
EXPECT_FALSE(helper_->IsTooltipVisible());
generator_->MoveMouseToCenterOf(window.get());
EXPECT_EQ(u"x", test_tooltip_->tooltip_text());
}
// Verifies that tooltip is hidden and tooltip window closed upon cancel mode.
TEST_F(TooltipControllerTest2, CloseOnCancelMode) {
aura::test::TestWindowDelegate test_delegate;
std::unique_ptr<aura::Window> window(
CreateNormalWindow(100, root_window(), &test_delegate));
window->SetBounds(gfx::Rect(0, 0, 300, 300));
std::u16string tooltip_text(u"Tooltip Text");
wm::SetTooltipText(window.get(), &tooltip_text);
EXPECT_FALSE(helper_->IsTooltipVisible());
generator_->MoveMouseToCenterOf(window.get());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
// Send OnCancelMode event and verify that tooltip becomes invisible and
// the tooltip window is closed.
ui::CancelModeEvent event;
helper_->controller()->OnCancelMode(&event);
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->GetTooltipParentWindow() == nullptr);
}
// Use for tests that need both views and a TestTooltip.
class TooltipControllerTest3 : public ViewsTestBase {
public:
TooltipControllerTest3() = default;
TooltipControllerTest3(const TooltipControllerTest3&) = delete;
TooltipControllerTest3& operator=(const TooltipControllerTest3&) = delete;
~TooltipControllerTest3() override = default;
void SetUp() override {
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
set_native_widget_type(NativeWidgetType::kDesktop);
#endif
ViewsTestBase::SetUp();
aura::Window* root_window = GetContext();
widget_.reset(CreateWidget(root_window));
widget_->SetContentsView(std::make_unique<View>());
view_ = new TooltipTestView;
widget_->GetContentsView()->AddChildView(view_.get());
view_->SetBoundsRect(widget_->GetContentsView()->GetLocalBounds());
generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow());
auto tooltip = std::make_unique<TestTooltip>();
test_tooltip_ = tooltip.get();
controller_ = std::make_unique<TooltipController>(
std::move(tooltip), /* activation_client */ nullptr);
auto* tooltip_controller = static_cast<TooltipController*>(
wm::GetTooltipClient(widget_->GetNativeWindow()->GetRootWindow()));
if (tooltip_controller)
GetRootWindow()->RemovePreTargetHandler(tooltip_controller);
GetRootWindow()->AddPreTargetHandler(controller_.get());
helper_ = std::make_unique<TooltipControllerTestHelper>(controller_.get());
#if BUILDFLAG(IS_CHROMEOS_LACROS)
test_tooltip_->SetStateManager(helper_->state_manager());
#endif
SetTooltipClient(GetRootWindow(), controller_.get());
}
void TearDown() override {
GetRootWindow()->RemovePreTargetHandler(controller_.get());
wm::SetTooltipClient(GetRootWindow(), nullptr);
controller_.reset();
generator_.reset();
helper_.reset();
widget_.reset();
ViewsTestBase::TearDown();
}
aura::Window* GetWindow() { return widget_->GetNativeWindow(); }
protected:
// Owned by |controller_|.
raw_ptr<TestTooltip> test_tooltip_ = nullptr;
std::unique_ptr<TooltipControllerTestHelper> helper_;
std::unique_ptr<ui::test::EventGenerator> generator_;
std::unique_ptr<views::Widget> widget_;
raw_ptr<TooltipTestView> view_;
private:
std::unique_ptr<TooltipController> controller_;
#if BUILDFLAG(IS_WIN)
ui::ScopedOleInitializer ole_initializer_;
#endif
aura::Window* GetRootWindow() { return GetWindow()->GetRootWindow(); }
};
TEST_F(TooltipControllerTest3, TooltipPositionChangesOnTwoViewsWithSameLabel) {
// Owned by |view_|.
// These two views have the same tooltip text
TooltipTestView* v1 = new TooltipTestView;
TooltipTestView* v2 = new TooltipTestView;
// v1_1 is a view inside v1 that has an identical tooltip text to that of v1
// and v2
TooltipTestView* v1_1 = new TooltipTestView;
// v2_1 is a view inside v2 that has an identical tooltip text to that of v1
// and v2
TooltipTestView* v2_1 = new TooltipTestView;
// v2_2 is a view inside v2 with the tooltip text different from all the
// others
TooltipTestView* v2_2 = new TooltipTestView;
// Setup all the views' relations
view_->AddChildView(v1);
view_->AddChildView(v2);
v1->AddChildView(v1_1);
v2->AddChildView(v2_1);
v2->AddChildView(v2_2);
const std::u16string reference_string(u"Identical Tooltip Text");
const std::u16string alternative_string(u"Another Shrubbery");
v1->set_tooltip_text(reference_string);
v2->set_tooltip_text(reference_string);
v1_1->set_tooltip_text(reference_string);
v2_1->set_tooltip_text(reference_string);
v2_2->set_tooltip_text(alternative_string);
// Set views' bounds
gfx::Rect view_bounds(view_->GetLocalBounds());
view_bounds.set_height(view_bounds.height() / 2);
v1->SetBoundsRect(view_bounds);
v1_1->SetBounds(0, 0, 3, 3);
view_bounds.set_y(view_bounds.height());
v2->SetBoundsRect(view_bounds);
v2_2->SetBounds(view_bounds.width() - 3, view_bounds.height() - 3, 3, 3);
v2_1->SetBounds(0, 0, 3, 3);
// Test whether a toolbar appears on v1
gfx::Point center = v1->bounds().CenterPoint();
generator_->MoveMouseRelativeTo(GetWindow(), center);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(reference_string, helper_->GetTooltipText());
gfx::Point tooltip_bounds1 = test_tooltip_->anchor_point();
// Test whether the toolbar changes position on mouse over v2
center = v2->bounds().CenterPoint();
generator_->MoveMouseRelativeTo(GetWindow(), center);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(reference_string, helper_->GetTooltipText());
gfx::Point tooltip_bounds2 = test_tooltip_->anchor_point();
EXPECT_NE(tooltip_bounds1, gfx::Point());
EXPECT_NE(tooltip_bounds2, gfx::Point());
EXPECT_NE(tooltip_bounds1, tooltip_bounds2);
// Test if the toolbar does not change position on encountering a contained
// view with the same tooltip text
center = v2_1->GetLocalBounds().CenterPoint();
views::View::ConvertPointToTarget(v2_1, view_, ¢er);
generator_->MoveMouseRelativeTo(GetWindow(), center);
gfx::Point tooltip_bounds2_1 = test_tooltip_->anchor_point();
EXPECT_NE(tooltip_bounds2, tooltip_bounds2_1);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(reference_string, helper_->GetTooltipText());
// Test if the toolbar changes position on encountering a contained
// view with a different tooltip text
center = v2_2->GetLocalBounds().CenterPoint();
views::View::ConvertPointToTarget(v2_2, view_, ¢er);
generator_->MoveMouseRelativeTo(GetWindow(), center);
gfx::Point tooltip_bounds2_2 = test_tooltip_->anchor_point();
EXPECT_NE(tooltip_bounds2_1, tooltip_bounds2_2);
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(alternative_string, helper_->GetTooltipText());
// Test if moving from a view that is contained by a larger view, both with
// the same tooltip text, does not change tooltip's position.
center = v1_1->GetLocalBounds().CenterPoint();
views::View::ConvertPointToTarget(v1_1, view_, ¢er);
generator_->MoveMouseRelativeTo(GetWindow(), center);
gfx::Point tooltip_bounds1_1 = test_tooltip_->anchor_point();
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
EXPECT_EQ(reference_string, helper_->GetTooltipText());
center = v1->bounds().CenterPoint();
generator_->MoveMouseRelativeTo(GetWindow(), center);
tooltip_bounds1 = test_tooltip_->anchor_point();
EXPECT_NE(tooltip_bounds1_1, tooltip_bounds1);
EXPECT_EQ(reference_string, helper_->GetTooltipText());
}
class TooltipStateManagerTest : public TooltipControllerTest {
public:
TooltipStateManagerTest() = default;
TooltipStateManagerTest(const TooltipStateManagerTest&) = delete;
TooltipStateManagerTest& operator=(const TooltipStateManagerTest&) = delete;
~TooltipStateManagerTest() override = default;
};
TEST_F(TooltipStateManagerTest, ShowAndHideTooltip) {
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(std::u16string(), helper_->state_manager()->tooltip_text());
std::u16string expected_text = u"Tooltip Text";
helper_->state_manager()->Show(GetRootWindow(), expected_text,
gfx::Point(0, 0), TooltipTrigger::kCursor,
helper_->GetShowTooltipDelay(), {});
EXPECT_EQ(GetRootWindow(), helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_TRUE(helper_->IsTooltipVisible());
EXPECT_EQ(helper_->state_manager()->tooltip_trigger(),
TooltipTrigger::kCursor);
helper_->HideAndReset();
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
// We don't clear the text of the next tooltip because we use to validate that
// we're not about to show a tooltip that has been explicitly hidden.
// TODO(bebeaudr): Update this when we have a truly unique tooltipd id, even
// for web content.
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_FALSE(helper_->IsTooltipVisible());
}
// Disabled on Lacros since TooltipLacros cannot handle tooltip with delay on
// client side properly. To test with delay, it needs to use Ash server with
// ui_controls in interactive_ui_tests.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_ShowTooltipWithDelay DISABLED_ShowTooltipWithDelay
#else
#define MAYBE_ShowTooltipWithDelay ShowTooltipWithDelay
#endif
TEST_F(TooltipStateManagerTest, MAYBE_ShowTooltipWithDelay) {
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(std::u16string(), helper_->state_manager()->tooltip_text());
std::u16string expected_text = u"Tooltip Text";
helper_->SkipTooltipShowDelay(false);
// 1. Showing the tooltip will start the |will_show_tooltip_timer_| and set
// the attributes, but won't make the tooltip visible.
helper_->state_manager()->Show(GetRootWindow(), expected_text,
gfx::Point(0, 0), TooltipTrigger::kCursor,
helper_->GetShowTooltipDelay(), {});
EXPECT_EQ(GetRootWindow(), helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->IsWillShowTooltipTimerRunning());
// 2. Showing the tooltip again with a different expected text will cancel the
// existing timers running and will update the text, but it still won't make
// the tooltip visible.
expected_text = u"Tooltip Text 2";
helper_->state_manager()->Show(GetRootWindow(), expected_text,
gfx::Point(0, 0), TooltipTrigger::kCursor,
helper_->GetShowTooltipDelay(), {});
EXPECT_EQ(GetRootWindow(), helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->IsWillShowTooltipTimerRunning());
// 3. Calling HideAndReset should cancel the timer running.
helper_->HideAndReset();
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_FALSE(helper_->IsWillShowTooltipTimerRunning());
helper_->SkipTooltipShowDelay(true);
}
// Disabled on Lacros since TooltipLacros cannot handle tooltip with delay on
// client side properly. To test with delay, it needs to use Ash server with
// ui_controls in interactive_ui_tests.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_UpdatePositionIfNeeded DISABLED_UpdatePositionIfNeeded
#else
#define MAYBE_UpdatePositionIfNeeded UpdatePositionIfNeeded
#endif
// This test ensures that we can update the position of the tooltip after the
// |will_show_tooltip_timer_| has been started. This is needed because the
// cursor might still move between the moment Show is called and the timer
// fires.
TEST_F(TooltipStateManagerTest, MAYBE_UpdatePositionIfNeeded) {
EXPECT_EQ(nullptr, helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(std::u16string(), helper_->state_manager()->tooltip_text());
std::u16string expected_text = u"Tooltip Text";
helper_->SkipTooltipShowDelay(false);
{
gfx::Point position(0, 0);
// 1. When the |will_show_tooltip_timer_| is running, validate that we can
// update the position.
helper_->state_manager()->Show(GetRootWindow(), expected_text, position,
TooltipTrigger::kCursor,
helper_->GetShowTooltipDelay(), {});
EXPECT_EQ(GetRootWindow(),
helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_EQ(position, helper_->GetTooltipPosition());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->IsWillShowTooltipTimerRunning());
gfx::Point new_position = gfx::Point(10, 10);
// Because the tooltip was triggered by the cursor, the position should be
// updated by a keyboard triggered modification.
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kKeyboard);
EXPECT_EQ(position, helper_->GetTooltipPosition());
// But it should be updated when the position's update is triggered by the
// cursor.
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kCursor);
EXPECT_EQ(new_position, helper_->GetTooltipPosition());
// 2. Validate that we can't update the position when the timer isn't
// running.
helper_->HideAndReset();
position = new_position;
new_position = gfx::Point(20, 20);
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kCursor);
EXPECT_EQ(position, helper_->GetTooltipPosition());
}
{
gfx::Point position(0, 0);
// 1. When the |will_show_tooltip_timer_| is running, validate that we can
// update the position.
helper_->state_manager()->Show(GetRootWindow(), expected_text, position,
TooltipTrigger::kKeyboard,
helper_->GetShowTooltipDelay(), {});
EXPECT_EQ(GetRootWindow(),
helper_->state_manager()->tooltip_parent_window());
EXPECT_EQ(expected_text, helper_->state_manager()->tooltip_text());
EXPECT_EQ(position, helper_->GetTooltipPosition());
EXPECT_FALSE(helper_->IsTooltipVisible());
EXPECT_TRUE(helper_->IsWillShowTooltipTimerRunning());
gfx::Point new_position = gfx::Point(10, 10);
// Because the tooltip was triggered by the keyboard, the position shouldn't
// be updated by a cursor triggered modification.
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kCursor);
EXPECT_EQ(position, helper_->GetTooltipPosition());
// But it should be updated when the position's update is triggered by a
// keyboard action.
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kKeyboard);
EXPECT_EQ(new_position, helper_->GetTooltipPosition());
// 2. Validate that we can't update the position when the timer isn't
// running.
helper_->HideAndReset();
position = new_position;
new_position = gfx::Point(20, 20);
helper_->state_manager()->UpdatePositionIfNeeded(new_position,
TooltipTrigger::kKeyboard);
EXPECT_EQ(position, helper_->GetTooltipPosition());
}
helper_->SkipTooltipShowDelay(true);
}
} // namespace views::corewm::test
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_controller_unittest.cc | C++ | unknown | 61,241 |
// 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/corewm/tooltip_lacros.h"
#include <algorithm>
#include "ui/aura/window.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/platform_window/platform_window.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h"
#include "ui/wm/public/tooltip_observer.h"
namespace views::corewm {
namespace {
ui::PlatformWindowTooltipTrigger ToPlatformWindowTooltipTrigger(
TooltipTrigger trigger) {
switch (trigger) {
case TooltipTrigger::kCursor:
return ui::PlatformWindowTooltipTrigger::kCursor;
case TooltipTrigger::kKeyboard:
return ui::PlatformWindowTooltipTrigger::kKeyboard;
}
}
} // namespace
const char TooltipLacros::kWidgetName[] = "TooltipLacros";
TooltipLacros::TooltipLacros() = default;
TooltipLacros::~TooltipLacros() {
// Hide tooltip before destructing.
Hide();
}
void TooltipLacros::AddObserver(wm::TooltipObserver* observer) {
observers_.AddObserver(observer);
}
void TooltipLacros::RemoveObserver(wm::TooltipObserver* observer) {
observers_.RemoveObserver(observer);
}
void TooltipLacros::OnTooltipShownOnServer(const std::u16string& text,
const gfx::Rect& bounds) {
is_visible_ = true;
for (auto& observer : observers_) {
observer.OnTooltipShown(parent_window_, text, bounds);
}
}
void TooltipLacros::OnTooltipHiddenOnServer() {
is_visible_ = false;
for (auto& observer : observers_) {
observer.OnTooltipHidden(parent_window_);
}
}
int TooltipLacros::GetMaxWidth(const gfx::Point& location) const {
display::Screen* screen = display::Screen::GetScreen();
gfx::Rect display_bounds(screen->GetDisplayNearestPoint(location).bounds());
return std::min(kTooltipMaxWidth, (display_bounds.width() + 1) / 2);
}
void TooltipLacros::Update(aura::Window* parent_window,
const std::u16string& text,
const gfx::Point& position,
const TooltipTrigger trigger) {
DCHECK(parent_window);
parent_window_ = parent_window;
text_ = text;
position_ = position;
// Add the distance between `parent_window` and its toplevel window to
// `position_` since Ash-side server will use this position as relative to
// wayland toplevel window.
// TODO(crbug.com/1385219): Use WaylandWindow instead of ToplevelWindow/Popup
// when it's supported on ozone.
aura::Window::ConvertPointToTarget(
parent_window_, parent_window_->GetToplevelWindow(), &position_);
trigger_ = trigger;
}
void TooltipLacros::SetDelay(const base::TimeDelta& show_delay,
const base::TimeDelta& hide_delay) {
show_delay_ = show_delay;
hide_delay_ = hide_delay;
}
void TooltipLacros::Show() {
DCHECK(parent_window_);
auto* host =
views::DesktopWindowTreeHostLacros::From(parent_window_->GetHost());
auto* platform_window = host ? host->platform_window() : nullptr;
DCHECK(platform_window);
platform_window->ShowTooltip(text_, position_,
ToPlatformWindowTooltipTrigger(trigger_),
show_delay_, hide_delay_);
}
void TooltipLacros::Hide() {
if (!parent_window_) {
return;
}
auto* host =
views::DesktopWindowTreeHostLacros::From(parent_window_->GetHost());
auto* platform_window = host ? host->platform_window() : nullptr;
// `platform_window` may be null for testing.
if (platform_window) {
platform_window->HideTooltip();
}
parent_window_ = nullptr;
}
bool TooltipLacros::IsVisible() {
return is_visible_;
}
} // namespace views::corewm
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_lacros.cc | C++ | unknown | 3,772 |
// 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_COREWM_TOOLTIP_LACROS_H_
#define UI_VIEWS_COREWM_TOOLTIP_LACROS_H_
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/corewm/tooltip.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
}
namespace gfx {
class Rect;
}
namespace wm {
class TooltipObserver;
}
namespace views::corewm {
namespace test {
class TooltipLacrosForTesting;
}
// Implementation of Tooltip on Lacros using server side tooltip.
// TooltipLacros requests Ash to show/hide tooltip and Ash creates tooltip
// widget on server side and notifies Lacros of the tooltip visibility, position
// and the actual text to be shown.
//
// This is only used when Ash supports server side tooltip. If not, fallbacks to
// TooltipAura.
class VIEWS_EXPORT TooltipLacros : public Tooltip {
public:
static const char kWidgetName[];
TooltipLacros();
TooltipLacros(const TooltipLacros&) = delete;
TooltipLacros& operator=(const TooltipLacros&) = delete;
~TooltipLacros() override;
// Tooltip:
void AddObserver(wm::TooltipObserver* observer) override;
void RemoveObserver(wm::TooltipObserver* observer) override;
void OnTooltipShownOnServer(const std::u16string& text,
const gfx::Rect& boudns) override;
void OnTooltipHiddenOnServer() override;
private:
friend class test::TooltipLacrosForTesting;
// Tooltip:
int GetMaxWidth(const gfx::Point& location) const override;
void Update(aura::Window* parent_window,
const std::u16string& text,
const gfx::Point& position,
const TooltipTrigger trigger) override;
void SetDelay(const base::TimeDelta& show_delay,
const base::TimeDelta& hide_delay) override;
void Show() override;
void Hide() override;
bool IsVisible() override;
// True if tooltip is visible.
bool is_visible_ = false;
raw_ptr<aura::Window, DanglingUntriaged> parent_window_ = nullptr;
std::u16string text_;
gfx::Point position_;
TooltipTrigger trigger_;
base::TimeDelta show_delay_;
base::TimeDelta hide_delay_;
// Observes tooltip state change.
base::ObserverList<wm::TooltipObserver> observers_;
};
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TOOLTIP_LACROS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_lacros.h | C++ | unknown | 2,472 |
// 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/corewm/tooltip_state_manager.h"
#include <stddef.h>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/text_elider.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/wm/public/tooltip_client.h"
#include "ui/wm/public/tooltip_observer.h"
namespace views::corewm {
namespace {
#if BUILDFLAG(IS_WIN)
// Drawing a long word in tooltip is very slow on Windows. crbug.com/513693
constexpr size_t kMaxTooltipLength = 1024;
#else
constexpr size_t kMaxTooltipLength = 2048;
#endif
} // namespace
TooltipStateManager::TooltipStateManager(std::unique_ptr<Tooltip> tooltip)
: tooltip_(std::move(tooltip)) {}
TooltipStateManager::~TooltipStateManager() = default;
void TooltipStateManager::AddObserver(wm::TooltipObserver* observer) {
DCHECK(tooltip_);
tooltip_->AddObserver(observer);
}
void TooltipStateManager::RemoveObserver(wm::TooltipObserver* observer) {
DCHECK(tooltip_);
tooltip_->RemoveObserver(observer);
}
int TooltipStateManager::GetMaxWidth(const gfx::Point& location) const {
return tooltip_->GetMaxWidth(location);
}
void TooltipStateManager::HideAndReset() {
// Hide any open tooltips.
will_hide_tooltip_timer_.Stop();
tooltip_->Hide();
// Cancel pending tooltips and reset states.
will_show_tooltip_timer_.Stop();
tooltip_id_ = nullptr;
tooltip_parent_window_ = nullptr;
}
void TooltipStateManager::Show(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
TooltipTrigger trigger,
const base::TimeDelta show_delay,
const base::TimeDelta hide_delay) {
HideAndReset();
position_ = position;
tooltip_id_ = wm::GetTooltipId(window);
tooltip_text_ = tooltip_text;
tooltip_parent_window_ = window;
tooltip_trigger_ = trigger;
std::u16string truncated_text =
gfx::TruncateString(tooltip_text_, kMaxTooltipLength, gfx::WORD_BREAK);
std::u16string trimmed_text;
base::TrimWhitespace(truncated_text, base::TRIM_ALL, &trimmed_text);
// If the string consists entirely of whitespace, then don't both showing it
// (an empty tooltip is useless).
if (trimmed_text.empty())
return;
// Initialize the one-shot timer to show the tooltip after a delay. Any
// running timers have already been canceled by calling HideAndReset above.
// This ensures that the tooltip won't show up too early. The delayed
// appearance of a tooltip is by default and the `show_delay` is only set to
// 0 in the unit tests.
StartWillShowTooltipTimer(trimmed_text, show_delay, hide_delay);
}
void TooltipStateManager::UpdatePositionIfNeeded(const gfx::Point& position,
TooltipTrigger trigger) {
// The position should only be updated when the tooltip has been triggered but
// is not yet visible. Also, we only want to allow the update when it's set
// off by the same trigger that started the |will_show_tooltip_timer_| in
// the first place. Otherwise, for example, the position of a keyboard
// triggered tooltip could be updated by an unrelated mouse exited event. The
// tooltip would then show up at the wrong location.
if (!will_show_tooltip_timer_.IsRunning() || trigger != tooltip_trigger_)
return;
position_ = position;
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
void TooltipStateManager::OnTooltipShownOnServer(aura::Window* window,
const std::u16string& text,
const gfx::Rect& bounds) {
tooltip_id_ = wm::GetTooltipId(window);
tooltip_parent_window_ = window;
tooltip_->OnTooltipShownOnServer(text, bounds);
}
void TooltipStateManager::OnTooltipHiddenOnServer() {
tooltip_id_ = nullptr;
tooltip_parent_window_ = nullptr;
tooltip_->OnTooltipHiddenOnServer();
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
void TooltipStateManager::ShowNow(const std::u16string& trimmed_text,
const base::TimeDelta hide_delay) {
if (!tooltip_parent_window_)
return;
tooltip_->Update(tooltip_parent_window_, trimmed_text, position_,
tooltip_trigger_);
tooltip_->Show();
if (!hide_delay.is_zero()) {
will_hide_tooltip_timer_.Start(FROM_HERE, hide_delay, this,
&TooltipStateManager::HideAndReset);
}
}
void TooltipStateManager::StartWillShowTooltipTimer(
const std::u16string& trimmed_text,
const base::TimeDelta show_delay,
const base::TimeDelta hide_delay) {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(crbug.com/1338597): Remove support check and always use this step when
// Ash-chrome supporting server side tooltip is spread enough.
if (ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_tooltip) {
// Send `show_delay` and `hide_delay` together and delegate the timer
// handling on Ash side.
tooltip_->Update(tooltip_parent_window_, trimmed_text, position_,
tooltip_trigger_);
tooltip_->SetDelay(show_delay, hide_delay);
tooltip_->Show();
return;
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
if (!show_delay.is_zero()) {
// Start will show tooltip timer is show_delay is non-zero.
will_show_tooltip_timer_.Start(
FROM_HERE, show_delay,
base::BindOnce(&TooltipStateManager::ShowNow,
weak_factory_.GetWeakPtr(), trimmed_text, hide_delay));
return;
} else {
// This other path is needed for the unit tests to pass because Show is not
// immediately called when we have a `show_delay` of zero.
// TODO(bebeaudr): Fix this by ensuring that the unit tests wait for the
// timer to fire before continuing for non-Lacros platforms.
ShowNow(trimmed_text, hide_delay);
}
}
} // namespace views::corewm
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_state_manager.cc | C++ | unknown | 6,246 |
// 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_COREWM_TOOLTIP_STATE_MANAGER_H_
#define UI_VIEWS_COREWM_TOOLTIP_STATE_MANAGER_H_
#include <map>
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/corewm/tooltip.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
}
namespace gfx {
class Rect;
}
namespace wm {
class TooltipObserver;
}
namespace views::corewm {
namespace test {
class TooltipControllerTestHelper;
} // namespace test
// TooltipStateManager separates the state handling from the events handling of
// the TooltipController. It is in charge of updating the tooltip state and
// keeping track of it.
class VIEWS_EXPORT TooltipStateManager {
public:
explicit TooltipStateManager(std::unique_ptr<Tooltip> tooltip);
TooltipStateManager(const TooltipStateManager&) = delete;
TooltipStateManager& operator=(const TooltipStateManager&) = delete;
~TooltipStateManager();
void AddObserver(wm::TooltipObserver* observer);
void RemoveObserver(wm::TooltipObserver* observer);
int GetMaxWidth(const gfx::Point& location) const;
// Hide the tooltip, clear timers, and reset controller states.
void HideAndReset();
bool IsVisible() const { return tooltip_->IsVisible(); }
// Update the tooltip state attributes and start timer to show the tooltip. If
// `hide_timeout` is greater than 0, set a timer to hide it after a specific
// delay. Otherwise, show indefinitely.
void Show(aura::Window* window,
const std::u16string& tooltip_text,
const gfx::Point& position,
TooltipTrigger trigger,
const base::TimeDelta show_delay,
const base::TimeDelta hide_delay);
// Returns the `tooltip_id_`, which corresponds to the pointer of the view on
// which the tooltip was last added.
const void* tooltip_id() const { return tooltip_id_; }
// Returns the `tooltip_text_`, which corresponds to the last value the
// tooltip got updated to.
const std::u16string& tooltip_text() const { return tooltip_text_; }
const aura::Window* tooltip_parent_window() const {
return tooltip_parent_window_;
}
TooltipTrigger tooltip_trigger() const { return tooltip_trigger_; }
// Update the 'position_' if we're about to show the tooltip. This is to
// ensure that the tooltip's position is aligned with either the latest cursor
// location for a cursor triggered tooltip or the most recent position
// received for a keyboard triggered tooltip.
void UpdatePositionIfNeeded(const gfx::Point& position,
TooltipTrigger trigger);
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// Called when tooltip is shown/hidden on server.
// Only used by Lacros.
void OnTooltipShownOnServer(aura::Window* window,
const std::u16string& text,
const gfx::Rect& bounds);
void OnTooltipHiddenOnServer();
#endif
private:
friend class test::TooltipControllerTestHelper;
// Called once the |will_show_timer_| fires to show the tooltip.
void ShowNow(const std::u16string& trimmed_text,
const base::TimeDelta hide_delay);
// Start the show timer to show the tooltip.
void StartWillShowTooltipTimer(const std::u16string& trimmed_text,
const base::TimeDelta show_delay,
const base::TimeDelta hide_delay);
// For tests only.
bool IsWillShowTooltipTimerRunningForTesting() const {
return will_show_tooltip_timer_.IsRunning();
}
bool IsWillHideTooltipTimerRunningForTesting() const {
return will_hide_tooltip_timer_.IsRunning();
}
// The current position of the tooltip. This position is relative to the
// `tooltip_window_` and in that window's coordinate space.
gfx::Point position_;
std::unique_ptr<Tooltip> tooltip_;
// The pointer to the view for which the tooltip is set.
raw_ptr<const void> tooltip_id_ = nullptr;
// The text value used at the last tooltip update.
std::u16string tooltip_text_;
// The window on which the tooltip is added.
raw_ptr<aura::Window> tooltip_parent_window_ = nullptr;
TooltipTrigger tooltip_trigger_ = TooltipTrigger::kCursor;
// Two timers for the tooltip: one to hide an on-screen tooltip after a delay,
// and one to display the tooltip when the timer fires.
// Timers are always not running on Lacros using server side tooltip since
// they are handled on Ash side.
base::OneShotTimer will_hide_tooltip_timer_;
base::OneShotTimer will_show_tooltip_timer_;
// WeakPtrFactory to use for callbacks.
base::WeakPtrFactory<TooltipStateManager> weak_factory_{this};
};
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TOOLTIP_STATE_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_state_manager.h | C++ | unknown | 5,015 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/corewm/tooltip_view_aura.h"
#include "base/strings/string_util.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_provider.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/text_elider.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/painter.h"
namespace views::corewm {
namespace {
constexpr int kTooltipBorderThickness = 1;
constexpr gfx::Insets kBorderInset = gfx::Insets::TLBR(4, 8, 5, 8);
} // namespace
TooltipViewAura::TooltipViewAura()
: render_text_(gfx::RenderText::CreateRenderText()) {
render_text_->SetWordWrapBehavior(gfx::WRAP_LONG_WORDS);
render_text_->SetMultiline(true);
SetBackground(
views::CreateThemedSolidBackground(ui::kColorTooltipBackground));
SetBorder(views::CreatePaddedBorder(
views::CreateThemedSolidBorder(kTooltipBorderThickness,
ui::kColorTooltipForeground),
kBorderInset - gfx::Insets(kTooltipBorderThickness)));
ResetDisplayRect();
}
TooltipViewAura::~TooltipViewAura() = default;
void TooltipViewAura::SetText(const std::u16string& text) {
render_text_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD);
// Replace tabs with whitespace to avoid placeholder character rendering
// where previously it did not. crbug.com/993100
std::u16string newText(text);
base::ReplaceChars(newText, u"\t", u" ", &newText);
render_text_->SetText(newText);
SchedulePaint();
}
void TooltipViewAura::SetFontList(const gfx::FontList& font_list) {
render_text_->SetFontList(font_list);
}
void TooltipViewAura::SetMinLineHeight(int line_height) {
render_text_->SetMinLineHeight(line_height);
}
void TooltipViewAura::SetMaxWidth(int width) {
max_width_ = width;
ResetDisplayRect();
}
void TooltipViewAura::OnPaint(gfx::Canvas* canvas) {
OnPaintBackground(canvas);
gfx::Size text_size = size();
gfx::Insets insets = GetInsets();
text_size.Enlarge(-insets.width(), -insets.height());
render_text_->SetDisplayRect(gfx::Rect(text_size));
canvas->Save();
canvas->Translate(gfx::Vector2d(insets.left(), insets.top()));
render_text_->Draw(canvas);
canvas->Restore();
OnPaintBorder(canvas);
}
gfx::Size TooltipViewAura::CalculatePreferredSize() const {
gfx::Size view_size = render_text_->GetStringSize();
gfx::Insets insets = GetInsets();
view_size.Enlarge(insets.width(), insets.height());
return view_size;
}
void TooltipViewAura::OnThemeChanged() {
views::View::OnThemeChanged();
// Force the text color to be readable when |background_color| is not
// opaque.
render_text_->set_subpixel_rendering_suppressed(
SkColorGetA(background()->get_color()) != SK_AlphaOPAQUE);
render_text_->SetColor(
GetColorProvider()->GetColor(ui::kColorTooltipForeground));
}
void TooltipViewAura::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kTooltip;
node_data->SetNameChecked(render_text_->GetDisplayText());
}
void TooltipViewAura::ResetDisplayRect() {
render_text_->SetDisplayRect(gfx::Rect(0, 0, max_width_, 100000));
}
BEGIN_METADATA(TooltipViewAura, views::View)
END_METADATA
} // namespace views::corewm
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_view_aura.cc | C++ | unknown | 3,425 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_COREWM_TOOLTIP_VIEW_AURA_H_
#define UI_VIEWS_COREWM_TOOLTIP_VIEW_AURA_H_
#include <memory>
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/render_text.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace views::corewm {
// The contents view for tooltip widget on aura platforms.
// TODO(oshima): Consider to use views::Label when the performance issue is
// resolved.
class VIEWS_EXPORT TooltipViewAura : public views::View {
public:
METADATA_HEADER(TooltipViewAura);
TooltipViewAura();
TooltipViewAura(const TooltipViewAura&) = delete;
TooltipViewAura& operator=(const TooltipViewAura&) = delete;
~TooltipViewAura() override;
const gfx::RenderText* render_text() const { return render_text_.get(); }
void SetText(const std::u16string& text);
void SetFontList(const gfx::FontList& font_list);
void SetMinLineHeight(int line_height);
void SetMaxWidth(int width);
// views:View:
void OnPaint(gfx::Canvas* canvas) override;
gfx::Size CalculatePreferredSize() const override;
void OnThemeChanged() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
private:
void ResetDisplayRect();
std::unique_ptr<gfx::RenderText> render_text_;
int max_width_ = 0;
};
} // namespace views::corewm
#endif // UI_VIEWS_COREWM_TOOLTIP_VIEW_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/corewm/tooltip_view_aura.h | C++ | unknown | 1,534 |
include_rules = [
# Views debug code should avoid relying on //ui/views code to ensure debugger
# extensions are resillient to version structure changes within the codebase.
"-ui/views",
"+ui/views/debug",
]
| Zhao-PengFei35/chromium_src_4 | ui/views/debug/DEPS | Python | unknown | 216 |
// 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/debug/debugger_utils.h"
#include <inttypes.h>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
namespace views::debug {
namespace {
using AttributeStrings = std::vector<std::string>;
constexpr int kElementIndent = 2;
constexpr int kAttributeIndent = 4;
std::string ToString(bool val) {
return val ? "true" : "false";
}
std::string ToString(int val) {
return base::NumberToString(val);
}
std::string ToString(ViewDebugWrapper::BoundsTuple bounds) {
return base::StringPrintf("%d %d %dx%d", std::get<0>(bounds),
std::get<1>(bounds), std::get<2>(bounds),
std::get<3>(bounds));
}
// intptr_t can alias to int, preventing the use of overloading for ToString.
std::string PtrToString(intptr_t val) {
return base::StringPrintf("0x%" PRIxPTR, val);
}
// Adds attribute string of the form <attribute_name>="<attribute_value>".
template <typename T>
void AddAttributeString(AttributeStrings& attributes,
const std::string& name,
const T& value) {
attributes.push_back(name + "=\"" + ToString(value) + "\"");
}
void AddPtrAttributeString(AttributeStrings& attributes,
const std::string& name,
const absl::optional<intptr_t>& value) {
if (!value)
return;
attributes.push_back(name + "=\"" + PtrToString(value.value()) + "\"");
}
AttributeStrings GetAttributeStrings(ViewDebugWrapper* view, bool verbose) {
AttributeStrings attributes;
if (verbose) {
view->ForAllProperties(base::BindRepeating(
[](AttributeStrings* attributes, const std::string& name,
const std::string& val) {
attributes->push_back(name + "=\"" + val + "\"");
},
base::Unretained(&attributes)));
} else {
AddPtrAttributeString(attributes, "address", view->GetAddress());
AddAttributeString(attributes, "bounds", view->GetBounds());
AddAttributeString(attributes, "enabled", view->GetNeedsLayout());
AddAttributeString(attributes, "id", view->GetID());
AddAttributeString(attributes, "needs-layout", view->GetNeedsLayout());
AddAttributeString(attributes, "visible", view->GetVisible());
}
return attributes;
}
std::string GetPaddedLine(int current_depth, bool attribute_line = false) {
const int padding = attribute_line
? current_depth * kElementIndent + kAttributeIndent
: current_depth * kElementIndent;
return std::string(padding, ' ');
}
void PrintViewHierarchyImpl(std::ostream* out,
ViewDebugWrapper* view,
int current_depth,
bool verbose,
int target_depth,
size_t column_limit) {
std::string line = GetPaddedLine(current_depth);
line += "<" + view->GetViewClassName();
for (const std::string& attribute_string :
GetAttributeStrings(view, verbose)) {
if (line.size() + attribute_string.size() + 1 > column_limit) {
// If adding the attribute string would cause the line to exceed the
// column limit, send the line to `out` and start a new line. The new line
// should fit at least one attribute string even if it means exceeding the
// column limit.
*out << line << "\n";
line = GetPaddedLine(current_depth, true) + attribute_string;
} else {
// Keep attribute strings on the existing line if it fits within the
// column limit.
line += " " + attribute_string;
}
}
// Print children only if they exist and we are not yet at our target tree
// depth.
if (!view->GetChildren().empty() &&
(target_depth == -1 || current_depth < target_depth)) {
*out << line << ">\n";
for (ViewDebugWrapper* child : view->GetChildren()) {
PrintViewHierarchyImpl(out, child, current_depth + 1, verbose,
target_depth, column_limit);
}
line = GetPaddedLine(current_depth);
*out << line << "</" << view->GetViewClassName() << ">\n";
} else {
// If no children are to be printed use a self closing tag to terminate the
// View element.
*out << line << " />\n";
}
}
} // namespace
absl::optional<intptr_t> ViewDebugWrapper::GetAddress() {
return absl::nullopt;
}
void PrintViewHierarchy(std::ostream* out,
ViewDebugWrapper* view,
bool verbose,
int depth,
size_t column_limit) {
PrintViewHierarchyImpl(out, view, 0, verbose, depth, column_limit);
}
} // namespace views::debug
| Zhao-PengFei35/chromium_src_4 | ui/views/debug/debugger_utils.cc | C++ | unknown | 4,891 |
// 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_DEBUG_DEBUGGER_UTILS_H_
#define UI_VIEWS_DEBUG_DEBUGGER_UTILS_H_
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#include "base/functional/callback.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace views::debug {
// This class acts as a "view" over the View class. This has been done to allow
// debugger extensions to remnain resillient to structure and version changes in
// the code base.
// TODO(tluk): Replace use of //ui/views/debug_utils.h with this.
class ViewDebugWrapper {
public:
// Tuple used to represent View bounds. Takes the form <x, y, width, height>.
using BoundsTuple = std::tuple<int, int, int, int>;
// Callback function used to iterate through all metadata properties.
using PropCallback =
base::RepeatingCallback<void(const std::string&, const std::string&)>;
ViewDebugWrapper() = default;
virtual ~ViewDebugWrapper() = default;
virtual std::string GetViewClassName() = 0;
virtual int GetID() = 0;
virtual BoundsTuple GetBounds() = 0;
virtual bool GetVisible() = 0;
virtual bool GetNeedsLayout() = 0;
virtual bool GetEnabled() = 0;
virtual std::vector<ViewDebugWrapper*> GetChildren() = 0;
virtual void ForAllProperties(PropCallback callback) {}
virtual absl::optional<intptr_t> GetAddress();
};
void PrintViewHierarchy(std::ostream* out,
ViewDebugWrapper* view,
bool verbose = false,
int depth = -1,
size_t column_limit = 240);
} // namespace views::debug
#endif // UI_VIEWS_DEBUG_DEBUGGER_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/debug/debugger_utils.h | C++ | unknown | 1,771 |
// 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/debug_utils.h"
#include <ostream>
#include "base/logging.h"
#include "ui/compositor/layer.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#if !defined(NDEBUG)
#include "ui/gfx/geometry/angle_conversions.h"
#include "ui/gfx/geometry/decomposed_transform.h"
#include "ui/gfx/geometry/transform.h"
#endif
namespace views {
namespace {
void PrintViewHierarchyImp(const View* view,
size_t indent,
std::ostringstream* out) {
*out << std::string(indent, ' ');
*out << view->GetClassName();
*out << ' ';
*out << view->GetID();
*out << ' ';
*out << view->x() << "," << view->y() << ",";
*out << view->bounds().right() << "," << view->bounds().bottom();
*out << ' ';
*out << view;
*out << '\n';
for (const View* child : view->children())
PrintViewHierarchyImp(child, indent + 2, out);
}
void PrintFocusHierarchyImp(const View* view,
size_t indent,
std::ostringstream* out) {
*out << std::string(indent, ' ');
*out << view->GetClassName();
*out << ' ';
*out << view->GetID();
*out << ' ';
*out << view->GetClassName();
*out << ' ';
*out << view;
*out << '\n';
if (!view->children().empty())
PrintFocusHierarchyImp(view->children().front(), indent + 2, out);
const View* next_focusable = view->GetNextFocusableView();
if (next_focusable)
PrintFocusHierarchyImp(next_focusable, indent, out);
}
#if !defined(NDEBUG)
std::string PrintViewGraphImpl(const View* view) {
// 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
const size_t kMaxPointerStringLength = 19;
std::string result;
// Node characteristics.
char p[kMaxPointerStringLength];
const std::string class_name(view->GetClassName());
size_t base_name_index = class_name.find_last_of('/');
if (base_name_index == std::string::npos)
base_name_index = 0;
else
base_name_index++;
constexpr size_t kBoundsBufferSize = 512;
char bounds_buffer[kBoundsBufferSize];
// Information about current node.
base::snprintf(p, kBoundsBufferSize, "%p", view);
result.append(" N");
result.append(p + 2);
result.append(" [label=\"");
result.append(class_name.substr(base_name_index).c_str());
base::snprintf(bounds_buffer, kBoundsBufferSize,
"\\n bounds: (%d, %d), (%dx%d)", view->bounds().x(),
view->bounds().y(), view->bounds().width(),
view->bounds().height());
result.append(bounds_buffer);
if (!view->GetTransform().IsIdentity()) {
if (absl::optional<gfx::DecomposedTransform> decomp =
view->GetTransform().Decompose()) {
base::snprintf(bounds_buffer, kBoundsBufferSize,
"\\n translation: (%f, %f)", decomp->translate[0],
decomp->translate[1]);
result.append(bounds_buffer);
base::snprintf(bounds_buffer, kBoundsBufferSize, "\\n rotation: %3.2f",
gfx::RadToDeg(std::acos(decomp->quaternion.w()) * 2));
result.append(bounds_buffer);
base::snprintf(bounds_buffer, kBoundsBufferSize,
"\\n scale: (%2.4f, %2.4f)", decomp->scale[0],
decomp->scale[1]);
result.append(bounds_buffer);
}
}
result.append("\"");
if (!view->parent())
result.append(", shape=box");
if (view->layer()) {
if (view->layer()->has_external_content())
result.append(", color=green");
else
result.append(", color=red");
if (view->layer()->fills_bounds_opaquely())
result.append(", style=filled");
}
result.append("]\n");
// Link to parent.
if (view->parent()) {
char pp[kMaxPointerStringLength];
base::snprintf(pp, kMaxPointerStringLength, "%p", view->parent());
result.append(" N");
result.append(pp + 2);
result.append(" -> N");
result.append(p + 2);
result.append("\n");
}
for (const View* child : view->children())
result.append(PrintViewGraphImpl(child));
return result;
}
#endif
} // namespace
void PrintWidgetInformation(const Widget& widget,
bool detailed,
std::ostringstream* out) {
*out << " name=" << widget.GetName();
*out << " (" << &widget << ")";
if (widget.parent())
*out << " parent=" << widget.parent();
else
*out << " parent=none";
const ui::Layer* layer = widget.GetLayer();
if (layer)
*out << " layer=" << layer;
else
*out << " layer=none";
*out << (widget.is_top_level() ? " [top_level]" : " [!top_level]");
if (detailed) {
*out << (widget.IsActive() ? " [active]" : " [!active]");
*out << (widget.IsVisible() ? " [visible]" : " [!visible]");
}
*out << (widget.IsClosed() ? " [closed]" : "");
*out << (widget.IsMaximized() ? " [maximized]" : "");
*out << (widget.IsMinimized() ? " [minimized]" : "");
*out << (widget.IsFullscreen() ? " [fullscreen]" : "");
if (detailed)
*out << " " << widget.GetWindowBoundsInScreen().ToString();
*out << '\n';
}
void PrintViewHierarchy(const View* view) {
std::ostringstream out;
PrintViewHierarchy(view, &out);
// Error so users in the field can generate and upload logs.
LOG(ERROR) << out.str();
}
void PrintViewHierarchy(const View* view, std::ostringstream* out) {
*out << "View hierarchy:\n";
PrintViewHierarchyImp(view, 0, out);
}
void PrintFocusHierarchy(const View* view) {
std::ostringstream out;
out << "Focus hierarchy:\n";
PrintFocusHierarchyImp(view, 0, &out);
// Error so users in the field can generate and upload logs.
LOG(ERROR) << out.str();
}
#if !defined(NDEBUG)
std::string PrintViewGraph(const View* view) {
return "digraph {\n" + PrintViewGraphImpl(view) + "}\n";
}
#endif
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/debug_utils.cc | C++ | unknown | 5,951 |
// 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_DEBUG_UTILS_H_
#define UI_VIEWS_DEBUG_UTILS_H_
#include <sstream>
#include <string>
#include "ui/views/views_export.h"
namespace views {
class View;
class Widget;
// Log the view hierarchy.
VIEWS_EXPORT void PrintViewHierarchy(const View* view);
// Print the view hierarchy to |out|.
VIEWS_EXPORT void PrintViewHierarchy(const View* view, std::ostringstream* out);
// Log the focus traversal hierarchy.
VIEWS_EXPORT void PrintFocusHierarchy(const View* view);
// Log the information of the widget to |out|. |detailed| controls the amount of
// information logged.
VIEWS_EXPORT void PrintWidgetInformation(const Widget& widget,
bool detailed,
std::ostringstream* out);
#if !defined(NDEBUG)
// Returns string containing a graph of the views hierarchy in graphViz DOT
// language (http://graphviz.org/). Can be called within debugger and saved
// to a file to compile/view.
VIEWS_EXPORT std::string PrintViewGraph(const View* view);
#endif
} // namespace views
#endif // UI_VIEWS_DEBUG_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/debug_utils.h | C++ | unknown | 1,248 |
// 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/dialog_model_context_menu_controller.h"
#include "ui/base/models/dialog_model.h"
#include "ui/views/view.h"
namespace views {
DialogModelContextMenuController::DialogModelContextMenuController(
View* host,
base::RepeatingCallback<std::unique_ptr<ui::DialogModel>()>
model_generator_callback,
int run_types,
MenuAnchorPosition anchor_position)
: host_(host),
run_types_(run_types),
anchor_position_(anchor_position),
model_generator_callback_(model_generator_callback) {
host_->set_context_menu_controller(this);
}
DialogModelContextMenuController::~DialogModelContextMenuController() {
host_->set_context_menu_controller(nullptr);
}
void DialogModelContextMenuController::ShowContextMenuForViewImpl(
View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) {
DCHECK_EQ(source, host_);
menu_model_ = std::make_unique<ui::DialogModelMenuModelAdapter>(
model_generator_callback_.Run());
menu_runner_ =
std::make_unique<views::MenuRunner>(menu_model_.get(), run_types_);
menu_runner_->RunMenuAt(source->GetWidget(), /*button_controller=*/nullptr,
gfx::Rect(point, gfx::Size()), anchor_position_,
source_type);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/dialog_model_context_menu_controller.cc | C++ | unknown | 1,447 |
// 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_DIALOG_MODEL_CONTEXT_MENU_CONTROLLER_H_
#define UI_VIEWS_DIALOG_MODEL_CONTEXT_MENU_CONTROLLER_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/base/models/dialog_model_menu_model_adapter.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/views_export.h"
namespace views {
class View;
// A ContextMenuController that makes it easier to host context menus using
// ui::DialogModel. The constructor registers `this` as the context-menu
// controller of the `host` View.
class VIEWS_EXPORT DialogModelContextMenuController final
: public ContextMenuController {
public:
DialogModelContextMenuController(
View* host,
base::RepeatingCallback<std::unique_ptr<ui::DialogModel>()>
model_generator_callback,
int run_types,
MenuAnchorPosition anchor_position = MenuAnchorPosition::kTopLeft);
DialogModelContextMenuController(const DialogModelContextMenuController&) =
delete;
DialogModelContextMenuController& operator=(
const DialogModelContextMenuController&) = delete;
~DialogModelContextMenuController() override;
void ShowContextMenuForViewImpl(View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) override;
private:
const raw_ptr<View> host_;
const int run_types_;
const MenuAnchorPosition anchor_position_;
const base::RepeatingCallback<std::unique_ptr<ui::DialogModel>()>
model_generator_callback_;
std::unique_ptr<ui::DialogModelMenuModelAdapter> menu_model_;
std::unique_ptr<MenuRunner> menu_runner_;
};
} // namespace views
#endif // UI_VIEWS_DIALOG_MODEL_CONTEXT_MENU_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/dialog_model_context_menu_controller.h | C++ | unknown | 1,907 |
// 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_DRAG_CONTROLLER_H_
#define UI_VIEWS_DRAG_CONTROLLER_H_
#include "ui/views/views_export.h"
namespace gfx {
class Point;
}
namespace ui {
class OSExchangeData;
}
namespace views {
class View;
// DragController is responsible for writing drag data for a view, as well as
// supplying the supported drag operations. Use DragController if you don't
// want to subclass.
class VIEWS_EXPORT DragController {
public:
// Writes the data for the drag.
virtual void WriteDragDataForView(View* sender,
const gfx::Point& press_pt,
ui::OSExchangeData* data) = 0;
// Returns the supported drag operations (see DragDropTypes for possible
// values). A drag is only started if this returns a non-zero value.
virtual int GetDragOperationsForView(View* sender, const gfx::Point& p) = 0;
// Returns true if a drag operation can be started.
// |press_pt| represents the coordinates where the mouse was initially
// pressed down. |p| is the current mouse coordinates.
virtual bool CanStartDragForView(View* sender,
const gfx::Point& press_pt,
const gfx::Point& p) = 0;
// Called when the drag on view will start.
virtual void OnWillStartDragForView(View* dragged_view) {}
protected:
virtual ~DragController() = default;
};
} // namespace views
#endif // UI_VIEWS_DRAG_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/drag_controller.h | C++ | unknown | 1,602 |
// 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/drag_utils.h"
#include "ui/base/layout.h"
#include "ui/views/widget/widget.h"
namespace views {
float ScaleFactorForDragFromWidget(const Widget* widget) {
float device_scale = 1.0f;
if (widget && widget->GetNativeView()) {
gfx::NativeView view = widget->GetNativeView();
device_scale = ui::GetScaleFactorForNativeView(view);
}
return device_scale;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/drag_utils.cc | C++ | unknown | 555 |
// 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_DRAG_UTILS_H_
#define UI_VIEWS_DRAG_UTILS_H_
#include <memory>
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
namespace gfx {
class Point;
}
namespace views {
class Widget;
// Starts a drag operation. This blocks until the drag operation completes.
VIEWS_EXPORT void RunShellDrag(gfx::NativeView view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source);
// Returns the device scale for the display associated with this |widget|'s
// native view.
VIEWS_EXPORT float ScaleFactorForDragFromWidget(const Widget* widget);
} // namespace views
#endif // UI_VIEWS_DRAG_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/drag_utils.h | C++ | unknown | 1,076 |
// 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/drag_utils.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/wm/core/coordinate_conversion.h"
namespace views {
void RunShellDrag(gfx::NativeView view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
gfx::Point screen_location(location);
wm::ConvertPointToScreen(view, &screen_location);
aura::Window* root_window = view->GetRootWindow();
if (aura::client::GetDragDropClient(root_window)) {
aura::client::GetDragDropClient(root_window)
->StartDragAndDrop(std::move(data), root_window, view, screen_location,
operation, source);
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/drag_utils_aura.cc | C++ | unknown | 1,000 |
// 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/drag_utils.h"
#include "base/notreached.h"
namespace views {
void RunShellDrag(gfx::NativeView view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
NOTIMPLEMENTED();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/drag_utils_mac.mm | Objective-C++ | unknown | 506 |
// 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_EVENT_MONITOR_H_
#define UI_VIEWS_EVENT_MONITOR_H_
#include <memory>
#include <set>
#include "ui/events/event_observer.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
namespace views {
// RAII-style class that forwards events matching the specified |types| to
// |event_observer| before they are dispatched to the intended target.
// EventObservers cannot modify events nor alter dispatch.
class VIEWS_EXPORT EventMonitor {
public:
virtual ~EventMonitor() = default;
// Create an instance for monitoring application events. This includes all
// events on ChromeOS, but only events targeting Chrome on desktop platforms.
// |context| is used to determine where to observe events from.
// |context| may be destroyed before the EventMonitor.
static std::unique_ptr<EventMonitor> CreateApplicationMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow context,
const std::set<ui::EventType>& types);
// Create an instance for monitoring events on a specific window.
// The EventMonitor instance must be destroyed before |target_window|.
static std::unique_ptr<EventMonitor> CreateWindowMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow target_window,
const std::set<ui::EventType>& types);
// Returns the last recorded mouse event location in screen coordinates.
virtual gfx::Point GetLastMouseLocation() = 0;
};
} // namespace views
#endif // UI_VIEWS_EVENT_MONITOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor.h | C++ | unknown | 1,721 |
// 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/event_monitor_aura.h"
#include <memory>
#include "base/check_op.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/events/event_observer.h"
#include "ui/events/event_target.h"
namespace views {
namespace {
// An EventMonitorAura that removes its event observer on window destruction.
class WindowMonitorAura : public EventMonitorAura, public aura::WindowObserver {
public:
WindowMonitorAura(ui::EventObserver* event_observer,
aura::Window* target_window,
const std::set<ui::EventType>& types)
: EventMonitorAura(event_observer, target_window, types),
target_window_(target_window) {
window_observation_.Observe(target_window);
}
WindowMonitorAura(const WindowMonitorAura&) = delete;
WindowMonitorAura& operator=(const WindowMonitorAura&) = delete;
~WindowMonitorAura() override = default;
// aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override {
DCHECK_EQ(window, target_window_);
DCHECK(window_observation_.IsObservingSource(target_window_.get()));
window_observation_.Reset();
target_window_ = nullptr;
TearDown();
}
private:
raw_ptr<aura::Window> target_window_;
base::ScopedObservation<aura::Window, aura::WindowObserver>
window_observation_{this};
};
} // namespace
// static
std::unique_ptr<EventMonitor> EventMonitor::CreateApplicationMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow context,
const std::set<ui::EventType>& types) {
return std::make_unique<EventMonitorAura>(event_observer,
aura::Env::GetInstance(), types);
}
// static
std::unique_ptr<EventMonitor> EventMonitor::CreateWindowMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow target_window,
const std::set<ui::EventType>& types) {
return std::make_unique<WindowMonitorAura>(event_observer, target_window,
types);
}
EventMonitorAura::EventMonitorAura(ui::EventObserver* event_observer,
ui::EventTarget* event_target,
const std::set<ui::EventType>& types)
: event_observer_(event_observer), event_target_(event_target) {
DCHECK(event_observer_);
DCHECK(event_target_);
aura::Env::GetInstance()->AddEventObserver(event_observer_, event_target,
types);
}
EventMonitorAura::~EventMonitorAura() {
TearDown();
}
gfx::Point EventMonitorAura::GetLastMouseLocation() {
return aura::Env::GetInstance()->last_mouse_location();
}
void EventMonitorAura::TearDown() {
if (event_observer_)
aura::Env::GetInstance()->RemoveEventObserver(event_observer_);
event_observer_ = nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor_aura.cc | C++ | unknown | 3,042 |
// 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_EVENT_MONITOR_AURA_H_
#define UI_VIEWS_EVENT_MONITOR_AURA_H_
#include <set>
#include "base/memory/raw_ptr.h"
#include "ui/views/event_monitor.h"
namespace ui {
class EventTarget;
}
namespace views {
// Observes events by installing a pre-target handler on the ui::EventTarget.
class EventMonitorAura : public EventMonitor {
public:
EventMonitorAura(ui::EventObserver* event_observer,
ui::EventTarget* event_target,
const std::set<ui::EventType>& types);
EventMonitorAura(const EventMonitorAura&) = delete;
EventMonitorAura& operator=(const EventMonitorAura&) = delete;
~EventMonitorAura() override;
// EventMonitor:
gfx::Point GetLastMouseLocation() override;
protected:
// Removes the pre-target handler. Called by window monitors on window close.
void TearDown();
private:
raw_ptr<ui::EventObserver, DanglingUntriaged>
event_observer_; // Weak. Owned by our owner.
raw_ptr<ui::EventTarget, DanglingUntriaged> event_target_; // Weak.
};
} // namespace views
#endif // UI_VIEWS_EVENT_MONITOR_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor_aura.h | C++ | unknown | 1,244 |
// 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_EVENT_MONITOR_MAC_H_
#define UI_VIEWS_EVENT_MONITOR_MAC_H_
#include <memory>
#include <set>
#include "base/memory/weak_ptr.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/event_monitor.h"
namespace views {
class EventMonitorMac : public EventMonitor {
public:
EventMonitorMac(ui::EventObserver* event_observer,
gfx::NativeWindow target_window,
const std::set<ui::EventType>& types);
EventMonitorMac(const EventMonitorMac&) = delete;
EventMonitorMac& operator=(const EventMonitorMac&) = delete;
~EventMonitorMac() override;
// EventMonitor:
gfx::Point GetLastMouseLocation() override;
private:
const std::set<ui::EventType> types_;
struct ObjCStorage;
std::unique_ptr<ObjCStorage> objc_storage_;
base::WeakPtrFactory<EventMonitorMac> factory_{this};
};
} // namespace views
#endif // UI_VIEWS_EVENT_MONITOR_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor_mac.h | C++ | unknown | 1,060 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "ui/views/event_monitor_mac.h"
#import <Cocoa/Cocoa.h>
#include <memory>
#include "base/check.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/events/event_observer.h"
#include "ui/events/event_utils.h"
namespace views {
// static
std::unique_ptr<EventMonitor> EventMonitor::CreateApplicationMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow context,
const std::set<ui::EventType>& types) {
// |context| is not needed on Mac.
return std::make_unique<EventMonitorMac>(event_observer, nullptr, types);
}
// static
std::unique_ptr<EventMonitor> EventMonitor::CreateWindowMonitor(
ui::EventObserver* event_observer,
gfx::NativeWindow target_window,
const std::set<ui::EventType>& types) {
return std::make_unique<EventMonitorMac>(event_observer, target_window,
types);
}
struct EventMonitorMac::ObjCStorage {
id monitor_ = nil;
};
EventMonitorMac::EventMonitorMac(ui::EventObserver* event_observer,
gfx::NativeWindow target_native_window,
const std::set<ui::EventType>& types)
: types_(types), objc_storage_(std::make_unique<ObjCStorage>()) {
DCHECK(event_observer);
NSWindow* target_window = target_native_window.GetNativeNSWindow();
// Capture a WeakPtr. This allows the block to detect another event monitor
// for the same event deleting |this|.
base::WeakPtr<EventMonitorMac> weak_ptr = factory_.GetWeakPtr();
auto block = ^NSEvent*(NSEvent* event) {
if (!weak_ptr) {
return event;
}
if (!target_window || [event window] == target_window) {
std::unique_ptr<ui::Event> ui_event = ui::EventFromNative(event);
if (ui_event && types_.find(ui_event->type()) != types_.end()) {
event_observer->OnEvent(*ui_event);
}
}
return event;
};
objc_storage_->monitor_ =
[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskAny
handler:block];
}
EventMonitorMac::~EventMonitorMac() {
[NSEvent removeMonitor:objc_storage_->monitor_];
}
gfx::Point EventMonitorMac::GetLastMouseLocation() {
return display::Screen::GetScreen()->GetCursorScreenPoint();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor_mac.mm | Objective-C++ | unknown | 2,503 |
// 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/event_monitor.h"
#include <utility>
#include "base/memory/raw_ptr.h"
#include "ui/events/event_observer.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget_utils.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace views::test {
// A simple event observer that records the number of events.
class TestEventObserver : public ui::EventObserver {
public:
TestEventObserver() = default;
TestEventObserver(const TestEventObserver&) = delete;
TestEventObserver& operator=(const TestEventObserver&) = delete;
~TestEventObserver() override = default;
// ui::EventObserver:
void OnEvent(const ui::Event& event) override { ++observed_event_count_; }
size_t observed_event_count() const { return observed_event_count_; }
private:
size_t observed_event_count_ = 0;
};
class EventMonitorTest : public WidgetTest {
public:
EventMonitorTest() = default;
EventMonitorTest(const EventMonitorTest&) = delete;
EventMonitorTest& operator=(const EventMonitorTest&) = delete;
// testing::Test:
void SetUp() override {
WidgetTest::SetUp();
widget_ = CreateTopLevelNativeWidget();
widget_->SetSize(gfx::Size(100, 100));
widget_->Show();
generator_ = std::make_unique<ui::test::EventGenerator>(
GetContext(), widget_->GetNativeWindow());
generator_->set_target(ui::test::EventGenerator::Target::APPLICATION);
}
void TearDown() override {
widget_->CloseNow();
WidgetTest::TearDown();
}
protected:
raw_ptr<Widget> widget_ = nullptr;
std::unique_ptr<ui::test::EventGenerator> generator_;
TestEventObserver observer_;
};
TEST_F(EventMonitorTest, ShouldReceiveAppEventsWhileInstalled) {
std::unique_ptr<EventMonitor> monitor(EventMonitor::CreateApplicationMonitor(
&observer_, widget_->GetNativeWindow(),
{ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_RELEASED}));
generator_->ClickLeftButton();
EXPECT_EQ(2u, observer_.observed_event_count());
monitor.reset();
generator_->ClickLeftButton();
EXPECT_EQ(2u, observer_.observed_event_count());
}
TEST_F(EventMonitorTest, ShouldReceiveWindowEventsWhileInstalled) {
std::unique_ptr<EventMonitor> monitor(EventMonitor::CreateWindowMonitor(
&observer_, widget_->GetNativeWindow(),
{ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_RELEASED}));
generator_->ClickLeftButton();
EXPECT_EQ(2u, observer_.observed_event_count());
monitor.reset();
generator_->ClickLeftButton();
EXPECT_EQ(2u, observer_.observed_event_count());
}
TEST_F(EventMonitorTest, ShouldNotReceiveEventsFromOtherWindow) {
Widget* widget2 = CreateTopLevelNativeWidget();
std::unique_ptr<EventMonitor> monitor(EventMonitor::CreateWindowMonitor(
&observer_, widget2->GetNativeWindow(),
{ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_RELEASED}));
generator_->ClickLeftButton();
EXPECT_EQ(0u, observer_.observed_event_count());
monitor.reset();
widget2->CloseNow();
}
TEST_F(EventMonitorTest, ShouldOnlyReceiveRequestedEventTypes) {
// This event monitor only listens to mouse press, not release.
std::unique_ptr<EventMonitor> monitor(EventMonitor::CreateWindowMonitor(
&observer_, widget_->GetNativeWindow(), {ui::ET_MOUSE_PRESSED}));
generator_->ClickLeftButton();
EXPECT_EQ(1u, observer_.observed_event_count());
monitor.reset();
}
TEST_F(EventMonitorTest, WindowMonitorTornDownOnWindowClose) {
Widget* widget2 = CreateTopLevelNativeWidget();
widget2->Show();
std::unique_ptr<EventMonitor> monitor(EventMonitor::CreateWindowMonitor(
&observer_, widget2->GetNativeWindow(), {ui::ET_MOUSE_PRESSED}));
// Closing the widget before destroying the monitor should not crash.
widget2->CloseNow();
monitor.reset();
}
namespace {
class DeleteOtherOnEventObserver : public ui::EventObserver {
public:
explicit DeleteOtherOnEventObserver(gfx::NativeWindow context) {
monitor_ = EventMonitor::CreateApplicationMonitor(
this, context, {ui::ET_MOUSE_PRESSED, ui::ET_MOUSE_RELEASED});
}
DeleteOtherOnEventObserver(const DeleteOtherOnEventObserver&) = delete;
DeleteOtherOnEventObserver& operator=(const DeleteOtherOnEventObserver&) =
delete;
bool DidDelete() const { return !observer_to_delete_; }
void set_monitor_to_delete(
std::unique_ptr<DeleteOtherOnEventObserver> observer_to_delete) {
observer_to_delete_ = std::move(observer_to_delete);
}
// ui::EventObserver:
void OnEvent(const ui::Event& event) override {
observer_to_delete_ = nullptr;
}
private:
std::unique_ptr<EventMonitor> monitor_;
std::unique_ptr<DeleteOtherOnEventObserver> observer_to_delete_;
};
} // namespace
// Ensure correct behavior when an event monitor is removed while iterating
// over the OS-controlled observer list.
TEST_F(EventMonitorTest, TwoMonitors) {
gfx::NativeWindow window = widget_->GetNativeWindow();
auto deleter = std::make_unique<DeleteOtherOnEventObserver>(window);
auto deletee = std::make_unique<DeleteOtherOnEventObserver>(window);
deleter->set_monitor_to_delete(std::move(deletee));
EXPECT_FALSE(deleter->DidDelete());
generator_->PressLeftButton();
EXPECT_TRUE(deleter->DidDelete());
// Now try setting up observers in the alternate order.
deletee = std::make_unique<DeleteOtherOnEventObserver>(window);
deleter = std::make_unique<DeleteOtherOnEventObserver>(window);
deleter->set_monitor_to_delete(std::move(deletee));
EXPECT_FALSE(deleter->DidDelete());
generator_->ReleaseLeftButton();
EXPECT_TRUE(deleter->DidDelete());
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/event_monitor_unittest.cc | C++ | unknown | 5,746 |
include_rules = [
"+components/viz/common/features.h",
"+components/viz/host",
"+components/viz/service", # In-process viz service.
"+content/public",
"+content/shell",
"+mojo/core/embedder/embedder.h", # TestGpuServiceHolder needs Mojo.
"+sandbox",
"+ui/gl/gl_utils.h", # Disable Direct Composition Workaround.
"+ui/gl/init/gl_factory.h", # To initialize GL bindings.
"+ui/message_center", # For the notification example.
"+ui/snapshot", # Enable Skia Gold testing
"+ui/views_content_client",
]
specific_include_rules = {
"examples_main_proc.cc": [
"+ui/wm/core/wm_state.h",
],
"examples_views_delegate_chromeos.cc": [
"+ui/wm/test/wm_test_helper.h",
],
}
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/DEPS | Python | unknown | 703 |
// 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/examples/animated_image_view_example.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "cc/paint/skottie_wrapper.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/lottie/animation.h"
#include "ui/views/border.h"
#include "ui/views/controls/animated_image_view.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
namespace views::examples {
namespace {
// This class can load a skottie(and lottie) animation file from disk and play
// it in a view as AnimatedImageView.
// See https://skia.org/user/modules/skottie for more info on skottie.
class AnimationGallery : public BoxLayoutView, public TextfieldController {
public:
AnimationGallery() {
View* image_view_container = nullptr;
BoxLayoutView* file_container = nullptr;
Builder<BoxLayoutView>(this)
.SetOrientation(BoxLayout::Orientation::kVertical)
.SetInsideBorderInsets(gfx::Insets(10))
.SetBetweenChildSpacing(10)
.AddChildren(
Builder<Textfield>()
.CopyAddressTo(&size_input_)
.SetPlaceholderText(u"Size in dip (Empty for default)")
.SetController(this),
Builder<View>()
.CopyAddressTo(&image_view_container)
.SetUseDefaultFillLayout(true)
.AddChild(
Builder<AnimatedImageView>()
.CopyAddressTo(&animated_image_view_)
.SetBorder(CreateThemedSolidBorder(
1, ExamplesColorIds::
kColorAnimatedImageViewExampleBorder))),
Builder<BoxLayoutView>()
.CopyAddressTo(&file_container)
.SetInsideBorderInsets(gfx::Insets(10))
.SetBetweenChildSpacing(10)
.AddChildren(
Builder<Textfield>()
.CopyAddressTo(&file_chooser_)
.SetPlaceholderText(u"Enter path to lottie JSON file"),
Builder<MdTextButton>()
.SetCallback(base::BindRepeating(
&AnimationGallery::ButtonPressed,
base::Unretained(this)))
.SetText(u"Render")))
.BuildChildren();
SetFlexForView(image_view_container, 1);
file_container->SetFlexForView(file_chooser_, 1);
}
AnimationGallery(const AnimationGallery&) = delete;
AnimationGallery& operator=(const AnimationGallery&) = delete;
~AnimationGallery() override = default;
// TextfieldController:
void ContentsChanged(Textfield* sender,
const std::u16string& new_contents) override {
if (sender == size_input_) {
if (!base::StringToInt(new_contents, &size_) && (size_ > 0)) {
size_ = 0;
size_input_->SetText(std::u16string());
}
Update();
}
}
void ButtonPressed(const ui::Event& event) {
std::string json;
base::ScopedAllowBlockingForTesting allow_blocking;
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
base::FilePath path(base::UTF16ToUTF8(file_chooser_->GetText()));
#else
base::FilePath path(base::UTF16ToWide(file_chooser_->GetText()));
#endif // BUILDFLAG(IS_POSIX)
if (base::ReadFileToString(path, &json)) {
auto skottie = cc::SkottieWrapper::CreateSerializable(
std::vector<uint8_t>(json.begin(), json.end()));
animated_image_view_->SetAnimatedImage(
std::make_unique<lottie::Animation>(skottie));
animated_image_view_->Play();
Update();
}
}
private:
void Update() {
if (size_ > 24)
animated_image_view_->SetImageSize(gfx::Size(size_, size_));
else
animated_image_view_->ResetImageSize();
InvalidateLayout();
}
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION AnimatedImageView* animated_image_view_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* size_input_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* file_chooser_ = nullptr;
int size_ = 0;
};
} // namespace
AnimatedImageViewExample::AnimatedImageViewExample()
: ExampleBase("Animated Image View") {}
AnimatedImageViewExample::~AnimatedImageViewExample() = default;
void AnimatedImageViewExample::CreateExampleView(View* container) {
container->SetUseDefaultFillLayout(true);
container->AddChildView(std::make_unique<AnimationGallery>());
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/animated_image_view_example.cc | C++ | unknown | 5,535 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_ANIMATED_IMAGE_VIEW_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_ANIMATED_IMAGE_VIEW_EXAMPLE_H_
#include "ui/views/examples/example_base.h"
namespace views::examples {
class VIEWS_EXAMPLES_EXPORT AnimatedImageViewExample : public ExampleBase {
public:
AnimatedImageViewExample();
AnimatedImageViewExample(const AnimatedImageViewExample&) = delete;
AnimatedImageViewExample& operator=(const AnimatedImageViewExample&) = delete;
~AnimatedImageViewExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_ANIMATED_IMAGE_VIEW_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/animated_image_view_example.h | C++ | unknown | 809 |
// 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/examples/animation_example.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/font.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/bounds_animator.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/layout_manager_base.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/style/typography.h"
#include "ui/views/style/typography_provider.h"
#include "ui/views/view.h"
namespace views::examples {
AnimationExample::AnimationExample() : ExampleBase("Animation") {}
AnimationExample::~AnimationExample() = default;
class AnimatingSquare : public View {
public:
explicit AnimatingSquare(size_t index);
AnimatingSquare(const AnimatingSquare&) = delete;
AnimatingSquare& operator=(const AnimatingSquare&) = delete;
~AnimatingSquare() override = default;
protected:
// views::View override
void OnPaint(gfx::Canvas* canvas) override;
private:
int index_;
int paint_counter_ = 0;
gfx::FontList font_list_ =
LayoutProvider::Get()->GetTypographyProvider().GetFont(
style::CONTEXT_DIALOG_TITLE,
style::STYLE_PRIMARY);
};
AnimatingSquare::AnimatingSquare(size_t index) : index_(index) {
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
layer()->SetFillsBoundsCompletely(false);
}
void AnimatingSquare::OnPaint(gfx::Canvas* canvas) {
View::OnPaint(canvas);
const SkColor color = SkColorSetRGB((5 - index_) * 51, 0, index_ * 51);
// TODO(crbug/1308932): Remove this FromColor and make all SkColor4f.
const SkColor4f colors[2] = {
SkColor4f::FromColor(color),
SkColor4f::FromColor(color_utils::HSLShift(color, {-1.0, -1.0, 0.75}))};
cc::PaintFlags flags;
gfx::Rect local_bounds = gfx::Rect(layer()->size());
const float dsf = canvas->UndoDeviceScaleFactor();
gfx::RectF local_bounds_f = gfx::RectF(local_bounds);
local_bounds_f.Scale(dsf);
SkRect bounds = gfx::RectToSkRect(gfx::ToEnclosingRect(local_bounds_f));
flags.setAntiAlias(true);
flags.setShader(cc::PaintShader::MakeRadialGradient(
SkPoint::Make(bounds.centerX(), bounds.centerY()), bounds.width() / 2,
colors, nullptr, 2, SkTileMode::kClamp));
canvas->DrawRect(gfx::ToEnclosingRect(local_bounds_f), flags);
int width = 0;
int height = 0;
std::u16string counter = base::NumberToString16(++paint_counter_);
canvas->SizeStringInt(counter, font_list_, &width, &height, 0,
gfx::Canvas::TEXT_ALIGN_CENTER);
local_bounds.ClampToCenteredSize(gfx::Size(width, height));
canvas->DrawStringRectWithFlags(
counter, font_list_,
GetColorProvider()->GetColor(
ExamplesColorIds::kColorAnimationExampleForeground),
local_bounds, gfx::Canvas::TEXT_ALIGN_CENTER);
}
class SquaresLayoutManager : public LayoutManagerBase {
public:
SquaresLayoutManager() = default;
~SquaresLayoutManager() override = default;
protected:
// LayoutManagerBase:
ProposedLayout CalculateProposedLayout(
const SizeBounds& size_bounds) const override;
void LayoutImpl() override;
void OnInstalled(View* host) override;
private:
static constexpr int kPadding = 25;
static constexpr gfx::Size kSize = gfx::Size(100, 100);
std::unique_ptr<BoundsAnimator> bounds_animator_;
};
// static
constexpr gfx::Size SquaresLayoutManager::kSize;
ProposedLayout SquaresLayoutManager::CalculateProposedLayout(
const SizeBounds& size_bounds) const {
ProposedLayout layout;
const auto& children = host_view()->children();
const int item_width = kSize.width() + kPadding;
const int item_height = kSize.height() + kPadding;
const int max_width = kPadding + (children.size() * item_width);
const int bounds_width =
std::max(kPadding + item_width, size_bounds.width().min_of(max_width));
const int views_per_row = (bounds_width - kPadding) / item_width;
for (size_t i = 0; i < children.size(); ++i) {
const size_t row = i / views_per_row;
const size_t column = i % views_per_row;
const gfx::Point origin(kPadding + column * item_width,
kPadding + row * item_height);
layout.child_layouts.push_back(
{children[i], true, gfx::Rect(origin, kSize), SizeBounds(kSize)});
}
const size_t num_rows = (children.size() + views_per_row - 1) / views_per_row;
const int max_height = kPadding + (num_rows * item_height);
const int bounds_height =
std::max(kPadding + item_height, size_bounds.height().min_of(max_height));
layout.host_size = {bounds_width, bounds_height};
return layout;
}
void SquaresLayoutManager::LayoutImpl() {
ProposedLayout proposed_layout = GetProposedLayout(host_view()->size());
for (auto child_layout : proposed_layout.child_layouts) {
bounds_animator_->AnimateViewTo(child_layout.child_view,
child_layout.bounds);
}
}
void SquaresLayoutManager::OnInstalled(View* host) {
bounds_animator_ = std::make_unique<BoundsAnimator>(host, true);
bounds_animator_->SetAnimationDuration(base::Seconds(1));
}
void AnimationExample::CreateExampleView(View* container) {
container->SetLayoutManager(std::make_unique<BoxLayout>(
BoxLayout::Orientation::kVertical, gfx::Insets(), 10));
View* squares_container = container->AddChildView(std::make_unique<View>());
squares_container->SetBackground(CreateThemedSolidBackground(
ExamplesColorIds::kColorAnimationExampleBackground));
squares_container->SetPaintToLayer();
squares_container->layer()->SetMasksToBounds(true);
squares_container->layer()->SetFillsBoundsOpaquely(true);
squares_container->SetLayoutManager(std::make_unique<SquaresLayoutManager>());
for (size_t i = 0; i < 5; ++i)
squares_container->AddChildView(std::make_unique<AnimatingSquare>(i));
{
gfx::RoundedCornersF rounded_corners(12.0f, 12.0f, 12.0f, 12.0f);
AnimationBuilder b;
abort_handle_ = b.GetAbortHandle();
for (auto* view : squares_container->children()) {
b.Once()
.SetDuration(base::Seconds(10))
.SetRoundedCorners(view, rounded_corners);
b.Repeatedly()
.SetDuration(base::Seconds(2))
.SetOpacity(view, 0.4f, gfx::Tween::LINEAR_OUT_SLOW_IN)
.Then()
.SetDuration(base::Seconds(2))
.SetOpacity(view, 0.9f, gfx::Tween::EASE_OUT_3);
}
}
container->AddChildView(std::make_unique<MdTextButton>(
base::BindRepeating(
[](std::unique_ptr<AnimationAbortHandle>* abort_handle) {
abort_handle->reset();
},
&abort_handle_),
l10n_util::GetStringUTF16(IDS_ABORT_ANIMATION_BUTTON)));
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/animation_example.cc | C++ | unknown | 7,623 |
// 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_EXAMPLES_ANIMATION_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_ANIMATION_EXAMPLE_H_
#include <memory>
#include "ui/views/animation/animation_abort_handle.h"
#include "ui/views/examples/example_base.h"
namespace views::examples {
class VIEWS_EXAMPLES_EXPORT AnimationExample : public ExampleBase {
public:
AnimationExample();
AnimationExample(const AnimationExample&) = delete;
AnimationExample& operator=(const AnimationExample&) = delete;
~AnimationExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
std::unique_ptr<AnimationAbortHandle> abort_handle_;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_ANIMATION_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/animation_example.h | C++ | unknown | 861 |
// 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/examples/ax_example.h"
#include <memory>
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view_class_properties.h"
namespace views::examples {
AxExample::AxExample() : ExampleBase("Accessibility Features") {}
AxExample::~AxExample() = default;
void AxExample::CreateExampleView(View* container) {
container->SetBackground(CreateThemedSolidBackground(
ExamplesColorIds::kColorAccessibilityExampleBackground));
FlexLayout* const layout =
container->SetLayoutManager(std::make_unique<FlexLayout>());
layout->SetCollapseMargins(true);
layout->SetOrientation(LayoutOrientation::kVertical);
layout->SetDefault(kMarginsKey, gfx::Insets(10));
layout->SetMainAxisAlignment(LayoutAlignment::kStart);
layout->SetCrossAxisAlignment(LayoutAlignment::kStart);
auto announce_text = [](AxExample* example) {
example->announce_button_->GetViewAccessibility().AnnounceText(
u"Button pressed.");
};
announce_button_ = container->AddChildView(std::make_unique<MdTextButton>(
base::BindRepeating(announce_text, base::Unretained(this)),
u"AnnounceText"));
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/ax_example.cc | C++ | unknown | 1,497 |
// 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_EXAMPLES_AX_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_AX_EXAMPLE_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/examples/example_base.h"
namespace views {
class Button;
namespace examples {
// ButtonExample simply counts the number of clicks.
class VIEWS_EXAMPLES_EXPORT AxExample : public ExampleBase {
public:
AxExample();
AxExample(const AxExample&) = delete;
AxExample& operator=(const AxExample&) = delete;
~AxExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
raw_ptr<Button> announce_button_ = nullptr;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_AX_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/ax_example.h | C++ | unknown | 838 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/examples/badge_example.h"
#include <memory>
#include <set>
#include <utility>
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/badge.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
using l10n_util::GetStringUTF16;
using l10n_util::GetStringUTF8;
namespace views::examples {
BadgeExample::BadgeExample()
: ExampleBase(GetStringUTF8(IDS_BADGE_SELECT_LABEL).c_str()) {}
BadgeExample::~BadgeExample() = default;
void BadgeExample::CreateExampleView(View* container) {
container->SetUseDefaultFillLayout(true);
auto show_menu = [](BadgeExample* example) {
// Create a menu item view.
auto* menu_item_view = new views::MenuItemView(&example->menu_delegate_);
// Add items to the context menu.
menu_item_view->AppendMenuItem(1, GetStringUTF16(IDS_BADGE_MENU_ITEM_1));
menu_item_view->AppendMenuItem(2, GetStringUTF16(IDS_BADGE_MENU_ITEM_2));
// Enable the "New" Badge.
menu_item_view->AppendMenuItem(3, GetStringUTF16(IDS_BADGE_MENU_ITEM_3))
->set_is_new(true);
example->menu_runner_ = std::make_unique<MenuRunner>(menu_item_view, 0);
View* menu_button = example->menu_button_;
gfx::Point screen_loc;
views::View::ConvertPointToScreen(menu_button, &screen_loc);
gfx::Rect bounds(screen_loc, menu_button->size());
example->menu_runner_->RunMenuAt(menu_button->GetWidget(), nullptr, bounds,
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE);
};
auto view =
Builder<BoxLayoutView>()
.SetOrientation(BoxLayout::Orientation::kVertical)
.SetInsideBorderInsets(gfx::Insets(10))
.SetBetweenChildSpacing(10)
.SetCrossAxisAlignment(BoxLayout::CrossAxisAlignment::kStart)
.AddChildren(
Builder<BoxLayoutView>().SetBetweenChildSpacing(10).AddChildren(
Builder<Link>().SetText(GetStringUTF16(IDS_BADGE_LINK_TEXT)),
Builder<Badge>().SetText(
GetStringUTF16(IDS_BADGE_BADGE_TEXT))),
Builder<MdTextButton>()
.CopyAddressTo(&menu_button_)
.SetText(GetStringUTF16(IDS_BADGE_MENU_BUTTON))
.SetCallback(
base::BindRepeating(show_menu, base::Unretained(this))))
.Build();
container->AddChildView(std::move(view));
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/badge_example.cc | C++ | unknown | 2,944 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_BADGE_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_BADGE_EXAMPLE_H_
#include <memory>
#include "ui/views/controls/menu/menu_delegate.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/examples/example_base.h"
namespace views::examples {
// BadgeExample demonstrates how to use the generic views::Badge and
// the New Badge in a MenuItemView.
class VIEWS_EXAMPLES_EXPORT BadgeExample : public ExampleBase {
public:
BadgeExample();
BadgeExample(const BadgeExample&) = delete;
BadgeExample& operator=(const BadgeExample&) = delete;
~BadgeExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
std::unique_ptr<MenuRunner> menu_runner_;
MenuDelegate menu_delegate_;
raw_ptr<View> menu_button_;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_BADGE_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/badge_example.h | C++ | unknown | 1,021 |
// 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/examples/box_layout_example.h"
#include <memory>
#include <string>
#include <utility>
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/models/combobox_model.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/examples/example_combobox_model.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
namespace views::examples {
BoxLayoutExample::BoxLayoutExample() : LayoutExampleBase("Box Layout") {}
BoxLayoutExample::~BoxLayoutExample() = default;
void BoxLayoutExample::ContentsChanged(Textfield* textfield,
const std::u16string& new_contents) {
if (textfield == between_child_spacing_) {
UpdateLayoutManager();
} else if (textfield == default_flex_) {
int default_flex;
base::StringToInt(default_flex_->GetText(), &default_flex);
layout_->SetDefaultFlex(default_flex);
} else if (textfield == min_cross_axis_size_) {
int min_cross_size;
base::StringToInt(min_cross_axis_size_->GetText(), &min_cross_size);
layout_->set_minimum_cross_axis_size(min_cross_size);
} else if (textfield == border_insets_.left ||
textfield == border_insets_.top ||
textfield == border_insets_.right ||
textfield == border_insets_.bottom) {
UpdateBorderInsets();
}
RefreshLayoutPanel(false);
}
void BoxLayoutExample::CreateAdditionalControls() {
constexpr const char* kOrientationValues[2] = {"Horizontal", "Vertical"};
orientation_ = CreateAndAddCombobox(
u"Orientation", kOrientationValues, std::size(kOrientationValues),
base::BindRepeating(&LayoutExampleBase::RefreshLayoutPanel,
base::Unretained(this), true));
constexpr const char* kMainAxisValues[3] = {"Start", "Center", "End"};
main_axis_alignment_ = CreateAndAddCombobox(
u"Main axis", kMainAxisValues, std::size(kMainAxisValues),
base::BindRepeating(&BoxLayoutExample::MainAxisAlignmentChanged,
base::Unretained(this)));
constexpr const char* kCrossAxisValues[4] = {"Stretch", "Start", "Center",
"End"};
cross_axis_alignment_ = CreateAndAddCombobox(
u"Cross axis", kCrossAxisValues, std::size(kCrossAxisValues),
base::BindRepeating(&BoxLayoutExample::CrossAxisAlignmentChanged,
base::Unretained(this)));
between_child_spacing_ = CreateAndAddTextfield(u"Child spacing");
default_flex_ = CreateAndAddTextfield(u"Default flex");
min_cross_axis_size_ = CreateAndAddTextfield(u"Min cross axis");
CreateMarginsTextFields(u"Insets", &border_insets_);
collapse_margins_ = CreateAndAddCheckbox(
u"Collapse margins",
base::BindRepeating(&LayoutExampleBase::RefreshLayoutPanel,
base::Unretained(this), true));
UpdateLayoutManager();
}
void BoxLayoutExample::UpdateLayoutManager() {
View* const panel = layout_panel();
int child_spacing;
base::StringToInt(between_child_spacing_->GetText(), &child_spacing);
layout_ = panel->SetLayoutManager(std::make_unique<BoxLayout>(
orientation_->GetSelectedIndex() == 0u
? BoxLayout::Orientation::kHorizontal
: BoxLayout::Orientation::kVertical,
gfx::Insets(), child_spacing, collapse_margins_->GetChecked()));
layout_->set_cross_axis_alignment(static_cast<BoxLayout::CrossAxisAlignment>(
cross_axis_alignment_->GetSelectedIndex().value()));
layout_->set_main_axis_alignment(static_cast<BoxLayout::MainAxisAlignment>(
main_axis_alignment_->GetSelectedIndex().value()));
int default_flex;
base::StringToInt(default_flex_->GetText(), &default_flex);
layout_->SetDefaultFlex(default_flex);
int min_cross_size;
base::StringToInt(min_cross_axis_size_->GetText(), &min_cross_size);
layout_->set_minimum_cross_axis_size(min_cross_size);
UpdateBorderInsets();
for (View* child : panel->children()) {
const int flex = static_cast<ChildPanel*>(child)->GetFlex();
if (flex < 0)
layout_->ClearFlexForView(child);
else
layout_->SetFlexForView(child, flex);
}
}
void BoxLayoutExample::UpdateBorderInsets() {
layout_->set_inside_border_insets(TextfieldsToInsets(border_insets_));
}
void BoxLayoutExample::MainAxisAlignmentChanged() {
layout_->set_main_axis_alignment(static_cast<BoxLayout::MainAxisAlignment>(
main_axis_alignment_->GetSelectedIndex().value()));
RefreshLayoutPanel(false);
}
void BoxLayoutExample::CrossAxisAlignmentChanged() {
layout_->set_cross_axis_alignment(static_cast<BoxLayout::CrossAxisAlignment>(
cross_axis_alignment_->GetSelectedIndex().value()));
RefreshLayoutPanel(false);
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/box_layout_example.cc | C++ | unknown | 5,315 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_BOX_LAYOUT_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_BOX_LAYOUT_EXAMPLE_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/examples/layout_example_base.h"
#include "ui/views/layout/box_layout.h"
namespace views {
class Checkbox;
class Combobox;
class Textfield;
namespace examples {
class VIEWS_EXAMPLES_EXPORT BoxLayoutExample : public LayoutExampleBase {
public:
BoxLayoutExample();
BoxLayoutExample(const BoxLayoutExample&) = delete;
BoxLayoutExample& operator=(const BoxLayoutExample&) = delete;
~BoxLayoutExample() override;
private:
// LayoutExampleBase:
void ContentsChanged(Textfield* sender,
const std::u16string& new_contents) override;
void CreateAdditionalControls() override;
void UpdateLayoutManager() override;
// Set the border insets on the current BoxLayout instance.
void UpdateBorderInsets();
void MainAxisAlignmentChanged();
void CrossAxisAlignmentChanged();
raw_ptr<BoxLayout> layout_ = nullptr;
raw_ptr<Combobox> orientation_ = nullptr;
raw_ptr<Combobox> main_axis_alignment_ = nullptr;
raw_ptr<Combobox> cross_axis_alignment_ = nullptr;
raw_ptr<Textfield> between_child_spacing_ = nullptr;
raw_ptr<Textfield> default_flex_ = nullptr;
raw_ptr<Textfield> min_cross_axis_size_ = nullptr;
InsetTextfields border_insets_;
raw_ptr<Checkbox> collapse_margins_ = nullptr;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_BOX_LAYOUT_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/box_layout_example.h | C++ | unknown | 1,731 |
// 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/examples/bubble_example.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
using base::ASCIIToUTF16;
namespace views::examples {
namespace {
ExamplesColorIds colors[] = {ExamplesColorIds::kColorBubbleExampleBackground1,
ExamplesColorIds::kColorBubbleExampleBackground2,
ExamplesColorIds::kColorBubbleExampleBackground3,
ExamplesColorIds::kColorBubbleExampleBackground4};
BubbleBorder::Arrow arrows[] = {
BubbleBorder::TOP_LEFT, BubbleBorder::TOP_CENTER,
BubbleBorder::TOP_RIGHT, BubbleBorder::RIGHT_TOP,
BubbleBorder::RIGHT_CENTER, BubbleBorder::RIGHT_BOTTOM,
BubbleBorder::BOTTOM_RIGHT, BubbleBorder::BOTTOM_CENTER,
BubbleBorder::BOTTOM_LEFT, BubbleBorder::LEFT_BOTTOM,
BubbleBorder::LEFT_CENTER, BubbleBorder::LEFT_TOP};
std::u16string GetArrowName(BubbleBorder::Arrow arrow) {
switch (arrow) {
case BubbleBorder::TOP_LEFT:
return u"TOP_LEFT";
case BubbleBorder::TOP_RIGHT:
return u"TOP_RIGHT";
case BubbleBorder::BOTTOM_LEFT:
return u"BOTTOM_LEFT";
case BubbleBorder::BOTTOM_RIGHT:
return u"BOTTOM_RIGHT";
case BubbleBorder::LEFT_TOP:
return u"LEFT_TOP";
case BubbleBorder::RIGHT_TOP:
return u"RIGHT_TOP";
case BubbleBorder::LEFT_BOTTOM:
return u"LEFT_BOTTOM";
case BubbleBorder::RIGHT_BOTTOM:
return u"RIGHT_BOTTOM";
case BubbleBorder::TOP_CENTER:
return u"TOP_CENTER";
case BubbleBorder::BOTTOM_CENTER:
return u"BOTTOM_CENTER";
case BubbleBorder::LEFT_CENTER:
return u"LEFT_CENTER";
case BubbleBorder::RIGHT_CENTER:
return u"RIGHT_CENTER";
case BubbleBorder::NONE:
return u"NONE";
case BubbleBorder::FLOAT:
return u"FLOAT";
}
return u"INVALID";
}
class ExampleBubble : public BubbleDialogDelegateView {
public:
ExampleBubble(View* anchor, BubbleBorder::Arrow arrow)
: BubbleDialogDelegateView(anchor, arrow) {
DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE);
}
ExampleBubble(const ExampleBubble&) = delete;
ExampleBubble& operator=(const ExampleBubble&) = delete;
protected:
void Init() override {
SetLayoutManager(std::make_unique<BoxLayout>(
BoxLayout::Orientation::kVertical, gfx::Insets(50)));
AddChildView(std::make_unique<Label>(GetArrowName(arrow())));
}
};
} // namespace
BubbleExample::BubbleExample() : ExampleBase("Bubble") {}
BubbleExample::~BubbleExample() = default;
void BubbleExample::CreateExampleView(View* container) {
container->SetLayoutManager(std::make_unique<BoxLayout>(
BoxLayout::Orientation::kHorizontal, gfx::Insets(), 10));
standard_shadow_ = container->AddChildView(std::make_unique<LabelButton>(
base::BindRepeating(&BubbleExample::ShowBubble, base::Unretained(this),
&standard_shadow_, BubbleBorder::STANDARD_SHADOW,
false),
u"Standard Shadow"));
no_shadow_ = container->AddChildView(std::make_unique<LabelButton>(
base::BindRepeating(&BubbleExample::ShowBubble, base::Unretained(this),
&no_shadow_, BubbleBorder::NO_SHADOW, false),
u"No Shadow"));
persistent_ = container->AddChildView(std::make_unique<LabelButton>(
base::BindRepeating(&BubbleExample::ShowBubble, base::Unretained(this),
&persistent_, BubbleBorder::NO_SHADOW, true),
u"Persistent"));
}
void BubbleExample::ShowBubble(Button** button,
BubbleBorder::Shadow shadow,
bool persistent,
const ui::Event& event) {
static int arrow_index = 0, color_index = 0;
static const int count = std::size(arrows);
arrow_index = (arrow_index + count + (event.IsShiftDown() ? -1 : 1)) % count;
BubbleBorder::Arrow arrow = arrows[arrow_index];
if (event.IsControlDown())
arrow = BubbleBorder::NONE;
else if (event.IsAltDown())
arrow = BubbleBorder::FLOAT;
auto* provider = (*button)->GetColorProvider();
// |bubble| will be destroyed by its widget when the widget is destroyed.
auto bubble = std::make_unique<ExampleBubble>(*button, arrow);
bubble->set_color(
provider->GetColor(colors[(color_index++) % std::size(colors)]));
bubble->set_shadow(shadow);
if (persistent)
bubble->set_close_on_deactivate(false);
BubbleDialogDelegateView::CreateBubble(std::move(bubble))->Show();
LogStatus(
"Click with optional modifiers: [Ctrl] for set_arrow(NONE), "
"[Alt] for set_arrow(FLOAT), or [Shift] to reverse the arrow iteration.");
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/bubble_example.cc | C++ | unknown | 5,233 |
// 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_EXAMPLES_BUBBLE_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_BUBBLE_EXAMPLE_H_
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/events/event.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/examples/example_base.h"
#include "ui/views/examples/views_examples_export.h"
namespace views {
class Button;
namespace examples {
// A Bubble example.
class VIEWS_EXAMPLES_EXPORT BubbleExample : public ExampleBase {
public:
BubbleExample();
BubbleExample(const BubbleExample&) = delete;
BubbleExample& operator=(const BubbleExample&) = delete;
~BubbleExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
void ShowBubble(Button** button,
BubbleBorder::Shadow shadow,
bool persistent,
const ui::Event& event);
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Button* standard_shadow_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Button* no_shadow_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Button* persistent_;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_BUBBLE_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/bubble_example.h | C++ | unknown | 1,505 |
// 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/examples/button_example.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/gfx/skia_paint_util.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/resources/grit/views_resources.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/vector_icons.h"
#include "ui/views/view.h"
#include "ui/views/view_utils.h"
using base::ASCIIToUTF16;
namespace {
const char16_t kLabelButton[] = u"Label Button";
const char16_t kLongText[] =
u"Start of Really Really Really Really Really Really "
u"Really Really Really Really Really Really Really "
u"Really Really Really Really Really Long Button Text";
} // namespace
namespace views::examples {
// Creates a rounded rect with a border plus shadow. This is used by FabButton
// to draw the button background.
class SolidRoundRectPainterWithShadow : public Painter {
public:
SolidRoundRectPainterWithShadow(SkColor bg_color,
SkColor stroke_color,
float radius,
const gfx::Insets& insets,
SkBlendMode blend_mode,
bool antialias,
bool has_shadow)
: bg_color_(bg_color),
stroke_color_(stroke_color),
radius_(radius),
insets_(insets),
blend_mode_(blend_mode),
antialias_(antialias),
has_shadow_(has_shadow) {}
SolidRoundRectPainterWithShadow(const SolidRoundRectPainterWithShadow&) =
delete;
SolidRoundRectPainterWithShadow& operator=(
const SolidRoundRectPainterWithShadow&) = delete;
~SolidRoundRectPainterWithShadow() override = default;
// Painter:
gfx::Size GetMinimumSize() const override { return gfx::Size(); }
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override {
gfx::ScopedCanvas scoped_canvas(canvas);
const float scale = canvas->UndoDeviceScaleFactor();
float scaled_radius = radius_ * scale;
gfx::Rect inset_rect(size);
inset_rect.Inset(insets_);
cc::PaintFlags flags;
// Draw a shadow effect by shrinking the rect and then inserting a
// shadow looper.
if (has_shadow_) {
gfx::Rect shadow_bounds = inset_rect;
gfx::ShadowValues shadow;
constexpr int kOffset = 2;
constexpr int kBlur = 4;
shadow.emplace_back(gfx::Vector2d(kOffset, kOffset), kBlur,
SkColorSetA(SK_ColorBLACK, 0x24));
shadow_bounds.Inset(-gfx::ShadowValue::GetMargin(shadow));
inset_rect.Inset(-gfx::ShadowValue::GetMargin(shadow));
flags.setAntiAlias(true);
flags.setLooper(gfx::CreateShadowDrawLooper(shadow));
canvas->DrawRoundRect(shadow_bounds, scaled_radius, flags);
}
gfx::RectF fill_rect(gfx::ScaleToEnclosingRect(inset_rect, scale));
gfx::RectF stroke_rect = fill_rect;
flags.setBlendMode(blend_mode_);
flags.setAntiAlias(antialias_);
flags.setStyle(cc::PaintFlags::kFill_Style);
flags.setColor(bg_color_);
canvas->DrawRoundRect(fill_rect, scaled_radius, flags);
if (stroke_color_ != SK_ColorTRANSPARENT && !has_shadow_) {
constexpr float kStrokeWidth = 1.0f;
stroke_rect.Inset(gfx::InsetsF(kStrokeWidth / 2));
scaled_radius -= kStrokeWidth / 2;
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(kStrokeWidth);
flags.setColor(stroke_color_);
canvas->DrawRoundRect(stroke_rect, scaled_radius, flags);
}
}
private:
const SkColor bg_color_;
const SkColor stroke_color_;
const float radius_;
const gfx::Insets insets_;
const SkBlendMode blend_mode_;
const bool antialias_;
const bool has_shadow_;
};
// Floating Action Button (Fab) is a button that has a shadow around the button
// to simulate a floating effect. This class is not used officially in the Views
// library. This is a prototype of a potential way to implement such an effect
// by overriding the hover effect to draw a new background with a shadow.
class FabButton : public views::MdTextButton {
public:
using MdTextButton::MdTextButton;
FabButton(const FabButton&) = delete;
FabButton& operator=(const FabButton&) = delete;
~FabButton() override = default;
void UpdateBackgroundColor() override {
SkColor bg_color = GetColorProvider()->GetColor(
ExamplesColorIds::kColorButtonBackgroundFab);
SetBackground(CreateBackgroundFromPainter(
std::make_unique<SolidRoundRectPainterWithShadow>(
bg_color, SK_ColorTRANSPARENT, GetCornerRadiusValue(),
gfx::Insets(), SkBlendMode::kSrcOver, true, use_shadow_)));
}
void OnHoverChanged() {
use_shadow_ = !use_shadow_;
UpdateBackgroundColor();
}
void OnThemeChanged() override {
MdTextButton::OnThemeChanged();
UpdateBackgroundColor();
}
private:
base::CallbackListSubscription highlighted_changed_subscription_ =
InkDrop::Get(this)->AddHighlightedChangedCallback(
base::BindRepeating([](FabButton* host) { host->OnHoverChanged(); },
base::Unretained(this)));
bool use_shadow_ = false;
};
class IconAndTextButton : public views::MdTextButton {
public:
IconAndTextButton(PressedCallback callback,
const std::u16string& text,
const gfx::VectorIcon& icon)
: MdTextButton(callback, text), icon_(icon) {}
IconAndTextButton(const IconAndTextButton&) = delete;
IconAndTextButton& operator=(const IconAndTextButton&) = delete;
~IconAndTextButton() override = default;
void OnThemeChanged() override {
views::MdTextButton::OnThemeChanged();
// Use the text color for the associated vector image.
SetImageModel(
views::Button::ButtonState::STATE_NORMAL,
ui::ImageModel::FromVectorIcon(*icon_, label()->GetEnabledColor()));
}
private:
const raw_ref<const gfx::VectorIcon> icon_;
};
ButtonExample::ButtonExample() : ExampleBase("Button") {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_ = rb.GetImageNamed(IDR_CLOSE_H).ToImageSkia();
}
ButtonExample::~ButtonExample() = default;
void ButtonExample::CreateExampleView(View* container) {
container->SetUseDefaultFillLayout(true);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
auto view = Builder<BoxLayoutView>()
.SetOrientation(BoxLayout::Orientation::kVertical)
.SetInsideBorderInsets(gfx::Insets(10))
.SetBetweenChildSpacing(10)
.SetCrossAxisAlignment(BoxLayout::CrossAxisAlignment::kCenter)
.AddChildren(Builder<LabelButton>()
.CopyAddressTo(&label_button_)
.SetText(kLabelButton)
.SetRequestFocusOnPress(true)
.SetCallback(base::BindRepeating(
&ButtonExample::LabelButtonPressed,
base::Unretained(this), label_button_)),
Builder<MdTextButton>()
.CopyAddressTo(&md_button_)
.SetText(u"Material Design"),
Builder<MdTextButton>()
.CopyAddressTo(&md_disabled_button_)
.SetText(u"Material Design Disabled Button")
.SetState(Button::STATE_DISABLED),
Builder<MdTextButton>()
.CopyAddressTo(&md_default_button_)
.SetText(u"Default")
.SetIsDefault(true),
Builder<MdTextButton>()
.CopyAddressTo(&md_tonal_button_)
.SetStyle(MdTextButton::Style::kTonal)
.SetText(u"Tonal"),
Builder<MdTextButton>()
.CopyAddressTo(&md_text_button_)
.SetStyle(MdTextButton::Style::kText)
.SetText(u"Material Text"),
Builder<ImageButton>()
.CopyAddressTo(&image_button_)
.SetAccessibleName(l10n_util::GetStringUTF16(
IDS_BUTTON_IMAGE_BUTTON_AX_LABEL))
.SetRequestFocusOnPress(true)
.SetCallback(base::BindRepeating(
&ButtonExample::ImageButtonPressed,
base::Unretained(this))))
.Build();
view->AddChildView(std::make_unique<IconAndTextButton>(
base::BindRepeating(&ButtonExample::ImageButtonPressed,
base::Unretained(this)),
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_CHOOSER_BUTTON),
views::kInfoIcon));
view->AddChildView(std::make_unique<FabButton>(
base::BindRepeating(&ButtonExample::ImageButtonPressed,
base::Unretained(this)),
u"Fab Prototype"));
view->AddChildView(ImageButton::CreateIconButton(
base::BindRepeating(&ButtonExample::ImageButtonPressed,
base::Unretained(this)),
views::kLaunchIcon, u"Icon button"));
image_button_->SetImage(ImageButton::STATE_NORMAL,
rb.GetImageNamed(IDR_CLOSE).ToImageSkia());
image_button_->SetImage(ImageButton::STATE_HOVERED,
rb.GetImageNamed(IDR_CLOSE_H).ToImageSkia());
image_button_->SetImage(ImageButton::STATE_PRESSED,
rb.GetImageNamed(IDR_CLOSE_P).ToImageSkia());
container->AddChildView(std::move(view));
}
void ButtonExample::LabelButtonPressed(LabelButton* label_button,
const ui::Event& event) {
PrintStatus("Label Button Pressed! count: %d", ++count_);
if (event.IsControlDown()) {
if (event.IsShiftDown()) {
label_button->SetText(
label_button->GetText().empty()
? kLongText
: label_button->GetText().length() > 50 ? kLabelButton : u"");
} else if (event.IsAltDown()) {
label_button->SetImageModel(
Button::STATE_NORMAL,
label_button->GetImage(Button::STATE_NORMAL).isNull()
? ui::ImageModel::FromImageSkia(*icon_)
: ui::ImageModel());
} else {
static int alignment = 0;
label_button->SetHorizontalAlignment(
static_cast<gfx::HorizontalAlignment>(++alignment % 3));
}
} else if (event.IsShiftDown()) {
if (event.IsAltDown()) {
// Toggle focusability.
label_button->IsAccessibilityFocusable()
? label_button->SetFocusBehavior(View::FocusBehavior::NEVER)
: label_button->SetFocusBehavior(
PlatformStyle::kDefaultFocusBehavior);
}
} else if (event.IsAltDown()) {
label_button->SetIsDefault(!label_button->GetIsDefault());
}
example_view()->GetLayoutManager()->Layout(example_view());
PrintViewHierarchy(example_view());
}
void ButtonExample::ImageButtonPressed() {
PrintStatus("Image Button Pressed! count: %d", ++count_);
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/button_example.cc | C++ | unknown | 12,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.
#ifndef UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/views/examples/example_base.h"
namespace gfx {
class ImageSkia;
} // namespace gfx
namespace ui {
class Event;
} // namespace ui
namespace views {
class ImageButton;
class LabelButton;
class MdTextButton;
namespace examples {
// ButtonExample simply counts the number of clicks.
class VIEWS_EXAMPLES_EXPORT ButtonExample : public ExampleBase {
public:
ButtonExample();
ButtonExample(const ButtonExample&) = delete;
ButtonExample& operator=(const ButtonExample&) = delete;
~ButtonExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
void LabelButtonPressed(LabelButton* label_button, const ui::Event& event);
void ImageButtonPressed();
// Example buttons.
// These fields are not a raw_ptr<> because they were filtered by the rewriter
// for: #addr-of
RAW_PTR_EXCLUSION LabelButton* label_button_ = nullptr;
RAW_PTR_EXCLUSION MdTextButton* md_button_ = nullptr;
RAW_PTR_EXCLUSION MdTextButton* md_disabled_button_ = nullptr;
RAW_PTR_EXCLUSION MdTextButton* md_default_button_ = nullptr;
RAW_PTR_EXCLUSION MdTextButton* md_tonal_button_ = nullptr;
RAW_PTR_EXCLUSION MdTextButton* md_text_button_ = nullptr;
RAW_PTR_EXCLUSION ImageButton* image_button_ = nullptr;
raw_ptr<const gfx::ImageSkia> icon_ = nullptr;
// The number of times the buttons are pressed.
int count_ = 0;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/button_example.h | C++ | unknown | 1,794 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/examples/button_sticker_sheet.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/layout/table_layout.h"
namespace views::examples {
namespace {
// Creates a stretchy table layout: there are |ncols| columns, separated from
// each other by padding columns, and all non-padding columns have equal flex
// weight and will flex in either dimension as needed.
TableLayout* MakeStretchyTableLayout(View* host, int ncols) {
const float kPaddingResizesEqually = 1.0;
const int kPaddingWidth = 30;
const int kColumnWidth = 96;
auto* layout = host->SetLayoutManager(std::make_unique<views::TableLayout>());
for (int i = 0; i < ncols; ++i) {
if (i != 0)
layout->AddPaddingColumn(kPaddingResizesEqually, kPaddingWidth);
layout->AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch,
TableLayout::kFixedSize, TableLayout::ColumnSize::kFixed,
kColumnWidth, kColumnWidth);
}
return layout;
}
std::unique_ptr<View> MakePlainLabel(const std::string& text) {
return std::make_unique<Label>(base::ASCIIToUTF16(text));
}
// Adds a label whose text is |label_text| and then all the views in |views|.
template <typename T>
void AddLabeledRow(View* parent,
const std::string& label_text,
std::vector<std::unique_ptr<T>> views) {
parent->AddChildView(MakePlainLabel(label_text));
for (auto& view : views)
parent->AddChildView(std::move(view));
}
// Constructs a pair of MdTextButtons in the specified |state| with the
// specified |listener|, and returns them in |*primary| and |*secondary|. The
// button in |*primary| is a call-to-action button, and the button in
// |*secondary| is a regular button.
std::vector<std::unique_ptr<MdTextButton>> MakeButtonsInState(
Button::ButtonState state) {
std::vector<std::unique_ptr<MdTextButton>> buttons;
const std::u16string button_text = u"Button";
auto primary = std::make_unique<views::MdTextButton>(
Button::PressedCallback(), button_text);
primary->SetProminent(true);
primary->SetState(state);
buttons.push_back(std::move(primary));
auto secondary = std::make_unique<views::MdTextButton>(
Button::PressedCallback(), button_text);
secondary->SetState(state);
buttons.push_back(std::move(secondary));
return buttons;
}
} // namespace
ButtonStickerSheet::ButtonStickerSheet()
: ExampleBase("Button (Sticker Sheet)") {}
ButtonStickerSheet::~ButtonStickerSheet() = default;
void ButtonStickerSheet::CreateExampleView(View* container) {
TableLayout* layout = MakeStretchyTableLayout(container, 3);
for (int i = 0; i < 6; ++i) {
const int kPaddingRowHeight = 8;
layout->AddRows(1, TableLayout::kFixedSize)
.AddPaddingRow(TableLayout::kFixedSize, kPaddingRowHeight);
}
// The title row has an empty row label.
std::vector<std::unique_ptr<View>> plainLabel;
plainLabel.push_back(MakePlainLabel("Primary"));
plainLabel.push_back(MakePlainLabel("Secondary"));
AddLabeledRow(container, std::string(), std::move(plainLabel));
AddLabeledRow(container, "Default", MakeButtonsInState(Button::STATE_NORMAL));
AddLabeledRow(container, "Normal", MakeButtonsInState(Button::STATE_NORMAL));
AddLabeledRow(container, "Hovered",
MakeButtonsInState(Button::STATE_HOVERED));
AddLabeledRow(container, "Pressed",
MakeButtonsInState(Button::STATE_PRESSED));
AddLabeledRow(container, "Disabled",
MakeButtonsInState(Button::STATE_DISABLED));
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/button_sticker_sheet.cc | C++ | unknown | 3,936 |
// 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_EXAMPLES_BUTTON_STICKER_SHEET_H_
#define UI_VIEWS_EXAMPLES_BUTTON_STICKER_SHEET_H_
#include "ui/views/examples/example_base.h"
namespace views::examples {
// An "example" that displays a sticker sheet of all the available material
// design button styles. This example only looks right with `--secondary-ui-md`.
// It is designed to be as visually similar to the UI Harmony spec's sticker
// sheet for buttons as possible.
class VIEWS_EXAMPLES_EXPORT ButtonStickerSheet : public ExampleBase {
public:
ButtonStickerSheet();
ButtonStickerSheet(const ButtonStickerSheet&) = delete;
ButtonStickerSheet& operator=(const ButtonStickerSheet&) = delete;
~ButtonStickerSheet() override;
// ExampleBase:
void CreateExampleView(View* container) override;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_BUTTON_STICKER_SHEET_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/button_sticker_sheet.h | C++ | unknown | 1,014 |
// 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/examples/checkbox_example.h"
#include "base/functional/bind.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/layout/flex_layout_view.h"
namespace views::examples {
CheckboxExample::CheckboxExample() : ExampleBase("Checkbox") {}
CheckboxExample::~CheckboxExample() = default;
void CheckboxExample::CreateExampleView(View* container) {
Builder<View>(container)
.SetUseDefaultFillLayout(true)
.AddChild(Builder<FlexLayoutView>()
.SetOrientation(LayoutOrientation::kVertical)
.SetMainAxisAlignment(views::LayoutAlignment::kCenter)
.AddChildren(Builder<Checkbox>()
.SetText(u"Checkbox")
.SetCallback(base::BindRepeating(
[](int* count) {
PrintStatus("Pressed! count: %d",
++(*count));
},
&count_)),
Builder<Checkbox>()
.SetText(u"Disabled Unchecked")
.SetState(Button::STATE_DISABLED),
Builder<Checkbox>()
.SetText(u"Disabled Checked")
.SetChecked(true)
.SetState(Button::STATE_DISABLED)))
.BuildChildren();
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/checkbox_example.cc | C++ | unknown | 1,799 |
// 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_EXAMPLES_CHECKBOX_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_CHECKBOX_EXAMPLE_H_
#include "ui/views/examples/example_base.h"
#include "ui/views/examples/views_examples_export.h"
namespace views {
class Checkbox;
namespace examples {
// CheckboxExample exercises a Checkbox control.
class VIEWS_EXAMPLES_EXPORT CheckboxExample : public ExampleBase {
public:
CheckboxExample();
CheckboxExample(const CheckboxExample&) = delete;
CheckboxExample& operator=(const CheckboxExample&) = delete;
~CheckboxExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
// The number of times the contained checkbox has been clicked.
int count_ = 0;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_CHECKBOX_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/checkbox_example.h | C++ | unknown | 953 |
// 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/examples/color_chooser_example.h"
#include "ui/views/widget/widget_delegate.h"
namespace views::examples {
ColorChooserExample::ColorChooserExample() : ExampleBase("ColorChooser") {}
ColorChooserExample::~ColorChooserExample() = default;
void ColorChooserExample::CreateExampleView(View* container) {
container->SetUseDefaultFillLayout(true);
container->AddChildView(
chooser_.MakeWidgetDelegate()->TransferOwnershipOfContentsView());
}
void ColorChooserExample::OnColorChosen(SkColor color) {}
void ColorChooserExample::OnColorChooserDialogClosed() {}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/color_chooser_example.cc | C++ | unknown | 766 |
// 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_EXAMPLES_COLOR_CHOOSER_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_COLOR_CHOOSER_EXAMPLE_H_
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/color_palette.h"
#include "ui/views/color_chooser/color_chooser_listener.h"
#include "ui/views/color_chooser/color_chooser_view.h"
#include "ui/views/examples/example_base.h"
namespace views::examples {
// A ColorChooser example.
class VIEWS_EXAMPLES_EXPORT ColorChooserExample : public ExampleBase,
public ColorChooserListener {
public:
ColorChooserExample();
ColorChooserExample(const ColorChooserExample&) = delete;
ColorChooserExample& operator=(const ColorChooserExample&) = delete;
~ColorChooserExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
// ColorChooserListener:
void OnColorChosen(SkColor color) override;
void OnColorChooserDialogClosed() override;
private:
ColorChooser chooser_{this, gfx::kPlaceholderColor};
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_COLOR_CHOOSER_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/color_chooser_example.h | C++ | unknown | 1,247 |
// 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/examples/colored_dialog_example.h"
#include <memory>
#include <utility>
#include "base/containers/adapters.h"
#include "base/memory/raw_ref.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/vector_icon_types.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/vector_icons.h"
#include "ui/views/widget/widget.h"
namespace views::examples {
class ThemeTrackingCheckbox : public views::Checkbox {
public:
explicit ThemeTrackingCheckbox(const std::u16string& label)
: Checkbox(label,
base::BindRepeating(&ThemeTrackingCheckbox::ButtonPressed,
base::Unretained(this))) {}
ThemeTrackingCheckbox(const ThemeTrackingCheckbox&) = delete;
ThemeTrackingCheckbox& operator=(const ThemeTrackingCheckbox&) = delete;
~ThemeTrackingCheckbox() override = default;
// views::Checkbox
void OnThemeChanged() override {
views::Checkbox::OnThemeChanged();
SetChecked(GetNativeTheme()->ShouldUseDarkColors());
}
void ButtonPressed() {
GetNativeTheme()->set_use_dark_colors(GetChecked());
GetWidget()->ThemeChanged();
}
};
class TextVectorImageButton : public views::MdTextButton {
public:
TextVectorImageButton(PressedCallback callback,
const std::u16string& text,
const gfx::VectorIcon& icon)
: MdTextButton(callback, text), icon_(icon) {}
TextVectorImageButton(const TextVectorImageButton&) = delete;
TextVectorImageButton& operator=(const TextVectorImageButton&) = delete;
~TextVectorImageButton() override = default;
void OnThemeChanged() override {
views::MdTextButton::OnThemeChanged();
// Use the text color for the associated vector image.
SetImageModel(
views::Button::ButtonState::STATE_NORMAL,
ui::ImageModel::FromVectorIcon(*icon_, label()->GetEnabledColor()));
}
private:
const raw_ref<const gfx::VectorIcon> icon_;
};
ColoredDialog::ColoredDialog(AcceptCallback accept_callback) {
SetAcceptCallback(base::BindOnce(
[](ColoredDialog* dialog, AcceptCallback callback) {
std::move(callback).Run(dialog->textfield_->GetText());
},
base::Unretained(this), std::move(accept_callback)));
SetModalType(ui::MODAL_TYPE_WINDOW);
SetTitle(l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_TITLE));
SetLayoutManager(std::make_unique<views::FillLayout>());
set_margins(views::LayoutProvider::Get()->GetDialogInsetsForContentType(
views::DialogContentType::kControl, views::DialogContentType::kControl));
textfield_ = AddChildView(std::make_unique<views::Textfield>());
textfield_->SetPlaceholderText(
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_TEXTFIELD_PLACEHOLDER));
textfield_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_TEXTFIELD_AX_LABEL));
textfield_->set_controller(this);
SetButtonLabel(ui::DIALOG_BUTTON_OK,
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_SUBMIT_BUTTON));
SetButtonEnabled(ui::DIALOG_BUTTON_OK, false);
}
ColoredDialog::~ColoredDialog() = default;
bool ColoredDialog::ShouldShowCloseButton() const {
return false;
}
void ColoredDialog::ContentsChanged(Textfield* sender,
const std::u16string& new_contents) {
SetButtonEnabled(ui::DIALOG_BUTTON_OK, !textfield_->GetText().empty());
DialogModelChanged();
}
ColoredDialogChooser::ColoredDialogChooser() {
views::LayoutProvider* provider = views::LayoutProvider::Get();
const int vertical_spacing =
provider->GetDistanceMetric(views::DISTANCE_UNRELATED_CONTROL_VERTICAL);
auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, gfx::Insets(),
vertical_spacing));
layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kStart);
AddChildView(std::make_unique<ThemeTrackingCheckbox>(
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_CHOOSER_CHECKBOX)));
AddChildView(std::make_unique<TextVectorImageButton>(
base::BindRepeating(&ColoredDialogChooser::ButtonPressed,
base::Unretained(this)),
l10n_util::GetStringUTF16(IDS_COLORED_DIALOG_CHOOSER_BUTTON),
views::kInfoIcon));
confirmation_label_ = AddChildView(
std::make_unique<views::Label>(std::u16string(), style::CONTEXT_LABEL));
confirmation_label_->SetVisible(false);
}
ColoredDialogChooser::~ColoredDialogChooser() = default;
void ColoredDialogChooser::ButtonPressed() {
// Create the colored dialog.
views::Widget* widget = DialogDelegate::CreateDialogWidget(
new ColoredDialog(base::BindOnce(&ColoredDialogChooser::OnFeedbackSubmit,
base::Unretained(this))),
nullptr, GetWidget()->GetNativeView());
widget->Show();
}
void ColoredDialogChooser::OnFeedbackSubmit(std::u16string text) {
constexpr base::TimeDelta kConfirmationDuration = base::Seconds(3);
confirmation_label_->SetText(l10n_util::GetStringFUTF16(
IDS_COLORED_DIALOG_CHOOSER_CONFIRM_LABEL, text));
confirmation_label_->SetVisible(true);
confirmation_timer_.Start(
FROM_HERE, kConfirmationDuration,
base::BindOnce([](views::View* view) { view->SetVisible(false); },
confirmation_label_));
}
ColoredDialogExample::ColoredDialogExample() : ExampleBase("Colored Dialog") {}
ColoredDialogExample::~ColoredDialogExample() = default;
void ColoredDialogExample::CreateExampleView(views::View* container) {
container->SetLayoutManager(std::make_unique<views::FillLayout>());
container->AddChildView(std::make_unique<ColoredDialogChooser>());
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/colored_dialog_example.cc | C++ | unknown | 6,254 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_COLORED_DIALOG_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_COLORED_DIALOG_EXAMPLE_H_
#include "base/memory/raw_ptr.h"
#include "base/timer/timer.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/examples/example_base.h"
#include "ui/views/view.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
class Label;
namespace examples {
class ColoredDialog : public views::DialogDelegateView,
public views::TextfieldController {
public:
using AcceptCallback = base::OnceCallback<void(std::u16string)>;
explicit ColoredDialog(AcceptCallback accept_callback);
ColoredDialog(const ColoredDialog&) = delete;
ColoredDialog& operator=(const ColoredDialog&) = delete;
~ColoredDialog() override;
protected:
// views::DialogDelegateView
bool ShouldShowCloseButton() const override;
// views::TextfieldController
void ContentsChanged(Textfield* sender,
const std::u16string& new_contents) override;
private:
raw_ptr<views::Textfield> textfield_;
};
class ColoredDialogChooser : public views::View {
public:
ColoredDialogChooser();
ColoredDialogChooser(const ColoredDialogChooser&) = delete;
ColoredDialogChooser& operator=(const ColoredDialogChooser&) = delete;
~ColoredDialogChooser() override;
void ButtonPressed();
private:
void OnFeedbackSubmit(std::u16string text);
raw_ptr<views::Label> confirmation_label_;
base::OneShotTimer confirmation_timer_;
};
// An example that exercises BubbleDialogDelegateView or DialogDelegateView.
class VIEWS_EXAMPLES_EXPORT ColoredDialogExample : public ExampleBase {
public:
ColoredDialogExample();
ColoredDialogExample(const ColoredDialogExample&) = delete;
ColoredDialogExample& operator=(const ColoredDialogExample&) = delete;
~ColoredDialogExample() override;
// ExampleBase
void CreateExampleView(views::View* container) override;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_COLORED_DIALOG_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/colored_dialog_example.h | C++ | unknown | 2,190 |
// 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/examples/colors_example.h"
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/views/background.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/table_layout.h"
namespace views::examples {
namespace {
// Argument utility macro that expands |label| to both a UTF16 string as the
// first argument and the corresponding ui::ColorId as the second argument.
#define COLOR_LABEL_ARGS(label) u## #label, ui::label
// Starts a new row and adds two columns to |layout|, the first displaying
// |label_string| and the second displaying |color_id| with its color and
// equivalent components as text.
void InsertColorRow(View* parent,
base::StringPiece16 label_string,
ui::ColorId color_id) {
auto* label_view = parent->AddChildView(
std::make_unique<Label>(std::u16string(label_string)));
label_view->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);
label_view->SetSelectable(true);
auto* color_view = parent->AddChildView(std::make_unique<Label>());
color_view->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);
auto background_color = color_view->GetColorProvider()->GetColor(color_id);
uint8_t red = SkColorGetR(background_color);
uint8_t green = SkColorGetG(background_color);
uint8_t blue = SkColorGetB(background_color);
uint8_t alpha = SkColorGetA(background_color);
std::string color_string =
base::StringPrintf("#%02x%02x%02x Alpha: %d", red, green, blue, alpha);
color_view->SetText(base::ASCIIToUTF16(color_string));
color_view->SetBackgroundColor(background_color);
color_view->SetBackground(CreateSolidBackground(background_color));
color_view->SetSelectable(true);
}
// Returns a view of two columns where the first contains the identifier names
// of ui::ColorId and the second contains the color.
void CreateAllColorsView(ScrollView* scroll_view) {
auto* container = scroll_view->SetContents(std::make_unique<View>());
container->SetLayoutManager(std::make_unique<TableLayout>())
->AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddRows(71, TableLayout::kFixedSize);
InsertColorRow(container, COLOR_LABEL_ARGS(kColorWindowBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorDialogBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorDialogForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorBubbleBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorFocusableBorderFocused));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorFocusableBorderUnfocused));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorButtonForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorButtonForegroundDisabled));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorRadioButtonForegroundUnchecked));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorButtonBackgroundProminent));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorButtonBackgroundProminentFocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorButtonBackgroundProminentDisabled));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorButtonForegroundProminent));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorButtonBorder));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuItemForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuItemForegroundDisabled));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuItemForegroundSelected));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuItemBackgroundSelected));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorMenuItemForegroundSecondary));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuSeparator));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuBorder));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorMenuIcon));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorMenuItemBackgroundHighlighted));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorMenuItemForegroundHighlighted));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorMenuItemBackgroundAlertedInitial));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorMenuItemBackgroundAlertedTarget));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLabelForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLabelForegroundDisabled));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLabelForegroundSecondary));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLabelSelectionForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLabelSelectionBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLinkForegroundDisabled));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLinkForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorLinkForegroundPressed));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorSeparator));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTabForegroundSelected));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTabForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTabContentSeparator));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTextfieldForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTextfieldBackground));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTextfieldForegroundPlaceholder));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTextfieldForegroundDisabled));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTextfieldBackgroundDisabled));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTextfieldSelectionForeground));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTextfieldSelectionBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTooltipBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTooltipForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTreeBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTreeNodeForeground));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTreeNodeForegroundSelectedFocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTreeNodeForegroundSelectedUnfocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTreeNodeBackgroundSelectedFocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTreeNodeBackgroundSelectedUnfocused));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableForeground));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTableForegroundSelectedFocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTableForegroundSelectedUnfocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTableBackgroundSelectedFocused));
InsertColorRow(container,
COLOR_LABEL_ARGS(kColorTableBackgroundSelectedUnfocused));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableGroupingIndicator));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableHeaderForeground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableHeaderBackground));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorTableHeaderSeparator));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorThrobber));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorThrobberPreconnect));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorAlertLowSeverity));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorAlertMediumSeverityIcon));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorAlertMediumSeverityText));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorAlertHighSeverity));
InsertColorRow(container, COLOR_LABEL_ARGS(kColorIcon));
// Expands the view to allow for scrolling.
container->SizeToPreferredSize();
}
class AllColorsScrollView : public ScrollView {
public:
AllColorsScrollView() {
constexpr int kMaxHeight = 300;
ClipHeightTo(0, kMaxHeight);
}
protected:
void OnThemeChanged() override {
ScrollView::OnThemeChanged();
CreateAllColorsView(this);
}
};
} // namespace
ColorsExample::ColorsExample()
: ExampleBase(l10n_util::GetStringUTF8(IDS_THEME_SELECT_LABEL).c_str()) {}
ColorsExample::~ColorsExample() = default;
void ColorsExample::CreateExampleView(View* container) {
container->SetLayoutManager(std::make_unique<FillLayout>());
container->AddChildView(std::make_unique<AllColorsScrollView>());
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/colors_example.cc | C++ | unknown | 9,496 |
// 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_EXAMPLES_COLORS_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_COLORS_EXAMPLE_H_
#include "ui/views/examples/example_base.h"
namespace views::examples {
class VIEWS_EXAMPLES_EXPORT ColorsExample : public ExampleBase {
public:
ColorsExample();
ColorsExample(const ColorsExample&) = delete;
ColorsExample& operator=(const ColorsExample&) = delete;
~ColorsExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_COLORS_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/colors_example.h | C++ | unknown | 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/examples/combobox_example.h"
#include <memory>
#include <utility>
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/fill_layout.h"
namespace views::examples {
namespace {
// A combobox model implementation that generates a list of "Item <index>".
class ComboboxModelExample : public ui::ComboboxModel {
public:
ComboboxModelExample() = default;
ComboboxModelExample(const ComboboxModelExample&) = delete;
ComboboxModelExample& operator=(const ComboboxModelExample&) = delete;
~ComboboxModelExample() override = default;
private:
// ui::ComboboxModel:
size_t GetItemCount() const override { return 10; }
std::u16string GetItemAt(size_t index) const override {
return base::UTF8ToUTF16(
base::StringPrintf("%c item", static_cast<char>('A' + index)));
}
};
} // namespace
ComboboxExample::ComboboxExample()
: ExampleBase(l10n_util::GetStringUTF8(IDS_COMBOBOX_SELECT_LABEL).c_str()) {
}
ComboboxExample::~ComboboxExample() = default;
void ComboboxExample::CreateExampleView(View* container) {
container->SetLayoutManager(std::make_unique<FillLayout>());
auto view =
Builder<BoxLayoutView>()
.SetOrientation(BoxLayout::Orientation::kVertical)
.SetInsideBorderInsets(gfx::Insets::VH(10, 0))
.SetBetweenChildSpacing(5)
.AddChildren(
Builder<Combobox>()
.CopyAddressTo(&combobox_)
.SetOwnedModel(std::make_unique<ComboboxModelExample>())
.SetSelectedIndex(3)
.SetAccessibleName(
l10n_util::GetStringUTF16(IDS_COMBOBOX_NAME_1))
.SetCallback(base::BindRepeating(
&ComboboxExample::ValueChanged, base::Unretained(this))),
Builder<Combobox>()
.SetOwnedModel(std::make_unique<ComboboxModelExample>())
.SetEnabled(false)
.SetSelectedIndex(4)
.SetAccessibleName(
l10n_util::GetStringUTF16(IDS_COMBOBOX_NAME_2))
.SetCallback(base::BindRepeating(
&ComboboxExample::ValueChanged, base::Unretained(this))))
.Build();
container->AddChildView(std::move(view));
}
void ComboboxExample::ValueChanged() {
PrintStatus("Selected: %s",
base::UTF16ToUTF8(combobox_->GetModel()->GetItemAt(
combobox_->GetSelectedIndex().value()))
.c_str());
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/combobox_example.cc | C++ | unknown | 3,024 |
// 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_EXAMPLES_COMBOBOX_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_COMBOBOX_EXAMPLE_H_
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/base/models/combobox_model.h"
#include "ui/views/examples/example_base.h"
namespace views {
class Combobox;
namespace examples {
class VIEWS_EXAMPLES_EXPORT ComboboxExample : public ExampleBase {
public:
ComboboxExample();
ComboboxExample(const ComboboxExample&) = delete;
ComboboxExample& operator=(const ComboboxExample&) = delete;
~ComboboxExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
void ValueChanged();
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Combobox* combobox_ = nullptr;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_COMBOBOX_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/combobox_example.h | C++ | unknown | 1,021 |
// 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/examples/create_examples.h"
#include <memory>
#include <utility>
#include "build/build_config.h"
#include "ui/views/examples/animated_image_view_example.h"
#include "ui/views/examples/animation_example.h"
#include "ui/views/examples/ax_example.h"
#include "ui/views/examples/badge_example.h"
#include "ui/views/examples/box_layout_example.h"
#include "ui/views/examples/bubble_example.h"
#include "ui/views/examples/button_example.h"
#include "ui/views/examples/button_sticker_sheet.h"
#include "ui/views/examples/checkbox_example.h"
#include "ui/views/examples/colored_dialog_example.h"
#include "ui/views/examples/colors_example.h"
#include "ui/views/examples/combobox_example.h"
#include "ui/views/examples/designer_example.h"
#include "ui/views/examples/dialog_example.h"
#include "ui/views/examples/fade_animation.h"
#include "ui/views/examples/flex_layout_example.h"
#include "ui/views/examples/ink_drop_example.h"
#include "ui/views/examples/label_example.h"
#include "ui/views/examples/link_example.h"
#include "ui/views/examples/login_bubble_dialog_example.h"
#include "ui/views/examples/menu_example.h"
#include "ui/views/examples/message_box_example.h"
#include "ui/views/examples/multiline_example.h"
#include "ui/views/examples/notification_example.h"
#include "ui/views/examples/progress_bar_example.h"
#include "ui/views/examples/radio_button_example.h"
#include "ui/views/examples/scroll_view_example.h"
#include "ui/views/examples/slider_example.h"
#include "ui/views/examples/square_ink_drop_example.h"
#include "ui/views/examples/tabbed_pane_example.h"
#include "ui/views/examples/table_example.h"
#include "ui/views/examples/text_example.h"
#include "ui/views/examples/textarea_example.h"
#include "ui/views/examples/textfield_example.h"
#include "ui/views/examples/throbber_example.h"
#include "ui/views/examples/toggle_button_example.h"
#include "ui/views/examples/tree_view_example.h"
#include "ui/views/examples/vector_example.h"
#include "ui/views/examples/widget_example.h"
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_FUCHSIA)
#include "ui/views/examples/color_chooser_example.h"
#endif
namespace views::examples {
// Creates the default set of examples.
ExampleVector CreateExamples(ExampleVector extra_examples) {
ExampleVector examples = std::move(extra_examples);
examples.push_back(std::make_unique<AnimatedImageViewExample>());
examples.push_back(std::make_unique<AnimationExample>());
examples.push_back(std::make_unique<AxExample>());
examples.push_back(std::make_unique<BadgeExample>());
examples.push_back(std::make_unique<BoxLayoutExample>());
examples.push_back(std::make_unique<BubbleExample>());
examples.push_back(std::make_unique<ButtonExample>());
examples.push_back(std::make_unique<ButtonStickerSheet>());
examples.push_back(std::make_unique<CheckboxExample>());
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_FUCHSIA)
examples.push_back(std::make_unique<ColorChooserExample>());
#endif
examples.push_back(std::make_unique<ColoredDialogExample>());
examples.push_back(std::make_unique<ColorsExample>());
examples.push_back(std::make_unique<ComboboxExample>());
examples.push_back(std::make_unique<DesignerExample>());
examples.push_back(std::make_unique<DialogExample>());
examples.push_back(std::make_unique<FadeAnimationExample>());
examples.push_back(std::make_unique<FlexLayoutExample>());
examples.push_back(std::make_unique<InkDropExample>());
examples.push_back(std::make_unique<LabelExample>());
examples.push_back(std::make_unique<LinkExample>());
examples.push_back(std::make_unique<LoginBubbleDialogExample>());
examples.push_back(std::make_unique<MenuExample>());
examples.push_back(std::make_unique<MessageBoxExample>());
examples.push_back(std::make_unique<MultilineExample>());
examples.push_back(std::make_unique<NotificationExample>());
examples.push_back(std::make_unique<ProgressBarExample>());
examples.push_back(std::make_unique<RadioButtonExample>());
examples.push_back(std::make_unique<ScrollViewExample>());
examples.push_back(std::make_unique<SliderExample>());
examples.push_back(std::make_unique<SquareInkDropExample>());
examples.push_back(std::make_unique<TabbedPaneExample>());
examples.push_back(std::make_unique<TableExample>());
examples.push_back(std::make_unique<TextExample>());
examples.push_back(std::make_unique<TextareaExample>());
examples.push_back(std::make_unique<TextfieldExample>());
examples.push_back(std::make_unique<ToggleButtonExample>());
examples.push_back(std::make_unique<ThrobberExample>());
examples.push_back(std::make_unique<TreeViewExample>());
examples.push_back(std::make_unique<VectorExample>());
examples.push_back(std::make_unique<WidgetExample>());
return examples;
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/create_examples.cc | C++ | unknown | 5,006 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_CREATE_EXAMPLES_H_
#define UI_VIEWS_EXAMPLES_CREATE_EXAMPLES_H_
#include "ui/views/examples/example_base.h"
#include "ui/views/examples/views_examples_export.h"
namespace views::examples {
// Creates the default set of examples.
ExampleVector VIEWS_EXAMPLES_EXPORT
CreateExamples(ExampleVector extra_examples = ExampleVector());
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_CREATE_EXAMPLES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/create_examples.h | C++ | unknown | 585 |
// 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/examples/designer_example.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/ranges/ranges.h"
#include "base/strings/utf_string_conversions.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_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/color/color_id.h"
#include "ui/events/event.h"
#include "ui/events/event_targeter.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/gfx/skia_util.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/button/radio_button.h"
#include "ui/views/controls/button/toggle_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/table/table_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/examples/examples_color_id.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/vector_icons.h"
#include "ui/views/view.h"
#include "ui/views/view_targeter.h"
namespace views::examples {
class DesignerSurface : public View {
public:
METADATA_HEADER(DesignerSurface);
explicit DesignerSurface(int grid_size = 8);
DesignerSurface(const DesignerSurface&) = delete;
DesignerSurface& operator=(const DesignerSurface&) = delete;
~DesignerSurface() override = default;
int GetGridSize() const { return grid_size_; }
void SetGridSize(int grid_size);
// View overrides.
void OnPaint(gfx::Canvas* canvas) override;
void OnThemeChanged() override;
private:
void RebuildGridImage();
gfx::ImageSkia grid_image_;
int grid_size_ = 8;
};
DesignerSurface::DesignerSurface(int grid_size) : grid_size_(grid_size) {}
void DesignerSurface::SetGridSize(int grid_size) {
if (grid_size_ != grid_size) {
grid_size_ = grid_size;
if (GetWidget())
RebuildGridImage();
}
}
void DesignerSurface::OnPaint(gfx::Canvas* canvas) {
views::View::OnPaint(canvas);
canvas->TileImageInt(grid_image_, 0, 0, size().width(), size().height());
}
void DesignerSurface::OnThemeChanged() {
View::OnThemeChanged();
RebuildGridImage();
}
void DesignerSurface::RebuildGridImage() {
const SkColor grid_color =
GetColorProvider()->GetColor(ExamplesColorIds::kColorDesignerGrid);
gfx::Size grid_size = grid_size_ <= 8
? gfx::Size(grid_size_ * 8, grid_size_ * 8)
: gfx::Size(grid_size_, grid_size_);
auto grid_canvas = std::make_unique<gfx::Canvas>(grid_size, 1.0, false);
for (int i = 0; i < grid_size.width(); i += grid_size_) {
for (int j = 0; j < grid_size.height(); j += grid_size_) {
grid_canvas->FillRect(gfx::Rect(i, j, 1, 1), grid_color);
}
}
grid_image_ = gfx::ImageSkia::CreateFrom1xBitmap(grid_canvas->GetBitmap());
}
BEGIN_METADATA(DesignerSurface, View)
ADD_PROPERTY_METADATA(int, GridSize)
END_METADATA
BEGIN_VIEW_BUILDER(/* no export */, DesignerSurface, View)
VIEW_BUILDER_PROPERTY(int, GridSize)
END_VIEW_BUILDER
} // namespace views::examples
DEFINE_VIEW_BUILDER(/* no export */, views::examples::DesignerSurface)
namespace views::examples {
namespace {
ui::TableColumn MakeColumn(int id, std::u16string title, bool sortable) {
ui::TableColumn column;
column.id = id;
column.title = title;
column.alignment = ui::TableColumn::LEFT;
column.width = -1;
column.percent = 0.5f;
column.sortable = sortable;
return column;
}
int SnapToInterval(int value, int interval) {
return value - (value % interval);
}
template <typename C>
class ClassRegistration : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override { return std::make_unique<C>(); }
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(C::MetaData()->type_name());
}
};
template <>
class ClassRegistration<Combobox> : public BaseClassRegistration,
public ui::ComboboxModel {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return std::make_unique<Combobox>(this);
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(Combobox::MetaData()->type_name());
}
// ui::ComboboxModel
size_t GetItemCount() const override { return 1; }
std::u16string GetItemAt(size_t index) const override { return u"<empty>"; }
absl::optional<size_t> GetDefaultIndex() const override { return 0; }
};
template <>
class ClassRegistration<MdTextButton> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return Builder<MdTextButton>().SetText(u"Button").Build();
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(MdTextButton::MetaData()->type_name());
}
};
template <>
class ClassRegistration<Textfield> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
const std::u16string text = u"<text field>";
return Builder<Textfield>()
.SetText(text)
.SetDefaultWidthInChars(text.size())
.Build();
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(Textfield::MetaData()->type_name());
}
};
template <>
class ClassRegistration<Checkbox> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return std::make_unique<Checkbox>(u"<Checkbox>");
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(Checkbox::MetaData()->type_name());
}
};
template <>
class ClassRegistration<RadioButton> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return std::make_unique<RadioButton>(u"<RadioButton>", 0);
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(RadioButton::MetaData()->type_name());
}
};
template <>
class ClassRegistration<ToggleButton> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return std::make_unique<ToggleButton>();
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(ToggleButton::MetaData()->type_name());
}
};
template <>
class ClassRegistration<ImageButton> : public BaseClassRegistration {
public:
ClassRegistration() = default;
~ClassRegistration() override = default;
std::unique_ptr<View> CreateView() override {
return Builder<ImageButton>()
.SetImage(Button::ButtonState::STATE_NORMAL,
gfx::CreateVectorIcon(kPinIcon, ui::kColorIcon))
.Build();
}
std::u16string GetViewClassName() override {
return base::ASCIIToUTF16(ImageButton::MetaData()->type_name());
}
};
std::vector<std::unique_ptr<BaseClassRegistration>> GetClassRegistrations() {
std::vector<std::unique_ptr<BaseClassRegistration>> registrations;
registrations.push_back(std::make_unique<ClassRegistration<Checkbox>>());
registrations.push_back(std::make_unique<ClassRegistration<Combobox>>());
registrations.push_back(std::make_unique<ClassRegistration<MdTextButton>>());
registrations.push_back(std::make_unique<ClassRegistration<RadioButton>>());
registrations.push_back(std::make_unique<ClassRegistration<Textfield>>());
registrations.push_back(std::make_unique<ClassRegistration<ToggleButton>>());
registrations.push_back(std::make_unique<ClassRegistration<ImageButton>>());
return registrations;
}
bool IsViewParent(View* parent, View* view) {
while (view) {
if (view == parent)
return true;
view = view->parent();
}
return false;
}
View* GetDesignerChild(View* child_view, View* designer) {
while (child_view && child_view != designer &&
child_view->parent() != designer) {
child_view = child_view->parent();
}
return child_view;
}
} // namespace
BaseClassRegistration::~BaseClassRegistration() = default;
DesignerExample::GrabHandle::GrabHandle(GrabHandles* grab_handles,
GrabHandlePosition position)
: position_(position), grab_handles_(grab_handles) {}
DesignerExample::GrabHandle::~GrabHandle() = default;
void DesignerExample::GrabHandle::SetAttachedView(View* view) {
bool was_visible = GetVisible() && attached_view_ != view;
attached_view_ = view;
SetVisible(!!attached_view_);
UpdatePosition(!was_visible);
}
void DesignerExample::GrabHandle::UpdatePosition(bool reorder) {
if (GetVisible() && attached_view_) {
PositionOnView();
if (reorder)
parent()->ReorderChildView(this, parent()->children().size());
}
}
ui::Cursor DesignerExample::GrabHandle::GetCursor(const ui::MouseEvent& event) {
switch (position_) {
case GrabHandlePosition::kTop:
case GrabHandlePosition::kBottom:
return ui::mojom::CursorType::kNorthSouthResize;
case GrabHandlePosition::kLeft:
case GrabHandlePosition::kRight:
return ui::mojom::CursorType::kEastWestResize;
case GrabHandlePosition::kTopLeft:
case GrabHandlePosition::kBottomRight:
return ui::mojom::CursorType::kNorthWestSouthEastResize;
case GrabHandlePosition::kTopRight:
case GrabHandlePosition::kBottomLeft:
return ui::mojom::CursorType::kNorthEastSouthWestResize;
}
}
gfx::Size DesignerExample::GrabHandle::CalculatePreferredSize() const {
return gfx::Size(kGrabHandleSize, kGrabHandleSize);
}
void DesignerExample::GrabHandle::OnPaint(gfx::Canvas* canvas) {
SkPath path;
gfx::Point center = GetLocalBounds().CenterPoint();
path.addCircle(center.x(), center.y(), width() / 2);
cc::PaintFlags flags;
flags.setColor(
GetColorProvider()->GetColor(ExamplesColorIds::kColorDesignerGrabHandle));
flags.setAntiAlias(true);
canvas->DrawPath(path, flags);
}
bool DesignerExample::GrabHandle::OnMousePressed(const ui::MouseEvent& event) {
mouse_drag_pos_ = event.location();
return true;
}
bool DesignerExample::GrabHandle::OnMouseDragged(const ui::MouseEvent& event) {
gfx::Point new_location = event.location();
if (position_ == GrabHandlePosition::kTop ||
position_ == GrabHandlePosition::kBottom) {
new_location.set_x(mouse_drag_pos_.x());
}
if (position_ == GrabHandlePosition::kLeft ||
position_ == GrabHandlePosition::kRight) {
new_location.set_y(mouse_drag_pos_.y());
}
SetPosition(origin() + (new_location - mouse_drag_pos_));
UpdateViewSize();
grab_handles_->SetAttachedView(attached_view_);
return true;
}
void DesignerExample::GrabHandle::PositionOnView() {
DCHECK(attached_view_);
gfx::Rect view_bounds = attached_view_->bounds();
gfx::Point edge_position;
if (IsTop(position_)) {
edge_position.set_y(view_bounds.y());
if (position_ == GrabHandlePosition::kTop)
edge_position.set_x(view_bounds.top_center().x());
} else if (IsBottom(position_)) {
edge_position.set_y(view_bounds.bottom());
if (position_ == GrabHandlePosition::kBottom)
edge_position.set_x(view_bounds.bottom_center().x());
}
if (IsLeft(position_)) {
edge_position.set_x(view_bounds.x());
if (position_ == GrabHandlePosition::kLeft)
edge_position.set_y(view_bounds.left_center().y());
} else if (IsRight(position_)) {
edge_position.set_x(view_bounds.right());
if (position_ == GrabHandlePosition::kRight)
edge_position.set_y(view_bounds.right_center().y());
}
SetPosition(edge_position - (bounds().CenterPoint() - origin()));
}
void DesignerExample::GrabHandle::UpdateViewSize() {
DCHECK(attached_view_);
gfx::Rect view_bounds = attached_view_->bounds();
gfx::Point view_center = bounds().CenterPoint();
if (IsTop(position_)) {
view_bounds.set_height(view_bounds.height() -
(view_center.y() - view_bounds.y()));
view_bounds.set_y(view_center.y());
}
if (IsBottom(position_))
view_bounds.set_height(view_center.y() - view_bounds.y());
if (IsLeft(position_)) {
view_bounds.set_width(view_bounds.width() -
(view_center.x() - view_bounds.x()));
view_bounds.set_x(view_center.x());
}
if (IsRight(position_))
view_bounds.set_width(view_center.x() - view_bounds.x());
attached_view_->SetBoundsRect(view_bounds);
}
// static
bool DesignerExample::GrabHandle::IsTop(GrabHandlePosition position) {
return (position & GrabHandlePosition::kTop);
}
// static
bool DesignerExample::GrabHandle::IsBottom(GrabHandlePosition position) {
return (position & GrabHandlePosition::kBottom);
}
// static
bool DesignerExample::GrabHandle::IsLeft(GrabHandlePosition position) {
return (position & GrabHandlePosition::kLeft);
}
// static
bool DesignerExample::GrabHandle::IsRight(GrabHandlePosition position) {
return (position & GrabHandlePosition::kRight);
}
BEGIN_METADATA(DesignerExample, GrabHandle, View)
END_METADATA
DesignerExample::GrabHandles::GrabHandles() = default;
DesignerExample::GrabHandles::~GrabHandles() = default;
void DesignerExample::GrabHandles::Initialize(View* layout_panel) {
static constexpr GrabHandlePosition positions[] = {
GrabHandlePosition::kTop, GrabHandlePosition::kBottom,
GrabHandlePosition::kLeft, GrabHandlePosition::kRight,
GrabHandlePosition::kTopLeft, GrabHandlePosition::kTopRight,
GrabHandlePosition::kBottomLeft, GrabHandlePosition::kBottomRight,
};
DCHECK(grab_handles_.empty());
for (GrabHandlePosition position : positions) {
auto grab_handle = std::make_unique<GrabHandle>(this, position);
grab_handle->SizeToPreferredSize();
grab_handle->SetVisible(false);
grab_handles_.push_back(layout_panel->AddChildView(std::move(grab_handle)));
}
}
void DesignerExample::GrabHandles::SetAttachedView(View* view) {
for (GrabHandle* grab_handle : grab_handles_)
grab_handle->SetAttachedView(view);
}
bool DesignerExample::GrabHandles::IsGrabHandle(View* view) {
return base::ranges::find(grab_handles_, view) != grab_handles_.end();
}
DesignerExample::DesignerExample() : ExampleBase("Designer") {}
DesignerExample::~DesignerExample() {
if (tracker_.view())
inspector_->SetModel(nullptr);
}
void DesignerExample::CreateExampleView(View* container) {
Builder<View>(container)
.SetUseDefaultFillLayout(true)
.AddChildren(
Builder<BoxLayoutView>()
.CopyAddressTo(&designer_container_)
.SetOrientation(BoxLayout::Orientation::kHorizontal)
.SetMainAxisAlignment(BoxLayout::MainAxisAlignment::kEnd)
.SetCrossAxisAlignment(BoxLayout::CrossAxisAlignment::kStretch)
.AddChildren(
Builder<DesignerSurface>()
.CopyAddressTo(&designer_panel_)
.CustomConfigure(base::BindOnce(
[](DesignerExample* designer_example,
DesignerSurface* designer_surface) {
designer_surface->AddPreTargetHandler(
designer_example);
},
base::Unretained(this))),
Builder<BoxLayoutView>()
.CopyAddressTo(&palette_panel_)
.SetOrientation(BoxLayout::Orientation::kVertical)
.SetInsideBorderInsets(gfx::Insets::TLBR(0, 3, 0, 0))
.SetBetweenChildSpacing(3)
.AddChildren(
Builder<Combobox>()
.CopyAddressTo(&view_type_)
.SetAccessibleName(u"View Type")
.SetModel(this),
Builder<MdTextButton>()
.SetCallback(base::BindRepeating(
&DesignerExample::CreateView,
base::Unretained(this)))
.SetText(u"Add"),
TableView::CreateScrollViewBuilderWithTable(
Builder<TableView>()
.CopyAddressTo(&inspector_)
.SetColumns({MakeColumn(0, u"Name", true),
MakeColumn(1, u"Value", false)})
.SetModel(this)
.SetTableType(views::TEXT_ONLY)
.SetSingleSelection(true))
.SetPreferredSize(gfx::Size(250, 400)))))
.BuildChildren();
grab_handles_.Initialize(designer_panel_);
designer_container_->SetFlexForView(designer_panel_, 75);
class_registrations_ = GetClassRegistrations();
// TODO(crbug.com/1392538): Refactor such that the TableModel is not
// responsible for managing the lifetimes of views
tracker_.SetView(inspector_);
}
void DesignerExample::OnEvent(ui::Event* event) {
if (event->IsMouseEvent() && event->target()) {
View* view = static_cast<View*>(event->target());
if (IsViewParent(designer_panel_, view->parent()) ||
view == designer_panel_) {
HandleDesignerMouseEvent(event);
return;
}
}
ui::EventHandler::OnEvent(event);
}
void DesignerExample::HandleDesignerMouseEvent(ui::Event* event) {
ui::MouseEvent* mouse_event = event->AsMouseEvent();
switch (mouse_event->type()) {
case ui::ET_MOUSE_PRESSED:
if (mouse_event->IsOnlyLeftMouseButton()) {
DCHECK(!dragging_);
View* event_view = GetDesignerChild(static_cast<View*>(event->target()),
designer_panel_);
if (grab_handles_.IsGrabHandle(event_view)) {
dragging_ = event_view;
return;
}
grab_handles_.SetAttachedView(nullptr);
if (event_view == designer_panel_) {
SelectView(nullptr);
return;
}
SelectView(event_view);
dragging_ = selected_;
last_mouse_pos_ = mouse_event->location();
event->SetHandled();
return;
}
break;
case ui::ET_MOUSE_DRAGGED:
if (dragging_) {
if (grab_handles_.IsGrabHandle(dragging_))
return;
gfx::Point new_position =
selected_->origin() +
SnapToGrid(mouse_event->location() - last_mouse_pos_);
new_position.SetToMax(gfx::Point());
new_position.SetToMin(designer_panel_->GetLocalBounds().bottom_right() -
gfx::Vector2d(dragging_->size().width(),
dragging_->size().height()));
dragging_->SetPosition(new_position);
event->SetHandled();
return;
}
break;
case ui::ET_MOUSE_RELEASED:
grab_handles_.SetAttachedView(selected_);
if (dragging_) {
bool dragging_handle = grab_handles_.IsGrabHandle(dragging_);
dragging_ = nullptr;
if (!dragging_handle)
event->SetHandled();
return;
}
break;
default:
return;
}
}
void DesignerExample::SelectView(View* view) {
if (view != selected_) {
selected_ = view;
selected_members_.clear();
if (selected_) {
for (auto* member : *selected_->GetClassMetaData())
selected_members_.push_back(member);
}
if (model_observer_)
model_observer_->OnModelChanged();
}
}
gfx::Vector2d DesignerExample::SnapToGrid(const gfx::Vector2d& distance) {
return gfx::Vector2d(
SnapToInterval(distance.x(), designer_panel_->GetGridSize()),
SnapToInterval(distance.y(), designer_panel_->GetGridSize()));
}
void DesignerExample::CreateView(const ui::Event& event) {
std::unique_ptr<View> new_view =
class_registrations_[view_type_->GetSelectedRow().value()]->CreateView();
new_view->SizeToPreferredSize();
gfx::Rect child_rect = designer_panel_->GetContentsBounds();
child_rect.ClampToCenteredSize(new_view->size());
child_rect.set_origin(gfx::Point() +
SnapToGrid(child_rect.OffsetFromOrigin()));
new_view->SetBoundsRect(child_rect);
designer_panel_->AddChildView(std::move(new_view));
}
size_t DesignerExample::RowCount() {
return selected_ ? selected_members_.size() : 0;
}
std::u16string DesignerExample::GetText(size_t row, int column_id) {
if (selected_) {
ui::metadata::MemberMetaDataBase* member = selected_members_[row];
if (column_id == 0)
return base::ASCIIToUTF16(member->member_name());
return member->GetValueAsString(selected_);
}
return std::u16string();
}
void DesignerExample::SetObserver(ui::TableModelObserver* observer) {
model_observer_ = observer;
}
size_t DesignerExample::GetItemCount() const {
return class_registrations_.size();
}
std::u16string DesignerExample::GetItemAt(size_t index) const {
return class_registrations_[index]->GetViewClassName();
}
absl::optional<size_t> DesignerExample::GetDefaultIndex() const {
return 0;
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/designer_example.cc | C++ | unknown | 22,116 |
// 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_EXAMPLES_DESIGNER_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_DESIGNER_EXAMPLE_H_
#include <memory>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/models/table_model.h"
#include "ui/events/event_handler.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/examples/example_base.h"
#include "ui/views/masked_targeter_delegate.h"
#include "ui/views/view.h"
#include "ui/views/view_tracker.h"
namespace ui {
class Event;
}
namespace gfx {
class Vector2d;
}
namespace views {
class BoxLayoutView;
class Combobox;
class TableView;
namespace examples {
class DesignerSurface;
class BaseClassRegistration {
public:
virtual ~BaseClassRegistration();
virtual std::unique_ptr<View> CreateView() = 0;
virtual std::u16string GetViewClassName() = 0;
};
// DesignerExample. Demonstrates a simple visual designer for creating, placing,
// moving and sizing individual views on a surface.
class VIEWS_EXAMPLES_EXPORT DesignerExample : public ExampleBase,
public ui::TableModel,
public ui::ComboboxModel,
public ui::EventHandler {
public:
enum GrabHandlePosition : int {
kTop = 0x01,
kBottom = 0x02,
kLeft = 0x04,
kRight = 0x08,
kTopLeft = kTop | kLeft,
kTopRight = kTop | kRight,
kBottomLeft = kBottom | kLeft,
kBottomRight = kBottom | kRight,
};
static constexpr int kGrabHandleSize = 8;
class GrabHandles;
class GrabHandle : public View {
public:
METADATA_HEADER(GrabHandle);
GrabHandle(GrabHandles* grab_handles, GrabHandlePosition position);
GrabHandle(const GrabHandle&) = delete;
GrabHandle& operator=(const GrabHandle&) = delete;
~GrabHandle() override;
void SetAttachedView(View* view);
View* attached_view() { return attached_view_; }
const View* attached_view() const { return attached_view_; }
GrabHandlePosition position() const { return position_; }
void UpdatePosition(bool reorder);
protected:
// View overrides.
ui::Cursor GetCursor(const ui::MouseEvent& event) override;
gfx::Size CalculatePreferredSize() const override;
void OnPaint(gfx::Canvas* canvas) override;
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
private:
friend class DesignerExample;
void PositionOnView();
void UpdateViewSize();
static bool IsTop(GrabHandlePosition position);
static bool IsBottom(GrabHandlePosition position);
static bool IsLeft(GrabHandlePosition position);
static bool IsRight(GrabHandlePosition position);
GrabHandlePosition position_;
raw_ptr<GrabHandles> grab_handles_;
raw_ptr<View> attached_view_ = nullptr;
gfx::Point mouse_drag_pos_;
};
class GrabHandles {
public:
GrabHandles();
~GrabHandles();
void Initialize(View* layout_panel);
void SetAttachedView(View* view);
bool IsGrabHandle(View* view);
private:
std::vector<GrabHandle*> grab_handles_;
};
DesignerExample();
DesignerExample(const DesignerExample&) = delete;
DesignerExample& operator=(const DesignerExample&) = delete;
~DesignerExample() override;
protected:
// ExampleBase overrides
void CreateExampleView(View* container) override;
// ui::EventHandler overrides
void OnEvent(ui::Event* event) override;
private:
void HandleDesignerMouseEvent(ui::Event* event);
void SelectView(View* view);
gfx::Vector2d SnapToGrid(const gfx::Vector2d& distance);
// Creates the selected view class.
void CreateView(const ui::Event& event);
// ui::TableModel overrides
size_t RowCount() override;
std::u16string GetText(size_t row, int column_id) override;
void SetObserver(ui::TableModelObserver* observer) override;
// ui::ComboboxModel overrides
size_t GetItemCount() const override;
std::u16string GetItemAt(size_t index) const override;
absl::optional<size_t> GetDefaultIndex() const override;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION BoxLayoutView* designer_container_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION DesignerSurface* designer_panel_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION View* palette_panel_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Combobox* view_type_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION TableView* inspector_ = nullptr;
raw_ptr<ui::TableModelObserver> model_observer_ = nullptr;
raw_ptr<View> selected_ = nullptr;
raw_ptr<View> dragging_ = nullptr;
gfx::Point last_mouse_pos_;
std::vector<ui::metadata::MemberMetaDataBase*> selected_members_;
GrabHandles grab_handles_;
std::vector<std::unique_ptr<BaseClassRegistration>> class_registrations_;
views::ViewTracker tracker_;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_DESIGNER_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/designer_example.h | C++ | unknown | 5,754 |
// 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/examples/dialog_example.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/examples/examples_window.h"
#include "ui/views/examples/grit/views_examples_resources.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/layout/table_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views::examples {
namespace {
constexpr size_t kFakeModeless = ui::MODAL_TYPE_SYSTEM + 1;
} // namespace
template <class DialogType>
class DialogExample::Delegate : public virtual DialogType {
public:
explicit Delegate(DialogExample* parent) : parent_(parent) {
DialogDelegate::SetButtons(parent_->GetDialogButtons());
DialogDelegate::SetButtonLabel(ui::DIALOG_BUTTON_OK,
parent_->ok_button_label_->GetText());
DialogDelegate::SetButtonLabel(ui::DIALOG_BUTTON_CANCEL,
parent_->cancel_button_label_->GetText());
WidgetDelegate::SetModalType(parent_->GetModalType());
}
Delegate(const Delegate&) = delete;
Delegate& operator=(const Delegate&) = delete;
void InitDelegate() {
this->SetLayoutManager(std::make_unique<FillLayout>());
auto body = std::make_unique<Label>(parent_->body_->GetText());
body->SetMultiLine(true);
body->SetHorizontalAlignment(gfx::ALIGN_LEFT);
// Give the example code a way to change the body text.
parent_->last_body_label_ = this->AddChildView(std::move(body));
if (parent_->has_extra_button_->GetChecked()) {
DialogDelegate::SetExtraView(std::make_unique<views::MdTextButton>(
Button::PressedCallback(), parent_->extra_button_label_->GetText()));
}
}
protected:
std::u16string GetWindowTitle() const override {
return parent_->title_->GetText();
}
bool Cancel() override { return parent_->AllowDialogClose(false); }
bool Accept() override { return parent_->AllowDialogClose(true); }
private:
raw_ptr<DialogExample> parent_;
};
class DialogExample::Bubble : public Delegate<BubbleDialogDelegateView> {
public:
Bubble(DialogExample* parent, View* anchor)
: BubbleDialogDelegateView(anchor, BubbleBorder::TOP_LEFT),
Delegate(parent) {
set_close_on_deactivate(!parent->persistent_bubble_->GetChecked());
}
Bubble(const Bubble&) = delete;
Bubble& operator=(const Bubble&) = delete;
// BubbleDialogDelegateView:
void Init() override { InitDelegate(); }
};
class DialogExample::Dialog : public Delegate<DialogDelegateView> {
public:
explicit Dialog(DialogExample* parent) : Delegate(parent) {
// Mac supports resizing of modal dialogs (parent or window-modal). On other
// platforms this will be weird unless the modal type is "none", but helps
// test layout.
SetCanResize(true);
}
Dialog(const Dialog&) = delete;
Dialog& operator=(const Dialog&) = delete;
};
DialogExample::DialogExample()
: ExampleBase("Dialog"),
mode_model_({
ui::SimpleComboboxModel::Item(u"Modeless"),
ui::SimpleComboboxModel::Item(u"Window Modal"),
ui::SimpleComboboxModel::Item(u"Child Modal"),
ui::SimpleComboboxModel::Item(u"System Modal"),
ui::SimpleComboboxModel::Item(u"Fake Modeless (non-bubbles)"),
}) {}
DialogExample::~DialogExample() = default;
void DialogExample::CreateExampleView(View* container) {
auto* flex_layout =
container->SetLayoutManager(std::make_unique<FlexLayout>());
flex_layout->SetOrientation(LayoutOrientation::kVertical);
auto* table = container->AddChildView(std::make_unique<View>());
views::LayoutProvider* provider = views::LayoutProvider::Get();
const int horizontal_spacing =
provider->GetDistanceMetric(views::DISTANCE_RELATED_BUTTON_HORIZONTAL);
auto* table_layout = table->SetLayoutManager(std::make_unique<TableLayout>());
table_layout
->AddColumn(LayoutAlignment::kStart, LayoutAlignment::kStretch,
TableLayout::kFixedSize,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddPaddingColumn(TableLayout::kFixedSize, horizontal_spacing)
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch, 1.0f,
TableLayout::ColumnSize::kUsePreferred, 0, 0)
.AddPaddingColumn(TableLayout::kFixedSize, horizontal_spacing)
.AddColumn(LayoutAlignment::kStretch, LayoutAlignment::kStretch,
TableLayout::kFixedSize,
TableLayout::ColumnSize::kUsePreferred, 0, 0);
const int vertical_padding =
provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL);
for (int i = 0; i < 7; ++i) {
table_layout->AddPaddingRow(TableLayout::kFixedSize, vertical_padding)
.AddRows(1, TableLayout::kFixedSize);
}
StartTextfieldRow(
table, &title_, l10n_util::GetStringUTF16(IDS_DIALOG_TITLE_LABEL),
l10n_util::GetStringUTF16(IDS_DIALOG_TITLE_TEXT), nullptr, true);
StartTextfieldRow(
table, &body_, l10n_util::GetStringUTF16(IDS_DIALOG_BODY_LABEL),
l10n_util::GetStringUTF16(IDS_DIALOG_BODY_LABEL), nullptr, true);
Label* row_label = nullptr;
StartTextfieldRow(table, &ok_button_label_,
l10n_util::GetStringUTF16(IDS_DIALOG_OK_BUTTON_LABEL),
l10n_util::GetStringUTF16(IDS_DIALOG_OK_BUTTON_TEXT),
&row_label, false);
AddCheckbox(table, &has_ok_button_, row_label);
StartTextfieldRow(table, &cancel_button_label_,
l10n_util::GetStringUTF16(IDS_DIALOG_CANCEL_BUTTON_LABEL),
l10n_util::GetStringUTF16(IDS_DIALOG_CANCEL_BUTTON_TEXT),
&row_label, false);
AddCheckbox(table, &has_cancel_button_, row_label);
StartTextfieldRow(table, &extra_button_label_,
l10n_util::GetStringUTF16(IDS_DIALOG_EXTRA_BUTTON_LABEL),
l10n_util::GetStringUTF16(IDS_DIALOG_EXTRA_BUTTON_TEXT),
&row_label, false);
AddCheckbox(table, &has_extra_button_, row_label);
std::u16string modal_label =
l10n_util::GetStringUTF16(IDS_DIALOG_MODAL_TYPE_LABEL);
table->AddChildView(std::make_unique<Label>(modal_label));
mode_ = table->AddChildView(std::make_unique<Combobox>(&mode_model_));
mode_->SetCallback(base::BindRepeating(&DialogExample::OnPerformAction,
base::Unretained(this)));
mode_->SetSelectedIndex(ui::MODAL_TYPE_CHILD);
mode_->SetAccessibleName(modal_label);
table->AddChildView(std::make_unique<View>());
Label* bubble_label = table->AddChildView(std::make_unique<Label>(
l10n_util::GetStringUTF16(IDS_DIALOG_BUBBLE_LABEL)));
AddCheckbox(table, &bubble_, bubble_label);
AddCheckbox(table, &persistent_bubble_, nullptr);
persistent_bubble_->SetText(
l10n_util::GetStringUTF16(IDS_DIALOG_PERSISTENT_LABEL));
show_ = container->AddChildView(std::make_unique<views::MdTextButton>(
base::BindRepeating(&DialogExample::ShowButtonPressed,
base::Unretained(this)),
l10n_util::GetStringUTF16(IDS_DIALOG_SHOW_BUTTON_LABEL)));
show_->SetProperty(kCrossAxisAlignmentKey, LayoutAlignment::kCenter);
show_->SetProperty(
kMarginsKey,
gfx::Insets::TLBR(provider->GetDistanceMetric(
views::DISTANCE_UNRELATED_CONTROL_VERTICAL),
0, 0, 0));
}
void DialogExample::StartTextfieldRow(View* parent,
Textfield** member,
std::u16string label,
std::u16string value,
Label** created_label,
bool pad_last_col) {
Label* row_label = parent->AddChildView(std::make_unique<Label>(label));
if (created_label)
*created_label = row_label;
auto textfield = std::make_unique<Textfield>();
textfield->set_controller(this);
textfield->SetText(value);
textfield->SetAccessibleName(row_label);
*member = parent->AddChildView(std::move(textfield));
if (pad_last_col)
parent->AddChildView(std::make_unique<View>());
}
void DialogExample::AddCheckbox(View* parent, Checkbox** member, Label* label) {
auto callback = member == &bubble_ ? &DialogExample::BubbleCheckboxPressed
: &DialogExample::OtherCheckboxPressed;
auto checkbox = std::make_unique<Checkbox>(
std::u16string(), base::BindRepeating(callback, base::Unretained(this)));
checkbox->SetChecked(true);
if (label)
checkbox->SetAccessibleName(label);
*member = parent->AddChildView(std::move(checkbox));
}
ui::ModalType DialogExample::GetModalType() const {
// "Fake" modeless happens when a DialogDelegate specifies window-modal, but
// doesn't provide a parent window.
// TODO(ellyjones): This doesn't work on Mac at all - something should happen
// other than changing modality on the fly like this. In fact, it should be
// impossible to change modality in a live dialog at all, and this example
// should stop doing it.
if (mode_->GetSelectedIndex() == kFakeModeless)
return ui::MODAL_TYPE_WINDOW;
return static_cast<ui::ModalType>(mode_->GetSelectedIndex().value());
}
int DialogExample::GetDialogButtons() const {
int buttons = 0;
if (has_ok_button_->GetChecked())
buttons |= ui::DIALOG_BUTTON_OK;
if (has_cancel_button_->GetChecked())
buttons |= ui::DIALOG_BUTTON_CANCEL;
return buttons;
}
bool DialogExample::AllowDialogClose(bool accept) {
PrintStatus("Dialog closed with %s.", accept ? "Accept" : "Cancel");
last_dialog_ = nullptr;
last_body_label_ = nullptr;
return true;
}
void DialogExample::ResizeDialog() {
DCHECK(last_dialog_);
Widget* widget = last_dialog_->GetWidget();
gfx::Rect preferred_bounds(widget->GetRestoredBounds());
preferred_bounds.set_size(widget->non_client_view()->GetPreferredSize());
// Q: Do we need NonClientFrameView::GetWindowBoundsForClientBounds() here?
// A: When DialogCientView properly feeds back sizes, we do not.
widget->SetBoundsConstrained(preferred_bounds);
// For user-resizable dialogs, ensure the window manager enforces any new
// minimum size.
widget->OnSizeConstraintsChanged();
}
void DialogExample::ShowButtonPressed() {
if (bubble_->GetChecked()) {
// |bubble| will be destroyed by its widget when the widget is destroyed.
Bubble* bubble = new Bubble(this, show_);
last_dialog_ = bubble;
BubbleDialogDelegateView::CreateBubble(bubble);
} else {
// |dialog| will be destroyed by its widget when the widget is destroyed.
Dialog* dialog = new Dialog(this);
last_dialog_ = dialog;
dialog->InitDelegate();
// constrained_window::CreateBrowserModalDialogViews() allows dialogs to
// be created as MODAL_TYPE_WINDOW without specifying a parent.
gfx::NativeView parent = nullptr;
if (mode_->GetSelectedIndex() != kFakeModeless)
parent = example_view()->GetWidget()->GetNativeView();
DialogDelegate::CreateDialogWidget(
dialog, example_view()->GetWidget()->GetNativeWindow(), parent);
}
last_dialog_->GetWidget()->Show();
}
void DialogExample::BubbleCheckboxPressed() {
if (bubble_->GetChecked() && GetModalType() != ui::MODAL_TYPE_CHILD) {
mode_->SetSelectedIndex(ui::MODAL_TYPE_CHILD);
LogStatus("You nearly always want Child Modal for bubbles.");
}
persistent_bubble_->SetEnabled(bubble_->GetChecked());
OnPerformAction(); // Validate the modal type.
if (!bubble_->GetChecked() && GetModalType() == ui::MODAL_TYPE_CHILD) {
// Do something reasonable when simply unchecking bubble and re-enable.
mode_->SetSelectedIndex(ui::MODAL_TYPE_WINDOW);
OnPerformAction();
}
}
void DialogExample::OtherCheckboxPressed() {
// Buttons other than show and bubble are pressed. They are all checkboxes.
// Update the dialog if there is one.
if (last_dialog_) {
// TODO(crbug.com/1261666): This can segfault.
last_dialog_->DialogModelChanged();
ResizeDialog();
}
}
void DialogExample::ContentsChanged(Textfield* sender,
const std::u16string& new_contents) {
if (!last_dialog_)
return;
if (sender == extra_button_label_)
LogStatus("DialogDelegate can never refresh the extra view.");
if (sender == title_) {
last_dialog_->GetWidget()->UpdateWindowTitle();
} else if (sender == body_) {
last_body_label_->SetText(new_contents);
} else {
last_dialog_->DialogModelChanged();
}
ResizeDialog();
}
void DialogExample::OnPerformAction() {
bool enable = bubble_->GetChecked() || GetModalType() != ui::MODAL_TYPE_CHILD;
#if BUILDFLAG(IS_MAC)
enable = enable && GetModalType() != ui::MODAL_TYPE_SYSTEM;
#endif
show_->SetEnabled(enable);
if (!enable && GetModalType() == ui::MODAL_TYPE_CHILD)
LogStatus("MODAL_TYPE_CHILD can't be used with non-bubbles.");
if (!enable && GetModalType() == ui::MODAL_TYPE_SYSTEM)
LogStatus("MODAL_TYPE_SYSTEM isn't supported on Mac.");
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/dialog_example.cc | C++ | unknown | 13,781 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_DIALOG_EXAMPLE_H_
#define UI_VIEWS_EXAMPLES_DIALOG_EXAMPLE_H_
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/base/models/simple_combobox_model.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/examples/example_base.h"
namespace views {
class Checkbox;
class Combobox;
class DialogDelegate;
class Label;
class LabelButton;
class Textfield;
class View;
namespace examples {
// An example that exercises BubbleDialogDelegateView or DialogDelegateView.
class VIEWS_EXAMPLES_EXPORT DialogExample : public ExampleBase,
public TextfieldController {
public:
DialogExample();
DialogExample(const DialogExample&) = delete;
DialogExample& operator=(const DialogExample&) = delete;
~DialogExample() override;
// ExampleBase:
void CreateExampleView(View* container) override;
private:
template <class>
class Delegate;
class Bubble;
class Dialog;
// Helper methods to setup the configuration Views.
void StartTextfieldRow(View* parent,
Textfield** member,
std::u16string label,
std::u16string value,
Label** created_label = nullptr,
bool pad_last_col = false);
void AddCheckbox(View* parent, Checkbox** member, Label* label);
// Checkbox callback
void OnPerformAction();
// Interrogates the configuration Views for DialogDelegate.
ui::ModalType GetModalType() const;
int GetDialogButtons() const;
// Invoked when the dialog is closing.
bool AllowDialogClose(bool accept);
// Resize the dialog Widget to match the preferred size. Triggers Layout().
void ResizeDialog();
void ShowButtonPressed();
void BubbleCheckboxPressed();
void OtherCheckboxPressed();
// TextfieldController:
void ContentsChanged(Textfield* sender,
const std::u16string& new_contents) override;
raw_ptr<DialogDelegate> last_dialog_ = nullptr;
raw_ptr<Label> last_body_label_ = nullptr;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* title_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* body_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* ok_button_label_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Checkbox* has_ok_button_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* cancel_button_label_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Checkbox* has_cancel_button_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Textfield* extra_button_label_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Checkbox* has_extra_button_;
raw_ptr<Combobox> mode_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Checkbox* bubble_;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION Checkbox* persistent_bubble_;
raw_ptr<LabelButton> show_;
ui::SimpleComboboxModel mode_model_;
};
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_DIALOG_EXAMPLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/dialog_example.h | C++ | unknown | 3,892 |
// 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/examples/example_base.h"
#include "ui/views/view.h"
namespace views::examples {
ExampleBase::~ExampleBase() = default;
ExampleBase::ExampleBase(const char* title) : example_title_(title) {}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/example_base.cc | C++ | unknown | 390 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_
#define UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_
#include <memory>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/views/examples/views_examples_export.h"
namespace views {
class View;
namespace examples {
class VIEWS_EXAMPLES_EXPORT ExampleBase {
public:
ExampleBase(const ExampleBase&) = delete;
ExampleBase& operator=(const ExampleBase&) = delete;
virtual ~ExampleBase();
// Sub-classes should creates and add the views to the given parent.
virtual void CreateExampleView(View* parent) = 0;
const std::string& example_title() const { return example_title_; }
raw_ptr<View> example_view() { return container_; }
void SetContainer(View* container) { container_ = container; }
protected:
explicit ExampleBase(const char* title);
private:
// Name of the example - used as title in the side panel.
std::string example_title_;
// The view that contains the views example.
// The tab of the respective view in the tabbed pane owns the view.
raw_ptr<View> container_;
};
using ExampleVector = std::vector<std::unique_ptr<ExampleBase>>;
} // namespace examples
} // namespace views
#endif // UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/example_base.h | C++ | unknown | 1,381 |
// 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/examples/example_combobox_model.h"
#include "base/strings/utf_string_conversions.h"
namespace views::examples {
ExampleComboboxModel::ExampleComboboxModel(const char* const* strings,
size_t count)
: strings_(strings), count_(count) {}
ExampleComboboxModel::~ExampleComboboxModel() = default;
size_t ExampleComboboxModel::GetItemCount() const {
return count_;
}
std::u16string ExampleComboboxModel::GetItemAt(size_t index) const {
return base::ASCIIToUTF16(strings_[index]);
}
} // namespace views::examples
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/example_combobox_model.cc | C++ | unknown | 729 |
// 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_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_
#define UI_VIEWS_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_
#include "base/memory/raw_ptr.h"
#include "ui/base/models/combobox_model.h"
namespace views::examples {
class ExampleComboboxModel : public ui::ComboboxModel {
public:
ExampleComboboxModel(const char* const* strings, size_t count);
ExampleComboboxModel(const ExampleComboboxModel&) = delete;
ExampleComboboxModel& operator=(const ExampleComboboxModel&) = delete;
~ExampleComboboxModel() override;
// ui::ComboboxModel:
size_t GetItemCount() const override;
std::u16string GetItemAt(size_t index) const override;
private:
const raw_ptr<const char* const> strings_;
const size_t count_;
};
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/example_combobox_model.h | C++ | unknown | 952 |
// 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_EXAMPLES_EXAMPLES_COLOR_ID_H_
#define UI_VIEWS_EXAMPLES_EXAMPLES_COLOR_ID_H_
#include "ui/color/color_id.h"
// clang-format off
#define EXAMPLES_COLOR_IDS \
E_CPONLY(kColorAnimatedImageViewExampleBorder, , kColorExamplesStart) \
E_CPONLY(kColorAnimationExampleForeground) \
E_CPONLY(kColorAnimationExampleBackground) \
E_CPONLY(kColorAccessibilityExampleBackground) \
E_CPONLY(kColorBubbleExampleBackground1) \
E_CPONLY(kColorBubbleExampleBackground2) \
E_CPONLY(kColorBubbleExampleBackground3) \
E_CPONLY(kColorBubbleExampleBackground4) \
E_CPONLY(kColorButtonBackgroundFab) \
E_CPONLY(kColorDesignerGrabHandle) \
E_CPONLY(kColorDesignerGrid) \
E_CPONLY(kColorFadeAnimationExampleBackground) \
E_CPONLY(kColorFadeAnimationExampleBorder) \
E_CPONLY(kColorFadeAnimationExampleForeground) \
E_CPONLY(kColorInkDropExampleBase) \
E_CPONLY(kColorInkDropExampleBorder) \
E_CPONLY(kColorLabelExampleBorder) \
E_CPONLY(kColorLabelExampleBlueLabel) \
E_CPONLY(kColorLabelExampleLowerShadow) \
E_CPONLY(kColorLabelExampleUpperShadow) \
E_CPONLY(kColorLabelExampleCustomBackground) \
E_CPONLY(kColorLabelExampleCustomBorder) \
E_CPONLY(kColorLabelExampleThickBorder) \
E_CPONLY(kColorMenuButtonExampleBorder) \
E_CPONLY(kColorMultilineExampleBorder) \
E_CPONLY(kColorMultilineExampleColorRange) \
E_CPONLY(kColorMultilineExampleForeground) \
E_CPONLY(kColorMultilineExampleLabelBorder) \
E_CPONLY(kColorMultilineExampleSelectionBackground) \
E_CPONLY(kColorMultilineExampleSelectionForeground) \
E_CPONLY(kColorNotificationExampleImage) \
E_CPONLY(kColorScrollViewExampleBigSquareFrom) \
E_CPONLY(kColorScrollViewExampleBigSquareTo) \
E_CPONLY(kColorScrollViewExampleSmallSquareFrom) \
E_CPONLY(kColorScrollViewExampleSmallSquareTo) \
E_CPONLY(kColorScrollViewExampleTallFrom) \
E_CPONLY(kColorScrollViewExampleTallTo) \
E_CPONLY(kColorScrollViewExampleWideFrom) \
E_CPONLY(kColorScrollViewExampleWideTo) \
E_CPONLY(kColorTableExampleEvenRowIcon) \
E_CPONLY(kColorTableExampleOddRowIcon) \
E_CPONLY(kColorTextfieldExampleBigRange) \
E_CPONLY(kColorTextfieldExampleName) \
E_CPONLY(kColorTextfieldExampleSmallRange) \
E_CPONLY(kColorVectorExampleImageBorder) \
E_CPONLY(kColorWidgetExampleContentBorder) \
E_CPONLY(kColorWidgetExampleDialogBorder)
// clang-format on
namespace views::examples {
#include "ui/color/color_id_macros.inc"
// clang-format off
enum ExamplesColorIds : ui::ColorId {
// This should move the example color ids out of the range of any production
// ids.
kColorExamplesStart = ui::kUiColorsEnd + 0x8000,
EXAMPLES_COLOR_IDS
kColorExamplesEnd,
};
// clang-format on
// Note that this second include is not redundant. The second inclusion of the
// .inc file serves to undefine the macros the first inclusion defined.
#include "ui/color/color_id_macros.inc" // NOLINT
} // namespace views::examples
#endif // UI_VIEWS_EXAMPLES_EXAMPLES_COLOR_ID_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/examples/examples_color_id.h | C++ | unknown | 3,134 |