-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathAXObjectCache.cpp
More file actions
6429 lines (5469 loc) · 254 KB
/
AXObjectCache.cpp
File metadata and controls
6429 lines (5469 loc) · 254 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 "AXObjectCache.h"
#include "AXAttributeCacheScope.h"
#include "AXComputedObjectAttributeCache.h"
#include "AXIsolatedObject.h"
#include "AXIsolatedTree.h"
#include "AXListHelpers.h"
#include "AXLocalFrame.h"
#include "AXLogger.h"
#include "AXLoggerBase.h"
#include "AXNotifications.h"
#include "AXObjectCacheInlines.h"
#include "AXRemoteFrame.h"
#include "AXTextMarker.h"
#include "AXTreeStoreInlines.h"
#include "AXUtilities.h"
#include "AccessibilityListBoxOption.h"
#include "AccessibilityMathMLElement.h"
#include "AccessibilityMenuList.h"
#include "AccessibilityMenuListOption.h"
#include "AccessibilityMenuListPopup.h"
#include "AccessibilityObjectInlines.h"
#include "AccessibilityProgressIndicator.h"
#include "AccessibilityRenderObject.h"
#include "AccessibilitySVGObject.h"
#include "AccessibilityScrollView.h"
#include "AccessibilityScrollbar.h"
#include "AccessibilitySlider.h"
#include "AccessibilitySpinButton.h"
#include "AccessibilityTableColumn.h"
#include "AccessibilityTableHeaderContainer.h"
#include "AriaNotifyOptions.h"
#include "CaretRectComputation.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "ContainerNodeInlines.h"
#include "CustomElementDefaultARIA.h"
#include "DeprecatedGlobalSettings.h"
#include "DocumentPage.h"
#include "EditingInlines.h"
#include "Editor.h"
#include "ElementAncestorIteratorInlines.h"
#include "ElementChildIteratorInlines.h"
#include "ElementRareData.h"
#include "EventNames.h"
#include "FocusController.h"
#include "FrameLoader.h"
#include "HTMLAreaElement.h"
#include "HTMLButtonElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLDetailsElement.h"
#include "HTMLDialogElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLLabelElement.h"
#include "HTMLMapElement.h"
#include "HTMLMeterElement.h"
#include "HTMLNames.h"
#include "HTMLOptGroupElement.h"
#include "HTMLOptionElement.h"
#include "HTMLProgressElement.h"
#include "HTMLSelectElement.h"
#include "HTMLSummaryElement.h"
#include "HTMLTableElement.h"
#include "HTMLTablePartElement.h"
#include "HTMLTableRowElement.h"
#include "HTMLTableSectionElement.h"
#include "HTMLTextFormControlElement.h"
#include "HitTestSource.h"
#include "InlineIteratorLogicalOrderTraversal.h"
#include "InlineRunAndOffset.h"
#include "LocalFrame.h"
#include "Logging.h"
#include "MathMLElement.h"
#include "Page.h"
#include "ProgressTracker.h"
#include "Range.h"
#include "RemoteFrame.h"
#include "RemoteFrameView.h"
#include "RenderAttachment.h"
#include "RenderImage.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderLineBreak.h"
#include "RenderListBox.h"
#include "RenderListMarker.h"
#include "RenderMathMLOperator.h"
#include "RenderMeter.h"
#include "RenderObjectInlines.h"
#include "RenderProgress.h"
#include "RenderSVGInlineText.h"
#include "RenderSlider.h"
#include "RenderTable.h"
#include "RenderTableCell.h"
#include "RenderTableRow.h"
#include "RenderView.h"
#include "SVGElement.h"
#include "ScriptDisallowedScope.h"
#include "ScrollView.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "TextBoundaries.h"
#include "TextControlInnerElements.h"
#include "TextIterator.h"
#include "TypedElementDescendantIteratorInlines.h"
#include <utility>
#include <wtf/DataLog.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/SetForScope.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/AtomString.h>
#include <wtf/text/MakeString.h>
#if PLATFORM(COCOA)
#include "AXLiveRegionManager.h"
#include <wtf/spi/darwin/OSVariantSPI.h>
#endif
namespace WebCore {
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(AXObjectCache);
WTF_MAKE_TZONE_ALLOCATED_IMPL(AXObjectCache);
using namespace HTMLNames;
#if PLATFORM(COCOA)
// Post notifications for secure fields or elements contained in secure fields at a 40hz interval to thwart analysis of typing cadence.
static const Seconds accessibilityPasswordValueChangeNotificationInterval { 25_ms };
static bool isSecureFieldOrContainedBySecureField(AccessibilityObject& object)
{
return object.isSecureField() || object.isContainedBySecureField();
}
#endif // PLATFORM(COCOA)
static bool rendererNeedsDeferredUpdate(const RenderObject& renderer)
{
AX_ASSERT(!renderer.beingDestroyed());
auto& document = renderer.document();
return renderer.needsLayout() || document.needsStyleRecalc() || document.inRenderTreeUpdate() || (document.view() && document.view()->layoutContext().isInRenderTreeLayout());
}
static bool NODELETE nodeRendererIsValid(Node& node)
{
auto* renderer = node.renderer();
return renderer && !renderer->beingDestroyed();
}
static bool NODELETE nodeAndRendererAreValid(Node* node)
{
return node ? nodeRendererIsValid(*node) : false;
}
AccessibilityReplacedText::AccessibilityReplacedText(const VisibleSelection& selection)
{
if (AXObjectCache::accessibilityEnabled()) {
m_replacedRange.startIndex.value = indexForVisiblePosition(selection.visibleStart(), m_replacedRange.startIndex.scope);
if (selection.isRange()) {
m_replacedText = AccessibilityObject::stringForVisiblePositionRange(selection);
m_replacedRange.endIndex.value = indexForVisiblePosition(selection.visibleEnd(), m_replacedRange.endIndex.scope);
} else
m_replacedRange.endIndex = m_replacedRange.startIndex;
}
}
void AccessibilityReplacedText::postTextStateChangeNotification(AXObjectCache* cache, AXTextEditType type, const String& text, const VisibleSelection& selection)
{
if (!cache)
return;
if (!AXObjectCache::accessibilityEnabled())
return;
VisiblePosition position = selection.start();
auto node = highestEditableRoot(position.deepEquivalent(), HasEditableAXRole);
if (m_replacedText.length())
cache->postTextReplacementNotification(node.get(), AXTextEditType::Delete, m_replacedText, type, text, position);
else
cache->postTextStateChangeNotification(node.get(), type, text, position);
}
std::atomic<AccessibilityMode> AXObjectCache::gAccessibilityMode { AccessibilityMode::Off };
bool AXObjectCache::gAccessibilityEnhancedUserInterfaceEnabled = false;
std::atomic<bool> AXObjectCache::gForceDeferredSpellChecking = false;
std::atomic<bool> AXObjectCache::gAccessibilityTextStitchingEnabled = false;
std::atomic<bool> AXObjectCache::gAccessibilityThreadHitTestingEnabled = false;
std::atomic<bool> AXObjectCache::gForceInitialFrameCaching = false;
#if PLATFORM(COCOA)
std::atomic<bool> AXObjectCache::gAccessibilityDOMIdentifiersEnabled = false;
std::atomic<bool> AXObjectCache::gShouldRepostNotificationsForTests = false;
#endif
static AXObjectCache::SyncModeToOtherProcessesCallback& syncModeToOtherProcessesCallback()
{
static NeverDestroyed<AXObjectCache::SyncModeToOtherProcessesCallback> callback;
return callback.get();
}
void AXObjectCache::setSyncModeToOtherProcessesCallback(SyncModeToOtherProcessesCallback&& callback)
{
syncModeToOtherProcessesCallback() = WTF::move(callback);
}
std::optional<AccessibilityMode> resolveAccessibilityModeTransition(AccessibilityMode current, AccessibilityMode requested)
{
#if !ENABLE(ACCESSIBILITY_ISOLATED_TREE)
if (requested == AccessibilityMode::AXThread)
requested = AccessibilityMode::MainThread;
#endif
if (current == requested)
return std::nullopt;
if (isAccessibilityModeOff(current)) {
if (requested == AccessibilityMode::MainThread || requested == AccessibilityMode::AXThread)
return requested;
return std::nullopt;
}
bool isOffRequested = isAccessibilityModeOff(requested);
if (current == AccessibilityMode::MainThread) {
if (requested == AccessibilityMode::AXThread)
return requested;
if (isOffRequested)
return AccessibilityMode::OffWasMainThread;
return std::nullopt;
}
if (current == AccessibilityMode::AXThread && isOffRequested)
return AccessibilityMode::OffWasAXThread;
// Default to disallowing the transition.
return std::nullopt;
}
enum class ShouldSyncToOtherProcesses : bool { No, Yes };
static std::optional<AccessibilityMode> attemptModeTransition(AccessibilityMode requestedMode, ShouldSyncToOtherProcesses shouldSyncToOtherProcesses = ShouldSyncToOtherProcesses::Yes)
{
std::optional resolvedMode = resolveAccessibilityModeTransition(AXObjectCache::accessibilityMode(), requestedMode);
if (!resolvedMode)
return std::nullopt;
AXObjectCache::gAccessibilityMode.store(*resolvedMode, std::memory_order_relaxed);
if (shouldSyncToOtherProcesses == ShouldSyncToOtherProcesses::Yes) {
if (auto& callback = syncModeToOtherProcessesCallback())
callback(*resolvedMode);
}
return resolvedMode;
}
std::optional<AccessibilityMode> AXObjectCache::attemptMainThreadModeTransition()
{
return attemptModeTransition(AccessibilityMode::MainThread);
}
void AXObjectCache::disableAccessibilityForTesting()
{
if (isAccessibilityModeOff(accessibilityMode()))
return;
// See comment for this function in the header to understand
// why we don't sync this mode change outside this process.
[[maybe_unused]] std::optional newMode = attemptModeTransition(AccessibilityMode::Off, ShouldSyncToOtherProcesses::No);
// Assuming proper context (i.e. this is a test client), the transition should
// always be successful. Anything else indicates a programming error.
AX_ASSERT(newMode);
AX_ASSERT(isAccessibilityModeOff(*newMode));
}
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
std::optional<AccessibilityMode> AXObjectCache::transitionToAXThreadModeIfNeeded(ForceAXThreadMode forceAXThread)
{
if (accessibilityMode() == AccessibilityMode::AXThread)
return std::nullopt;
if (platformAXThreadSupport(forceAXThread) == PlatformAXThreadSupport::NotSupported)
return std::nullopt;
if (forceAXThread == ForceAXThreadMode::No
&& !DeprecatedGlobalSettings::isAccessibilityIsolatedTreeEnabled())
return std::nullopt;
// At this point we *must* be on the main-thread (our mode was not AXThread and
// thus the accessibility thread should not have been started). This is important
// because we call several functions that must be run on the main-thread, like
// attemptModeTransition which can initiate IPC (and sending IPC is main-thread only)
// and iterating over the AXObjectCaches in this process.
AX_ASSERT(isMainThread());
// Set mode before building all the isolated trees so any code
// triggered during tree building that checks the mode sees AXThread.
// Don't sync yet — we need to confirm the secondary thread starts
// successfully before notifying other processes.
auto previousMode = accessibilityMode();
std::optional newMode = attemptModeTransition(AccessibilityMode::AXThread, ShouldSyncToOtherProcesses::No);
if (!newMode || *newMode != AccessibilityMode::AXThread) {
// The mode change wasn't successful — do not start the secondary thread
// or build any isolated trees.
//
// We should either fail the transition outright (std::nullopt), or successfully
// transition to AXThread mode. Nothing else is expected.
AX_ASSERT(!newMode);
return newMode;
}
// Initialize the role map before the accessibility thread starts so that
// it's safe for both threads to use (the only thing that needs to be
// thread-safe about it is initialization since it's not modified after
// creation and is never destroyed).
Accessibility::initializeRoleMap();
if (platformStartSecondaryThread() == DidStartThread::No && !clientIsInTestMode()) {
// Failed to start the secondary thread. Revert to the previous mode.
// In test contexts, failing to start the real AX thread is expected
// because the test runner uses its own fake AX thread.
gAccessibilityMode.store(previousMode, std::memory_order_relaxed);
return std::nullopt;
}
// The transition succeeded — now sync the mode to other processes.
if (auto& callback = syncModeToOtherProcessesCallback())
callback(*newMode);
// Build isolated trees for all existing AXObjectCaches.
forEachAXObjectCache([](AXObjectCache& cache) {
cache.getOrCreateIsolatedTree();
});
return newMode;
}
#endif // ENABLE(ACCESSIBILITY_ISOLATED_TREE)
bool AXObjectCache::accessibilityEnhancedUserInterfaceEnabled()
{
AX_ASSERT(isMainThread());
return gAccessibilityEnhancedUserInterfaceEnabled;
}
void AXObjectCache::setEnhancedUserInterfaceAccessibility(bool flag)
{
AX_ASSERT(isMainThread());
gAccessibilityEnhancedUserInterfaceEnabled = flag;
#if PLATFORM(MAC)
if (flag)
enableAccessibility();
#endif
}
bool AXObjectCache::isAXThreadHitTestingEnabled()
{
return gAccessibilityThreadHitTestingEnabled;
}
void AXObjectCache::setForceInitialFrameCaching(bool shouldForce)
{
gForceInitialFrameCaching = shouldForce;
}
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
bool AXObjectCache::shouldServeInitialCachedFrame()
{
return !clientIsInTestMode() || forceInitialFrameCaching();
}
static constexpr Seconds updateTreeSnapshotTimerInterval { 100_ms };
#endif
AXObjectCache::AXObjectCache(LocalFrame& localFrame, Document* document)
: m_document(document)
, m_frameID(localFrame.frameID())
, m_notificationPostTimer(*this, &AXObjectCache::notificationPostTimerFired)
#if PLATFORM(COCOA)
, m_passwordNotificationTimer(*this, &AXObjectCache::passwordNotificationTimerFired)
#endif
, m_liveRegionChangedPostTimer(*this, &AXObjectCache::liveRegionChangedNotificationPostTimerFired)
, m_currentModalElement(nullptr)
, m_performCacheUpdateTimer(*this, &AXObjectCache::performCacheUpdateTimerFired)
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
, m_buildIsolatedTreeTimer(*this, &AXObjectCache::buildIsolatedTree)
, m_geometryManager(AXGeometryManager::create(*this))
, m_selectedTextRangeTimer(*this, &AXObjectCache::selectedTextRangeTimerFired, platformSelectedTextRangeDebounceInterval())
, m_updateTreeSnapshotTimer(*this, &AXObjectCache::updateTreeSnapshotTimerFired)
#endif
{
AXTRACE(makeString("AXObjectCache::AXObjectCache 0x"_s, hex(reinterpret_cast<uintptr_t>(this))));
#ifndef NDEBUG
AXLOG(makeString("frameID "_s, m_frameID.loggingString()));
#endif
AX_ASSERT(isMainThread());
#if !LOG_DISABLED || !RELEASE_LOG_DISABLED
setAccessibilityLogChannelEnabled(LOG_CHANNEL(Accessibility).state != logChannelStateOff);
#endif
gAccessibilityTextStitchingEnabled = DeprecatedGlobalSettings::accessibilityTextStitchingEnabled();
gAccessibilityThreadHitTestingEnabled = DeprecatedGlobalSettings::accessibilityThreadHitTestingEnabled();
#if PLATFORM(COCOA)
initializeUserDefaultValues();
#endif
// If loading completed before the cache was created, loading progress will have been reset to zero.
// Consider loading progress to be 100% in this case.
if (auto* page = localFrame.page()) {
m_loadingProgress = page->progress().estimatedProgress();
m_pageActivityState = page->activityState();
}
if (m_loadingProgress <= 0)
m_loadingProgress = 1;
#if PLATFORM(COCOA)
if (RefPtr document = m_document.get()) {
if (document->settings().isAriaLiveRegionManagementEnabled())
m_liveRegionManager = makeUnique<AXLiveRegionManager>(*this);
}
#endif
AXTreeStore::add(m_id, WeakPtr { this });
#if ENABLE(ACCESSIBILITY_LOCAL_FRAME)
// This is the first time this frame has its cache initialized, so it has no geometry. Kick off a request to initialize it asynchronously.
if (RefPtr page = localFrame.page())
page->chrome().client().requestFrameScreenPosition(m_frameID);
#endif
}
AXObjectCache::~AXObjectCache()
{
AXTRACE(makeString("AXObjectCache::~AXObjectCache 0x"_s, hex(reinterpret_cast<uintptr_t>(this))));
m_notificationPostTimer.stop();
m_liveRegionChangedPostTimer.stop();
m_performCacheUpdateTimer.stop();
for (const auto& object : m_objects.values())
object->detach(AccessibilityDetachmentType::CacheDestroyed);
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
m_selectedTextRangeTimer.stop();
m_updateTreeSnapshotTimer.stop();
if (auto tree = AXIsolatedTree::treeForFrameID(m_frameID))
tree->setPageActivityState({ });
AXIsolatedTree::removeTreeForFrameID(m_frameID);
#endif
AXTreeStore::remove(m_id);
}
String AXObjectCache::debugDescription() const
{
TextStream stream;
stream << this;
RefPtr document = m_document.get();
return makeString(
"AXObjectCache "_s,
stream.release(),
" { "_s,
document ? document->debugDescription() : "null document"_s,
" }"_s
);
}
String AXNotificationWithData::debugDescription() const
{
TextStream stream;
stream << "AXNotificationWithData { notification: " << notification;
WTF::switchOn(data,
[&] (const std::monostate&) { },
[&] (const AriaNotifyData& ariaData) {
stream << ", data: " << ariaData.debugDescription();
}
#if PLATFORM(COCOA)
, [&] (const LiveRegionAnnouncementData& liveRegionData) {
stream << ", data: " << liveRegionData.debugDescription();
}
#endif
);
stream << " }";
return stream.release();
}
bool AXObjectCache::isModalElement(Element& element) const
{
if (hasAnyRole(element, { "dialog"_s, "alertdialog"_s }) && equalLettersIgnoringASCIICase(element.attributeWithDefaultARIA(aria_modalAttr), "true"_s))
return true;
RefPtr dialog = dynamicDowncast<HTMLDialogElement>(element);
return dialog && dialog->isModal();
}
void AXObjectCache::findModalNodes()
{
// Traverse the DOM tree to look for the aria-modal=true nodes or modal <dialog> elements.
RefPtr document = this->document();
for (RefPtr element = document ? ElementTraversal::firstWithin(document->rootNode()) : nullptr; element; element = ElementTraversal::nextIncludingPseudo(*element)) {
if (isModalElement(*element))
m_modalElements.append(element.get());
}
m_modalNodesInitialized = true;
}
bool AXObjectCache::modalElementHasAccessibleContent(Element& element)
{
// Unless you're trying to compute the new modal node, determining whether an element
// has accessible content is as easy as !getOrCreate(element)->unignoredChildren().isEmpty().
// So don't call this method on anything besides modal elements.
AX_ASSERT(isModalElement(element));
// Because computing any object's unignored children is dependent on whether a modal is on the page,
// we'll need to walk the DOM and find non-ignored AX objects manually.
Vector<Node*> nodeStack = { element.firstChild() };
while (!nodeStack.isEmpty()) {
for (RefPtr node = nodeStack.takeLast(); node; node = node->nextSibling()) {
if (RefPtr axObject = getOrCreate(*node)) {
if (!axObject->computeIsIgnored())
return true;
#if USE(ATSPI)
// When using ATSPI, an accessibility object with 'StaticText' role is ignored.
// Its content is exposed by its parent.
// Treat such elements as having accessible content.
// FIXME: This may not be sufficient for visibility:hidden or inert (https://bugs.webkit.org/show_bug.cgi?id=280914).
if (axObject->role() == AccessibilityRole::StaticText && !axObject->isAXHidden())
return true;
#endif
}
// Don't descend into subtrees for non-visible nodes.
if (isNodeVisible(node.get()))
nodeStack.append(node->firstChild());
}
}
return false;
}
void AXObjectCache::updateCurrentModalNode()
{
auto recomputeModalElement = [&] () -> Element* {
// There might be multiple modal dialog nodes.
// We use this function to pick the one we want.
if (m_modalElements.isEmpty())
return nullptr;
RefPtr document = this->document();
if (!document)
return nullptr;
// Pick the document active modal <dialog> element if it exists.
if (RefPtr activeModalDialog = document->activeModalDialog()) {
AX_ASSERT(m_modalElements.contains(activeModalDialog.get()));
return activeModalDialog.unsafeGet();
}
SetForScope retrievingCurrentModalNode(m_isRetrievingCurrentModalNode, true);
// If any of the modal nodes contains the keyboard focus, we want to pick that one.
// If multiple contain the keyboard focus, we want the deepest.
// If no modal contains focus, we want to pick the last visible dialog in the DOM.
RefPtr<Element> focusedElement = document->focusedElement();
RefPtr<Element> modalElementToReturn;
bool foundModalWithFocusInside = false;
for (auto& element : m_modalElements) {
// Elements in m_modalElementsSet may have become un-modal since we added them, but not yet removed
// as part of the asynchronous m_deferredModalChangedList handling. Skip these.
if (!element || !isModalElement(*element))
continue;
// To avoid trapping users in an empty modal, skip any non-visible element, or any element without accessible content.
if (!isNodeVisible(element.get()) || !modalElementHasAccessibleContent(*element))
continue;
bool focusIsInsideElement = focusedElement && focusedElement->isInclusiveDescendantOf(*element);
// If the modal we found previously is a descendant of this one, prefer the descendant and skip this one.
if (modalElementToReturn && foundModalWithFocusInside && modalElementToReturn->isDescendantOf(*element))
continue;
// If we already found a modal that focus is inside, and this one doesn't have focus inside, skip in favor of the one with focus inside.
if (modalElementToReturn && foundModalWithFocusInside && !focusIsInsideElement)
continue;
modalElementToReturn = element.get();
if (focusIsInsideElement)
foundModalWithFocusInside = true;
}
if (!focusedElement || !foundModalWithFocusInside)
return nullptr;
RefPtr object = getOrCreate(modalElementToReturn.get());
if (!object || object->isAXHidden())
return nullptr;
return modalElementToReturn.unsafeGet();
};
RefPtr previousModal = m_currentModalElement.get();
m_currentModalElement = recomputeModalElement();
if (previousModal.get() != m_currentModalElement.get()) {
childrenChanged(rootWebArea());
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
// Because the presence of a modal affects every element on the page,
// regenerate the entire isolated tree with the next cache update.
m_deferredRegenerateIsolatedTree = true;
#endif
}
}
bool AXObjectCache::isNodeVisible(const Node* node) const
{
RefPtr element = dynamicDowncast<Element>(node);
if (!element)
return false;
CheckedPtr renderer = element->renderer();
if (!renderer)
return false;
CheckedRef style = renderer->style();
if (style->display() == Style::DisplayType::None)
return false;
CheckedPtr renderLayer = renderer->enclosingLayer();
if (isVisibilityHidden(style) && renderLayer && !renderLayer->hasVisibleContent())
return false;
// Check whether this object or any of its ancestors has opacity 0.
// The resulting opacity of a RenderObject is computed as the multiplication
// of its opacity times the opacities of its ancestors.
for (auto* ancestor = renderer.get(); ancestor; ancestor = ancestor->parent()) {
if (ancestor->style().opacity().isTransparent())
return false;
}
// We also need to consider aria hidden status.
return !equalLettersIgnoringASCIICase(element->attributeWithDefaultARIA(aria_hiddenAttr), "true"_s) || element->focused();
}
// This function returns the valid aria modal node.
Node* AXObjectCache::modalNode()
{
if (!m_modalNodesInitialized)
findModalNodes();
if (m_modalElements.isEmpty())
return nullptr;
// Check the cached current valid aria modal node first.
// Usually when one dialog sets aria-modal=true, that dialog is the one we want.
if (isNodeVisible(m_currentModalElement))
return m_currentModalElement;
// Recompute the valid aria modal node when m_currentModalElement is null or hidden.
updateCurrentModalNode();
return m_currentModalElement;
}
AccessibilityObject* AXObjectCache::focusedImageMapUIElement(HTMLAreaElement& areaElement)
{
// Find the corresponding accessibility object for the HTMLAreaElement. This should be
// in the list of children for its corresponding image.
RefPtr imageElement = areaElement.imageElement();
if (!imageElement)
return nullptr;
RefPtr axRenderImage = protect(areaElement.document())->axObjectCache()->getOrCreate(*imageElement);
if (!axRenderImage)
return nullptr;
for (const auto& child : axRenderImage->unignoredChildren()) {
if (child->isImageMapLink() && child->node() == &areaElement)
return dynamicDowncast<AccessibilityObject>(child.get());
}
return nullptr;
}
AccessibilityObject* AXObjectCache::focusedObjectForPage(const Page* page)
{
#if ENABLE_ACCESSIBILITY_LOCAL_FRAME
return focusedObjectForLocalFrame();
#endif
AX_ASSERT(isMainThread());
if (!accessibilityEnabled())
return nullptr;
// get the focused node in the page
RefPtr focusedOrMainFrame = page->focusController().focusedOrMainFrame();
if (!focusedOrMainFrame)
return nullptr;
RefPtr document = focusedOrMainFrame->document();
if (!document)
return nullptr;
document->updateStyleIfNeeded();
if (RefPtr remoteFrame = dynamicDowncast<RemoteFrame>(page->focusController().focusedFrame())) {
// Check if focus is in a site-isolated sub-frame. If so, return the AXRemoteFrame
// so ATs can follow it to the remote process to get the actual focused element.
if (RefPtr remoteFrameView = remoteFrame->view()) {
if (RefPtr scrollView = dynamicDowncast<AccessibilityScrollView>(getOrCreate(remoteFrameView.get())))
return scrollView->remoteFrame().unsafeGet();
}
}
if (RefPtr focusedElement = document->focusedElement())
return focusedObjectForNode(focusedElement.get());
return focusedObjectForNode(document.get());
}
AccessibilityObject* AXObjectCache::focusedObjectForLocalFrame()
{
AX_ASSERT(isMainThread());
if (!accessibilityEnabled())
return nullptr;
RefPtr document = this->document();
if (!document)
return nullptr;
RefPtr page = document->page();
#if ENABLE(ACCESSIBILITY_LOCAL_FRAME)
RefPtr focusedOrMainFrame = page ? page->focusController().focusedOrMainFrame() : nullptr;
if (!focusedOrMainFrame || focusedOrMainFrame->document() != document.get()) {
// Return null if focus is in a different local frame (which would have a different AXObjectCache).
return nullptr;
}
#endif // ENABLE(ACCESSIBILITY_LOCAL_FRAME)
if (RefPtr remoteFrame = page ? dynamicDowncast<RemoteFrame>(page->focusController().focusedFrame()) : nullptr) {
// Check if focus is in a site-isolated sub-frame. If so, return the AXRemoteFrame
// so ATs can follow it to the remote process to get the actual focused element.
if (RefPtr remoteFrameView = remoteFrame->view()) {
if (RefPtr scrollView = dynamicDowncast<AccessibilityScrollView>(getOrCreate(remoteFrameView.get())))
return scrollView->remoteFrame().unsafeGet();
}
}
document->updateStyleIfNeeded();
if (RefPtr focusedElement = document->focusedElement())
return focusedObjectForNode(focusedElement.get());
return focusedObjectForNode(document.get());
}
AccessibilityObject* AXObjectCache::focusedObjectForNode(Node* focusedNode)
{
if (auto* area = dynamicDowncast<HTMLAreaElement>(focusedNode))
return focusedImageMapUIElement(*area);
RefPtr focus = getOrCreate(focusedNode);
if (!focus)
return nullptr;
if (focus->shouldFocusActiveDescendant()) {
if (RefPtr descendant = focus->activeDescendant())
return dynamicDowncast<AccessibilityObject>(descendant.get());
}
if (focus->isIgnored())
return focus->parentObjectUnignored();
return focus.unsafeGet();
}
#if ENABLE(ACCESSIBILITY_ISOLATED_TREE)
void AXObjectCache::setIsolatedTreeFocusedObject(AccessibilityObject* focus)
{
AX_ASSERT(isMainThread());
if (RefPtr tree = AXIsolatedTree::treeForFrameID(m_frameID))
tree->setFocusedNodeID(focus ? std::optional { focus->objectID() } : std::nullopt);
}
#endif
IntPoint AXObjectCache::mapScreenPointToPagePoint(const IntPoint& screenRelativePoint) const
{
RefPtr page = this->page();
if (!page)
return screenRelativePoint;
RefPtr frame = m_document ? m_document->frame() : nullptr;
RefPtr frameView = frame ? frame->view() : nullptr;
// Try to use cached accessibility position to avoid sync IPC (macOS only).
IntPoint convertedPoint;
if (auto localResult = page->chrome().client().screenToRootViewUsingCachedPosition(screenRelativePoint, frameView ? frameView->size() : IntSize()))
convertedPoint = *localResult;
else
convertedPoint = page->chrome().client().screenToRootView(screenRelativePoint);
if (frameView)
convertedPoint.moveBy(frameView->scrollPosition());
auto obscuredContentInsets = page->obscuredContentInsets();
convertedPoint.move(-obscuredContentInsets.left(), -obscuredContentInsets.top());
return convertedPoint;
}
RefPtr<Page> AXObjectCache::page() const
{
return m_document ? m_document->page() : nullptr;
}
Ref<AccessibilityRenderObject> AXObjectCache::createObjectFromRenderer(RenderObject& renderer)
{
RefPtr node = renderer.node();
if (RefPtr element = dynamicDowncast<Element>(node)) {
// Lists shouldn't fallthrough to table components, so explicitly create a render object.
if (AXListHelpers::isAccessibilityList(*element))
return AccessibilityRenderObject::create(AXID::generate(), renderer, *this);
}
if (renderer.isRenderOrLegacyRenderSVGRoot())
return AccessibilitySVGObject::create(AXID::generate(), renderer, *this, /* isSVGRoot */ true);
if (is<SVGElement>(node) || is<RenderSVGInlineText>(renderer))
return AccessibilitySVGObject::create(AXID::generate(), renderer, *this);
if (CheckedPtr renderImage = toSimpleImage(renderer))
return AccessibilityRenderObject::create(AXID::generate(), *renderImage, *this);
#if ENABLE(MATHML)
// The mfenced element creates anonymous RenderMathMLOperators which should be treated
// as MathML elements and assigned the MathElementRole so that platform logic regarding
// inclusion and role mapping is not bypassed.
bool isAnonymousOperator = renderer.isAnonymous() && is<RenderMathMLOperator>(renderer);
if (isAnonymousOperator || is<MathMLElement>(node))
return AccessibilityMathMLElement::create(AXID::generate(), renderer, *this, isAnonymousOperator);
#endif
if (RefPtr select = dynamicDowncast<HTMLSelectElement>(node); select && select->usesMenuList())
return AccessibilityMenuList::create(AXID::generate(), renderer, *this);
// Progress indicator.
if (is<RenderProgress>(renderer) || is<RenderMeter>(renderer)
|| is<HTMLProgressElement>(node) || is<HTMLMeterElement>(node))
return AccessibilityProgressIndicator::create(AXID::generate(), renderer, *this);
// input type=range
if (is<RenderSlider>(renderer))
return AccessibilitySlider::create(AXID::generate(), renderer, *this);
return AccessibilityRenderObject::create(AXID::generate(), renderer, *this);
}
Ref<AccessibilityNodeObject> AXObjectCache::createFromNode(Node& node)
{
if (RefPtr element = dynamicDowncast<Element>(node)) {
// Lists shouldn't fallthrough to table components, so explicitly create a render object.
if (AXListHelpers::isAccessibilityList(*element))
return AccessibilityRenderObject::create(AXID::generate(), *element, *this);
if (RefPtr areaElement = dynamicDowncast<HTMLAreaElement>(*element))
return AccessibilityNodeObject::create(AXID::generate(), areaElement.get(), *this);
if (is<HTMLProgressElement>(*element) || is<HTMLMeterElement>(*element))
return AccessibilityProgressIndicator::create(AXID::generate(), *element, *this);
if (is<SVGElement>(*element))
return AccessibilitySVGObject::create(AXID::generate(), *element, *this);
}
return AccessibilityRenderObject::create(AXID::generate(), node, *this);
}
void AXObjectCache::cacheAndInitializeWrapper(AccessibilityObject& newObject, DOMObjectVariant domObject)
{
AXID axID = newObject.objectID();
WTF::switchOn(domObject,
[&] (RenderObject* typedValue) {
CheckedPtr node = typedValue->node();
if (!node)
m_renderObjectIdMapping.set(*typedValue, axID);
else {
m_nodeIdMapping.set(*node, axID);
m_nodeObjectMapping.set(*node, newObject);
}
},
[&] (Node* typedValue) {
m_nodeIdMapping.set(*typedValue, axID);
m_nodeObjectMapping.set(*typedValue, newObject);
},
[&] (Widget* typedValue) { m_widgetIdMapping.set(*typedValue, axID); },
[] (auto&) { }
);
m_objects.set(axID, newObject);
newObject.init();
attachWrapper(newObject);
}
AccessibilityObject* AXObjectCache::exportedGetOrCreate(Node* node)
{
return node ? exportedGetOrCreate(*node) : nullptr;
}
AccessibilityObject* AXObjectCache::exportedGetOrCreate(Node& node)
{
return getOrCreate(node, IsPartOfRelation::No);
}
AccessibilityObject* AXObjectCache::getOrCreate(Widget& widget)
{
if (RefPtr object = get(widget))
return object.unsafeGet();
RefPtr<AccessibilityObject> newObject;
if (auto* scrollView = dynamicDowncast<ScrollView>(widget))
newObject = AccessibilityScrollView::create(AXID::generate(), *scrollView, *this);
else if (auto* scrollbar = dynamicDowncast<Scrollbar>(widget))
newObject = AccessibilityScrollbar::create(AXID::generate(), *scrollbar, *this);
// Will crash later if we have two objects for the same widget.
AX_ASSERT(!get(widget));
// Ensure we weren't given an unsupported widget type.
AX_ASSERT(newObject);
if (!newObject)
return nullptr;
cacheAndInitializeWrapper(*newObject, &widget);
return newObject.unsafeGet();
}
AccessibilityObject* AXObjectCache::getOrCreateSlow(Node& node, IsPartOfRelation isPartOfRelation)
{
// `get` for this Node should've been attempted before calling this method.
AX_ASSERT(!get(node));
#if ENABLE_ACCESSIBILITY_LOCAL_FRAME
// Easily reproducible on most pages with ITM off.
AX_BROKEN_ASSERT(&node.document() == document());
#endif
bool isYouTubeReplacement = false;
if (CheckedPtr renderer = nodeRendererIsValid(node) ? node.renderer() : nullptr) {
if (!renderer->isYouTubeReplacement()) [[likely]]
return getOrCreate(*renderer);
isYouTubeReplacement = true;
}
if (CheckedPtr document = dynamicDowncast<Document>(node)) [[unlikely]]
return getOrCreate(document->renderView());
RefPtr composedParent = node.parentElementInComposedTree();
if (!composedParent)
return nullptr;
Ref protectedNode { node };
RefPtr optionElement = dynamicDowncast<HTMLOptionElement>(node);
RefPtr optGroupElement = dynamicDowncast<HTMLOptGroupElement>(node);
if (optionElement || optGroupElement) {
RefPtr select = optionElement
? optionElement->ownerSelectElement()
: optGroupElement->ownerSelectElement();
if (!select)
return nullptr;
RefPtr<AccessibilityObject> object;
if (select->usesMenuList()) {
if (!optionElement || !select->renderer())
return nullptr;
object = AccessibilityMenuListOption::create(AXID::generate(), *optionElement, *this);
} else
object = AccessibilityListBoxOption::create(AXID::generate(), downcast<HTMLElement>(node), *this);
cacheAndInitializeWrapper(*object, &node);
return object.unsafeGet();
}
bool inCanvasSubtree = lineageOfType<HTMLCanvasElement>(*composedParent).first();