OSDN Git Service

efa2036807e0d0b385d119144cd701498d4d967b
[android-x86/external-webkit.git] / WebCore / accessibility / AccessibilityRenderObject.cpp
1 /*
2 * Copyright (C) 2008 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
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.
16 *
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.
27 */
28
29 #include "config.h"
30 #include "AccessibilityRenderObject.h"
31
32 #include "AXObjectCache.h"
33 #include "AccessibilityImageMapLink.h"
34 #include "AccessibilityListBox.h"
35 #include "CharacterNames.h"
36 #include "EventNames.h"
37 #include "FloatRect.h"
38 #include "Frame.h"
39 #include "FrameLoader.h"
40 #include "HTMLAreaElement.h"
41 #include "HTMLFormElement.h"
42 #include "HTMLFrameElementBase.h"
43 #include "HTMLImageElement.h"
44 #include "HTMLInputElement.h"
45 #include "HTMLLabelElement.h"
46 #include "HTMLMapElement.h"
47 #include "HTMLOptGroupElement.h"
48 #include "HTMLOptionElement.h"
49 #include "HTMLOptionsCollection.h"
50 #include "HTMLSelectElement.h"
51 #include "HTMLTextAreaElement.h"
52 #include "HitTestRequest.h"
53 #include "HitTestResult.h"
54 #include "LocalizedStrings.h"
55 #include "NodeList.h"
56 #include "ProgressTracker.h"
57 #include "RenderButton.h"
58 #include "RenderFieldset.h"
59 #include "RenderFileUploadControl.h"
60 #include "RenderHTMLCanvas.h"
61 #include "RenderImage.h"
62 #include "RenderInline.h"
63 #include "RenderLayer.h"
64 #include "RenderListBox.h"
65 #include "RenderListMarker.h"
66 #include "RenderMenuList.h"
67 #include "RenderText.h"
68 #include "RenderTextControl.h"
69 #include "RenderTextFragment.h"
70 #include "RenderTheme.h"
71 #include "RenderView.h"
72 #include "RenderWidget.h"
73 #include "SelectElement.h"
74 #include "SelectionController.h"
75 #include "Text.h"
76 #include "TextIterator.h"
77 #include "htmlediting.h"
78 #include "visible_units.h"
79 #include <wtf/StdLibExtras.h>
80
81 using namespace std;
82
83 namespace WebCore {
84
85 using namespace HTMLNames;
86
87 AccessibilityRenderObject::AccessibilityRenderObject(RenderObject* renderer)
88     : AccessibilityObject()
89     , m_renderer(renderer)
90     , m_ariaRole(UnknownRole)
91     , m_childrenDirty(false)
92     , m_roleForMSAA(UnknownRole)
93 {
94     m_role = determineAccessibilityRole();
95     
96 #ifndef NDEBUG
97     m_renderer->setHasAXObject(true);
98 #endif
99 }
100
101 AccessibilityRenderObject::~AccessibilityRenderObject()
102 {
103     ASSERT(isDetached());
104 }
105
106 PassRefPtr<AccessibilityRenderObject> AccessibilityRenderObject::create(RenderObject* renderer)
107 {
108     return adoptRef(new AccessibilityRenderObject(renderer));
109 }
110
111 void AccessibilityRenderObject::detach()
112 {
113     clearChildren();
114     AccessibilityObject::detach();
115     
116 #ifndef NDEBUG
117     if (m_renderer)
118         m_renderer->setHasAXObject(false);
119 #endif
120     m_renderer = 0;    
121 }
122
123 RenderBoxModelObject* AccessibilityRenderObject::renderBoxModelObject() const
124 {
125     if (!m_renderer || !m_renderer->isBoxModelObject())
126         return 0;
127     return toRenderBoxModelObject(m_renderer);
128 }
129
130 static inline bool isInlineWithContinuation(RenderObject* object)
131 {
132     if (!object->isBoxModelObject())
133         return false;
134
135     RenderBoxModelObject* renderer = toRenderBoxModelObject(object);
136     if (!renderer->isRenderInline())
137         return false;
138
139     return toRenderInline(renderer)->continuation();
140 }
141
142 static inline RenderObject* firstChildInContinuation(RenderObject* renderer)
143 {
144     RenderObject* r = toRenderInline(renderer)->continuation();
145
146     while (r) {
147         if (r->isRenderBlock())
148             return r;
149         if (RenderObject* child = r->firstChild())
150             return child;
151         r = toRenderInline(r)->continuation(); 
152     }
153
154     return 0;
155 }
156
157 static inline RenderObject* firstChildConsideringContinuation(RenderObject* renderer)
158 {
159     RenderObject* firstChild = renderer->firstChild();
160
161     if (!firstChild && isInlineWithContinuation(renderer))
162         firstChild = firstChildInContinuation(renderer);
163
164     return firstChild;
165 }
166
167
168 static inline RenderObject* lastChildConsideringContinuation(RenderObject* renderer)
169 {
170     RenderObject* lastChild = renderer->lastChild();
171     RenderObject* prev;
172     RenderObject* cur = renderer;
173
174     if (!cur->isRenderInline() && !cur->isRenderBlock())
175         return renderer;
176
177     while (cur) {
178         prev = cur;
179
180         if (RenderObject* lc = cur->lastChild())
181             lastChild = lc;
182
183         if (cur->isRenderInline()) {
184             cur = toRenderInline(cur)->inlineElementContinuation();
185             ASSERT(cur || !toRenderInline(prev)->continuation());
186         } else
187             cur = toRenderBlock(cur)->inlineElementContinuation();
188     }
189
190     return lastChild;
191 }
192
193 AccessibilityObject* AccessibilityRenderObject::firstChild() const
194 {
195     if (!m_renderer)
196         return 0;
197     
198     RenderObject* firstChild = firstChildConsideringContinuation(m_renderer);
199
200     if (!firstChild)
201         return 0;
202     
203     return axObjectCache()->getOrCreate(firstChild);
204 }
205
206 AccessibilityObject* AccessibilityRenderObject::lastChild() const
207 {
208     if (!m_renderer)
209         return 0;
210
211     RenderObject* lastChild = lastChildConsideringContinuation(m_renderer);
212
213     if (!lastChild)
214         return 0;
215     
216     return axObjectCache()->getOrCreate(lastChild);
217 }
218
219 static inline RenderInline* startOfContinuations(RenderObject* r)
220 {
221     if (r->isInlineElementContinuation())
222         return toRenderInline(r->node()->renderer());
223
224     // Blocks with a previous continuation always have a next continuation
225     if (r->isRenderBlock() && toRenderBlock(r)->inlineElementContinuation())
226         return toRenderInline(toRenderBlock(r)->inlineElementContinuation()->node()->renderer());
227
228     return 0;
229 }
230
231 static inline RenderObject* endOfContinuations(RenderObject* renderer)
232 {
233     RenderObject* prev = renderer;
234     RenderObject* cur = renderer;
235
236     if (!cur->isRenderInline() && !cur->isRenderBlock())
237         return renderer;
238
239     while (cur) {
240         prev = cur;
241         if (cur->isRenderInline()) {
242             cur = toRenderInline(cur)->inlineElementContinuation();
243             ASSERT(cur || !toRenderInline(prev)->continuation());
244         } else 
245             cur = toRenderBlock(cur)->inlineElementContinuation();
246     }
247
248     return prev;
249 }
250
251
252 static inline RenderObject* childBeforeConsideringContinuations(RenderInline* r, RenderObject* child)
253 {
254     RenderBoxModelObject* curContainer = r;
255     RenderObject* cur = 0;
256     RenderObject* prev = 0;
257
258     while (curContainer) {
259         if (curContainer->isRenderInline()) {
260             cur = curContainer->firstChild();
261             while (cur) {
262                 if (cur == child)
263                     return prev;
264                 prev = cur;
265                 cur = cur->nextSibling();
266             }
267
268             curContainer = toRenderInline(curContainer)->continuation();
269         } else if (curContainer->isRenderBlock()) {
270             if (curContainer == child)
271                 return prev;
272
273             prev = curContainer;
274             curContainer = toRenderBlock(curContainer)->inlineElementContinuation();
275         }
276     }
277
278     ASSERT_NOT_REACHED();
279
280     return 0;
281 }
282
283 static inline bool firstChildIsInlineContinuation(RenderObject* renderer)
284 {
285     return renderer->firstChild() && renderer->firstChild()->isInlineElementContinuation();
286 }
287
288 AccessibilityObject* AccessibilityRenderObject::previousSibling() const
289 {
290     if (!m_renderer)
291         return 0;
292
293     RenderObject* previousSibling = 0;
294
295     // Case 1: The node is a block and is an inline's continuation. In that case, the inline's
296     // last child is our previous sibling (or further back in the continuation chain)
297     RenderInline* startOfConts;
298     if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer)))
299         previousSibling = childBeforeConsideringContinuations(startOfConts, m_renderer);
300
301     // Case 2: Anonymous block parent of the end of a continuation - skip all the way to before
302     // the parent of the start, since everything in between will be linked up via the continuation.
303     else if (m_renderer->isAnonymousBlock() && firstChildIsInlineContinuation(m_renderer))
304         previousSibling = startOfContinuations(m_renderer->firstChild())->parent()->previousSibling();
305
306     // Case 3: The node has an actual previous sibling
307     else if (RenderObject* ps = m_renderer->previousSibling())
308         previousSibling = ps;
309
310     // Case 4: This node has no previous siblings, but its parent is an inline,
311     // and is another node's inline continutation. Follow the continuation chain.
312     else if (m_renderer->parent()->isRenderInline() && (startOfConts = startOfContinuations(m_renderer->parent())))
313         previousSibling = childBeforeConsideringContinuations(startOfConts, m_renderer->parent()->firstChild());
314
315     if (!previousSibling)
316         return 0;
317     
318     return axObjectCache()->getOrCreate(previousSibling);
319 }
320
321 static inline bool lastChildHasContinuation(RenderObject* renderer)
322 {
323     return renderer->lastChild() && isInlineWithContinuation(renderer->lastChild());
324 }
325
326 AccessibilityObject* AccessibilityRenderObject::nextSibling() const
327 {
328     if (!m_renderer)
329         return 0;
330
331     RenderObject* nextSibling = 0;
332
333     // Case 1: node is a block and has an inline continuation. Next sibling is the inline continuation's
334     // first child.
335     RenderInline* inlineContinuation;
336     if (m_renderer->isRenderBlock() && (inlineContinuation = toRenderBlock(m_renderer)->inlineElementContinuation()))
337         nextSibling = firstChildConsideringContinuation(inlineContinuation);
338
339     // Case 2: Anonymous block parent of the start of a continuation - skip all the way to
340     // after the parent of the end, since everything in between will be linked up via the continuation.
341     else if (m_renderer->isAnonymousBlock() && lastChildHasContinuation(m_renderer))
342         nextSibling = endOfContinuations(m_renderer->lastChild())->parent()->nextSibling();
343
344     // Case 3: node has an actual next sibling
345     else if (RenderObject* ns = m_renderer->nextSibling())
346         nextSibling = ns;
347
348     // Case 4: node is an inline with a continuation. Next sibling is the next sibling of the end 
349     // of the continuation chain.
350     else if (isInlineWithContinuation(m_renderer))
351         nextSibling = endOfContinuations(m_renderer)->nextSibling();
352
353     // Case 5: node has no next sibling, and its parent is an inline with a continuation.
354     else if (isInlineWithContinuation(m_renderer->parent())) {
355         RenderObject* continuation = toRenderInline(m_renderer->parent())->continuation();
356         
357         // Case 5a: continuation is a block - in this case the block itself is the next sibling.
358         if (continuation->isRenderBlock())
359             nextSibling = continuation;
360         // Case 5b: continuation is an inline - in this case the inline's first child is the next sibling
361         else
362             nextSibling = firstChildConsideringContinuation(continuation);
363     }
364
365     if (!nextSibling)
366         return 0;
367     
368     return axObjectCache()->getOrCreate(nextSibling);
369 }
370
371 static RenderBoxModelObject* nextContinuation(RenderObject* renderer)
372 {
373     ASSERT(renderer);
374     if (renderer->isRenderInline() && !renderer->isReplaced())
375         return toRenderInline(renderer)->continuation();
376     if (renderer->isRenderBlock())
377         return toRenderBlock(renderer)->inlineElementContinuation();
378     return 0;
379 }
380     
381 RenderObject* AccessibilityRenderObject::renderParentObject() const
382 {
383     if (!m_renderer)
384         return 0;
385
386     RenderObject* parent = m_renderer->parent();
387
388     // Case 1: node is a block and is an inline's continuation. Parent
389     // is the start of the continuation chain.
390     RenderObject* startOfConts = 0;
391     RenderObject* firstChild = 0;
392     if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer)))
393         parent = startOfConts;
394
395     // Case 2: node's parent is an inline which is some node's continuation; parent is 
396     // the earliest node in the continuation chain.
397     else if (parent && parent->isRenderInline() && (startOfConts = startOfContinuations(parent)))
398         parent = startOfConts;
399     
400     // Case 3: The first sibling is the beginning of a continuation chain. Find the origin of that continuation.
401     else if (parent && (firstChild = parent->firstChild()) && firstChild->node()) {
402         // Get the node's renderer and follow that continuation chain until the first child is found
403         RenderObject* nodeRenderFirstChild = firstChild->node()->renderer();
404         if (nodeRenderFirstChild != firstChild) {
405             for (RenderObject* contsTest = nodeRenderFirstChild; contsTest; contsTest = nextContinuation(contsTest)) {
406                 if (contsTest == firstChild) {
407                     parent = nodeRenderFirstChild->parent();
408                     break;
409                 }
410             }
411         }
412     }
413         
414     return parent;
415 }
416     
417 AccessibilityObject* AccessibilityRenderObject::parentObjectIfExists() const
418 {
419     return axObjectCache()->get(renderParentObject());
420 }
421     
422 AccessibilityObject* AccessibilityRenderObject::parentObject() const
423 {
424     if (!m_renderer)
425         return 0;
426     
427     if (ariaRoleAttribute() == MenuBarRole)
428         return axObjectCache()->getOrCreate(m_renderer->parent());
429
430     // menuButton and its corresponding menu are DOM siblings, but Accessibility needs them to be parent/child
431     if (ariaRoleAttribute() == MenuRole) {
432         AccessibilityObject* parent = menuButtonForMenu();
433         if (parent)
434             return parent;
435     }
436     
437     return axObjectCache()->getOrCreate(renderParentObject());
438 }
439
440 bool AccessibilityRenderObject::isWebArea() const
441 {
442     return roleValue() == WebAreaRole;
443 }
444
445 bool AccessibilityRenderObject::isImageButton() const
446 {
447     return isNativeImage() && roleValue() == ButtonRole;
448 }
449
450 bool AccessibilityRenderObject::isAnchor() const
451 {
452     return !isNativeImage() && isLink();
453 }
454
455 bool AccessibilityRenderObject::isNativeTextControl() const
456 {
457     return m_renderer->isTextControl();
458 }
459     
460 bool AccessibilityRenderObject::isTextControl() const
461 {
462     AccessibilityRole role = roleValue();
463     return role == TextAreaRole || role == TextFieldRole;
464 }
465
466 bool AccessibilityRenderObject::isNativeImage() const
467 {
468     return m_renderer->isBoxModelObject() && toRenderBoxModelObject(m_renderer)->isImage();
469 }    
470     
471 bool AccessibilityRenderObject::isImage() const
472 {
473     return roleValue() == ImageRole;
474 }
475
476 bool AccessibilityRenderObject::isAttachment() const
477 {
478     RenderBoxModelObject* renderer = renderBoxModelObject();
479     if (!renderer)
480         return false;
481     // Widgets are the replaced elements that we represent to AX as attachments
482     bool isWidget = renderer->isWidget();
483     ASSERT(!isWidget || (renderer->isReplaced() && !isImage()));
484     return isWidget && ariaRoleAttribute() == UnknownRole;
485 }
486
487 bool AccessibilityRenderObject::isPasswordField() const
488 {
489     ASSERT(m_renderer);
490     if (!m_renderer->node() || !m_renderer->node()->isHTMLElement())
491         return false;
492     if (ariaRoleAttribute() != UnknownRole)
493         return false;
494
495     InputElement* inputElement = toInputElement(static_cast<Element*>(m_renderer->node()));
496     if (!inputElement)
497         return false;
498
499     return inputElement->isPasswordField();
500 }
501     
502 bool AccessibilityRenderObject::isFileUploadButton() const
503 {
504     if (m_renderer && m_renderer->node() && m_renderer->node()->hasTagName(inputTag)) {
505         HTMLInputElement* input = static_cast<HTMLInputElement*>(m_renderer->node());
506         return input->isFileUpload();
507     }
508     
509     return false;
510 }
511     
512 bool AccessibilityRenderObject::isInputImage() const
513 {
514     Node* elementNode = node();
515     if (roleValue() == ButtonRole && elementNode && elementNode->hasTagName(inputTag)) {
516         HTMLInputElement* input = static_cast<HTMLInputElement*>(elementNode);
517         return input->isImageButton();
518     }
519     
520     return false;
521 }
522
523 bool AccessibilityRenderObject::isProgressIndicator() const
524 {
525     return roleValue() == ProgressIndicatorRole;
526 }
527
528 bool AccessibilityRenderObject::isSlider() const
529 {
530     return roleValue() == SliderRole;
531 }
532
533 bool AccessibilityRenderObject::isMenuRelated() const
534 {
535     AccessibilityRole role = roleValue();
536     return role == MenuRole 
537         || role == MenuBarRole
538         || role == MenuButtonRole
539         || role == MenuItemRole;
540 }    
541
542 bool AccessibilityRenderObject::isMenu() const
543 {
544     return roleValue() == MenuRole;
545 }
546
547 bool AccessibilityRenderObject::isMenuBar() const
548 {
549     return roleValue() == MenuBarRole;
550 }
551
552 bool AccessibilityRenderObject::isMenuButton() const
553 {
554     return roleValue() == MenuButtonRole;
555 }
556
557 bool AccessibilityRenderObject::isMenuItem() const
558 {
559     return roleValue() == MenuItemRole;
560 }
561      
562 bool AccessibilityRenderObject::isPressed() const
563 {
564     ASSERT(m_renderer);
565     if (roleValue() != ButtonRole)
566         return false;
567
568     Node* node = m_renderer->node();
569     if (!node)
570         return false;
571
572     // If this is an ARIA button, check the aria-pressed attribute rather than node()->active()
573     if (ariaRoleAttribute() == ButtonRole) {
574         if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true"))
575             return true;
576         return false;
577     }
578
579     return node->active();
580 }
581
582 bool AccessibilityRenderObject::isIndeterminate() const
583 {
584     ASSERT(m_renderer);
585     if (!m_renderer->node() || !m_renderer->node()->isElementNode())
586         return false;
587
588     InputElement* inputElement = toInputElement(static_cast<Element*>(m_renderer->node()));
589     if (!inputElement)
590         return false;
591
592     return inputElement->isIndeterminate();
593 }
594
595 bool AccessibilityRenderObject::isNativeCheckboxOrRadio() const
596 {
597     Node* elementNode = node();
598     if (elementNode && elementNode->isElementNode()) {
599         InputElement* input = toInputElement(static_cast<Element*>(elementNode));
600         if (input)
601             return input->isCheckbox() || input->isRadioButton();
602     }
603     
604     return false;
605 }
606     
607 bool AccessibilityRenderObject::isChecked() const
608 {
609     ASSERT(m_renderer);
610     if (!m_renderer->node() || !m_renderer->node()->isElementNode())
611         return false;
612
613     // First test for native checkedness semantics
614     InputElement* inputElement = toInputElement(static_cast<Element*>(m_renderer->node()));
615     if (inputElement)
616         return inputElement->isChecked();
617
618     // Else, if this is an ARIA checkbox or radio, respect the aria-checked attribute
619     AccessibilityRole ariaRole = ariaRoleAttribute();
620     if (ariaRole == RadioButtonRole || ariaRole == CheckBoxRole) {
621         if (equalIgnoringCase(getAttribute(aria_checkedAttr), "true"))
622             return true;
623         return false;
624     }
625
626     // Otherwise it's not checked
627     return false;
628 }
629
630 bool AccessibilityRenderObject::isHovered() const
631 {
632     ASSERT(m_renderer);
633     return m_renderer->node() && m_renderer->node()->hovered();
634 }
635
636 bool AccessibilityRenderObject::isMultiSelectable() const
637 {
638     ASSERT(m_renderer);
639     
640     const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr);
641     if (equalIgnoringCase(ariaMultiSelectable, "true"))
642         return true;
643     if (equalIgnoringCase(ariaMultiSelectable, "false"))
644         return false;
645     
646     if (!m_renderer->isBoxModelObject() || !toRenderBoxModelObject(m_renderer)->isListBox())
647         return false;
648     return m_renderer->node() && static_cast<HTMLSelectElement*>(m_renderer->node())->multiple();
649 }
650     
651 bool AccessibilityRenderObject::isReadOnly() const
652 {
653     ASSERT(m_renderer);
654     
655     if (isWebArea()) {
656         Document* document = m_renderer->document();
657         if (!document)
658             return true;
659         
660         HTMLElement* body = document->body();
661         if (body && body->isContentEditable())
662             return false;
663         
664         Frame* frame = document->frame();
665         if (!frame)
666             return true;
667         
668         return !frame->isContentEditable();
669     }
670
671     if (m_renderer->isBoxModelObject()) {
672         RenderBoxModelObject* box = toRenderBoxModelObject(m_renderer);
673         if (box->isTextField())
674             return static_cast<HTMLInputElement*>(box->node())->readOnly();
675         if (box->isTextArea())
676             return static_cast<HTMLTextAreaElement*>(box->node())->readOnly();
677     }
678
679     return !m_renderer->node() || !m_renderer->node()->isContentEditable();
680 }
681
682 bool AccessibilityRenderObject::isOffScreen() const
683 {
684     ASSERT(m_renderer);
685     IntRect contentRect = m_renderer->absoluteClippedOverflowRect();
686     FrameView* view = m_renderer->frame()->view();
687     FloatRect viewRect = view->visibleContentRect();
688     viewRect.intersect(contentRect);
689     return viewRect.isEmpty();
690 }
691
692 int AccessibilityRenderObject::headingLevel() const
693 {
694     // headings can be in block flow and non-block flow
695     Node* element = node();
696     if (!element)
697         return 0;
698
699     if (ariaRoleAttribute() == HeadingRole)
700         return getAttribute(aria_levelAttr).toInt();
701
702     if (element->hasTagName(h1Tag))
703         return 1;
704     
705     if (element->hasTagName(h2Tag))
706         return 2;
707     
708     if (element->hasTagName(h3Tag))
709         return 3;
710     
711     if (element->hasTagName(h4Tag))
712         return 4;
713     
714     if (element->hasTagName(h5Tag))
715         return 5;
716     
717     if (element->hasTagName(h6Tag))
718         return 6;
719     
720     return 0;
721 }
722
723 bool AccessibilityRenderObject::isHeading() const
724 {
725     return roleValue() == HeadingRole;
726 }
727     
728 bool AccessibilityRenderObject::isLink() const
729 {
730     return roleValue() == WebCoreLinkRole;
731 }    
732     
733 bool AccessibilityRenderObject::isControl() const
734 {
735     if (!m_renderer)
736         return false;
737     
738     Node* node = m_renderer->node();
739     return node && ((node->isElementNode() && static_cast<Element*>(node)->isFormControlElement())
740                     || AccessibilityObject::isARIAControl(ariaRoleAttribute()));
741 }
742
743 bool AccessibilityRenderObject::isFieldset() const
744 {
745     RenderBoxModelObject* renderer = renderBoxModelObject();
746     if (!renderer)
747         return false;
748     return renderer->isFieldset();
749 }
750   
751 bool AccessibilityRenderObject::isGroup() const
752 {
753     return roleValue() == GroupRole;
754 }
755     
756 AccessibilityObject* AccessibilityRenderObject::selectedRadioButton()
757 {
758     if (!isRadioGroup())
759         return 0;
760     
761     // Find the child radio button that is selected (ie. the intValue == 1).
762     int count = m_children.size();
763     for (int i = 0; i < count; ++i) {
764         AccessibilityObject* object = m_children[i].get();
765         if (object->roleValue() == RadioButtonRole && object->checkboxOrRadioValue() == ButtonStateOn)
766             return object;
767     }
768     return 0;
769 }
770
771 AccessibilityObject* AccessibilityRenderObject::selectedTabItem()
772 {
773     if (!isTabList())
774         return 0;
775     
776     // Find the child tab item that is selected (ie. the intValue == 1).
777     AccessibilityObject::AccessibilityChildrenVector tabs;
778     tabChildren(tabs);
779     
780     int count = tabs.size();
781     for (int i = 0; i < count; ++i) {
782         AccessibilityObject* object = m_children[i].get();
783         if (object->isTabItem() && object->isChecked())
784             return object;
785     }
786     return 0;
787 }
788
789 Element* AccessibilityRenderObject::anchorElement() const
790 {
791     if (!m_renderer)
792         return 0;
793     
794     AXObjectCache* cache = axObjectCache();
795     RenderObject* currRenderer;
796     
797     // Search up the render tree for a RenderObject with a DOM node.  Defer to an earlier continuation, though.
798     for (currRenderer = m_renderer; currRenderer && !currRenderer->node(); currRenderer = currRenderer->parent()) {
799         if (currRenderer->isAnonymousBlock()) {
800             RenderObject* continuation = toRenderBlock(currRenderer)->continuation();
801             if (continuation)
802                 return cache->getOrCreate(continuation)->anchorElement();
803         }
804     }
805     
806     // bail if none found
807     if (!currRenderer)
808         return 0;
809     
810     // search up the DOM tree for an anchor element
811     // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
812     Node* node = currRenderer->node();
813     for ( ; node; node = node->parentNode()) {
814         if (node->hasTagName(aTag) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
815             return static_cast<Element*>(node);
816     }
817     
818     return 0;
819 }
820
821 Element* AccessibilityRenderObject::actionElement() const
822 {
823     if (!m_renderer)
824         return 0;
825     
826     Node* node = m_renderer->node();
827     if (node) {
828         if (node->hasTagName(inputTag)) {
829             HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
830             if (!input->disabled() && (isCheckboxOrRadio() || input->isTextButton()))
831                 return input;
832         } else if (node->hasTagName(buttonTag))
833             return static_cast<Element*>(node);
834     }
835
836     if (isFileUploadButton())
837         return static_cast<Element*>(m_renderer->node());
838             
839     if (AccessibilityObject::isARIAInput(ariaRoleAttribute()))
840         return static_cast<Element*>(m_renderer->node());
841
842     if (isImageButton())
843         return static_cast<Element*>(m_renderer->node());
844     
845     if (m_renderer->isBoxModelObject() && toRenderBoxModelObject(m_renderer)->isMenuList())
846         return static_cast<Element*>(m_renderer->node());
847
848     AccessibilityRole role = roleValue();
849     if (role == ButtonRole || role == PopUpButtonRole)
850         return static_cast<Element*>(m_renderer->node()); 
851     
852     Element* elt = anchorElement();
853     if (!elt)
854         elt = mouseButtonListener();
855     return elt;
856 }
857
858 Element* AccessibilityRenderObject::mouseButtonListener() const
859 {
860     Node* node = m_renderer->node();
861     if (!node)
862         return 0;
863     
864     // check if our parent is a mouse button listener
865     while (node && !node->isElementNode())
866         node = node->parent();
867
868     if (!node)
869         return 0;
870
871     // FIXME: Do the continuation search like anchorElement does
872     for (Element* element = static_cast<Element*>(node); element; element = element->parentElement()) {
873         if (element->getAttributeEventListener(eventNames().clickEvent) || element->getAttributeEventListener(eventNames().mousedownEvent) || element->getAttributeEventListener(eventNames().mouseupEvent))
874             return element;
875     }
876
877     return 0;
878 }
879
880 void AccessibilityRenderObject::increment()
881 {
882     if (roleValue() != SliderRole)
883         return;
884     
885     changeValueByPercent(5);
886 }
887
888 void AccessibilityRenderObject::decrement()
889 {
890     if (roleValue() != SliderRole)
891         return;
892     
893     changeValueByPercent(-5);
894 }
895
896 static Element* siblingWithAriaRole(String role, Node* node)
897 {
898     Node* sibling = node->parent()->firstChild();
899     while (sibling) {
900         if (sibling->isElementNode()) {
901             const AtomicString& siblingAriaRole = static_cast<Element*>(sibling)->getAttribute(roleAttr);
902             if (equalIgnoringCase(siblingAriaRole, role))
903                 return static_cast<Element*>(sibling);
904         }
905         sibling = sibling->nextSibling();
906     }
907     
908     return 0;
909 }
910
911 Element* AccessibilityRenderObject::menuElementForMenuButton() const
912 {
913     if (ariaRoleAttribute() != MenuButtonRole)
914         return 0;
915
916     return siblingWithAriaRole("menu", renderer()->node());
917 }
918
919 AccessibilityObject* AccessibilityRenderObject::menuForMenuButton() const
920 {
921     Element* menu = menuElementForMenuButton();
922     if (menu && menu->renderer())
923         return axObjectCache()->getOrCreate(menu->renderer());
924     return 0;
925 }
926
927 Element* AccessibilityRenderObject::menuItemElementForMenu() const
928 {
929     if (ariaRoleAttribute() != MenuRole)
930         return 0;
931     
932     return siblingWithAriaRole("menuitem", renderer()->node());    
933 }
934
935 AccessibilityObject* AccessibilityRenderObject::menuButtonForMenu() const
936 {
937     Element* menuItem = menuItemElementForMenu();
938
939     if (menuItem && menuItem->renderer()) {
940         // ARIA just has generic menu items.  AppKit needs to know if this is a top level items like MenuBarButton or MenuBarItem
941         AccessibilityObject* menuItemAX = axObjectCache()->getOrCreate(menuItem->renderer());
942         if (menuItemAX->isMenuButton())
943             return menuItemAX;
944     }
945     return 0;
946 }
947
948 String AccessibilityRenderObject::helpText() const
949 {
950     if (!m_renderer)
951         return String();
952     
953     const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
954     if (!ariaHelp.isEmpty())
955         return ariaHelp;
956     
957     for (RenderObject* curr = m_renderer; curr; curr = curr->parent()) {
958         if (curr->node() && curr->node()->isHTMLElement()) {
959             const AtomicString& summary = static_cast<Element*>(curr->node())->getAttribute(summaryAttr);
960             if (!summary.isEmpty())
961                 return summary;
962             const AtomicString& title = static_cast<Element*>(curr->node())->getAttribute(titleAttr);
963             if (!title.isEmpty())
964                 return title;
965         }
966         
967         // Only take help text from an ancestor element if its a group or an unknown role. If help was 
968         // added to those kinds of elements, it is likely it was meant for a child element.
969         AccessibilityObject* axObj = axObjectCache()->getOrCreate(curr);
970         if (axObj) {
971             AccessibilityRole role = axObj->roleValue();
972             if (role != GroupRole && role != UnknownRole)
973                 break;
974         }
975     }
976     
977     return String();
978 }
979     
980 unsigned AccessibilityRenderObject::hierarchicalLevel() const
981 {
982     if (!m_renderer)
983         return 0;
984
985     Node* node = m_renderer->node();
986     if (!node || !node->isElementNode())
987         return 0;
988     Element* element = static_cast<Element*>(node);
989     String ariaLevel = element->getAttribute(aria_levelAttr);
990     if (!ariaLevel.isEmpty())
991         return ariaLevel.toInt();
992     
993     // Only tree item will calculate its level through the DOM currently.
994     if (roleValue() != TreeItemRole)
995         return 0;
996     
997     // Hierarchy leveling starts at 0.
998     // We measure tree hierarchy by the number of groups that the item is within.
999     unsigned level = 0;
1000     AccessibilityObject* parent = parentObject();
1001     while (parent) {
1002         AccessibilityRole parentRole = parent->roleValue();
1003         if (parentRole == GroupRole)
1004             level++;
1005         else if (parentRole == TreeRole)
1006             break;
1007         
1008         parent = parent->parentObject();
1009     }
1010     
1011     return level;
1012 }
1013
1014 String AccessibilityRenderObject::textUnderElement() const
1015 {
1016     if (!m_renderer)
1017         return String();
1018     
1019     if (isFileUploadButton())
1020         return toRenderFileUploadControl(m_renderer)->buttonValue();
1021     
1022     Node* node = m_renderer->node();
1023     if (node) {
1024         if (Frame* frame = node->document()->frame()) {
1025             // catch stale WebCoreAXObject (see <rdar://problem/3960196>)
1026             if (frame->document() != node->document())
1027                 return String();
1028             return plainText(rangeOfContents(node).get(), TextIteratorIgnoresStyleVisibility);
1029         }
1030     }
1031     
1032     // Sometimes text fragments don't have Node's associated with them (like when
1033     // CSS content is used to insert text).
1034     if (m_renderer->isText()) {
1035         RenderText* renderTextObject = toRenderText(m_renderer);
1036         if (renderTextObject->isTextFragment())
1037             return String(static_cast<RenderTextFragment*>(m_renderer)->contentString());
1038     }
1039     
1040     // return the null string for anonymous text because it is non-trivial to get
1041     // the actual text and, so far, that is not needed
1042     return String();
1043 }
1044
1045 Node* AccessibilityRenderObject::node() const
1046
1047     return m_renderer ? m_renderer->node() : 0; 
1048 }    
1049     
1050 AccessibilityButtonState AccessibilityRenderObject::checkboxOrRadioValue() const
1051 {
1052     if (isNativeCheckboxOrRadio())
1053         return isChecked() ? ButtonStateOn : ButtonStateOff;
1054     
1055     return AccessibilityObject::checkboxOrRadioValue();
1056 }
1057
1058 String AccessibilityRenderObject::valueDescription() const
1059 {
1060     // Only sliders and progress bars support value descriptions currently.
1061     if (!isProgressIndicator() && !isSlider())
1062         return String();
1063     
1064     return getAttribute(aria_valuetextAttr).string();
1065 }
1066     
1067 float AccessibilityRenderObject::valueForRange() const
1068 {
1069     if (!isProgressIndicator() && !isSlider() && !isScrollbar())
1070         return 0.0f;
1071
1072     return getAttribute(aria_valuenowAttr).toFloat();
1073 }
1074
1075 float AccessibilityRenderObject::maxValueForRange() const
1076 {
1077     if (!isProgressIndicator() && !isSlider())
1078         return 0.0f;
1079
1080     return getAttribute(aria_valuemaxAttr).toFloat();
1081 }
1082
1083 float AccessibilityRenderObject::minValueForRange() const
1084 {
1085     if (!isProgressIndicator() && !isSlider())
1086         return 0.0f;
1087
1088     return getAttribute(aria_valueminAttr).toFloat();
1089 }
1090
1091 String AccessibilityRenderObject::stringValue() const
1092 {
1093     if (!m_renderer || isPasswordField())
1094         return String();
1095
1096     RenderBoxModelObject* cssBox = renderBoxModelObject();
1097
1098     if (ariaRoleAttribute() == StaticTextRole) {
1099         String staticText = text();
1100         if (!staticText.length())
1101             staticText = textUnderElement();
1102         return staticText;
1103     }
1104         
1105     if (m_renderer->isText())
1106         return textUnderElement();
1107     
1108     if (cssBox && cssBox->isMenuList()) {
1109         // RenderMenuList will go straight to the text() of its selected item.
1110         // This has to be overriden in the case where the selected item has an aria label
1111         SelectElement* selectNode = toSelectElement(static_cast<Element*>(m_renderer->node()));
1112         int selectedIndex = selectNode->selectedIndex();
1113         const Vector<Element*> listItems = selectNode->listItems();
1114         
1115         Element* selectedOption = 0;
1116         if (selectedIndex >= 0 && selectedIndex < (int)listItems.size()) 
1117             selectedOption = listItems[selectedIndex];
1118         if (selectedOption) {
1119             String overridenDescription = selectedOption->getAttribute(aria_labelAttr);
1120             if (!overridenDescription.isNull())
1121                 return overridenDescription;
1122         }
1123         
1124         return toRenderMenuList(m_renderer)->text();
1125     }
1126     
1127     if (m_renderer->isListMarker())
1128         return toRenderListMarker(m_renderer)->text();
1129     
1130     if (cssBox && cssBox->isRenderButton())
1131         return toRenderButton(m_renderer)->text();
1132
1133     if (isWebArea()) {
1134         if (m_renderer->frame())
1135             return String();
1136         
1137         // FIXME: should use startOfDocument and endOfDocument (or rangeForDocument?) here
1138         VisiblePosition startVisiblePosition = m_renderer->positionForCoordinates(0, 0);
1139         VisiblePosition endVisiblePosition = m_renderer->positionForCoordinates(INT_MAX, INT_MAX);
1140         if (startVisiblePosition.isNull() || endVisiblePosition.isNull())
1141             return String();
1142         
1143         return plainText(makeRange(startVisiblePosition, endVisiblePosition).get(), TextIteratorIgnoresStyleVisibility);
1144     }
1145     
1146     if (isTextControl())
1147         return text();
1148     
1149     if (isFileUploadButton())
1150         return toRenderFileUploadControl(m_renderer)->fileTextValue();
1151     
1152     // FIXME: We might need to implement a value here for more types
1153     // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
1154     // this would require subclassing or making accessibilityAttributeNames do something other than return a
1155     // single static array.
1156     return String();
1157 }
1158
1159 // This function implements the ARIA accessible name as described by the Mozilla
1160 // ARIA Implementer's Guide.
1161 static String accessibleNameForNode(Node* node)
1162 {
1163     if (node->isTextNode())
1164         return static_cast<Text*>(node)->data();
1165
1166     if (node->hasTagName(inputTag))
1167         return static_cast<HTMLInputElement*>(node)->value();
1168
1169     if (node->isHTMLElement()) {
1170         const AtomicString& alt = static_cast<HTMLElement*>(node)->getAttribute(altAttr);
1171         if (!alt.isEmpty())
1172             return alt;
1173     }
1174
1175     return String();
1176 }
1177
1178 String AccessibilityRenderObject::accessibilityDescriptionForElements(Vector<Element*> &elements) const
1179 {
1180     Vector<UChar> ariaLabel;
1181     unsigned size = elements.size();
1182     for (unsigned i = 0; i < size; ++i) {
1183         Element* idElement = elements[i];
1184         
1185         String nameFragment = accessibleNameForNode(idElement);
1186         ariaLabel.append(nameFragment.characters(), nameFragment.length());
1187         for (Node* n = idElement->firstChild(); n; n = n->traverseNextNode(idElement)) {
1188             nameFragment = accessibleNameForNode(n);
1189             ariaLabel.append(nameFragment.characters(), nameFragment.length());
1190         }
1191             
1192         if (i != size - 1)
1193             ariaLabel.append(' ');
1194     }
1195     return String::adopt(ariaLabel);
1196 }
1197
1198     
1199 void AccessibilityRenderObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
1200 {
1201     Node* node = m_renderer->node();
1202     if (!node || !node->isElementNode())
1203         return;
1204
1205     Document* document = m_renderer->document();
1206     if (!document)
1207         return;
1208     
1209     String idList = getAttribute(attribute).string();
1210     if (idList.isEmpty())
1211         return;
1212     
1213     idList.replace('\n', ' ');
1214     Vector<String> idVector;
1215     idList.split(' ', idVector);
1216     
1217     unsigned size = idVector.size();
1218     for (unsigned i = 0; i < size; ++i) {
1219         String idName = idVector[i];
1220         Element* idElement = document->getElementById(idName);
1221         if (idElement)
1222             elements.append(idElement);
1223     }
1224 }
1225     
1226 void AccessibilityRenderObject::ariaLabeledByElements(Vector<Element*>& elements) const
1227 {
1228     elementsFromAttribute(elements, aria_labeledbyAttr);
1229     if (!elements.size())
1230         elementsFromAttribute(elements, aria_labelledbyAttr);
1231 }
1232    
1233 String AccessibilityRenderObject::ariaLabeledByAttribute() const
1234 {
1235     Vector<Element*> elements;
1236     ariaLabeledByElements(elements);
1237     
1238     return accessibilityDescriptionForElements(elements);
1239 }
1240
1241 static HTMLLabelElement* labelForElement(Element* element)
1242 {
1243     RefPtr<NodeList> list = element->document()->getElementsByTagName("label");
1244     unsigned len = list->length();
1245     for (unsigned i = 0; i < len; i++) {
1246         if (list->item(i)->hasTagName(labelTag)) {
1247             HTMLLabelElement* label = static_cast<HTMLLabelElement*>(list->item(i));
1248             if (label->control() == element)
1249                 return label;
1250         }
1251     }
1252     
1253     return 0;
1254 }
1255     
1256 HTMLLabelElement* AccessibilityRenderObject::labelElementContainer() const
1257 {
1258     if (!m_renderer)
1259         return 0;
1260
1261     // the control element should not be considered part of the label
1262     if (isControl())
1263         return 0;
1264     
1265     // find if this has a parent that is a label
1266     for (Node* parentNode = m_renderer->node(); parentNode; parentNode = parentNode->parentNode()) {
1267         if (parentNode->hasTagName(labelTag))
1268             return static_cast<HTMLLabelElement*>(parentNode);
1269     }
1270     
1271     return 0;
1272 }
1273
1274 String AccessibilityRenderObject::title() const
1275 {
1276     AccessibilityRole ariaRole = ariaRoleAttribute();
1277     
1278     if (!m_renderer)
1279         return String();
1280
1281     Node* node = m_renderer->node();
1282     if (!node)
1283         return String();
1284     
1285     String ariaLabel = ariaLabeledByAttribute();
1286     if (!ariaLabel.isEmpty())
1287         return ariaLabel;
1288     
1289     const AtomicString& title = getAttribute(titleAttr);
1290     if (!title.isEmpty())
1291         return title;
1292     
1293     bool isInputTag = node->hasTagName(inputTag);
1294     if (isInputTag) {
1295         HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
1296         if (input->isTextButton())
1297             return input->value();
1298     }
1299     
1300     if (isInputTag || AccessibilityObject::isARIAInput(ariaRole) || isControl()) {
1301         HTMLLabelElement* label = labelForElement(static_cast<Element*>(node));
1302         if (label && !titleUIElement())
1303             return label->innerText();
1304     }
1305     
1306     if (roleValue() == ButtonRole
1307         || ariaRole == ListBoxOptionRole
1308         || ariaRole == MenuItemRole
1309         || ariaRole == MenuButtonRole
1310         || ariaRole == RadioButtonRole
1311         || ariaRole == CheckBoxRole
1312         || ariaRole == TabRole
1313         || ariaRole == PopUpButtonRole
1314         || isHeading()
1315         || isLink())
1316         return textUnderElement();
1317     
1318     return String();
1319 }
1320
1321 String AccessibilityRenderObject::ariaDescribedByAttribute() const
1322 {
1323     Vector<Element*> elements;
1324     elementsFromAttribute(elements, aria_describedbyAttr);
1325     
1326     return accessibilityDescriptionForElements(elements);
1327 }
1328
1329 String AccessibilityRenderObject::accessibilityDescription() const
1330 {
1331     if (!m_renderer)
1332         return String();
1333
1334     const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
1335     if (!ariaLabel.isEmpty())
1336         return ariaLabel;
1337     
1338     String ariaDescription = ariaDescribedByAttribute();
1339     if (!ariaDescription.isEmpty())
1340         return ariaDescription;
1341     
1342     if (isImage() || isInputImage() || isNativeImage()) {
1343         Node* node = m_renderer->node();
1344         if (node && node->isHTMLElement()) {
1345             const AtomicString& alt = static_cast<HTMLElement*>(node)->getAttribute(altAttr);
1346             if (alt.isEmpty())
1347                 return String();
1348             return alt;
1349         }
1350     }
1351     
1352     if (isWebArea()) {
1353         Document* document = m_renderer->document();
1354         
1355         // Check if the HTML element has an aria-label for the webpage.
1356         Element* documentElement = document->documentElement();
1357         if (documentElement) {
1358             const AtomicString& ariaLabel = documentElement->getAttribute(aria_labelAttr);
1359             if (!ariaLabel.isEmpty())
1360                 return ariaLabel;
1361         }
1362         
1363         Node* owner = document->ownerElement();
1364         if (owner) {
1365             if (owner->hasTagName(frameTag) || owner->hasTagName(iframeTag)) {
1366                 const AtomicString& title = static_cast<HTMLFrameElementBase*>(owner)->getAttribute(titleAttr);
1367                 if (!title.isEmpty())
1368                     return title;
1369                 return static_cast<HTMLFrameElementBase*>(owner)->getAttribute(nameAttr);
1370             }
1371             if (owner->isHTMLElement())
1372                 return static_cast<HTMLElement*>(owner)->getAttribute(nameAttr);
1373         }
1374         owner = document->body();
1375         if (owner && owner->isHTMLElement())
1376             return static_cast<HTMLElement*>(owner)->getAttribute(nameAttr);
1377     }
1378
1379     return String();
1380 }
1381
1382 IntRect AccessibilityRenderObject::boundingBoxRect() const
1383 {
1384     RenderObject* obj = m_renderer;
1385     
1386     if (!obj)
1387         return IntRect();
1388     
1389     if (obj->node()) // If we are a continuation, we want to make sure to use the primary renderer.
1390         obj = obj->node()->renderer();
1391     
1392     // absoluteFocusRingQuads will query the hierarchy below this element, which for large webpages can be very slow.
1393     // For a web area, which will have the most elements of any element, absoluteQuads should be used.
1394     Vector<FloatQuad> quads;
1395     if (obj->isText())
1396         toRenderText(obj)->absoluteQuads(quads, RenderText::ClipToEllipsis);
1397     else if (isWebArea())
1398         obj->absoluteQuads(quads);
1399     else
1400         obj->absoluteFocusRingQuads(quads);
1401     const size_t n = quads.size();
1402     if (!n)
1403         return IntRect();
1404
1405     IntRect result;
1406     for (size_t i = 0; i < n; ++i) {
1407         IntRect r = quads[i].enclosingBoundingBox();
1408         if (!r.isEmpty()) {
1409             if (obj->style()->hasAppearance())
1410                 obj->theme()->adjustRepaintRect(obj, r);
1411             result.unite(r);
1412         }
1413     }
1414     return result;
1415 }
1416     
1417 IntRect AccessibilityRenderObject::checkboxOrRadioRect() const
1418 {
1419     if (!m_renderer)
1420         return IntRect();
1421     
1422     HTMLLabelElement* label = labelForElement(static_cast<Element*>(m_renderer->node()));
1423     if (!label || !label->renderer())
1424         return boundingBoxRect();
1425     
1426     IntRect labelRect = axObjectCache()->getOrCreate(label->renderer())->elementRect();
1427     labelRect.unite(boundingBoxRect());
1428     return labelRect;
1429 }
1430
1431 IntRect AccessibilityRenderObject::elementRect() const
1432 {
1433     // a checkbox or radio button should encompass its label
1434     if (isCheckboxOrRadio())
1435         return checkboxOrRadioRect();
1436     
1437     return boundingBoxRect();
1438 }
1439
1440 IntSize AccessibilityRenderObject::size() const
1441 {
1442     IntRect rect = elementRect();
1443     return rect.size();
1444 }
1445
1446 IntPoint AccessibilityRenderObject::clickPoint() const
1447 {
1448     // use the default position unless this is an editable web area, in which case we use the selection bounds.
1449     if (!isWebArea() || isReadOnly())
1450         return AccessibilityObject::clickPoint();
1451     
1452     VisibleSelection visSelection = selection();
1453     VisiblePositionRange range = VisiblePositionRange(visSelection.visibleStart(), visSelection.visibleEnd());
1454     IntRect bounds = boundsForVisiblePositionRange(range);
1455 #if PLATFORM(MAC)
1456     bounds.setLocation(m_renderer->document()->view()->screenToContents(bounds.location()));
1457 #endif        
1458     return IntPoint(bounds.x() + (bounds.width() / 2), bounds.y() - (bounds.height() / 2));
1459 }
1460     
1461 AccessibilityObject* AccessibilityRenderObject::internalLinkElement() const
1462 {
1463     Element* element = anchorElement();
1464     if (!element)
1465         return 0;
1466     
1467     // Right now, we do not support ARIA links as internal link elements
1468     if (!element->hasTagName(aTag))
1469         return 0;
1470     HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(element);
1471     
1472     KURL linkURL = anchor->href();
1473     String fragmentIdentifier = linkURL.fragmentIdentifier();
1474     if (fragmentIdentifier.isEmpty())
1475         return 0;
1476     
1477     // check if URL is the same as current URL
1478     KURL documentURL = m_renderer->document()->url();
1479     if (!equalIgnoringFragmentIdentifier(documentURL, linkURL))
1480         return 0;
1481     
1482     Node* linkedNode = m_renderer->document()->findAnchor(fragmentIdentifier);
1483     if (!linkedNode)
1484         return 0;
1485     
1486     // The element we find may not be accessible, so find the first accessible object.
1487     return firstAccessibleObjectFromNode(linkedNode);
1488 }
1489
1490 ESpeak AccessibilityRenderObject::speakProperty() const
1491 {
1492     if (!m_renderer)
1493         return AccessibilityObject::speakProperty();
1494     
1495     return m_renderer->style()->speak();
1496 }
1497     
1498 void AccessibilityRenderObject::addRadioButtonGroupMembers(AccessibilityChildrenVector& linkedUIElements) const
1499 {
1500     if (!m_renderer || roleValue() != RadioButtonRole)
1501         return;
1502     
1503     Node* node = m_renderer->node();
1504     if (!node || !node->hasTagName(inputTag))
1505         return;
1506     
1507     HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
1508     // if there's a form, then this is easy
1509     if (input->form()) {
1510         Vector<RefPtr<Node> > formElements;
1511         input->form()->getNamedElements(input->name(), formElements);
1512         
1513         unsigned len = formElements.size();
1514         for (unsigned i = 0; i < len; ++i) {
1515             Node* associateElement = formElements[i].get();
1516             if (AccessibilityObject* object = axObjectCache()->getOrCreate(associateElement->renderer()))
1517                 linkedUIElements.append(object);        
1518         } 
1519     } else {
1520         RefPtr<NodeList> list = node->document()->getElementsByTagName("input");
1521         unsigned len = list->length();
1522         for (unsigned i = 0; i < len; ++i) {
1523             if (list->item(i)->hasTagName(inputTag)) {
1524                 HTMLInputElement* associateElement = static_cast<HTMLInputElement*>(list->item(i));
1525                 if (associateElement->isRadioButton() && associateElement->name() == input->name()) {
1526                     if (AccessibilityObject* object = axObjectCache()->getOrCreate(associateElement->renderer()))
1527                         linkedUIElements.append(object);
1528                 }
1529             }
1530         }
1531     }
1532 }
1533     
1534 // linked ui elements could be all the related radio buttons in a group
1535 // or an internal anchor connection
1536 void AccessibilityRenderObject::linkedUIElements(AccessibilityChildrenVector& linkedUIElements) const
1537 {
1538     ariaFlowToElements(linkedUIElements);
1539
1540     if (isAnchor()) {
1541         AccessibilityObject* linkedAXElement = internalLinkElement();
1542         if (linkedAXElement)
1543             linkedUIElements.append(linkedAXElement);
1544     }
1545
1546     if (roleValue() == RadioButtonRole)
1547         addRadioButtonGroupMembers(linkedUIElements);
1548 }
1549
1550 bool AccessibilityRenderObject::hasTextAlternative() const
1551 {
1552     // ARIA: section 2A, bullet #3 says if aria-labeledby or aria-label appears, it should
1553     // override the "label" element association.
1554     if (!ariaLabeledByAttribute().isEmpty() || !getAttribute(aria_labelAttr).isEmpty())
1555         return true;
1556         
1557     return false;   
1558 }
1559     
1560 bool AccessibilityRenderObject::ariaHasPopup() const
1561 {
1562     return elementAttributeValue(aria_haspopupAttr);
1563 }
1564     
1565 bool AccessibilityRenderObject::supportsARIAFlowTo() const
1566 {
1567     return !getAttribute(aria_flowtoAttr).isEmpty();
1568 }
1569     
1570 void AccessibilityRenderObject::ariaFlowToElements(AccessibilityChildrenVector& flowTo) const
1571 {
1572     Vector<Element*> elements;
1573     elementsFromAttribute(elements, aria_flowtoAttr);
1574     
1575     AXObjectCache* cache = axObjectCache();
1576     unsigned count = elements.size();
1577     for (unsigned k = 0; k < count; ++k) {
1578         Element* element = elements[k];
1579         AccessibilityObject* flowToElement = cache->getOrCreate(element->renderer());
1580         if (flowToElement)
1581             flowTo.append(flowToElement);
1582     }
1583         
1584 }
1585     
1586 bool AccessibilityRenderObject::supportsARIADropping() const 
1587 {
1588     const AtomicString& dropEffect = getAttribute(aria_dropeffectAttr);
1589     return !dropEffect.isEmpty();
1590 }
1591
1592 bool AccessibilityRenderObject::supportsARIADragging() const
1593 {
1594     const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
1595     return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false");   
1596 }
1597
1598 bool AccessibilityRenderObject::isARIAGrabbed()
1599 {
1600     return elementAttributeValue(aria_grabbedAttr);
1601 }
1602
1603 void AccessibilityRenderObject::setARIAGrabbed(bool grabbed)
1604 {
1605     setElementAttributeValue(aria_grabbedAttr, grabbed);
1606 }
1607
1608 void AccessibilityRenderObject::determineARIADropEffects(Vector<String>& effects)
1609 {
1610     const AtomicString& dropEffects = getAttribute(aria_dropeffectAttr);
1611     if (dropEffects.isEmpty()) {
1612         effects.clear();
1613         return;
1614     }
1615     
1616     String dropEffectsString = dropEffects.string();
1617     dropEffectsString.replace('\n', ' ');
1618     dropEffectsString.split(' ', effects);
1619 }
1620     
1621 bool AccessibilityRenderObject::exposesTitleUIElement() const
1622 {
1623     if (!isControl())
1624         return false;
1625
1626     // checkbox or radio buttons don't expose the title ui element unless it has a title already
1627     if (isCheckboxOrRadio() && getAttribute(titleAttr).isEmpty())
1628         return false;
1629     
1630     if (hasTextAlternative())
1631         return false;
1632     
1633     return true;
1634 }
1635     
1636 AccessibilityObject* AccessibilityRenderObject::titleUIElement() const
1637 {
1638     if (!m_renderer)
1639         return 0;
1640     
1641     // if isFieldset is true, the renderer is guaranteed to be a RenderFieldset
1642     if (isFieldset())
1643         return axObjectCache()->getOrCreate(toRenderFieldset(m_renderer)->findLegend());
1644     
1645     if (!exposesTitleUIElement())
1646         return 0;
1647     
1648     Node* element = m_renderer->node();
1649     HTMLLabelElement* label = labelForElement(static_cast<Element*>(element));
1650     if (label && label->renderer())
1651         return axObjectCache()->getOrCreate(label->renderer());
1652
1653     return 0;   
1654 }
1655     
1656 bool AccessibilityRenderObject::ariaIsHidden() const
1657 {
1658     if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "true"))
1659         return true;
1660     
1661     // aria-hidden hides this object and any children
1662     AccessibilityObject* object = parentObject();
1663     while (object) {
1664         if (object->isAccessibilityRenderObject() && equalIgnoringCase(static_cast<AccessibilityRenderObject*>(object)->getAttribute(aria_hiddenAttr), "true"))
1665             return true;
1666         object = object->parentObject();
1667     }
1668
1669     return false;
1670 }
1671
1672 bool AccessibilityRenderObject::isDescendantOfBarrenParent() const
1673 {
1674     for (AccessibilityObject* object = parentObject(); object; object = object->parentObject()) {
1675         if (!object->canHaveChildren())
1676             return true;
1677     }
1678     
1679     return false;
1680 }
1681     
1682 bool AccessibilityRenderObject::isAllowedChildOfTree() const
1683 {
1684     // Determine if this is in a tree. If so, we apply special behavior to make it work like an AXOutline.
1685     AccessibilityObject* axObj = parentObject();
1686     bool isInTree = false;
1687     while (axObj) {
1688         if (axObj->isTree()) {
1689             isInTree = true;
1690             break;
1691         }
1692         axObj = axObj->parentObject();
1693     }
1694     
1695     // If the object is in a tree, only tree items should be exposed (and the children of tree items).
1696     if (isInTree) {
1697         AccessibilityRole role = roleValue();
1698         if (role != TreeItemRole && role != StaticTextRole)
1699             return false;
1700     }
1701     return true;
1702 }
1703     
1704 AccessibilityObjectInclusion AccessibilityRenderObject::accessibilityIsIgnoredBase() const
1705 {
1706     // The following cases can apply to any element that's a subclass of AccessibilityRenderObject.
1707     
1708     // Ignore invisible elements.
1709     if (!m_renderer || m_renderer->style()->visibility() != VISIBLE)
1710         return IgnoreObject;
1711
1712     // Anything marked as aria-hidden or a child of something aria-hidden must be hidden.
1713     if (ariaIsHidden())
1714         return IgnoreObject;
1715     
1716     // Anything that is a presentational role must be hidden.
1717     if (isPresentationalChildOfAriaRole())
1718         return IgnoreObject;
1719
1720     // Allow the platform to make a decision.
1721     AccessibilityObjectInclusion decision = accessibilityPlatformIncludesObject();
1722     if (decision == IncludeObject)
1723         return IncludeObject;
1724     if (decision == IgnoreObject)
1725         return IgnoreObject;
1726         
1727     return DefaultBehavior;
1728 }  
1729  
1730 bool AccessibilityRenderObject::accessibilityIsIgnored() const
1731 {
1732     // Check first if any of the common reasons cause this element to be ignored.
1733     // Then process other use cases that need to be applied to all the various roles
1734     // that AccessibilityRenderObjects take on.
1735     AccessibilityObjectInclusion decision = accessibilityIsIgnoredBase();
1736     if (decision == IncludeObject)
1737         return false;
1738     if (decision == IgnoreObject)
1739         return true;
1740     
1741     // If this element is within a parent that cannot have children, it should not be exposed.
1742     if (isDescendantOfBarrenParent())
1743         return true;    
1744     
1745     if (roleValue() == IgnoredRole)
1746         return true;
1747     
1748     if (roleValue() == PresentationalRole || inheritsPresentationalRole())
1749         return true;
1750     
1751     // An ARIA tree can only have tree items and static text as children.
1752     if (!isAllowedChildOfTree())
1753         return true;
1754
1755     // ignore popup menu items because AppKit does
1756     for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
1757         if (parent->isBoxModelObject() && toRenderBoxModelObject(parent)->isMenuList())
1758             return true;
1759     }
1760
1761     // find out if this element is inside of a label element.
1762     // if so, it may be ignored because it's the label for a checkbox or radio button
1763     AccessibilityObject* controlObject = correspondingControlForLabelElement();
1764     if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
1765         return true;
1766         
1767     // NOTE: BRs always have text boxes now, so the text box check here can be removed
1768     if (m_renderer->isText()) {
1769         // static text beneath MenuItems and MenuButtons are just reported along with the menu item, so it's ignored on an individual level
1770         if (parentObjectUnignored()->ariaRoleAttribute() == MenuItemRole
1771             || parentObjectUnignored()->ariaRoleAttribute() == MenuButtonRole)
1772             return true;
1773         RenderText* renderText = toRenderText(m_renderer);
1774         if (m_renderer->isBR() || !renderText->firstTextBox())
1775             return true;
1776         
1777         // text elements that are just empty whitespace should not be returned
1778         return renderText->text()->containsOnlyWhitespace();
1779     }
1780     
1781     if (isHeading())
1782         return false;
1783     
1784     if (isLink())
1785         return false;
1786     
1787     // all controls are accessible
1788     if (isControl())
1789         return false;
1790     
1791     if (ariaRoleAttribute() != UnknownRole)
1792         return false;
1793
1794     if (!helpText().isEmpty())
1795         return false;
1796     
1797     // don't ignore labels, because they serve as TitleUIElements
1798     Node* node = m_renderer->node();
1799     if (node && node->hasTagName(labelTag))
1800         return false;
1801     
1802     // Anything that is content editable should not be ignored.
1803     // However, one cannot just call node->isContentEditable() since that will ask if its parents
1804     // are also editable. Only the top level content editable region should be exposed.
1805     if (node && node->isElementNode()) {
1806         Element* element = static_cast<Element*>(node);
1807         const AtomicString& contentEditable = element->getAttribute(contenteditableAttr);
1808         if (equalIgnoringCase(contentEditable, "true"))
1809             return false;
1810     }
1811     
1812     // if this element has aria attributes on it, it should not be ignored.
1813     if (supportsARIAAttributes())
1814         return false;
1815     
1816     if (m_renderer->isBlockFlow() && m_renderer->childrenInline())
1817         return !toRenderBlock(m_renderer)->firstLineBox() && !mouseButtonListener();
1818     
1819     // ignore images seemingly used as spacers
1820     if (isImage()) {
1821         if (node && node->isElementNode()) {
1822             Element* elt = static_cast<Element*>(node);
1823             const AtomicString& alt = elt->getAttribute(altAttr);
1824             // don't ignore an image that has an alt tag
1825             if (!alt.isEmpty())
1826                 return false;
1827             // informal standard is to ignore images with zero-length alt strings
1828             if (!alt.isNull())
1829                 return true;
1830         }
1831         
1832         if (node && node->hasTagName(canvasTag)) {
1833             RenderHTMLCanvas* canvas = toRenderHTMLCanvas(m_renderer);
1834             if (canvas->height() <= 1 || canvas->width() <= 1)
1835                 return true;
1836             return false;
1837         }
1838         
1839         if (isNativeImage()) {
1840             // check for one-dimensional image
1841             RenderImage* image = toRenderImage(m_renderer);
1842             if (image->height() <= 1 || image->width() <= 1)
1843                 return true;
1844             
1845             // check whether rendered image was stretched from one-dimensional file image
1846             if (image->cachedImage()) {
1847                 IntSize imageSize = image->cachedImage()->imageSize(image->view()->zoomFactor());
1848                 return imageSize.height() <= 1 || imageSize.width() <= 1;
1849             }
1850         }
1851         return false;
1852     }
1853     
1854     // make a platform-specific decision
1855     if (isAttachment())
1856         return accessibilityIgnoreAttachment();
1857     
1858     return !m_renderer->isListMarker() && !isWebArea();
1859 }
1860
1861 bool AccessibilityRenderObject::isLoaded() const
1862 {
1863     return !m_renderer->document()->parser();
1864 }
1865
1866 double AccessibilityRenderObject::estimatedLoadingProgress() const
1867 {
1868     if (!m_renderer)
1869         return 0;
1870     
1871     if (isLoaded())
1872         return 1.0;
1873     
1874     Page* page = m_renderer->document()->page();
1875     if (!page)
1876         return 0;
1877     
1878     return page->progress()->estimatedProgress();
1879 }
1880     
1881 int AccessibilityRenderObject::layoutCount() const
1882 {
1883     if (!m_renderer->isRenderView())
1884         return 0;
1885     return toRenderView(m_renderer)->frameView()->layoutCount();
1886 }
1887
1888 String AccessibilityRenderObject::text() const
1889 {
1890     // If this is a user defined static text, use the accessible name computation.
1891     if (ariaRoleAttribute() == StaticTextRole)
1892         return accessibilityDescription();
1893     
1894     if (!isTextControl() || isPasswordField())
1895         return String();
1896     
1897     if (isNativeTextControl())
1898         return toRenderTextControl(m_renderer)->text();
1899     
1900     Node* node = m_renderer->node();
1901     if (!node)
1902         return String();
1903     if (!node->isElementNode())
1904         return String();
1905     
1906     return static_cast<Element*>(node)->innerText();
1907 }
1908     
1909 int AccessibilityRenderObject::textLength() const
1910 {
1911     ASSERT(isTextControl());
1912     
1913     if (isPasswordField())
1914         return -1; // need to return something distinct from 0
1915     
1916     return text().length();
1917 }
1918
1919 PlainTextRange AccessibilityRenderObject::ariaSelectedTextRange() const
1920 {
1921     Node* node = m_renderer->node();
1922     if (!node)
1923         return PlainTextRange();
1924     
1925     ExceptionCode ec = 0;
1926     VisibleSelection visibleSelection = selection();
1927     RefPtr<Range> currentSelectionRange = visibleSelection.toNormalizedRange();
1928     if (!currentSelectionRange || !currentSelectionRange->intersectsNode(node, ec))
1929         return PlainTextRange();
1930     
1931     int start = indexForVisiblePosition(visibleSelection.start());
1932     int end = indexForVisiblePosition(visibleSelection.end());
1933     
1934     return PlainTextRange(start, end - start);
1935 }
1936
1937 String AccessibilityRenderObject::selectedText() const
1938 {
1939     ASSERT(isTextControl());
1940     
1941     if (isPasswordField())
1942         return String(); // need to return something distinct from empty string
1943     
1944     if (isNativeTextControl()) {
1945         RenderTextControl* textControl = toRenderTextControl(m_renderer);
1946         return textControl->text().substring(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
1947     }
1948     
1949     if (ariaRoleAttribute() == UnknownRole)
1950         return String();
1951     
1952     return doAXStringForRange(ariaSelectedTextRange());
1953 }
1954
1955 const AtomicString& AccessibilityRenderObject::accessKey() const
1956 {
1957     Node* node = m_renderer->node();
1958     if (!node)
1959         return nullAtom;
1960     if (!node->isElementNode())
1961         return nullAtom;
1962     return static_cast<Element*>(node)->getAttribute(accesskeyAttr);
1963 }
1964
1965 VisibleSelection AccessibilityRenderObject::selection() const
1966 {
1967     return m_renderer->frame()->selection()->selection();
1968 }
1969
1970 PlainTextRange AccessibilityRenderObject::selectedTextRange() const
1971 {
1972     ASSERT(isTextControl());
1973     
1974     if (isPasswordField())
1975         return PlainTextRange();
1976     
1977     AccessibilityRole ariaRole = ariaRoleAttribute();
1978     if (isNativeTextControl() && ariaRole == UnknownRole) {
1979         RenderTextControl* textControl = toRenderTextControl(m_renderer);
1980         return PlainTextRange(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
1981     }
1982     
1983     if (ariaRole == UnknownRole)
1984         return PlainTextRange();
1985     
1986     return ariaSelectedTextRange();
1987 }
1988
1989 void AccessibilityRenderObject::setSelectedTextRange(const PlainTextRange& range)
1990 {
1991     if (isNativeTextControl()) {
1992         setSelectionRange(m_renderer->node(), range.start, range.start + range.length);
1993         return;
1994     }
1995
1996     Document* document = m_renderer->document();
1997     if (!document)
1998         return;
1999     Frame* frame = document->frame();
2000     if (!frame)
2001         return;
2002     Node* node = m_renderer->node();
2003     frame->selection()->setSelection(VisibleSelection(Position(node, range.start),
2004         Position(node, range.start + range.length), DOWNSTREAM));
2005 }
2006
2007 KURL AccessibilityRenderObject::url() const
2008 {
2009     if (isAnchor() && m_renderer->node()->hasTagName(aTag)) {
2010         if (HTMLAnchorElement* anchor = static_cast<HTMLAnchorElement*>(anchorElement()))
2011             return anchor->href();
2012     }
2013     
2014     if (isWebArea())
2015         return m_renderer->document()->url();
2016     
2017     if (isImage() && m_renderer->node() && m_renderer->node()->hasTagName(imgTag))
2018         return static_cast<HTMLImageElement*>(m_renderer->node())->src();
2019     
2020     if (isInputImage())
2021         return static_cast<HTMLInputElement*>(m_renderer->node())->src();
2022     
2023     return KURL();
2024 }
2025
2026 bool AccessibilityRenderObject::isVisited() const
2027 {
2028     // FIXME: Is it a privacy violation to expose visited information to accessibility APIs?
2029     return m_renderer->style()->isLink() && m_renderer->style()->insideLink() == InsideVisitedLink;
2030 }
2031     
2032 bool AccessibilityRenderObject::isExpanded() const
2033 {
2034     if (equalIgnoringCase(getAttribute(aria_expandedAttr), "true"))
2035         return true;
2036     
2037     return false;  
2038 }
2039
2040 void AccessibilityRenderObject::setElementAttributeValue(const QualifiedName& attributeName, bool value)
2041 {
2042     if (!m_renderer)
2043         return;
2044     
2045     Node* node = m_renderer->node();
2046     if (!node || !node->isElementNode())
2047         return;
2048     
2049     Element* element = static_cast<Element*>(node);
2050     element->setAttribute(attributeName, (value) ? "true" : "false");        
2051 }
2052     
2053 bool AccessibilityRenderObject::elementAttributeValue(const QualifiedName& attributeName) const
2054 {
2055     if (!m_renderer)
2056         return false;
2057     
2058     return equalIgnoringCase(getAttribute(attributeName), "true");
2059 }
2060     
2061 void AccessibilityRenderObject::setIsExpanded(bool isExpanded)
2062 {
2063     // Combo boxes, tree items and rows can be expanded (in different ways on different platforms).
2064     // That action translates into setting the aria-expanded attribute to true.
2065     AccessibilityRole role = roleValue();
2066     switch (role) {
2067     case ComboBoxRole:
2068     case TreeItemRole:
2069     case RowRole:
2070         setElementAttributeValue(aria_expandedAttr, isExpanded);
2071         break;
2072     default:
2073         break;
2074     }
2075 }
2076     
2077 bool AccessibilityRenderObject::isRequired() const
2078 {
2079     if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
2080         return true;
2081     
2082     return false;
2083 }
2084
2085 bool AccessibilityRenderObject::isSelected() const
2086 {
2087     if (!m_renderer)
2088         return false;
2089     
2090     Node* node = m_renderer->node();
2091     if (!node)
2092         return false;
2093     
2094     const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
2095     if (equalIgnoringCase(ariaSelected, "true"))
2096         return true;    
2097     
2098     if (isTabItem() && isTabItemSelected())
2099         return true;
2100
2101     return false;
2102 }
2103
2104 bool AccessibilityRenderObject::isTabItemSelected() const
2105 {
2106     if (!isTabItem() || !m_renderer)
2107         return false;
2108     
2109     Node* node = m_renderer->node();
2110     if (!node || !node->isElementNode())
2111         return false;
2112     
2113     // The ARIA spec says a tab item can also be selected if it is aria-labeled by a tabpanel
2114     // that has keyboard focus inside of it, or if a tabpanel in its aria-controls list has KB
2115     // focus inside of it.
2116     AccessibilityObject* focusedElement = focusedUIElement();
2117     if (!focusedElement)
2118         return false;
2119     
2120     Vector<Element*> elements;
2121     elementsFromAttribute(elements, aria_controlsAttr);
2122     
2123     unsigned count = elements.size();
2124     for (unsigned k = 0; k < count; ++k) {
2125         Element* element = elements[k];
2126         AccessibilityObject* tabPanel = axObjectCache()->getOrCreate(element->renderer());
2127
2128         // A tab item should only control tab panels.
2129         if (!tabPanel || tabPanel->roleValue() != TabPanelRole)
2130             continue;
2131         
2132         AccessibilityObject* checkFocusElement = focusedElement;
2133         // Check if the focused element is a descendant of the element controlled by the tab item.
2134         while (checkFocusElement) {
2135             if (tabPanel == checkFocusElement)
2136                 return true;
2137             checkFocusElement = checkFocusElement->parentObject();
2138         }
2139     }
2140     
2141     return false;
2142 }
2143     
2144 bool AccessibilityRenderObject::isFocused() const
2145 {
2146     if (!m_renderer)
2147         return false;
2148     
2149     Document* document = m_renderer->document();
2150     if (!document)
2151         return false;
2152     
2153     Node* focusedNode = document->focusedNode();
2154     if (!focusedNode)
2155         return false;
2156     
2157     // A web area is represented by the Document node in the DOM tree, which isn't focusable.
2158     // Check instead if the frame's selection controller is focused
2159     if (focusedNode == m_renderer->node()
2160         || (roleValue() == WebAreaRole && document->frame()->selection()->isFocusedAndActive()))
2161         return true;
2162     
2163     return false;
2164 }
2165
2166 void AccessibilityRenderObject::setFocused(bool on)
2167 {
2168     if (!canSetFocusAttribute())
2169         return;
2170     
2171     if (!on)
2172         m_renderer->document()->setFocusedNode(0);
2173     else {
2174         if (m_renderer->node()->isElementNode())
2175             static_cast<Element*>(m_renderer->node())->focus();
2176         else
2177             m_renderer->document()->setFocusedNode(m_renderer->node());
2178     }
2179 }
2180
2181 void AccessibilityRenderObject::changeValueByPercent(float percentChange)
2182 {
2183     float range = maxValueForRange() - minValueForRange();
2184     float value = valueForRange();
2185     
2186     value += range * (percentChange / 100);
2187     setValue(String::number(value));
2188     
2189     axObjectCache()->postNotification(m_renderer, AXObjectCache::AXValueChanged, true);
2190 }
2191     
2192 void AccessibilityRenderObject::setSelected(bool enabled)
2193 {
2194     setElementAttributeValue(aria_selectedAttr, enabled);
2195 }
2196
2197 void AccessibilityRenderObject::setSelectedRows(AccessibilityChildrenVector& selectedRows)
2198 {
2199     // Setting selected only makes sense in trees and tables (and tree-tables).
2200     AccessibilityRole role = roleValue();
2201     if (role != TreeRole && role != TreeGridRole && role != TableRole)
2202         return;
2203     
2204     bool isMulti = isMultiSelectable();
2205     unsigned count = selectedRows.size();
2206     if (count > 1 && !isMulti)
2207         count = 1;
2208     
2209     for (unsigned k = 0; k < count; ++k)
2210         selectedRows[k]->setSelected(true);
2211 }
2212     
2213 void AccessibilityRenderObject::setValue(const String& string)
2214 {
2215     if (!m_renderer || !m_renderer->node() || !m_renderer->node()->isElementNode())
2216         return;
2217     Element* element = static_cast<Element*>(m_renderer->node());
2218
2219     if (roleValue() == SliderRole)
2220         element->setAttribute(aria_valuenowAttr, string);
2221
2222     if (!m_renderer->isBoxModelObject())
2223         return;
2224     RenderBoxModelObject* renderer = toRenderBoxModelObject(m_renderer);
2225
2226     // FIXME: Do we want to do anything here for ARIA textboxes?
2227     if (renderer->isTextField()) {
2228         // FIXME: This is not safe!  Other elements could have a TextField renderer.
2229         static_cast<HTMLInputElement*>(element)->setValue(string);
2230     } else if (renderer->isTextArea()) {
2231         // FIXME: This is not safe!  Other elements could have a TextArea renderer.
2232         static_cast<HTMLTextAreaElement*>(element)->setValue(string);
2233     }
2234 }
2235
2236 void AccessibilityRenderObject::ariaOwnsElements(AccessibilityChildrenVector& axObjects) const
2237 {
2238     Vector<Element*> elements;
2239     elementsFromAttribute(elements, aria_ownsAttr);
2240     
2241     unsigned count = elements.size();
2242     for (unsigned k = 0; k < count; ++k) {
2243         RenderObject* render = elements[k]->renderer();
2244         AccessibilityObject* obj = axObjectCache()->getOrCreate(render);
2245         if (obj)
2246             axObjects.append(obj);
2247     }
2248 }
2249
2250 bool AccessibilityRenderObject::supportsARIAOwns() const
2251 {
2252     if (!m_renderer)
2253         return false;
2254     const AtomicString& ariaOwns = getAttribute(aria_ownsAttr);
2255
2256     return !ariaOwns.isEmpty();
2257 }
2258     
2259 bool AccessibilityRenderObject::isEnabled() const
2260 {
2261     ASSERT(m_renderer);
2262     
2263     if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
2264         return false;
2265     
2266     Node* node = m_renderer->node();
2267     if (!node || !node->isElementNode())
2268         return true;
2269
2270     return static_cast<Element*>(node)->isEnabledFormControl();
2271 }
2272
2273 RenderView* AccessibilityRenderObject::topRenderer() const
2274 {
2275     return m_renderer->document()->topDocument()->renderView();
2276 }
2277
2278 Document* AccessibilityRenderObject::document() const
2279 {
2280     if (!m_renderer)
2281         return 0;
2282     return m_renderer->document();
2283 }
2284
2285 FrameView* AccessibilityRenderObject::topDocumentFrameView() const
2286 {
2287     return topRenderer()->view()->frameView();
2288 }
2289
2290 Widget* AccessibilityRenderObject::widget() const
2291 {
2292     if (!m_renderer->isBoxModelObject() || !toRenderBoxModelObject(m_renderer)->isWidget())
2293         return 0;
2294     return toRenderWidget(m_renderer)->widget();
2295 }
2296
2297 AXObjectCache* AccessibilityRenderObject::axObjectCache() const
2298 {
2299     ASSERT(m_renderer);
2300     return m_renderer->document()->axObjectCache();
2301 }
2302
2303 AccessibilityObject* AccessibilityRenderObject::accessibilityParentForImageMap(HTMLMapElement* map) const
2304 {
2305     // find an image that is using this map
2306     if (!map)
2307         return 0;
2308
2309     HTMLImageElement* imageElement = map->imageElement();
2310     if (!imageElement)
2311         return 0;
2312     
2313     return axObjectCache()->getOrCreate(imageElement->renderer());
2314 }
2315     
2316 void AccessibilityRenderObject::getDocumentLinks(AccessibilityChildrenVector& result)
2317 {
2318     Document* document = m_renderer->document();
2319     RefPtr<HTMLCollection> coll = document->links();
2320     Node* curr = coll->firstItem();
2321     while (curr) {
2322         RenderObject* obj = curr->renderer();
2323         if (obj) {
2324             RefPtr<AccessibilityObject> axobj = document->axObjectCache()->getOrCreate(obj);
2325             ASSERT(axobj);
2326             if (!axobj->accessibilityIsIgnored() && axobj->isLink())
2327                 result.append(axobj);
2328         } else {
2329             Node* parent = curr->parent();
2330             if (parent && curr->hasTagName(areaTag) && parent->hasTagName(mapTag)) {
2331                 AccessibilityImageMapLink* areaObject = static_cast<AccessibilityImageMapLink*>(axObjectCache()->getOrCreate(ImageMapLinkRole));
2332                 areaObject->setHTMLAreaElement(static_cast<HTMLAreaElement*>(curr));
2333                 areaObject->setHTMLMapElement(static_cast<HTMLMapElement*>(parent));
2334                 areaObject->setParent(accessibilityParentForImageMap(static_cast<HTMLMapElement*>(parent)));
2335
2336                 result.append(areaObject);
2337             }
2338         }
2339         curr = coll->nextItem();
2340     }
2341 }
2342
2343 FrameView* AccessibilityRenderObject::documentFrameView() const 
2344
2345     if (!m_renderer || !m_renderer->document()) 
2346         return 0; 
2347
2348     // this is the RenderObject's Document's Frame's FrameView 
2349     return m_renderer->document()->view();
2350 }
2351
2352 Widget* AccessibilityRenderObject::widgetForAttachmentView() const
2353 {
2354     if (!isAttachment())
2355         return 0;
2356     return toRenderWidget(m_renderer)->widget();
2357 }
2358
2359 FrameView* AccessibilityRenderObject::frameViewIfRenderView() const
2360 {
2361     if (!m_renderer->isRenderView())
2362         return 0;
2363     // this is the RenderObject's Document's renderer's FrameView
2364     return m_renderer->view()->frameView();
2365 }
2366
2367 // This function is like a cross-platform version of - (WebCoreTextMarkerRange*)textMarkerRange. It returns
2368 // a Range that we can convert to a WebCoreTextMarkerRange in the Obj-C file
2369 VisiblePositionRange AccessibilityRenderObject::visiblePositionRange() const
2370 {
2371     if (!m_renderer)
2372         return VisiblePositionRange();
2373     
2374     // construct VisiblePositions for start and end
2375     Node* node = m_renderer->node();
2376     if (!node)
2377         return VisiblePositionRange();
2378
2379     VisiblePosition startPos = firstDeepEditingPositionForNode(node);
2380     VisiblePosition endPos = lastDeepEditingPositionForNode(node);
2381
2382     // the VisiblePositions are equal for nodes like buttons, so adjust for that
2383     // FIXME: Really?  [button, 0] and [button, 1] are distinct (before and after the button)
2384     // I expect this code is only hit for things like empty divs?  In which case I don't think
2385     // the behavior is correct here -- eseidel
2386     if (startPos == endPos) {
2387         endPos = endPos.next();
2388         if (endPos.isNull())
2389             endPos = startPos;
2390     }
2391
2392     return VisiblePositionRange(startPos, endPos);
2393 }
2394
2395 VisiblePositionRange AccessibilityRenderObject::visiblePositionRangeForLine(unsigned lineCount) const
2396 {
2397     if (!lineCount || !m_renderer)
2398         return VisiblePositionRange();
2399     
2400     // iterate over the lines
2401     // FIXME: this is wrong when lineNumber is lineCount+1,  because nextLinePosition takes you to the
2402     // last offset of the last line
2403     VisiblePosition visiblePos = m_renderer->document()->renderer()->positionForCoordinates(0, 0);
2404     VisiblePosition savedVisiblePos;
2405     while (--lineCount) {
2406         savedVisiblePos = visiblePos;
2407         visiblePos = nextLinePosition(visiblePos, 0);
2408         if (visiblePos.isNull() || visiblePos == savedVisiblePos)
2409             return VisiblePositionRange();
2410     }
2411     
2412     // make a caret selection for the marker position, then extend it to the line
2413     // NOTE: ignores results of sel.modify because it returns false when
2414     // starting at an empty line.  The resulting selection in that case
2415     // will be a caret at visiblePos.
2416     SelectionController selection;
2417     selection.setSelection(VisibleSelection(visiblePos));
2418     selection.modify(SelectionController::AlterationExtend, SelectionController::DirectionRight, LineBoundary);
2419     
2420     return VisiblePositionRange(selection.selection().visibleStart(), selection.selection().visibleEnd());
2421 }
2422     
2423 VisiblePosition AccessibilityRenderObject::visiblePositionForIndex(int index) const
2424 {
2425     if (!m_renderer)
2426         return VisiblePosition();
2427     
2428     if (isNativeTextControl())
2429         return toRenderTextControl(m_renderer)->visiblePositionForIndex(index);
2430
2431     if (!allowsTextRanges() && !m_renderer->isText())
2432         return VisiblePosition();
2433     
2434     Node* node = m_renderer->node();
2435     if (!node)
2436         return VisiblePosition();
2437     
2438     if (index <= 0)
2439         return VisiblePosition(node, 0, DOWNSTREAM);
2440     
2441     ExceptionCode ec = 0;
2442     RefPtr<Range> range = Range::create(m_renderer->document());
2443     range->selectNodeContents(node, ec);
2444     CharacterIterator it(range.get());
2445     it.advance(index - 1);
2446     return VisiblePosition(it.range()->endContainer(ec), it.range()->endOffset(ec), UPSTREAM);
2447 }
2448     
2449 int AccessibilityRenderObject::indexForVisiblePosition(const VisiblePosition& pos) const
2450 {
2451     if (isNativeTextControl())
2452         return toRenderTextControl(m_renderer)->indexForVisiblePosition(pos);
2453     
2454     if (!isTextControl())
2455         return 0;
2456     
2457     Node* node = m_renderer->node();
2458     if (!node)
2459         return 0;
2460     
2461     Position indexPosition = pos.deepEquivalent();
2462     if (!indexPosition.node() || indexPosition.node()->rootEditableElement() != node)
2463         return 0;
2464     
2465     ExceptionCode ec = 0;
2466     RefPtr<Range> range = Range::create(m_renderer->document());
2467     range->setStart(node, 0, ec);
2468     range->setEnd(indexPosition.node(), indexPosition.deprecatedEditingOffset(), ec);
2469     return TextIterator::rangeLength(range.get());
2470 }
2471
2472 IntRect AccessibilityRenderObject::boundsForVisiblePositionRange(const VisiblePositionRange& visiblePositionRange) const
2473 {
2474     if (visiblePositionRange.isNull())
2475         return IntRect();
2476     
2477     // Create a mutable VisiblePositionRange.
2478     VisiblePositionRange range(visiblePositionRange);
2479     IntRect rect1 = range.start.absoluteCaretBounds();
2480     IntRect rect2 = range.end.absoluteCaretBounds();
2481     
2482     // 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
2483     if (rect2.y() != rect1.y()) {
2484         VisiblePosition endOfFirstLine = endOfLine(range.start);
2485         if (range.start == endOfFirstLine) {
2486             range.start.setAffinity(DOWNSTREAM);
2487             rect1 = range.start.absoluteCaretBounds();
2488         }
2489         if (range.end == endOfFirstLine) {
2490             range.end.setAffinity(UPSTREAM);
2491             rect2 = range.end.absoluteCaretBounds();
2492         }
2493     }
2494     
2495     IntRect ourrect = rect1;
2496     ourrect.unite(rect2);
2497     
2498     // if the rectangle spans lines and contains multiple text chars, use the range's bounding box intead
2499     if (rect1.bottom() != rect2.bottom()) {
2500         RefPtr<Range> dataRange = makeRange(range.start, range.end);
2501         IntRect boundingBox = dataRange->boundingBox();
2502         String rangeString = plainText(dataRange.get());
2503         if (rangeString.length() > 1 && !boundingBox.isEmpty())
2504             ourrect = boundingBox;
2505     }
2506     
2507 #if PLATFORM(MAC)
2508     return m_renderer->document()->view()->contentsToScreen(ourrect);
2509 #else
2510     return ourrect;
2511 #endif
2512 }
2513     
2514 void AccessibilityRenderObject::setSelectedVisiblePositionRange(const VisiblePositionRange& range) const
2515 {
2516     if (range.start.isNull() || range.end.isNull())
2517         return;
2518     
2519     // make selection and tell the document to use it. if it's zero length, then move to that position
2520     if (range.start == range.end)
2521         m_renderer->frame()->selection()->moveTo(range.start, true);
2522     else {
2523         VisibleSelection newSelection = VisibleSelection(range.start, range.end);
2524         m_renderer->frame()->selection()->setSelection(newSelection);
2525     }    
2526 }
2527
2528 VisiblePosition AccessibilityRenderObject::visiblePositionForPoint(const IntPoint& point) const
2529 {
2530     if (!m_renderer)
2531         return VisiblePosition();
2532     
2533     // convert absolute point to view coordinates
2534     FrameView* frameView = m_renderer->document()->topDocument()->renderer()->view()->frameView();
2535     RenderView* renderView = topRenderer();
2536     Node* innerNode = 0;
2537     
2538     // locate the node containing the point
2539     IntPoint pointResult;
2540     while (1) {
2541         IntPoint ourpoint;
2542 #if PLATFORM(MAC)
2543         ourpoint = frameView->screenToContents(point);
2544 #else
2545         ourpoint = point;
2546 #endif
2547         HitTestRequest request(HitTestRequest::ReadOnly |
2548                                HitTestRequest::Active);
2549         HitTestResult result(ourpoint);
2550         renderView->layer()->hitTest(request, result);
2551         innerNode = result.innerNode();
2552         if (!innerNode)
2553             return VisiblePosition();
2554         
2555         RenderObject* renderer = innerNode->renderer();
2556         if (!renderer)
2557             return VisiblePosition();
2558         
2559         pointResult = result.localPoint();
2560
2561         // done if hit something other than a widget
2562         if (!renderer->isWidget())
2563             break;
2564
2565         // descend into widget (FRAME, IFRAME, OBJECT...)
2566         Widget* widget = toRenderWidget(renderer)->widget();
2567         if (!widget || !widget->isFrameView())
2568             break;
2569         Frame* frame = static_cast<FrameView*>(widget)->frame();
2570         if (!frame)
2571             break;
2572         renderView = frame->document()->renderView();
2573         frameView = static_cast<FrameView*>(widget);
2574     }
2575     
2576     return innerNode->renderer()->positionForPoint(pointResult);
2577 }
2578
2579 // NOTE: Consider providing this utility method as AX API
2580 VisiblePosition AccessibilityRenderObject::visiblePositionForIndex(unsigned indexValue, bool lastIndexOK) const
2581 {
2582     if (!isTextControl())
2583         return VisiblePosition();
2584     
2585     // lastIndexOK specifies whether the position after the last character is acceptable
2586     if (indexValue >= text().length()) {
2587         if (!lastIndexOK || indexValue > text().length())
2588             return VisiblePosition();
2589     }
2590     VisiblePosition position = visiblePositionForIndex(indexValue);
2591     position.setAffinity(DOWNSTREAM);
2592     return position;
2593 }
2594
2595 // NOTE: Consider providing this utility method as AX API
2596 int AccessibilityRenderObject::index(const VisiblePosition& position) const
2597 {
2598     if (!isTextControl())
2599         return -1;
2600     
2601     Node* node = position.deepEquivalent().node();
2602     if (!node)
2603         return -1;
2604     
2605     for (RenderObject* renderer = node->renderer(); renderer && renderer->node(); renderer = renderer->parent()) {
2606         if (renderer == m_renderer)
2607             return indexForVisiblePosition(position);
2608     }
2609     
2610     return -1;
2611 }
2612
2613 // Given a line number, the range of characters of the text associated with this accessibility
2614 // object that contains the line number.
2615 PlainTextRange AccessibilityRenderObject::doAXRangeForLine(unsigned lineNumber) const
2616 {
2617     if (!isTextControl())
2618         return PlainTextRange();
2619     
2620     // iterate to the specified line
2621     VisiblePosition visiblePos = visiblePositionForIndex(0);
2622     VisiblePosition savedVisiblePos;
2623     for (unsigned lineCount = lineNumber; lineCount; lineCount -= 1) {
2624         savedVisiblePos = visiblePos;
2625         visiblePos = nextLinePosition(visiblePos, 0);
2626         if (visiblePos.isNull() || visiblePos == savedVisiblePos)
2627             return PlainTextRange();
2628     }
2629
2630     // Get the end of the line based on the starting position.
2631     VisiblePosition endPosition = endOfLine(visiblePos);
2632
2633     int index1 = indexForVisiblePosition(visiblePos);
2634     int index2 = indexForVisiblePosition(endPosition);
2635     
2636     // add one to the end index for a line break not caused by soft line wrap (to match AppKit)
2637     if (endPosition.affinity() == DOWNSTREAM && endPosition.next().isNotNull())
2638         index2 += 1;
2639     
2640     // return nil rather than an zero-length range (to match AppKit)
2641     if (index1 == index2)
2642         return PlainTextRange();
2643     
2644     return PlainTextRange(index1, index2 - index1);
2645 }
2646
2647 // The composed character range in the text associated with this accessibility object that
2648 // is specified by the given index value. This parameterized attribute returns the complete
2649 // range of characters (including surrogate pairs of multi-byte glyphs) at the given index.
2650 PlainTextRange AccessibilityRenderObject::doAXRangeForIndex(unsigned index) const
2651 {
2652     if (!isTextControl())
2653         return PlainTextRange();
2654     
2655     String elementText = text();
2656     if (!elementText.length() || index > elementText.length() - 1)
2657         return PlainTextRange();
2658     
2659     return PlainTextRange(index, 1);
2660 }
2661
2662 // A substring of the text associated with this accessibility object that is
2663 // specified by the given character range.
2664 String AccessibilityRenderObject::doAXStringForRange(const PlainTextRange& range) const
2665 {
2666     if (isPasswordField())
2667         return String();
2668     
2669     if (!range.length)
2670         return String();
2671     
2672     if (!isTextControl())
2673         return String();
2674     
2675     String elementText = text();
2676     if (range.start + range.length > elementText.length())
2677         return String();
2678     
2679     return elementText.substring(range.start, range.length);
2680 }
2681
2682 // The bounding rectangle of the text associated with this accessibility object that is
2683 // specified by the given range. This is the bounding rectangle a sighted user would see
2684 // on the display screen, in pixels.
2685 IntRect AccessibilityRenderObject::doAXBoundsForRange(const PlainTextRange& range) const
2686 {
2687     if (allowsTextRanges())
2688         return boundsForVisiblePositionRange(visiblePositionRangeForRange(range));
2689     return IntRect();
2690 }
2691
2692 AccessibilityObject* AccessibilityRenderObject::accessibilityImageMapHitTest(HTMLAreaElement* area, const IntPoint& point) const
2693 {
2694     if (!area)
2695         return 0;
2696     
2697     HTMLMapElement* map = static_cast<HTMLMapElement*>(area->parent());
2698     AccessibilityObject* parent = accessibilityParentForImageMap(map);
2699     if (!parent)
2700         return 0;
2701     
2702     AccessibilityObject::AccessibilityChildrenVector children = parent->children();
2703     
2704     unsigned count = children.size();
2705     for (unsigned k = 0; k < count; ++k) {
2706         if (children[k]->elementRect().contains(point))
2707             return children[k].get();
2708     }
2709     
2710     return 0;
2711 }
2712     
2713 AccessibilityObject* AccessibilityRenderObject::doAccessibilityHitTest(const IntPoint& point) const
2714 {
2715     if (!m_renderer || !m_renderer->hasLayer())
2716         return 0;
2717     
2718     RenderLayer* layer = toRenderBox(m_renderer)->layer();
2719      
2720     HitTestRequest request(HitTestRequest::ReadOnly |
2721                            HitTestRequest::Active);
2722     HitTestResult hitTestResult = HitTestResult(point);
2723     layer->hitTest(request, hitTestResult);
2724     if (!hitTestResult.innerNode())
2725         return 0;
2726     Node* node = hitTestResult.innerNode()->shadowAncestorNode();
2727
2728     if (node->hasTagName(areaTag)) 
2729         return accessibilityImageMapHitTest(static_cast<HTMLAreaElement*>(node), point);
2730     
2731     if (node->hasTagName(optionTag))
2732         node = static_cast<HTMLOptionElement*>(node)->ownerSelectElement();
2733     
2734     RenderObject* obj = node->renderer();
2735     if (!obj)
2736         return 0;
2737     
2738     AccessibilityObject* result = obj->document()->axObjectCache()->getOrCreate(obj);
2739
2740     if (obj->isBoxModelObject() && toRenderBoxModelObject(obj)->isListBox()) {
2741         // Make sure the children are initialized so that hit testing finds the right element.
2742         AccessibilityListBox* listBox = static_cast<AccessibilityListBox*>(result);
2743         listBox->updateChildrenIfNecessary();
2744         return listBox->doAccessibilityHitTest(point);
2745     }
2746
2747     if (result->accessibilityIsIgnored()) {
2748         // If this element is the label of a control, a hit test should return the control.
2749         AccessibilityObject* controlObject = result->correspondingControlForLabelElement();
2750         if (controlObject && !controlObject->exposesTitleUIElement())
2751             return controlObject;
2752
2753         result = result->parentObjectUnignored();
2754     }
2755
2756     return result;
2757 }
2758
2759 AccessibilityObject* AccessibilityRenderObject::focusedUIElement() const
2760 {
2761     Page* page = m_renderer->document()->page();
2762     if (!page)
2763         return 0;
2764
2765     return AXObjectCache::focusedUIElementForPage(page);
2766 }
2767
2768 bool AccessibilityRenderObject::shouldFocusActiveDescendant() const
2769 {
2770     switch (ariaRoleAttribute()) {
2771     case GroupRole:
2772     case ComboBoxRole:
2773     case ListBoxRole:
2774     case MenuRole:
2775     case MenuBarRole:
2776     case RadioGroupRole:
2777     case RowRole:
2778     case PopUpButtonRole:
2779     case ProgressIndicatorRole:
2780     case ToolbarRole:
2781     case OutlineRole:
2782     case TreeRole:
2783     case GridRole:
2784     /* FIXME: replace these with actual roles when they are added to AccessibilityRole
2785     composite
2786     alert
2787     alertdialog
2788     status
2789     timer
2790     */
2791         return true;
2792     default:
2793         return false;
2794     }
2795 }
2796
2797 AccessibilityObject* AccessibilityRenderObject::activeDescendant() const
2798 {
2799     if (!m_renderer)
2800         return 0;
2801     
2802     if (m_renderer->node() && !m_renderer->node()->isElementNode())
2803         return 0;
2804     Element* element = static_cast<Element*>(m_renderer->node());
2805         
2806     const AtomicString& activeDescendantAttrStr = element->getAttribute(aria_activedescendantAttr);
2807     if (activeDescendantAttrStr.isNull() || activeDescendantAttrStr.isEmpty())
2808         return 0;
2809     
2810     Element* target = document()->getElementById(activeDescendantAttrStr);
2811     if (!target)
2812         return 0;
2813     
2814     AccessibilityObject* obj = axObjectCache()->getOrCreate(target->renderer());
2815     if (obj && obj->isAccessibilityRenderObject())
2816     // an activedescendant is only useful if it has a renderer, because that's what's needed to post the notification
2817         return obj;
2818     return 0;
2819 }
2820
2821 void AccessibilityRenderObject::handleAriaExpandedChanged()
2822 {
2823     // Find if a parent of this object should handle aria-expanded changes.
2824     AccessibilityObject* containerParent = this->parentObject();
2825     while (containerParent) {
2826         bool foundParent = false;
2827         
2828         switch (containerParent->roleValue()) {
2829         case TreeRole:
2830         case TreeGridRole:
2831         case GridRole:
2832         case TableRole:
2833         case BrowserRole:
2834             foundParent = true;
2835             break;
2836         default:
2837             break;
2838         }
2839         
2840         if (foundParent)
2841             break;
2842         
2843         containerParent = containerParent->parentObject();
2844     }
2845     
2846     // Post that the row count changed.
2847     if (containerParent)
2848         axObjectCache()->postNotification(containerParent, document(), AXObjectCache::AXRowCountChanged, true);
2849
2850     // Post that the specific row either collapsed or expanded.
2851     if (roleValue() == RowRole || roleValue() == TreeItemRole)
2852         axObjectCache()->postNotification(this, document(), isExpanded() ? AXObjectCache::AXRowExpanded : AXObjectCache::AXRowCollapsed, true);
2853 }
2854
2855 void AccessibilityRenderObject::handleActiveDescendantChanged()
2856 {
2857     Element* element = static_cast<Element*>(renderer()->node());
2858     if (!element)
2859         return;
2860     Document* doc = renderer()->document();
2861     if (!doc->frame()->selection()->isFocusedAndActive() || doc->focusedNode() != element)
2862         return; 
2863     AccessibilityRenderObject* activedescendant = static_cast<AccessibilityRenderObject*>(activeDescendant());
2864     
2865     if (activedescendant && shouldFocusActiveDescendant())
2866         doc->axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
2867 }
2868
2869 AccessibilityObject* AccessibilityRenderObject::correspondingControlForLabelElement() const
2870 {
2871     HTMLLabelElement* labelElement = labelElementContainer();
2872     if (!labelElement)
2873         return 0;
2874     
2875     HTMLElement* correspondingControl = labelElement->control();
2876     if (!correspondingControl)
2877         return 0;
2878     
2879     return axObjectCache()->getOrCreate(correspondingControl->renderer());     
2880 }
2881
2882 AccessibilityObject* AccessibilityRenderObject::correspondingLabelForControlElement() const
2883 {
2884     if (!m_renderer)
2885         return 0;
2886
2887     Node* node = m_renderer->node();
2888     if (node && node->isHTMLElement()) {
2889         HTMLLabelElement* label = labelForElement(static_cast<Element*>(node));
2890         if (label)
2891             return axObjectCache()->getOrCreate(label->renderer());
2892     }
2893
2894     return 0;
2895 }
2896
2897 bool AccessibilityRenderObject::renderObjectIsObservable(RenderObject* renderer) const
2898 {
2899     // AX clients will listen for AXValueChange on a text control.
2900     if (renderer->isTextControl())
2901         return true;
2902     
2903     // AX clients will listen for AXSelectedChildrenChanged on listboxes.
2904     Node* node = renderer->node();
2905     if (nodeHasRole(node, "listbox") || (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListBox()))
2906         return true;
2907
2908     // Textboxes should send out notifications.
2909     if (nodeHasRole(node, "textbox"))
2910         return true;
2911     
2912     return false;
2913 }
2914     
2915 AccessibilityObject* AccessibilityRenderObject::observableObject() const
2916 {
2917     // Find the object going up the parent chain that is used in accessibility to monitor certain notifications.
2918     for (RenderObject* renderer = m_renderer; renderer && renderer->node(); renderer = renderer->parent()) {
2919         if (renderObjectIsObservable(renderer))
2920             return axObjectCache()->getOrCreate(renderer);
2921     }
2922     
2923     return 0;
2924 }
2925
2926 AccessibilityRole AccessibilityRenderObject::determineAriaRoleAttribute() const
2927 {
2928     const AtomicString& ariaRole = getAttribute(roleAttr);
2929     if (ariaRole.isNull() || ariaRole.isEmpty())
2930         return UnknownRole;
2931     
2932     AccessibilityRole role = ariaRoleToWebCoreRole(ariaRole);
2933
2934     if (role == ButtonRole && ariaHasPopup())
2935         role = PopUpButtonRole;
2936     
2937     if (role)
2938         return role;
2939     // selects and listboxes both have options as child roles, but they map to different roles within WebCore
2940     if (equalIgnoringCase(ariaRole, "option")) {
2941         if (parentObjectUnignored()->ariaRoleAttribute() == MenuRole)
2942             return MenuItemRole;
2943         if (parentObjectUnignored()->ariaRoleAttribute() == ListBoxRole)
2944             return ListBoxOptionRole;
2945     }
2946     // an aria "menuitem" may map to MenuButton or MenuItem depending on its parent
2947     if (equalIgnoringCase(ariaRole, "menuitem")) {
2948         if (parentObjectUnignored()->ariaRoleAttribute() == GroupRole)
2949             return MenuButtonRole;
2950         if (parentObjectUnignored()->ariaRoleAttribute() == MenuRole)
2951             return MenuItemRole;
2952     }
2953     
2954     return UnknownRole;
2955 }
2956
2957 AccessibilityRole AccessibilityRenderObject::ariaRoleAttribute() const
2958 {
2959     return m_ariaRole;
2960 }
2961     
2962 void AccessibilityRenderObject::updateAccessibilityRole()
2963 {
2964     bool ignoredStatus = accessibilityIsIgnored();
2965     m_role = determineAccessibilityRole();
2966     
2967     // The AX hierarchy only needs to be updated if the ignored status of an element has changed.
2968     if (ignoredStatus != accessibilityIsIgnored())
2969         childrenChanged();
2970 }
2971     
2972 AccessibilityRole AccessibilityRenderObject::determineAccessibilityRole()
2973 {
2974     if (!m_renderer)
2975         return UnknownRole;
2976
2977     m_ariaRole = determineAriaRoleAttribute();
2978     
2979     Node* node = m_renderer->node();
2980     AccessibilityRole ariaRole = ariaRoleAttribute();
2981     if (ariaRole != UnknownRole)
2982         return ariaRole;
2983
2984     RenderBoxModelObject* cssBox = renderBoxModelObject();
2985
2986     if (node && node->isLink()) {
2987         if (cssBox && cssBox->isImage())
2988             return ImageMapRole;
2989         return WebCoreLinkRole;
2990     }
2991     if (cssBox && cssBox->isListItem())
2992         return ListItemRole;
2993     if (m_renderer->isListMarker())
2994         return ListMarkerRole;
2995     if (node && node->hasTagName(buttonTag))
2996         return ButtonRole;
2997     if (m_renderer->isText())
2998         return StaticTextRole;
2999     if (cssBox && cssBox->isImage()) {
3000         if (node && node->hasTagName(inputTag))
3001             return ButtonRole;
3002         return ImageRole;
3003     }
3004     if (node && node->hasTagName(canvasTag))
3005         return ImageRole;
3006
3007     if (cssBox && cssBox->isRenderView())
3008         return WebAreaRole;
3009     
3010     if (cssBox && cssBox->isTextField())
3011         return TextFieldRole;
3012     
3013     if (cssBox && cssBox->isTextArea())
3014         return TextAreaRole;
3015
3016     if (node && node->hasTagName(inputTag)) {
3017         HTMLInputElement* input = static_cast<HTMLInputElement*>(node);
3018         if (input->isCheckbox())
3019             return CheckBoxRole;
3020         if (input->isRadioButton())
3021             return RadioButtonRole;
3022         if (input->isTextButton())
3023             return ButtonRole;
3024     }
3025
3026     if (node && node->hasTagName(buttonTag))
3027         return ButtonRole;
3028
3029     if (isFileUploadButton())
3030         return ButtonRole;
3031     
3032     if (cssBox && cssBox->isMenuList())
3033         return PopUpButtonRole;
3034     
3035     if (headingLevel())
3036         return HeadingRole;
3037     
3038     if (node && node->hasTagName(ddTag))
3039         return DefinitionListDefinitionRole;
3040     
3041     if (node && node->hasTagName(dtTag))
3042         return DefinitionListTermRole;
3043
3044     if (node && (node->hasTagName(rpTag) || node->hasTagName(rtTag)))
3045         return AnnotationRole;
3046
3047 #if PLATFORM(GTK)
3048     // Gtk ATs expect all tables, data and layout, to be exposed as tables.
3049     if (node && (node->hasTagName(tdTag) || node->hasTagName(thTag)))
3050         return CellRole;
3051
3052     if (node && node->hasTagName(trTag))
3053         return RowRole;
3054
3055     if (node && node->hasTagName(tableTag))
3056         return TableRole;
3057 #endif
3058
3059     // Table sections should be ignored.
3060     if (m_renderer->isTableSection())
3061         return IgnoredRole;
3062     
3063 #if PLATFORM(GTK)
3064     if (m_renderer->isHR())
3065         return SplitterRole;
3066 #endif
3067
3068     if (m_renderer->isBlockFlow() || (node && node->hasTagName(labelTag)))
3069         return GroupRole;
3070     
3071     // If the element does not have role, but it has ARIA attributes, accessibility should fallback to exposing it as a group.
3072     if (supportsARIAAttributes())
3073         return GroupRole;
3074     
3075     return UnknownRole;
3076 }
3077
3078 AccessibilityOrientation AccessibilityRenderObject::orientation() const
3079 {
3080     const AtomicString& ariaOrientation = getAttribute(aria_orientationAttr);
3081     if (equalIgnoringCase(ariaOrientation, "horizontal"))
3082         return AccessibilityOrientationHorizontal;
3083     if (equalIgnoringCase(ariaOrientation, "vertical"))
3084         return AccessibilityOrientationVertical;
3085     
3086     return AccessibilityObject::orientation();
3087 }
3088     
3089 bool AccessibilityRenderObject::inheritsPresentationalRole() const
3090 {
3091     // ARIA spec says that when a parent object is presentational, and it has required child elements,
3092     // those child elements are also presentational. For example, <li> becomes presentational from <ul>.
3093     // http://www.w3.org/WAI/PF/aria/complete#presentation
3094     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, listItemParents, ());
3095
3096     HashSet<QualifiedName>* possibleParentTagNames = 0;
3097     switch (roleValue()) {
3098     case ListItemRole:
3099     case ListMarkerRole:
3100         if (listItemParents.isEmpty()) {
3101             listItemParents.add(ulTag);
3102             listItemParents.add(olTag);
3103             listItemParents.add(dlTag);
3104         }
3105         possibleParentTagNames = &listItemParents;
3106         break;
3107     default:
3108         break;
3109     }
3110     
3111     // Not all elements need to check for this, only ones that are required children.
3112     if (!possibleParentTagNames)
3113         return false;
3114     
3115     for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) { 
3116         if (!parent->isAccessibilityRenderObject())
3117             continue;
3118         
3119         Node* elementNode = static_cast<AccessibilityRenderObject*>(parent)->node();
3120         if (!elementNode || !elementNode->isElementNode())
3121             continue;
3122         
3123         // If native tag of the parent element matches an acceptable name, then return
3124         // based on its presentational status.
3125         if (possibleParentTagNames->contains(static_cast<Element*>(elementNode)->tagQName()))
3126             return parent->roleValue() == PresentationalRole;
3127     }
3128     
3129     return false;
3130 }
3131     
3132 bool AccessibilityRenderObject::isPresentationalChildOfAriaRole() const
3133 {
3134     // Walk the parent chain looking for a parent that has presentational children
3135     AccessibilityObject* parent;
3136     for (parent = parentObject(); parent && !parent->ariaRoleHasPresentationalChildren(); parent = parent->parentObject())
3137     { }
3138     
3139     return parent;
3140 }
3141     
3142 bool AccessibilityRenderObject::ariaRoleHasPresentationalChildren() const
3143 {
3144     switch (m_ariaRole) {
3145     case ButtonRole:
3146     case SliderRole:
3147     case ImageRole:
3148     case ProgressIndicatorRole:
3149     // case SeparatorRole:
3150         return true;
3151     default:
3152         return false;
3153     }
3154 }
3155
3156 bool AccessibilityRenderObject::canSetFocusAttribute() const
3157 {
3158     ASSERT(m_renderer);
3159     Node* node = m_renderer->node();
3160
3161     // NOTE: It would be more accurate to ask the document whether setFocusedNode() would
3162     // do anything.  For example, setFocusedNode() will do nothing if the current focused
3163     // node will not relinquish the focus.
3164     if (!node || !node->isElementNode())
3165         return false;
3166
3167     if (!static_cast<Element*>(node)->isEnabledFormControl())
3168         return false;
3169
3170     switch (roleValue()) {
3171     case WebCoreLinkRole:
3172     case ImageMapLinkRole:
3173     case TextFieldRole:
3174     case TextAreaRole:
3175     case ButtonRole:
3176     case PopUpButtonRole:
3177     case CheckBoxRole:
3178     case RadioButtonRole:
3179     case SliderRole:
3180         return true;
3181     default:
3182         return node->supportsFocus();
3183     }
3184 }
3185     
3186 bool AccessibilityRenderObject::canSetExpandedAttribute() const
3187 {
3188     // An object can be expanded if it aria-expanded is true or false.
3189     const AtomicString& ariaExpanded = getAttribute(aria_expandedAttr);
3190     return equalIgnoringCase(ariaExpanded, "true") || equalIgnoringCase(ariaExpanded, "false");
3191 }
3192
3193 bool AccessibilityRenderObject::canSetValueAttribute() const
3194 {
3195     if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
3196         return false;
3197
3198     // Any node could be contenteditable, so isReadOnly should be relied upon
3199     // for this information for all elements.
3200     return isProgressIndicator() || isSlider() || !isReadOnly();
3201 }
3202
3203 bool AccessibilityRenderObject::canSetTextRangeAttributes() const
3204 {
3205     return isTextControl();
3206 }
3207
3208 void AccessibilityRenderObject::contentChanged()
3209 {
3210     // If this element supports ARIA live regions, then notify the AT of changes.
3211     AXObjectCache* cache = axObjectCache();
3212     for (RenderObject* renderParent = m_renderer; renderParent; renderParent = renderParent->parent()) {
3213         AccessibilityObject* parent = cache->get(renderParent);
3214         if (!parent)
3215             continue;
3216         
3217         // If we find a parent that has ARIA live region on, send the notification and stop processing.
3218         // The spec does not talk about nested live regions.
3219         if (parent->supportsARIALiveRegion()) {
3220             axObjectCache()->postNotification(renderParent, AXObjectCache::AXLiveRegionChanged, true);
3221             break;
3222         }
3223     }
3224 }
3225     
3226 void AccessibilityRenderObject::childrenChanged()
3227 {
3228     // This method is meant as a quick way of marking a portion of the accessibility tree dirty.
3229     if (!m_renderer)
3230         return;
3231     
3232     bool sentChildrenChanged = false;
3233     
3234     // Go up the accessibility parent chain, but only if the element already exists. This method is
3235     // called during render layouts, minimal work should be done. 
3236     // If AX elements are created now, they could interrogate the render tree while it's in a funky state.
3237     // At the same time, process ARIA live region changes.
3238     for (AccessibilityObject* parent = this; parent; parent = parent->parentObjectIfExists()) {
3239         if (!parent->isAccessibilityRenderObject())
3240             continue;
3241         
3242         AccessibilityRenderObject* axParent = static_cast<AccessibilityRenderObject*>(parent);
3243         
3244         // Send the children changed notification on the first accessibility render object ancestor.
3245         if (!sentChildrenChanged) {
3246             axObjectCache()->postNotification(axParent->renderer(), AXObjectCache::AXChildrenChanged, true);
3247             sentChildrenChanged = true;
3248         }
3249         
3250         // Only do work if the children haven't been marked dirty. This has the effect of blocking
3251         // future live region change notifications until the AX tree has been accessed again. This
3252         // is a good performance win for all parties.
3253         if (!axParent->needsToUpdateChildren()) {
3254             axParent->setNeedsToUpdateChildren();
3255             
3256             // If this element supports ARIA live regions, then notify the AT of changes.
3257             if (axParent->supportsARIALiveRegion())
3258                 axObjectCache()->postNotification(axParent->renderer(), AXObjectCache::AXLiveRegionChanged, true);
3259         }
3260     }
3261 }
3262     
3263 bool AccessibilityRenderObject::canHaveChildren() const
3264 {
3265     if (!m_renderer)
3266         return false;
3267     
3268     // Elements that should not have children
3269     switch (roleValue()) {
3270     case ImageRole:
3271     case ButtonRole:
3272     case PopUpButtonRole:
3273     case CheckBoxRole:
3274     case RadioButtonRole:
3275     case TabRole:
3276     case StaticTextRole:
3277     case ListBoxOptionRole:
3278     case ScrollBarRole:
3279         return false;
3280     default:
3281         return true;
3282     }
3283 }
3284
3285 void AccessibilityRenderObject::clearChildren()
3286 {
3287     AccessibilityObject::clearChildren();
3288     m_childrenDirty = false;
3289 }
3290     
3291 void AccessibilityRenderObject::updateChildrenIfNecessary()
3292 {
3293     if (needsToUpdateChildren())
3294         clearChildren();        
3295     
3296     if (!hasChildren())
3297         addChildren();    
3298 }
3299     
3300 const AccessibilityObject::AccessibilityChildrenVector& AccessibilityRenderObject::children()
3301 {
3302     updateChildrenIfNecessary();
3303     
3304     return m_children;
3305 }
3306
3307 void AccessibilityRenderObject::addChildren()
3308 {
3309     // If the need to add more children in addition to existing children arises, 
3310     // childrenChanged should have been called, leaving the object with no children.
3311     ASSERT(!m_haveChildren); 
3312     
3313     // nothing to add if there is no RenderObject
3314     if (!m_renderer)
3315         return;
3316     
3317     m_haveChildren = true;
3318     
3319     if (!canHaveChildren())
3320         return;
3321     
3322     // add all unignored acc children
3323     for (RefPtr<AccessibilityObject> obj = firstChild(); obj; obj = obj->nextSibling()) {
3324         if (obj->accessibilityIsIgnored()) {
3325             obj->updateChildrenIfNecessary();
3326             AccessibilityChildrenVector children = obj->children();
3327             unsigned length = children.size();
3328             for (unsigned i = 0; i < length; ++i)
3329                 m_children.append(children[i]);
3330         } else {
3331             ASSERT(obj->parentObject() == this);
3332             m_children.append(obj);
3333         }
3334     }
3335     
3336     // for a RenderImage, add the <area> elements as individual accessibility objects
3337     RenderBoxModelObject* cssBox = renderBoxModelObject();
3338     if (cssBox && cssBox->isRenderImage()) {
3339         HTMLMapElement* map = toRenderImage(cssBox)->imageMap();
3340         if (map) {
3341             for (Node* current = map->firstChild(); current; current = current->traverseNextNode(map)) {
3342
3343                 // add an <area> element for this child if it has a link
3344                 if (current->hasTagName(areaTag) && current->isLink()) {
3345                     AccessibilityImageMapLink* areaObject = static_cast<AccessibilityImageMapLink*>(axObjectCache()->getOrCreate(ImageMapLinkRole));
3346                     areaObject->setHTMLAreaElement(static_cast<HTMLAreaElement*>(current));
3347                     areaObject->setHTMLMapElement(map);
3348                     areaObject->setParent(this);
3349
3350                     m_children.append(areaObject);
3351                 }
3352             }
3353         }
3354     }
3355 }
3356         
3357 const AtomicString& AccessibilityRenderObject::ariaLiveRegionStatus() const
3358 {
3359     DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusAssertive, ("assertive"));
3360     DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusPolite, ("polite"));
3361     DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusOff, ("off"));
3362     
3363     const AtomicString& liveRegionStatus = getAttribute(aria_liveAttr);
3364     // These roles have implicit live region status.
3365     if (liveRegionStatus.isEmpty()) {
3366         switch (roleValue()) {
3367         case ApplicationAlertDialogRole:
3368         case ApplicationAlertRole:
3369             return liveRegionStatusAssertive;
3370         case ApplicationLogRole:
3371         case ApplicationStatusRole:
3372             return liveRegionStatusPolite;
3373         case ApplicationTimerRole:
3374         case ApplicationMarqueeRole:
3375             return liveRegionStatusOff;
3376         default:
3377             break;
3378         }
3379     }
3380
3381     return liveRegionStatus;
3382 }
3383
3384 const AtomicString& AccessibilityRenderObject::ariaLiveRegionRelevant() const
3385 {
3386     DEFINE_STATIC_LOCAL(const AtomicString, defaultLiveRegionRelevant, ("additions text"));
3387     const AtomicString& relevant = getAttribute(aria_relevantAttr);
3388
3389     // Default aria-relevant = "additions text".
3390     if (relevant.isEmpty())
3391         return defaultLiveRegionRelevant;
3392     
3393     return relevant;
3394 }
3395
3396 bool AccessibilityRenderObject::ariaLiveRegionAtomic() const
3397 {
3398     return elementAttributeValue(aria_atomicAttr);    
3399 }
3400
3401 bool AccessibilityRenderObject::ariaLiveRegionBusy() const
3402 {
3403     return elementAttributeValue(aria_busyAttr);    
3404 }
3405     
3406 void AccessibilityRenderObject::ariaSelectedRows(AccessibilityChildrenVector& result)
3407 {
3408     // Get all the rows. 
3409     AccessibilityChildrenVector allRows;
3410     ariaTreeRows(allRows);
3411
3412     // Determine which rows are selected.
3413     bool isMulti = isMultiSelectable();
3414
3415     // Prefer active descendant over aria-selected.
3416     AccessibilityObject* activeDesc = activeDescendant();
3417     if (activeDesc && (activeDesc->isTreeItem() || activeDesc->isTableRow())) {
3418         result.append(activeDesc);    
3419         if (!isMulti)
3420             return;
3421     }
3422
3423     unsigned count = allRows.size();
3424     for (unsigned k = 0; k < count; ++k) {
3425         if (allRows[k]->isSelected()) {
3426             result.append(allRows[k]);
3427             if (!isMulti)
3428                 break;
3429         }
3430     }
3431 }
3432     
3433 void AccessibilityRenderObject::ariaListboxSelectedChildren(AccessibilityChildrenVector& result)
3434 {
3435     bool isMulti = isMultiSelectable();
3436
3437     AccessibilityChildrenVector childObjects = children();
3438     unsigned childrenSize = childObjects.size();
3439     for (unsigned k = 0; k < childrenSize; ++k) {
3440         // Every child should have aria-role option, and if so, check for selected attribute/state.
3441         AccessibilityObject* child = childObjects[k].get();
3442         if (child->isSelected() && child->ariaRoleAttribute() == ListBoxOptionRole) {
3443             result.append(child);
3444             if (!isMulti)
3445                 return;
3446         }
3447     }
3448 }
3449
3450 void AccessibilityRenderObject::selectedChildren(AccessibilityChildrenVector& result)
3451 {
3452     ASSERT(result.isEmpty());
3453
3454     // only listboxes should be asked for their selected children. 
3455     AccessibilityRole role = roleValue();
3456     if (role == ListBoxRole) // native list boxes would be AccessibilityListBoxes, so only check for aria list boxes
3457         ariaListboxSelectedChildren(result);
3458     else if (role == TreeRole || role == TreeGridRole || role == TableRole)
3459         ariaSelectedRows(result);
3460 }
3461
3462 void AccessibilityRenderObject::ariaListboxVisibleChildren(AccessibilityChildrenVector& result)      
3463 {
3464     if (!hasChildren())
3465         addChildren();
3466     
3467     unsigned length = m_children.size();
3468     for (unsigned i = 0; i < length; i++) {
3469         if (!m_children[i]->isOffScreen())
3470             result.append(m_children[i]);
3471     }
3472 }
3473
3474 void AccessibilityRenderObject::visibleChildren(AccessibilityChildrenVector& result)
3475 {
3476     ASSERT(result.isEmpty());
3477         
3478     // only listboxes are asked for their visible children. 
3479     if (ariaRoleAttribute() != ListBoxRole) { // native list boxes would be AccessibilityListBoxes, so only check for aria list boxes
3480         ASSERT_NOT_REACHED();
3481         return;
3482     }
3483     return ariaListboxVisibleChildren(result);
3484 }
3485  
3486 void AccessibilityRenderObject::tabChildren(AccessibilityChildrenVector& result)
3487 {
3488     ASSERT(roleValue() == TabListRole);
3489     
3490     unsigned length = m_children.size();
3491     for (unsigned i = 0; i < length; ++i) {
3492         if (m_children[i]->isTabItem())
3493             result.append(m_children[i]);
3494     }
3495 }
3496     
3497 const String& AccessibilityRenderObject::actionVerb() const
3498 {
3499     // FIXME: Need to add verbs for select elements.
3500     DEFINE_STATIC_LOCAL(const String, buttonAction, (AXButtonActionVerb()));
3501     DEFINE_STATIC_LOCAL(const String, textFieldAction, (AXTextFieldActionVerb()));
3502     DEFINE_STATIC_LOCAL(const String, radioButtonAction, (AXRadioButtonActionVerb()));
3503     DEFINE_STATIC_LOCAL(const String, checkedCheckBoxAction, (AXCheckedCheckBoxActionVerb()));
3504     DEFINE_STATIC_LOCAL(const String, uncheckedCheckBoxAction, (AXUncheckedCheckBoxActionVerb()));
3505     DEFINE_STATIC_LOCAL(const String, linkAction, (AXLinkActionVerb()));
3506     DEFINE_STATIC_LOCAL(const String, noAction, ());
3507     
3508     switch (roleValue()) {
3509     case ButtonRole:
3510         return buttonAction;
3511     case TextFieldRole:
3512     case TextAreaRole:
3513         return textFieldAction;
3514     case RadioButtonRole:
3515         return radioButtonAction;
3516     case CheckBoxRole:
3517         return isChecked() ? checkedCheckBoxAction : uncheckedCheckBoxAction;
3518     case LinkRole:
3519     case WebCoreLinkRole:
3520         return linkAction;
3521     default:
3522         return noAction;
3523     }
3524 }
3525     
3526 void AccessibilityRenderObject::setAccessibleName(String& name)
3527 {
3528     // Setting the accessible name can store the value in the DOM
3529     if (!m_renderer)
3530         return;
3531
3532     Node* domNode = 0;
3533     // For web areas, set the aria-label on the HTML element.
3534     if (isWebArea())
3535         domNode = m_renderer->document()->documentElement();
3536     else
3537         domNode = m_renderer->node();
3538
3539     if (domNode && domNode->isElementNode())
3540         static_cast<Element*>(domNode)->setAttribute(aria_labelAttr, name);
3541 }
3542     
3543 void AccessibilityRenderObject::updateBackingStore()
3544 {
3545     if (!m_renderer)
3546         return;
3547
3548     // Updating layout may delete m_renderer and this object.
3549     m_renderer->document()->updateLayoutIgnorePendingStylesheets();
3550 }
3551
3552 static bool isLinkable(const AccessibilityRenderObject& object)
3553 {
3554     if (!object.renderer())
3555         return false;
3556
3557     // See https://wiki.mozilla.org/Accessibility/AT-Windows-API for the elements
3558     // Mozilla considers linkable.
3559     return object.isLink() || object.isImage() || object.renderer()->isText();
3560 }
3561
3562 String AccessibilityRenderObject::stringValueForMSAA() const
3563 {
3564     if (isLinkable(*this)) {
3565         Element* anchor = anchorElement();
3566         if (anchor && anchor->hasTagName(aTag))
3567             return static_cast<HTMLAnchorElement*>(anchor)->href();
3568     }
3569
3570     return stringValue();
3571 }
3572
3573 bool AccessibilityRenderObject::isLinked() const
3574 {
3575     if (!isLinkable(*this))
3576         return false;
3577
3578     Element* anchor = anchorElement();
3579     if (!anchor || !anchor->hasTagName(aTag))
3580         return false;
3581
3582     return !static_cast<HTMLAnchorElement*>(anchor)->href().isEmpty();
3583 }
3584
3585 String AccessibilityRenderObject::nameForMSAA() const
3586 {
3587     if (m_renderer && m_renderer->isText())
3588         return textUnderElement();
3589
3590     return title();
3591 }
3592
3593 static bool shouldReturnTagNameAsRoleForMSAA(const Element& element)
3594 {
3595     // See "document structure",
3596     // https://wiki.mozilla.org/Accessibility/AT-Windows-API
3597     // FIXME: Add the other tag names that should be returned as the role.
3598     return element.hasTagName(h1Tag) || element.hasTagName(h2Tag) 
3599         || element.hasTagName(h3Tag) || element.hasTagName(h4Tag)
3600         || element.hasTagName(h5Tag) || element.hasTagName(h6Tag);
3601 }
3602
3603 String AccessibilityRenderObject::stringRoleForMSAA() const
3604 {
3605     if (!m_renderer)
3606         return String();
3607
3608     Node* node = m_renderer->node();
3609     if (!node || !node->isElementNode())
3610         return String();
3611
3612     Element* element = static_cast<Element*>(node);
3613     if (!shouldReturnTagNameAsRoleForMSAA(*element))
3614         return String();
3615
3616     return element->tagName();
3617 }
3618
3619 String AccessibilityRenderObject::positionalDescriptionForMSAA() const
3620 {
3621     // See "positional descriptions",
3622     // https://wiki.mozilla.org/Accessibility/AT-Windows-API
3623     if (isHeading())
3624         return "L" + String::number(headingLevel());
3625
3626     // FIXME: Add positional descriptions for other elements.
3627     return String();
3628 }
3629
3630 String AccessibilityRenderObject::descriptionForMSAA() const
3631 {
3632     String description = positionalDescriptionForMSAA();
3633     if (!description.isEmpty())
3634         return description;
3635
3636     description = accessibilityDescription();
3637     if (!description.isEmpty()) {
3638         // From the Mozilla MSAA implementation:
3639         // "Signal to screen readers that this description is speakable and is not
3640         // a formatted positional information description. Don't localize the
3641         // 'Description: ' part of this string, it will be parsed out by assistive
3642         // technologies."
3643         return "Description: " + description;
3644     }
3645
3646     return String();
3647 }
3648
3649 static AccessibilityRole msaaRoleForRenderer(const RenderObject* renderer)
3650 {
3651     if (!renderer)
3652         return UnknownRole;
3653
3654     if (renderer->isText())
3655         return EditableTextRole;
3656
3657     if (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListItem())
3658         return ListItemRole;
3659
3660     return UnknownRole;
3661 }
3662
3663 AccessibilityRole AccessibilityRenderObject::roleValueForMSAA() const
3664 {
3665     if (m_roleForMSAA != UnknownRole)
3666         return m_roleForMSAA;
3667
3668     m_roleForMSAA = msaaRoleForRenderer(m_renderer);
3669
3670     if (m_roleForMSAA == UnknownRole)
3671         m_roleForMSAA = roleValue();
3672
3673     return m_roleForMSAA;
3674 }
3675
3676 } // namespace WebCore