-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathAccessibilityObject.cpp
More file actions
4331 lines (3712 loc) · 168 KB
/
AccessibilityObject.cpp
File metadata and controls
4331 lines (3712 loc) · 168 KB
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008-2025 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityObject.h"
#include "AXAttributeCacheScope.h"
#include "AXComputedObjectAttributeCache.h"
#include "AXIsolatedTree.h"
#include "AXLogger.h"
#include "AXLoggerBase.h"
#include "AXNotifications.h"
#include "AXObjectCacheInlines.h"
#include "AXObjectRareData.h"
#include "AXRemoteFrame.h"
#include "AXTextMarker.h"
#include "AXUtilities.h"
#include "AccessibilityMockObject.h"
#include "AccessibilityObjectInlines.h"
#include "AccessibilityRenderObject.h"
#include "AccessibilityScrollView.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "ContainerNodeInlines.h"
#include "CustomElementDefaultARIA.h"
#include "DOMTokenList.h"
#include "DocumentPage.h"
#include "EditingInlines.h"
#include "Editor.h"
#include "ElementInlines.h"
#include "ElementIterator.h"
#include "Event.h"
#include "EventDispatcher.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "GeometryUtilities.h"
#include "HTMLAreaElement.h"
#include "HTMLBodyElement.h"
#include "HTMLDataListElement.h"
#include "HTMLDetailsElement.h"
#include "HTMLFormControlElement.h"
#include "HTMLInputElement.h"
#include "HTMLModelElement.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HTMLSlotElement.h"
#include "HTMLTableSectionElement.h"
#include "HTMLTextAreaElement.h"
#include "HitTestResult.h"
#include "LocalFrame.h"
#include "LocalizedStrings.h"
#include "Logging.h"
#include "MathMLNames.h"
#include "NodeList.h"
#include "NodeName.h"
#include "NodeTraversal.h"
#include "Page.h"
#include "PositionInlines.h"
#include "ProgressTracker.h"
#include "Range.h"
#include "RenderElementInlines.h"
#include "RenderImage.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderLayerInlines.h"
#include "RenderListItem.h"
#include "RenderListMarker.h"
#include "RenderObjectInlines.h"
#include "RenderText.h"
#include "RenderTextControl.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "RenderedPosition.h"
#include "SVGNames.h"
#include "Settings.h"
#include "TextCheckerClient.h"
#include "TextCheckingHelper.h"
#include "TextIterator.h"
#include "UserGestureIndicator.h"
#include "VisibleUnits.h"
#include <numeric>
#include <ranges>
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringView.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
#if ENABLE(MODEL_ELEMENT_ACCESSIBILITY)
#include "ModelPlayerAccessibilityChildren.h"
#endif
namespace WebCore {
using namespace HTMLNames;
AccessibilityObject::AccessibilityObject(AXID axID, AXObjectCache& cache)
: AXCoreObject(axID)
, m_axObjectCache(cache)
{
}
AccessibilityObject::~AccessibilityObject()
{
AX_ASSERT(isDetached());
}
String AccessibilityObject::debugDescriptionInternal(bool verbose, std::optional<OptionSet<AXDebugStringOption>> debugOptions) const
{
StringBuilder result;
result.append("{"_s);
result.append("role: "_s, roleToString(role()));
result.append(", ID "_s, objectID().loggingString());
if (debugOptions) {
if (verbose || *debugOptions & AXDebugStringOption::Ignored)
result.append(isIgnored() ? ", ignored"_s : emptyString());
if (verbose || *debugOptions & AXDebugStringOption::RelativeFrame) {
FloatRect frame = relativeFrame();
result.append(", relativeFrame ((x: "_s, frame.x(), ", y: "_s, frame.y(), "), (w: "_s, frame.width(), ", h: "_s, frame.height(), "))"_s);
}
if (verbose || *debugOptions & AXDebugStringOption::RemoteFrameOffset)
result.append(", remoteFrameOffset ("_s, remoteFrameOffset().x(), ", "_s, remoteFrameOffset().y(), ")"_s);
if (verbose || *debugOptions & AXDebugStringOption::IsRemoteFrame)
result.append(isRemoteFrame() ? ", remote frame"_s : emptyString());
}
if (auto* renderer = this->renderer())
result.append(", "_s, renderer->debugDescription());
else if (auto* node = this->node())
result.append(", "_s, node->debugDescription());
if (String extraDebugInfo = this->extraDebugInfo(); !extraDebugInfo.isEmpty()) {
result.append(" ("_s);
result.append(WTF::move(extraDebugInfo));
result.append(")"_s);
}
result.append("}"_s);
return result.toString();
}
void AccessibilityObject::postMenuClosedNotificationIfNecessary() const
{
if (!isMenu())
return;
if (CheckedPtr cache = axObjectCache()) {
// Assistive technologies need to be informed when menus close.
// No element is passed in the notification because it's a destruction event.
cache->postNotification(nullptr, cache->document(), AXNotification::MenuClosed);
}
}
void AccessibilityObject::detachRemoteParts(AccessibilityDetachmentType detachmentType)
{
if (detachmentType == AccessibilityDetachmentType::ElementDestroyed)
postMenuClosedNotificationIfNecessary();
// Clear any children and call detachFromParent on them so that
// no children are left with dangling pointers to their parent.
clearChildren();
}
OptionSet<AXAncestorFlag> AccessibilityObject::computeAncestorFlags() const
{
OptionSet<AXAncestorFlag> computedFlags;
if (hasAncestorFlag(AXAncestorFlag::IsInDescriptionListDetail) || matchesAncestorFlag(AXAncestorFlag::IsInDescriptionListDetail))
computedFlags.set(AXAncestorFlag::IsInDescriptionListDetail, 1);
if (hasAncestorFlag(AXAncestorFlag::IsInDescriptionListTerm) || matchesAncestorFlag(AXAncestorFlag::IsInDescriptionListTerm))
computedFlags.set(AXAncestorFlag::IsInDescriptionListTerm, 1);
if (hasAncestorFlag(AXAncestorFlag::IsInCell) || matchesAncestorFlag(AXAncestorFlag::IsInCell))
computedFlags.set(AXAncestorFlag::IsInCell, 1);
if (hasAncestorFlag(AXAncestorFlag::IsInRow) || matchesAncestorFlag(AXAncestorFlag::IsInRow))
computedFlags.set(AXAncestorFlag::IsInRow, 1);
return computedFlags;
}
OptionSet<AXAncestorFlag> AccessibilityObject::computeAncestorFlagsWithTraversal() const
{
// If this object's flags are initialized, this traversal is unnecessary. Use AccessibilityObject::ancestorFlags() instead.
AX_ASSERT(!ancestorFlagsAreInitialized());
OptionSet<AXAncestorFlag> computedFlags;
computedFlags.set(AXAncestorFlag::FlagsInitialized, true);
Accessibility::enumerateAncestors<AccessibilityObject>(*this, false, [&] (const AccessibilityObject& ancestor) {
computedFlags.add(ancestor.computeAncestorFlags());
});
return computedFlags;
}
bool AccessibilityObject::matchesAncestorFlag(AXAncestorFlag flag) const
{
auto role = this->role();
switch (flag) {
case AXAncestorFlag::IsInDescriptionListDetail:
return role == AccessibilityRole::DescriptionListDetail;
case AXAncestorFlag::IsInDescriptionListTerm:
return role == AccessibilityRole::DescriptionListTerm;
case AXAncestorFlag::IsInCell:
return role == AccessibilityRole::Cell;
case AXAncestorFlag::IsInRow:
return role == AccessibilityRole::Row;
default:
AX_ASSERT_NOT_REACHED();
return false;
}
}
bool AccessibilityObject::hasAncestorMatchingFlag(AXAncestorFlag flag) const
{
return Accessibility::findAncestor<AccessibilityObject>(*this, false, [flag] (const AccessibilityObject& object) {
if (object.ancestorFlagsAreInitialized())
return object.ancestorFlags().contains(flag);
return object.matchesAncestorFlag(flag);
}) != nullptr;
}
bool AccessibilityObject::isInDescriptionListDetail() const
{
if (ancestorFlagsAreInitialized())
return m_ancestorFlags.contains(AXAncestorFlag::IsInDescriptionListDetail);
return hasAncestorMatchingFlag(AXAncestorFlag::IsInDescriptionListDetail);
}
bool AccessibilityObject::isInDescriptionListTerm() const
{
if (ancestorFlagsAreInitialized())
return m_ancestorFlags.contains(AXAncestorFlag::IsInDescriptionListTerm);
return hasAncestorMatchingFlag(AXAncestorFlag::IsInDescriptionListTerm);
}
bool AccessibilityObject::isInCell() const
{
if (ancestorFlagsAreInitialized())
return m_ancestorFlags.contains(AXAncestorFlag::IsInCell);
return hasAncestorMatchingFlag(AXAncestorFlag::IsInCell);
}
bool AccessibilityObject::isInRow() const
{
if (ancestorFlagsAreInitialized())
return m_ancestorFlags.contains(AXAncestorFlag::IsInRow);
return hasAncestorMatchingFlag(AXAncestorFlag::IsInRow);
}
// ARIA marks elements as having their accessible name derive from either their contents, or their author-provided name.
bool AccessibilityObject::accessibleNameDerivesFromContent() const
{
// First check for objects specifically identified by ARIA.
switch (ariaRoleAttribute()) {
case AccessibilityRole::ApplicationAlert:
case AccessibilityRole::ApplicationAlertDialog:
case AccessibilityRole::ApplicationDialog:
case AccessibilityRole::ApplicationLog:
case AccessibilityRole::ApplicationMarquee:
case AccessibilityRole::ApplicationStatus:
case AccessibilityRole::ApplicationTimer:
case AccessibilityRole::ComboBox:
case AccessibilityRole::Definition:
case AccessibilityRole::Document:
case AccessibilityRole::DocumentArticle:
case AccessibilityRole::DocumentMath:
case AccessibilityRole::DocumentNote:
case AccessibilityRole::LandmarkRegion:
case AccessibilityRole::LandmarkDocRegion:
case AccessibilityRole::Form:
case AccessibilityRole::Grid:
case AccessibilityRole::Group:
case AccessibilityRole::Image:
case AccessibilityRole::List:
case AccessibilityRole::ListBox:
case AccessibilityRole::LandmarkBanner:
case AccessibilityRole::LandmarkComplementary:
case AccessibilityRole::LandmarkContentInfo:
case AccessibilityRole::LandmarkNavigation:
case AccessibilityRole::LandmarkMain:
case AccessibilityRole::LandmarkSearch:
case AccessibilityRole::Menu:
case AccessibilityRole::MenuBar:
case AccessibilityRole::ProgressIndicator:
case AccessibilityRole::Meter:
case AccessibilityRole::RadioGroup:
case AccessibilityRole::SectionFooter:
case AccessibilityRole::SectionHeader:
case AccessibilityRole::ScrollBar:
case AccessibilityRole::Slider:
case AccessibilityRole::SpinButton:
case AccessibilityRole::Splitter:
case AccessibilityRole::Table:
case AccessibilityRole::TabList:
case AccessibilityRole::TabPanel:
case AccessibilityRole::TextArea:
case AccessibilityRole::TextField:
case AccessibilityRole::Toolbar:
case AccessibilityRole::TreeGrid:
case AccessibilityRole::Tree:
case AccessibilityRole::WebApplication:
return false;
default:
break;
}
// Now check for generically derived elements now that we know the element does not match a specific ARIA role.
switch (role()) {
case AccessibilityRole::Slider:
case AccessibilityRole::ListBox:
return false;
default:
break;
}
return true;
}
String AccessibilityObject::computedLabel()
{
// This method is being called by WebKit inspector, which may happen at any time, so we need to update our backing store now.
// Also hold onto this object in case updateBackingStore deletes this node.
Ref protectedThis { *this };
updateBackingStore();
Vector<AccessibilityText> text;
accessibilityText(text);
if (text.size())
return text[0].text;
return { };
}
// FIXME: We should unify all of the special cases for live regions, textUnderElement, title, description, etc. under one method, similar to computedLabel.
String AccessibilityObject::announcementText() const
{
Vector<AccessibilityText> computedText;
accessibilityText(computedText);
#if PLATFORM(COCOA)
String descriptionText = descriptionAttributeValue(&computedText);
if (!descriptionText.isEmpty())
return descriptionText;
#endif
if (is<HTMLInputElement>(node())) {
// Many inputs derive their accessible name from their title.
if (String titleText = title(&computedText); !titleText.isEmpty())
return titleText;
}
TextUnderElementMode mode;
mode.includeListMarkers = IncludeListMarkerText::Yes;
// We want all of the text beneath this object when speaking live regions.
mode.descendIntoContainers = DescendIntoContainers::Yes;
mode.childrenInclusion = TextUnderElementMode::Children::IncludeNameFromContentsChildren;
return textUnderElement(mode);
}
bool AccessibilityObject::isEditableWebArea() const
{
if (!isWebArea())
return false;
RefPtr page = this->page();
if (page && page->isEditable())
return true;
RefPtr document = this->document();
return document && document->inDesignMode();
}
Vector<AXTextMarkerRange> AccessibilityObject::misspellingRanges() const
{
AXTRACE("AccessibilityObject::misspellingRanges"_s);
RefPtr node = this->node();
if (!node)
return { };
RefPtr frame = node->document().frame();
if (!frame)
return { };
auto* textChecker = frame->editor().textChecker();
if (!textChecker)
return { };
// In order to resolve to the correct ranges, Editor::rangeForTextCheckingResult(...)
// assumes that the selection is within the Node for which text we are calling checkTextOfParagraph.
// Therefore, remember the current selection, set it to the beginning of the Node and restore it aftwards.
auto originalSelection = frame->selection().selection();
if (auto range = simpleRange()) {
// Passing UserTriggered::No, which is the default value, guaranties that accessibility is not notified of text selection changes.
frame->selection().setSelectedRange(SimpleRange { range->start, range->start }, Affinity::Downstream, FrameSelection::ShouldCloseTyping::Yes, UserTriggered::No);
}
Vector<AXTextMarkerRange> ranges;
if (unifiedTextCheckerEnabled(frame.get())) {
Vector<TextCheckingResult> misspellings;
checkTextOfParagraph(*textChecker, stringValue(), TextCheckingType::Spelling, misspellings, frame->selection().selection());
for (auto& misspelling : misspellings) {
if (auto range = frame->editor().rangeForTextCheckingResult(misspelling))
ranges.append(range);
}
} else {
int location = -1;
int length = 0;
textChecker->checkSpellingOfString(stringValue(), &location, &length);
if (location > -1 && length > 0)
ranges = { { treeID(), objectID(), static_cast<unsigned>(location), static_cast<unsigned>(length) } };
}
frame->selection().setSelectedRange(originalSelection.range(), Affinity::Downstream, FrameSelection::ShouldCloseTyping::Yes, UserTriggered::No);
return ranges;
}
std::optional<SimpleRange> AccessibilityObject::misspellingRange(const SimpleRange& start, AccessibilitySearchDirection direction) const
{
auto node = this->node();
if (!node)
return std::nullopt;
RefPtr frame = node->document().frame();
if (!frame)
return std::nullopt;
if (!unifiedTextCheckerEnabled(frame.get()))
return std::nullopt;
Ref editor = frame->editor();
TextCheckerClient* textChecker = editor->textChecker();
if (!textChecker)
return std::nullopt;
Vector<TextCheckingResult> misspellings;
checkTextOfParagraph(*textChecker, stringValue(), TextCheckingType::Spelling, misspellings, frame->selection().selection());
// Find the first misspelling past the start.
if (direction == AccessibilitySearchDirection::Next) {
for (auto& misspelling : misspellings) {
auto misspellingRange = editor->rangeForTextCheckingResult(misspelling);
if (misspellingRange && is_gt(treeOrder<ComposedTree>(misspellingRange->end, start.end)))
return *misspellingRange;
}
} else {
for (auto& misspelling : misspellings | std::views::reverse) {
auto misspellingRange = editor->rangeForTextCheckingResult(misspelling);
if (misspellingRange && is_lt(treeOrder<ComposedTree>(misspellingRange->start, start.start)))
return *misspellingRange;
}
}
return std::nullopt;
}
AXTextMarkerRange AccessibilityObject::textInputMarkedTextMarkerRange() const
{
WeakPtr node = this->node();
if (!node)
return { };
RefPtr frame = node->document().frame();
if (!frame)
return { };
CheckedPtr cache = axObjectCache();
if (!cache)
return { };
Ref editor = frame->editor();
RefPtr object = cache->getOrCreate(editor->compositionNode());
if (!object)
return { };
if (RefPtr observableObject = object->observableObject())
object = observableObject;
if (object->objectID() != objectID())
return { };
return { editor->compositionRange() };
}
AccessibilityObject* AccessibilityObject::displayContentsParent() const
{
RefPtr parentNode = node() ? node()->parentNode() : nullptr;
if (RefPtr parentElement = dynamicDowncast<Element>(parentNode); !parentElement || !parentElement->hasDisplayContents())
return nullptr;
CheckedPtr cache = axObjectCache();
return cache ? cache->getOrCreate(*parentNode) : nullptr;
}
AccessibilityObject* AccessibilityObject::nextSiblingUnignored(unsigned limit) const
{
AX_ASSERT(limit);
for (auto sibling = iterator(nextSibling()); limit && sibling; --limit, ++sibling) {
if (!sibling->isIgnored())
return sibling.ptr();
}
return nullptr;
}
AccessibilityObject* AccessibilityObject::previousSiblingUnignored(unsigned limit) const
{
AX_ASSERT(limit);
for (auto sibling = iterator(previousSibling()); limit && sibling; --limit, --sibling) {
if (!sibling->isIgnored())
return sibling.ptr();
}
return nullptr;
}
FloatRect AccessibilityObject::convertFrameToSpace(const FloatRect& frameRect, AccessibilityConversionSpace conversionSpace) const
{
AX_ASSERT(isMainThread());
// Find the appropriate scroll view to use to convert the contents to the window.
RefPtr parentAccessibilityScrollView = ancestorAccessibilityScrollView(false /* includeSelf */);
RefPtr parentScrollView = parentAccessibilityScrollView ? parentAccessibilityScrollView->scrollView() : nullptr;
auto snappedFrameRect = snappedIntRect(IntRect(frameRect));
#if ENABLE(ACCESSIBILITY_LOCAL_FRAME)
if (conversionSpace == AccessibilityConversionSpace::Screen) {
// For screen space, use contentsToView() to adjust for scroll *within* this frame,
// then apply the frame's screen transform and position (which account for iframe offsets and viewport scale).
if (parentScrollView)
snappedFrameRect = parentScrollView->contentsToView(snappedFrameRect);
RefPtr rootScrollView = dynamicDowncast<AccessibilityScrollView>(ancestorAccessibilityScrollView(true /* includeSelf */));
if (!rootScrollView)
return snappedFrameRect;
auto geometry = rootScrollView->frameGeometry();
auto scaledRect = geometry.screenTransform.mapRect(FloatRect(snappedFrameRect));
// macOS uses bottom-left origin, non-macOS assumes top-left origin.
FloatPoint position = {
geometry.screenPosition.x() + scaledRect.x(),
#if PLATFORM(MAC)
geometry.screenPosition.y() - scaledRect.maxY()
#else
geometry.screenPosition.y() + scaledRect.y()
#endif
};
return { position, scaledRect.size() };
}
// FIXME: ENABLE(ACCESSIBILITY_LOCAL_FRAME) doesn't support page-relative frame, but this is used for old tests. Remove this once all tests are updated.
if (parentScrollView)
snappedFrameRect = parentScrollView->contentsToRootView(snappedFrameRect);
#else
// Legacy behavior: contentsToRootView walks up through all frames for local frames.
// For remote frames, the caller (e.g., relativeFrame()) adds remoteFrameOffset().
if (parentScrollView)
snappedFrameRect = parentScrollView->contentsToRootView(snappedFrameRect);
if (conversionSpace == AccessibilityConversionSpace::Screen) {
RefPtr page = this->page();
if (!page)
return snappedFrameRect;
// If we have an empty chrome client (like SVG) then we should use the page
// of the scroll view parent to help us get to the screen rect.
if (parentAccessibilityScrollView && page->chrome().client().isEmptyChromeClient())
page = parentAccessibilityScrollView->page();
snappedFrameRect = page->chrome().rootViewToAccessibilityScreen(snappedFrameRect);
}
#endif // ENABLE(ACCESSIBILITY_LOCAL_FRAME)
return snappedFrameRect;
}
FloatRect AccessibilityObject::relativeFrame() const
{
auto rect = elementRect();
#if !ENABLE(ACCESSIBILITY_LOCAL_FRAME)
rect.moveBy(remoteFrameOffset());
#endif
return convertFrameToSpace(rect, AccessibilityConversionSpace::Page);
}
AccessibilityObject* AccessibilityObject::firstAccessibleObjectFromNode(const Node* node)
{
return WebCore::firstAccessibleObjectFromNode(node, [] (const AccessibilityObject& accessible) {
return !accessible.isIgnored();
});
}
AccessibilityObject* firstAccessibleObjectFromNode(const Node* node, NOESCAPE const Function<bool(const AccessibilityObject&)>& isAccessible)
{
RefPtr axNode = node;
if (!axNode)
return nullptr;
CheckedPtr cache = axNode->document().axObjectCache();
if (!cache)
return nullptr;
RefPtr accessibleObject = cache->getOrCreate(const_cast<Node&>(*axNode));
while (accessibleObject && !isAccessible(*accessibleObject)) {
axNode = NodeTraversal::next(*axNode);
while (axNode && !axNode->renderer())
axNode = NodeTraversal::nextSkippingChildren(*axNode);
if (!axNode)
return nullptr;
accessibleObject = cache->getOrCreate(const_cast<Node&>(*axNode));
}
return accessibleObject.unsafeGet();
}
// FIXME: Usages of this function should be replaced by a new flag in AccessibilityObject::m_ancestorFlags.
bool AccessibilityObject::isDescendantOfRole(AccessibilityRole role) const
{
return Accessibility::findAncestor<AccessibilityObject>(*this, false, [&role] (const AccessibilityObject& object) {
return object.role() == role;
}) != nullptr;
}
static bool isTableComponent(AXCoreObject& axObject)
{
return axObject.isTable() || axObject.isTableColumn() || axObject.isExposedTableRow() || axObject.isTableCell();
}
void AccessibilityObject::insertChild(AccessibilityObject& child, unsigned index, DescendIfIgnored descendIfIgnored)
{
auto owners = child.owners();
if (owners.size()) {
size_t indexOfThis = owners.findIf([this] (const Ref<AXCoreObject>& object) {
return object.ptr() == this;
});
if (indexOfThis == notFound) {
// The child is aria-owned, and not by us, so we shouldn't insert it.
return;
}
}
if (is<HTMLAreaElement>(child.node())) [[unlikely]] {
// Despite the DOM parent for <area> elements being <map>, we expose <area> elements as children
// of the <img> using the <map>. This provides a better experience for AT users, e.g. a screenreader
// would hear "image map" or "group" plus the image description, then the links, which provides the
// added context for what the links represent.
//
// Due to the difference in DOM vs. expected AX hierarchy, make sure area elements are only inserted
// by their associated image as children.
if (child.parentObject() != this)
return;
}
// If the parent is asking for this child's children, then either it's the first time (and clearing is a no-op),
// or its visibility has changed. In the latter case, this child may have a stale child cached.
// This can prevent aria-hidden changes from working correctly. Hence, whenever a parent is getting children, ensure data is not stale.
// Only clear the child's children when we know it's in the updating chain in order to avoid unnecessary work.
if (child.needsToUpdateChildren() || m_subtreeDirty) {
child.clearChildren();
// Pass m_subtreeDirty flag down to the child so that children cache gets reset properly.
if (m_subtreeDirty)
child.setNeedsToUpdateSubtree();
}
#if USE(ATSPI)
// FIXME: Consider removing this ATSPI-only branch with https://bugs.webkit.org/show_bug.cgi?id=282117.
RefPtr displayContentsParent = child.displayContentsParent();
// To avoid double-inserting a child of a `display: contents` element, only insert if `this` is the rightful parent.
if (displayContentsParent && displayContentsParent != this) {
// Make sure the display:contents parent object knows it has a child it needs to add.
displayContentsParent->setNeedsToUpdateChildren();
// Don't exit early for certain table components, as they rely on inserting children for which they are not the rightful parent to behave correctly.
bool allowInsert = isTableColumn() || role() == AccessibilityRole::TableHeaderContainer;
// AccessibilityTable::addChildren never actually calls `insertChild` for table section elements
// (e.g. tbody, thead), so don't block this `insertChild` for display:contents section elements,
// or else the child elements of the section element will never be inserted into the tree.
allowInsert = allowInsert || (isTable() && is<HTMLTableSectionElement>(displayContentsParent->element()));
if (!allowInsert)
return;
}
#endif // USE(ATSPI)
auto insert = [this] (Ref<AXCoreObject>&& object, unsigned index) {
std::ignore = setChildIndexInParent(object.get(), index);
m_children.insert(index, WTF::move(object));
};
auto thisAncestorFlags = computeAncestorFlags();
child.initializeAncestorFlags(thisAncestorFlags);
setIsIgnoredFromParentDataForChild(child);
if (!includeIgnoredInCoreTree() && child.isIgnored()) {
if (descendIfIgnored == DescendIfIgnored::Yes) {
unsigned insertionIndex = index;
auto childAncestorFlags = child.computeAncestorFlags();
for (auto grandchildCoreObject : child.children()) {
Ref grandchild = downcast<AccessibilityObject>(grandchildCoreObject.get());
// Even though `child` is ignored, we still need to set ancestry flags based on it.
grandchild->initializeAncestorFlags(childAncestorFlags);
grandchild->addAncestorFlags(thisAncestorFlags);
// Calls to `child.isIgnored()` or `child.children()` can cause layout, which in turn can cause this object to clear its m_children. This can cause `insertionIndex` to no longer be valid. Detect this and break early if necessary.
if (insertionIndex > m_children.size())
break;
insert(WTF::move(grandchild), insertionIndex);
++insertionIndex;
}
}
} else {
// Table component child-parent relationships often don't line up properly, hence the need for methods
// like parentTable() and parentRow(). Exclude them from this ASSERT.
// FIXME: We hit this ASSERT on gmail.com. https://bugs.webkit.org/show_bug.cgi?id=293264
AX_BROKEN_ASSERT(isTableComponent(child) || isTableComponent(*this) || child.parentObject() == this);
insert(Ref { child }, index);
}
// Reset the child's m_isIgnoredFromParentData since we are done adding that child and its children.
child.clearIsIgnoredFromParentData();
}
void AccessibilityObject::resetChildrenIndexInParent() const
{
if (!shouldSetChildIndexInParent())
return;
unsigned index = 0;
for (const auto& child : m_children) {
bool didSet = setChildIndexInParent(child.get(), index);
// We check shouldSetChildIndexInParent above, so this should always be true.
ASSERT_UNUSED(didSet, didSet);
++index;
}
}
AXCoreObject::AccessibilityChildrenVector AccessibilityObject::findMatchingObjectsWithin(AccessibilitySearchCriteria&& criteria)
{
if (CheckedPtr cache = axObjectCache())
cache->startCachingComputedObjectAttributesUntilTreeMutates();
return AXCoreObject::findMatchingObjectsWithin(WTF::move(criteria));
}
// Returns the range that is fewer positions away from the reference range.
// NOTE: The after range is expected to ACTUALLY be after the reference range and the before
// range is expected to ACTUALLY be before. These are not checked for performance reasons.
static std::optional<SimpleRange> rangeClosestToRange(const SimpleRange& referenceRange, std::optional<SimpleRange>&& afterRange, std::optional<SimpleRange>&& beforeRange)
{
if (!beforeRange)
return WTF::move(afterRange);
if (!afterRange)
return WTF::move(beforeRange);
auto distanceBefore = characterCount({ beforeRange->end, referenceRange.start });
auto distanceAfter = characterCount({ afterRange->start, referenceRange.end });
return WTF::move(distanceBefore <= distanceAfter ? beforeRange : afterRange);
}
std::optional<SimpleRange> AccessibilityObject::rangeOfStringClosestToRangeInDirection(const SimpleRange& referenceRange, AccessibilitySearchDirection searchDirection, const Vector<String>& searchStrings) const
{
RefPtr frame = this->frame();
if (!frame)
return std::nullopt;
bool isBackwardSearch = searchDirection == AccessibilitySearchDirection::Previous;
FindOptions findOptions { FindOption::AtWordStarts, FindOption::AtWordEnds, FindOption::CaseInsensitive, FindOption::StartInSelection };
if (isBackwardSearch)
findOptions.add(FindOption::Backwards);
std::optional<SimpleRange> closestStringRange;
for (auto& searchString : searchStrings) {
if (std::optional foundStringRange = frame->editor().rangeOfString(searchString, referenceRange, findOptions)) {
bool foundStringIsCloser;
if (!closestStringRange)
foundStringIsCloser = true;
else {
foundStringIsCloser = isBackwardSearch
? is_gt(treeOrder<ComposedTree>(foundStringRange->end, closestStringRange->end))
: is_lt(treeOrder<ComposedTree>(foundStringRange->start, closestStringRange->start));
}
if (foundStringIsCloser)
closestStringRange = *foundStringRange;
}
}
return closestStringRange;
}
VisibleSelection AccessibilityObject::selection() const
{
RefPtr document = this->document();
RefPtr frame = document ? document->frame() : nullptr;
return frame ? frame->selection().selection() : VisibleSelection();
}
// Returns an collapsed range preceding the document contents if there is no selection.
// FIXME: Why is that behavior more useful than returning null in that case?
std::optional<SimpleRange> AccessibilityObject::selectionRange() const
{
RefPtr frame = this->frame();
if (!frame)
return std::nullopt;
if (auto range = frame->selection().selection().firstRange())
return *range;
Ref document = *frame->document();
return { { { document.get(), 0 }, { document.get(), 0 } } };
}
std::optional<SimpleRange> AccessibilityObject::simpleRange() const
{
RefPtr node = this->node();
if (!node)
return std::nullopt;
std::optional stitchGroup = stitchGroupIfRepresentative();
if (!stitchGroup)
return AXObjectCache::rangeForNodeContents(*node);
// |this| is a stitching of multiple objects, so we need to include all of their contents in the range.
CheckedPtr cache = axObjectCache();
if (RefPtr endNode = cache ? lastNonAriaHiddenNode(stitchGroup->members(), *cache) : nullptr) {
if (std::optional range = makeSimpleRange(positionBeforeNode(*node), positionAfterNode(*endNode)))
return range;
}
return AXObjectCache::rangeForNodeContents(*node);
}
Vector<BoundaryPoint> AccessibilityObject::previousLineStartBoundaryPoints(const VisiblePosition& startingPosition, const SimpleRange& targetRange, unsigned positionsToRetrieve) const
{
Vector<BoundaryPoint> boundaryPoints;
boundaryPoints.reserveInitialCapacity(positionsToRetrieve);
std::optional<VisiblePosition> lastPosition = startingPosition;
for (unsigned i = 0; i < positionsToRetrieve; i++) {
lastPosition = previousLineStartPositionInternal(*lastPosition);
if (!lastPosition)
break;
auto boundaryPoint = makeBoundaryPoint(*lastPosition);
if (!boundaryPoint || !contains(targetRange, *boundaryPoint))
break;
boundaryPoints.append(WTF::move(*boundaryPoint));
}
boundaryPoints.shrinkToFit();
return boundaryPoints;
}
std::optional<BoundaryPoint> AccessibilityObject::lastBoundaryPointContainedInRect(const Vector<BoundaryPoint>& boundaryPoints, const BoundaryPoint& startBoundary, const FloatRect& rect, int leftIndex, int rightIndex, bool isFlippedWritingMode) const
{
if (leftIndex > rightIndex || boundaryPoints.isEmpty())
return std::nullopt;
auto indexIsValid = [&] (int index) {
return index >= 0 && static_cast<size_t>(index) < boundaryPoints.size();
};
auto boundaryPointContainedInRect = [&] (const BoundaryPoint& boundary) {
return boundaryPointsContainedInRect(startBoundary, boundary, rect, isFlippedWritingMode);
};
int midIndex = std::midpoint(leftIndex, rightIndex);
if (boundaryPointContainedInRect(boundaryPoints.at(midIndex))) {
// We have a match if `midIndex` boundary point is contained in the rect, but the one at `midIndex - 1` isn't.
if (indexIsValid(midIndex - 1) && !boundaryPointContainedInRect(boundaryPoints.at(midIndex - 1)))
return boundaryPoints.at(midIndex);
return lastBoundaryPointContainedInRect(boundaryPoints, startBoundary, rect, leftIndex, midIndex - 1, isFlippedWritingMode);
}
// And vice versa, we have a match if the `midIndex` boundary point is not contained in the rect, but the one at `midIndex + 1` is.
if (indexIsValid(midIndex + 1) && boundaryPointContainedInRect(boundaryPoints.at(midIndex + 1)))
return boundaryPoints.at(midIndex + 1);
return lastBoundaryPointContainedInRect(boundaryPoints, startBoundary, rect, midIndex + 1, rightIndex, isFlippedWritingMode);
}
static IntPoint NODELETE textStartPoint(const IntRect& rect, bool isFlippedWritingMode)
{
if (!isFlippedWritingMode)
return rect.minXMinYCorner();
return rect.maxXMinYCorner();
}
static IntPoint NODELETE textEndPoint(const IntRect& rect, bool isFlippedWritingMode)
{
if (!isFlippedWritingMode)
return rect.maxXMaxYCorner();
return rect.minXMaxYCorner();
}
bool AccessibilityObject::boundaryPointsContainedInRect(const BoundaryPoint& startBoundary, const BoundaryPoint& endBoundary, const FloatRect& rect, bool isFlippedWritingMode) const
{
auto elementRect = boundsForRange({ startBoundary, endBoundary });
return rect.contains(textEndPoint(elementRect, isFlippedWritingMode));
}
std::optional<SimpleRange> AccessibilityObject::visibleCharacterRangeInternal(SimpleRange& range, const FloatRect& contentRect, const IntRect& startingElementRect) const
{
if (!contentRect.intersects(startingElementRect))
return std::nullopt;
auto elementRect = startingElementRect;
auto startBoundary = range.start;
auto endBoundary = range.end;
const CheckedPtr style = this->style();
bool isFlipped = style && style->writingMode().isBlockFlipped();
// In vertical-rl writing-modes (e.g. some Japanese text), text lays out vertically from right-to-left, meaning the the start of the text
// has a larger `x`-coordinate than the end.
bool laysOutIntoNegativeX = isFlipped && style->writingMode().isVertical();
// Origin isn't contained in visible rect, start moving forward by line.
while (!contentRect.contains(textStartPoint(elementRect, isFlipped))) {
auto currentPosition = VisiblePosition(makeContainerOffsetPosition(startBoundary));
auto nextLinePosition = nextLineEndPosition(currentPosition);
if (nextLinePosition == currentPosition) {
// We tried to move to the next line end, but got the same position back. Break to avoid
// looping infinitely. It would be better if we understood *why* nextLineEndPosition
// is returning the same position, but do this for now. If you hit this assert, please
// file a bug with steps to reproduce.
AX_ASSERT_NOT_REACHED();
break;
}
auto testStartBoundary = makeBoundaryPoint(nextLinePosition);
if (!testStartBoundary || !contains(range, *testStartBoundary))
break;
// testStartBoundary is valid, so commit it and update the elementRect.
startBoundary = *testStartBoundary;
elementRect = boundsForRange(SimpleRange(startBoundary, range.end));
if (elementRect.isEmpty() || (elementRect.x() < 0 && !laysOutIntoNegativeX) || elementRect.y() < 0)
break;
}
bool didCorrectStartBoundary = false;
// Sometimes we shrink one line too far -- check the previous line start to see if it's in bounds.
auto previousLineStartPosition = previousLineStartPositionInternal(VisiblePosition(makeContainerOffsetPosition(startBoundary)));
if (previousLineStartPosition) {
if (auto previousLineStartBoundaryPoint = makeBoundaryPoint(*previousLineStartPosition)) {
auto lineStartRect = boundsForRange(SimpleRange(*previousLineStartBoundaryPoint, range.end));
if (previousLineStartBoundaryPoint->container.ptr() == startBoundary.container.ptr() && contentRect.contains(textStartPoint(lineStartRect, isFlipped))) {
elementRect = lineStartRect;
startBoundary = *previousLineStartBoundaryPoint;
didCorrectStartBoundary = true;
}
}
}
if (!didCorrectStartBoundary) {
// We iterated to a line-end position above. We must also check if the start of this line is in bounds.
auto startBoundaryLineStartPosition = startOfLine(VisiblePosition(makeContainerOffsetPosition(startBoundary)));
auto lineStartBoundaryPoint = makeBoundaryPoint(startBoundaryLineStartPosition);