| Flutter iOS Embedder |

SemanticsObject.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h"
6
7 #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h"
8 #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h"
9
10 FLUTTER_ASSERT_ARC
11
12 namespace {
13
14 flutter::SemanticsAction GetSemanticsActionForScrollDirection(
15 UIAccessibilityScrollDirection direction) {
16 // To describe the vertical scroll direction, UIAccessibilityScrollDirection uses the
17 // direction the scroll bar moves in and SemanticsAction uses the direction the finger
18 // moves in. However, the horizontal scroll direction matches the SemanticsAction direction.
19 // That is way the following maps vertical opposite of the SemanticsAction, but the horizontal
20 // maps directly.
21 switch (direction) {
22 case UIAccessibilityScrollDirectionRight:
23 case UIAccessibilityScrollDirectionPrevious: // TODO(abarth): Support RTL using
24 // _node.textDirection.
25 return flutter::SemanticsAction::kScrollRight;
26 case UIAccessibilityScrollDirectionLeft:
27 case UIAccessibilityScrollDirectionNext: // TODO(abarth): Support RTL using
28 // _node.textDirection.
29 return flutter::SemanticsAction::kScrollLeft;
30 case UIAccessibilityScrollDirectionUp:
31 return flutter::SemanticsAction::kScrollDown;
32 case UIAccessibilityScrollDirectionDown:
33 return flutter::SemanticsAction::kScrollUp;
34 }
35 FML_DCHECK(false); // Unreachable
36 return flutter::SemanticsAction::kScrollUp;
37 }
38
39 SkM44 GetGlobalTransform(SemanticsObject* reference) {
40 SkM44 globalTransform = [reference node].transform;
41 for (SemanticsObject* parent = [reference parent]; parent; parent = parent.parent) {
42 globalTransform = parent.node.transform * globalTransform;
43 }
44 return globalTransform;
45 }
46
47 SkPoint ApplyTransform(SkPoint& point, const SkM44& transform) {
48 SkV4 vector = transform.map(point.x(), point.y(), 0, 1);
49 return SkPoint::Make(vector.x / vector.w, vector.y / vector.w);
50 }
51
52 CGPoint ConvertPointToGlobal(SemanticsObject* reference, CGPoint local_point) {
53 SkM44 globalTransform = GetGlobalTransform(reference);
54 SkPoint point = SkPoint::Make(local_point.x, local_point.y);
55 point = ApplyTransform(point, globalTransform);
56 // `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in
57 // the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to
58 // convert.
59 UIScreen* screen = reference.bridge->view().window.screen;
60 // Screen can be nil if the FlutterView is covered by another native view.
61 CGFloat scale = (screen ?: UIScreen.mainScreen).scale;
62 auto result = CGPointMake(point.x() / scale, point.y() / scale);
63 return [reference.bridge->view() convertPoint:result toView:nil];
64 }
65
66 CGRect ConvertRectToGlobal(SemanticsObject* reference, CGRect local_rect) {
67 SkM44 globalTransform = GetGlobalTransform(reference);
68
69 SkPoint quad[4] = {
70 SkPoint::Make(local_rect.origin.x, local_rect.origin.y), // top left
71 SkPoint::Make(local_rect.origin.x + local_rect.size.width, local_rect.origin.y), // top right
72 SkPoint::Make(local_rect.origin.x + local_rect.size.width,
73 local_rect.origin.y + local_rect.size.height), // bottom right
74 SkPoint::Make(local_rect.origin.x,
75 local_rect.origin.y + local_rect.size.height) // bottom left
76 };
77 for (auto& point : quad) {
78 point = ApplyTransform(point, globalTransform);
79 }
80 SkRect rect;
81 NSCAssert(rect.setBoundsCheck(quad, 4), @"Transformed points can't form a rect");
82 rect.setBounds(quad, 4);
83
84 // `rect` is in the physical pixel coordinate system. iOS expects the accessibility frame in
85 // the logical pixel coordinate system. Therefore, we divide by the `scale` (pixel ratio) to
86 // convert.
87 UIScreen* screen = reference.bridge->view().window.screen;
88 // Screen can be nil if the FlutterView is covered by another native view.
89 CGFloat scale = (screen ?: UIScreen.mainScreen).scale;
90 auto result =
91 CGRectMake(rect.x() / scale, rect.y() / scale, rect.width() / scale, rect.height() / scale);
92 return UIAccessibilityConvertFrameToScreenCoordinates(result, reference.bridge->view());
93 }
94
95 } // namespace
96
97 @interface FlutterSwitchSemanticsObject ()
98 @property(nonatomic, retain, readonly) UISwitch* nativeSwitch;
99 @end
100
101 @implementation FlutterSwitchSemanticsObject
102
103 - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
104 uid:(int32_t)uid {
105 self = [super initWithBridge:bridge uid:uid];
106 if (self) {
107 _nativeSwitch = [[UISwitch alloc] init];
108 }
109 return self;
110 }
111
112 - (NSMethodSignature*)methodSignatureForSelector:(SEL)sel {
113 NSMethodSignature* result = [super methodSignatureForSelector:sel];
114 if (!result) {
115 result = [self.nativeSwitch methodSignatureForSelector:sel];
116 }
117 return result;
118 }
119
120 - (void)forwardInvocation:(NSInvocation*)anInvocation {
121 anInvocation.target = self.nativeSwitch;
122 [anInvocation invoke];
123 }
124
125 - (NSString*)accessibilityValue {
126 self.nativeSwitch.on = self.node.flags.isToggled == flutter::SemanticsTristate::kTrue ||
127 self.node.flags.isChecked == flutter::SemanticsCheckState::kTrue;
128
129 if (![self isAccessibilityBridgeAlive]) {
130 return nil;
131 } else {
132 return self.nativeSwitch.accessibilityValue;
133 }
134 }
135
136 - (UIAccessibilityTraits)accessibilityTraits {
137 self.nativeSwitch.enabled = self.node.flags.isEnabled == flutter::SemanticsTristate::kTrue;
138
139 return self.nativeSwitch.accessibilityTraits;
140 }
141
142 @end // FlutterSwitchSemanticsObject
143
144 @interface FlutterScrollableSemanticsObject ()
145 @property(nonatomic) FlutterSemanticsScrollView* scrollView;
146 @end
147
148 @implementation FlutterScrollableSemanticsObject
149
150 - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
151 uid:(int32_t)uid {
152 self = [super initWithBridge:bridge uid:uid];
153 if (self) {
154 _scrollView = [[FlutterSemanticsScrollView alloc] initWithSemanticsObject:self];
155 [_scrollView setShowsHorizontalScrollIndicator:NO];
156 [_scrollView setShowsVerticalScrollIndicator:NO];
157 [_scrollView setContentInset:UIEdgeInsetsZero];
158 [_scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
159 [self.bridge->view() addSubview:_scrollView];
160 }
161 return self;
162 }
163
164 - (void)dealloc {
165 [_scrollView removeFromSuperview];
166 }
167
168 - (void)accessibilityBridgeDidFinishUpdate {
169 // In order to make iOS think this UIScrollView is scrollable, the following
170 // requirements must be true.
171 // 1. contentSize must be bigger than the frame size.
172 // 2. The scrollable isAccessibilityElement must return YES
173 //
174 // Once the requirements are met, the iOS uses contentOffset to determine
175 // what scroll actions are available. e.g. If the view scrolls vertically and
176 // contentOffset is 0.0, only the scroll down action is available.
177 self.scrollView.frame = self.accessibilityFrame;
178 self.scrollView.contentSize = [self contentSizeInternal];
179 // See the documentation on `isDoingSystemScrolling`.
180 if (!self.scrollView.isDoingSystemScrolling) {
181 [self.scrollView setContentOffset:self.contentOffsetInternal animated:NO];
182 }
183 }
184
185 - (id)nativeAccessibility {
186 return self.scrollView;
187 }
188
189 // private methods
190
191 - (float)scrollExtentMax {
192 if (![self isAccessibilityBridgeAlive]) {
193 return 0.0f;
194 }
195 float scrollExtentMax = self.node.scrollExtentMax;
196 if (isnan(scrollExtentMax)) {
197 scrollExtentMax = 0.0f;
198 } else if (!isfinite(scrollExtentMax)) {
199 scrollExtentMax = kScrollExtentMaxForInf + [self scrollPosition];
200 }
201 return scrollExtentMax;
202 }
203
204 - (float)scrollPosition {
205 if (![self isAccessibilityBridgeAlive]) {
206 return 0.0f;
207 }
208 float scrollPosition = self.node.scrollPosition;
209 if (isnan(scrollPosition)) {
210 scrollPosition = 0.0f;
211 }
212 NSCAssert(isfinite(scrollPosition), @"The scrollPosition must not be infinity");
213 return scrollPosition;
214 }
215
216 - (CGSize)contentSizeInternal {
217 CGRect result;
218 const SkRect& rect = self.node.rect;
219
220 if (self.node.actions & flutter::kVerticalScrollSemanticsActions) {
221 result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height() + [self scrollExtentMax]);
222 } else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) {
223 result = CGRectMake(rect.x(), rect.y(), rect.width() + [self scrollExtentMax], rect.height());
224 } else {
225 result = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
226 }
227 return ConvertRectToGlobal(self, result).size;
228 }
229
230 - (CGPoint)contentOffsetInternal {
231 CGPoint result;
232 CGPoint origin = self.scrollView.frame.origin;
233 const SkRect& rect = self.node.rect;
234 if (self.node.actions & flutter::kVerticalScrollSemanticsActions) {
235 result = ConvertPointToGlobal(self, CGPointMake(rect.x(), rect.y() + [self scrollPosition]));
236 } else if (self.node.actions & flutter::kHorizontalScrollSemanticsActions) {
237 result = ConvertPointToGlobal(self, CGPointMake(rect.x() + [self scrollPosition], rect.y()));
238 } else {
239 result = origin;
240 }
241 return CGPointMake(result.x - origin.x, result.y - origin.y);
242 }
243
244 @end // FlutterScrollableSemanticsObject
245
246 @implementation FlutterCustomAccessibilityAction {
247 }
248 @end
249
250 @interface SemanticsObject ()
251 @property(nonatomic) SemanticsObjectContainer* container;
252
253 /** Should only be called in conjunction with setting child/parent relationship. */
254 @property(nonatomic, weak, readwrite) SemanticsObject* parent;
255
256 @end
257
258 @implementation SemanticsObject {
259 NSMutableArray<SemanticsObject*>* _children;
260 BOOL _inDealloc;
261 }
262
263 #pragma mark - Designated initializers
264
265 - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
266 uid:(int32_t)uid {
267 FML_DCHECK(bridge) << "bridge must be set";
268 FML_DCHECK(uid >= kRootNodeId);
269 // Initialize with the UIView as the container.
270 // The UIView will not necessarily be accessibility parent for this object.
271 // The bridge informs the OS of the actual structure via
272 // `accessibilityContainer` and `accessibilityElementAtIndex`.
273 self = [super initWithAccessibilityContainer:bridge->view()];
274
275 if (self) {
276 _bridge = bridge;
277 _uid = uid;
278 _children = [[NSMutableArray alloc] init];
279 _childrenInHitTestOrder = [[NSArray alloc] init];
280 }
281
282 return self;
283 }
284
285 - (void)dealloc {
286 // Set parent and children parents to nil explicitly in dealloc.
287 // -[UIAccessibilityElement dealloc] has in the past called into -accessibilityContainer
288 // and self.children. There have also been crashes related to iOS
289 // accessing methods during dealloc, and there's a lag before the tree changes.
290 // See https://github.com/flutter/engine/pull/4602 and
291 // https://github.com/flutter/engine/pull/27786.
292 for (SemanticsObject* child in _children) {
293 child.parent = nil;
294 }
295 [_children removeAllObjects];
296
297 _parent = nil;
298 _inDealloc = YES;
299 }
300
301 #pragma mark - Semantic object property accesser
302
303 - (void)setChildren:(NSArray<SemanticsObject*>*)children {
304 for (SemanticsObject* child in _children) {
305 child.parent = nil;
306 }
307 _children = [children mutableCopy];
308 for (SemanticsObject* child in _children) {
309 child.parent = self;
310 }
311 }
312
313 - (void)setChildrenInHitTestOrder:(NSArray<SemanticsObject*>*)childrenInHitTestOrder {
314 for (SemanticsObject* child in _childrenInHitTestOrder) {
315 child.parent = nil;
316 }
317 _childrenInHitTestOrder = [childrenInHitTestOrder copy];
318 for (SemanticsObject* child in _childrenInHitTestOrder) {
319 child.parent = self;
320 }
321 }
322
323 - (BOOL)hasChildren {
324 return [self.children count] != 0;
325 }
326
327 #pragma mark - Semantic object method
328
329 - (BOOL)isAccessibilityBridgeAlive {
330 return self.bridge.get() != nil;
331 }
332
333 - (void)setSemanticsNode:(const flutter::SemanticsNode*)node {
334 _node = *node;
335 }
336
337 - (void)accessibilityBridgeDidFinishUpdate { /* Do nothing by default */
338 }
339
340 /**
341 * Whether calling `setSemanticsNode:` with `node` would cause a layout change.
342 */
343 - (BOOL)nodeWillCauseLayoutChange:(const flutter::SemanticsNode*)node {
344 return self.node.rect != node->rect || self.node.transform != node->transform;
345 }
346
347 /**
348 * Whether calling `setSemanticsNode:` with `node` would cause a scroll event.
349 */
350 - (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node {
351 return !isnan(self.node.scrollPosition) && !isnan(node->scrollPosition) &&
352 self.node.scrollPosition != node->scrollPosition;
353 }
354
355 /**
356 * Whether calling `setSemanticsNode:` with `node` should trigger an
357 * announcement.
358 */
359 - (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node {
360 // The node dropped the live region flag, if it ever had one.
361 if (!node || !node->flags.isLiveRegion) {
362 return NO;
363 }
364
365 // The node has gained a new live region flag, always announce.
366 if (!self.node.flags.isLiveRegion) {
367 return YES;
368 }
369
370 // The label has updated, and the new node has a live region flag.
371 return self.node.label != node->label;
372 }
373
374 - (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child {
375 SemanticsObject* oldChild = _children[index];
376 oldChild.parent = nil;
377 child.parent = self;
378 [_children replaceObjectAtIndex:index withObject:child];
379 }
380
381 - (NSString*)routeName {
382 // Returns the first non-null and non-empty semantic label of a child
383 // with an NamesRoute flag. Otherwise returns nil.
384 if (self.node.flags.namesRoute) {
385 NSString* newName = self.accessibilityLabel;
386 if (newName != nil && [newName length] > 0) {
387 return newName;
388 }
389 }
390 if ([self hasChildren]) {
391 for (SemanticsObject* child in self.children) {
392 NSString* newName = [child routeName];
393 if (newName != nil && [newName length] > 0) {
394 return newName;
395 }
396 }
397 }
398 return nil;
399 }
400
401 - (id)nativeAccessibility {
402 return self;
403 }
404
405 - (NSAttributedString*)createAttributedStringFromString:(NSString*)string
406 withAttributes:
407 (const flutter::StringAttributes&)attributes {
408 NSMutableAttributedString* attributedString =
409 [[NSMutableAttributedString alloc] initWithString:string];
410 for (const auto& attribute : attributes) {
411 NSRange range = NSMakeRange(attribute->start, attribute->end - attribute->start);
412 switch (attribute->type) {
413 case flutter::StringAttributeType::kLocale: {
414 std::shared_ptr<flutter::LocaleStringAttribute> locale_attribute =
415 std::static_pointer_cast<flutter::LocaleStringAttribute>(attribute);
416 NSDictionary* attributeDict = @{
417 UIAccessibilitySpeechAttributeLanguage : @(locale_attribute->locale.data()),
418 };
419 [attributedString setAttributes:attributeDict range:range];
420 break;
421 }
422 case flutter::StringAttributeType::kSpellOut: {
423 NSDictionary* attributeDict = @{
424 UIAccessibilitySpeechAttributeSpellOut : @YES,
425 };
426 [attributedString setAttributes:attributeDict range:range];
427 break;
428 }
429 }
430 }
431 return attributedString;
432 }
433
434 - (void)showOnScreen {
435 self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kShowOnScreen);
436 }
437
438 #pragma mark - UIAccessibility overrides
439
440 - (BOOL)isAccessibilityElement {
441 if (![self isAccessibilityBridgeAlive]) {
442 return false;
443 }
444
445 // Note: hit detection will only apply to elements that report
446 // -isAccessibilityElement of YES. The framework will continue scanning the
447 // entire element tree looking for such a hit.
448
449 // We enforce in the framework that no other useful semantics are merged with these nodes.
450 if (self.node.flags.scopesRoute) {
451 return false;
452 }
453
454 return [self isFocusable];
455 }
456
457 - (bool)isFocusable {
458 // If the node is scrollable AND hidden OR
459 // The node has a label, value, or hint OR
460 // The node has non-scrolling related actions.
461 //
462 // The kIsHidden flag set with the scrollable flag means this node is now
463 // hidden but still is a valid target for a11y focus in the tree, e.g. a list
464 // item that is currently off screen but the a11y navigation needs to know
465 // about.
466 return (self.node.flags.hasImplicitScrolling && self.node.flags.isHidden)
467
468 || !self.node.label.empty() || !self.node.value.empty() || !self.node.hint.empty() ||
469 (self.node.actions & ~flutter::kScrollableSemanticsActions) != 0;
470 }
471
472 - (void)collectRoutes:(NSMutableArray<SemanticsObject*>*)edges {
473 if (self.node.flags.scopesRoute) {
474 [edges addObject:self];
475 }
476 if ([self hasChildren]) {
477 for (SemanticsObject* child in self.children) {
478 [child collectRoutes:edges];
479 }
480 }
481 }
482
483 - (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action {
484 if (!self.node.HasAction(flutter::SemanticsAction::kCustomAction)) {
485 return NO;
486 }
487 int32_t action_id = action.uid;
488 std::vector<uint8_t> args;
489 args.push_back(3); // type=int32.
490 args.push_back(action_id);
491 args.push_back(action_id >> 8);
492 args.push_back(action_id >> 16);
493 args.push_back(action_id >> 24);
494 self.bridge->DispatchSemanticsAction(
495 self.uid, flutter::SemanticsAction::kCustomAction,
496 fml::MallocMapping::Copy(args.data(), args.size() * sizeof(uint8_t)));
497 return YES;
498 }
499
500 - (NSString*)accessibilityIdentifier {
501 if (![self isAccessibilityBridgeAlive]) {
502 return nil;
503 }
504
505 if (self.node.identifier.empty()) {
506 return nil;
507 }
508 return @(self.node.identifier.data());
509 }
510
511 - (NSString*)accessibilityLabel {
512 if (![self isAccessibilityBridgeAlive]) {
513 return nil;
514 }
515 NSString* label = nil;
516 if (!self.node.label.empty()) {
517 label = @(self.node.label.data());
518 }
519 if (!self.node.tooltip.empty()) {
520 label = label ? [NSString stringWithFormat:@"%@\n%@", label, @(self.node.tooltip.data())]
521 : @(self.node.tooltip.data());
522 }
523 return label;
524 }
525
526 - (bool)containsPoint:(CGPoint)point {
527 // The point is in global coordinates, so use the global rect here.
528 return CGRectContainsPoint([self globalRect], point);
529 }
530
531 // Finds the first eligiable semantics object in hit test order.
532 - (id)search:(CGPoint)point {
533 // Search children in hit test order.
534 for (SemanticsObject* child in [self childrenInHitTestOrder]) {
535 if ([child containsPoint:point]) {
536 id childSearchResult = [child search:point];
537 if (childSearchResult != nil) {
538 return childSearchResult;
539 }
540 }
541 }
542 // Check if the current semantic object should be returned.
543 if ([self containsPoint:point] && [self isFocusable]) {
544 return self.nativeAccessibility;
545 }
546 return nil;
547 }
548
549 // iOS uses this method to determine the hittest results when users touch
550 // explore in VoiceOver.
551 //
552 // For overlapping UIAccessibilityElements (e.g. a stack) in IOS, the focus
553 // goes to the smallest object before IOS 16, but to the top-left object in
554 // IOS 16. Overrides this method to focus the first eligiable semantics
555 // object in hit test order.
556 - (id)_accessibilityHitTest:(CGPoint)point withEvent:(UIEvent*)event {
557 return [self search:point];
558 }
559
560 // iOS calls this method when this item is swipe-to-focusd in VoiceOver.
561 - (BOOL)accessibilityScrollToVisible {
562 [self showOnScreen];
563 return YES;
564 }
565
566 // iOS calls this method when this item is swipe-to-focusd in VoiceOver.
567 - (BOOL)accessibilityScrollToVisibleWithChild:(id)child {
568 if ([child isKindOfClass:[SemanticsObject class]]) {
569 [child showOnScreen];
570 return YES;
571 }
572 return NO;
573 }
574
575 - (NSAttributedString*)accessibilityAttributedLabel {
576 NSString* label = self.accessibilityLabel;
577 if (label.length == 0) {
578 return nil;
579 }
580 return [self createAttributedStringFromString:label withAttributes:self.node.labelAttributes];
581 }
582
583 - (NSString*)accessibilityHint {
584 if (![self isAccessibilityBridgeAlive]) {
585 return nil;
586 }
587
588 if (self.node.hint.empty()) {
589 return nil;
590 }
591 return @(self.node.hint.data());
592 }
593
594 - (NSAttributedString*)accessibilityAttributedHint {
595 NSString* hint = [self accessibilityHint];
596 if (hint.length == 0) {
597 return nil;
598 }
599 return [self createAttributedStringFromString:hint withAttributes:self.node.hintAttributes];
600 }
601
602 - (NSString*)accessibilityValue {
603 if (![self isAccessibilityBridgeAlive]) {
604 return nil;
605 }
606
607 if (!self.node.value.empty()) {
608 return @(self.node.value.data());
609 }
610
611 // iOS does not announce values of native radio buttons.
612 if (self.node.flags.isInMutuallyExclusiveGroup) {
613 return nil;
614 }
615
616 // FlutterSwitchSemanticsObject should supercede these conditionals.
617
618 if (self.node.flags.isToggled == flutter::SemanticsTristate::kTrue ||
619 self.node.flags.isChecked == flutter::SemanticsCheckState::kTrue) {
620 return @"1";
621 } else if (self.node.flags.isToggled == flutter::SemanticsTristate::kFalse ||
622 self.node.flags.isChecked == flutter::SemanticsCheckState::kFalse) {
623 return @"0";
624 }
625
626 return nil;
627 }
628
629 - (NSAttributedString*)accessibilityAttributedValue {
630 NSString* value = [self accessibilityValue];
631 if (value.length == 0) {
632 return nil;
633 }
634 return [self createAttributedStringFromString:value withAttributes:self.node.valueAttributes];
635 }
636
637 - (CGRect)accessibilityFrame {
638 if (![self isAccessibilityBridgeAlive]) {
639 return CGRectMake(0, 0, 0, 0);
640 }
641
642 if (self.node.flags.isHidden) {
643 return [super accessibilityFrame];
644 }
645 return [self globalRect];
646 }
647
648 - (CGRect)globalRect {
649 const SkRect& rect = self.node.rect;
650 CGRect localRect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
651 return ConvertRectToGlobal(self, localRect);
652 }
653
654 #pragma mark - UIAccessibilityElement protocol
655
656 - (void)setAccessibilityContainer:(id)container {
657 // Explicit noop. The containers are calculated lazily in `accessibilityContainer`.
658 // See also: https://github.com/flutter/flutter/issues/54366
659 }
660
661 - (id)accessibilityContainer {
662 if (_inDealloc) {
663 // In iOS9, `accessibilityContainer` will be called by `[UIAccessibilityElementSuperCategory
664 // dealloc]` during `[super dealloc]`. And will crash when accessing `_children` which has
665 // called `[_children release]` in `[SemanticsObject dealloc]`.
666 // https://github.com/flutter/flutter/issues/87247
667 return nil;
668 }
669
670 if (![self isAccessibilityBridgeAlive]) {
671 return nil;
672 }
673
674 if ([self hasChildren] || self.uid == kRootNodeId) {
675 if (self.container == nil) {
676 self.container = [[SemanticsObjectContainer alloc] initWithSemanticsObject:self
677 bridge:self.bridge];
678 }
679 return self.container;
680 }
681 if (self.parent == nil) {
682 // This can happen when we have released the accessibility tree but iOS is
683 // still holding onto our objects. iOS can take some time before it
684 // realizes that the tree has changed.
685 return nil;
686 }
687 return self.parent.accessibilityContainer;
688 }
689
690 #pragma mark - UIAccessibilityAction overrides
691
692 - (BOOL)accessibilityActivate {
693 if (![self isAccessibilityBridgeAlive]) {
694 return NO;
695 }
696 if (!self.node.HasAction(flutter::SemanticsAction::kTap)) {
697 // Prevent sliders to receive a regular tap which will change the value.
698 //
699 // This is needed because it causes slider to select to middle if it
700 // does not have a semantics tap.
701 if (self.node.flags.isSlider) {
702 return YES;
703 }
704 return NO;
705 }
706 self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kTap);
707 return YES;
708 }
709
710 - (void)accessibilityIncrement {
711 if (![self isAccessibilityBridgeAlive]) {
712 return;
713 }
714 if (self.node.HasAction(flutter::SemanticsAction::kIncrease)) {
715 self.node.value = self.node.increasedValue;
716 self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kIncrease);
717 }
718 }
719
720 - (void)accessibilityDecrement {
721 if (![self isAccessibilityBridgeAlive]) {
722 return;
723 }
724 if (self.node.HasAction(flutter::SemanticsAction::kDecrease)) {
725 self.node.value = self.node.decreasedValue;
726 self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kDecrease);
727 }
728 }
729
730 - (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction {
731 if (![self isAccessibilityBridgeAlive]) {
732 return NO;
733 }
734 flutter::SemanticsAction action = GetSemanticsActionForScrollDirection(direction);
735 if (!self.node.HasAction(action)) {
736 return NO;
737 }
738 self.bridge->DispatchSemanticsAction(self.uid, action);
739 return YES;
740 }
741
742 - (BOOL)accessibilityPerformEscape {
743 if (![self isAccessibilityBridgeAlive]) {
744 return NO;
745 }
746 if (!self.node.HasAction(flutter::SemanticsAction::kDismiss)) {
747 return NO;
748 }
749 self.bridge->DispatchSemanticsAction(self.uid, flutter::SemanticsAction::kDismiss);
750 return YES;
751 }
752
753 #pragma mark UIAccessibilityFocus overrides
754
755 - (void)accessibilityElementDidBecomeFocused {
756 if (![self isAccessibilityBridgeAlive]) {
757 return;
758 }
759 self.bridge->AccessibilityObjectDidBecomeFocused(self.uid);
760 if (self.node.flags.isHidden || self.node.flags.isHeader) {
761 [self showOnScreen];
762 }
763 if (self.node.HasAction(flutter::SemanticsAction::kDidGainAccessibilityFocus)) {
764 self.bridge->DispatchSemanticsAction(self.uid,
765 flutter::SemanticsAction::kDidGainAccessibilityFocus);
766 }
767 }
768
769 - (void)accessibilityElementDidLoseFocus {
770 if (![self isAccessibilityBridgeAlive]) {
771 return;
772 }
773 self.bridge->AccessibilityObjectDidLoseFocus(self.uid);
774 if (self.node.HasAction(flutter::SemanticsAction::kDidLoseAccessibilityFocus)) {
775 self.bridge->DispatchSemanticsAction(self.uid,
776 flutter::SemanticsAction::kDidLoseAccessibilityFocus);
777 }
778 }
779
780 - (BOOL)accessibilityRespondsToUserInteraction {
781 // Return true only if the node contains actions other than system actions.
782 if ((self.node.actions & ~flutter::kSystemActions) != 0) {
783 return true;
784 }
785
786 if (!self.node.customAccessibilityActions.empty()) {
787 return true;
788 }
789
790 return false;
791 }
792
793 @end
794
795 @implementation FlutterSemanticsObject
796
797 #pragma mark - Designated initializers
798
799 - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
800 uid:(int32_t)uid {
801 self = [super initWithBridge:bridge uid:uid];
802 return self;
803 }
804
805 #pragma mark - UIAccessibility overrides
806
807 - (UIAccessibilityTraits)accessibilityTraits {
808 UIAccessibilityTraits traits = UIAccessibilityTraitNone;
809 if (self.node.HasAction(flutter::SemanticsAction::kIncrease) ||
810 self.node.HasAction(flutter::SemanticsAction::kDecrease)) {
811 traits |= UIAccessibilityTraitAdjustable;
812 }
813 // This should also capture radio buttons.
814 if (self.node.flags.isToggled != flutter::SemanticsTristate::kNone ||
815 self.node.flags.isChecked != flutter::SemanticsCheckState::kNone) {
816 traits |= UIAccessibilityTraitButton;
817 }
818 if (self.node.flags.isSelected == flutter::SemanticsTristate::kTrue) {
819 traits |= UIAccessibilityTraitSelected;
820 }
821 if (self.node.flags.isButton) {
822 traits |= UIAccessibilityTraitButton;
823 }
824 if (self.node.flags.isEnabled == flutter::SemanticsTristate::kFalse) {
825 traits |= UIAccessibilityTraitNotEnabled;
826 }
827 if (self.node.flags.isHeader) {
828 traits |= UIAccessibilityTraitHeader;
829 }
830 if (self.node.flags.isImage) {
831 traits |= UIAccessibilityTraitImage;
832 }
833 if (self.node.flags.isLiveRegion) {
834 traits |= UIAccessibilityTraitUpdatesFrequently;
835 }
836 if (self.node.flags.isLink) {
837 traits |= UIAccessibilityTraitLink;
838 }
839 if (traits == UIAccessibilityTraitNone && ![self hasChildren] &&
840 self.accessibilityLabel.length != 0 && !self.node.flags.isTextField) {
841 traits = UIAccessibilityTraitStaticText;
842 }
843 return traits;
844 }
845
846 @end
847
848 @interface FlutterPlatformViewSemanticsContainer ()
849 @property(nonatomic, weak) UIView* platformView;
850 @end
851
852 @implementation FlutterPlatformViewSemanticsContainer
853
854 - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge
855 uid:(int32_t)uid
856 platformView:(nonnull FlutterTouchInterceptingView*)platformView {
857 if (self = [super initWithBridge:bridge uid:uid]) {
858 _platformView = platformView;
859 [platformView setFlutterAccessibilityContainer:self];
860 }
861 return self;
862 }
863
864 - (id)nativeAccessibility {
865 return self.platformView;
866 }
867
868 @end
869
870 @implementation SemanticsObjectContainer {
871 fml::WeakPtr<flutter::AccessibilityBridgeIos> _bridge;
872 }
873
874 #pragma mark - initializers
875
876 - (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject
877 bridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge {
878 FML_DCHECK(semanticsObject) << "semanticsObject must be set";
879 // Initialize with the UIView as the container.
880 // The UIView will not necessarily be accessibility parent for this object.
881 // The bridge informs the OS of the actual structure via
882 // `accessibilityContainer` and `accessibilityElementAtIndex`.
883 self = [super initWithAccessibilityContainer:bridge->view()];
884
885 if (self) {
886 _semanticsObject = semanticsObject;
887 _bridge = bridge;
888 }
889
890 return self;
891 }
892
893 #pragma mark - UIAccessibilityContainer overrides
894
895 - (NSInteger)accessibilityElementCount {
896 return self.semanticsObject.children.count + 1;
897 }
898
899 - (nullable id)accessibilityElementAtIndex:(NSInteger)index {
900 if (index < 0 || index >= [self accessibilityElementCount]) {
901 return nil;
902 }
903 if (index == 0) {
904 return self.semanticsObject.nativeAccessibility;
905 }
906
907 SemanticsObject* child = self.semanticsObject.children[index - 1];
908
909 if ([child hasChildren]) {
910 return child.accessibilityContainer;
911 }
912 return child.nativeAccessibility;
913 }
914
915 - (NSInteger)indexOfAccessibilityElement:(id)element {
916 if (element == self.semanticsObject.nativeAccessibility) {
917 return 0;
918 }
919
920 NSArray<SemanticsObject*>* children = self.semanticsObject.children;
921 for (size_t i = 0; i < [children count]; i++) {
922 SemanticsObject* child = children[i];
923 if ((![child hasChildren] && child.nativeAccessibility == element) ||
924 ([child hasChildren] && [child.nativeAccessibility accessibilityContainer] == element)) {
925 return i + 1;
926 }
927 }
928 return NSNotFound;
929 }
930
931 #pragma mark - UIAccessibilityElement protocol
932
933 - (BOOL)isAccessibilityElement {
934 return NO;
935 }
936
937 - (CGRect)accessibilityFrame {
938 // For OverlayPortals, the child element is sometimes outside the bounds of the parent
939 // Even if it's marked accessible, VoiceControl labels will not appear if it's too
940 // spatially distant. Set the frame to be the max screen size so all children are guaraenteed
941 // to be contained.
942
943 return UIScreen.mainScreen.bounds;
944 }
945
946 - (id)accessibilityContainer {
947 if (!_bridge) {
948 return nil;
949 }
950 return ([self.semanticsObject uid] == kRootNodeId)
951 ? _bridge->view()
952 : self.semanticsObject.parent.accessibilityContainer;
953 }
954
955 #pragma mark - UIAccessibilityAction overrides
956
957 - (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction {
958 return [self.semanticsObject accessibilityScroll:direction];
959 }
960
961 @end
FlutterPlatformViews_Internal.h
FlutterSemanticsScrollView.h
self
return self
Definition: FlutterTextureRegistryRelay.mm:19
SemanticsObject.h
kRootNodeId
constexpr int32_t kRootNodeId
Definition: SemanticsObject.h:16
kScrollExtentMaxForInf
constexpr float kScrollExtentMaxForInf
Definition: SemanticsObject.h:18
_inDealloc
BOOL _inDealloc
Definition: SemanticsObject.mm:258
FlutterTouchInterceptingView
Definition: FlutterPlatformViews.mm:513
FlutterCustomAccessibilityAction
Definition: SemanticsObject.h:136
FlutterCustomAccessibilityAction::uid
int32_t uid
Definition: SemanticsObject.h:140
FlutterPlatformViewSemanticsContainer
Definition: SemanticsObject.h:170
FlutterScrollableSemanticsObject
Definition: SemanticsObject.h:190
FlutterScrollableSemanticsObject::scrollView
FlutterSemanticsScrollView * scrollView
Definition: SemanticsObject.h:190
FlutterSemanticsObject
Definition: SemanticsObject.h:156
FlutterSemanticsScrollView
Definition: FlutterSemanticsScrollView.h:21
FlutterSemanticsScrollView::isDoingSystemScrolling
BOOL isDoingSystemScrolling
Definition: FlutterSemanticsScrollView.h:43
FlutterSwitchSemanticsObject
Definition: SemanticsObject.h:184
SemanticsObjectContainer
Definition: SemanticsObject.h:228
SemanticsObject
Definition: SemanticsObject.h:32
SemanticsObject::parent
SemanticsObject * parent
Definition: SemanticsObject.h:42
SemanticsObject::nativeAccessibility
id nativeAccessibility
Definition: SemanticsObject.h:83
-[SemanticsObject isAccessibilityBridgeAlive]
BOOL isAccessibilityBridgeAlive()
Definition: SemanticsObject.mm:329
-[SemanticsObject accessibilityBridgeDidFinishUpdate]
void accessibilityBridgeDidFinishUpdate()
Definition: SemanticsObject.mm:337
SemanticsObject::uid
int32_t uid
Definition: SemanticsObject.h:36
SemanticsObject::hasChildren
BOOL hasChildren
Definition: SemanticsObject.h:62
SemanticsObject::node
flutter::SemanticsNode node
Definition: SemanticsObject.h:57
SemanticsObject::children
NSArray< SemanticsObject * > * children
Definition: SemanticsObject.h:68
SemanticsObject::bridge
fml::WeakPtr< flutter::AccessibilityBridgeIos > bridge
Definition: SemanticsObject.h:52
FLUTTER_ASSERT_ARC
Definition: FlutterChannelKeyResponder.mm:13
FLUTTER_ASSERT_ARC::ConvertRectToGlobal
CGRect ConvertRectToGlobal(SemanticsObject *reference, CGRect local_rect)
Definition: SemanticsObject.mm:66
FLUTTER_ASSERT_ARC::GetSemanticsActionForScrollDirection
flutter::SemanticsAction GetSemanticsActionForScrollDirection(UIAccessibilityScrollDirection direction)
Definition: SemanticsObject.mm:14
FLUTTER_ASSERT_ARC::ConvertPointToGlobal
CGPoint ConvertPointToGlobal(SemanticsObject *reference, CGPoint local_point)
Definition: SemanticsObject.mm:52
FLUTTER_ASSERT_ARC::GetGlobalTransform
SkM44 GetGlobalTransform(SemanticsObject *reference)
Definition: SemanticsObject.mm:39
FLUTTER_ASSERT_ARC::ApplyTransform
SkPoint ApplyTransform(SkPoint &point, const SkM44 &transform)
Definition: SemanticsObject.mm:47
flutter
Definition: accessibility_bridge.h:26
fml
Definition: profiler_metrics_ios.mm:41