2 * Copyright (C) 2012, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "core/accessibility/AXNodeObject.h"
32 #include "core/accessibility/AXObjectCache.h"
33 #include "core/dom/NodeTraversal.h"
34 #include "core/dom/Text.h"
35 #include "core/html/HTMLFieldSetElement.h"
36 #include "core/html/HTMLFrameElementBase.h"
37 #include "core/html/HTMLInputElement.h"
38 #include "core/html/HTMLLabelElement.h"
39 #include "core/html/HTMLLegendElement.h"
40 #include "core/html/HTMLSelectElement.h"
41 #include "core/html/HTMLTextAreaElement.h"
42 #include "core/rendering/RenderObject.h"
43 #include "platform/UserGestureIndicator.h"
44 #include "wtf/text/StringBuilder.h"
49 using namespace HTMLNames;
51 AXNodeObject::AXNodeObject(Node* node)
53 , m_ariaRole(UnknownRole)
54 , m_childrenDirty(false)
56 , m_initialized(false)
62 PassRefPtr<AXNodeObject> AXNodeObject::create(Node* node)
64 return adoptRef(new AXNodeObject(node));
67 AXNodeObject::~AXNodeObject()
72 // This function implements the ARIA accessible name as described by the Mozilla
73 // ARIA Implementer's Guide.
74 static String accessibleNameForNode(Node* node)
79 if (node->isTextNode())
80 return toText(node)->data();
82 if (isHTMLInputElement(*node))
83 return toHTMLInputElement(*node).value();
85 if (node->isHTMLElement()) {
86 const AtomicString& alt = toHTMLElement(node)->getAttribute(altAttr);
94 String AXNodeObject::accessibilityDescriptionForElements(Vector<Element*> &elements) const
96 StringBuilder builder;
97 unsigned size = elements.size();
98 for (unsigned i = 0; i < size; ++i) {
99 Element* idElement = elements[i];
101 builder.append(accessibleNameForNode(idElement));
102 for (Node* n = idElement->firstChild(); n; n = NodeTraversal::next(*n, idElement))
103 builder.append(accessibleNameForNode(n));
108 return builder.toString();
111 void AXNodeObject::alterSliderValue(bool increase)
113 if (roleValue() != SliderRole)
116 if (!getAttribute(stepAttr).isEmpty())
117 changeValueByStep(increase);
119 changeValueByPercent(increase ? 5 : -5);
122 String AXNodeObject::ariaAccessibilityDescription() const
124 String ariaLabeledBy = ariaLabeledByAttribute();
125 if (!ariaLabeledBy.isEmpty())
126 return ariaLabeledBy;
128 const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
129 if (!ariaLabel.isEmpty())
136 void AXNodeObject::ariaLabeledByElements(Vector<Element*>& elements) const
138 elementsFromAttribute(elements, aria_labeledbyAttr);
139 if (!elements.size())
140 elementsFromAttribute(elements, aria_labelledbyAttr);
143 void AXNodeObject::changeValueByStep(bool increase)
145 float step = stepValueForRange();
146 float value = valueForRange();
148 value += increase ? step : -step;
150 setValue(String::number(value));
152 axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
155 bool AXNodeObject::computeAccessibilityIsIgnored() const
158 // Double-check that an AXObject is never accessed before
159 // it's been initialized.
160 ASSERT(m_initialized);
163 // If this element is within a parent that cannot have children, it should not be exposed.
164 if (isDescendantOfBarrenParent())
167 // Ignore labels that are already referenced by a control's title UI element.
168 AXObject* controlObject = correspondingControlForLabelElement();
169 if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
172 return m_role == UnknownRole;
175 AccessibilityRole AXNodeObject::determineAccessibilityRole()
180 m_ariaRole = determineAriaRoleAttribute();
182 AccessibilityRole ariaRole = ariaRoleAttribute();
183 if (ariaRole != UnknownRole)
186 if (node()->isLink())
188 if (node()->isTextNode())
189 return StaticTextRole;
190 if (isHTMLButtonElement(*node()))
191 return buttonRoleType();
192 if (isHTMLInputElement(*node())) {
193 HTMLInputElement& input = toHTMLInputElement(*node());
194 if (input.isCheckbox())
196 if (input.isRadioButton())
197 return RadioButtonRole;
198 if (input.isTextButton())
199 return buttonRoleType();
200 if (input.isRangeControl())
203 const AtomicString& type = input.getAttribute(typeAttr);
204 if (equalIgnoringCase(type, "color"))
205 return ColorWellRole;
207 return TextFieldRole;
209 if (isHTMLSelectElement(*node())) {
210 HTMLSelectElement& selectElement = toHTMLSelectElement(*node());
211 return selectElement.multiple() ? ListBoxRole : PopUpButtonRole;
213 if (isHTMLTextAreaElement(*node()))
217 if (isHTMLDivElement(*node()))
219 if (isHTMLParagraphElement(*node()))
220 return ParagraphRole;
221 if (isHTMLLabelElement(*node()))
223 if (node()->isElementNode() && toElement(node())->isFocusable())
225 if (isHTMLAnchorElement(*node()) && isClickable())
227 if (node()->hasTagName(iframeTag))
229 if (isEmbeddedObject())
230 return EmbeddedObjectRole;
235 AccessibilityRole AXNodeObject::determineAriaRoleAttribute() const
237 const AtomicString& ariaRole = getAttribute(roleAttr);
238 if (ariaRole.isNull() || ariaRole.isEmpty())
241 AccessibilityRole role = ariaRoleToWebCoreRole(ariaRole);
243 // ARIA states if an item can get focus, it should not be presentational.
244 if (role == PresentationalRole && canSetFocusAttribute())
247 if (role == ButtonRole)
248 role = buttonRoleType();
250 if (role == TextAreaRole && !ariaIsMultiline())
251 role = TextFieldRole;
253 role = remapAriaRoleDueToParent(role);
261 void AXNodeObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
263 Node* node = this->node();
264 if (!node || !node->isElementNode())
267 TreeScope& scope = node->treeScope();
269 String idList = getAttribute(attribute).string();
270 if (idList.isEmpty())
273 idList.replace('\n', ' ');
274 Vector<String> idVector;
275 idList.split(' ', idVector);
277 unsigned size = idVector.size();
278 for (unsigned i = 0; i < size; ++i) {
279 AtomicString idName(idVector[i]);
280 Element* idElement = scope.getElementById(idName);
282 elements.append(idElement);
286 // If you call node->rendererIsEditable() since that will return true if an ancestor is editable.
287 // This only returns true if this is the element that actually has the contentEditable attribute set.
288 bool AXNodeObject::hasContentEditableAttributeSet() const
290 if (!hasAttribute(contenteditableAttr))
292 const AtomicString& contentEditableValue = getAttribute(contenteditableAttr);
293 // Both "true" (case-insensitive) and the empty string count as true.
294 return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "true");
297 bool AXNodeObject::isDescendantOfBarrenParent() const
299 for (AXObject* object = parentObject(); object; object = object->parentObject()) {
300 if (!object->canHaveChildren())
307 bool AXNodeObject::isGenericFocusableElement() const
309 if (!canSetFocusAttribute())
312 // If it's a control, it's not generic.
316 // If it has an aria role, it's not generic.
317 if (m_ariaRole != UnknownRole)
320 // If the content editable attribute is set on this element, that's the reason
321 // it's focusable, and existing logic should handle this case already - so it's not a
322 // generic focusable element.
324 if (hasContentEditableAttributeSet())
327 // The web area and body element are both focusable, but existing logic handles these
328 // cases already, so we don't need to include them here.
329 if (roleValue() == WebAreaRole)
331 if (isHTMLBodyElement(node()))
334 // An SVG root is focusable by default, but it's probably not interactive, so don't
335 // include it. It can still be made accessible by giving it an ARIA role.
336 if (roleValue() == SVGRootRole)
342 HTMLLabelElement* AXNodeObject::labelForElement(Element* element) const
344 if (!element->isHTMLElement() || !toHTMLElement(element)->isLabelable())
347 const AtomicString& id = element->getIdAttribute();
349 if (HTMLLabelElement* label = element->treeScope().labelElementForId(id))
353 for (Element* parent = element->parentElement(); parent; parent = parent->parentElement()) {
354 if (isHTMLLabelElement(*parent))
355 return toHTMLLabelElement(parent);
361 AXObject* AXNodeObject::menuButtonForMenu() const
363 Element* menuItem = menuItemElementForMenu();
366 // ARIA just has generic menu items. AppKit needs to know if this is a top level items like MenuBarButton or MenuBarItem
367 AXObject* menuItemAX = axObjectCache()->getOrCreate(menuItem);
368 if (menuItemAX && menuItemAX->isMenuButton())
374 static Element* siblingWithAriaRole(String role, Node* node)
376 Node* parent = node->parentNode();
380 for (Element* sibling = ElementTraversal::firstChild(*parent); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
381 const AtomicString& siblingAriaRole = sibling->getAttribute(roleAttr);
382 if (equalIgnoringCase(siblingAriaRole, role))
389 Element* AXNodeObject::menuItemElementForMenu() const
391 if (ariaRoleAttribute() != MenuRole)
394 return siblingWithAriaRole("menuitem", node());
397 Element* AXNodeObject::mouseButtonListener() const
399 Node* node = this->node();
403 // check if our parent is a mouse button listener
404 while (node && !node->isElementNode())
405 node = node->parentNode();
410 // FIXME: Do the continuation search like anchorElement does
411 for (Element* element = toElement(node); element; element = element->parentElement()) {
412 if (element->getAttributeEventListener(EventTypeNames::click) || element->getAttributeEventListener(EventTypeNames::mousedown) || element->getAttributeEventListener(EventTypeNames::mouseup))
419 AccessibilityRole AXNodeObject::remapAriaRoleDueToParent(AccessibilityRole role) const
421 // Some objects change their role based on their parent.
422 // However, asking for the unignoredParent calls accessibilityIsIgnored(), which can trigger a loop.
423 // While inside the call stack of creating an element, we need to avoid accessibilityIsIgnored().
424 // https://bugs.webkit.org/show_bug.cgi?id=65174
426 if (role != ListBoxOptionRole && role != MenuItemRole)
429 for (AXObject* parent = parentObject(); parent && !parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
430 AccessibilityRole parentAriaRole = parent->ariaRoleAttribute();
432 // Selects and listboxes both have options as child roles, but they map to different roles within WebCore.
433 if (role == ListBoxOptionRole && parentAriaRole == MenuRole)
435 // An aria "menuitem" may map to MenuButton or MenuItem depending on its parent.
436 if (role == MenuItemRole && parentAriaRole == GroupRole)
437 return MenuButtonRole;
439 // If the parent had a different role, then we don't need to continue searching up the chain.
447 void AXNodeObject::init()
450 ASSERT(!m_initialized);
451 m_initialized = true;
453 m_role = determineAccessibilityRole();
456 void AXNodeObject::detach()
463 bool AXNodeObject::isAnchor() const
465 return !isNativeImage() && isLink();
468 bool AXNodeObject::isControl() const
470 Node* node = this->node();
474 return ((node->isElementNode() && toElement(node)->isFormControlElement())
475 || AXObject::isARIAControl(ariaRoleAttribute()));
478 bool AXNodeObject::isEmbeddedObject() const
481 && (node()->hasTagName(objectTag) || node()->hasTagName(embedTag)
482 || node()->hasTagName(appletTag));
485 bool AXNodeObject::isFieldset() const
487 return isHTMLFieldSetElement(node());
490 bool AXNodeObject::isHeading() const
492 return roleValue() == HeadingRole;
495 bool AXNodeObject::isHovered() const
497 Node* node = this->node();
501 return node->hovered();
504 bool AXNodeObject::isImage() const
506 return roleValue() == ImageRole;
509 bool AXNodeObject::isImageButton() const
511 return isNativeImage() && isButton();
514 bool AXNodeObject::isInputImage() const
516 Node* node = this->node();
517 if (roleValue() == ButtonRole && isHTMLInputElement(node))
518 return toHTMLInputElement(*node).isImageButton();
523 bool AXNodeObject::isLink() const
525 return roleValue() == LinkRole;
528 bool AXNodeObject::isMenu() const
530 return roleValue() == MenuRole;
533 bool AXNodeObject::isMenuButton() const
535 return roleValue() == MenuButtonRole;
538 bool AXNodeObject::isMultiSelectable() const
540 const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr);
541 if (equalIgnoringCase(ariaMultiSelectable, "true"))
543 if (equalIgnoringCase(ariaMultiSelectable, "false"))
546 return isHTMLSelectElement(node()) && toHTMLSelectElement(*node()).multiple();
549 bool AXNodeObject::isNativeCheckboxOrRadio() const
551 Node* node = this->node();
552 if (!isHTMLInputElement(node))
555 HTMLInputElement* input = toHTMLInputElement(node);
556 return input->isCheckbox() || input->isRadioButton();
559 bool AXNodeObject::isNativeImage() const
561 Node* node = this->node();
565 if (isHTMLImageElement(*node))
568 if (isHTMLAppletElement(*node) || isHTMLEmbedElement(*node) || isHTMLObjectElement(*node))
571 if (isHTMLInputElement(*node))
572 return toHTMLInputElement(*node).isImageButton();
577 bool AXNodeObject::isNativeTextControl() const
579 Node* node = this->node();
583 if (isHTMLTextAreaElement(*node))
586 if (isHTMLInputElement(*node)) {
587 HTMLInputElement* input = toHTMLInputElement(node);
588 return input->isText() || input->isNumberField();
594 bool AXNodeObject::isNonNativeTextControl() const
596 if (isNativeTextControl())
599 if (hasContentEditableAttributeSet())
602 if (isARIATextControl())
608 bool AXNodeObject::isPasswordField() const
610 Node* node = this->node();
611 if (!isHTMLInputElement(node))
614 if (ariaRoleAttribute() != UnknownRole)
617 return toHTMLInputElement(node)->isPasswordField();
620 bool AXNodeObject::isProgressIndicator() const
622 return roleValue() == ProgressIndicatorRole;
625 bool AXNodeObject::isSlider() const
627 return roleValue() == SliderRole;
630 bool AXNodeObject::isChecked() const
632 Node* node = this->node();
636 // First test for native checkedness semantics
637 if (isHTMLInputElement(*node))
638 return toHTMLInputElement(*node).shouldAppearChecked();
640 // Else, if this is an ARIA checkbox or radio, respect the aria-checked attribute
641 AccessibilityRole ariaRole = ariaRoleAttribute();
642 if (ariaRole == RadioButtonRole || ariaRole == CheckBoxRole) {
643 if (equalIgnoringCase(getAttribute(aria_checkedAttr), "true"))
648 // Otherwise it's not checked
652 bool AXNodeObject::isClickable() const
655 if (node()->isElementNode() && toElement(node())->isDisabledFormControl())
658 // Note: we can't call node()->willRespondToMouseClickEvents() because that triggers a style recalc and can delete this.
659 if (node()->hasEventListeners(EventTypeNames::mouseup) || node()->hasEventListeners(EventTypeNames::mousedown) || node()->hasEventListeners(EventTypeNames::click) || node()->hasEventListeners(EventTypeNames::DOMActivate))
663 return AXObject::isClickable();
666 bool AXNodeObject::isEnabled() const
668 if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
671 Node* node = this->node();
672 if (!node || !node->isElementNode())
675 return !toElement(node)->isDisabledFormControl();
678 bool AXNodeObject::isIndeterminate() const
680 Node* node = this->node();
681 if (!isHTMLInputElement(node))
684 return toHTMLInputElement(node)->shouldAppearIndeterminate();
687 bool AXNodeObject::isPressed() const
692 Node* node = this->node();
696 // If this is an ARIA button, check the aria-pressed attribute rather than node()->active()
697 if (ariaRoleAttribute() == ButtonRole) {
698 if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true"))
703 return node->active();
706 bool AXNodeObject::isReadOnly() const
708 Node* node = this->node();
712 if (isHTMLTextAreaElement(*node))
713 return toHTMLTextAreaElement(*node).isReadOnly();
715 if (isHTMLInputElement(*node)) {
716 HTMLInputElement& input = toHTMLInputElement(*node);
717 if (input.isTextField())
718 return input.isReadOnly();
721 return !node->rendererIsEditable();
724 bool AXNodeObject::isRequired() const
726 if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
729 Node* n = this->node();
730 if (n && (n->isElementNode() && toElement(n)->isFormControlElement()))
731 return toHTMLFormControlElement(n)->isRequired();
736 bool AXNodeObject::canSetFocusAttribute() const
738 Node* node = this->node();
745 // NOTE: It would be more accurate to ask the document whether setFocusedNode() would
746 // do anything. For example, setFocusedNode() will do nothing if the current focused
747 // node will not relinquish the focus.
751 if (isDisabledFormControl(node))
754 return node->isElementNode() && toElement(node)->supportsFocus();
757 bool AXNodeObject::canSetValueAttribute() const
759 if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
762 if (isProgressIndicator() || isSlider())
765 if (isTextControl() && !isNativeTextControl())
768 // Any node could be contenteditable, so isReadOnly should be relied upon
769 // for this information for all elements.
770 return !isReadOnly();
773 bool AXNodeObject::canvasHasFallbackContent() const
775 Node* node = this->node();
776 if (!isHTMLCanvasElement(node))
779 // If it has any children that are elements, we'll assume it might be fallback
780 // content. If it has no children or its only children are not elements
781 // (e.g. just text nodes), it doesn't have fallback content.
782 return ElementTraversal::firstChild(*node);
785 bool AXNodeObject::exposesTitleUIElement() const
790 // If this control is ignored (because it's invisible),
791 // then the label needs to be exposed so it can be visible to accessibility.
792 if (accessibilityIsIgnored())
795 // ARIA: section 2A, bullet #3 says if aria-labeledby or aria-label appears, it should
796 // override the "label" element association.
797 bool hasTextAlternative = (!ariaLabeledByAttribute().isEmpty() || !getAttribute(aria_labelAttr).isEmpty());
799 // Checkboxes and radio buttons use the text of their title ui element as their own AXTitle.
800 // This code controls whether the title ui element should appear in the AX tree (usually, no).
801 // It should appear if the control already has a label (which will be used as the AXTitle instead).
802 if (isCheckboxOrRadio())
803 return hasTextAlternative;
805 // When controls have their own descriptions, the title element should be ignored.
806 if (hasTextAlternative)
812 int AXNodeObject::headingLevel() const
814 // headings can be in block flow and non-block flow
815 Node* node = this->node();
819 if (ariaRoleAttribute() == HeadingRole)
820 return getAttribute(aria_levelAttr).toInt();
822 if (node->hasTagName(h1Tag))
825 if (node->hasTagName(h2Tag))
828 if (node->hasTagName(h3Tag))
831 if (node->hasTagName(h4Tag))
834 if (node->hasTagName(h5Tag))
837 if (node->hasTagName(h6Tag))
843 unsigned AXNodeObject::hierarchicalLevel() const
845 Node* node = this->node();
846 if (!node || !node->isElementNode())
848 Element* element = toElement(node);
849 String ariaLevel = element->getAttribute(aria_levelAttr);
850 if (!ariaLevel.isEmpty())
851 return ariaLevel.toInt();
853 // Only tree item will calculate its level through the DOM currently.
854 if (roleValue() != TreeItemRole)
857 // Hierarchy leveling starts at 1, to match the aria-level spec.
858 // We measure tree hierarchy by the number of groups that the item is within.
860 for (AXObject* parent = parentObject(); parent; parent = parent->parentObject()) {
861 AccessibilityRole parentRole = parent->roleValue();
862 if (parentRole == GroupRole)
864 else if (parentRole == TreeRole)
871 String AXNodeObject::text() const
873 // If this is a user defined static text, use the accessible name computation.
874 if (ariaRoleAttribute() == StaticTextRole)
875 return ariaAccessibilityDescription();
877 if (!isTextControl())
880 Node* node = this->node();
884 if (isNativeTextControl() && (isHTMLTextAreaElement(*node) || isHTMLInputElement(*node)))
885 return toHTMLTextFormControlElement(*node).value();
887 if (!node->isElementNode())
890 return toElement(node)->innerText();
893 AXObject* AXNodeObject::titleUIElement() const
895 if (!node() || !node()->isElementNode())
899 return axObjectCache()->getOrCreate(toHTMLFieldSetElement(node())->legend());
901 HTMLLabelElement* label = labelForElement(toElement(node()));
903 return axObjectCache()->getOrCreate(label);
908 AccessibilityButtonState AXNodeObject::checkboxOrRadioValue() const
910 if (isNativeCheckboxOrRadio())
911 return isChecked() ? ButtonStateOn : ButtonStateOff;
913 return AXObject::checkboxOrRadioValue();
916 void AXNodeObject::colorValue(int& r, int& g, int& b) const
925 if (!isHTMLInputElement(node()))
928 HTMLInputElement* input = toHTMLInputElement(node());
929 const AtomicString& type = input->getAttribute(typeAttr);
930 if (!equalIgnoringCase(type, "color"))
933 // HTMLInputElement::value always returns a string parseable by Color.
935 bool success = color.setFromString(input->value());
936 ASSERT_UNUSED(success, success);
942 String AXNodeObject::valueDescription() const
944 if (!supportsRangeValue())
947 return getAttribute(aria_valuetextAttr).string();
950 float AXNodeObject::valueForRange() const
952 if (hasAttribute(aria_valuenowAttr))
953 return getAttribute(aria_valuenowAttr).toFloat();
955 if (isHTMLInputElement(node())) {
956 HTMLInputElement& input = toHTMLInputElement(*node());
957 if (input.isRangeControl())
958 return input.valueAsNumber();
964 float AXNodeObject::maxValueForRange() const
966 if (hasAttribute(aria_valuemaxAttr))
967 return getAttribute(aria_valuemaxAttr).toFloat();
969 if (isHTMLInputElement(node())) {
970 HTMLInputElement& input = toHTMLInputElement(*node());
971 if (input.isRangeControl())
972 return input.maximum();
978 float AXNodeObject::minValueForRange() const
980 if (hasAttribute(aria_valueminAttr))
981 return getAttribute(aria_valueminAttr).toFloat();
983 if (isHTMLInputElement(node())) {
984 HTMLInputElement& input = toHTMLInputElement(*node());
985 if (input.isRangeControl())
986 return input.minimum();
992 float AXNodeObject::stepValueForRange() const
994 return getAttribute(stepAttr).toFloat();
997 String AXNodeObject::stringValue() const
999 Node* node = this->node();
1003 if (ariaRoleAttribute() == StaticTextRole) {
1004 String staticText = text();
1005 if (!staticText.length())
1006 staticText = textUnderElement();
1010 if (node->isTextNode())
1011 return textUnderElement();
1013 if (isHTMLSelectElement(*node)) {
1014 HTMLSelectElement& selectElement = toHTMLSelectElement(*node);
1015 int selectedIndex = selectElement.selectedIndex();
1016 const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& listItems = selectElement.listItems();
1017 if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
1018 const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
1019 if (!overriddenDescription.isNull())
1020 return overriddenDescription;
1022 if (!selectElement.multiple())
1023 return selectElement.value();
1027 if (isTextControl())
1030 // FIXME: We might need to implement a value here for more types
1031 // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
1032 // this would require subclassing or making accessibilityAttributeNames do something other than return a
1033 // single static array.
1037 String AXNodeObject::ariaDescribedByAttribute() const
1039 Vector<Element*> elements;
1040 elementsFromAttribute(elements, aria_describedbyAttr);
1042 return accessibilityDescriptionForElements(elements);
1046 String AXNodeObject::ariaLabeledByAttribute() const
1048 Vector<Element*> elements;
1049 ariaLabeledByElements(elements);
1051 return accessibilityDescriptionForElements(elements);
1054 AccessibilityRole AXNodeObject::ariaRoleAttribute() const
1059 // When building the textUnderElement for an object, determine whether or not
1060 // we should include the inner text of this given descendant object or skip it.
1061 static bool shouldUseAccessiblityObjectInnerText(AXObject* obj)
1063 // Consider this hypothetical example:
1066 // Table of contents
1068 // <a href="#start">Jump to start of book</a>
1070 // <li><a href="#1">Chapter 1</a></li>
1071 // <li><a href="#1">Chapter 2</a></li>
1075 // The goal is to return a reasonable title for the outer container div, because
1076 // it's focusable - but without making its title be the full inner text, which is
1077 // quite long. As a heuristic, skip links, controls, and elements that are usually
1078 // containers with lots of children.
1080 // Skip hidden children
1081 if (obj->isInertOrAriaHidden())
1084 // Skip focusable children, so we don't include the text of links and controls.
1085 if (obj->canSetFocusAttribute())
1088 // Skip big container elements like lists, tables, etc.
1089 if (obj->isList() || obj->isAXTable() || obj->isTree() || obj->isCanvas())
1095 String AXNodeObject::textUnderElement() const
1097 Node* node = this->node();
1098 if (node && node->isTextNode())
1099 return toText(node)->wholeText();
1101 StringBuilder builder;
1102 for (AXObject* child = firstChild(); child; child = child->nextSibling()) {
1103 if (!shouldUseAccessiblityObjectInnerText(child))
1106 if (child->isAXNodeObject()) {
1107 Vector<AccessibilityText> textOrder;
1108 toAXNodeObject(child)->alternativeText(textOrder);
1109 if (textOrder.size() > 0) {
1110 builder.append(textOrder[0].text);
1115 builder.append(child->textUnderElement());
1118 return builder.toString();
1121 String AXNodeObject::accessibilityDescription() const
1123 // Static text should not have a description, it should only have a stringValue.
1124 if (roleValue() == StaticTextRole)
1127 String ariaDescription = ariaAccessibilityDescription();
1128 if (!ariaDescription.isEmpty())
1129 return ariaDescription;
1131 if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
1132 // Images should use alt as long as the attribute is present, even if empty.
1133 // Otherwise, it should fallback to other methods, like the title attribute.
1134 const AtomicString& alt = getAttribute(altAttr);
1139 // An element's descriptive text is comprised of title() (what's visible on the screen) and accessibilityDescription() (other descriptive text).
1140 // Both are used to generate what a screen reader speaks.
1141 // If this point is reached (i.e. there's no accessibilityDescription) and there's no title(), we should fallback to using the title attribute.
1142 // The title attribute is normally used as help text (because it is a tooltip), but if there is nothing else available, this should be used (according to ARIA).
1143 if (title().isEmpty())
1144 return getAttribute(titleAttr);
1149 String AXNodeObject::title() const
1151 Node* node = this->node();
1155 bool isInputElement = isHTMLInputElement(*node);
1156 if (isInputElement) {
1157 HTMLInputElement& input = toHTMLInputElement(*node);
1158 if (input.isTextButton())
1159 return input.valueWithDefault();
1162 if (isInputElement || AXObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
1163 HTMLLabelElement* label = labelForElement(toElement(node));
1164 if (label && !exposesTitleUIElement())
1165 return label->innerText();
1168 // If this node isn't rendered, there's no inner text we can extract from a select element.
1169 if (!isAXRenderObject() && isHTMLSelectElement(*node))
1172 switch (roleValue()) {
1173 case PopUpButtonRole:
1174 // Native popup buttons should not use their button children's text as a title. That value is retrieved through stringValue().
1175 if (isHTMLSelectElement(*node))
1178 case ToggleButtonRole:
1180 case ListBoxOptionRole:
1181 case MenuButtonRole:
1183 case RadioButtonRole:
1185 return textUnderElement();
1186 // SVGRoots should not use the text under itself as a title. That could include the text of objects like <text>.
1193 if (isHeading() || isLink())
1194 return textUnderElement();
1196 // If it's focusable but it's not content editable or a known control type, then it will appear to
1197 // the user as a single atomic object, so we should use its text as the default title.
1198 if (isGenericFocusableElement())
1199 return textUnderElement();
1204 String AXNodeObject::helpText() const
1206 Node* node = this->node();
1210 const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
1211 if (!ariaHelp.isEmpty())
1214 String describedBy = ariaDescribedByAttribute();
1215 if (!describedBy.isEmpty())
1218 String description = accessibilityDescription();
1219 for (Node* curr = node; curr; curr = curr->parentNode()) {
1220 if (curr->isHTMLElement()) {
1221 const AtomicString& summary = toElement(curr)->getAttribute(summaryAttr);
1222 if (!summary.isEmpty())
1225 // The title attribute should be used as help text unless it is already being used as descriptive text.
1226 const AtomicString& title = toElement(curr)->getAttribute(titleAttr);
1227 if (!title.isEmpty() && description != title)
1231 // Only take help text from an ancestor element if its a group or an unknown role. If help was
1232 // added to those kinds of elements, it is likely it was meant for a child element.
1233 AXObject* axObj = axObjectCache()->getOrCreate(curr);
1235 AccessibilityRole role = axObj->roleValue();
1236 if (role != GroupRole && role != UnknownRole)
1244 LayoutRect AXNodeObject::elementRect() const
1246 // First check if it has a custom rect, for example if this element is tied to a canvas path.
1247 if (!m_explicitElementRect.isEmpty())
1248 return m_explicitElementRect;
1250 // AXNodeObjects have no mechanism yet to return a size or position.
1251 // For now, let's return the position of the ancestor that does have a position,
1252 // and make it the width of that parent, and about the height of a line of text, so that it's clear the object is a child of the parent.
1254 LayoutRect boundingBox;
1256 for (AXObject* positionProvider = parentObject(); positionProvider; positionProvider = positionProvider->parentObject()) {
1257 if (positionProvider->isAXRenderObject()) {
1258 LayoutRect parentRect = positionProvider->elementRect();
1259 boundingBox.setSize(LayoutSize(parentRect.width(), LayoutUnit(std::min(10.0f, parentRect.height().toFloat()))));
1260 boundingBox.setLocation(parentRect.location());
1268 AXObject* AXNodeObject::parentObject() const
1273 Node* parentObj = node()->parentNode();
1275 return axObjectCache()->getOrCreate(parentObj);
1280 AXObject* AXNodeObject::parentObjectIfExists() const
1282 return parentObject();
1285 AXObject* AXNodeObject::firstChild() const
1290 Node* firstChild = node()->firstChild();
1295 return axObjectCache()->getOrCreate(firstChild);
1298 AXObject* AXNodeObject::nextSibling() const
1303 Node* nextSibling = node()->nextSibling();
1307 return axObjectCache()->getOrCreate(nextSibling);
1310 void AXNodeObject::addChildren()
1312 // If the need to add more children in addition to existing children arises,
1313 // childrenChanged should have been called, leaving the object with no children.
1314 ASSERT(!m_haveChildren);
1319 m_haveChildren = true;
1321 // The only time we add children from the DOM tree to a node with a renderer is when it's a canvas.
1322 if (renderer() && !isHTMLCanvasElement(*m_node))
1325 for (Node* child = m_node->firstChild(); child; child = child->nextSibling())
1326 addChild(axObjectCache()->getOrCreate(child));
1329 void AXNodeObject::addChild(AXObject* child)
1331 insertChild(child, m_children.size());
1334 void AXNodeObject::insertChild(AXObject* child, unsigned index)
1339 // If the parent is asking for this child's children, then either it's the first time (and clearing is a no-op),
1340 // or its visibility has changed. In the latter case, this child may have a stale child cached.
1341 // This can prevent aria-hidden changes from working correctly. Hence, whenever a parent is getting children, ensure data is not stale.
1342 child->clearChildren();
1344 if (child->accessibilityIsIgnored()) {
1345 AccessibilityChildrenVector children = child->children();
1346 size_t length = children.size();
1347 for (size_t i = 0; i < length; ++i)
1348 m_children.insert(index + i, children[i]);
1350 ASSERT(child->parentObject() == this);
1351 m_children.insert(index, child);
1355 bool AXNodeObject::canHaveChildren() const
1357 // If this is an AXRenderObject, then it's okay if this object
1358 // doesn't have a node - there are some renderers that don't have associated
1359 // nodes, like scroll areas and css-generated text.
1360 if (!node() && !isAXRenderObject())
1363 // Elements that should not have children
1364 switch (roleValue()) {
1367 case PopUpButtonRole:
1369 case RadioButtonRole:
1371 case ToggleButtonRole:
1372 case ListBoxOptionRole:
1375 case StaticTextRole:
1376 if (!axObjectCache()->inlineTextBoxAccessibility())
1383 Element* AXNodeObject::actionElement() const
1385 Node* node = this->node();
1389 if (isHTMLInputElement(*node)) {
1390 HTMLInputElement& input = toHTMLInputElement(*node);
1391 if (!input.isDisabledFormControl() && (isCheckboxOrRadio() || input.isTextButton()))
1393 } else if (isHTMLButtonElement(*node)) {
1394 return toElement(node);
1397 if (isFileUploadButton())
1398 return toElement(node);
1400 if (AXObject::isARIAInput(ariaRoleAttribute()))
1401 return toElement(node);
1403 if (isImageButton())
1404 return toElement(node);
1406 if (isHTMLSelectElement(*node))
1407 return toElement(node);
1409 switch (roleValue()) {
1411 case PopUpButtonRole:
1412 case ToggleButtonRole:
1416 return toElement(node);
1421 Element* elt = anchorElement();
1423 elt = mouseButtonListener();
1427 Element* AXNodeObject::anchorElement() const
1429 Node* node = this->node();
1433 AXObjectCache* cache = axObjectCache();
1435 // search up the DOM tree for an anchor element
1436 // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
1437 for ( ; node; node = node->parentNode()) {
1438 if (isHTMLAnchorElement(*node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
1439 return toElement(node);
1445 Document* AXNodeObject::document() const
1449 return &node()->document();
1452 void AXNodeObject::setNode(Node* node)
1457 AXObject* AXNodeObject::correspondingControlForLabelElement() const
1459 HTMLLabelElement* labelElement = labelElementContainer();
1463 HTMLElement* correspondingControl = labelElement->control();
1464 if (!correspondingControl)
1467 // Make sure the corresponding control isn't a descendant of this label
1468 // that's in the middle of being destroyed.
1469 if (correspondingControl->renderer() && !correspondingControl->renderer()->parent())
1472 return axObjectCache()->getOrCreate(correspondingControl);
1475 HTMLLabelElement* AXNodeObject::labelElementContainer() const
1480 // the control element should not be considered part of the label
1484 // find if this has a ancestor that is a label
1485 return Traversal<HTMLLabelElement>::firstAncestorOrSelf(*node());
1488 void AXNodeObject::setFocused(bool on)
1490 if (!canSetFocusAttribute())
1493 Document* document = this->document();
1495 document->setFocusedElement(nullptr);
1497 Node* node = this->node();
1498 if (node && node->isElementNode()) {
1499 // If this node is already the currently focused node, then calling focus() won't do anything.
1500 // That is a problem when focus is removed from the webpage to chrome, and then returns.
1501 // In these cases, we need to do what keyboard and mouse focus do, which is reset focus first.
1502 if (document->focusedElement() == node)
1503 document->setFocusedElement(nullptr);
1505 toElement(node)->focus();
1507 document->setFocusedElement(nullptr);
1512 void AXNodeObject::increment()
1514 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
1515 alterSliderValue(true);
1518 void AXNodeObject::decrement()
1520 UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
1521 alterSliderValue(false);
1524 void AXNodeObject::childrenChanged()
1526 // This method is meant as a quick way of marking a portion of the accessibility tree dirty.
1527 if (!node() && !renderer())
1530 axObjectCache()->postNotification(this, document(), AXObjectCache::AXChildrenChanged, true);
1532 // Go up the accessibility parent chain, but only if the element already exists. This method is
1533 // called during render layouts, minimal work should be done.
1534 // If AX elements are created now, they could interrogate the render tree while it's in a funky state.
1535 // At the same time, process ARIA live region changes.
1536 for (AXObject* parent = this; parent; parent = parent->parentObjectIfExists()) {
1537 parent->setNeedsToUpdateChildren();
1539 // These notifications always need to be sent because screenreaders are reliant on them to perform.
1540 // In other words, they need to be sent even when the screen reader has not accessed this live region since the last update.
1542 // If this element supports ARIA live regions, then notify the AT of changes.
1543 if (parent->supportsARIALiveRegion())
1544 axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXLiveRegionChanged, true);
1546 // If this element is an ARIA text box or content editable, post a "value changed" notification on it
1547 // so that it behaves just like a native input element or textarea.
1548 if (isNonNativeTextControl())
1549 axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXValueChanged, true);
1553 void AXNodeObject::selectionChanged()
1555 // Post the selected text changed event on the first ancestor that's
1556 // focused (to handle form controls, ARIA text boxes and contentEditable),
1557 // or the web area if the selection is just in the document somewhere.
1558 if (isFocused() || isWebArea())
1559 axObjectCache()->postNotification(this, document(), AXObjectCache::AXSelectedTextChanged, true);
1561 AXObject::selectionChanged(); // Calls selectionChanged on parent.
1564 void AXNodeObject::textChanged()
1566 // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
1567 // then notify the AT of changes.
1568 AXObjectCache* cache = axObjectCache();
1569 for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
1570 AXObject* parent = cache->get(parentNode);
1574 if (parent->supportsARIALiveRegion())
1575 cache->postNotification(parentNode, AXObjectCache::AXLiveRegionChanged, true);
1577 // If this element is an ARIA text box or content editable, post a "value changed" notification on it
1578 // so that it behaves just like a native input element or textarea.
1579 if (parent->isNonNativeTextControl())
1580 cache->postNotification(parentNode, AXObjectCache::AXValueChanged, true);
1584 void AXNodeObject::updateAccessibilityRole()
1586 bool ignoredStatus = accessibilityIsIgnored();
1587 m_role = determineAccessibilityRole();
1589 // The AX hierarchy only needs to be updated if the ignored status of an element has changed.
1590 if (ignoredStatus != accessibilityIsIgnored())
1594 String AXNodeObject::alternativeTextForWebArea() const
1596 // The WebArea description should follow this order:
1597 // aria-label on the <html>
1598 // title on the <html>
1599 // <title> inside the <head> (of it was set through JS)
1600 // name on the <html>
1602 // aria-label on the <iframe>
1603 // title on the <iframe>
1604 // name on the <iframe>
1606 Document* document = this->document();
1610 // Check if the HTML element has an aria-label for the webpage.
1611 if (Element* documentElement = document->documentElement()) {
1612 const AtomicString& ariaLabel = documentElement->getAttribute(aria_labelAttr);
1613 if (!ariaLabel.isEmpty())
1617 Node* owner = document->ownerElement();
1619 if (isHTMLFrameElementBase(*owner)) {
1620 const AtomicString& title = toElement(owner)->getAttribute(titleAttr);
1621 if (!title.isEmpty())
1623 return toElement(owner)->getNameAttribute();
1625 if (owner->isHTMLElement())
1626 return toHTMLElement(owner)->getNameAttribute();
1629 String documentTitle = document->title();
1630 if (!documentTitle.isEmpty())
1631 return documentTitle;
1633 owner = document->body();
1634 if (owner && owner->isHTMLElement())
1635 return toHTMLElement(owner)->getNameAttribute();
1640 void AXNodeObject::alternativeText(Vector<AccessibilityText>& textOrder) const
1643 String webAreaText = alternativeTextForWebArea();
1644 if (!webAreaText.isEmpty())
1645 textOrder.append(AccessibilityText(webAreaText, AlternativeText));
1649 ariaLabeledByText(textOrder);
1651 const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
1652 if (!ariaLabel.isEmpty())
1653 textOrder.append(AccessibilityText(ariaLabel, AlternativeText));
1655 if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
1656 // Images should use alt as long as the attribute is present, even if empty.
1657 // Otherwise, it should fallback to other methods, like the title attribute.
1658 const AtomicString& alt = getAttribute(altAttr);
1660 textOrder.append(AccessibilityText(alt, AlternativeText));
1664 void AXNodeObject::ariaLabeledByText(Vector<AccessibilityText>& textOrder) const
1666 String ariaLabeledBy = ariaLabeledByAttribute();
1667 if (!ariaLabeledBy.isEmpty()) {
1668 Vector<Element*> elements;
1669 ariaLabeledByElements(elements);
1671 unsigned length = elements.size();
1672 for (unsigned k = 0; k < length; k++) {
1673 RefPtr<AXObject> axElement = axObjectCache()->getOrCreate(elements[k]);
1674 textOrder.append(AccessibilityText(ariaLabeledBy, AlternativeText, axElement));
1679 void AXNodeObject::changeValueByPercent(float percentChange)
1681 float range = maxValueForRange() - minValueForRange();
1682 float value = valueForRange();
1684 value += range * (percentChange / 100);
1685 setValue(String::number(value));
1687 axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
1690 } // namespace WebCore