File: ax_element_wrapper_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 (486 lines) | stat: -rw-r--r-- 15,550 bytes parent folder | download | duplicates (2)
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/accessibility/platform/inspect/ax_element_wrapper_mac.h"

#import <Accessibility/Accessibility.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Foundation/Foundation.h>

#include <ostream>

#include "base/apple/bridging.h"
#include "base/apple/foundation_util.h"
#include "base/apple/scoped_cftyperef.h"
#include "base/compiler_specific.h"
#include "base/containers/fixed_flat_set.h"
#include "base/debug/stack_trace.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/strings/pattern.h"
#include "base/strings/sys_string_conversions.h"
#include "ui/accessibility/platform/ax_platform_node_cocoa.h"
#include "ui/accessibility/platform/ax_private_attributes_mac.h"

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

namespace {

// AXUIElementCopyAttributeValue("AXCustomContent") returns an NSData
// that contains an NSDictionary in NSKeyedArchiver format.
// This function unpacks the array of AXCustomContents contained within.
NSArray<AXCustomContent*>* CustomContentFromArchive(NSData* archive_data) {
  NSError* error = nil;
  NSKeyedUnarchiver* unarchiver =
      [[NSKeyedUnarchiver alloc] initForReadingFromData:archive_data
                                                  error:&error];

  if (error) {
    return nil;
  }

  id contents = [unarchiver
      decodeObjectOfClasses:
          [NSSet setWithArray:@[ NSArray.class, AXCustomContent.class ]]
                     forKey:NSKeyedArchiveRootObjectKey];

  return base::apple::ObjCCast<NSArray>(contents);
}

}  // namespace

