File: ax_tree_formatter_mac.mm

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (334 lines) | stat: -rw-r--r-- 11,311 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// 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/accessibility/platform/inspect/ax_tree_formatter_mac.h"

#include <string>

#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "ui/accessibility/platform/ax_platform_node_cocoa.h"
#include "ui/accessibility/platform/inspect/ax_element_wrapper_mac.h"
#include "ui/accessibility/platform/inspect/ax_inspect_scenario.h"
#include "ui/accessibility/platform/inspect/ax_inspect_utils.h"
#include "ui/accessibility/platform/inspect/ax_inspect_utils_mac.h"
#include "ui/accessibility/platform/inspect/ax_property_node.h"
#include "ui/accessibility/platform/inspect/ax_script_instruction.h"
#include "ui/accessibility/platform/inspect/ax_transform_mac.h"
#include "ui/gfx/native_widget_types.h"

// TODO(https://crbug.com/406190900): Remove this deprecation pragma.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

namespace ui {

namespace {

constexpr char kLocalPositionDictAttr[] = "LocalPosition";

constexpr char kFailedPrefix[] = "_const_ERROR:";
constexpr char kFailedToParseError[] = "_const_ERROR:FAILED_TO_PARSE";
constexpr char kNotApplicable[] = "_const_n/a";

}  // namespace

AXTreeFormatterMac::AXTreeFormatterMac() = default;

AXTreeFormatterMac::~AXTreeFormatterMac() = default;

void AXTreeFormatterMac::AddDefaultFilters(
    std::vector<AXPropertyFilter>* property_filters) {
  static NSArray* default_attributes = @[
    @"AXAutocompleteValue", @"AXDescription", @"AXRole", @"AXSubrole",
    @"AXTitle", @"AXTitleUIElement", @"AXValue"
  ];

  for (NSString* attribute : default_attributes) {
    AddPropertyFilter(property_filters, base::SysNSStringToUTF8(attribute));
  }

  if (show_ids()) {
    AddPropertyFilter(property_filters, "ChromeAXNodeId");
  }
}

base::Value::Dict AXTreeFormatterMac::BuildTree(
    AXPlatformNodeDelegate* root) const {
  DCHECK(root);
  return BuildTree(root->GetNativeViewAccessible().Get());
}

base::Value::Dict AXTreeFormatterMac::BuildTreeForSelector(
    const AXTreeSelector& selector) const {
  base::apple::ScopedCFTypeRef<AXUIElementRef> node;
  std::tie(node, std::ignore) = FindAXUIElement(selector);
  if (!node) {
    return base::Value::Dict();
  }
  return BuildTreeForAXUIElement(node.get());
}

base::Value::Dict AXTreeFormatterMac::BuildTreeForAXUIElement(
    AXUIElementRef node) const {
  return BuildTree((__bridge id)node);
}

base::Value::Dict AXTreeFormatterMac::BuildTree(id root) const {
  DCHECK(root);

  AXTreeIndexerMac indexer((gfx::NativeViewAccessible(root)));
  base::Value::Dict dict;

  AXElementWrapper ax_element(root);
  NSPoint position = ax_element.Position();
  NSSize size = ax_element.Size();
  NSRect rect = NSMakeRect(position.x, position.y, size.width, size.height);

  RecursiveBuildTree(ax_element, rect, &indexer, &dict);

  return dict;
}

std::string AXTreeFormatterMac::EvaluateScript(
    const AXTreeSelector& selector,
    const AXInspectScenario& scenario) const {
  base::apple::ScopedCFTypeRef<AXUIElementRef> root;
  std::tie(root, std::ignore) = FindAXUIElement(selector);
  if (!root)
    return "";

  std::string result =
      EvaluateScript((__bridge id)root.get(), scenario.script_instructions, 0,
                     scenario.script_instructions.size());

  return result;
}

std::string AXTreeFormatterMac::EvaluateScript(
    AXPlatformNodeDelegate* root,
    const std::vector<AXScriptInstruction>& instructions,
    size_t start_index,
    size_t end_index) const {
  return EvaluateScript(root->GetNativeViewAccessible().Get(), instructions,
                        start_index, end_index);
}

std::string AXTreeFormatterMac::EvaluateScript(
    id platform_root,
    const std::vector<AXScriptInstruction>& instructions,
    size_t start_index,
    size_t end_index) const {
  base::Value::List scripts;
  AXTreeIndexerMac indexer((gfx::NativeViewAccessible(platform_root)));
  std::map<std::string, id> storage;
  AXCallStatementInvoker invoker(&indexer, &storage);
  for (size_t index = start_index; index < end_index; index++) {
    if (instructions[index].IsComment()) {
      scripts.Append(instructions[index].AsComment());
      continue;
    }

    DCHECK(instructions[index].IsScript());
    const AXPropertyNode& property_node = instructions[index].AsScript();
    AXOptionalNSObject value = invoker.Invoke(property_node);
    if (value.IsUnsupported()) {
      continue;
    }

    base::Value result;
    if (value.IsError()) {
      result = value.HasStateText()
                   ? base::Value(kFailedPrefix + value.StateText())
                   : base::Value(kFailedToParseError);
    } else if (value.IsNotApplicable()) {
      result = base::Value(kNotApplicable);
    } else {
      result = AXNSObjectToBaseValue(*value, &indexer);
    }

    scripts.Append(property_node.ToString() + "=" + AXFormatValue(result));
  }

  std::string contents;
  for (const base::Value& script : scripts) {
    std::string line;
    WriteAttribute(true, script.GetString(), &line);
    contents += line + "\n";
  }
  return contents;
}

base::Value::Dict AXTreeFormatterMac::BuildNode(
    AXPlatformNodeDelegate* node) const {
  DCHECK(node);
  return BuildNode(node->GetNativeViewAccessible());
}

base::Value::Dict AXTreeFormatterMac::BuildNodeForSelector(
    const AXTreeSelector& selector) const {
  base::apple::ScopedCFTypeRef<AXUIElementRef> node;
  std::tie(node, std::ignore) = FindAXUIElement(selector);
  if (!node) {
    return base::Value::Dict();
  }
  return BuildNode(gfx::NativeViewAccessible((__bridge id)node.get()));
}

base::Value::Dict AXTreeFormatterMac::BuildNode(
    gfx::NativeViewAccessible node) const {
  DCHECK(node);

  AXTreeIndexerMac indexer(node);
  base::Value::Dict dict;

  AXElementWrapper ax_element(node.Get());
  NSPoint position = ax_element.Position();
  NSSize size = ax_element.Size();
  NSRect rect = NSMakeRect(position.x, position.y, size.width, size.height);

  AddProperties(ax_element, rect, &indexer, &dict);
  return dict;
}

void AXTreeFormatterMac::RecursiveBuildTree(const AXElementWrapper& ax_element,
                                            const NSRect& root_rect,
                                            const AXTreeIndexerMac* indexer,
                                            base::Value::Dict* dict) const {
  AXPlatformNodeDelegate* platform_node = ax_element.IsNSAccessibilityElement()
                                              ? [ax_element.AsId() nodeDelegate]
                                              : nullptr;

  if (platform_node && !ShouldDumpNode(*platform_node))
    return;

  AddProperties(ax_element, root_rect, indexer, dict);
  if (platform_node && !ShouldDumpChildren(*platform_node))
    return;

  NSArray* children = ax_element.Children();
  base::Value::List child_dict_list;
  for (id child in children) {
    base::Value::Dict child_dict;
    RecursiveBuildTree(AXElementWrapper{child}, root_rect, indexer,
                       &child_dict);
    child_dict_list.Append(std::move(child_dict));
  }
  dict->Set(kChildrenDictAttr, std::move(child_dict_list));
}

void AXTreeFormatterMac::AddProperties(const AXElementWrapper& ax_element,
                                       const NSRect& root_rect,
                                       const AXTreeIndexerMac* indexer,
                                       base::Value::Dict* dict) const {
  // Chromium special attributes.
  dict->Set(kLocalPositionDictAttr,
            PopulateLocalPosition(ax_element, root_rect));

  // Dump all attributes if match-all filter is specified.
  if (HasMatchAllPropertyFilter()) {
    NSArray* attributes = ax_element.AttributeNames();
    for (NSString* attribute : attributes) {
      dict->SetByDottedPath(
          base::SysNSStringToUTF8(attribute),
          AXNSObjectToBaseValue(*ax_element.GetAttributeValue(attribute),
                                indexer));
    }
    return;
  }

  // Otherwise dump attributes matching allow filters only.
  std::string line_index =
      indexer->IndexBy(gfx::NativeViewAccessible(ax_element.AsId()));
  for (const AXPropertyNode& property_node :
       PropertyFilterNodesFor(line_index)) {
    AXCallStatementInvoker invoker(ax_element.AsId(), indexer);
    AXOptionalNSObject value = invoker.Invoke(property_node);
    if (value.IsNotApplicable() || value.IsUnsupported()) {
      continue;
    }
    if (value.IsError()) {
      dict->SetByDottedPath(property_node.original_property,
                            base::Value(kFailedToParseError));
      continue;
    }
    dict->SetByDottedPath(property_node.original_property,
                          AXNSObjectToBaseValue(*value, indexer));
  }
}

base::Value::Dict AXTreeFormatterMac::PopulateLocalPosition(
    const AXElementWrapper& ax_element,
    const NSRect& root_rect) const {
  // The NSAccessibility position of an object is in global coordinates and
  // based on the lower-left corner of the object. To make this easier and
  // less confusing, convert it to local window coordinates using the top-left
  // corner when dumping the position.
  int root_top = -static_cast<int>(root_rect.origin.y + root_rect.size.height);
  int root_left = static_cast<int>(root_rect.origin.x);

  NSPoint node_position = ax_element.Position();
  NSSize node_size = ax_element.Size();

  return AXNSPointToBaseValue(NSMakePoint(
      static_cast<int>(node_position.x - root_left),
      static_cast<int>(-node_position.y - node_size.height - root_top)));
}

std::string AXTreeFormatterMac::ProcessTreeForOutput(
    const base::Value::Dict& dict) const {
  const std::string* error_value = dict.FindString("error");
  if (error_value)
    return *error_value;

  std::string line;

  // AXRole and AXSubrole have own formatting and should be listed upfront.
  std::string role_attr = base::SysNSStringToUTF8(NSAccessibilityRoleAttribute);
  const std::string* value = dict.FindString(role_attr);
  if (value) {
    WriteAttribute(true, *value, &line);
  }
  std::string subrole_attr =
      base::SysNSStringToUTF8(NSAccessibilitySubroleAttribute);
  value = dict.FindString(subrole_attr);
  if (value) {
    WriteAttribute(
        false,
        base::StringPrintf("%s=%s", subrole_attr.c_str(), value->c_str()),
        &line);
  }

  // Expose all other attributes.
  for (auto item : dict) {
    if (item.second.is_string() &&
        (item.first == role_attr || item.first == subrole_attr)) {
      continue;
    }

    // Special case: children.
    // Children are used to generate the tree
    // itself, thus no sense to expose them on each node.
    if (item.first == kChildrenDictAttr) {
      continue;
    }

    // Write formatted value.
    std::string formatted_value = AXFormatValue(item.second);
    WriteAttribute(false,
                   base::StringPrintf("%s=%s", item.first.c_str(),
                                      formatted_value.c_str()),
                   &line);
  }

  return line;
}

}  // namespace ui

#pragma clang diagnostic pop