forked from qt/qtwebkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessibilityObject.cpp
More file actions
3001 lines (2505 loc) · 103 KB
/
Copy pathAccessibilityObject.cpp
File metadata and controls
3001 lines (2505 loc) · 103 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, 2009, 2011 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 "AXObjectCache.h"
#include "AccessibilityRenderObject.h"
#include "AccessibilityScrollView.h"
#include "AccessibilityTable.h"
#include "DOMTokenList.h"
#include "Editor.h"
#include "ElementIterator.h"
#include "EventHandler.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "HTMLDetailsElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HitTestResult.h"
#include "LocalizedStrings.h"
#include "MainFrame.h"
#include "MathMLNames.h"
#include "NodeList.h"
#include "NodeTraversal.h"
#include "Page.h"
#include "RenderImage.h"
#include "RenderLayer.h"
#include "RenderListItem.h"
#include "RenderListMarker.h"
#include "RenderMenuList.h"
#include "RenderText.h"
#include "RenderTextControl.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "RenderedPosition.h"
#include "Settings.h"
#include "TextCheckerClient.h"
#include "TextCheckingHelper.h"
#include "TextIterator.h"
#include "UserGestureIndicator.h"
#include "VisibleUnits.h"
#include "htmlediting.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
using namespace HTMLNames;
AccessibilityObject::AccessibilityObject()
: m_id(0)
, m_haveChildren(false)
, m_role(UnknownRole)
, m_lastKnownIsIgnoredValue(DefaultBehavior)
#if PLATFORM(GTK) || (PLATFORM(EFL) && HAVE(ACCESSIBILITY))
, m_wrapper(nullptr)
#endif
{
}
AccessibilityObject::~AccessibilityObject()
{
ASSERT(isDetached());
}
void AccessibilityObject::detach(AccessibilityDetachmentType detachmentType, AXObjectCache* cache)
{
// Menu close events need to notify the platform. No element is used in the notification because it's a destruction event.
if (detachmentType == ElementDestroyed && roleValue() == MenuRole && cache)
cache->postNotification(nullptr, &cache->document(), AXObjectCache::AXMenuClosed);
// Clear any children and call detachFromParent on them so that
// no children are left with dangling pointers to their parent.
clearChildren();
#if HAVE(ACCESSIBILITY)
setWrapper(nullptr);
#endif
}
bool AccessibilityObject::isDetached() const
{
#if HAVE(ACCESSIBILITY)
return !wrapper();
#else
return true;
#endif
}
bool AccessibilityObject::isAccessibilityObjectSearchMatchAtIndex(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria, size_t index)
{
switch (criteria->searchKeys[index]) {
// The AnyTypeSearchKey matches any non-null AccessibilityObject.
case AnyTypeSearchKey:
return true;
case BlockquoteSameLevelSearchKey:
return criteria->startObject
&& axObject->isBlockquote()
&& axObject->blockquoteLevel() == criteria->startObject->blockquoteLevel();
case BlockquoteSearchKey:
return axObject->isBlockquote();
case BoldFontSearchKey:
return axObject->hasBoldFont();
case ButtonSearchKey:
return axObject->isButton();
case CheckBoxSearchKey:
return axObject->isCheckbox();
case ControlSearchKey:
return axObject->isControl();
case DifferentTypeSearchKey:
return criteria->startObject
&& axObject->roleValue() != criteria->startObject->roleValue();
case FontChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameFont(criteria->startObject->renderer());
case FontColorChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameFontColor(criteria->startObject->renderer());
case FrameSearchKey:
return axObject->isWebArea();
case GraphicSearchKey:
return axObject->isImage();
case HeadingLevel1SearchKey:
return axObject->headingLevel() == 1;
case HeadingLevel2SearchKey:
return axObject->headingLevel() == 2;
case HeadingLevel3SearchKey:
return axObject->headingLevel() == 3;
case HeadingLevel4SearchKey:
return axObject->headingLevel() == 4;
case HeadingLevel5SearchKey:
return axObject->headingLevel() == 5;
case HeadingLevel6SearchKey:
return axObject->headingLevel() == 6;
case HeadingSameLevelSearchKey:
return criteria->startObject
&& axObject->isHeading()
&& axObject->headingLevel() == criteria->startObject->headingLevel();
case HeadingSearchKey:
return axObject->isHeading();
case HighlightedSearchKey:
return axObject->hasHighlighting();
case ItalicFontSearchKey:
return axObject->hasItalicFont();
case LandmarkSearchKey:
return axObject->isLandmark();
case LinkSearchKey:
return axObject->isLink();
case ListSearchKey:
return axObject->isList();
case LiveRegionSearchKey:
return axObject->supportsARIALiveRegion();
case MisspelledWordSearchKey:
return axObject->hasMisspelling();
case OutlineSearchKey:
return axObject->isTree();
case PlainTextSearchKey:
return axObject->hasPlainText();
case RadioGroupSearchKey:
return axObject->isRadioGroup();
case SameTypeSearchKey:
return criteria->startObject
&& axObject->roleValue() == criteria->startObject->roleValue();
case StaticTextSearchKey:
return axObject->isStaticText();
case StyleChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameStyle(criteria->startObject->renderer());
case TableSameLevelSearchKey:
return criteria->startObject
&& is<AccessibilityTable>(*axObject) && downcast<AccessibilityTable>(*axObject).isExposableThroughAccessibility()
&& downcast<AccessibilityTable>(*axObject).tableLevel() == criteria->startObject->tableLevel();
case TableSearchKey:
return is<AccessibilityTable>(*axObject) && downcast<AccessibilityTable>(*axObject).isExposableThroughAccessibility();
case TextFieldSearchKey:
return axObject->isTextControl();
case UnderlineSearchKey:
return axObject->hasUnderline();
case UnvisitedLinkSearchKey:
return axObject->isUnvisited();
case VisitedLinkSearchKey:
return axObject->isVisited();
default:
return false;
}
}
bool AccessibilityObject::isAccessibilityObjectSearchMatch(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria)
{
if (!axObject || !criteria)
return false;
size_t length = criteria->searchKeys.size();
for (size_t i = 0; i < length; ++i) {
if (isAccessibilityObjectSearchMatchAtIndex(axObject, criteria, i)) {
if (criteria->visibleOnly && !axObject->isOnscreen())
return false;
return true;
}
}
return false;
}
bool AccessibilityObject::isAccessibilityTextSearchMatch(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria)
{
if (!axObject || !criteria)
return false;
return axObject->accessibilityObjectContainsText(&criteria->searchText);
}
bool AccessibilityObject::accessibilityObjectContainsText(String* text) const
{
// If text is null or empty we return true.
return !text
|| text->isEmpty()
|| title().contains(*text, false)
|| accessibilityDescription().contains(*text, false)
|| stringValue().contains(*text, false);
}
// ARIA marks elements as having their accessible name derive from either their contents, or their author provide name.
bool AccessibilityObject::accessibleNameDerivesFromContent() const
{
// First check for objects specifically identified by ARIA.
switch (ariaRoleAttribute()) {
case ApplicationAlertRole:
case ApplicationAlertDialogRole:
case ApplicationDialogRole:
case ApplicationLogRole:
case ApplicationMarqueeRole:
case ApplicationStatusRole:
case ApplicationTimerRole:
case ComboBoxRole:
case DefinitionRole:
case DocumentRole:
case DocumentArticleRole:
case DocumentMathRole:
case DocumentNoteRole:
case DocumentRegionRole:
case FormRole:
case GridRole:
case GroupRole:
case ImageRole:
case ListRole:
case ListBoxRole:
case LandmarkApplicationRole:
case LandmarkBannerRole:
case LandmarkComplementaryRole:
case LandmarkContentInfoRole:
case LandmarkNavigationRole:
case LandmarkMainRole:
case LandmarkSearchRole:
case MenuRole:
case MenuBarRole:
case ProgressIndicatorRole:
case RadioGroupRole:
case ScrollBarRole:
case SliderRole:
case SpinButtonRole:
case SplitterRole:
case TableRole:
case TabListRole:
case TabPanelRole:
case TextAreaRole:
case TextFieldRole:
case ToolbarRole:
case TreeGridRole:
case TreeRole:
return false;
default:
break;
}
// Now check for generically derived elements now that we know the element does not match a specific ARIA role.
switch (roleValue()) {
case SliderRole:
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.
RefPtr<AccessibilityObject> protector(this);
updateBackingStore();
Vector<AccessibilityText> text;
accessibilityText(text);
if (text.size())
return text[0].text;
return String();
}
bool AccessibilityObject::isBlockquote() const
{
return roleValue() == BlockquoteRole;
}
bool AccessibilityObject::isTextControl() const
{
switch (roleValue()) {
case ComboBoxRole:
case SearchFieldRole:
case TextAreaRole:
case TextFieldRole:
return true;
default:
return false;
}
}
bool AccessibilityObject::isARIATextControl() const
{
return ariaRoleAttribute() == TextAreaRole || ariaRoleAttribute() == TextFieldRole || ariaRoleAttribute() == SearchFieldRole;
}
bool AccessibilityObject::isNonNativeTextControl() const
{
return (isARIATextControl() || hasContentEditableAttributeSet()) && !isNativeTextControl();
}
bool AccessibilityObject::isLandmark() const
{
AccessibilityRole role = roleValue();
return role == LandmarkApplicationRole
|| role == LandmarkBannerRole
|| role == LandmarkComplementaryRole
|| role == LandmarkContentInfoRole
|| role == LandmarkMainRole
|| role == LandmarkNavigationRole
|| role == LandmarkSearchRole;
}
bool AccessibilityObject::hasMisspelling() const
{
if (!node())
return false;
Frame* frame = node()->document().frame();
if (!frame)
return false;
Editor& editor = frame->editor();
TextCheckerClient* textChecker = editor.textChecker();
if (!textChecker)
return false;
bool isMisspelled = false;
if (unifiedTextCheckerEnabled(frame)) {
Vector<TextCheckingResult> results;
checkTextOfParagraph(*textChecker, stringValue(), TextCheckingTypeSpelling, results);
if (!results.isEmpty())
isMisspelled = true;
return isMisspelled;
}
int misspellingLength = 0;
int misspellingLocation = -1;
textChecker->checkSpellingOfString(stringValue(), &misspellingLocation, &misspellingLength);
if (misspellingLength || misspellingLocation != -1)
isMisspelled = true;
return isMisspelled;
}
int AccessibilityObject::blockquoteLevel() const
{
int level = 0;
for (Node* elementNode = node(); elementNode; elementNode = elementNode->parentNode()) {
if (elementNode->hasTagName(blockquoteTag))
++level;
}
return level;
}
AccessibilityObject* AccessibilityObject::parentObjectUnignored() const
{
AccessibilityObject* parent;
for (parent = parentObject(); parent && parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
}
return parent;
}
AccessibilityObject* AccessibilityObject::previousSiblingUnignored(int limit) const
{
AccessibilityObject* previous;
ASSERT(limit >= 0);
for (previous = previousSibling(); previous && previous->accessibilityIsIgnored(); previous = previous->previousSibling()) {
limit--;
if (limit <= 0)
break;
}
return previous;
}
AccessibilityObject* AccessibilityObject::nextSiblingUnignored(int limit) const
{
AccessibilityObject* next;
ASSERT(limit >= 0);
for (next = nextSibling(); next && next->accessibilityIsIgnored(); next = next->nextSibling()) {
limit--;
if (limit <= 0)
break;
}
return next;
}
AccessibilityObject* AccessibilityObject::firstAccessibleObjectFromNode(const Node* node)
{
if (!node)
return nullptr;
AXObjectCache* cache = node->document().axObjectCache();
if (!cache)
return nullptr;
AccessibilityObject* accessibleObject = cache->getOrCreate(node->renderer());
while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
node = NodeTraversal::next(*node);
while (node && !node->renderer())
node = NodeTraversal::nextSkippingChildren(*node);
if (!node)
return nullptr;
accessibleObject = cache->getOrCreate(node->renderer());
}
return accessibleObject;
}
static void appendAccessibilityObject(AccessibilityObject* object, AccessibilityObject::AccessibilityChildrenVector& results)
{
// Find the next descendant of this attachment object so search can continue through frames.
if (object->isAttachment()) {
Widget* widget = object->widgetForAttachmentView();
if (!is<FrameView>(widget))
return;
Document* document = downcast<FrameView>(*widget).frame().document();
if (!document || !document->hasLivingRenderTree())
return;
object = object->axObjectCache()->getOrCreate(document);
}
if (object)
results.append(object);
}
static void appendChildrenToArray(AccessibilityObject* object, bool isForward, AccessibilityObject* startObject, AccessibilityObject::AccessibilityChildrenVector& results)
{
// A table's children includes elements whose own children are also the table's children (due to the way the Mac exposes tables).
// The rows from the table should be queried, since those are direct descendants of the table, and they contain content.
const auto& searchChildren = is<AccessibilityTable>(*object) && downcast<AccessibilityTable>(*object).isExposableThroughAccessibility() ? downcast<AccessibilityTable>(*object).rows() : object->children();
size_t childrenSize = searchChildren.size();
size_t startIndex = isForward ? childrenSize : 0;
size_t endIndex = isForward ? 0 : childrenSize;
size_t searchPosition = startObject ? searchChildren.find(startObject) : WTF::notFound;
if (searchPosition != WTF::notFound) {
if (isForward)
endIndex = searchPosition + 1;
else
endIndex = searchPosition;
}
// This is broken into two statements so that it's easier read.
if (isForward) {
for (size_t i = startIndex; i > endIndex; i--)
appendAccessibilityObject(searchChildren.at(i - 1).get(), results);
} else {
for (size_t i = startIndex; i < endIndex; i++)
appendAccessibilityObject(searchChildren.at(i).get(), results);
}
}
// Returns true if the number of results is now >= the number of results desired.
bool AccessibilityObject::objectMatchesSearchCriteriaWithResultLimit(AccessibilityObject* object, AccessibilitySearchCriteria* criteria, AccessibilityChildrenVector& results)
{
if (isAccessibilityObjectSearchMatch(object, criteria) && isAccessibilityTextSearchMatch(object, criteria)) {
results.append(object);
// Enough results were found to stop searching.
if (results.size() >= criteria->resultsLimit)
return true;
}
return false;
}
void AccessibilityObject::findMatchingObjects(AccessibilitySearchCriteria* criteria, AccessibilityChildrenVector& results)
{
ASSERT(criteria);
if (!criteria)
return;
if (AXObjectCache* cache = axObjectCache())
cache->startCachingComputedObjectAttributesUntilTreeMutates();
// This search mechanism only searches the elements before/after the starting object.
// It does this by stepping up the parent chain and at each level doing a DFS.
// If there's no start object, it means we want to search everything.
AccessibilityObject* startObject = criteria->startObject;
if (!startObject)
startObject = this;
bool isForward = criteria->searchDirection == SearchDirectionNext;
// The first iteration of the outer loop will examine the children of the start object for matches. However, when
// iterating backwards, the start object children should not be considered, so the loop is skipped ahead. We make an
// exception when no start object was specified because we want to search everything regardless of search direction.
AccessibilityObject* previousObject = nullptr;
if (!isForward && startObject != this) {
previousObject = startObject;
startObject = startObject->parentObjectUnignored();
}
// The outer loop steps up the parent chain each time (unignored is important here because otherwise elements would be searched twice)
for (AccessibilityObject* stopSearchElement = parentObjectUnignored(); startObject != stopSearchElement; startObject = startObject->parentObjectUnignored()) {
// Only append the children after/before the previous element, so that the search does not check elements that are
// already behind/ahead of start element.
AccessibilityChildrenVector searchStack;
if (!criteria->immediateDescendantsOnly || startObject == this)
appendChildrenToArray(startObject, isForward, previousObject, searchStack);
// This now does a DFS at the current level of the parent.
while (!searchStack.isEmpty()) {
AccessibilityObject* searchObject = searchStack.last().get();
searchStack.removeLast();
if (objectMatchesSearchCriteriaWithResultLimit(searchObject, criteria, results))
break;
if (!criteria->immediateDescendantsOnly)
appendChildrenToArray(searchObject, isForward, 0, searchStack);
}
if (results.size() >= criteria->resultsLimit)
break;
// When moving backwards, the parent object needs to be checked, because technically it's "before" the starting element.
if (!isForward && startObject != this && objectMatchesSearchCriteriaWithResultLimit(startObject, criteria, results))
break;
previousObject = startObject;
}
}
// 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 RefPtr<Range> rangeClosestToRange(Range* referenceRange, RefPtr<Range>&& afterRange, RefPtr<Range>&& beforeRange)
{
if (!referenceRange)
return nullptr;
// The treeScope for shadow nodes may not be the same scope as another element in a document.
// Comparisons may fail in that case, which are expected behavior and should not assert.
if (afterRange && ((afterRange->startPosition().anchorNode()->compareDocumentPosition(referenceRange->endPosition().anchorNode()) & Node::DOCUMENT_POSITION_DISCONNECTED) == Node::DOCUMENT_POSITION_DISCONNECTED))
return nullptr;
ASSERT(!afterRange || afterRange->startPosition() >= referenceRange->endPosition());
if (beforeRange && ((beforeRange->endPosition().anchorNode()->compareDocumentPosition(referenceRange->startPosition().anchorNode()) & Node::DOCUMENT_POSITION_DISCONNECTED) == Node::DOCUMENT_POSITION_DISCONNECTED))
return nullptr;
ASSERT(!beforeRange || beforeRange->endPosition() <= referenceRange->startPosition());
if (!afterRange && !beforeRange)
return nullptr;
if (afterRange && !beforeRange)
return afterRange;
if (!afterRange && beforeRange)
return beforeRange;
unsigned positionsToAfterRange = Position::positionCountBetweenPositions(afterRange->startPosition(), referenceRange->endPosition());
unsigned positionsToBeforeRange = Position::positionCountBetweenPositions(beforeRange->endPosition(), referenceRange->startPosition());
return positionsToAfterRange < positionsToBeforeRange ? afterRange : beforeRange;
}
RefPtr<Range> AccessibilityObject::rangeOfStringClosestToRangeInDirection(Range* referenceRange, AccessibilitySearchDirection searchDirection, Vector<String>& searchStrings) const
{
Frame* frame = this->frame();
if (!frame)
return nullptr;
if (!referenceRange)
return nullptr;
bool isBackwardSearch = searchDirection == SearchDirectionPrevious;
FindOptions findOptions = AtWordStarts | AtWordEnds | CaseInsensitive | StartInSelection;
if (isBackwardSearch)
findOptions |= Backwards;
RefPtr<Range> closestStringRange = nullptr;
for (const auto& searchString : searchStrings) {
if (RefPtr<Range> searchStringRange = frame->editor().rangeOfString(searchString, referenceRange, findOptions)) {
if (!closestStringRange)
closestStringRange = searchStringRange;
else {
// If searching backward, use the trailing range edges to correctly determine which
// range is closest. Similarly, if searching forward, use the leading range edges.
Position closestStringPosition = isBackwardSearch ? closestStringRange->endPosition() : closestStringRange->startPosition();
Position searchStringPosition = isBackwardSearch ? searchStringRange->endPosition() : searchStringRange->startPosition();
int closestPositionOffset = closestStringPosition.computeOffsetInContainerNode();
int searchPositionOffset = searchStringPosition.computeOffsetInContainerNode();
Node* closestContainerNode = closestStringPosition.containerNode();
Node* searchContainerNode = searchStringPosition.containerNode();
short result = Range::compareBoundaryPoints(closestContainerNode, closestPositionOffset, searchContainerNode, searchPositionOffset, ASSERT_NO_EXCEPTION);
if ((!isBackwardSearch && result > 0) || (isBackwardSearch && result < 0))
closestStringRange = searchStringRange;
}
}
}
return closestStringRange;
}
// Returns the range of the entire document if there is no selection.
RefPtr<Range> AccessibilityObject::selectionRange() const
{
Frame* frame = this->frame();
if (!frame)
return nullptr;
const VisibleSelection& selection = frame->selection().selection();
if (!selection.isNone())
return selection.firstRange();
return Range::create(*frame->document());
}
RefPtr<Range> AccessibilityObject::elementRange() const
{
return AXObjectCache::rangeForNodeContents(node());
}
String AccessibilityObject::selectText(AccessibilitySelectTextCriteria* criteria)
{
ASSERT(criteria);
if (!criteria)
return String();
Frame* frame = this->frame();
if (!frame)
return String();
AccessibilitySelectTextActivity& activity = criteria->activity;
AccessibilitySelectTextAmbiguityResolution& ambiguityResolution = criteria->ambiguityResolution;
String& replacementString = criteria->replacementString;
Vector<String>& searchStrings = criteria->searchStrings;
RefPtr<Range> selectedStringRange = selectionRange();
// When starting our search again, make this a zero length range so that search forwards will find this selected range if its appropriate.
selectedStringRange->setEnd(&selectedStringRange->startContainer(), selectedStringRange->startOffset());
RefPtr<Range> closestAfterStringRange = nullptr;
RefPtr<Range> closestBeforeStringRange = nullptr;
// Search forward if necessary.
if (ambiguityResolution == ClosestAfterSelectionAmbiguityResolution || ambiguityResolution == ClosestToSelectionAmbiguityResolution)
closestAfterStringRange = rangeOfStringClosestToRangeInDirection(selectedStringRange.get(), SearchDirectionNext, searchStrings);
// Search backward if necessary.
if (ambiguityResolution == ClosestBeforeSelectionAmbiguityResolution || ambiguityResolution == ClosestToSelectionAmbiguityResolution)
closestBeforeStringRange = rangeOfStringClosestToRangeInDirection(selectedStringRange.get(), SearchDirectionPrevious, searchStrings);
// Determine which candidate is closest to the selection and perform the activity.
if (RefPtr<Range> closestStringRange = rangeClosestToRange(selectedStringRange.get(), WTFMove(closestAfterStringRange), WTFMove(closestBeforeStringRange))) {
// If the search started within a text control, ensure that the result is inside that element.
if (element() && element()->isTextFormControl()) {
if (!closestStringRange->startContainer().isDescendantOrShadowDescendantOf(element()) || !closestStringRange->endContainer().isDescendantOrShadowDescendantOf(element()))
return String();
}
String closestString = closestStringRange->text();
bool replaceSelection = false;
if (frame->selection().setSelectedRange(closestStringRange.get(), DOWNSTREAM, true)) {
switch (activity) {
case FindAndCapitalize:
replacementString = closestString;
makeCapitalized(&replacementString, 0);
replaceSelection = true;
break;
case FindAndUppercase:
replacementString = closestString.convertToUppercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
replaceSelection = true;
break;
case FindAndLowercase:
replacementString = closestString.convertToLowercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
replaceSelection = true;
break;
case FindAndReplaceActivity: {
replaceSelection = true;
// When applying find and replace activities, we want to match the capitalization of the replaced text,
// (unless we're replacing with an abbreviation.)
if (closestString.length() > 0 && replacementString.length() > 2 && replacementString != replacementString.convertToUppercaseWithoutLocale()) {
if (closestString[0] == u_toupper(closestString[0]))
makeCapitalized(&replacementString, 0);
else
replacementString = replacementString.convertToLowercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
}
break;
}
case FindAndSelectActivity:
break;
}
// A bit obvious, but worth noting the API contract for this method is that we should
// return the replacement string when replacing, but the selected string if not.
if (replaceSelection) {
frame->editor().replaceSelectionWithText(replacementString, true, true);
return replacementString;
}
return closestString;
}
}
return String();
}
bool AccessibilityObject::hasAttributesRequiredForInclusion() const
{
// These checks are simplified in the interest of execution speed.
if (!getAttribute(aria_helpAttr).isEmpty()
|| !getAttribute(aria_describedbyAttr).isEmpty()
|| !getAttribute(altAttr).isEmpty()
|| !getAttribute(titleAttr).isEmpty())
return true;
#if ENABLE(MATHML)
if (!getAttribute(MathMLNames::alttextAttr).isEmpty())
return true;
#endif
return false;
}
bool AccessibilityObject::isARIAInput(AccessibilityRole ariaRole)
{
return ariaRole == RadioButtonRole || ariaRole == CheckBoxRole || ariaRole == TextFieldRole || ariaRole == SwitchRole || ariaRole == SearchFieldRole;
}
bool AccessibilityObject::isARIAControl(AccessibilityRole ariaRole)
{
return isARIAInput(ariaRole) || ariaRole == TextAreaRole || ariaRole == ButtonRole
|| ariaRole == ComboBoxRole || ariaRole == SliderRole;
}
bool AccessibilityObject::isRangeControl() const
{
switch (roleValue()) {
case ProgressIndicatorRole:
case SliderRole:
case ScrollBarRole:
case SpinButtonRole:
return true;
default:
return false;
}
}
bool AccessibilityObject::isMeter() const
{
#if ENABLE(METER_ELEMENT)
RenderObject* renderer = this->renderer();
return renderer && renderer->isMeter();
#else
return false;
#endif
}
IntPoint AccessibilityObject::clickPoint()
{
LayoutRect rect = elementRect();
return roundedIntPoint(LayoutPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2));
}
IntRect AccessibilityObject::boundingBoxForQuads(RenderObject* obj, const Vector<FloatQuad>& quads)
{
ASSERT(obj);
if (!obj)
return IntRect();
FloatRect result;
for (const auto& quad : quads) {
FloatRect r = quad.enclosingBoundingBox();
if (!r.isEmpty()) {
if (obj->style().hasAppearance())
obj->theme().adjustRepaintRect(*obj, r);
result.unite(r);
}
}
return snappedIntRect(LayoutRect(result));
}
bool AccessibilityObject::press()
{
// The presence of the actionElement will confirm whether we should even attempt a press.
Element* actionElem = actionElement();
if (!actionElem)
return false;
if (Frame* f = actionElem->document().frame())
f->loader().resetMultipleFormSubmissionProtection();
// Hit test at this location to determine if there is a sub-node element that should act
// as the target of the action.
Element* hitTestElement = nullptr;
Document* document = this->document();
if (document) {
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AccessibilityHitTest);
HitTestResult hitTestResult(clickPoint());
document->renderView()->hitTest(request, hitTestResult);
if (hitTestResult.innerNode()) {
Node* innerNode = hitTestResult.innerNode()->deprecatedShadowAncestorNode();
if (is<Element>(*innerNode))
hitTestElement = downcast<Element>(innerNode);
else if (innerNode)
hitTestElement = innerNode->parentElement();
}
}
// Prefer the actionElement instead of this node, if the actionElement is inside this node.
Element* pressElement = this->element();
if (!pressElement || actionElem->isDescendantOf(pressElement))
pressElement = actionElem;
// Prefer the hit test element, if it is inside the target element.
if (hitTestElement && hitTestElement->isDescendantOf(pressElement))
pressElement = hitTestElement;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, document);
bool dispatchedTouchEvent = dispatchTouchEvent();
if (!dispatchedTouchEvent)
pressElement->accessKeyAction(true);
return true;
}
bool AccessibilityObject::dispatchTouchEvent()
{
bool handled = false;
#if ENABLE(IOS_TOUCH_EVENTS)
MainFrame* frame = mainFrame();
if (!frame)
return false;
frame->eventHandler().dispatchSimulatedTouchEvent(clickPoint());
#endif
return handled;
}
Frame* AccessibilityObject::frame() const
{
Node* node = this->node();
if (!node)
return nullptr;
return node->document().frame();
}
MainFrame* AccessibilityObject::mainFrame() const
{
Document* document = topDocument();
if (!document)
return nullptr;
Frame* frame = document->frame();
if (!frame)
return nullptr;
return &frame->mainFrame();
}
Document* AccessibilityObject::topDocument() const
{
if (!document())
return nullptr;
return &document()->topDocument();
}
String AccessibilityObject::language() const
{
const AtomicString& lang = getAttribute(langAttr);
if (!lang.isEmpty())
return lang;
AccessibilityObject* parent = parentObject();
// as a last resort, fall back to the content language specified in the meta tag
if (!parent) {
Document* doc = document();
if (doc)
return doc->contentLanguage();
return nullAtom;
}
return parent->language();
}
VisiblePositionRange AccessibilityObject::visiblePositionRangeForUnorderedPositions(const VisiblePosition& visiblePos1, const VisiblePosition& visiblePos2) const
{
if (visiblePos1.isNull() || visiblePos2.isNull())
return VisiblePositionRange();
// If there's no common tree scope between positions, return early.
if (!commonTreeScope(visiblePos1.deepEquivalent().deprecatedNode(), visiblePos2.deepEquivalent().deprecatedNode()))
return VisiblePositionRange();