Implement ITextProvider and ITextRangeProvider for UIA (flutter/engine#38538)

* Import files from Chromium as-is

* Modify AX to compile

* Disable new untitests for now

* Formatting

* License

* License

* License

* License

* Excl files

* Update third_party/accessibility/ax/ax_node.h

Co-authored-by: Loïc Sharma <737941+loic-sharma@users.noreply.github.com>

* Update third_party/accessibility/ax/ax_node.h

Co-authored-by: Loïc Sharma <737941+loic-sharma@users.noreply.github.com>

* Typo

* Update third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.h

Co-authored-by: Loïc Sharma <737941+loic-sharma@users.noreply.github.com>

* Add clipping_behavior, tree_id

* Formatting

* Fix bad patch

* TODOs

Co-authored-by: Loïc Sharma <737941+loic-sharma@users.noreply.github.com>
This commit is contained in:
yaakovschectman
2023-01-03 09:18:46 -05:00
committed by GitHub
parent ed7aabd18f
commit 87bc194d42
21 changed files with 11203 additions and 14 deletions

View File

@@ -358,6 +358,8 @@
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_base_unittest.cc
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_mac_unittest.h
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_mac_unittest.mm
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win_unittest.cc
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win_unittest.cc
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_unittest.cc
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_unittest.h
../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_win_unittest.cc

View File

@@ -6072,6 +6072,11 @@ ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_fragment_root_
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_fragment_root_win.h + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.cc + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.h + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.cc + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.h + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.cc + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.h + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_tree_manager.h + ../../../flutter/third_party/accessibility/LICENSE
ORIGIN: ../../../flutter/third_party/accessibility/base/win/scoped_safearray.h + ../../../flutter/third_party/accessibility/LICENSE
TYPE: LicenseType.bsd
FILE: ../../../flutter/third_party/accessibility/ax/ax_active_popup.cc
@@ -6091,6 +6096,11 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_fragment_root_wi
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_fragment_root_win.h
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.cc
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.h
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.cc
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textprovider_win.h
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.cc
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.h
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_tree_manager.h
FILE: ../../../flutter/third_party/accessibility/base/win/scoped_safearray.h
----------------------------------------------------------------------------------------------------
Copyright 2019 The Chromium Authors. All rights reserved.

View File

@@ -91,6 +91,8 @@ if (enable_unittests) {
if (is_win) {
sources += [
"ax/platform/ax_fragment_root_win_unittest.cc",
"ax/platform/ax_platform_node_textprovider_win_unittest.cc",
"ax/platform/ax_platform_node_textrangeprovider_win_unittest.cc",
"ax/platform/ax_platform_node_win_unittest.cc",
"base/win/dispatch_stub.cc",
"base/win/dispatch_stub.h",

View File

@@ -17,6 +17,7 @@ source_set("ax") {
"platform/ax_platform_node_delegate.h",
"platform/ax_platform_node_delegate_base.cc",
"platform/ax_platform_node_delegate_base.h",
"platform/ax_platform_tree_manager.h",
"platform/ax_unique_id.cc",
"platform/ax_unique_id.h",
"platform/compute_attributes.cc",
@@ -92,6 +93,10 @@ source_set("ax") {
"platform/ax_fragment_root_win.h",
"platform/ax_platform_node_delegate_utils_win.cc",
"platform/ax_platform_node_delegate_utils_win.h",
"platform/ax_platform_node_textprovider_win.cc",
"platform/ax_platform_node_textprovider_win.h",
"platform/ax_platform_node_textrangeprovider_win.cc",
"platform/ax_platform_node_textrangeprovider_win.h",
"platform/ax_platform_node_win.cc",
"platform/ax_platform_node_win.h",
"platform/uia_registrar_win.cc",

View File

@@ -11,6 +11,8 @@
#include "ax_role_properties.h"
#include "ax_table_info.h"
#include "ax_tree.h"
#include "ax_tree_manager.h"
#include "ax_tree_manager_map.h"
#include "base/color_utils.h"
#include "base/string_utils.h"
@@ -1197,6 +1199,30 @@ bool AXNode::IsEmbeddedGroup() const {
return ui::IsSetLike(parent()->data().role);
}
AXNode* AXNode::GetLowestPlatformAncestor() const {
AXNode* current_node = const_cast<AXNode*>(this);
AXNode* lowest_unignored_node = current_node;
for (; lowest_unignored_node && lowest_unignored_node->IsIgnored();
lowest_unignored_node = lowest_unignored_node->parent()) {
}
// `highest_leaf_node` could be nullptr.
AXNode* highest_leaf_node = lowest_unignored_node;
// For the purposes of this method, a leaf node does not include leaves in the
// internal accessibility tree, only in the platform exposed tree.
for (AXNode* ancestor_node = lowest_unignored_node; ancestor_node;
ancestor_node = ancestor_node->GetUnignoredParent()) {
if (ancestor_node->IsLeaf())
highest_leaf_node = ancestor_node;
}
if (highest_leaf_node)
return highest_leaf_node;
if (lowest_unignored_node)
return lowest_unignored_node;
return current_node;
}
AXNode* AXNode::GetTextFieldAncestor() const {
AXNode* parent = GetUnignoredParent();
@@ -1210,4 +1236,69 @@ AXNode* AXNode::GetTextFieldAncestor() const {
return nullptr;
}
bool AXNode::IsDescendantOfCrossingTreeBoundary(const AXNode* ancestor) const {
if (!ancestor)
return false;
if (this == ancestor)
return true;
if (const AXNode* parent = GetParentCrossingTreeBoundary())
return parent->IsDescendantOfCrossingTreeBoundary(ancestor);
return false;
}
AXNode* AXNode::GetParentCrossingTreeBoundary() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
if (parent_)
return parent_;
const AXTreeManager* manager =
AXTreeManagerMap::GetInstance().GetManager(tree_->GetAXTreeID());
if (manager)
return manager->GetParentNodeFromParentTreeAsAXNode();
return nullptr;
}
AXTree::Selection AXNode::GetUnignoredSelection() const {
BASE_DCHECK(tree())
<< "Cannot retrieve the current selection if the node is not "
"attached to an accessibility tree.\n"
<< *this;
AXTree::Selection selection = tree()->GetUnignoredSelection();
// "selection.anchor_offset" and "selection.focus_ofset" might need to be
// adjusted if the anchor or the focus nodes include ignored children.
//
// TODO(nektar): Move this logic into its own "AXSelection" class and cache
// the result for faster reuse.
const AXNode* anchor = tree()->GetFromId(selection.anchor_object_id);
if (anchor && !anchor->IsLeaf()) {
BASE_DCHECK(selection.anchor_offset >= 0);
if (static_cast<size_t>(selection.anchor_offset) <
anchor->children().size()) {
const AXNode* anchor_child = anchor->children()[selection.anchor_offset];
BASE_DCHECK(anchor_child);
selection.anchor_offset =
static_cast<int>(anchor_child->GetUnignoredIndexInParent());
} else {
selection.anchor_offset =
static_cast<int>(anchor->GetUnignoredChildCount());
}
}
const AXNode* focus = tree()->GetFromId(selection.focus_object_id);
if (focus && !focus->IsLeaf()) {
BASE_DCHECK(selection.focus_offset >= 0);
if (static_cast<size_t>(selection.focus_offset) <
focus->children().size()) {
const AXNode* focus_child = focus->children()[selection.focus_offset];
BASE_DCHECK(focus_child);
selection.focus_offset =
static_cast<int>(focus_child->GetUnignoredIndexInParent());
} else {
selection.focus_offset =
static_cast<int>(focus->GetUnignoredChildCount());
}
}
return selection;
}
} // namespace ui

View File

@@ -120,6 +120,10 @@ class AX_EXPORT AXNode final {
size_t GetUnignoredChildCount() const;
AXNode* GetUnignoredChildAtIndex(size_t index) const;
AXNode* GetUnignoredParent() const;
// Gets the unignored selection from the accessibility tree, meaning the
// selection whose endpoints are on unignored nodes. (An "ignored" node is a
// node that is not exposed to platform APIs: See `IsIgnored`.)
OwnerTree::Selection GetUnignoredSelection() const;
size_t GetUnignoredIndexInParent() const;
size_t GetIndexInParent() const;
AXNode* GetFirstUnignoredChild() const;
@@ -191,6 +195,9 @@ class AX_EXPORT AXNode final {
// Return true if this object is equal to or a descendant of |ancestor|.
bool IsDescendantOf(const AXNode* ancestor) const;
bool IsDescendantOfCrossingTreeBoundary(const AXNode* ancestor) const;
AXNode* GetParentCrossingTreeBoundary() const;
// Gets the text offsets where new lines start either from the node's data or
// by computing them and caching the result.
std::vector<int> GetOrComputeLineStartOffsets();
@@ -436,6 +443,12 @@ class AX_EXPORT AXNode final {
// Finds and returns a pointer to ordered set containing node.
AXNode* GetOrderedSet() const;
// If this node is exposed to the platform's accessibility layer, returns this
// node. Otherwise, returns the lowest ancestor that is exposed to the
// platform. (See `IsLeaf` and `IsIgnored` for information on what is
// exposed to platform APIs.)
AXNode* GetLowestPlatformAncestor() const;
private:
// Computes the text offset where each line starts by traversing all child
// leaf nodes.

View File

@@ -20,6 +20,16 @@ AXEmbeddedObjectBehavior g_ax_embedded_object_behavior =
AXEmbeddedObjectBehavior::kSuppressCharacter;
#endif // defined(OS_WIN)
ScopedAXEmbeddedObjectBehaviorSetter::ScopedAXEmbeddedObjectBehaviorSetter(
AXEmbeddedObjectBehavior behavior) {
prev_behavior_ = g_ax_embedded_object_behavior;
g_ax_embedded_object_behavior = behavior;
}
ScopedAXEmbeddedObjectBehaviorSetter::~ScopedAXEmbeddedObjectBehaviorSetter() {
g_ax_embedded_object_behavior = prev_behavior_;
}
// static
AXNodePosition::AXPositionInstance AXNodePosition::CreatePosition(
const AXNode& node,
@@ -205,8 +215,9 @@ std::u16string AXNodePosition::GetText() const {
ax::mojom::StringAttribute::kName);
}
for (int i = 0; i < AnchorChildCount(); ++i)
for (int i = 0; i < AnchorChildCount(); ++i) {
text += CreateChildPositionAt(i)->GetText();
}
return text;
}
@@ -263,8 +274,9 @@ int AXNodePosition::MaxTextOffset() const {
}
int text_length = 0;
for (int i = 0; i < AnchorChildCount(); ++i)
for (int i = 0; i < AnchorChildCount(); ++i) {
text_length += CreateChildPositionAt(i)->MaxTextOffset();
}
return text_length;
}
@@ -286,9 +298,10 @@ bool AXNodePosition::IsInLineBreakingObject() const {
if (IsNullPosition())
return false;
BASE_DCHECK(GetAnchor());
return GetAnchor()->data().GetBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject) &&
!GetAnchor()->IsInListMarker();
return (GetAnchor()->data().GetBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject) &&
!GetAnchor()->IsInListMarker()) ||
GetAnchor()->data().role == ax::mojom::Role::kLineBreak;
}
ax::mojom::Role AXNodePosition::GetAnchorRole() const {

View File

@@ -105,6 +105,16 @@ enum class AXEmbeddedObjectBehavior {
// overridden for testing.
AX_EXPORT extern AXEmbeddedObjectBehavior g_ax_embedded_object_behavior;
class AX_EXPORT ScopedAXEmbeddedObjectBehaviorSetter {
public:
explicit ScopedAXEmbeddedObjectBehaviorSetter(
AXEmbeddedObjectBehavior behavior);
~ScopedAXEmbeddedObjectBehaviorSetter();
private:
AXEmbeddedObjectBehavior prev_behavior_;
};
// Forward declarations.
template <class AXPositionType, class AXNodeType>
class AXPosition;
@@ -324,8 +334,9 @@ class AXPosition {
BASE_DCHECK(GetAnchor());
// If this position is anchored to an ignored node, then consider this
// position to be ignored.
if (GetAnchor()->IsIgnored())
if (GetAnchor()->IsIgnored()) {
return true;
}
switch (kind_) {
case AXPositionKind::NULL_POSITION:
@@ -372,8 +383,9 @@ class AXPosition {
// If the corresponding leaf position is ignored, the current text
// offset will point to ignored text. Therefore, consider this position
// to be ignored.
if (!IsLeaf())
if (!IsLeaf()) {
return AsLeafTreePosition()->IsIgnored();
}
return false;
}
}
@@ -417,8 +429,9 @@ class AXPosition {
(child_index_ >= 0 && child_index_ <= AnchorChildCount())) &&
!IsInDescendantOfEmptyObject();
case AXPositionKind::TEXT_POSITION:
if (!GetAnchor() || IsInDescendantOfEmptyObject())
if (!GetAnchor() || IsInDescendantOfEmptyObject()) {
return false;
}
// For performance reasons we skip any validation of the text offset
// that involves retrieving the anchor's text, if the offset is set to
@@ -1029,8 +1042,9 @@ class AXPosition {
const AXNodeType* ancestor_anchor,
ax::mojom::MoveDirection move_direction =
ax::mojom::MoveDirection::kForward) const {
if (!ancestor_anchor)
if (!ancestor_anchor) {
return CreateNullPosition();
}
AXPositionInstance ancestor_position = Clone();
while (!ancestor_position->IsNullPosition() &&
@@ -1285,8 +1299,9 @@ class AXPosition {
}
AXPositionInstance AsLeafTextPosition() const {
if (IsNullPosition() || IsLeaf())
if (IsNullPosition() || IsLeaf()) {
return AsTextPosition();
}
// Adjust the text offset.
// No need to check for "before text" positions here because they are only
@@ -1316,7 +1331,7 @@ class AXPosition {
child_position->affinity_ = ax::mojom::TextAffinity::kUpstream;
break;
}
child_position = text_position->CreateChildPositionAt(i);
child_position = std::move(text_position->CreateChildPositionAt(i));
adjusted_offset -= max_text_offset_in_parent;
}
@@ -1902,7 +1917,7 @@ class AXPosition {
// the same as the one that would have been computed if the original
// position were at the start of the inline text box for "Line two".
const int max_text_offset = MaxTextOffset();
const int max_text_offset_in_parent =
int max_text_offset_in_parent =
IsEmbeddedObjectInParent() ? 1 : max_text_offset;
int parent_offset = AnchorTextOffsetInParent();
ax::mojom::TextAffinity parent_affinity = affinity_;
@@ -1935,6 +1950,14 @@ class AXPosition {
parent_affinity = ax::mojom::TextAffinity::kDownstream;
}
// This dummy position serves to retrieve the max text offset of the
// anchor-node in which we want to create the parent position.
AXPositionInstance dummy_position =
CreateTextPosition(tree_id, parent_id, 0, parent_affinity);
max_text_offset_in_parent = dummy_position->MaxTextOffset();
if (parent_offset > max_text_offset_in_parent) {
parent_offset = max_text_offset_in_parent;
}
AXPositionInstance parent_position = CreateTextPosition(
tree_id, parent_id, parent_offset, parent_affinity);
@@ -2061,6 +2084,7 @@ class AXPosition {
BASE_DCHECK(text_position->text_offset_ >= 0);
return text_position;
}
text_position = text_position->CreateNextLeafTextPosition();
while (!text_position->IsNullPosition() &&
(text_position->IsIgnored() || !text_position->MaxTextOffset())) {

View File

@@ -11,6 +11,7 @@
#include <utility>
#include <vector>
#include "ax_clipping_behavior.h"
#include "ax_enums.h"
#include "ax_offscreen_result.h"
#include "ax_role_properties.h"
@@ -35,6 +36,7 @@ class AXRangeRectDelegate {
AXNode::AXID node_id,
int start_offset,
int end_offset,
ui::AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) = 0;
virtual gfx::Rect GetBoundsRect(AXTreeID tree_id,
AXNode::AXID node_id,
@@ -392,7 +394,8 @@ class AXRange {
current_line_start->tree_id(),
current_line_start->anchor_id(),
current_line_start->text_offset(),
current_line_end->text_offset(), &offscreen_result)
current_line_end->text_offset(),
ui::AXClippingBehavior::kUnclipped, &offscreen_result)
: delegate->GetBoundsRect(current_line_start->tree_id(),
current_line_start->anchor_id(),
&offscreen_result);

View File

@@ -68,6 +68,7 @@ class TestAXRangeScreenRectDelegate : public AXRangeRectDelegate {
AXNode::AXID node_id,
int start_offset,
int end_offset,
ui::AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) override {
if (tree_manager_->GetTreeID() != tree_id)
return gfx::Rect();
@@ -80,7 +81,7 @@ class TestAXRangeScreenRectDelegate : public AXRangeRectDelegate {
TestAXNodeHelper::GetOrCreate(tree_manager_->GetTree(), node);
return wrapper->GetInnerTextRangeBoundsRect(
start_offset, end_offset, AXCoordinateSystem::kScreenDIPs,
AXClippingBehavior::kClipped, offscreen_result);
clipping_behavior, offscreen_result);
}
gfx::Rect GetBoundsRect(AXTreeID tree_id,

View File

@@ -7,6 +7,7 @@
#include "ax_export.h"
#include "ax_node.h"
#include "ax_tree.h"
#include "ax_tree_id.h"
namespace ui {
@@ -16,6 +17,8 @@ namespace ui {
// trees).
class AX_EXPORT AXTreeManager {
public:
virtual ~AXTreeManager() = default;
// Returns the AXNode with the given |node_id| from the tree that has the
// given |tree_id|. This allows for callers to access nodes outside of their
// own tree. Returns nullptr if |tree_id| or |node_id| is not found.
@@ -40,6 +43,8 @@ class AX_EXPORT AXTreeManager {
// hosts the current tree. Returns nullptr if this tree doesn't have a parent
// tree.
virtual AXNode* GetParentNodeFromParentTreeAsAXNode() const = 0;
virtual AXTree* GetTree() const = 0;
};
} // namespace ui

View File

@@ -416,6 +416,14 @@ class AX_EXPORT AXPlatformNodeDelegate {
// element. The default value should be false if not in testing mode.
virtual bool ShouldIgnoreHoveredStateForTesting() = 0;
// If this object is exposed to the platform's accessibility layer, returns
// this object. Otherwise, returns the platform leaf or lowest unignored
// ancestor under which this object is found.
//
// (An ignored node means that the node should not be exposed to platform
// APIs: See `IsIgnored`.)
virtual gfx::NativeViewAccessible GetLowestPlatformAncestor() const = 0;
// Creates a string representation of this delegate's data.
std::string ToString() { return GetData().ToString(); }

View File

@@ -87,6 +87,32 @@ gfx::NativeViewAccessible AXPlatformNodeDelegateBase::GetParent() {
return nullptr;
}
gfx::NativeViewAccessible
AXPlatformNodeDelegateBase::GetLowestPlatformAncestor() const {
AXPlatformNodeDelegateBase* current_delegate =
const_cast<AXPlatformNodeDelegateBase*>(this);
AXPlatformNodeDelegateBase* lowest_unignored_delegate = current_delegate;
// `highest_leaf_delegate` could be nullptr.
AXPlatformNodeDelegateBase* highest_leaf_delegate = lowest_unignored_delegate;
// For the purposes of this method, a leaf node does not include leaves in the
// internal accessibility tree, only in the platform exposed tree.
for (AXPlatformNodeDelegateBase* ancestor_delegate =
lowest_unignored_delegate;
ancestor_delegate;
ancestor_delegate = static_cast<AXPlatformNodeDelegateBase*>(
ancestor_delegate->GetParentDelegate())) {
if (ancestor_delegate->IsLeaf())
highest_leaf_delegate = ancestor_delegate;
}
if (highest_leaf_delegate)
return highest_leaf_delegate->GetNativeViewAccessible();
if (lowest_unignored_delegate)
return lowest_unignored_delegate->GetNativeViewAccessible();
return current_delegate->GetNativeViewAccessible();
}
int AXPlatformNodeDelegateBase::GetChildCount() const {
return 0;
}

View File

@@ -51,6 +51,14 @@ class AX_EXPORT AXPlatformNodeDelegateBase : public AXPlatformNodeDelegate {
// be a native accessible object implemented by another class.
gfx::NativeViewAccessible GetParent() override;
// If this object is exposed to the platform's accessibility layer, returns
// this object. Otherwise, returns the platform leaf or lowest unignored
// ancestor under which this object is found.
//
// (An ignored node means that the node should not be exposed to platform
// APIs: See `IsIgnored`.)
gfx::NativeViewAccessible GetLowestPlatformAncestor() const override;
// Get the index in parent. Typically this is the AXNode's index_in_parent_.
int GetIndexInParent() override;

View File

@@ -0,0 +1,354 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax/platform/ax_platform_node_textprovider_win.h"
#include <wrl/client.h>
#include "base/win/scoped_safearray.h"
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#define UIA_VALIDATE_TEXTPROVIDER_CALL() \
if (!owner()->GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE;
#define UIA_VALIDATE_TEXTPROVIDER_CALL_1_ARG(arg) \
if (!owner()->GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!arg) \
return E_INVALIDARG;
namespace ui {
AXPlatformNodeTextProviderWin::AXPlatformNodeTextProviderWin() {}
AXPlatformNodeTextProviderWin::~AXPlatformNodeTextProviderWin() {}
// static
AXPlatformNodeTextProviderWin* AXPlatformNodeTextProviderWin::Create(
AXPlatformNodeWin* owner) {
CComObject<AXPlatformNodeTextProviderWin>* text_provider = nullptr;
if (SUCCEEDED(CComObject<AXPlatformNodeTextProviderWin>::CreateInstance(
&text_provider))) {
BASE_DCHECK(text_provider);
text_provider->owner_ = owner;
text_provider->AddRef();
return text_provider;
}
return nullptr;
}
// static
void AXPlatformNodeTextProviderWin::CreateIUnknown(AXPlatformNodeWin* owner,
IUnknown** unknown) {
Microsoft::WRL::ComPtr<AXPlatformNodeTextProviderWin> text_provider(
Create(owner));
if (text_provider)
*unknown = text_provider.Detach();
}
//
// ITextProvider methods.
//
HRESULT AXPlatformNodeTextProviderWin::GetSelection(SAFEARRAY** selection) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*selection = nullptr;
AXPlatformNodeDelegate* delegate = owner()->GetDelegate();
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
AXPlatformNode* anchor_object =
delegate->GetFromNodeID(unignored_selection.anchor_object_id);
AXPlatformNode* focus_object =
delegate->GetFromNodeID(unignored_selection.focus_object_id);
// anchor_offset corresponds to the selection start index
// and focus_offset is where the selection ends.
auto start_offset = unignored_selection.anchor_offset;
auto end_offset = unignored_selection.focus_offset;
// If there's no selected object, return success and don't fill the SAFEARRAY.
if (!anchor_object || !focus_object)
return S_OK;
AXNodePosition::AXPositionInstance start =
anchor_object->GetDelegate()->CreateTextPositionAt(start_offset);
AXNodePosition::AXPositionInstance end =
focus_object->GetDelegate()->CreateTextPositionAt(end_offset);
BASE_DCHECK(!start->IsNullPosition());
BASE_DCHECK(!end->IsNullPosition());
// Reverse start and end if the selection goes backwards
if (*start > *end)
std::swap(start, end);
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
if (&text_range_provider == nullptr)
return E_OUTOFMEMORY;
// Since we don't support disjoint text ranges, the SAFEARRAY returned
// will always have one element
base::win::ScopedSafearray selections_to_return(
SafeArrayCreateVector(VT_UNKNOWN /* element type */, 0 /* lower bound */,
1 /* number of elements */));
if (!selections_to_return.Get())
return E_OUTOFMEMORY;
LONG index = 0;
HRESULT hr = SafeArrayPutElement(selections_to_return.Get(), &index,
text_range_provider.Get());
BASE_DCHECK(SUCCEEDED(hr));
// Since BASE_DCHECK only happens in debug builds, return immediately to
// ensure that we're not leaking the SAFEARRAY on release builds
if (FAILED(hr))
return E_FAIL;
*selection = selections_to_return.Release();
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::GetVisibleRanges(
SAFEARRAY** visible_ranges) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
const AXPlatformNodeDelegate* delegate = owner()->GetDelegate();
// Get the Clipped Frame Bounds of the current node, not from the root,
// so if this node is wrapped with overflow styles it will have the
// correct bounds
const gfx::Rect frame_rect = delegate->GetBoundsRect(
AXCoordinateSystem::kFrame, AXClippingBehavior::kClipped);
const auto start = delegate->CreateTextPositionAt(0);
const auto end = start->CreatePositionAtEndOfAnchor();
BASE_DCHECK(start->GetAnchor() == end->GetAnchor());
// SAFEARRAYs are not dynamic, so fill the visible ranges in a vector
// and then transfer to an appropriately-sized SAFEARRAY
std::vector<Microsoft::WRL::ComPtr<ITextRangeProvider>> ranges;
auto current_line_start = start->Clone();
while (!current_line_start->IsNullPosition() && *current_line_start < *end) {
auto current_line_end = current_line_start->CreateNextLineEndPosition(
AXBoundaryBehavior::CrossBoundary);
if (current_line_end->IsNullPosition() || *current_line_end > *end)
current_line_end = end->Clone();
gfx::Rect current_rect = delegate->GetInnerTextRangeBoundsRect(
current_line_start->text_offset(), current_line_end->text_offset(),
AXCoordinateSystem::kFrame, AXClippingBehavior::kUnclipped);
if (frame_rect.Contains(current_rect)) {
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
current_line_start->Clone(), current_line_end->Clone());
ranges.emplace_back(text_range_provider);
}
current_line_start = current_line_start->CreateNextLineStartPosition(
AXBoundaryBehavior::CrossBoundary);
}
base::win::ScopedSafearray scoped_visible_ranges(
SafeArrayCreateVector(VT_UNKNOWN /* element type */, 0 /* lower bound */,
ranges.size() /* number of elements */));
if (!scoped_visible_ranges.Get())
return E_OUTOFMEMORY;
LONG index = 0;
for (Microsoft::WRL::ComPtr<ITextRangeProvider>& current_provider : ranges) {
HRESULT hr = SafeArrayPutElement(scoped_visible_ranges.Get(), &index,
current_provider.Get());
BASE_DCHECK(SUCCEEDED(hr));
// Since BASE_DCHECK only happens in debug builds, return immediately to
// ensure that we're not leaking the SAFEARRAY on release builds
if (FAILED(hr))
return E_FAIL;
++index;
}
*visible_ranges = scoped_visible_ranges.Release();
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::RangeFromChild(
IRawElementProviderSimple* child,
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL_1_ARG(child);
*range = nullptr;
Microsoft::WRL::ComPtr<ui::AXPlatformNodeWin> child_platform_node;
if (!SUCCEEDED(child->QueryInterface(IID_PPV_ARGS(&child_platform_node))))
return UIA_E_INVALIDOPERATION;
if (!owner()->IsDescendant(child_platform_node.Get()))
return E_INVALIDARG;
*range = GetRangeFromChild(owner(), child_platform_node.Get());
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::RangeFromPoint(
UiaPoint uia_point,
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
gfx::Point point(uia_point.x, uia_point.y);
// Retrieve the closest accessibility node. No coordinate unit conversion is
// needed, hit testing input is also in screen coordinates.
AXPlatformNodeWin* nearest_node =
static_cast<AXPlatformNodeWin*>(owner()->NearestLeafToPoint(point));
BASE_DCHECK(nearest_node);
BASE_DCHECK(nearest_node->IsLeaf());
AXNodePosition::AXPositionInstance start, end;
start = nearest_node->GetDelegate()->CreateTextPositionAt(
nearest_node->NearestTextIndexToPoint(point));
BASE_DCHECK(!start->IsNullPosition());
end = start->Clone();
*range = AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::get_DocumentRange(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
// Get range from child, where child is the current node. In other words,
// getting the text range of the current owner AxPlatformNodeWin node.
*range = GetRangeFromChild(owner(), owner());
return S_OK;
}
HRESULT AXPlatformNodeTextProviderWin::get_SupportedTextSelection(
enum SupportedTextSelection* text_selection) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*text_selection = SupportedTextSelection_Single;
return S_OK;
}
//
// ITextEditProvider methods.
//
HRESULT AXPlatformNodeTextProviderWin::GetActiveComposition(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
return GetTextRangeProviderFromActiveComposition(range);
}
HRESULT AXPlatformNodeTextProviderWin::GetConversionTarget(
ITextRangeProvider** range) {
UIA_VALIDATE_TEXTPROVIDER_CALL();
*range = nullptr;
return GetTextRangeProviderFromActiveComposition(range);
}
ITextRangeProvider* AXPlatformNodeTextProviderWin::GetRangeFromChild(
ui::AXPlatformNodeWin* ancestor,
ui::AXPlatformNodeWin* descendant) {
BASE_DCHECK(ancestor);
BASE_DCHECK(descendant);
BASE_DCHECK(descendant->GetDelegate());
BASE_DCHECK(ancestor->IsDescendant(descendant));
// Start and end should be leaf text positions that span the beginning and end
// of text content within a node. The start position should be the directly
// first child and the end position should be the deepest last child node.
AXNodePosition::AXPositionInstance start =
descendant->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
AXNodePosition::AXPositionInstance end;
if (descendant->GetChildCount() == 0) {
end = descendant->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor()
->AsLeafTextPosition();
} else {
AXPlatformNodeBase* deepest_last_child = descendant->GetLastChild();
while (deepest_last_child && deepest_last_child->GetChildCount() > 0)
deepest_last_child = deepest_last_child->GetLastChild();
end = deepest_last_child->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor()
->AsLeafTextPosition();
}
return AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
ITextRangeProvider* AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
ui::AXPlatformNodeWin* node) {
BASE_DCHECK(node);
BASE_DCHECK(node->GetDelegate());
// Create a degenerate range positioned at the node's start.
AXNodePosition::AXPositionInstance start, end;
start = node->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
end = start->Clone();
return AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
ui::AXPlatformNodeWin* AXPlatformNodeTextProviderWin::owner() const {
return owner_.Get();
}
HRESULT
AXPlatformNodeTextProviderWin::GetTextRangeProviderFromActiveComposition(
ITextRangeProvider** range) {
*range = nullptr;
// We fetch the start and end offset of an active composition only if
// this object has focus and TSF is in composition mode.
// The offsets here refer to the character positions in a plain text
// view of the DOM tree. Ex: if the active composition in an element
// has "abc" then the range will be (0,3) in both TSF and accessibility
if ((AXPlatformNode::FromNativeViewAccessible(
owner()->GetDelegate()->GetFocus()) ==
static_cast<AXPlatformNode*>(owner())) &&
owner()->HasActiveComposition()) {
gfx::Range active_composition_offset =
owner()->GetActiveCompositionOffsets();
AXNodePosition::AXPositionInstance start =
owner()->GetDelegate()->CreateTextPositionAt(
/*offset*/ active_composition_offset.start());
AXNodePosition::AXPositionInstance end =
owner()->GetDelegate()->CreateTextPositionAt(
/*offset*/ active_composition_offset.end());
*range = AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
std::move(start), std::move(end));
}
return S_OK;
}
} // namespace ui

View File

@@ -0,0 +1,82 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_
#include <atlbase.h>
#include <atlcom.h>
#include <UIAutomationCore.h>
#include "ax/ax_node_position.h"
#include "ax/platform/ax_platform_node_win.h"
namespace ui {
class AX_EXPORT __declspec(uuid("3e1c192b-4348-45ac-8eb6-4b58eeb3dcca"))
AXPlatformNodeTextProviderWin
: public CComObjectRootEx<CComMultiThreadModel>,
public ITextEditProvider {
public:
BEGIN_COM_MAP(AXPlatformNodeTextProviderWin)
COM_INTERFACE_ENTRY(ITextProvider)
COM_INTERFACE_ENTRY(ITextEditProvider)
COM_INTERFACE_ENTRY(AXPlatformNodeTextProviderWin)
END_COM_MAP()
AXPlatformNodeTextProviderWin();
~AXPlatformNodeTextProviderWin();
static AXPlatformNodeTextProviderWin* Create(AXPlatformNodeWin* owner);
static void CreateIUnknown(AXPlatformNodeWin* owner, IUnknown** unknown);
//
// ITextProvider methods.
//
IFACEMETHODIMP GetSelection(SAFEARRAY** selection) override;
IFACEMETHODIMP GetVisibleRanges(SAFEARRAY** visible_ranges) override;
IFACEMETHODIMP RangeFromChild(IRawElementProviderSimple* child,
ITextRangeProvider** range) override;
IFACEMETHODIMP RangeFromPoint(UiaPoint point,
ITextRangeProvider** range) override;
IFACEMETHODIMP get_DocumentRange(ITextRangeProvider** range) override;
IFACEMETHODIMP get_SupportedTextSelection(
enum SupportedTextSelection* text_selection) override;
//
// ITextEditProvider methods.
//
IFACEMETHODIMP GetActiveComposition(ITextRangeProvider** range) override;
IFACEMETHODIMP GetConversionTarget(ITextRangeProvider** range) override;
// ITextProvider supporting methods.
static ITextRangeProvider* GetRangeFromChild(
ui::AXPlatformNodeWin* ancestor,
ui::AXPlatformNodeWin* descendant);
// Create a dengerate text range at the start of the specified node.
static ITextRangeProvider* CreateDegenerateRangeAtStart(
ui::AXPlatformNodeWin* node);
private:
friend class AXPlatformNodeTextProviderTest;
ui::AXPlatformNodeWin* owner() const;
HRESULT GetTextRangeProviderFromActiveComposition(ITextRangeProvider** range);
Microsoft::WRL::ComPtr<ui::AXPlatformNodeWin> owner_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTPROVIDER_WIN_H_

View File

@@ -0,0 +1,951 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax/platform/ax_platform_node_win_unittest.h"
#include <UIAutomationClient.h>
#include <UIAutomationCoreApi.h>
#include <vector>
#include "ax/ax_action_data.h"
#include "ax/platform/ax_fragment_root_win.h"
#include "ax/platform/ax_platform_node_textprovider_win.h"
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#include "ax/platform/test_ax_node_wrapper.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_safearray.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/win/wstring_conversion.h"
using Microsoft::WRL::ComPtr;
namespace ui {
// Helper macros for UIAutomation HRESULT expectations
#define EXPECT_UIA_INVALIDOPERATION(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr))
#define EXPECT_INVALIDARG(expr) \
EXPECT_EQ(static_cast<HRESULT>(E_INVALIDARG), (expr))
class AXPlatformNodeTextProviderTest : public AXPlatformNodeWinTest {
public:
AXPlatformNodeTextProviderTest() = default;
~AXPlatformNodeTextProviderTest() override = default;
AXPlatformNodeTextProviderTest(const AXPlatformNodeTextProviderTest&) =
delete;
AXPlatformNodeTextProviderTest& operator=(
const AXPlatformNodeTextProviderTest&) = delete;
protected:
void SetOwner(AXPlatformNodeWin* owner,
ITextRangeProvider* destination_range) {
ComPtr<ITextRangeProvider> destination_provider = destination_range;
ComPtr<AXPlatformNodeTextRangeProviderWin> destination_provider_interal;
destination_provider->QueryInterface(
IID_PPV_ARGS(&destination_provider_interal));
destination_provider_interal->SetOwnerForTesting(owner);
}
AXPlatformNodeWin* GetOwner(
const AXPlatformNodeTextProviderWin* text_provider) {
return text_provider->owner_.Get();
}
const AXNodePosition::AXPositionInstance& GetStart(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->start();
}
const AXNodePosition::AXPositionInstance& GetEnd(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->end();
}
};
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_CreateDegenerateRangeFromStart) {
AXNodeData text1_data;
text1_data.id = 3;
text1_data.role = ax::mojom::Role::kStaticText;
text1_data.SetName("some text");
AXNodeData text2_data;
text2_data.id = 4;
text2_data.role = ax::mojom::Role::kStaticText;
text2_data.SetName("more text");
AXNodeData link_data;
link_data.id = 2;
link_data.role = ax::mojom::Role::kLink;
link_data.child_ids = {3, 4};
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids = {2};
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, link_data, text1_data, text2_data};
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* link_node = root_node->children()[0];
AXNode* text2_node = link_node->children()[1];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> link_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(link_node);
ComPtr<IRawElementProviderSimple> text2_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(text2_node);
ComPtr<AXPlatformNodeWin> root_platform_node;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->QueryInterface(IID_PPV_ARGS(&root_platform_node)));
ComPtr<AXPlatformNodeWin> link_platform_node;
EXPECT_HRESULT_SUCCEEDED(
link_node_raw->QueryInterface(IID_PPV_ARGS(&link_platform_node)));
ComPtr<AXPlatformNodeWin> text2_platform_node;
EXPECT_HRESULT_SUCCEEDED(
text2_node_raw->QueryInterface(IID_PPV_ARGS(&text2_platform_node)));
// Degenerate range created on root node should be:
// <>some textmore text
ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
root_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
AXNodePosition::AXPositionInstance expected_start, expected_end;
expected_start = root_platform_node->GetDelegate()->CreateTextPositionAt(0);
expected_end = expected_start->Clone();
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
// Degenerate range created on link node should be:
// <>some textmore text
text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
link_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
// Degenerate range created on more text node should be:
// some text<>more text
text_range_provider =
AXPlatformNodeTextProviderWin::CreateDegenerateRangeAtStart(
text2_platform_node.Get());
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
expected_start = text2_platform_node->GetDelegate()->CreateTextPositionAt(0);
expected_end = expected_start->Clone();
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
text_content.Release();
}
TEST_F(AXPlatformNodeTextProviderTest, DISABLED_ITextProviderRangeFromChild) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData empty_text_data;
empty_text_data.id = 3;
empty_text_data.role = ax::mojom::Role::kStaticText;
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
root_data.child_ids.push_back(3);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
update.nodes.push_back(empty_text_data);
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
AXNode* empty_text_node = root_node->children()[1];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_node);
ComPtr<IRawElementProviderSimple> empty_text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(empty_text_node);
// Call RangeFromChild on the root with the text child passed in.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->RangeFromChild(text_node_raw.Get(), &text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some text"));
// Now test that the reverse relation doesn't return a valid
// ITextRangeProvider, and instead returns E_INVALIDARG.
EXPECT_HRESULT_SUCCEEDED(
text_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_INVALIDARG(
text_provider->RangeFromChild(root_node_raw.Get(), &text_range_provider));
// Now test that a child with no text returns a degenerate range.
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(text_provider->RangeFromChild(
empty_text_node_raw.Get(), &text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr empty_text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, empty_text_content.Receive()));
EXPECT_EQ(0, wcscmp(empty_text_content.Get(), L""));
// Test that passing in an object from a different instance of
// IRawElementProviderSimple than that of the valid text provider
// returns UIA_E_INVALIDOPERATION.
ComPtr<IRawElementProviderSimple> other_root_node_raw;
MockIRawElementProviderSimple::CreateMockIRawElementProviderSimple(
&other_root_node_raw);
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
EXPECT_UIA_INVALIDOPERATION(text_provider->RangeFromChild(
other_root_node_raw.Get(), &text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderRangeFromChildMultipleChildren) {
const int ROOT_ID = 1;
const int DIALOG_ID = 2;
const int DIALOG_LABEL_ID = 3;
const int DIALOG_DESCRIPTION_ID = 4;
const int BUTTON_ID = 5;
const int BUTTON_IMG_ID = 6;
const int BUTTON_TEXT_ID = 7;
const int DIALOG_DETAIL_ID = 8;
AXNodeData root;
root.id = ROOT_ID;
root.role = ax::mojom::Role::kStaticText;
root.SetName("Document");
root.child_ids = {DIALOG_ID};
AXNodeData dialog;
dialog.id = DIALOG_ID;
dialog.role = ax::mojom::Role::kDialog;
dialog.child_ids = {DIALOG_LABEL_ID, DIALOG_DESCRIPTION_ID, BUTTON_ID,
DIALOG_DETAIL_ID};
AXNodeData dialog_label;
dialog_label.id = DIALOG_LABEL_ID;
dialog_label.role = ax::mojom::Role::kStaticText;
dialog_label.SetName("Dialog label.");
AXNodeData dialog_description;
dialog_description.id = DIALOG_DESCRIPTION_ID;
dialog_description.role = ax::mojom::Role::kStaticText;
dialog_description.SetName("Dialog description.");
AXNodeData button;
button.id = BUTTON_ID;
button.role = ax::mojom::Role::kButton;
button.child_ids = {BUTTON_IMG_ID, BUTTON_TEXT_ID};
AXNodeData button_img;
button_img.id = BUTTON_IMG_ID;
button_img.role = ax::mojom::Role::kImage;
AXNodeData button_text;
button_text.id = BUTTON_TEXT_ID;
button_text.role = ax::mojom::Role::kStaticText;
button_text.SetName("ok.");
AXNodeData dialog_detail;
dialog_detail.id = DIALOG_DETAIL_ID;
dialog_detail.role = ax::mojom::Role::kStaticText;
dialog_detail.SetName("Some more detail about dialog.");
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = ROOT_ID;
update.nodes = {root, dialog, dialog_label, dialog_description,
button, button_img, button_text, dialog_detail};
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* dialog_node = root_node->children()[0];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
BASE_DCHECK(owner);
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<IRawElementProviderSimple> dialog_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(dialog_node);
// Call RangeFromChild on the root with the dialog child passed in.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(text_provider->RangeFromChild(dialog_node_raw.Get(),
&text_range_provider));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(base::WideToUTF16(text_content.Get()),
u"Dialog label.Dialog description." + kEmbeddedCharacterAsString +
u"ok.Some more detail " + u"about dialog.");
// Check the reverse relationship that GetEnclosingElement on the text range
// gives back the dialog.
ComPtr<IRawElementProviderSimple> enclosing_element;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(enclosing_element.Get(), dialog_node_raw.Get());
}
TEST_F(AXPlatformNodeTextProviderTest, DISABLED_NearestTextIndexToPoint) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kInlineTextBox;
text_data.SetName("text");
// spacing: "t-e-x---t-"
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kCharacterOffsets,
{2, 4, 8, 10});
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.relative_bounds.bounds = gfx::RectF(1, 1, 2, 2);
root_data.child_ids.push_back(2);
Init(root_data, text_data);
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
struct NearestTextIndexTestData {
AXNode* node;
struct point_offset_expected_index_pair {
int point_offset_x;
int expected_index;
};
std::vector<point_offset_expected_index_pair> test_data;
};
NearestTextIndexTestData nodes[] = {
{text_node,
{{0, 0}, {2, 0}, {3, 1}, {4, 1}, {5, 2}, {8, 2}, {9, 3}, {10, 3}}},
{root_node,
{{0, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {8, 0}, {9, 0}, {10, 0}}}};
for (auto data : nodes) {
if (!data.node->IsText() && !data.node->data().IsTextField()) {
continue;
}
ComPtr<IRawElementProviderSimple> element_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(data.node);
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(element_provider->GetPatternProvider(
UIA_TextPatternId, &text_provider));
// get internal implementation to access helper for testing
ComPtr<AXPlatformNodeTextProviderWin> platform_text_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->QueryInterface(IID_PPV_ARGS(&platform_text_provider)));
ComPtr<AXPlatformNodeWin> platform_node;
EXPECT_HRESULT_SUCCEEDED(
element_provider->QueryInterface(IID_PPV_ARGS(&platform_node)));
for (auto pair : data.test_data) {
EXPECT_EQ(pair.expected_index, platform_node->NearestTextIndexToPoint(
gfx::Point(pair.point_offset_x, 0)));
}
}
}
TEST_F(AXPlatformNodeTextProviderTest, DISABLED_ITextProviderDocumentRange) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderDocumentRangeTrailingIgnored) {
// ++1 root
// ++++2 kGenericContainer
// ++++++3 kStaticText "Hello"
// ++++4 kGenericContainer
// ++++++5 kGenericContainer
// ++++++++6 kStaticText "3.14"
// ++++7 kGenericContainer (ignored)
// ++++++8 kGenericContainer (ignored)
// ++++++++9 kStaticText "ignored"
AXNodeData root_1;
AXNodeData gc_2;
AXNodeData static_text_3;
AXNodeData gc_4;
AXNodeData gc_5;
AXNodeData static_text_6;
AXNodeData gc_7_ignored;
AXNodeData gc_8_ignored;
AXNodeData static_text_9_ignored;
root_1.id = 1;
gc_2.id = 2;
static_text_3.id = 3;
gc_4.id = 4;
gc_5.id = 5;
static_text_6.id = 6;
gc_7_ignored.id = 7;
gc_8_ignored.id = 8;
static_text_9_ignored.id = 9;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {gc_2.id, gc_4.id, gc_7_ignored.id};
root_1.SetName("Document");
gc_2.role = ax::mojom::Role::kGenericContainer;
gc_2.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds,
{static_text_3.id});
gc_2.child_ids = {static_text_3.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.SetName("Hello");
gc_4.role = ax::mojom::Role::kGenericContainer;
gc_4.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds,
{gc_5.id});
gc_4.child_ids = {gc_5.id};
gc_5.role = ax::mojom::Role::kGenericContainer;
gc_5.child_ids = {static_text_6.id};
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.SetName("3.14");
gc_7_ignored.role = ax::mojom::Role::kGenericContainer;
gc_7_ignored.child_ids = {gc_8_ignored.id};
gc_7_ignored.AddState(ax::mojom::State::kIgnored);
gc_8_ignored.role = ax::mojom::Role::kGenericContainer;
gc_8_ignored.child_ids = {static_text_9_ignored.id};
gc_8_ignored.AddState(ax::mojom::State::kIgnored);
static_text_9_ignored.role = ax::mojom::Role::kStaticText;
static_text_9_ignored.SetName("ignored");
static_text_9_ignored.AddState(ax::mojom::State::kIgnored);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes = {root_1, gc_2, static_text_3,
gc_4, gc_5, static_text_6,
gc_7_ignored, gc_8_ignored, static_text_9_ignored};
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range;
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range));
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0)->AsLeafTextPosition();
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()
->CreateTextPositionAt(0)
->CreatePositionAtEndOfAnchor();
expected_end = expected_end->AsLeafTextPosition();
EXPECT_EQ(*GetStart(text_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(text_range.Get()), *expected_end);
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderDocumentRangeNested) {
AXNodeData text_data;
text_data.id = 3;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData paragraph_data;
paragraph_data.id = 2;
paragraph_data.role = ax::mojom::Role::kParagraph;
paragraph_data.child_ids.push_back(3);
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, paragraph_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderSupportedSelection) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
Init(root_data, text_data);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &text_provider));
SupportedTextSelection text_selection_mode;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_SupportedTextSelection(&text_selection_mode));
EXPECT_EQ(text_selection_mode, SupportedTextSelection_Single);
}
TEST_F(AXPlatformNodeTextProviderTest, DISABLED_ITextProviderGetSelection) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData textbox_data;
textbox_data.id = 3;
textbox_data.role = ax::mojom::Role::kInlineTextBox;
textbox_data.SetName("textbox text");
textbox_data.AddState(ax::mojom::State::kEditable);
AXNodeData nonatomic_textfield_data;
nonatomic_textfield_data.id = 4;
nonatomic_textfield_data.role = ax::mojom::Role::kGroup;
nonatomic_textfield_data.child_ids = {5};
AXNodeData text_child_data;
text_child_data.id = 5;
text_child_data.role = ax::mojom::Role::kStaticText;
text_child_data.SetName("text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids = {2, 3, 4};
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data, textbox_data, nonatomic_textfield_data,
text_child_data};
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
base::win::ScopedSafearray selections;
root_text_provider->GetSelection(selections.Receive());
ASSERT_EQ(nullptr, selections.Get());
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
AXTreeData& selected_tree_data =
const_cast<AXTreeData&>(owner->GetDelegate()->GetTreeData());
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 0;
selected_tree_data.sel_focus_offset = 4;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
LONG ubound;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
LONG lbound;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
LONG index = 0;
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify that start and end are appropriately swapped when sel_anchor_offset
// is greater than sel_focus_offset
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 4;
selected_tree_data.sel_focus_offset = 0;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify that text ranges at an insertion point returns a degenerate (empty)
// text range via textbox with sel_anchor_offset equal to sel_focus_offset
selected_tree_data.sel_focus_object_id = 3;
selected_tree_data.sel_anchor_object_id = 3;
selected_tree_data.sel_anchor_offset = 1;
selected_tree_data.sel_focus_offset = 1;
AXNode* text_edit_node = GetRootAsAXNode()->children()[1];
ComPtr<IRawElementProviderSimple> text_edit_com =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_edit_node);
ComPtr<ITextProvider> text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(text_edit_com->GetPatternProvider(
UIA_TextPatternId, &text_edit_provider));
selections.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_edit_provider->GetSelection(selections.Receive()));
EXPECT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
ComPtr<ITextRangeProvider> text_edit_range_provider;
EXPECT_HRESULT_SUCCEEDED(
SafeArrayGetElement(selections.Get(), &index,
static_cast<void**>(&text_edit_range_provider)));
SetOwner(owner, text_edit_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_edit_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0U, text_content.Length());
text_content.Reset();
selections.Reset();
text_edit_range_provider.Reset();
// Verify selections that span multiple nodes
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_focus_offset = 0;
selected_tree_data.sel_anchor_object_id = 3;
selected_tree_data.sel_anchor_offset = 12;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L"some texttextbox text"));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Verify SAFEARRAY value for degenerate selection.
selected_tree_data.sel_focus_object_id = 2;
selected_tree_data.sel_anchor_object_id = 2;
selected_tree_data.sel_anchor_offset = 1;
selected_tree_data.sel_focus_offset = 1;
root_text_provider->GetSelection(selections.Receive());
ASSERT_NE(nullptr, selections.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selections.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selections.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selections.Get(), &index, static_cast<void**>(&text_range_provider)));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_EQ(0, wcscmp(text_content.Get(), L""));
text_content.Reset();
selections.Reset();
text_range_provider.Reset();
// Removed testing logic for non-atomic text fields as we do not have this
// role.
// Now delete the tree (which will delete the associated elements) and verify
// that UIA_E_ELEMENTNOTAVAILABLE is returned when calling GetSelection on
// a dead element
DestroyTree();
EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE),
text_edit_provider->GetSelection(selections.Receive()));
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderGetActiveComposition) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<ITextEditProvider> root_text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(root_node->GetPatternProvider(
UIA_TextEditPatternId, &root_text_edit_provider));
ComPtr<ITextRangeProvider> text_range_provider;
root_text_edit_provider->GetActiveComposition(&text_range_provider);
ASSERT_EQ(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXActionData action_data;
action_data.action = ax::mojom::Action::kFocus;
action_data.target_node_id = 1;
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
owner->GetDelegate()->AccessibilityPerformAction(action_data);
const std::u16string active_composition_text = u"a";
owner->OnActiveComposition(gfx::Range(0, 1), active_composition_text, false);
root_text_edit_provider->GetActiveComposition(&text_range_provider);
ASSERT_NE(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0);
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()->CreateTextPositionAt(1);
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
}
TEST_F(AXPlatformNodeTextProviderTest,
DISABLED_ITextProviderGetConversionTarget) {
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kStaticText;
root_data.SetName("Document");
root_data.child_ids.push_back(2);
AXTreeUpdate update;
AXTreeData tree_data;
tree_data.tree_id = AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
Init(update);
ComPtr<IRawElementProviderSimple> root_node =
GetRootIRawElementProviderSimple();
ComPtr<ITextProvider> root_text_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node->GetPatternProvider(UIA_TextPatternId, &root_text_provider));
ComPtr<ITextEditProvider> root_text_edit_provider;
EXPECT_HRESULT_SUCCEEDED(root_node->GetPatternProvider(
UIA_TextEditPatternId, &root_text_edit_provider));
ComPtr<ITextRangeProvider> text_range_provider;
root_text_edit_provider->GetConversionTarget(&text_range_provider);
ASSERT_EQ(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextProviderWin> root_platform_node;
root_text_provider->QueryInterface(IID_PPV_ARGS(&root_platform_node));
AXActionData action_data;
action_data.action = ax::mojom::Action::kFocus;
action_data.target_node_id = 1;
AXPlatformNodeWin* owner = GetOwner(root_platform_node.Get());
owner->GetDelegate()->AccessibilityPerformAction(action_data);
const std::u16string active_composition_text = u"a";
owner->OnActiveComposition(gfx::Range(0, 1), active_composition_text, false);
root_text_edit_provider->GetConversionTarget(&text_range_provider);
ASSERT_NE(nullptr, text_range_provider);
ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range;
AXNodePosition::AXPositionInstance expected_start =
owner->GetDelegate()->CreateTextPositionAt(0);
AXNodePosition::AXPositionInstance expected_end =
owner->GetDelegate()->CreateTextPositionAt(1);
text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range));
EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start);
EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end);
}
} // namespace ui