namespace ui {

constexpr char kUnsupportedObject[] =
    "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";

// static
AXElementWrapper::AXType AXElementWrapper::TypeOf(id node) {
  DCHECK(IsValidElement(node));
  if (IsNSAccessibilityElement(node)) {
    return AXType::kNSAccessibilityElement;
  }
  if (IsAXUIElement(node)) {
    return AXType::kAXUIElement;
  }
  NOTREACHED() << "Unknown accessibility object type";
}

// static
bool AXElementWrapper::IsValidElement(id node) {
  return AXElementWrapper(node).IsValidElement();
}

// static
bool AXElementWrapper::IsNSAccessibilityElement(id node) {
  return AXElementWrapper(node).IsNSAccessibilityElement();
}

// static
bool AXElementWrapper::IsAXUIElement(id node) {
  return AXElementWrapper(node).IsAXUIElement();
}

// static
std::vector<gfx::NativeViewAccessible> AXElementWrapper::ChildrenOf(
    const gfx::NativeViewAccessible node) {
  NSArray* children = AXElementWrapper(node.Get()).Children();
  std::vector<gfx::NativeViewAccessible> result;
  result.reserve(children.count);
  for (id child in children) {
    result.emplace_back(child);
  }
  return result;
}

// static
std::string AXElementWrapper::DOMIdOf(gfx::NativeViewAccessible node) {
  return AXElementWrapper(node.Get()).DOMId();
}

AXElementWrapper::AXElementWrapper(id node) : node_(node) {
  CHECK(node);
}

bool AXElementWrapper::IsValidElement() const {
  return IsNSAccessibilityElement() || IsAXUIElement();
}

bool AXElementWrapper::IsNSAccessibilityElement() const {
  return [node_ isKindOfClass:[NSAccessibilityElement class]];
}

bool AXElementWrapper::IsAXUIElement() const {
  return CFGetTypeID((__bridge CFTypeRef)node_) == AXUIElementGetTypeID();
}

id AXElementWrapper::AsId() const {
  return node_;
}

std::string AXElementWrapper::DOMId() const {
  id domid_value = *GetAttributeValue(@"AXDOMIdentifier");
  return base::SysNSStringToUTF8(static_cast<NSString*>(domid_value));
}

NSArray* AXElementWrapper::Children() const {
  if (IsNSAccessibilityElement())
    return [node_ accessibilityChildren];

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFTypeRef> children_ref;
    if ((AXUIElementCopyAttributeValue(
            (__bridge AXUIElementRef)node_, kAXChildrenAttribute,
            children_ref.InitializeInto())) == kAXErrorSuccess) {
      return base::apple::CFToNSOwnershipCast(
          (CFArrayRef)children_ref.release());
    }
    return nil;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

NSSize AXElementWrapper::Size() const {
  if (IsNSAccessibilityElement()) {
    return [node_ accessibilityFrame].size;
  }

  if (!IsAXUIElement()) {
    NOTREACHED()
        << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
  }

  id value = *GetAttributeValue(NSAccessibilitySizeAttribute);
  if (value && CFGetTypeID((__bridge CFTypeRef)value) == AXValueGetTypeID()) {
    AXValueType type = AXValueGetType((__bridge AXValueRef)value);
    if (type == kAXValueCGSizeType) {
      NSSize size;
      if (AXValueGetValue((__bridge AXValueRef)value, type, &size)) {
        return size;
      }
    }
  }
  return NSMakeSize(0, 0);
}

NSPoint AXElementWrapper::Position() const {
  if (IsNSAccessibilityElement()) {
    return [node_ accessibilityFrame].origin;
  }

  if (IsAXUIElement()) {
    id value = *GetAttributeValue(NSAccessibilityPositionAttribute);
    if (value && CFGetTypeID((__bridge CFTypeRef)value) == AXValueGetTypeID()) {
      AXValueType type = AXValueGetType((__bridge AXValueRef)value);
      if (type == kAXValueCGPointType) {
        NSPoint point;
        if (AXValueGetValue((__bridge AXValueRef)value, type, &point)) {
          return point;
        }
      }
    }
    return NSMakePoint(0, 0);
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

NSArray* AXElementWrapper::AttributeNames() const {
  if (IsNSAccessibilityElement()) {
    // The NSAccessibility protocol implementation in AXPlatformNodeCocoa no
    // longer exposes old-style attributes. Instead, it provides the
    // internalAccessibilityAttributeNames method for backward compatibility in
    // testing.
    if ([node_ isKindOfClass:[AXPlatformNodeCocoa class]]) {
      return [node_ internalAccessibilityAttributeNames];
    }
    return [node_ accessibilityAttributeNames];
  }

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref;
    AXError result = AXUIElementCopyAttributeNames(
        (__bridge AXUIElementRef)node_, attributes_ref.InitializeInto());
    if (AXSuccess(result, "AXAttributeNamesOf")) {
      return base::apple::CFToNSOwnershipCast(attributes_ref.release());
    }
    return nil;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

NSArray* AXElementWrapper::ParameterizedAttributeNames() const {
  if (IsNSAccessibilityElement()) {
    // The NSAccessibility protocol implementation in AXPlatformNodeCocoa no
    // longer exposes old-style parameterized attributes. Instead, it provides
    // the internalAccessibilityParameterizedAttributeNames method for backward
    // compatibility in testing.
    if ([node_ isKindOfClass:[AXPlatformNodeCocoa class]]) {
      return [node_ internalAccessibilityParameterizedAttributeNames];
    }
    return [node_ accessibilityParameterizedAttributeNames];
  }

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref;
    AXError result = AXUIElementCopyParameterizedAttributeNames(
        (__bridge AXUIElementRef)node_, attributes_ref.InitializeInto());
    if (AXSuccess(result, "AXParameterizedAttributeNamesOf")) {
      return base::apple::CFToNSOwnershipCast(attributes_ref.release());
    }
    return nil;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

AXOptionalNSObject AXElementWrapper::GetAttributeValue(
    NSString* attribute) const {
  if (IsNSAccessibilityElement()) {
    return AXOptionalNSObject([node_ accessibilityAttributeValue:attribute]);
  }

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFTypeRef> value_ref;
    AXError result = AXUIElementCopyAttributeValue(
        (__bridge AXUIElementRef)node_, (__bridge CFStringRef)attribute,
        value_ref.InitializeInto());

    // AXCustomContent returns an NSData which contains a NSKeyedArchiver,
    // which cannot be easily understood. Convert to NSArray of AXCustomContent
    // objects.
    if ([attribute isEqualToString:@"AXCustomContent"] &&
        result == kAXErrorSuccess &&
        CFGetTypeID(value_ref.get()) == CFDataGetTypeID()) {
      NSData* data = (__bridge NSData*)value_ref.get();
      NSArray<AXCustomContent*>* custom_contents =
          CustomContentFromArchive(data);

      return AXOptionalNSObject(custom_contents);
    }

    return ToOptional(
        (__bridge id)value_ref.get(), result,
        "AXGetAttributeValue(" + base::SysNSStringToUTF8(attribute) + ")");
  }

  return AXOptionalNSObject::Error(kUnsupportedObject);
}

AXOptionalNSObject AXElementWrapper::GetParameterizedAttributeValue(
    NSString* attribute,
    id parameter) const {
  if (IsNSAccessibilityElement())
    return AXOptionalNSObject([node_ accessibilityAttributeValue:attribute
                                                    forParameter:parameter]);

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFTypeRef> parameter_ref(
        CFBridgingRetain(parameter));
    if ([parameter isKindOfClass:[NSValue class]] &&
        !UNSAFE_TODO(strcmp([parameter objCType], @encode(NSRange)))) {
      NSRange range = [parameter rangeValue];
      parameter_ref.reset(AXValueCreate(kAXValueTypeCFRange, &range));
    }

    // Get value.
    base::apple::ScopedCFTypeRef<CFTypeRef> value_ref;
    AXError result = AXUIElementCopyParameterizedAttributeValue(
        (__bridge AXUIElementRef)node_, (__bridge CFStringRef)attribute,
        parameter_ref.get(), value_ref.InitializeInto());

    return ToOptional((__bridge id)value_ref.get(), result,
                      "GetParameterizedAttributeValue(" +
                          base::SysNSStringToUTF8(attribute) + ")");
  }

  return AXOptionalNSObject::Error(kUnsupportedObject);
}

std::optional<id> AXElementWrapper::PerformSelector(
    const std::string& selector_string) const {
  if (![node_ conformsToProtocol:@protocol(NSAccessibility)])
    return std::nullopt;

  NSString* selector_nsstring = base::SysUTF8ToNSString(selector_string);
  SEL selector = NSSelectorFromString(selector_nsstring);

  if ([node_ respondsToSelector:selector])
    return [node_ valueForKey:selector_nsstring];
  return std::nullopt;
}

std::optional<id> AXElementWrapper::PerformSelector(
    const std::string& selector_string,
    const std::string& argument_string) const {
  if (![node_ conformsToProtocol:@protocol(NSAccessibility)])
    return std::nullopt;

  SEL selector =
      NSSelectorFromString(base::SysUTF8ToNSString(selector_string + ":"));
  NSString* argument = base::SysUTF8ToNSString(argument_string);

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  if ([node_ respondsToSelector:selector])
    return [node_ performSelector:selector withObject:argument];
#pragma clang diagnostic pop
  return std::nullopt;
}

void AXElementWrapper::SetAttributeValue(NSString* attribute, id value) const {
  if (IsNSAccessibilityElement()) {
    [node_ accessibilitySetValue:value forAttribute:attribute];
    return;
  }

  if (IsAXUIElement()) {
    AXUIElementSetAttributeValue((__bridge AXUIElementRef)node_,
                                 (__bridge CFStringRef)attribute,
                                 (__bridge CFTypeRef)value);
    return;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

NSArray* AXElementWrapper::ActionNames() const {
  // The NSAccessibility protocol implementation in AXPlatformNodeCocoa no
  // longer exposes old-style actions. Instead, it provides
  // the internalAccessibilityActionNames method for backward
  // compatibility in testing.
  if (IsNSAccessibilityElement()) {
    if ([node_ isKindOfClass:[AXPlatformNodeCocoa class]]) {
      return [node_ internalAccessibilityActionNames];
    }
    return [node_ accessibilityActionNames];
  }

  if (IsAXUIElement()) {
    base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref;
    if ((AXUIElementCopyActionNames((__bridge AXUIElementRef)node_,
                                    attributes_ref.InitializeInto())) ==
        kAXErrorSuccess) {
      return base::apple::CFToNSOwnershipCast(attributes_ref.release());
    }
    return nil;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

void AXElementWrapper::PerformAction(NSString* action) const {
  if (IsNSAccessibilityElement()) {
    [node_ accessibilityPerformAction:action];
    return;
  }

  if (IsAXUIElement()) {
    AXUIElementPerformAction((__bridge AXUIElementRef)node_,
                             (__bridge CFStringRef)action);
    return;
  }

  NOTREACHED()
      << "Only AXUIElementRef and BrowserAccessibilityCocoa are supported.";
}

std::string AXElementWrapper::AXErrorMessage(AXError result,
                                             const std::string& message) const {
  if (result == kAXErrorSuccess) {
    return {};
  }

  std::string error;
  switch (result) {
    case kAXErrorAPIDisabled:
      error = "API disabled; you may need to add terminal and/or this binary "
              "to System Settings -> Privacy & Security -> Accessibility";
      break;
    case kAXErrorActionUnsupported:
      error = "action unsupported";
      break;
    case kAXErrorAttributeUnsupported:
      error = "attribute unsupported";
      break;
    case kAXErrorCannotComplete:
      error = "cannot complete";
      break;
    case kAXErrorFailure:
      error = "failure";
      break;
    case kAXErrorIllegalArgument:
      error = "illegal argument";
      break;
    case kAXErrorInvalidUIElement:
      error = "invalid UI element";
      break;
    case kAXErrorInvalidUIElementObserver:
      error = "illegal UI element observer";
      break;
    case kAXErrorNoValue:
      error = "no value";
      break;
    case kAXErrorNotEnoughPrecision:
      error = "not enough precision";
      break;
    case kAXErrorNotImplemented:
      error = "not implemented";
      break;
    case kAXErrorNotificationAlreadyRegistered:
      error = "notification already registered";
      break;
    case kAXErrorNotificationNotRegistered:
      error = "notification not registered";
      break;
    case kAXErrorNotificationUnsupported:
      error = "notification unsupported";
      break;
    case kAXErrorParameterizedAttributeUnsupported:
      error = "parameterized attribute unsupported";
      break;
    default:
      error = "unknown error";
      break;
  }
  return {message + ": " + error};
}

bool AXElementWrapper::AXSuccess(AXError result,
                                 const std::string& message) const {
  std::string message_text = AXErrorMessage(result, message);
  if (message_text.empty())
    return true;

  LOG(WARNING) << message_text;
  return false;
}

AXOptionalNSObject AXElementWrapper::ToOptional(
    id value,
    AXError result,
    const std::string& message) const {
  switch (result) {
    case kAXErrorSuccess:
      return AXOptionalNSObject(value);
    case kAXErrorNoValue:
      return AXOptionalNSObject(nil);
    default:
      return AXOptionalNSObject::Error(AXErrorMessage(result, message));
  }
}

}  // namespace ui

#pragma clang diagnostic pop