2 * Copyright (C) 2008 Apple 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 "AccessibilityRenderObject.h"
32 #include "AXObjectCache.h"
33 #include "AccessibilityImageMapLink.h"
34 #include "AccessibilityListBox.h"
35 #include "AccessibilitySpinButton.h"
36 #include "AccessibilityTable.h"
37 #include "EventNames.h"
38 #include "FloatRect.h"
40 #include "FrameLoader.h"
41 #include "FrameSelection.h"
42 #include "HTMLAreaElement.h"
43 #include "HTMLFormElement.h"
44 #include "HTMLFrameElementBase.h"
45 #include "HTMLImageElement.h"
46 #include "HTMLInputElement.h"
47 #include "HTMLLabelElement.h"
48 #include "HTMLMapElement.h"
49 #include "HTMLNames.h"
50 #include "HTMLOptGroupElement.h"
51 #include "HTMLOptionElement.h"
52 #include "HTMLOptionsCollection.h"
53 #include "HTMLSelectElement.h"
54 #include "HTMLTextAreaElement.h"
55 #include "HitTestRequest.h"
56 #include "HitTestResult.h"
57 #include "LocalizedStrings.h"
58 #include "MathMLNames.h"
61 #include "ProgressTracker.h"
62 #include "RenderButton.h"
63 #include "RenderFieldset.h"
64 #include "RenderFileUploadControl.h"
65 #include "RenderHTMLCanvas.h"
66 #include "RenderImage.h"
67 #include "RenderInline.h"
68 #include "RenderLayer.h"
69 #include "RenderListBox.h"
70 #include "RenderListMarker.h"
71 #include "RenderMenuList.h"
72 #include "RenderText.h"
73 #include "RenderTextControl.h"
74 #include "RenderTextControlSingleLine.h"
75 #include "RenderTextFragment.h"
76 #include "RenderTheme.h"
77 #include "RenderView.h"
78 #include "RenderWidget.h"
79 #include "RenderedPosition.h"
81 #include "TextControlInnerElements.h"
82 #include "TextIterator.h"
83 #include "htmlediting.h"
84 #include "visible_units.h"
85 #include <wtf/StdLibExtras.h>
86 #include <wtf/text/StringBuilder.h>
87 #include <wtf/unicode/CharacterNames.h>
93 using namespace HTMLNames;
95 AccessibilityRenderObject::AccessibilityRenderObject(RenderObject* renderer)
96 : AccessibilityNodeObject(renderer->node())
97 , m_renderer(renderer)
100 m_renderer->setHasAXObject(true);
104 AccessibilityRenderObject::~AccessibilityRenderObject()
106 ASSERT(isDetached());
109 void AccessibilityRenderObject::init()
111 AccessibilityNodeObject::init();
114 PassRefPtr<AccessibilityRenderObject> AccessibilityRenderObject::create(RenderObject* renderer)
116 AccessibilityRenderObject* obj = new AccessibilityRenderObject(renderer);
118 return adoptRef(obj);
121 void AccessibilityRenderObject::detach()
123 AccessibilityNodeObject::detach();
127 m_renderer->setHasAXObject(false);
132 RenderBoxModelObject* AccessibilityRenderObject::renderBoxModelObject() const
134 if (!m_renderer || !m_renderer->isBoxModelObject())
136 return toRenderBoxModelObject(m_renderer);
139 void AccessibilityRenderObject::setRenderer(RenderObject* renderer)
141 m_renderer = renderer;
142 setNode(renderer->node());
145 static inline bool isInlineWithContinuation(RenderObject* object)
147 if (!object->isBoxModelObject())
150 RenderBoxModelObject* renderer = toRenderBoxModelObject(object);
151 if (!renderer->isRenderInline())
154 return toRenderInline(renderer)->continuation();
157 static inline RenderObject* firstChildInContinuation(RenderObject* renderer)
159 RenderObject* r = toRenderInline(renderer)->continuation();
162 if (r->isRenderBlock())
164 if (RenderObject* child = r->firstChild())
166 r = toRenderInline(r)->continuation();
172 static inline RenderObject* firstChildConsideringContinuation(RenderObject* renderer)
174 RenderObject* firstChild = renderer->firstChild();
176 if (!firstChild && isInlineWithContinuation(renderer))
177 firstChild = firstChildInContinuation(renderer);
183 static inline RenderObject* lastChildConsideringContinuation(RenderObject* renderer)
185 RenderObject* lastChild = renderer->lastChild();
187 RenderObject* cur = renderer;
189 if (!cur->isRenderInline() && !cur->isRenderBlock())
195 if (RenderObject* lc = cur->lastChild())
198 if (cur->isRenderInline()) {
199 cur = toRenderInline(cur)->inlineElementContinuation();
200 ASSERT_UNUSED(prev, cur || !toRenderInline(prev)->continuation());
202 cur = toRenderBlock(cur)->inlineElementContinuation();
208 AccessibilityObject* AccessibilityRenderObject::firstChild() const
213 RenderObject* firstChild = firstChildConsideringContinuation(m_renderer);
218 return axObjectCache()->getOrCreate(firstChild);
221 AccessibilityObject* AccessibilityRenderObject::lastChild() const
226 RenderObject* lastChild = lastChildConsideringContinuation(m_renderer);
231 return axObjectCache()->getOrCreate(lastChild);
234 static inline RenderInline* startOfContinuations(RenderObject* r)
236 if (r->isInlineElementContinuation())
237 return toRenderInline(r->node()->renderer());
239 // Blocks with a previous continuation always have a next continuation
240 if (r->isRenderBlock() && toRenderBlock(r)->inlineElementContinuation())
241 return toRenderInline(toRenderBlock(r)->inlineElementContinuation()->node()->renderer());
246 static inline RenderObject* endOfContinuations(RenderObject* renderer)
248 RenderObject* prev = renderer;
249 RenderObject* cur = renderer;
251 if (!cur->isRenderInline() && !cur->isRenderBlock())
256 if (cur->isRenderInline()) {
257 cur = toRenderInline(cur)->inlineElementContinuation();
258 ASSERT(cur || !toRenderInline(prev)->continuation());
260 cur = toRenderBlock(cur)->inlineElementContinuation();
267 static inline RenderObject* childBeforeConsideringContinuations(RenderInline* r, RenderObject* child)
269 RenderBoxModelObject* curContainer = r;
270 RenderObject* cur = 0;
271 RenderObject* prev = 0;
273 while (curContainer) {
274 if (curContainer->isRenderInline()) {
275 cur = curContainer->firstChild();
280 cur = cur->nextSibling();
283 curContainer = toRenderInline(curContainer)->continuation();
284 } else if (curContainer->isRenderBlock()) {
285 if (curContainer == child)
289 curContainer = toRenderBlock(curContainer)->inlineElementContinuation();
293 ASSERT_NOT_REACHED();
298 static inline bool firstChildIsInlineContinuation(RenderObject* renderer)
300 return renderer->firstChild() && renderer->firstChild()->isInlineElementContinuation();
303 AccessibilityObject* AccessibilityRenderObject::previousSibling() const
308 RenderObject* previousSibling = 0;
310 // Case 1: The node is a block and is an inline's continuation. In that case, the inline's
311 // last child is our previous sibling (or further back in the continuation chain)
312 RenderInline* startOfConts;
313 if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer)))
314 previousSibling = childBeforeConsideringContinuations(startOfConts, m_renderer);
316 // Case 2: Anonymous block parent of the end of a continuation - skip all the way to before
317 // the parent of the start, since everything in between will be linked up via the continuation.
318 else if (m_renderer->isAnonymousBlock() && firstChildIsInlineContinuation(m_renderer)) {
319 RenderObject* firstParent = startOfContinuations(m_renderer->firstChild())->parent();
320 while (firstChildIsInlineContinuation(firstParent))
321 firstParent = startOfContinuations(firstParent->firstChild())->parent();
322 previousSibling = firstParent->previousSibling();
325 // Case 3: The node has an actual previous sibling
326 else if (RenderObject* ps = m_renderer->previousSibling())
327 previousSibling = ps;
329 // Case 4: This node has no previous siblings, but its parent is an inline,
330 // and is another node's inline continutation. Follow the continuation chain.
331 else if (m_renderer->parent()->isRenderInline() && (startOfConts = startOfContinuations(m_renderer->parent())))
332 previousSibling = childBeforeConsideringContinuations(startOfConts, m_renderer->parent()->firstChild());
334 if (!previousSibling)
337 return axObjectCache()->getOrCreate(previousSibling);
340 static inline bool lastChildHasContinuation(RenderObject* renderer)
342 return renderer->lastChild() && isInlineWithContinuation(renderer->lastChild());
345 AccessibilityObject* AccessibilityRenderObject::nextSibling() const
350 RenderObject* nextSibling = 0;
352 // Case 1: node is a block and has an inline continuation. Next sibling is the inline continuation's
354 RenderInline* inlineContinuation;
355 if (m_renderer->isRenderBlock() && (inlineContinuation = toRenderBlock(m_renderer)->inlineElementContinuation()))
356 nextSibling = firstChildConsideringContinuation(inlineContinuation);
358 // Case 2: Anonymous block parent of the start of a continuation - skip all the way to
359 // after the parent of the end, since everything in between will be linked up via the continuation.
360 else if (m_renderer->isAnonymousBlock() && lastChildHasContinuation(m_renderer)) {
361 RenderObject* lastParent = endOfContinuations(m_renderer->lastChild())->parent();
362 while (lastChildHasContinuation(lastParent))
363 lastParent = endOfContinuations(lastParent->lastChild())->parent();
364 nextSibling = lastParent->nextSibling();
367 // Case 3: node has an actual next sibling
368 else if (RenderObject* ns = m_renderer->nextSibling())
371 // Case 4: node is an inline with a continuation. Next sibling is the next sibling of the end
372 // of the continuation chain.
373 else if (isInlineWithContinuation(m_renderer))
374 nextSibling = endOfContinuations(m_renderer)->nextSibling();
376 // Case 5: node has no next sibling, and its parent is an inline with a continuation.
377 else if (isInlineWithContinuation(m_renderer->parent())) {
378 RenderObject* continuation = toRenderInline(m_renderer->parent())->continuation();
380 // Case 5a: continuation is a block - in this case the block itself is the next sibling.
381 if (continuation->isRenderBlock())
382 nextSibling = continuation;
383 // Case 5b: continuation is an inline - in this case the inline's first child is the next sibling
385 nextSibling = firstChildConsideringContinuation(continuation);
391 return axObjectCache()->getOrCreate(nextSibling);
394 static RenderBoxModelObject* nextContinuation(RenderObject* renderer)
397 if (renderer->isRenderInline() && !renderer->isReplaced())
398 return toRenderInline(renderer)->continuation();
399 if (renderer->isRenderBlock())
400 return toRenderBlock(renderer)->inlineElementContinuation();
404 RenderObject* AccessibilityRenderObject::renderParentObject() const
409 RenderObject* parent = m_renderer->parent();
411 // Case 1: node is a block and is an inline's continuation. Parent
412 // is the start of the continuation chain.
413 RenderObject* startOfConts = 0;
414 RenderObject* firstChild = 0;
415 if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer)))
416 parent = startOfConts;
418 // Case 2: node's parent is an inline which is some node's continuation; parent is
419 // the earliest node in the continuation chain.
420 else if (parent && parent->isRenderInline() && (startOfConts = startOfContinuations(parent)))
421 parent = startOfConts;
423 // Case 3: The first sibling is the beginning of a continuation chain. Find the origin of that continuation.
424 else if (parent && (firstChild = parent->firstChild()) && firstChild->node()) {
425 // Get the node's renderer and follow that continuation chain until the first child is found
426 RenderObject* nodeRenderFirstChild = firstChild->node()->renderer();
427 while (nodeRenderFirstChild != firstChild) {
428 for (RenderObject* contsTest = nodeRenderFirstChild; contsTest; contsTest = nextContinuation(contsTest)) {
429 if (contsTest == firstChild) {
430 parent = nodeRenderFirstChild->parent();
434 if (firstChild == parent->firstChild())
436 firstChild = parent->firstChild();
437 if (!firstChild->node())
439 nodeRenderFirstChild = firstChild->node()->renderer();
446 AccessibilityObject* AccessibilityRenderObject::parentObjectIfExists() const
448 // WebArea's parent should be the scroll view containing it.
450 return axObjectCache()->get(m_renderer->frame()->view());
452 return axObjectCache()->get(renderParentObject());
455 AccessibilityObject* AccessibilityRenderObject::parentObject() const
460 if (ariaRoleAttribute() == MenuBarRole)
461 return axObjectCache()->getOrCreate(m_renderer->parent());
463 // menuButton and its corresponding menu are DOM siblings, but Accessibility needs them to be parent/child
464 if (ariaRoleAttribute() == MenuRole) {
465 AccessibilityObject* parent = menuButtonForMenu();
470 RenderObject* parentObj = renderParentObject();
472 return axObjectCache()->getOrCreate(parentObj);
474 // WebArea's parent should be the scroll view containing it.
476 return axObjectCache()->getOrCreate(m_renderer->frame()->view());
481 bool AccessibilityRenderObject::isWebArea() const
483 return roleValue() == WebAreaRole;
486 bool AccessibilityRenderObject::isImageButton() const
488 return isNativeImage() && roleValue() == ButtonRole;
491 bool AccessibilityRenderObject::isAnchor() const
493 return !isNativeImage() && isLink();
496 bool AccessibilityRenderObject::isNativeTextControl() const
498 return m_renderer->isTextControl();
501 bool AccessibilityRenderObject::isSearchField() const
506 HTMLInputElement* inputElement = node()->toInputElement();
510 if (inputElement->isSearchField())
513 // Some websites don't label their search fields as such. However, they will
514 // use the word "search" in either the form or input type. This won't catch every case,
515 // but it will catch google.com for example.
517 // Check the node name of the input type, sometimes it's "search".
518 const AtomicString& nameAttribute = getAttribute(nameAttr);
519 if (nameAttribute.contains("search", false))
522 // Check the form action and the name, which will sometimes be "search".
523 HTMLFormElement* form = inputElement->form();
524 if (form && (form->name().contains("search", false) || form->action().contains("search", false)))
530 bool AccessibilityRenderObject::isNativeImage() const
532 return m_renderer->isBoxModelObject() && toRenderBoxModelObject(m_renderer)->isImage();
535 bool AccessibilityRenderObject::isImage() const
537 return roleValue() == ImageRole;
540 bool AccessibilityRenderObject::isAttachment() const
542 RenderBoxModelObject* renderer = renderBoxModelObject();
545 // Widgets are the replaced elements that we represent to AX as attachments
546 bool isWidget = renderer->isWidget();
547 ASSERT(!isWidget || (renderer->isReplaced() && !isImage()));
548 return isWidget && ariaRoleAttribute() == UnknownRole;
551 bool AccessibilityRenderObject::isPasswordField() const
554 if (!m_renderer->node() || !m_renderer->node()->isHTMLElement())
556 if (ariaRoleAttribute() != UnknownRole)
559 HTMLInputElement* inputElement = m_renderer->node()->toInputElement();
563 return inputElement->isPasswordField();
566 bool AccessibilityRenderObject::isFileUploadButton() const
568 if (m_renderer && m_renderer->node() && m_renderer->node()->hasTagName(inputTag)) {
569 HTMLInputElement* input = static_cast<HTMLInputElement*>(m_renderer->node());
570 return input->isFileUpload();
576 bool AccessibilityRenderObject::isInputImage() const
578 Node* elementNode = node();
579 if (roleValue() == ButtonRole && elementNode && elementNode->hasTagName(inputTag)) {
580 HTMLInputElement* input = static_cast<HTMLInputElement*>(elementNode);
581 return input->isImageButton();
587 bool AccessibilityRenderObject::isProgressIndicator() const
589 return roleValue() == ProgressIndicatorRole;
592 bool AccessibilityRenderObject::isSlider() const
594 return roleValue() == SliderRole;
597 bool AccessibilityRenderObject::isMenuRelated() const
599 AccessibilityRole role = roleValue();
600 return role == MenuRole
601 || role == MenuBarRole
602 || role == MenuButtonRole
603 || role == MenuItemRole;
606 bool AccessibilityRenderObject::isMenu() const
608 return roleValue() == MenuRole;
611 bool AccessibilityRenderObject::isMenuBar() const
613 return roleValue() == MenuBarRole;
616 bool AccessibilityRenderObject::isMenuButton() const
618 return roleValue() == MenuButtonRole;
621 bool AccessibilityRenderObject::isMenuItem() const
623 return roleValue() == MenuItemRole;
626 bool AccessibilityRenderObject::isPressed() const
629 if (roleValue() != ButtonRole)
632 Node* node = m_renderer->node();
636 // If this is an ARIA button, check the aria-pressed attribute rather than node()->active()
637 if (ariaRoleAttribute() == ButtonRole) {
638 if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true"))
643 return node->active();
646 bool AccessibilityRenderObject::isIndeterminate() const
649 if (!m_renderer->node())
652 HTMLInputElement* inputElement = m_renderer->node()->toInputElement();
656 return inputElement->isIndeterminate();
659 bool AccessibilityRenderObject::isNativeCheckboxOrRadio() const
661 Node* elementNode = node();
663 HTMLInputElement* input = elementNode->toInputElement();
665 return input->isCheckbox() || input->isRadioButton();
671 bool AccessibilityRenderObject::isChecked() const
675 Node* node = this->node();
679 // First test for native checkedness semantics
680 HTMLInputElement* inputElement = node->toInputElement();
682 return inputElement->shouldAppearChecked();
684 // Else, if this is an ARIA checkbox or radio, respect the aria-checked attribute
685 AccessibilityRole ariaRole = ariaRoleAttribute();
686 if (ariaRole == RadioButtonRole || ariaRole == CheckBoxRole) {
687 if (equalIgnoringCase(getAttribute(aria_checkedAttr), "true"))
692 // Otherwise it's not checked
696 bool AccessibilityRenderObject::isHovered() const
699 return m_renderer->node() && m_renderer->node()->hovered();
702 bool AccessibilityRenderObject::isMultiSelectable() const
706 const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr);
707 if (equalIgnoringCase(ariaMultiSelectable, "true"))
709 if (equalIgnoringCase(ariaMultiSelectable, "false"))
712 if (!m_renderer->isBoxModelObject() || !toRenderBoxModelObject(m_renderer)->isListBox())
714 return m_renderer->node() && toHTMLSelectElement(m_renderer->node())->multiple();
717 bool AccessibilityRenderObject::isReadOnly() const
722 Document* document = m_renderer->document();
726 HTMLElement* body = document->body();
727 if (body && body->rendererIsEditable())
730 return !document->rendererIsEditable();
733 if (m_renderer->isBoxModelObject()) {
734 RenderBoxModelObject* box = toRenderBoxModelObject(m_renderer);
735 if (box->isTextField())
736 return static_cast<HTMLInputElement*>(box->node())->readOnly();
737 if (box->isTextArea())
738 return static_cast<HTMLTextAreaElement*>(box->node())->readOnly();
741 return !m_renderer->node() || !m_renderer->node()->rendererIsEditable();
744 bool AccessibilityRenderObject::isOffScreen() const
747 IntRect contentRect = pixelSnappedIntRect(m_renderer->absoluteClippedOverflowRect());
748 FrameView* view = m_renderer->frame()->view();
749 IntRect viewRect = view->visibleContentRect();
750 viewRect.intersect(contentRect);
751 return viewRect.isEmpty();
754 int AccessibilityRenderObject::headingLevel() const
756 // headings can be in block flow and non-block flow
757 Node* element = node();
761 if (ariaRoleAttribute() == HeadingRole)
762 return getAttribute(aria_levelAttr).toInt();
764 if (element->hasTagName(h1Tag))
767 if (element->hasTagName(h2Tag))
770 if (element->hasTagName(h3Tag))
773 if (element->hasTagName(h4Tag))
776 if (element->hasTagName(h5Tag))
779 if (element->hasTagName(h6Tag))
785 bool AccessibilityRenderObject::isHeading() const
787 return roleValue() == HeadingRole;
790 bool AccessibilityRenderObject::isLink() const
792 return roleValue() == WebCoreLinkRole;
795 bool AccessibilityRenderObject::isControl() const
800 Node* node = m_renderer->node();
801 return node && ((node->isElementNode() && static_cast<Element*>(node)->isFormControlElement())
802 || AccessibilityObject::isARIAControl(ariaRoleAttribute()));
805 bool AccessibilityRenderObject::isFieldset() const
807 RenderBoxModelObject* renderer = renderBoxModelObject();
810 return renderer->isFieldset();
813 bool AccessibilityRenderObject::isGroup() const
815 return roleValue() == GroupRole;
818 AccessibilityObject* AccessibilityRenderObject::selectedRadioButton()
823 AccessibilityObject::AccessibilityChildrenVector children = this->children();
825 // Find the child radio button that is selected (ie. the intValue == 1).
826 size_t size = children.size();
827 for (size_t i = 0; i < size; ++i) {
828 AccessibilityObject* object = children[i].get();
829 if (object->roleValue() == RadioButtonRole && object->checkboxOrRadioValue() == ButtonStateOn)
835 AccessibilityObject* AccessibilityRenderObject::selectedTabItem()
840 // Find the child tab item that is selected (ie. the intValue == 1).
841 AccessibilityObject::AccessibilityChildrenVector tabs;
844 AccessibilityObject::AccessibilityChildrenVector children = this->children();
846 size_t size = tabs.size();
847 for (size_t i = 0; i < size; ++i) {
848 AccessibilityObject* object = children[i].get();
849 if (object->isTabItem() && object->isChecked())
855 Element* AccessibilityRenderObject::anchorElement() const
860 AXObjectCache* cache = axObjectCache();
861 RenderObject* currRenderer;
863 // Search up the render tree for a RenderObject with a DOM node. Defer to an earlier continuation, though.
864 for (currRenderer = m_renderer; currRenderer && !currRenderer->node(); currRenderer = currRenderer->parent()) {
865 if (currRenderer->isAnonymousBlock()) {
866 RenderObject* continuation = toRenderBlock(currRenderer)->continuation();
868 return cache->getOrCreate(continuation)->anchorElement();
872 // bail if none found
876 // search up the DOM tree for an anchor element
877 // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
878 Node* node = currRenderer->node();
879 for ( ; node; node = node->parentNode()) {
880 if (node->hasTagName(aTag) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
881 return static_cast<Element*>(node);
887 Element* AccessibilityRenderObject::actionElement() const
892 Node* node = m_renderer->node();
894 if (node->hasTagName(inputTag)) {
895 HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
896 if (!input->disabled() && (isCheckboxOrRadio() || input->isTextButton()))
898 } else if (node->hasTagName(buttonTag))
899 return toElement(node);
902 if (isFileUploadButton())
903 return toElement(m_renderer->node());
905 if (AccessibilityObject::isARIAInput(ariaRoleAttribute()))
906 return toElement(m_renderer->node());
909 return toElement(m_renderer->node());
911 if (m_renderer->isBoxModelObject() && toRenderBoxModelObject(m_renderer)->isMenuList())
912 return toElement(m_renderer->node());
914 switch (roleValue()) {
916 case PopUpButtonRole:
920 return toElement(m_renderer->node());
925 Element* elt = anchorElement();
927 elt = mouseButtonListener();
931 Element* AccessibilityRenderObject::mouseButtonListener() const
933 Node* node = m_renderer->node();
937 // check if our parent is a mouse button listener
938 while (node && !node->isElementNode())
939 node = node->parentNode();
944 // FIXME: Do the continuation search like anchorElement does
945 for (Element* element = static_cast<Element*>(node); element; element = element->parentElement()) {
946 if (element->getAttributeEventListener(eventNames().clickEvent) || element->getAttributeEventListener(eventNames().mousedownEvent) || element->getAttributeEventListener(eventNames().mouseupEvent))
953 void AccessibilityRenderObject::alterSliderValue(bool increase)
955 if (roleValue() != SliderRole)
958 if (!getAttribute(stepAttr).isEmpty())
959 changeValueByStep(increase);
961 changeValueByPercent(increase ? 5 : -5);
964 void AccessibilityRenderObject::increment()
966 alterSliderValue(true);
969 void AccessibilityRenderObject::decrement()
971 alterSliderValue(false);
974 static Element* siblingWithAriaRole(String role, Node* node)
976 Node* sibling = node->parentNode()->firstChild();
978 if (sibling->isElementNode()) {
979 const AtomicString& siblingAriaRole = static_cast<Element*>(sibling)->getAttribute(roleAttr);
980 if (equalIgnoringCase(siblingAriaRole, role))
981 return static_cast<Element*>(sibling);
983 sibling = sibling->nextSibling();
989 Element* AccessibilityRenderObject::menuElementForMenuButton() const
991 if (ariaRoleAttribute() != MenuButtonRole)
994 return siblingWithAriaRole("menu", renderer()->node());
997 AccessibilityObject* AccessibilityRenderObject::menuForMenuButton() const
999 Element* menu = menuElementForMenuButton();
1000 if (menu && menu->renderer())
1001 return axObjectCache()->getOrCreate(menu->renderer());
1005 Element* AccessibilityRenderObject::menuItemElementForMenu() const
1007 if (ariaRoleAttribute() != MenuRole)
1010 return siblingWithAriaRole("menuitem", renderer()->node());
1013 AccessibilityObject* AccessibilityRenderObject::menuButtonForMenu() const
1015 Element* menuItem = menuItemElementForMenu();
1017 if (menuItem && menuItem->renderer()) {
1018 // ARIA just has generic menu items. AppKit needs to know if this is a top level items like MenuBarButton or MenuBarItem
1019 AccessibilityObject* menuItemAX = axObjectCache()->getOrCreate(menuItem->renderer());
1020 if (menuItemAX->isMenuButton())
1026 String AccessibilityRenderObject::helpText() const
1031 const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
1032 if (!ariaHelp.isEmpty())
1035 String describedBy = ariaDescribedByAttribute();
1036 if (!describedBy.isEmpty())
1039 String description = accessibilityDescription();
1040 for (RenderObject* curr = m_renderer; curr; curr = curr->parent()) {
1041 if (curr->node() && curr->node()->isHTMLElement()) {
1042 const AtomicString& summary = static_cast<Element*>(curr->node())->getAttribute(summaryAttr);
1043 if (!summary.isEmpty())
1046 // The title attribute should be used as help text unless it is already being used as descriptive text.
1047 const AtomicString& title = static_cast<Element*>(curr->node())->getAttribute(titleAttr);
1048 if (!title.isEmpty() && description != title)
1052 // Only take help text from an ancestor element if its a group or an unknown role. If help was
1053 // added to those kinds of elements, it is likely it was meant for a child element.
1054 AccessibilityObject* axObj = axObjectCache()->getOrCreate(curr);
1056 AccessibilityRole role = axObj->roleValue();
1057 if (role != GroupRole && role != UnknownRole)
1065 unsigned AccessibilityRenderObject::hierarchicalLevel() const
1070 Node* node = m_renderer->node();
1071 if (!node || !node->isElementNode())
1073 Element* element = static_cast<Element*>(node);
1074 String ariaLevel = element->getAttribute(aria_levelAttr);
1075 if (!ariaLevel.isEmpty())
1076 return ariaLevel.toInt();
1078 // Only tree item will calculate its level through the DOM currently.
1079 if (roleValue() != TreeItemRole)
1082 // Hierarchy leveling starts at 0.
1083 // We measure tree hierarchy by the number of groups that the item is within.
1085 AccessibilityObject* parent = parentObject();
1087 AccessibilityRole parentRole = parent->roleValue();
1088 if (parentRole == GroupRole)
1090 else if (parentRole == TreeRole)
1093 parent = parent->parentObject();
1099 static TextIteratorBehavior textIteratorBehaviorForTextRange()
1101 TextIteratorBehavior behavior = TextIteratorIgnoresStyleVisibility;
1104 // We need to emit replaced elements for GTK, and present
1105 // them with the 'object replacement character' (0xFFFC).
1106 behavior = static_cast<TextIteratorBehavior>(behavior | TextIteratorEmitsObjectReplacementCharacters);
1112 String AccessibilityRenderObject::textUnderElement() const
1117 if (m_renderer->isFileUploadControl())
1118 return toRenderFileUploadControl(m_renderer)->buttonValue();
1120 Node* node = m_renderer->node();
1122 if (Frame* frame = node->document()->frame()) {
1123 // catch stale WebCoreAXObject (see <rdar://problem/3960196>)
1124 if (frame->document() != node->document())
1127 return plainText(rangeOfContents(node).get(), textIteratorBehaviorForTextRange());
1131 // Sometimes text fragments don't have Node's associated with them (like when
1132 // CSS content is used to insert text).
1133 if (m_renderer->isText()) {
1134 RenderText* renderTextObject = toRenderText(m_renderer);
1135 if (renderTextObject->isTextFragment())
1136 return String(static_cast<RenderTextFragment*>(m_renderer)->contentString());
1139 // return the null string for anonymous text because it is non-trivial to get
1140 // the actual text and, so far, that is not needed
1144 Node* AccessibilityRenderObject::node() const
1146 return m_renderer ? m_renderer->node() : 0;
1149 AccessibilityButtonState AccessibilityRenderObject::checkboxOrRadioValue() const
1151 if (isNativeCheckboxOrRadio())
1152 return isChecked() ? ButtonStateOn : ButtonStateOff;
1154 return AccessibilityObject::checkboxOrRadioValue();
1157 String AccessibilityRenderObject::valueDescription() const
1159 // Only sliders and progress bars support value descriptions currently.
1160 if (!isProgressIndicator() && !isSlider())
1163 return getAttribute(aria_valuetextAttr).string();
1166 float AccessibilityRenderObject::stepValueForRange() const
1168 return getAttribute(stepAttr).toFloat();
1171 float AccessibilityRenderObject::valueForRange() const
1173 if (!isProgressIndicator() && !isSlider() && !isScrollbar())
1176 return getAttribute(aria_valuenowAttr).toFloat();
1179 float AccessibilityRenderObject::maxValueForRange() const
1181 if (!isProgressIndicator() && !isSlider())
1184 return getAttribute(aria_valuemaxAttr).toFloat();
1187 float AccessibilityRenderObject::minValueForRange() const
1189 if (!isProgressIndicator() && !isSlider())
1192 return getAttribute(aria_valueminAttr).toFloat();
1195 String AccessibilityRenderObject::stringValue() const
1197 if (!m_renderer || isPasswordField())
1200 RenderBoxModelObject* cssBox = renderBoxModelObject();
1202 if (ariaRoleAttribute() == StaticTextRole) {
1203 String staticText = text();
1204 if (!staticText.length())
1205 staticText = textUnderElement();
1209 if (m_renderer->isText())
1210 return textUnderElement();
1212 if (cssBox && cssBox->isMenuList()) {
1213 // RenderMenuList will go straight to the text() of its selected item.
1214 // This has to be overridden in the case where the selected item has an ARIA label.
1215 HTMLSelectElement* selectElement = toHTMLSelectElement(m_renderer->node());
1216 int selectedIndex = selectElement->selectedIndex();
1217 const Vector<HTMLElement*> listItems = selectElement->listItems();
1218 if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
1219 const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
1220 if (!overriddenDescription.isNull())
1221 return overriddenDescription;
1223 return toRenderMenuList(m_renderer)->text();
1226 if (m_renderer->isListMarker())
1227 return toRenderListMarker(m_renderer)->text();
1230 // FIXME: Why would a renderer exist when the Document isn't attached to a frame?
1231 if (m_renderer->frame())
1234 ASSERT_NOT_REACHED();
1237 if (isTextControl())
1240 if (m_renderer->isFileUploadControl())
1241 return toRenderFileUploadControl(m_renderer)->fileTextValue();
1243 // FIXME: We might need to implement a value here for more types
1244 // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
1245 // this would require subclassing or making accessibilityAttributeNames do something other than return a
1246 // single static array.
1250 // This function implements the ARIA accessible name as described by the Mozilla
1251 // ARIA Implementer's Guide.
1252 static String accessibleNameForNode(Node* node)
1254 if (node->isTextNode())
1255 return toText(node)->data();
1257 if (node->hasTagName(inputTag))
1258 return static_cast<HTMLInputElement*>(node)->value();
1260 if (node->isHTMLElement()) {
1261 const AtomicString& alt = toHTMLElement(node)->getAttribute(altAttr);
1269 String AccessibilityRenderObject::accessibilityDescriptionForElements(Vector<Element*> &elements) const
1271 StringBuilder builder;
1272 unsigned size = elements.size();
1273 for (unsigned i = 0; i < size; ++i) {
1274 Element* idElement = elements[i];
1276 builder.append(accessibleNameForNode(idElement));
1277 for (Node* n = idElement->firstChild(); n; n = n->traverseNextNode(idElement))
1278 builder.append(accessibleNameForNode(n));
1281 builder.append(' ');
1283 return builder.toString();
1286 void AccessibilityRenderObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
1288 Node* node = m_renderer->node();
1289 if (!node || !node->isElementNode())
1292 TreeScope* scope = node->treeScope();
1296 String idList = getAttribute(attribute).string();
1297 if (idList.isEmpty())
1300 idList.replace('\n', ' ');
1301 Vector<String> idVector;
1302 idList.split(' ', idVector);
1304 unsigned size = idVector.size();
1305 for (unsigned i = 0; i < size; ++i) {
1306 AtomicString idName(idVector[i]);
1307 Element* idElement = scope->getElementById(idName);
1309 elements.append(idElement);
1313 void AccessibilityRenderObject::ariaLabeledByElements(Vector<Element*>& elements) const
1315 elementsFromAttribute(elements, aria_labeledbyAttr);
1316 if (!elements.size())
1317 elementsFromAttribute(elements, aria_labelledbyAttr);
1320 String AccessibilityRenderObject::ariaLabeledByAttribute() const
1322 Vector<Element*> elements;
1323 ariaLabeledByElements(elements);
1325 return accessibilityDescriptionForElements(elements);
1328 static HTMLLabelElement* labelForElement(Element* element)
1330 RefPtr<NodeList> list = element->document()->getElementsByTagName("label");
1331 unsigned len = list->length();
1332 for (unsigned i = 0; i < len; i++) {
1333 if (list->item(i)->hasTagName(labelTag)) {
1334 HTMLLabelElement* label = static_cast<HTMLLabelElement*>(list->item(i));
1335 if (label->control() == element)
1343 HTMLLabelElement* AccessibilityRenderObject::labelElementContainer() const
1348 // the control element should not be considered part of the label
1352 // find if this has a parent that is a label
1353 for (Node* parentNode = m_renderer->node(); parentNode; parentNode = parentNode->parentNode()) {
1354 if (parentNode->hasTagName(labelTag))
1355 return static_cast<HTMLLabelElement*>(parentNode);
1361 String AccessibilityRenderObject::title() const
1363 AccessibilityRole role = roleValue();
1368 Node* node = m_renderer->node();
1372 bool isInputTag = node->hasTagName(inputTag);
1374 HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
1375 if (input->isTextButton())
1376 return input->valueWithDefault();
1379 if (isInputTag || AccessibilityObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
1380 HTMLLabelElement* label = labelForElement(static_cast<Element*>(node));
1381 if (label && !exposesTitleUIElement())
1382 return label->innerText();
1387 case ListBoxOptionRole:
1389 case MenuButtonRole:
1390 case RadioButtonRole:
1393 case PopUpButtonRole:
1394 return textUnderElement();
1399 if (isHeading() || isLink())
1400 return textUnderElement();
1405 String AccessibilityRenderObject::ariaDescribedByAttribute() const
1407 Vector<Element*> elements;
1408 elementsFromAttribute(elements, aria_describedbyAttr);
1410 return accessibilityDescriptionForElements(elements);
1413 String AccessibilityRenderObject::ariaAccessibilityDescription() const
1415 String ariaLabeledBy = ariaLabeledByAttribute();
1416 if (!ariaLabeledBy.isEmpty())
1417 return ariaLabeledBy;
1419 const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
1420 if (!ariaLabel.isEmpty())
1426 String AccessibilityRenderObject::webAreaAccessibilityDescription() const
1428 // The WebArea description should follow this order:
1429 // aria-label on the <html>
1430 // title on the <html>
1431 // <title> inside the <head> (of it was set through JS)
1432 // name on the <html>
1434 // aria-label on the <iframe>
1435 // title on the <iframe>
1436 // name on the <iframe>
1441 Document* document = m_renderer->document();
1443 // Check if the HTML element has an aria-label for the webpage.
1444 if (Element* documentElement = document->documentElement()) {
1445 const AtomicString& ariaLabel = documentElement->getAttribute(aria_labelAttr);
1446 if (!ariaLabel.isEmpty())
1450 Node* owner = document->ownerElement();
1452 if (owner->hasTagName(frameTag) || owner->hasTagName(iframeTag)) {
1453 const AtomicString& title = static_cast<HTMLFrameElementBase*>(owner)->getAttribute(titleAttr);
1454 if (!title.isEmpty())
1456 return static_cast<HTMLFrameElementBase*>(owner)->getNameAttribute();
1458 if (owner->isHTMLElement())
1459 return toHTMLElement(owner)->getNameAttribute();
1462 String documentTitle = document->title();
1463 if (!documentTitle.isEmpty())
1464 return documentTitle;
1466 owner = document->body();
1467 if (owner && owner->isHTMLElement())
1468 return toHTMLElement(owner)->getNameAttribute();
1473 String AccessibilityRenderObject::accessibilityDescription() const
1478 // Static text should not have a description, it should only have a stringValue.
1479 if (roleValue() == StaticTextRole)
1482 String ariaDescription = ariaAccessibilityDescription();
1483 if (!ariaDescription.isEmpty())
1484 return ariaDescription;
1486 Node* node = m_renderer->node();
1487 if (isImage() || isInputImage() || isNativeImage()) {
1488 if (node && node->isHTMLElement()) {
1489 const AtomicString& alt = toHTMLElement(node)->getAttribute(altAttr);
1497 if (node && node->isElementNode() && static_cast<Element*>(node)->isMathMLElement())
1498 return getAttribute(MathMLNames::alttextAttr);
1502 return webAreaAccessibilityDescription();
1504 // An element's descriptive text is comprised of title() (what's visible on the screen) and accessibilityDescription() (other descriptive text).
1505 // Both are used to generate what a screen reader speaks.
1506 // If this point is reached (i.e. there's no accessibilityDescription) and there's no title(), we should fallback to using the title attribute.
1507 // 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).
1508 if (title().isEmpty())
1509 return getAttribute(titleAttr);
1514 LayoutRect AccessibilityRenderObject::boundingBoxRect() const
1516 RenderObject* obj = m_renderer;
1519 return LayoutRect();
1521 if (obj->node()) // If we are a continuation, we want to make sure to use the primary renderer.
1522 obj = obj->node()->renderer();
1524 // absoluteFocusRingQuads will query the hierarchy below this element, which for large webpages can be very slow.
1525 // For a web area, which will have the most elements of any element, absoluteQuads should be used.
1526 Vector<FloatQuad> quads;
1528 toRenderText(obj)->absoluteQuads(quads, 0, RenderText::ClipToEllipsis);
1529 else if (isWebArea())
1530 obj->absoluteQuads(quads);
1532 obj->absoluteFocusRingQuads(quads);
1534 LayoutRect result = boundingBoxForQuads(obj, quads);
1536 // The size of the web area should be the content size, not the clipped size.
1537 if (isWebArea() && obj->frame()->view())
1538 result.setSize(obj->frame()->view()->contentsSize());
1543 LayoutRect AccessibilityRenderObject::checkboxOrRadioRect() const
1546 return LayoutRect();
1548 HTMLLabelElement* label = labelForElement(static_cast<Element*>(m_renderer->node()));
1549 if (!label || !label->renderer())
1550 return boundingBoxRect();
1552 LayoutRect labelRect = axObjectCache()->getOrCreate(label->renderer())->elementRect();
1553 labelRect.unite(boundingBoxRect());
1557 LayoutRect AccessibilityRenderObject::elementRect() const
1559 // a checkbox or radio button should encompass its label
1560 if (isCheckboxOrRadio())
1561 return checkboxOrRadioRect();
1563 return boundingBoxRect();
1566 IntPoint AccessibilityRenderObject::clickPoint()
1568 // Headings are usually much wider than their textual content. If the mid point is used, often it can be wrong.
1569 if (isHeading() && children().size() == 1)
1570 return children()[0]->clickPoint();
1572 // use the default position unless this is an editable web area, in which case we use the selection bounds.
1573 if (!isWebArea() || isReadOnly())
1574 return AccessibilityObject::clickPoint();
1576 VisibleSelection visSelection = selection();
1577 VisiblePositionRange range = VisiblePositionRange(visSelection.visibleStart(), visSelection.visibleEnd());
1578 IntRect bounds = boundsForVisiblePositionRange(range);
1580 bounds.setLocation(m_renderer->document()->view()->screenToContents(bounds.location()));
1582 return IntPoint(bounds.x() + (bounds.width() / 2), bounds.y() - (bounds.height() / 2));
1585 AccessibilityObject* AccessibilityRenderObject::internalLinkElement() const
1587 Element* element = anchorElement();
1591 // Right now, we do not support ARIA links as internal link elements
1592 if (!element->hasTagName(aTag))
1594 HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(element);
1596 KURL linkURL = anchor->href();
1597 String fragmentIdentifier = linkURL.fragmentIdentifier();
1598 if (fragmentIdentifier.isEmpty())
1601 // check if URL is the same as current URL
1602 KURL documentURL = m_renderer->document()->url();
1603 if (!equalIgnoringFragmentIdentifier(documentURL, linkURL))
1606 Node* linkedNode = m_renderer->document()->findAnchor(fragmentIdentifier);
1610 // The element we find may not be accessible, so find the first accessible object.
1611 return firstAccessibleObjectFromNode(linkedNode);
1614 ESpeak AccessibilityRenderObject::speakProperty() const
1617 return AccessibilityObject::speakProperty();
1619 return m_renderer->style()->speak();
1622 void AccessibilityRenderObject::addRadioButtonGroupMembers(AccessibilityChildrenVector& linkedUIElements) const
1624 if (!m_renderer || roleValue() != RadioButtonRole)
1627 Node* node = m_renderer->node();
1628 if (!node || !node->hasTagName(inputTag))
1631 HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
1632 // if there's a form, then this is easy
1633 if (input->form()) {
1634 Vector<RefPtr<Node> > formElements;
1635 input->form()->getNamedElements(input->name(), formElements);
1637 unsigned len = formElements.size();
1638 for (unsigned i = 0; i < len; ++i) {
1639 Node* associateElement = formElements[i].get();
1640 if (AccessibilityObject* object = axObjectCache()->getOrCreate(associateElement->renderer()))
1641 linkedUIElements.append(object);
1644 RefPtr<NodeList> list = node->document()->getElementsByTagName("input");
1645 unsigned len = list->length();
1646 for (unsigned i = 0; i < len; ++i) {
1647 if (list->item(i)->hasTagName(inputTag)) {
1648 HTMLInputElement* associateElement = static_cast<HTMLInputElement*>(list->item(i));
1649 if (associateElement->isRadioButton() && associateElement->name() == input->name()) {
1650 if (AccessibilityObject* object = axObjectCache()->getOrCreate(associateElement->renderer()))
1651 linkedUIElements.append(object);
1658 // linked ui elements could be all the related radio buttons in a group
1659 // or an internal anchor connection
1660 void AccessibilityRenderObject::linkedUIElements(AccessibilityChildrenVector& linkedUIElements) const
1662 ariaFlowToElements(linkedUIElements);
1665 AccessibilityObject* linkedAXElement = internalLinkElement();
1666 if (linkedAXElement)
1667 linkedUIElements.append(linkedAXElement);
1670 if (roleValue() == RadioButtonRole)
1671 addRadioButtonGroupMembers(linkedUIElements);
1674 bool AccessibilityRenderObject::hasTextAlternative() const
1676 // ARIA: section 2A, bullet #3 says if aria-labeledby or aria-label appears, it should
1677 // override the "label" element association.
1678 if (!ariaLabeledByAttribute().isEmpty() || !getAttribute(aria_labelAttr).isEmpty())
1684 bool AccessibilityRenderObject::ariaHasPopup() const
1686 return elementAttributeValue(aria_haspopupAttr);
1689 bool AccessibilityRenderObject::supportsARIAFlowTo() const
1691 return !getAttribute(aria_flowtoAttr).isEmpty();
1694 void AccessibilityRenderObject::ariaFlowToElements(AccessibilityChildrenVector& flowTo) const
1696 Vector<Element*> elements;
1697 elementsFromAttribute(elements, aria_flowtoAttr);
1699 AXObjectCache* cache = axObjectCache();
1700 unsigned count = elements.size();
1701 for (unsigned k = 0; k < count; ++k) {
1702 Element* element = elements[k];
1703 AccessibilityObject* flowToElement = cache->getOrCreate(element->renderer());
1705 flowTo.append(flowToElement);
1710 bool AccessibilityRenderObject::supportsARIADropping() const
1712 const AtomicString& dropEffect = getAttribute(aria_dropeffectAttr);
1713 return !dropEffect.isEmpty();
1716 bool AccessibilityRenderObject::supportsARIADragging() const
1718 const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
1719 return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false");
1722 bool AccessibilityRenderObject::isARIAGrabbed()
1724 return elementAttributeValue(aria_grabbedAttr);
1727 void AccessibilityRenderObject::determineARIADropEffects(Vector<String>& effects)
1729 const AtomicString& dropEffects = getAttribute(aria_dropeffectAttr);
1730 if (dropEffects.isEmpty()) {
1735 String dropEffectsString = dropEffects.string();
1736 dropEffectsString.replace('\n', ' ');
1737 dropEffectsString.split(' ', effects);
1740 bool AccessibilityRenderObject::exposesTitleUIElement() const
1745 // If this control is ignored (because it's invisible),
1746 // then the label needs to be exposed so it can be visible to accessibility.
1747 if (accessibilityIsIgnored())
1750 // Checkboxes and radio buttons use the text of their title ui element as their own AXTitle.
1751 // This code controls whether the title ui element should appear in the AX tree (usually, no).
1752 // It should appear if the control already has a label (which will be used as the AXTitle instead).
1753 if (isCheckboxOrRadio())
1754 return hasTextAlternative();
1756 // When controls have their own descriptions, the title element should be ignored.
1757 if (hasTextAlternative())
1763 AccessibilityObject* AccessibilityRenderObject::titleUIElement() const
1768 // if isFieldset is true, the renderer is guaranteed to be a RenderFieldset
1770 return axObjectCache()->getOrCreate(toRenderFieldset(m_renderer)->findLegend());
1772 Node* element = m_renderer->node();
1775 HTMLLabelElement* label = labelForElement(static_cast<Element*>(element));
1776 if (label && label->renderer())
1777 return axObjectCache()->getOrCreate(label->renderer());
1782 bool AccessibilityRenderObject::ariaIsHidden() const
1784 if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "true"))
1787 // aria-hidden hides this object and any children
1788 AccessibilityObject* object = parentObject();
1790 if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true"))
1792 object = object->parentObject();
1798 bool AccessibilityRenderObject::isDescendantOfBarrenParent() const
1800 for (AccessibilityObject* object = parentObject(); object; object = object->parentObject()) {
1801 if (!object->canHaveChildren())
1808 bool AccessibilityRenderObject::isAllowedChildOfTree() const
1810 // Determine if this is in a tree. If so, we apply special behavior to make it work like an AXOutline.
1811 AccessibilityObject* axObj = parentObject();
1812 bool isInTree = false;
1814 if (axObj->isTree()) {
1818 axObj = axObj->parentObject();
1821 // If the object is in a tree, only tree items should be exposed (and the children of tree items).
1823 AccessibilityRole role = roleValue();
1824 if (role != TreeItemRole && role != StaticTextRole)
1830 AccessibilityObjectInclusion AccessibilityRenderObject::accessibilityIsIgnoredBase() const
1832 // The following cases can apply to any element that's a subclass of AccessibilityRenderObject.
1834 // Ignore invisible elements.
1835 if (!m_renderer || m_renderer->style()->visibility() != VISIBLE)
1836 return IgnoreObject;
1838 // Anything marked as aria-hidden or a child of something aria-hidden must be hidden.
1840 return IgnoreObject;
1842 // Anything that is a presentational role must be hidden.
1843 if (isPresentationalChildOfAriaRole())
1844 return IgnoreObject;
1846 // Allow the platform to make a decision.
1847 AccessibilityObjectInclusion decision = accessibilityPlatformIncludesObject();
1848 if (decision == IncludeObject)
1849 return IncludeObject;
1850 if (decision == IgnoreObject)
1851 return IgnoreObject;
1853 return DefaultBehavior;
1856 bool AccessibilityRenderObject::accessibilityIsIgnored() const
1858 // Check first if any of the common reasons cause this element to be ignored.
1859 // Then process other use cases that need to be applied to all the various roles
1860 // that AccessibilityRenderObjects take on.
1861 AccessibilityObjectInclusion decision = accessibilityIsIgnoredBase();
1862 if (decision == IncludeObject)
1864 if (decision == IgnoreObject)
1867 // If this element is within a parent that cannot have children, it should not be exposed.
1868 if (isDescendantOfBarrenParent())
1871 if (roleValue() == IgnoredRole)
1874 if (roleValue() == PresentationalRole || inheritsPresentationalRole())
1877 // An ARIA tree can only have tree items and static text as children.
1878 if (!isAllowedChildOfTree())
1881 // Allow the platform to decide if the attachment is ignored or not.
1883 return accessibilityIgnoreAttachment();
1885 // ignore popup menu items because AppKit does
1886 for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
1887 if (parent->isBoxModelObject() && toRenderBoxModelObject(parent)->isMenuList())
1891 // find out if this element is inside of a label element.
1892 // if so, it may be ignored because it's the label for a checkbox or radio button
1893 AccessibilityObject* controlObject = correspondingControlForLabelElement();
1894 if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
1897 // NOTE: BRs always have text boxes now, so the text box check here can be removed
1898 if (m_renderer->isText()) {
1899 // static text beneath MenuItems and MenuButtons are just reported along with the menu item, so it's ignored on an individual level
1900 if (parentObjectUnignored()->ariaRoleAttribute() == MenuItemRole
1901 || parentObjectUnignored()->ariaRoleAttribute() == MenuButtonRole)
1903 RenderText* renderText = toRenderText(m_renderer);
1904 if (m_renderer->isBR() || !renderText->firstTextBox())
1907 // static text beneath TextControls is reported along with the text control text so it's ignored.
1908 for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
1909 if (parent->roleValue() == TextFieldRole)
1913 // text elements that are just empty whitespace should not be returned
1914 return renderText->text()->containsOnlyWhitespace();
1923 // all controls are accessible
1927 if (ariaRoleAttribute() != UnknownRole)
1930 // don't ignore labels, because they serve as TitleUIElements
1931 Node* node = m_renderer->node();
1932 if (node && node->hasTagName(labelTag))
1935 // Anything that is content editable should not be ignored.
1936 // However, one cannot just call node->rendererIsEditable() since that will ask if its parents
1937 // are also editable. Only the top level content editable region should be exposed.
1938 if (node && node->isElementNode()) {
1939 Element* element = static_cast<Element*>(node);
1940 const AtomicString& contentEditable = element->getAttribute(contenteditableAttr);
1941 if (equalIgnoringCase(contentEditable, "true"))
1945 // List items play an important role in defining the structure of lists. They should not be ignored.
1946 if (roleValue() == ListItemRole)
1949 // if this element has aria attributes on it, it should not be ignored.
1950 if (supportsARIAAttributes())
1953 if (m_renderer->isBlockFlow() && m_renderer->childrenInline())
1954 return !toRenderBlock(m_renderer)->firstLineBox() && !mouseButtonListener();
1956 // ignore images seemingly used as spacers
1959 // If the image can take focus, it should not be ignored, lest the user not be able to interact with something important.
1960 if (canSetFocusAttribute())
1963 if (node && node->isElementNode()) {
1964 Element* elt = static_cast<Element*>(node);
1965 const AtomicString& alt = elt->getAttribute(altAttr);
1966 // don't ignore an image that has an alt tag
1967 if (!alt.string().containsOnlyWhitespace())
1969 // informal standard is to ignore images with zero-length alt strings
1974 if (node && node->hasTagName(canvasTag)) {
1975 RenderHTMLCanvas* canvas = toRenderHTMLCanvas(m_renderer);
1976 if (canvas->height() <= 1 || canvas->width() <= 1)
1981 if (isNativeImage()) {
1982 // check for one-dimensional image
1983 RenderImage* image = toRenderImage(m_renderer);
1984 if (image->height() <= 1 || image->width() <= 1)
1987 // check whether rendered image was stretched from one-dimensional file image
1988 if (image->cachedImage()) {
1989 LayoutSize imageSize = image->cachedImage()->imageSizeForRenderer(m_renderer, image->view()->zoomFactor());
1990 return imageSize.height() <= 1 || imageSize.width() <= 1;
1996 if (isWebArea() || m_renderer->isListMarker())
1999 // Using the help text to decide an element's visibility is not as definitive
2000 // as previous checks, so this should remain as one of the last.
2001 if (!helpText().isEmpty())
2004 // By default, objects should be ignored so that the AX hierarchy is not
2005 // filled with unnecessary items.
2009 bool AccessibilityRenderObject::isLoaded() const
2011 return !m_renderer->document()->parser();
2014 double AccessibilityRenderObject::estimatedLoadingProgress() const
2022 Page* page = m_renderer->document()->page();
2026 return page->progress()->estimatedProgress();
2029 int AccessibilityRenderObject::layoutCount() const
2031 if (!m_renderer->isRenderView())
2033 return toRenderView(m_renderer)->frameView()->layoutCount();
2036 String AccessibilityRenderObject::text() const
2038 // If this is a user defined static text, use the accessible name computation.
2039 if (ariaRoleAttribute() == StaticTextRole)
2040 return ariaAccessibilityDescription();
2042 if (!isTextControl() || isPasswordField())
2045 Node* node = m_renderer->node();
2049 if (isNativeTextControl())
2050 return toRenderTextControl(m_renderer)->textFormControlElement()->value();
2052 if (!node->isElementNode())
2055 return static_cast<Element*>(node)->innerText();
2058 int AccessibilityRenderObject::textLength() const
2060 ASSERT(isTextControl());
2062 if (isPasswordField())
2063 return -1; // need to return something distinct from 0
2065 return text().length();
2068 PlainTextRange AccessibilityRenderObject::ariaSelectedTextRange() const
2070 Node* node = m_renderer->node();
2072 return PlainTextRange();
2074 ExceptionCode ec = 0;
2075 VisibleSelection visibleSelection = selection();
2076 RefPtr<Range> currentSelectionRange = visibleSelection.toNormalizedRange();
2077 if (!currentSelectionRange || !currentSelectionRange->intersectsNode(node, ec))
2078 return PlainTextRange();
2080 int start = indexForVisiblePosition(visibleSelection.start());
2081 int end = indexForVisiblePosition(visibleSelection.end());
2083 return PlainTextRange(start, end - start);
2086 String AccessibilityRenderObject::selectedText() const
2088 ASSERT(isTextControl());
2090 if (isPasswordField())
2091 return String(); // need to return something distinct from empty string
2093 if (isNativeTextControl()) {
2094 HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
2095 return textControl->selectedText();
2098 if (ariaRoleAttribute() == UnknownRole)
2101 return doAXStringForRange(ariaSelectedTextRange());
2104 const AtomicString& AccessibilityRenderObject::accessKey() const
2106 Node* node = m_renderer->node();
2109 if (!node->isElementNode())
2111 return static_cast<Element*>(node)->getAttribute(accesskeyAttr);
2114 VisibleSelection AccessibilityRenderObject::selection() const
2116 return m_renderer->frame()->selection()->selection();
2119 PlainTextRange AccessibilityRenderObject::selectedTextRange() const
2121 ASSERT(isTextControl());
2123 if (isPasswordField())
2124 return PlainTextRange();
2126 AccessibilityRole ariaRole = ariaRoleAttribute();
2127 if (isNativeTextControl() && ariaRole == UnknownRole) {
2128 HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
2129 return PlainTextRange(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
2132 if (ariaRole == UnknownRole)
2133 return PlainTextRange();
2135 return ariaSelectedTextRange();
2138 void AccessibilityRenderObject::setSelectedTextRange(const PlainTextRange& range)
2140 if (isNativeTextControl()) {
2141 HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
2142 textControl->setSelectionRange(range.start, range.start + range.length);
2146 Document* document = m_renderer->document();
2149 Frame* frame = document->frame();
2152 Node* node = m_renderer->node();
2153 frame->selection()->setSelection(VisibleSelection(Position(node, range.start, Position::PositionIsOffsetInAnchor),
2154 Position(node, range.start + range.length, Position::PositionIsOffsetInAnchor), DOWNSTREAM));
2157 KURL AccessibilityRenderObject::url() const
2159 if (isAnchor() && m_renderer->node()->hasTagName(aTag)) {
2160 if (HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(anchorElement()))
2161 return anchor->href();
2165 return m_renderer->document()->url();
2167 if (isImage() && m_renderer->node() && m_renderer->node()->hasTagName(imgTag))
2168 return static_cast<HTMLImageElement*>(m_renderer->node())->src();
2171 return static_cast<HTMLInputElement*>(m_renderer->node())->src();
2176 bool AccessibilityRenderObject::isUnvisited() const
2178 // FIXME: Is it a privacy violation to expose unvisited information to accessibility APIs?
2179 return m_renderer->style()->isLink() && m_renderer->style()->insideLink() == InsideUnvisitedLink;
2182 bool AccessibilityRenderObject::isVisited() const
2184 // FIXME: Is it a privacy violation to expose visited information to accessibility APIs?
2185 return m_renderer->style()->isLink() && m_renderer->style()->insideLink() == InsideVisitedLink;
2188 void AccessibilityRenderObject::setElementAttributeValue(const QualifiedName& attributeName, bool value)
2193 Node* node = m_renderer->node();
2194 if (!node || !node->isElementNode())
2197 Element* element = static_cast<Element*>(node);
2198 element->setAttribute(attributeName, (value) ? "true" : "false");
2201 bool AccessibilityRenderObject::elementAttributeValue(const QualifiedName& attributeName) const
2206 return equalIgnoringCase(getAttribute(attributeName), "true");
2209 bool AccessibilityRenderObject::isRequired() const
2211 if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
2215 if (n && (n->isElementNode() && static_cast<Element*>(n)->isFormControlElement()))
2216 return static_cast<HTMLFormControlElement*>(n)->required();
2221 bool AccessibilityRenderObject::isSelected() const
2226 Node* node = m_renderer->node();
2230 const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
2231 if (equalIgnoringCase(ariaSelected, "true"))
2234 if (isTabItem() && isTabItemSelected())
2240 bool AccessibilityRenderObject::isTabItemSelected() const
2242 if (!isTabItem() || !m_renderer)
2245 Node* node = m_renderer->node();
2246 if (!node || !node->isElementNode())
2249 // The ARIA spec says a tab item can also be selected if it is aria-labeled by a tabpanel
2250 // that has keyboard focus inside of it, or if a tabpanel in its aria-controls list has KB
2251 // focus inside of it.
2252 AccessibilityObject* focusedElement = focusedUIElement();
2253 if (!focusedElement)
2256 Vector<Element*> elements;
2257 elementsFromAttribute(elements, aria_controlsAttr);
2259 unsigned count = elements.size();
2260 for (unsigned k = 0; k < count; ++k) {
2261 Element* element = elements[k];
2262 AccessibilityObject* tabPanel = axObjectCache()->getOrCreate(element->renderer());
2264 // A tab item should only control tab panels.
2265 if (!tabPanel || tabPanel->roleValue() != TabPanelRole)
2268 AccessibilityObject* checkFocusElement = focusedElement;
2269 // Check if the focused element is a descendant of the element controlled by the tab item.
2270 while (checkFocusElement) {
2271 if (tabPanel == checkFocusElement)
2273 checkFocusElement = checkFocusElement->parentObject();
2280 bool AccessibilityRenderObject::isFocused() const
2285 Document* document = m_renderer->document();
2289 Node* focusedNode = document->focusedNode();
2293 // A web area is represented by the Document node in the DOM tree, which isn't focusable.
2294 // Check instead if the frame's selection controller is focused
2295 if (focusedNode == m_renderer->node()
2296 || (roleValue() == WebAreaRole && document->frame()->selection()->isFocusedAndActive()))
2302 void AccessibilityRenderObject::setFocused(bool on)
2304 if (!canSetFocusAttribute())
2308 m_renderer->document()->setFocusedNode(0);
2310 if (m_renderer->node()->isElementNode())
2311 static_cast<Element*>(m_renderer->node())->focus();
2313 m_renderer->document()->setFocusedNode(m_renderer->node());
2317 void AccessibilityRenderObject::changeValueByStep(bool increase)
2319 float step = stepValueForRange();
2320 float value = valueForRange();
2322 value += increase ? step : -step;
2324 setValue(String::number(value));
2326 axObjectCache()->postNotification(m_renderer, AXObjectCache::AXValueChanged, true);
2329 void AccessibilityRenderObject::changeValueByPercent(float percentChange)
2331 float range = maxValueForRange() - minValueForRange();
2332 float value = valueForRange();
2334 value += range * (percentChange / 100);
2335 setValue(String::number(value));
2337 axObjectCache()->postNotification(m_renderer, AXObjectCache::AXValueChanged, true);
2340 void AccessibilityRenderObject::setSelectedRows(AccessibilityChildrenVector& selectedRows)
2342 // Setting selected only makes sense in trees and tables (and tree-tables).
2343 AccessibilityRole role = roleValue();
2344 if (role != TreeRole && role != TreeGridRole && role != TableRole)
2347 bool isMulti = isMultiSelectable();
2348 unsigned count = selectedRows.size();
2349 if (count > 1 && !isMulti)
2352 for (unsigned k = 0; k < count; ++k)
2353 selectedRows[k]->setSelected(true);
2356 void AccessibilityRenderObject::setValue(const String& string)
2358 if (!m_renderer || !m_renderer->node() || !m_renderer->node()->isElementNode())
2360 Element* element = static_cast<Element*>(m_renderer->node());
2362 if (!m_renderer->isBoxModelObject())
2364 RenderBoxModelObject* renderer = toRenderBoxModelObject(m_renderer);
2366 // FIXME: Do we want to do anything here for ARIA textboxes?
2367 if (renderer->isTextField()) {
2368 // FIXME: This is not safe! Other elements could have a TextField renderer.
2369 static_cast<HTMLInputElement*>(element)->setValue(string);
2370 } else if (renderer->isTextArea()) {
2371 // FIXME: This is not safe! Other elements could have a TextArea renderer.
2372 static_cast<HTMLTextAreaElement*>(element)->setValue(string);
2376 void AccessibilityRenderObject::ariaOwnsElements(AccessibilityChildrenVector& axObjects) const
2378 Vector<Element*> elements;
2379 elementsFromAttribute(elements, aria_ownsAttr);
2381 unsigned count = elements.size();
2382 for (unsigned k = 0; k < count; ++k) {
2383 RenderObject* render = elements[k]->renderer();
2384 AccessibilityObject* obj = axObjectCache()->getOrCreate(render);
2386 axObjects.append(obj);
2390 bool AccessibilityRenderObject::supportsARIAOwns() const
2394 const AtomicString& ariaOwns = getAttribute(aria_ownsAttr);
2396 return !ariaOwns.isEmpty();
2399 bool AccessibilityRenderObject::isEnabled() const
2403 if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
2406 Node* node = m_renderer->node();
2407 if (!node || !node->isElementNode())
2410 return static_cast<Element*>(node)->isEnabledFormControl();
2413 RenderView* AccessibilityRenderObject::topRenderer() const
2415 Document* topDoc = topDocument();
2419 return topDoc->renderView();
2422 Document* AccessibilityRenderObject::document() const
2426 return m_renderer->document();
2429 Document* AccessibilityRenderObject::topDocument() const
2433 return document()->topDocument();
2436 FrameView* AccessibilityRenderObject::topDocumentFrameView() const
2438 RenderView* renderView = topRenderer();
2439 if (!renderView || !renderView->view())
2441 return renderView->view()->frameView();
2444 Widget* AccessibilityRenderObject::widget() const
2446 if (!m_renderer->isBoxModelObject() || !toRenderBoxModelObject(m_renderer)->isWidget())
2448 return toRenderWidget(m_renderer)->widget();
2451 AccessibilityObject* AccessibilityRenderObject::accessibilityParentForImageMap(HTMLMapElement* map) const
2453 // find an image that is using this map
2457 HTMLImageElement* imageElement = map->imageElement();
2461 return axObjectCache()->getOrCreate(imageElement->renderer());
2464 void AccessibilityRenderObject::getDocumentLinks(AccessibilityChildrenVector& result)
2466 Document* document = m_renderer->document();
2467 RefPtr<HTMLCollection> links = document->links();
2468 for (unsigned i = 0; Node* curr = links->item(i); i++) {
2469 RenderObject* obj = curr->renderer();
2471 RefPtr<AccessibilityObject> axobj = document->axObjectCache()->getOrCreate(obj);
2473 if (!axobj->accessibilityIsIgnored() && axobj->isLink())
2474 result.append(axobj);
2476 Node* parent = curr->parentNode();
2477 if (parent && curr->hasTagName(areaTag) && parent->hasTagName(mapTag)) {
2478 AccessibilityImageMapLink* areaObject = static_cast<AccessibilityImageMapLink*>(axObjectCache()->getOrCreate(ImageMapLinkRole));
2479 areaObject->setHTMLAreaElement(static_cast<HTMLAreaElement*>(curr));
2480 areaObject->setHTMLMapElement(static_cast<HTMLMapElement*>(parent));
2481 areaObject->setParent(accessibilityParentForImageMap(static_cast<HTMLMapElement*>(parent)));
2483 result.append(areaObject);
2489 FrameView* AccessibilityRenderObject::documentFrameView() const
2491 if (!m_renderer || !m_renderer->document())
2494 // this is the RenderObject's Document's Frame's FrameView
2495 return m_renderer->document()->view();
2498 Widget* AccessibilityRenderObject::widgetForAttachmentView() const
2500 if (!isAttachment())
2502 return toRenderWidget(m_renderer)->widget();
2505 FrameView* AccessibilityRenderObject::frameViewIfRenderView() const
2507 if (!m_renderer->isRenderView())
2509 // this is the RenderObject's Document's renderer's FrameView
2510 return m_renderer->view()->frameView();
2513 // This function is like a cross-platform version of - (WebCoreTextMarkerRange*)textMarkerRange. It returns
2514 // a Range that we can convert to a WebCoreTextMarkerRange in the Obj-C file
2515 VisiblePositionRange AccessibilityRenderObject::visiblePositionRange() const
2518 return VisiblePositionRange();
2520 // construct VisiblePositions for start and end
2521 Node* node = m_renderer->node();
2523 return VisiblePositionRange();
2525 VisiblePosition startPos = firstPositionInOrBeforeNode(node);
2526 VisiblePosition endPos = lastPositionInOrAfterNode(node);
2528 // the VisiblePositions are equal for nodes like buttons, so adjust for that
2529 // FIXME: Really? [button, 0] and [button, 1] are distinct (before and after the button)
2530 // I expect this code is only hit for things like empty divs? In which case I don't think
2531 // the behavior is correct here -- eseidel
2532 if (startPos == endPos) {
2533 endPos = endPos.next();
2534 if (endPos.isNull())
2538 return VisiblePositionRange(startPos, endPos);
2541 VisiblePositionRange AccessibilityRenderObject::visiblePositionRangeForLine(unsigned lineCount) const
2543 if (!lineCount || !m_renderer)
2544 return VisiblePositionRange();
2546 // iterate over the lines
2547 // FIXME: this is wrong when lineNumber is lineCount+1, because nextLinePosition takes you to the
2548 // last offset of the last line
2549 VisiblePosition visiblePos = m_renderer->document()->renderer()->positionForPoint(IntPoint());
2550 VisiblePosition savedVisiblePos;
2551 while (--lineCount) {
2552 savedVisiblePos = visiblePos;
2553 visiblePos = nextLinePosition(visiblePos, 0);
2554 if (visiblePos.isNull() || visiblePos == savedVisiblePos)
2555 return VisiblePositionRange();
2558 // make a caret selection for the marker position, then extend it to the line
2559 // NOTE: ignores results of sel.modify because it returns false when
2560 // starting at an empty line. The resulting selection in that case
2561 // will be a caret at visiblePos.
2562 FrameSelection selection;
2563 selection.setSelection(VisibleSelection(visiblePos));
2564 selection.modify(FrameSelection::AlterationExtend, DirectionRight, LineBoundary);
2566 return VisiblePositionRange(selection.selection().visibleStart(), selection.selection().visibleEnd());
2569 VisiblePosition AccessibilityRenderObject::visiblePositionForIndex(int index) const
2572 return VisiblePosition();
2574 if (isNativeTextControl())
2575 return toRenderTextControl(m_renderer)->visiblePositionForIndex(index);
2577 if (!allowsTextRanges() && !m_renderer->isText())
2578 return VisiblePosition();
2580 Node* node = m_renderer->node();
2582 return VisiblePosition();
2585 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2587 ExceptionCode ec = 0;
2588 RefPtr<Range> range = Range::create(m_renderer->document());
2589 range->selectNodeContents(node, ec);
2590 CharacterIterator it(range.get());
2591 it.advance(index - 1);
2592 return VisiblePosition(Position(it.range()->endContainer(ec), it.range()->endOffset(ec), Position::PositionIsOffsetInAnchor), UPSTREAM);
2595 int AccessibilityRenderObject::indexForVisiblePosition(const VisiblePosition& pos) const
2597 if (isNativeTextControl()) {
2598 HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
2599 return textControl->indexForVisiblePosition(pos);
2602 if (!isTextControl())
2605 Node* node = m_renderer->node();
2609 Position indexPosition = pos.deepEquivalent();
2610 if (indexPosition.isNull() || highestEditableRoot(indexPosition, HasEditableAXRole) != node)
2613 ExceptionCode ec = 0;
2614 RefPtr<Range> range = Range::create(m_renderer->document());
2615 range->setStart(node, 0, ec);
2616 range->setEnd(indexPosition, ec);
2619 // We need to consider replaced elements for GTK, as they will be
2620 // presented with the 'object replacement character' (0xFFFC).
2621 return TextIterator::rangeLength(range.get(), true);
2623 return TextIterator::rangeLength(range.get());
2627 Element* AccessibilityRenderObject::rootEditableElementForPosition(const Position& position) const
2629 // Find the root editable or pseudo-editable (i.e. having an editable ARIA role) element.
2630 Element* result = 0;
2632 Element* rootEditableElement = position.rootEditableElement();
2634 for (Element* e = position.element(); e && e != rootEditableElement; e = e->parentElement()) {
2635 if (nodeIsTextControl(e))
2637 if (e->hasTagName(bodyTag))
2644 return rootEditableElement;
2647 bool AccessibilityRenderObject::nodeIsTextControl(const Node* node) const
2652 const AccessibilityObject* axObjectForNode = axObjectCache()->getOrCreate(node->renderer());
2653 if (!axObjectForNode)
2656 return axObjectForNode->isTextControl();
2659 IntRect AccessibilityRenderObject::boundsForVisiblePositionRange(const VisiblePositionRange& visiblePositionRange) const
2661 if (visiblePositionRange.isNull())
2664 // Create a mutable VisiblePositionRange.
2665 VisiblePositionRange range(visiblePositionRange);
2666 LayoutRect rect1 = range.start.absoluteCaretBounds();
2667 LayoutRect rect2 = range.end.absoluteCaretBounds();
2669 // readjust for position at the edge of a line. This is to exclude line rect that doesn't need to be accounted in the range bounds
2670 if (rect2.y() != rect1.y()) {
2671 VisiblePosition endOfFirstLine = endOfLine(range.start);
2672 if (range.start == endOfFirstLine) {
2673 range.start.setAffinity(DOWNSTREAM);
2674 rect1 = range.start.absoluteCaretBounds();
2676 if (range.end == endOfFirstLine) {
2677 range.end.setAffinity(UPSTREAM);
2678 rect2 = range.end.absoluteCaretBounds();
2682 LayoutRect ourrect = rect1;
2683 ourrect.unite(rect2);
2685 // if the rectangle spans lines and contains multiple text chars, use the range's bounding box intead
2686 if (rect1.maxY() != rect2.maxY()) {
2687 RefPtr<Range> dataRange = makeRange(range.start, range.end);
2688 LayoutRect boundingBox = dataRange->boundingBox();
2689 String rangeString = plainText(dataRange.get());
2690 if (rangeString.length() > 1 && !boundingBox.isEmpty())
2691 ourrect = boundingBox;
2695 return m_renderer->document()->view()->contentsToScreen(pixelSnappedIntRect(ourrect));
2697 return pixelSnappedIntRect(ourrect);
2701 void AccessibilityRenderObject::setSelectedVisiblePositionRange(const VisiblePositionRange& range) const
2703 if (range.start.isNull() || range.end.isNull())
2706 // make selection and tell the document to use it. if it's zero length, then move to that position
2707 if (range.start == range.end)
2708 m_renderer->frame()->selection()->moveTo(range.start, UserTriggered);
2710 VisibleSelection newSelection = VisibleSelection(range.start, range.end);
2711 m_renderer->frame()->selection()->setSelection(newSelection);
2715 VisiblePosition AccessibilityRenderObject::visiblePositionForPoint(const IntPoint& point) const
2718 return VisiblePosition();
2720 // convert absolute point to view coordinates
2721 Document* topDoc = topDocument();
2722 if (!topDoc || !topDoc->renderer() || !topDoc->renderer()->view())
2723 return VisiblePosition();
2725 FrameView* frameView = topDoc->renderer()->view()->frameView();
2727 return VisiblePosition();
2729 RenderView* renderView = topRenderer();
2731 return VisiblePosition();
2733 Node* innerNode = 0;
2735 // locate the node containing the point
2736 LayoutPoint pointResult;
2738 LayoutPoint ourpoint;
2740 ourpoint = frameView->screenToContents(point);
2744 HitTestRequest request(HitTestRequest::ReadOnly |
2745 HitTestRequest::Active);
2746 HitTestResult result(ourpoint);
2747 renderView->hitTest(request, result);
2748 innerNode = result.innerNode();
2750 return VisiblePosition();
2752 RenderObject* renderer = innerNode->renderer();
2754 return VisiblePosition();
2756 pointResult = result.localPoint();
2758 // done if hit something other than a widget
2759 if (!renderer->isWidget())
2762 // descend into widget (FRAME, IFRAME, OBJECT...)
2763 Widget* widget = toRenderWidget(renderer)->widget();
2764 if (!widget || !widget->isFrameView())
2766 Frame* frame = static_cast<FrameView*>(widget)->frame();
2769 renderView = frame->document()->renderView();
2770 frameView = static_cast<FrameView*>(widget);
2773 return innerNode->renderer()->positionForPoint(pointResult);
2776 // NOTE: Consider providing this utility method as AX API
2777 VisiblePosition AccessibilityRenderObject::visiblePositionForIndex(unsigned indexValue, bool lastIndexOK) const
2779 if (!isTextControl())
2780 return VisiblePosition();
2782 // lastIndexOK specifies whether the position after the last character is acceptable
2783 if (indexValue >= text().length()) {
2784 if (!lastIndexOK || indexValue > text().length())
2785 return VisiblePosition();
2787 VisiblePosition position = visiblePositionForIndex(indexValue);
2788 position.setAffinity(DOWNSTREAM);
2792 // NOTE: Consider providing this utility method as AX API
2793 int AccessibilityRenderObject::index(const VisiblePosition& position) const
2795 if (position.isNull() || !isTextControl())
2798 if (renderObjectContainsPosition(m_renderer, position.deepEquivalent()))
2799 return indexForVisiblePosition(position);
2804 // Given a line number, the range of characters of the text associated with this accessibility
2805 // object that contains the line number.
2806 PlainTextRange AccessibilityRenderObject::doAXRangeForLine(unsigned lineNumber) const
2808 if (!isTextControl())
2809 return PlainTextRange();
2811 // iterate to the specified line
2812 VisiblePosition visiblePos = visiblePositionForIndex(0);
2813 VisiblePosition savedVisiblePos;
2814 for (unsigned lineCount = lineNumber; lineCount; lineCount -= 1) {
2815 savedVisiblePos = visiblePos;
2816 visiblePos = nextLinePosition(visiblePos, 0);
2817 if (visiblePos.isNull() || visiblePos == savedVisiblePos)
2818 return PlainTextRange();
2821 // Get the end of the line based on the starting position.
2822 VisiblePosition endPosition = endOfLine(visiblePos);
2824 int index1 = indexForVisiblePosition(visiblePos);
2825 int index2 = indexForVisiblePosition(endPosition);
2827 // add one to the end index for a line break not caused by soft line wrap (to match AppKit)
2828 if (endPosition.affinity() == DOWNSTREAM && endPosition.next().isNotNull())
2831 // return nil rather than an zero-length range (to match AppKit)
2832 if (index1 == index2)
2833 return PlainTextRange();
2835 return PlainTextRange(index1, index2 - index1);
2838 // The composed character range in the text associated with this accessibility object that
2839 // is specified by the given index value. This parameterized attribute returns the complete
2840 // range of characters (including surrogate pairs of multi-byte glyphs) at the given index.
2841 PlainTextRange AccessibilityRenderObject::doAXRangeForIndex(unsigned index) const
2843 if (!isTextControl())
2844 return PlainTextRange();
2846 String elementText = text();
2847 if (!elementText.length() || index > elementText.length() - 1)
2848 return PlainTextRange();
2850 return PlainTextRange(index, 1);
2853 // A substring of the text associated with this accessibility object that is
2854 // specified by the given character range.
2855 String AccessibilityRenderObject::doAXStringForRange(const PlainTextRange& range) const
2857 if (isPasswordField())
2863 if (!isTextControl())
2866 String elementText = text();
2867 if (range.start + range.length > elementText.length())
2870 return elementText.substring(range.start, range.length);
2873 // The bounding rectangle of the text associated with this accessibility object that is
2874 // specified by the given range. This is the bounding rectangle a sighted user would see
2875 // on the display screen, in pixels.
2876 IntRect AccessibilityRenderObject::doAXBoundsForRange(const PlainTextRange& range) const
2878 if (allowsTextRanges())
2879 return boundsForVisiblePositionRange(visiblePositionRangeForRange(range));
2883 AccessibilityObject* AccessibilityRenderObject::accessibilityImageMapHitTest(HTMLAreaElement* area, const IntPoint& point) const
2888 HTMLMapElement* map = static_cast<HTMLMapElement*>(area->parentNode());
2889 AccessibilityObject* parent = accessibilityParentForImageMap(map);
2893 AccessibilityObject::AccessibilityChildrenVector children = parent->children();
2895 unsigned count = children.size();
2896 for (unsigned k = 0; k < count; ++k) {
2897 if (children[k]->elementRect().contains(point))
2898 return children[k].get();
2904 AccessibilityObject* AccessibilityRenderObject::accessibilityHitTest(const IntPoint& point) const
2906 if (!m_renderer || !m_renderer->hasLayer())
2909 RenderLayer* layer = toRenderBox(m_renderer)->layer();
2911 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
2912 HitTestResult hitTestResult = HitTestResult(point);
2913 layer->hitTest(request, hitTestResult);
2914 if (!hitTestResult.innerNode())
2916 Node* node = hitTestResult.innerNode()->shadowAncestorNode();
2918 if (node->hasTagName(areaTag))
2919 return accessibilityImageMapHitTest(static_cast<HTMLAreaElement*>(node), point);
2921 if (node->hasTagName(optionTag))
2922 node = static_cast<HTMLOptionElement*>(node)->ownerSelectElement();
2924 RenderObject* obj = node->renderer();
2928 AccessibilityObject* result = obj->document()->axObjectCache()->getOrCreate(obj);
2929 result->updateChildrenIfNecessary();
2931 // Allow the element to perform any hit-testing it might need to do to reach non-render children.
2932 result = result->elementAccessibilityHitTest(point);
2934 if (result && result->accessibilityIsIgnored()) {
2935 // If this element is the label of a control, a hit test should return the control.
2936 AccessibilityObject* controlObject = result->correspondingControlForLabelElement();
2937 if (controlObject && !controlObject->exposesTitleUIElement())
2938 return controlObject;
2940 result = result->parentObjectUnignored();
2946 bool AccessibilityRenderObject::shouldFocusActiveDescendant() const
2948 switch (ariaRoleAttribute()) {
2954 case RadioGroupRole:
2956 case PopUpButtonRole:
2957 case ProgressIndicatorRole:
2962 /* FIXME: replace these with actual roles when they are added to AccessibilityRole
2975 AccessibilityObject* AccessibilityRenderObject::activeDescendant() const
2980 if (m_renderer->node() && !m_renderer->node()->isElementNode())
2982 Element* element = static_cast<Element*>(m_renderer->node());
2984 const AtomicString& activeDescendantAttrStr = element->getAttribute(aria_activedescendantAttr);
2985 if (activeDescendantAttrStr.isNull() || activeDescendantAttrStr.isEmpty())
2988 Element* target = element->treeScope()->getElementById(activeDescendantAttrStr);
2992 AccessibilityObject* obj = axObjectCache()->getOrCreate(target->renderer());
2993 if (obj && obj->isAccessibilityRenderObject())
2994 // an activedescendant is only useful if it has a renderer, because that's what's needed to post the notification
2999 void AccessibilityRenderObject::handleAriaExpandedChanged()
3001 // Find if a parent of this object should handle aria-expanded changes.
3002 AccessibilityObject* containerParent = this->parentObject();
3003 while (containerParent) {
3004 bool foundParent = false;
3006 switch (containerParent->roleValue()) {
3021 containerParent = containerParent->parentObject();
3024 // Post that the row count changed.
3025 if (containerParent)
3026 axObjectCache()->postNotification(containerParent, document(), AXObjectCache::AXRowCountChanged, true);
3028 // Post that the specific row either collapsed or expanded.
3029 if (roleValue() == RowRole || roleValue() == TreeItemRole)
3030 axObjectCache()->postNotification(this, document(), isExpanded() ? AXObjectCache::AXRowExpanded : AXObjectCache::AXRowCollapsed, true);
3033 void AccessibilityRenderObject::handleActiveDescendantChanged()
3035 Element* element = static_cast<Element*>(renderer()->node());
3038 Document* doc = renderer()->document();
3039 if (!doc->frame()->selection()->isFocusedAndActive() || doc->focusedNode() != element)
3041 AccessibilityRenderObject* activedescendant = static_cast<AccessibilityRenderObject*>(activeDescendant());
3043 if (activedescendant && shouldFocusActiveDescendant())
3044 doc->axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
3047 AccessibilityObject* AccessibilityRenderObject::correspondingControlForLabelElement() const
3049 HTMLLabelElement* labelElement = labelElementContainer();
3053 HTMLElement* correspondingControl = labelElement->control();
3054 if (!correspondingControl)
3057 return axObjectCache()->getOrCreate(correspondingControl->renderer());
3060 AccessibilityObject* AccessibilityRenderObject::correspondingLabelForControlElement() const
3065 Node* node = m_renderer->node();
3066 if (node && node->isHTMLElement()) {
3067 HTMLLabelElement* label = labelForElement(static_cast<Element*>(node));
3069 return axObjectCache()->getOrCreate(label->renderer());
3075 bool AccessibilityRenderObject::renderObjectIsObservable(RenderObject* renderer) const
3077 // AX clients will listen for AXValueChange on a text control.
3078 if (renderer->isTextControl())
3081 // AX clients will listen for AXSelectedChildrenChanged on listboxes.
3082 Node* node = renderer->node();
3083 if (nodeHasRole(node, "listbox") || (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListBox()))
3086 // Textboxes should send out notifications.
3087 if (nodeHasRole(node, "textbox"))
3093 AccessibilityObject* AccessibilityRenderObject::observableObject() const
3095 // Find the object going up the parent chain that is used in accessibility to monitor certain notifications.
3096 for (RenderObject* renderer = m_renderer; renderer && renderer->node(); renderer = renderer->parent()) {
3097 if (renderObjectIsObservable(renderer))
3098 return axObjectCache()->getOrCreate(renderer);
3104 bool AccessibilityRenderObject::isDescendantOfElementType(const QualifiedName& tagName) const
3106 for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
3107 if (parent->node() && parent->node()->hasTagName(tagName))
3113 AccessibilityRole AccessibilityRenderObject::determineAccessibilityRole()
3118 m_ariaRole = determineAriaRoleAttribute();
3120 Node* node = m_renderer->node();
3121 AccessibilityRole ariaRole = ariaRoleAttribute();
3122 if (ariaRole != UnknownRole)
3125 RenderBoxModelObject* cssBox = renderBoxModelObject();
3127 if (node && node->isLink()) {
3128 if (cssBox && cssBox->isImage())
3129 return ImageMapRole;
3130 return WebCoreLinkRole;
3132 if (cssBox && cssBox->isListItem())
3133 return ListItemRole;
3134 if (m_renderer->isListMarker())
3135 return ListMarkerRole;
3136 if (node && node->hasTagName(buttonTag))
3137 return ariaHasPopup() ? PopUpButtonRole : ButtonRole;
3138 if (m_renderer->isText())
3139 return StaticTextRole;
3140 if (cssBox && cssBox->isImage()) {
3141 if (node && node->hasTagName(inputTag))
3142 return ariaHasPopup() ? PopUpButtonRole : ButtonRole;
3145 if (node && node->hasTagName(canvasTag))
3148 if (cssBox && cssBox->isRenderView())
3151 if (cssBox && cssBox->isTextField())
3152 return TextFieldRole;
3154 if (cssBox && cssBox->isTextArea())
3155 return TextAreaRole;
3157 if (node && node->hasTagName(inputTag)) {
3158 HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
3159 if (input->isCheckbox())
3160 return CheckBoxRole;
3161 if (input->isRadioButton())
3162 return RadioButtonRole;
3163 if (input->isTextButton())
3164 return ariaHasPopup() ? PopUpButtonRole : ButtonRole;
3167 if (isFileUploadButton())
3170 if (cssBox && cssBox->isMenuList())
3171 return PopUpButtonRole;
3177 if (node && node->hasTagName(MathMLNames::mathTag))
3178 return DocumentMathRole;
3181 if (node && node->hasTagName(ddTag))
3182 return DefinitionListDefinitionRole;
3184 if (node && node->hasTagName(dtTag))
3185 return DefinitionListTermRole;
3187 if (node && (node->hasTagName(rpTag) || node->hasTagName(rtTag)))
3188 return AnnotationRole;
3191 // Gtk ATs expect all tables, data and layout, to be exposed as tables.
3192 if (node && (node->hasTagName(tdTag) || node->hasTagName(thTag)))
3195 if (node && node->hasTagName(trTag))
3198 if (node && node->hasTagName(tableTag))
3202 // Table sections should be ignored.
3203 if (m_renderer->isTableSection())
3207 if (m_renderer->isHR())
3208 return SplitterRole;
3210 if (node && node->hasTagName(pTag))
3211 return ParagraphRole;
3213 if (node && node->hasTagName(labelTag))
3216 if (node && node->hasTagName(divTag))
3219 if (node && node->hasTagName(formTag))
3222 if (node && node->hasTagName(labelTag))
3226 if (node && node->hasTagName(articleTag))
3227 return DocumentArticleRole;
3229 if (node && node->hasTagName(navTag))
3230 return LandmarkNavigationRole;
3232 if (node && node->hasTagName(asideTag))
3233 return LandmarkComplementaryRole;
3235 if (node && node->hasTagName(sectionTag))
3236 return DocumentRegionRole;
3238 if (node && node->hasTagName(addressTag))
3239 return LandmarkContentInfoRole;
3241 // There should only be one banner/contentInfo per page. If header/footer are being used within an article or section
3242 // then it should not be exposed as whole page's banner/contentInfo
3243 if (node && node->hasTagName(headerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
3244 return LandmarkBannerRole;
3245 if (node && node->hasTagName(footerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
3248 if (m_renderer->isBlockFlow())
3251 // If the element does not have role, but it has ARIA attributes, accessibility should fallback to exposing it as a group.
3252 if (supportsARIAAttributes())
3258 AccessibilityOrientation AccessibilityRenderObject::orientation() const
3260 const AtomicString& ariaOrientation = getAttribute(aria_orientationAttr);
3261 if (equalIgnoringCase(ariaOrientation, "horizontal"))
3262 return AccessibilityOrientationHorizontal;
3263 if (equalIgnoringCase(ariaOrientation, "vertical"))
3264 return AccessibilityOrientationVertical;
3266 return AccessibilityObject::orientation();
3269 bool AccessibilityRenderObject::inheritsPresentationalRole() const
3271 // ARIA states if an item can get focus, it should not be presentational.
3272 if (canSetFocusAttribute())
3275 // ARIA spec says that when a parent object is presentational, and it has required child elements,
3276 // those child elements are also presentational. For example, <li> becomes presentational from <ul>.
3277 // http://www.w3.org/WAI/PF/aria/complete#presentation
3278 DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, listItemParents, ());
3280 HashSet<QualifiedName>* possibleParentTagNames = 0;
3281 switch (roleValue()) {
3283 case ListMarkerRole:
3284 if (listItemParents.isEmpty()) {
3285 listItemParents.add(ulTag);
3286 listItemParents.add(olTag);
3287 listItemParents.add(dlTag);
3289 possibleParentTagNames = &listItemParents;
3295 // Not all elements need to check for this, only ones that are required children.
3296 if (!possibleParentTagNames)
3299 for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
3300 if (!parent->isAccessibilityRenderObject())
3303 Node* elementNode = static_cast<AccessibilityRenderObject*>(parent)->node();
3304 if (!elementNode || !elementNode->isElementNode())
3307 // If native tag of the parent element matches an acceptable name, then return
3308 // based on its presentational status.
3309 if (possibleParentTagNames->contains(static_cast<Element*>(elementNode)->tagQName()))
3310 return parent->roleValue() == PresentationalRole;
3316 bool AccessibilityRenderObject::isPresentationalChildOfAriaRole() const
3318 // Walk the parent chain looking for a parent that has presentational children
3319 AccessibilityObject* parent;
3320 for (parent = parentObject(); parent && !parent->ariaRoleHasPresentationalChildren(); parent = parent->parentObject())
3326 bool AccessibilityRenderObject::ariaRoleHasPresentationalChildren() const
3328 switch (m_ariaRole) {
3332 case ProgressIndicatorRole:
3333 // case SeparatorRole:
3340 bool AccessibilityRenderObject::canSetExpandedAttribute() const
3342 // An object can be expanded if it aria-expanded is true or false.
3343 const AtomicString& ariaExpanded = getAttribute(aria_expandedAttr);
3344 return equalIgnoringCase(ariaExpanded, "true") || equalIgnoringCase(ariaExpanded, "false");
3347 bool AccessibilityRenderObject::canSetValueAttribute() const
3349 if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
3352 if (isProgressIndicator() || isSlider())
3355 if (isTextControl() && !isNativeTextControl())
3358 // Any node could be contenteditable, so isReadOnly should be relied upon
3359 // for this information for all elements.
3360 return !isReadOnly();
3363 bool AccessibilityRenderObject::canSetTextRangeAttributes() const
3365 return isTextControl();
3368 void AccessibilityRenderObject::contentChanged()
3370 // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
3371 // then notify the AT of changes.
3372 AXObjectCache* cache = axObjectCache();
3373 for (RenderObject* renderParent = m_renderer; renderParent; renderParent = renderParent->parent()) {
3374 AccessibilityObject* parent = cache->get(renderParent);
3378 if (parent->supportsARIALiveRegion())
3379 cache->postNotification(renderParent, AXObjectCache::AXLiveRegionChanged, true);
3381 if (parent->isARIATextControl() && !parent->isNativeTextControl() && !parent->node()->rendererIsEditable())
3382 cache->postNotification(renderParent, AXObjectCache::AXValueChanged, true);
3386 bool AccessibilityRenderObject::canHaveChildren() const
3391 // Canvas is a special case; its role is ImageRole but it is allowed to have children.
3392 if (node() && node()->hasTagName(canvasTag))
3395 // Elements that should not have children
3396 switch (roleValue()) {
3399 case PopUpButtonRole:
3401 case RadioButtonRole:
3403 case StaticTextRole:
3404 case ListBoxOptionRole:
3412 void AccessibilityRenderObject::clearChildren()
3414 AccessibilityObject::clearChildren();
3415 m_childrenDirty = false;
3418 void AccessibilityRenderObject::addImageMapChildren()
3420 RenderBoxModelObject* cssBox = renderBoxModelObject();
3421 if (!cssBox || !cssBox->isRenderImage())
3424 HTMLMapElement* map = toRenderImage(cssBox)->imageMap();
3428 for (Node* current = map->firstChild(); current; current = current->traverseNextNode(map)) {
3430 // add an <area> element for this child if it has a link
3431 if (current->hasTagName(areaTag) && current->isLink()) {
3432 AccessibilityImageMapLink* areaObject = static_cast<AccessibilityImageMapLink*>(axObjectCache()->getOrCreate(ImageMapLinkRole));
3433 areaObject->setHTMLAreaElement(static_cast<HTMLAreaElement*>(current));
3434 areaObject->setHTMLMapElement(map);
3435 areaObject->setParent(this);
3437 m_children.append(areaObject);
3442 void AccessibilityRenderObject::updateChildrenIfNecessary()
3444 if (needsToUpdateChildren())
3447 AccessibilityObject::updateChildrenIfNecessary();
3450 void AccessibilityRenderObject::addTextFieldChildren()
3452 Node* node = this->node();
3453 if (!node || !node->hasTagName(inputTag))
3456 HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
3457 HTMLElement* spinButtonElement = input->innerSpinButtonElement();
3458 if (!spinButtonElement || !spinButtonElement->isSpinButtonElement())
3461 AccessibilitySpinButton* axSpinButton = static_cast<AccessibilitySpinButton*>(axObjectCache()->getOrCreate(SpinButtonRole));
3462 axSpinButton->setSpinButtonElement(static_cast<SpinButtonElement*>(spinButtonElement));
3463 axSpinButton->setParent(this);
3464 m_children.append(axSpinButton);
3467 void AccessibilityRenderObject::addCanvasChildren()
3469 if (!node() || !node()->hasTagName(canvasTag))
3472 // If it's a canvas, it won't have rendered children, but it might have accessible fallback content.
3473 // Clear m_haveChildren because AccessibilityNodeObject::addChildren will expect it to be false.
3474 ASSERT(!m_children.size());
3475 m_haveChildren = false;
3476 AccessibilityNodeObject::addChildren();
3479 void AccessibilityRenderObject::addAttachmentChildren()
3481 if (!isAttachment())
3484 // FrameView's need to be inserted into the AX hierarchy when encountered.
3485 Widget* widget = widgetForAttachmentView();
3486 if (!widget || !widget->isFrameView())
3489 AccessibilityObject* axWidget = axObjectCache()->getOrCreate(widget);
3490 if (!axWidget->accessibilityIsIgnored())
3491 m_children.append(axWidget);
3495 void AccessibilityRenderObject::updateAttachmentViewParents()
3497 // Only the unignored parent should set the attachment parent, because that's what is reflected in the AX
3498 // hierarchy to the client.
3499 if (accessibilityIsIgnored())
3502 size_t length = m_children.size();
3503 for (size_t k = 0; k < length; k++) {
3504 if (m_children[k]->isAttachment())
3505 m_children[k]->overrideAttachmentParent(this);
3510 void AccessibilityRenderObject::addChildren()
3512 // If the need to add more children in addition to existing children arises,
3513 // childrenChanged should have been called, leaving the object with no children.
3514 ASSERT(!m_haveChildren);
3516 m_haveChildren = true;
3518 if (!canHaveChildren())
3521 // add all unignored acc children
3522 for (RefPtr<AccessibilityObject> obj = firstChild(); obj; obj = obj->nextSibling()) {
3523 // If the parent is asking for this child's children, then either it's the first time (and clearing is a no-op),
3524 // or its visibility has changed. In the latter case, this child may have a stale child cached.
3525 // This can prevent aria-hidden changes from working correctly. Hence, whenever a parent is getting children, ensure data is not stale.
3526 obj->clearChildren();
3528 if (obj->accessibilityIsIgnored()) {
3529 AccessibilityChildrenVector children = obj->children();
3530 unsigned length = children.size();
3531 for (unsigned i = 0; i < length; ++i)
3532 m_children.append(children[i]);
3534 ASSERT(obj->parentObject() == this);
3535 m_children.append(obj);
3539 addAttachmentChildren();
3540 addImageMapChildren();
3541 addTextFieldChildren();
3542 addCanvasChildren();
3545 updateAttachmentViewParents();
3549 const AtomicString& AccessibilityRenderObject::ariaLiveRegionStatus() const
3551 DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusAssertive, ("assertive"));
3552 DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusPolite, ("polite"));
3553 DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusOff, ("off"));
3555 const AtomicString& liveRegionStatus = getAttribute(aria_liveAttr);
3556 // These roles have implicit live region status.
3557 if (liveRegionStatus.isEmpty()) {
3558 switch (roleValue()) {
3559 case ApplicationAlertDialogRole:
3560 case ApplicationAlertRole:
3561 return liveRegionStatusAssertive;
3562 case ApplicationLogRole:
3563 case ApplicationStatusRole:
3564 return liveRegionStatusPolite;
3565 case ApplicationTimerRole:
3566 case ApplicationMarqueeRole:
3567 return liveRegionStatusOff;
3573 return liveRegionStatus;
3576 const AtomicString& AccessibilityRenderObject::ariaLiveRegionRelevant() const
3578 DEFINE_STATIC_LOCAL(const AtomicString, defaultLiveRegionRelevant, ("additions text"));
3579 const AtomicString& relevant = getAttribute(aria_relevantAttr);
3581 // Default aria-relevant = "additions text".
3582 if (relevant.isEmpty())
3583 return defaultLiveRegionRelevant;
3588 bool AccessibilityRenderObject::ariaLiveRegionAtomic() const
3590 return elementAttributeValue(aria_atomicAttr);
3593 bool AccessibilityRenderObject::ariaLiveRegionBusy() const
3595 return elementAttributeValue(aria_busyAttr);
3598 void AccessibilityRenderObject::ariaSelectedRows(AccessibilityChildrenVector& result)
3600 // Get all the rows.
3601 AccessibilityChildrenVector allRows;
3603 ariaTreeRows(allRows);
3604 else if (isAccessibilityTable() && toAccessibilityTable(this)->supportsSelectedRows())
3605 allRows = toAccessibilityTable(this)->rows();
3607 // Determine which rows are selected.
3608 bool isMulti = isMultiSelectable();
3610 // Prefer active descendant over aria-selected.
3611 AccessibilityObject* activeDesc = activeDescendant();
3612 if (activeDesc && (activeDesc->isTreeItem() || activeDesc->isTableRow())) {
3613 result.append(activeDesc);
3618 unsigned count = allRows.size();
3619 for (unsigned k = 0; k < count; ++k) {
3620 if (allRows[k]->isSelected()) {
3621 result.append(allRows[k]);
3628 void AccessibilityRenderObject::ariaListboxSelectedChildren(AccessibilityChildrenVector& result)
3630 bool isMulti = isMultiSelectable();
3632 AccessibilityChildrenVector childObjects = children();
3633 unsigned childrenSize = childObjects.size();
3634 for (unsigned k = 0; k < childrenSize; ++k) {
3635 // Every child should have aria-role option, and if so, check for selected attribute/state.
3636 AccessibilityObject* child = childObjects[k].get();
3637 if (child->isSelected() && child->ariaRoleAttribute() == ListBoxOptionRole) {
3638 result.append(child);
3645 void AccessibilityRenderObject::selectedChildren(AccessibilityChildrenVector& result)
3647 ASSERT(result.isEmpty());
3649 // only listboxes should be asked for their selected children.
3650 AccessibilityRole role = roleValue();
3651 if (role == ListBoxRole) // native list boxes would be AccessibilityListBoxes, so only check for aria list boxes
3652 ariaListboxSelectedChildren(result);
3653 else if (role == TreeRole || role == TreeGridRole || role == TableRole)
3654 ariaSelectedRows(result);
3657 void AccessibilityRenderObject::ariaListboxVisibleChildren(AccessibilityChildrenVector& result)
3662 AccessibilityObject::AccessibilityChildrenVector children = this->children();
3663 size_t size = children.size();
3664 for (size_t i = 0; i < size; i++) {
3665 if (!children[i]->isOffScreen())
3666 result.append(children[i]);
3670 void AccessibilityRenderObject::visibleChildren(AccessibilityChildrenVector& result)
3672 ASSERT(result.isEmpty());
3674 // only listboxes are asked for their visible children.
3675 if (ariaRoleAttribute() != ListBoxRole) { // native list boxes would be AccessibilityListBoxes, so only check for aria list boxes
3676 ASSERT_NOT_REACHED();
3679 return ariaListboxVisibleChildren(result);
3682 void AccessibilityRenderObject::tabChildren(AccessibilityChildrenVector& result)
3684 ASSERT(roleValue() == TabListRole);
3686 AccessibilityObject::AccessibilityChildrenVector children = this->children();
3687 size_t size = children.size();
3688 for (size_t i = 0; i < size; ++i) {
3689 if (children[i]->isTabItem())
3690 result.append(children[i]);
3694 const String& AccessibilityRenderObject::actionVerb() const
3696 // FIXME: Need to add verbs for select elements.
3697 DEFINE_STATIC_LOCAL(const String, buttonAction, (AXButtonActionVerb()));
3698 DEFINE_STATIC_LOCAL(const String, textFieldAction, (AXTextFieldActionVerb()));
3699 DEFINE_STATIC_LOCAL(const String, radioButtonAction, (AXRadioButtonActionVerb()));
3700 DEFINE_STATIC_LOCAL(const String, checkedCheckBoxAction, (AXCheckedCheckBoxActionVerb()));
3701 DEFINE_STATIC_LOCAL(const String, uncheckedCheckBoxAction, (AXUncheckedCheckBoxActionVerb()));
3702 DEFINE_STATIC_LOCAL(const String, linkAction, (AXLinkActionVerb()));
3703 DEFINE_STATIC_LOCAL(const String, noAction, ());
3705 switch (roleValue()) {
3707 return buttonAction;
3710 return textFieldAction;
3711 case RadioButtonRole:
3712 return radioButtonAction;
3714 return isChecked() ? checkedCheckBoxAction : uncheckedCheckBoxAction;
3716 case WebCoreLinkRole:
3723 void AccessibilityRenderObject::setAccessibleName(const AtomicString& name)
3725 // Setting the accessible name can store the value in the DOM
3730 // For web areas, set the aria-label on the HTML element.
3732 domNode = m_renderer->document()->documentElement();
3734 domNode = m_renderer->node();
3736 if (domNode && domNode->isElementNode())
3737 static_cast<Element*>(domNode)->setAttribute(aria_labelAttr, name);
3740 static bool isLinkable(const AccessibilityRenderObject& object)
3742 if (!object.renderer())
3745 // See https://wiki.mozilla.org/Accessibility/AT-Windows-API for the elements
3746 // Mozilla considers linkable.
3747 return object.isLink() || object.isImage() || object.renderer()->isText();
3750 String AccessibilityRenderObject::stringValueForMSAA() const
3752 if (isLinkable(*this)) {
3753 Element* anchor = anchorElement();
3754 if (anchor && anchor->hasTagName(aTag))
3755 return static_cast<HTMLAnchorElement*>(anchor)->href();
3758 return stringValue();
3761 bool AccessibilityRenderObject::isLinked() const
3763 if (!isLinkable(*this))
3766 Element* anchor = anchorElement();
3767 if (!anchor || !anchor->hasTagName(aTag))
3770 return !static_cast<HTMLAnchorElement*>(anchor)->href().isEmpty();
3773 bool AccessibilityRenderObject::hasBoldFont() const
3778 return m_renderer->style()->fontDescription().weight() >= FontWeightBold;
3781 bool AccessibilityRenderObject::hasItalicFont() const
3786 return m_renderer->style()->fontDescription().italic() == FontItalicOn;
3789 bool AccessibilityRenderObject::hasPlainText() const
3794 RenderStyle* style = m_renderer->style();
3796 return style->fontDescription().weight() == FontWeightNormal
3797 && style->fontDescription().italic() == FontItalicOff
3798 && style->textDecorationsInEffect() == TDNONE;
3801 bool AccessibilityRenderObject::hasSameFont(RenderObject* renderer) const
3803 if (!m_renderer || !renderer)
3806 return m_renderer->style()->fontDescription().family() == renderer->style()->fontDescription().family();
3809 bool AccessibilityRenderObject::hasSameFontColor(RenderObject* renderer) const
3811 if (!m_renderer || !renderer)
3814 return m_renderer->style()->visitedDependentColor(CSSPropertyColor) == renderer->style()->visitedDependentColor(CSSPropertyColor);
3817 bool AccessibilityRenderObject::hasSameStyle(RenderObject* renderer) const
3819 if (!m_renderer || !renderer)
3822 return m_renderer->style() == renderer->style();
3825 bool AccessibilityRenderObject::hasUnderline() const
3830 return m_renderer->style()->textDecorationsInEffect() & UNDERLINE;
3833 String AccessibilityRenderObject::nameForMSAA() const
3835 if (m_renderer && m_renderer->isText())
3836 return textUnderElement();
3841 static bool shouldReturnTagNameAsRoleForMSAA(const Element& element)
3843 // See "document structure",
3844 // https://wiki.mozilla.org/Accessibility/AT-Windows-API
3845 // FIXME: Add the other tag names that should be returned as the role.
3846 return element.hasTagName(h1Tag) || element.hasTagName(h2Tag)
3847 || element.hasTagName(h3Tag) || element.hasTagName(h4Tag)
3848 || element.hasTagName(h5Tag) || element.hasTagName(h6Tag);
3851 String AccessibilityRenderObject::stringRoleForMSAA() const
3856 Node* node = m_renderer->node();
3857 if (!node || !node->isElementNode())
3860 Element* element = static_cast<Element*>(node);
3861 if (!shouldReturnTagNameAsRoleForMSAA(*element))
3864 return element->tagName();
3867 String AccessibilityRenderObject::positionalDescriptionForMSAA() const
3869 // See "positional descriptions",
3870 // https://wiki.mozilla.org/Accessibility/AT-Windows-API
3872 return "L" + String::number(headingLevel());
3874 // FIXME: Add positional descriptions for other elements.
3878 String AccessibilityRenderObject::descriptionForMSAA() const
3880 String description = positionalDescriptionForMSAA();
3881 if (!description.isEmpty())
3884 description = accessibilityDescription();
3885 if (!description.isEmpty()) {
3886 // From the Mozilla MSAA implementation:
3887 // "Signal to screen readers that this description is speakable and is not
3888 // a formatted positional information description. Don't localize the
3889 // 'Description: ' part of this string, it will be parsed out by assistive
3891 return "Description: " + description;
3897 static AccessibilityRole msaaRoleForRenderer(const RenderObject* renderer)
3902 if (renderer->isText())
3903 return EditableTextRole;
3905 if (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListItem())
3906 return ListItemRole;
3911 AccessibilityRole AccessibilityRenderObject::roleValueForMSAA() const
3913 if (m_roleForMSAA != UnknownRole)
3914 return m_roleForMSAA;
3916 m_roleForMSAA = msaaRoleForRenderer(m_renderer);
3918 if (m_roleForMSAA == UnknownRole)
3919 m_roleForMSAA = roleValue();
3921 return m_roleForMSAA;
3924 ScrollableArea* AccessibilityRenderObject::getScrollableAreaIfScrollable() const
3926 // If the parent is a scroll view, then this object isn't really scrollable, the parent ScrollView should handle the scrolling.
3927 if (parentObject() && parentObject()->isAccessibilityScrollView())
3930 if (!m_renderer || !m_renderer->isBox())
3933 RenderBox* box = toRenderBox(m_renderer);
3934 if (!box->canBeScrolledAndHasScrollableArea())
3937 return box->layer();
3940 void AccessibilityRenderObject::scrollTo(const IntPoint& point) const
3942 if (!m_renderer || !m_renderer->isBox())
3945 RenderBox* box = toRenderBox(m_renderer);
3946 if (!box->canBeScrolledAndHasScrollableArea())
3949 RenderLayer* layer = box->layer();
3950 layer->scrollToOffset(toSize(point), RenderLayer::ScrollOffsetClamped);
3953 } // namespace WebCore