View File

@@ -0,0 +1,285 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_
#include <atlbase.h>
#include <atlcom.h>
#include <UIAutomationCore.h>
#include "ax/ax_node_position.h"
#include "ax/ax_tree_observer.h"
#include "ax/platform/ax_platform_node_delegate.h"
#include "ax/platform/ax_platform_node_win.h"
namespace ui {
class AX_EXPORT __declspec(uuid("3071e40d-a10d-45ff-a59f-6e8e1138e2c1"))
AXPlatformNodeTextRangeProviderWin
: public CComObjectRootEx<CComMultiThreadModel>,
public ITextRangeProvider {
public:
BEGIN_COM_MAP(AXPlatformNodeTextRangeProviderWin)
COM_INTERFACE_ENTRY(ITextRangeProvider)
COM_INTERFACE_ENTRY(AXPlatformNodeTextRangeProviderWin)
END_COM_MAP()
AXPlatformNodeTextRangeProviderWin();
~AXPlatformNodeTextRangeProviderWin();
static ITextRangeProvider* CreateTextRangeProvider(
AXNodePosition::AXPositionInstance start,
AXNodePosition::AXPositionInstance end);
// Creates an instance of the class for unit tests, where AXPlatformNodes
// cannot be queried automatically from endpoints.
static ITextRangeProvider* CreateTextRangeProviderForTesting(
AXPlatformNodeWin* owner,
AXNodePosition::AXPositionInstance start,
AXNodePosition::AXPositionInstance end);
//
// ITextRangeProvider methods.
//
IFACEMETHODIMP Clone(ITextRangeProvider** clone) override;
IFACEMETHODIMP Compare(ITextRangeProvider* other, BOOL* result) override;
IFACEMETHODIMP
CompareEndpoints(TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint,
int* result) override;
IFACEMETHODIMP ExpandToEnclosingUnit(TextUnit unit) override;
IFACEMETHODIMP
FindAttribute(TEXTATTRIBUTEID attribute_id,
VARIANT attribute_val,
BOOL is_backward,
ITextRangeProvider** result) override;
IFACEMETHODIMP
FindText(BSTR string,
BOOL backwards,
BOOL ignore_case,
ITextRangeProvider** result) override;
IFACEMETHODIMP GetAttributeValue(TEXTATTRIBUTEID attribute_id,
VARIANT* value) override;
IFACEMETHODIMP
GetBoundingRectangles(SAFEARRAY** screen_physical_pixel_rectangles) override;
IFACEMETHODIMP
GetEnclosingElement(IRawElementProviderSimple** element) override;
IFACEMETHODIMP GetText(int max_count, BSTR* text) override;
IFACEMETHODIMP Move(TextUnit unit, int count, int* units_moved) override;
IFACEMETHODIMP
MoveEndpointByUnit(TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved) override;
IFACEMETHODIMP
MoveEndpointByRange(TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint) override;
IFACEMETHODIMP Select() override;
IFACEMETHODIMP AddToSelection() override;
IFACEMETHODIMP RemoveFromSelection() override;
IFACEMETHODIMP ScrollIntoView(BOOL align_to_top) override;
IFACEMETHODIMP GetChildren(SAFEARRAY** children) override;
AXPlatformNodeWin* GetOwner() const;
void SetOwnerForTesting(AXPlatformNodeWin* owner);
private:
using AXPositionInstance = AXNodePosition::AXPositionInstance;
using AXPositionInstanceType = typename AXPositionInstance::element_type;
using AXNodeRange = AXRange<AXPositionInstanceType>;
friend class AXPlatformNodeTextRangeProviderTest;
friend class AXPlatformNodeTextProviderTest;
friend class AXRangePhysicalPixelRectDelegate;
static bool AtStartOfLinePredicate(const AXPositionInstance& position);
static bool AtEndOfLinePredicate(const AXPositionInstance& position);
static AXPositionInstance GetNextTextBoundaryPosition(
const AXPositionInstance& position,
ax::mojom::TextBoundary boundary_type,
AXBoundaryBehavior options,
ax::mojom::MoveDirection boundary_direction);
// Prefer these *Impl methods when functionality is needed internally. We
// should avoid calling external APIs internally as it will cause the
// histograms to become innaccurate.
HRESULT MoveEndpointByUnitImpl(TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved);
IFACEMETHODIMP ExpandToEnclosingUnitImpl(TextUnit unit);
std::u16string GetString(int max_count,
size_t* appended_newlines_count = nullptr);
const AXPositionInstance& start() const { return endpoints_.GetStart(); }
const AXPositionInstance& end() const { return endpoints_.GetEnd(); }
AXPlatformNodeDelegate* GetDelegate(
const AXPositionInstanceType* position) const;
AXPlatformNodeDelegate* GetDelegate(const AXTreeID tree_id,
const AXNode::AXID node_id) const;
template <typename AnchorIterator, typename ExpandMatchLambda>
HRESULT FindAttributeRange(const TEXTATTRIBUTEID text_attribute_id,
VARIANT attribute_val,
const AnchorIterator first,
const AnchorIterator last,
ExpandMatchLambda expand_match);
AXPositionInstance MoveEndpointByCharacter(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByWord(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByLine(const AXPositionInstance& endpoint,
bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByParagraph(const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByPage(const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByDocument(const AXPositionInstance& endpoint,
const int count,
int* units_moved);
AXPositionInstance MoveEndpointByUnitHelper(
const AXPositionInstance& endpoint,
const ax::mojom::TextBoundary boundary_type,
const int count,
int* units_moved);
// A text range normalization is necessary to prevent a |start_| endpoint to
// be positioned at the end of an anchor when it can be at the start of the
// next anchor. After normalization, it is guaranteed that:
// * both endpoints passed by parameter are always positioned on unignored
// anchors;
// * both endpoints passed by parameter are never between a grapheme cluster;
// * if the endpoints passed by parameter create a degenerate range, both
// endpoints are on the same anchor.
// Normalization never updates the internal endpoints directly. Instead, it
// normalizes the endpoints passed by parameter.
void NormalizeTextRange(AXPositionInstance& start, AXPositionInstance& end);
static void NormalizeAsUnignoredPosition(AXPositionInstance& position);
static void NormalizeAsUnignoredTextRange(AXPositionInstance& start,
AXPositionInstance& end);
AXPlatformNodeDelegate* GetRootDelegate(const ui::AXTreeID tree_id);
AXNode* GetSelectionCommonAnchor();
void RemoveFocusFromPreviousSelectionIfNeeded(
const AXNodeRange& new_selection);
AXPlatformNodeWin* GetPlatformNodeFromAXNode(const AXNode* node) const;
AXPlatformNodeWin* GetLowestAccessibleCommonPlatformNode() const;
bool HasTextRangeOrSelectionInAtomicTextField(
const AXPositionInstance& start_position,
const AXPositionInstance& end_position) const;
void SetStart(AXPositionInstance start);
void SetEnd(AXPositionInstance end);
static bool TextAttributeIsArrayType(TEXTATTRIBUTEID attribute_id);
static bool TextAttributeIsUiaReservedValue(
const base::win::VariantVector& vector);
static bool ShouldReleaseTextAttributeAsSafearray(
TEXTATTRIBUTEID attribute_id,
const base::win::VariantVector& vector);
Microsoft::WRL::ComPtr<AXPlatformNodeWin> owner_for_test_;
// The TextRangeEndpoints class has the responsibility of keeping the
// endpoints of the range valid or nullify them when it can't find a valid
// alternative.
//
// An endpoint can become invalid when
// A. the node it's on gets deleted,
// B. when an ancestor node gets deleted, deleting the subtree our endpoint
// is on, or
// C. when a descendant node gets deleted, potentially rendering the
// position invalid due to a smaller MaxTextOffset value (for a text
// position) or fewer child nodes (for a tree position).
//
// In all cases, our approach to resolve the endpoints to valid positions
// takes two steps:
// 1. Move the endpoint to an equivalent ancestor position before the node
// gets deleted - we can't move the position once the node it's on is
// deleted since this position would already be considered invalid.
// 2. Call AsValidPosition on that new position once the node is deleted -
// calling this function before the node gets deleted wouldn't do much
// since our position would still be considered valid at this point.
//
// Because AsValidPosition can potentially be expensive, we only want to run
// it when necessary. For this reason, we store the node ID and tree ID that
// causes the first step to happen and only run the second step in
// OnNodeDeleted for the corresponding node deletion. When OnNodeDeleted is
// called, the |start_| and |end_| endpoints have already been moved up to an
// ancestor that is still part of the tree. This is to ensure that we don't
// have to read the node/tree structure of the deleted node in that function -
// which would likely result in a crash.
//
// Both scenarios A and B are fixed by this approach (by the implementation of
// OnSubtreeWillBeDeleted), but we still have work to do to fix scenario C.
// This case, in theory, would only require the second step to ensure that the
// position is always valid but computing whether node is part of the subtree
// of the endpoint we're on would be very expensive. Furthermore, because the
// endpoints are generally on leaf nodes, the scenario is unlikely - we
// haven't heard of issues caused by this scenario yet. Eventually, we might
// be able to scope the fix to specific use cases, like when the range is on
// UIA embedded object (e.g. button, select, etc.)
//
// ***
//
// Why we can't use a ScopedObserver here:
// We tried using a ScopedObserver instead of a simple observer in this case,
// but there appears to be a problem with the lifetime of the referenced
// AXTreeManager in the ScopedObserver. The AXTreeManager can get deleted
// before the TextRangeEndpoints does, so when the destructor of the
// ScopedObserver calls ScopedObserver::RemoveAll on an already deleted
// AXTreeManager, it crashes.
class TextRangeEndpoints : public AXTreeObserver {
public:
TextRangeEndpoints();
~TextRangeEndpoints() override;
const AXPositionInstance& GetStart() const { return start_; }
const AXPositionInstance& GetEnd() const { return end_; }
void SetStart(AXPositionInstance new_start);
void SetEnd(AXPositionInstance new_end);
void AddObserver(const AXTreeID tree_id);
void RemoveObserver(const AXTreeID tree_id);
void OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) override;
void OnNodeDeleted(AXTree* tree, AXNode::AXID node_id) override;
private:
struct DeletionOfInterest {
AXTreeID tree_id;
AXNode::AXID node_id;
};
void AdjustEndpointForSubtreeDeletion(AXTree* tree,
const AXNode* const node,
bool is_start_endpoint);
AXPositionInstance start_;
AXPositionInstance end_;
std::optional<DeletionOfInterest> validation_necessary_for_start_;
std::optional<DeletionOfInterest> validation_necessary_for_end_;
};
TextRangeEndpoints endpoints_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_TEXTRANGEPROVIDER_WIN_H_

View File

@@ -0,0 +1,39 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_TREE_MANAGER_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_TREE_MANAGER_H_
#include "ax/ax_export.h"
#include "ax/ax_node.h"
#include "ax/ax_tree_id.h"
#include "ax/ax_tree_manager.h"
namespace ui {
class AXPlatformNode;
class AXPlatformNodeDelegate;
// Abstract interface for a class that owns an AXTree and manages its
// connections to other AXTrees in the same page or desktop (parent and child
// trees).
class AX_EXPORT AXPlatformTreeManager : public AXTreeManager {
public:
virtual ~AXPlatformTreeManager() = default;
// Returns an AXPlatformNode with the specified and |node_id|.
virtual AXPlatformNode* GetPlatformNodeFromTree(
const AXNode::AXID node_id) const = 0;
// Returns an AXPlatformNode that corresponds to the given |node|.
virtual AXPlatformNode* GetPlatformNodeFromTree(const AXNode& node) const = 0;
// Returns an AXPlatformNodeDelegate that corresponds to a root node
// of the accessibility tree.
virtual AXPlatformNodeDelegate* RootDelegate() const = 0;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_TREE_MANAGER_H_