WK2: Support Accessibility
[WebKit-https.git] / WebCore / accessibility / mac / AccessibilityObjectWrapper.mm
1 /*
2  * Copyright (C) 2008, 2009, 2010 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 #import "config.h"
30 #import "AccessibilityObjectWrapper.h"
31
32 #if HAVE(ACCESSIBILITY)
33
34 #import "AXObjectCache.h"
35 #import "AccessibilityARIAGridRow.h"
36 #import "AccessibilityListBox.h"
37 #import "AccessibilityList.h"
38 #import "AccessibilityRenderObject.h"
39 #import "AccessibilityScrollView.h"
40 #import "AccessibilityTable.h"
41 #import "AccessibilityTableCell.h"
42 #import "AccessibilityTableRow.h"
43 #import "AccessibilityTableColumn.h"
44 #import "ColorMac.h"
45 #import "EditorClient.h"
46 #import "Frame.h"
47 #import "FrameLoaderClient.h"
48 #import "HTMLAnchorElement.h"
49 #import "HTMLAreaElement.h"
50 #import "HTMLFrameOwnerElement.h"
51 #import "HTMLImageElement.h"
52 #import "HTMLInputElement.h"
53 #import "HTMLTextAreaElement.h"
54 #import "LocalizedStrings.h"
55 #import "RenderTextControl.h"
56 #import "RenderView.h"
57 #import "RenderWidget.h"
58 #import "ScrollView.h"
59 #import "SelectionController.h"
60 #import "SimpleFontData.h"
61 #import "TextIterator.h"
62 #import "WebCoreFrameView.h"
63 #import "WebCoreObjCExtras.h"
64 #import "WebCoreViewFactory.h"
65 #import "htmlediting.h"
66 #import "visible_units.h"
67
68 using namespace WebCore;
69 using namespace HTMLNames;
70 using namespace std;
71
72 // Cell Tables
73 #ifndef NSAccessibilitySelectedCellsAttribute
74 #define NSAccessibilitySelectedCellsAttribute @"AXSelectedCells"
75 #endif
76
77 #ifndef NSAccessibilityVisibleCellsAttribute
78 #define NSAccessibilityVisibleCellsAttribute @"AXVisibleCells"
79 #endif
80
81 #ifndef NSAccessibilityRowHeaderUIElementsAttribute
82 #define NSAccessibilityRowHeaderUIElementsAttribute @"AXRowHeaderUIElements"
83 #endif
84
85 #ifndef NSAccessibilityRowIndexRangeAttribute
86 #define NSAccessibilityRowIndexRangeAttribute @"AXRowIndexRange"
87 #endif
88
89 #ifndef NSAccessibilityColumnIndexRangeAttribute
90 #define NSAccessibilityColumnIndexRangeAttribute @"AXColumnIndexRange"
91 #endif
92
93 #ifndef NSAccessibilityCellForColumnAndRowParameterizedAttribute
94 #define NSAccessibilityCellForColumnAndRowParameterizedAttribute @"AXCellForColumnAndRow"
95 #endif
96
97 #ifndef NSAccessibilityCellRole
98 #define NSAccessibilityCellRole @"AXCell"
99 #endif
100
101 // Lists
102 #ifndef NSAccessibilityContentListSubrole
103 #define NSAccessibilityContentListSubrole @"AXContentList"
104 #endif
105
106 #ifndef NSAccessibilityDefinitionListSubrole
107 #define NSAccessibilityDefinitionListSubrole @"AXDefinitionList"
108 #endif
109
110 // Miscellaneous
111 #ifndef NSAccessibilityBlockQuoteLevelAttribute
112 #define NSAccessibilityBlockQuoteLevelAttribute @"AXBlockQuoteLevel"
113 #endif
114
115 #ifndef NSAccessibilityAccessKeyAttribute
116 #define NSAccessibilityAccessKeyAttribute @"AXAccessKey"
117 #endif
118
119 #ifndef NSAccessibilityLanguageAttribute
120 #define NSAccessibilityLanguageAttribute @"AXLanguage"
121 #endif
122
123 #ifndef NSAccessibilityRequiredAttribute
124 #define NSAccessibilityRequiredAttribute @"AXRequired"
125 #endif
126
127 #ifndef NSAccessibilityInvalidAttribute
128 #define NSAccessibilityInvalidAttribute @"AXInvalid"
129 #endif
130
131 #ifndef NSAccessibilityOwnsAttribute
132 #define NSAccessibilityOwnsAttribute @"AXOwns"
133 #endif
134
135 #ifndef NSAccessibilityGrabbedAttribute
136 #define NSAccessibilityGrabbedAttribute @"AXGrabbed"
137 #endif
138
139 #ifndef NSAccessibilityDropEffectsAttribute
140 #define NSAccessibilityDropEffectsAttribute @"AXDropEffects"
141 #endif
142
143 #ifndef NSAccessibilityARIALiveAttribute
144 #define NSAccessibilityARIALiveAttribute @"AXARIALive"
145 #endif
146
147 #ifndef NSAccessibilityARIAAtomicAttribute
148 #define NSAccessibilityARIAAtomicAttribute @"AXARIAAtomic"
149 #endif
150
151 #ifndef NSAccessibilityARIARelevantAttribute
152 #define NSAccessibilityARIARelevantAttribute @"AXARIARelevant"
153 #endif
154
155 #ifndef NSAccessibilityARIABusyAttribute
156 #define NSAccessibilityARIABusyAttribute @"AXARIABusy"
157 #endif
158
159 #ifndef NSAccessibilityLoadingProgressAttribute
160 #define NSAccessibilityLoadingProgressAttribute @"AXLoadingProgress"
161 #endif
162
163 #ifndef NSAccessibilityHasPopupAttribute
164 #define NSAccessibilityHasPopupAttribute @"AXHasPopup"
165 #endif
166
167 #ifndef NSAccessibilityPlaceholderValueAttribute
168 #define NSAccessibilityPlaceholderValueAttribute @"AXPlaceholderValue"
169 #endif
170
171 #ifdef BUILDING_ON_TIGER
172 typedef unsigned NSUInteger;
173 #define NSAccessibilityValueDescriptionAttribute @"AXValueDescription"
174 #define NSAccessibilityTimelineSubrole @"AXTimeline"
175 #endif
176
177 @interface NSObject (WebKitAccessibilityArrayCategory)
178
179 - (NSUInteger)accessibilityIndexOfChild:(id)child;
180 - (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute;
181 - (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute index:(NSUInteger)index maxCount:(NSUInteger)maxCount;
182
183 @end
184
185 @implementation AccessibilityObjectWrapper
186
187 - (id)initWithAccessibilityObject:(AccessibilityObject*)axObject
188 {
189     [super init];
190
191     m_object = axObject;
192     return self;
193 }
194
195 - (void)unregisterUniqueIdForUIElement
196 {
197     [[WebCoreViewFactory sharedFactory] unregisterUniqueIdForUIElement:self];
198 }
199
200 - (void)detach
201 {
202     // Send unregisterUniqueIdForUIElement unconditionally because if it is
203     // ever accidentally not done (via other bugs in our AX implementation) you
204     // end up with a crash like <rdar://problem/4273149>.  It is safe and not
205     // expensive to send even if the object is not registered.
206     [self unregisterUniqueIdForUIElement];
207     m_object = 0;
208 }
209
210 - (BOOL)updateObjectBackingStore
211 {
212     // Calling updateBackingStore() can invalidate this element so self must be retained.
213     // If it does become invalidated, m_object will be nil.
214     [[self retain] autorelease];
215     
216     if (!m_object)
217         return NO;
218     
219     m_object->updateBackingStore();
220     if (!m_object)
221         return NO;
222     
223     return YES;
224 }
225
226 - (AccessibilityObject*)accessibilityObject
227 {
228     return m_object;
229 }
230
231 - (NSView*)attachmentView
232 {
233     ASSERT(m_object->isAttachment());
234     Widget* widget = m_object->widgetForAttachmentView();
235     if (!widget)
236         return nil;
237     return NSAccessibilityUnignoredDescendant(widget->platformWidget());
238 }
239
240 static WebCoreTextMarker* textMarkerForVisiblePosition(AXObjectCache* cache, const VisiblePosition& visiblePos)
241 {
242     ASSERT(cache);
243     
244     TextMarkerData textMarkerData;
245     cache->textMarkerDataForVisiblePosition(textMarkerData, visiblePos);
246     if (!textMarkerData.axID)
247         return nil;
248     
249     return [[WebCoreViewFactory sharedFactory] textMarkerWithBytes:&textMarkerData length:sizeof(textMarkerData)];
250 }
251
252 - (WebCoreTextMarker *)textMarkerForVisiblePosition:(const VisiblePosition &)visiblePos
253 {
254     return textMarkerForVisiblePosition(m_object->axObjectCache(), visiblePos);
255 }
256
257 static VisiblePosition visiblePositionForTextMarker(AXObjectCache* cache, WebCoreTextMarker* textMarker)
258 {
259     ASSERT(cache);
260
261     if (!textMarker)
262         return VisiblePosition();
263     TextMarkerData textMarkerData;
264     if (![[WebCoreViewFactory sharedFactory] getBytes:&textMarkerData fromTextMarker:textMarker length:sizeof(textMarkerData)])
265         return VisiblePosition();
266     
267     return cache->visiblePositionForTextMarkerData(textMarkerData);
268 }
269
270 - (VisiblePosition)visiblePositionForTextMarker:(WebCoreTextMarker *)textMarker
271 {
272     return visiblePositionForTextMarker(m_object->axObjectCache(), textMarker);
273 }
274
275 static VisiblePosition visiblePositionForStartOfTextMarkerRange(AXObjectCache *cache, WebCoreTextMarkerRange* textMarkerRange)
276 {
277     return visiblePositionForTextMarker(cache, [[WebCoreViewFactory sharedFactory] startOfTextMarkerRange:textMarkerRange]);
278 }
279
280 static VisiblePosition visiblePositionForEndOfTextMarkerRange(AXObjectCache *cache, WebCoreTextMarkerRange* textMarkerRange)
281 {
282     return visiblePositionForTextMarker(cache, [[WebCoreViewFactory sharedFactory] endOfTextMarkerRange:textMarkerRange]);
283 }
284
285 static WebCoreTextMarkerRange* textMarkerRangeFromMarkers(WebCoreTextMarker* textMarker1, WebCoreTextMarker* textMarker2)
286 {
287     if (!textMarker1 || !textMarker2)
288         return nil;
289         
290     return [[WebCoreViewFactory sharedFactory] textMarkerRangeWithStart:textMarker1 end:textMarker2];
291 }
292
293 static void AXAttributeStringSetFont(NSMutableAttributedString* attrString, NSString* attribute, NSFont* font, NSRange range)
294 {
295     NSDictionary* dict;
296     
297     if (font) {
298         dict = [NSDictionary dictionaryWithObjectsAndKeys:
299             [font fontName]                             , NSAccessibilityFontNameKey,
300             [font familyName]                           , NSAccessibilityFontFamilyKey,
301             [font displayName]                          , NSAccessibilityVisibleNameKey,
302             [NSNumber numberWithFloat:[font pointSize]] , NSAccessibilityFontSizeKey,
303         nil];
304
305         [attrString addAttribute:attribute value:dict range:range];
306     } else
307         [attrString removeAttribute:attribute range:range];
308     
309 }
310
311 static CGColorRef CreateCGColorIfDifferent(NSColor* nsColor, CGColorRef existingColor)
312 {
313     // get color information assuming NSDeviceRGBColorSpace 
314     NSColor* rgbColor = [nsColor colorUsingColorSpaceName:NSDeviceRGBColorSpace];
315     if (rgbColor == nil)
316         rgbColor = [NSColor blackColor];
317     CGFloat components[4];
318     [rgbColor getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
319     
320     // create a new CGColorRef to return
321     CGColorSpaceRef cgColorSpace = CGColorSpaceCreateDeviceRGB();
322     CGColorRef cgColor = CGColorCreate(cgColorSpace, components);
323     CGColorSpaceRelease(cgColorSpace);
324     
325     // check for match with existing color
326     if (existingColor && CGColorEqualToColor(cgColor, existingColor)) {
327         CGColorRelease(cgColor);
328         cgColor = 0;
329     }
330     
331     return cgColor;
332 }
333
334 static void AXAttributeStringSetColor(NSMutableAttributedString* attrString, NSString* attribute, NSColor* color, NSRange range)
335 {
336     if (color) {
337         CGColorRef existingColor = (CGColorRef) [attrString attribute:attribute atIndex:range.location effectiveRange:nil];
338         CGColorRef cgColor = CreateCGColorIfDifferent(color, existingColor);
339         if (cgColor) {
340             [attrString addAttribute:attribute value:(id)cgColor range:range];
341             CGColorRelease(cgColor);
342         }
343     } else
344         [attrString removeAttribute:attribute range:range];
345 }
346
347 static void AXAttributeStringSetNumber(NSMutableAttributedString* attrString, NSString* attribute, NSNumber* number, NSRange range)
348 {
349     if (number)
350         [attrString addAttribute:attribute value:number range:range];
351     else
352         [attrString removeAttribute:attribute range:range];
353 }
354
355 static void AXAttributeStringSetStyle(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
356 {
357     RenderStyle* style = renderer->style();
358
359     // set basic font info
360     AXAttributeStringSetFont(attrString, NSAccessibilityFontTextAttribute, style->font().primaryFont()->getNSFont(), range);
361
362     // set basic colors
363     AXAttributeStringSetColor(attrString, NSAccessibilityForegroundColorTextAttribute, nsColor(style->visitedDependentColor(CSSPropertyColor)), range);
364     AXAttributeStringSetColor(attrString, NSAccessibilityBackgroundColorTextAttribute, nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)), range);
365
366     // set super/sub scripting
367     EVerticalAlign alignment = style->verticalAlign();
368     if (alignment == SUB)
369         AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:(-1)], range);
370     else if (alignment == SUPER)
371         AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:1], range);
372     else
373         [attrString removeAttribute:NSAccessibilitySuperscriptTextAttribute range:range];
374     
375     // set shadow
376     if (style->textShadow())
377         AXAttributeStringSetNumber(attrString, NSAccessibilityShadowTextAttribute, [NSNumber numberWithBool:YES], range);
378     else
379         [attrString removeAttribute:NSAccessibilityShadowTextAttribute range:range];
380     
381     // set underline and strikethrough
382     int decor = style->textDecorationsInEffect();
383     if ((decor & UNDERLINE) == 0) {
384         [attrString removeAttribute:NSAccessibilityUnderlineTextAttribute range:range];
385         [attrString removeAttribute:NSAccessibilityUnderlineColorTextAttribute range:range];
386     }
387     
388     if ((decor & LINE_THROUGH) == 0) {
389         [attrString removeAttribute:NSAccessibilityStrikethroughTextAttribute range:range];
390         [attrString removeAttribute:NSAccessibilityStrikethroughColorTextAttribute range:range];
391     }
392
393     if ((decor & (UNDERLINE | LINE_THROUGH)) != 0) {
394         // find colors using quirk mode approach (strict mode would use current
395         // color for all but the root line box, which would use getTextDecorationColors)
396         Color underline, overline, linethrough;
397         renderer->getTextDecorationColors(decor, underline, overline, linethrough);
398         
399         if ((decor & UNDERLINE) != 0) {
400             AXAttributeStringSetNumber(attrString, NSAccessibilityUnderlineTextAttribute, [NSNumber numberWithBool:YES], range);
401             AXAttributeStringSetColor(attrString, NSAccessibilityUnderlineColorTextAttribute, nsColor(underline), range);
402         }
403
404         if ((decor & LINE_THROUGH) != 0) {
405             AXAttributeStringSetNumber(attrString, NSAccessibilityStrikethroughTextAttribute, [NSNumber numberWithBool:YES], range);
406             AXAttributeStringSetColor(attrString, NSAccessibilityStrikethroughColorTextAttribute, nsColor(linethrough), range);
407         }
408     }
409 }
410
411 static int blockquoteLevel(RenderObject* renderer)
412 {
413     if (!renderer)
414         return 0;
415     
416     int result = 0;
417     for (Node* node = renderer->node(); node; node = node->parentNode()) {
418         if (node->hasTagName(blockquoteTag))
419             result += 1;
420     }
421     
422     return result;
423 }
424
425 static void AXAttributeStringSetBlockquoteLevel(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
426 {
427     int quoteLevel = blockquoteLevel(renderer);
428     
429     if (quoteLevel)
430         [attrString addAttribute:NSAccessibilityBlockQuoteLevelAttribute value:[NSNumber numberWithInt:quoteLevel] range:range];
431     else
432         [attrString removeAttribute:NSAccessibilityBlockQuoteLevelAttribute range:range];
433 }
434
435 static void AXAttributeStringSetSpelling(NSMutableAttributedString* attrString, Node* node, const UChar* chars, int charLength, NSRange range)
436 {
437     // Check the spelling directly since document->markersForNode() does not store the misspelled marking when the cursor is in a word.
438     EditorClient* client = node->document()->page()->editorClient();
439     int currentPosition = 0;
440     while (charLength > 0) {
441         const UChar* charData = chars + currentPosition;
442
443         int misspellingLocation = -1;
444         int misspellingLength = 0;
445         client->checkSpellingOfString(charData, charLength, &misspellingLocation, &misspellingLength);
446         if (misspellingLocation == -1 || !misspellingLength)
447             break;
448         
449         NSRange spellRange = NSMakeRange(range.location + currentPosition + misspellingLocation, misspellingLength);
450         AXAttributeStringSetNumber(attrString, NSAccessibilityMisspelledTextAttribute, [NSNumber numberWithBool:YES], spellRange);
451         charLength -= (misspellingLocation + misspellingLength);
452         currentPosition += (misspellingLocation + misspellingLength);
453     }
454 }
455
456 static void AXAttributeStringSetHeadingLevel(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
457 {
458     if (!renderer)
459         return;
460     
461     AccessibilityObject* parentObject = renderer->document()->axObjectCache()->getOrCreate(renderer->parent());
462     int parentHeadingLevel = parentObject->headingLevel();
463     
464     if (parentHeadingLevel)
465         [attrString addAttribute:@"AXHeadingLevel" value:[NSNumber numberWithInt:parentHeadingLevel] range:range];
466     else
467         [attrString removeAttribute:@"AXHeadingLevel" range:range];
468 }
469
470 static void AXAttributeStringSetElement(NSMutableAttributedString* attrString, NSString* attribute, AccessibilityObject* object, NSRange range)
471 {
472     if (object && object->isAccessibilityRenderObject()) {
473         // make a serializable AX object
474         
475         RenderObject* renderer = static_cast<AccessibilityRenderObject*>(object)->renderer();
476         if (!renderer)
477             return;
478         
479         Document* doc = renderer->document();
480         if (!doc)
481             return;
482         
483         AXObjectCache* cache = doc->axObjectCache();
484         if (!cache)
485             return;
486
487         AXUIElementRef axElement = [[WebCoreViewFactory sharedFactory] AXUIElementForElement:object->wrapper()];
488         if (axElement) {
489             [attrString addAttribute:attribute value:(id)axElement range:range];
490             CFRelease(axElement);
491         }
492     } else
493         [attrString removeAttribute:attribute range:range];
494 }
495
496 static void AXAttributedStringAppendText(NSMutableAttributedString* attrString, Node* node, const UChar* chars, int length)
497 {
498     // skip invisible text
499     if (!node->renderer())
500         return;
501
502     // easier to calculate the range before appending the string
503     NSRange attrStringRange = NSMakeRange([attrString length], length);
504     
505     // append the string from this node
506     [[attrString mutableString] appendString:[NSString stringWithCharacters:chars length:length]];
507
508     // add new attributes and remove irrelevant inherited ones
509     // NOTE: color attributes are handled specially because -[NSMutableAttributedString addAttribute: value: range:] does not merge
510     // identical colors.  Workaround is to not replace an existing color attribute if it matches what we are adding.  This also means
511     // we cannot just pre-remove all inherited attributes on the appended string, so we have to remove the irrelevant ones individually.
512
513     // remove inherited attachment from prior AXAttributedStringAppendReplaced
514     [attrString removeAttribute:NSAccessibilityAttachmentTextAttribute range:attrStringRange];
515     [attrString removeAttribute:NSAccessibilityMisspelledTextAttribute range:attrStringRange];
516     
517     // set new attributes
518     AXAttributeStringSetStyle(attrString, node->renderer(), attrStringRange);
519     AXAttributeStringSetHeadingLevel(attrString, node->renderer(), attrStringRange);
520     AXAttributeStringSetBlockquoteLevel(attrString, node->renderer(), attrStringRange);
521     AXAttributeStringSetElement(attrString, NSAccessibilityLinkTextAttribute, AccessibilityObject::anchorElementForNode(node), attrStringRange);
522     
523     // do spelling last because it tends to break up the range
524     AXAttributeStringSetSpelling(attrString, node, chars, length, attrStringRange);
525 }
526
527 static NSString* nsStringForReplacedNode(Node* replacedNode)
528 {
529     // we should always be given a rendered node and a replaced node, but be safe
530     // replaced nodes are either attachments (widgets) or images
531     if (!replacedNode || !replacedNode->renderer() || !replacedNode->renderer()->isReplaced() || replacedNode->isTextNode()) {
532         ASSERT_NOT_REACHED();
533         return nil;
534     }
535
536     // create an AX object, but skip it if it is not supposed to be seen
537     RefPtr<AccessibilityObject> obj = replacedNode->renderer()->document()->axObjectCache()->getOrCreate(replacedNode->renderer());
538     if (obj->accessibilityIsIgnored())
539         return nil;
540     
541     // use the attachmentCharacter to represent the replaced node
542     const UniChar attachmentChar = NSAttachmentCharacter;
543     return [NSString stringWithCharacters:&attachmentChar length:1];
544 }
545
546 - (NSAttributedString*)doAXAttributedStringForTextMarkerRange:(WebCoreTextMarkerRange*)textMarkerRange
547 {
548     if (!m_object)
549         return nil;
550     
551     // extract the start and end VisiblePosition
552     VisiblePosition startVisiblePosition = visiblePositionForStartOfTextMarkerRange(m_object->axObjectCache(), textMarkerRange);
553     if (startVisiblePosition.isNull())
554         return nil;
555
556     VisiblePosition endVisiblePosition = visiblePositionForEndOfTextMarkerRange(m_object->axObjectCache(), textMarkerRange);
557     if (endVisiblePosition.isNull())
558         return nil;
559
560     VisiblePositionRange visiblePositionRange(startVisiblePosition, endVisiblePosition);
561     // iterate over the range to build the AX attributed string
562     NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] init];
563     TextIterator it(makeRange(startVisiblePosition, endVisiblePosition).get());
564     while (!it.atEnd()) {
565         // locate the node and starting offset for this range
566         int exception = 0;
567         Node* node = it.range()->startContainer(exception);
568         ASSERT(node == it.range()->endContainer(exception));
569         int offset = it.range()->startOffset(exception);
570
571         // non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
572         if (it.length() != 0) {
573             // Add the text of the list marker item if necessary.
574             String listMarkerText = m_object->listMarkerTextForNodeAndPosition(node, VisiblePosition(it.range()->startPosition()));
575             if (!listMarkerText.isEmpty())
576                 AXAttributedStringAppendText(attrString, node, listMarkerText.characters(), listMarkerText.length());
577             
578             AXAttributedStringAppendText(attrString, node, it.characters(), it.length());
579         } else {
580             Node* replacedNode = node->childNode(offset);
581             NSString *attachmentString = nsStringForReplacedNode(replacedNode);
582             if (attachmentString) {
583                 NSRange attrStringRange = NSMakeRange([attrString length], [attachmentString length]);
584
585                 // append the placeholder string
586                 [[attrString mutableString] appendString:attachmentString];
587
588                 // remove all inherited attributes
589                 [attrString setAttributes:nil range:attrStringRange];
590
591                 // add the attachment attribute
592                 AccessibilityObject* obj = replacedNode->renderer()->document()->axObjectCache()->getOrCreate(replacedNode->renderer());
593                 AXAttributeStringSetElement(attrString, NSAccessibilityAttachmentTextAttribute, obj, attrStringRange);
594             }
595         }
596         it.advance();
597     }
598
599     return [attrString autorelease];
600 }
601
602 static WebCoreTextMarkerRange* textMarkerRangeFromVisiblePositions(AXObjectCache *cache, VisiblePosition startPosition, VisiblePosition endPosition)
603 {
604     WebCoreTextMarker* startTextMarker = textMarkerForVisiblePosition(cache, startPosition);
605     WebCoreTextMarker* endTextMarker = textMarkerForVisiblePosition(cache, endPosition);
606     return textMarkerRangeFromMarkers(startTextMarker, endTextMarker);
607 }
608
609 - (WebCoreTextMarkerRange *)textMarkerRangeFromVisiblePositions:(VisiblePosition)startPosition endPosition:(VisiblePosition)endPosition
610 {
611     return textMarkerRangeFromVisiblePositions(m_object->axObjectCache(), startPosition, endPosition);
612 }
613
614 - (NSArray*)accessibilityActionNames
615 {
616     if (![self updateObjectBackingStore])
617         return nil;
618
619     static NSArray* actionElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityPressAction, NSAccessibilityShowMenuAction, nil];
620     static NSArray* defaultElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityShowMenuAction, nil];
621     static NSArray* menuElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityCancelAction, NSAccessibilityPressAction, nil];
622     static NSArray* sliderActions = [[NSArray alloc] initWithObjects: NSAccessibilityIncrementAction, NSAccessibilityDecrementAction, nil];
623
624     NSArray *actions;
625     if (m_object->actionElement()) 
626         actions = actionElementActions;
627     else if (m_object->isMenuRelated())
628         actions = menuElementActions;
629     else if (m_object->isSlider())
630         actions = sliderActions;
631     else if (m_object->isAttachment())
632         actions = [[self attachmentView] accessibilityActionNames];
633     else
634         actions = defaultElementActions;
635
636     return actions;
637 }
638
639 - (NSArray*)additionalAccessibilityAttributeNames
640 {
641     if (!m_object)
642         return nil;
643
644     NSMutableArray *additional = [NSMutableArray array];
645     if (m_object->supportsARIAOwns())
646         [additional addObject:NSAccessibilityOwnsAttribute];
647
648     if (m_object->isScrollbar())
649         [additional addObject:NSAccessibilityOrientationAttribute];
650     
651     if (m_object->supportsARIADragging())
652         [additional addObject:NSAccessibilityGrabbedAttribute];
653
654     if (m_object->supportsARIADropping())
655         [additional addObject:NSAccessibilityDropEffectsAttribute];
656
657     if (m_object->isAccessibilityTable() && static_cast<AccessibilityTable*>(m_object)->supportsSelectedRows())
658         [additional addObject:NSAccessibilitySelectedRowsAttribute];        
659     
660     if (m_object->supportsARIALiveRegion()) {
661         [additional addObject:NSAccessibilityARIALiveAttribute];
662         [additional addObject:NSAccessibilityARIARelevantAttribute];
663     }
664         
665     // If an object is a child of a live region, then add these
666     if (m_object->isInsideARIALiveRegion()) {
667         [additional addObject:NSAccessibilityARIAAtomicAttribute];
668         [additional addObject:NSAccessibilityARIABusyAttribute];
669     }
670     
671     if (m_object->ariaHasPopup())
672         [additional addObject:NSAccessibilityHasPopupAttribute];
673     
674     return additional;
675 }
676
677 - (NSArray*)accessibilityAttributeNames
678 {
679     if (![self updateObjectBackingStore])
680         return nil;
681     
682     if (m_object->isAttachment())
683         return [[self attachmentView] accessibilityAttributeNames];
684
685     static NSArray* attributes = nil;
686     static NSArray* anchorAttrs = nil;
687     static NSArray* webAreaAttrs = nil;
688     static NSArray* textAttrs = nil;
689     static NSArray* listAttrs = nil;
690     static NSArray* listBoxAttrs = nil;
691     static NSArray* rangeAttrs = nil;
692     static NSArray* commonMenuAttrs = nil;
693     static NSArray* menuAttrs = nil;
694     static NSArray* menuBarAttrs = nil;
695     static NSArray* menuItemAttrs = nil;
696     static NSArray* menuButtonAttrs = nil;
697     static NSArray* controlAttrs = nil;
698     static NSArray* tableAttrs = nil;
699     static NSArray* tableRowAttrs = nil;
700     static NSArray* tableColAttrs = nil;
701     static NSArray* tableCellAttrs = nil;
702     static NSArray* groupAttrs = nil;
703     static NSArray* inputImageAttrs = nil;
704     static NSArray* passwordFieldAttrs = nil;
705     static NSArray* tabListAttrs = nil;
706     static NSArray* comboBoxAttrs = nil;
707     static NSArray* outlineAttrs = nil;
708     static NSArray* outlineRowAttrs = nil;
709     static NSArray* buttonAttrs = nil;
710     static NSArray* scrollViewAttrs = nil;
711     NSMutableArray* tempArray;
712     if (attributes == nil) {
713         attributes = [[NSArray alloc] initWithObjects: NSAccessibilityRoleAttribute,
714                       NSAccessibilitySubroleAttribute,
715                       NSAccessibilityRoleDescriptionAttribute,
716                       NSAccessibilityChildrenAttribute,
717                       NSAccessibilityHelpAttribute,
718                       NSAccessibilityParentAttribute,
719                       NSAccessibilityPositionAttribute,
720                       NSAccessibilitySizeAttribute,
721                       NSAccessibilityTitleAttribute,
722                       NSAccessibilityDescriptionAttribute,
723                       NSAccessibilityValueAttribute,
724                       NSAccessibilityFocusedAttribute,
725                       NSAccessibilityEnabledAttribute,
726                       NSAccessibilityWindowAttribute,
727                       @"AXSelectedTextMarkerRange",
728                       @"AXStartTextMarker",
729                       @"AXEndTextMarker",
730                       @"AXVisited",
731                       NSAccessibilityLinkedUIElementsAttribute,
732                       NSAccessibilitySelectedAttribute,
733                       NSAccessibilityBlockQuoteLevelAttribute,
734                       NSAccessibilityTopLevelUIElementAttribute,
735                       nil];
736     }
737     if (commonMenuAttrs == nil) {
738         commonMenuAttrs = [[NSArray alloc] initWithObjects: NSAccessibilityRoleAttribute,
739                             NSAccessibilityRoleDescriptionAttribute,
740                             NSAccessibilityChildrenAttribute,
741                             NSAccessibilityParentAttribute,
742                             NSAccessibilityEnabledAttribute,
743                             NSAccessibilityPositionAttribute,
744                             NSAccessibilitySizeAttribute,
745                             nil];
746     }
747     if (anchorAttrs == nil) {
748         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
749         [tempArray addObject:NSAccessibilityURLAttribute];
750         [tempArray addObject:NSAccessibilityAccessKeyAttribute];
751         anchorAttrs = [[NSArray alloc] initWithArray:tempArray];
752         [tempArray release];
753     }
754     if (webAreaAttrs == nil) {
755         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
756         [tempArray addObject:@"AXLinkUIElements"];
757         [tempArray addObject:@"AXLoaded"];
758         [tempArray addObject:@"AXLayoutCount"];
759         [tempArray addObject:NSAccessibilityLoadingProgressAttribute];
760         [tempArray addObject:NSAccessibilityURLAttribute];
761         webAreaAttrs = [[NSArray alloc] initWithArray:tempArray];
762         [tempArray release];
763     }
764     if (textAttrs == nil) {
765         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
766         [tempArray addObject:NSAccessibilityNumberOfCharactersAttribute];
767         [tempArray addObject:NSAccessibilitySelectedTextAttribute];
768         [tempArray addObject:NSAccessibilitySelectedTextRangeAttribute];
769         [tempArray addObject:NSAccessibilityVisibleCharacterRangeAttribute];
770         [tempArray addObject:NSAccessibilityInsertionPointLineNumberAttribute];
771         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
772         [tempArray addObject:NSAccessibilityAccessKeyAttribute];
773         [tempArray addObject:NSAccessibilityRequiredAttribute];
774         [tempArray addObject:NSAccessibilityInvalidAttribute];
775         [tempArray addObject:NSAccessibilityPlaceholderValueAttribute];
776         textAttrs = [[NSArray alloc] initWithArray:tempArray];
777         [tempArray release];
778     }
779     if (listAttrs == nil) {
780         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
781         [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
782         [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
783         [tempArray addObject:NSAccessibilityOrientationAttribute];
784         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
785         listAttrs = [[NSArray alloc] initWithArray:tempArray];
786         [tempArray release];
787     }
788     if (listBoxAttrs == nil) {
789         tempArray = [[NSMutableArray alloc] initWithArray:listAttrs];    
790         [tempArray addObject:NSAccessibilityAccessKeyAttribute];
791         [tempArray addObject:NSAccessibilityRequiredAttribute];
792         [tempArray addObject:NSAccessibilityInvalidAttribute];
793         listBoxAttrs = [[NSArray alloc] initWithArray:tempArray];
794         [tempArray release];
795     }
796     if (rangeAttrs == nil) {
797         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
798         [tempArray addObject:NSAccessibilityMinValueAttribute];
799         [tempArray addObject:NSAccessibilityMaxValueAttribute];
800         [tempArray addObject:NSAccessibilityOrientationAttribute];
801         [tempArray addObject:NSAccessibilityValueDescriptionAttribute];
802         rangeAttrs = [[NSArray alloc] initWithArray:tempArray];
803         [tempArray release];
804     }
805     if (menuBarAttrs == nil) {
806         tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
807         [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
808         [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
809         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
810         menuBarAttrs = [[NSArray alloc] initWithArray:tempArray];
811         [tempArray release];
812     }
813     if (menuAttrs == nil) {
814         tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
815         [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
816         [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
817         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
818         menuAttrs = [[NSArray alloc] initWithArray:tempArray];
819         [tempArray release];
820     }
821     if (menuItemAttrs == nil) {
822         tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
823         [tempArray addObject:NSAccessibilityTitleAttribute];
824         [tempArray addObject:NSAccessibilityHelpAttribute];
825         [tempArray addObject:NSAccessibilitySelectedAttribute];
826         [tempArray addObject:(NSString*)kAXMenuItemCmdCharAttribute];
827         [tempArray addObject:(NSString*)kAXMenuItemCmdVirtualKeyAttribute];
828         [tempArray addObject:(NSString*)kAXMenuItemCmdGlyphAttribute];
829         [tempArray addObject:(NSString*)kAXMenuItemCmdModifiersAttribute];
830         [tempArray addObject:(NSString*)kAXMenuItemMarkCharAttribute];
831         [tempArray addObject:(NSString*)kAXMenuItemPrimaryUIElementAttribute];
832         [tempArray addObject:NSAccessibilityServesAsTitleForUIElementsAttribute];
833         menuItemAttrs = [[NSArray alloc] initWithArray:tempArray];
834         [tempArray release];
835     }
836     if (menuButtonAttrs == nil) {
837         menuButtonAttrs = [[NSArray alloc] initWithObjects:NSAccessibilityRoleAttribute,
838             NSAccessibilityRoleDescriptionAttribute,
839             NSAccessibilityParentAttribute,
840             NSAccessibilityPositionAttribute,
841             NSAccessibilitySizeAttribute,
842             NSAccessibilityWindowAttribute,
843             NSAccessibilityEnabledAttribute,
844             NSAccessibilityFocusedAttribute,
845             NSAccessibilityTitleAttribute,
846             NSAccessibilityChildrenAttribute, nil];
847     }
848     if (controlAttrs == nil) {
849         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
850         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
851         [tempArray addObject:NSAccessibilityAccessKeyAttribute];
852         [tempArray addObject:NSAccessibilityRequiredAttribute];
853         [tempArray addObject:NSAccessibilityInvalidAttribute];
854         controlAttrs = [[NSArray alloc] initWithArray:tempArray];
855         [tempArray release];
856     }
857     if (buttonAttrs == nil) {
858         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
859         // Buttons should not expose AXValue.
860         [tempArray removeObject:NSAccessibilityValueAttribute];
861         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
862         [tempArray addObject:NSAccessibilityAccessKeyAttribute];
863         buttonAttrs = [[NSArray alloc] initWithArray:tempArray];
864         [tempArray release];
865     }
866     if (comboBoxAttrs == nil) {
867         tempArray = [[NSMutableArray alloc] initWithArray:controlAttrs];
868         [tempArray addObject:NSAccessibilityExpandedAttribute];
869         comboBoxAttrs = [[NSArray alloc] initWithArray:tempArray];
870         [tempArray release];        
871     }
872     if (tableAttrs == nil) {
873         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
874         [tempArray addObject:NSAccessibilityRowsAttribute];
875         [tempArray addObject:NSAccessibilityVisibleRowsAttribute];
876         [tempArray addObject:NSAccessibilityColumnsAttribute];
877         [tempArray addObject:NSAccessibilityVisibleColumnsAttribute];
878         [tempArray addObject:NSAccessibilityVisibleCellsAttribute];
879         [tempArray addObject:(NSString *)kAXColumnHeaderUIElementsAttribute];
880         [tempArray addObject:NSAccessibilityRowHeaderUIElementsAttribute];
881         [tempArray addObject:NSAccessibilityHeaderAttribute];
882         tableAttrs = [[NSArray alloc] initWithArray:tempArray];
883         [tempArray release];
884     }
885     if (tableRowAttrs == nil) {
886         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
887         [tempArray addObject:NSAccessibilityIndexAttribute];
888         tableRowAttrs = [[NSArray alloc] initWithArray:tempArray];
889         [tempArray release];
890     }
891     if (tableColAttrs == nil) {
892         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
893         [tempArray addObject:NSAccessibilityIndexAttribute];
894         [tempArray addObject:NSAccessibilityHeaderAttribute];
895         [tempArray addObject:NSAccessibilityRowsAttribute];
896         [tempArray addObject:NSAccessibilityVisibleRowsAttribute];
897         tableColAttrs = [[NSArray alloc] initWithArray:tempArray];
898         [tempArray release];
899     }
900     if (tableCellAttrs == nil) {
901         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
902         [tempArray addObject:NSAccessibilityRowIndexRangeAttribute];
903         [tempArray addObject:NSAccessibilityColumnIndexRangeAttribute];
904         tableCellAttrs = [[NSArray alloc] initWithArray:tempArray];
905         [tempArray release];        
906     }
907     if (groupAttrs == nil) {
908         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
909         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
910         groupAttrs = [[NSArray alloc] initWithArray:tempArray];
911         [tempArray release];
912     }
913     if (inputImageAttrs == nil) {
914         tempArray = [[NSMutableArray alloc] initWithArray:buttonAttrs];
915         [tempArray addObject:NSAccessibilityURLAttribute];
916         inputImageAttrs = [[NSArray alloc] initWithArray:tempArray];
917         [tempArray release];
918     }
919     if (passwordFieldAttrs == nil) {
920         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
921         [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
922         [tempArray addObject:NSAccessibilityRequiredAttribute];
923         [tempArray addObject:NSAccessibilityInvalidAttribute];
924         passwordFieldAttrs = [[NSArray alloc] initWithArray:tempArray];
925         [tempArray release];
926     }
927     if (tabListAttrs == nil) {
928         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
929         [tempArray addObject:NSAccessibilityTabsAttribute];
930         [tempArray addObject:NSAccessibilityContentsAttribute];
931         tabListAttrs = [[NSArray alloc] initWithArray:tempArray];
932         [tempArray release];        
933     }
934     if (outlineAttrs == nil) {
935         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
936         [tempArray addObject:NSAccessibilitySelectedRowsAttribute];
937         [tempArray addObject:NSAccessibilityRowsAttribute];
938         [tempArray addObject:NSAccessibilityColumnsAttribute];
939         outlineAttrs = [[NSArray alloc] initWithArray:tempArray];
940         [tempArray release];
941     }
942     if (outlineRowAttrs == nil) {
943         tempArray = [[NSMutableArray alloc] initWithArray:tableRowAttrs];
944         [tempArray addObject:NSAccessibilityDisclosingAttribute];
945         [tempArray addObject:NSAccessibilityDisclosedByRowAttribute];
946         [tempArray addObject:NSAccessibilityDisclosureLevelAttribute];
947         [tempArray addObject:NSAccessibilityDisclosedRowsAttribute];
948         outlineRowAttrs = [[NSArray alloc] initWithArray:tempArray];
949         [tempArray release];
950     }
951     if (scrollViewAttrs == nil) {
952         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
953         [tempArray addObject:NSAccessibilityContentsAttribute];
954         [tempArray addObject:NSAccessibilityHorizontalScrollBarAttribute];
955         [tempArray addObject:NSAccessibilityVerticalScrollBarAttribute];
956         scrollViewAttrs = [[NSArray alloc] initWithArray:tempArray];
957         [tempArray release];
958     }
959     
960     NSArray *objectAttributes = attributes;
961     
962     if (m_object->isPasswordField())
963         objectAttributes = passwordFieldAttrs;
964
965     else if (m_object->isWebArea())
966         objectAttributes = webAreaAttrs;
967     
968     else if (m_object->isTextControl())
969         objectAttributes = textAttrs;
970
971     else if (m_object->isAnchor() || m_object->isImage() || m_object->isLink())
972         objectAttributes = anchorAttrs;
973
974     else if (m_object->isAccessibilityTable())
975         objectAttributes = tableAttrs;
976     else if (m_object->isTableColumn())
977         objectAttributes = tableColAttrs;
978     else if (m_object->isTableCell())
979         objectAttributes = tableCellAttrs;
980     else if (m_object->isTableRow()) {
981         // An ARIA table row can be collapsed and expanded, so it needs the extra attributes.
982         if (m_object->isARIATreeGridRow())
983             objectAttributes = outlineRowAttrs;
984         else
985             objectAttributes = tableRowAttrs;
986     }
987     
988     else if (m_object->isTree())
989         objectAttributes = outlineAttrs;
990     else if (m_object->isTreeItem())
991         objectAttributes = outlineRowAttrs;
992     
993     else if (m_object->isListBox())
994         objectAttributes = listBoxAttrs;
995     else if (m_object->isList())
996         objectAttributes = listAttrs;
997     
998     else if (m_object->isComboBox())
999         objectAttributes = comboBoxAttrs;
1000     
1001     else if (m_object->isProgressIndicator() || m_object->isSlider())
1002         objectAttributes = rangeAttrs;
1003
1004     // These are processed in order because an input image is a button, and a button is a control.
1005     else if (m_object->isInputImage())
1006         objectAttributes = inputImageAttrs;
1007     else if (m_object->isButton())
1008         objectAttributes = buttonAttrs;
1009     else if (m_object->isControl())
1010         objectAttributes = controlAttrs;
1011     
1012     else if (m_object->isGroup() || m_object->isListItem())
1013         objectAttributes = groupAttrs;
1014     else if (m_object->isTabList())
1015         objectAttributes = tabListAttrs;
1016     else if (m_object->isScrollView())
1017         objectAttributes = scrollViewAttrs;
1018     
1019     else if (m_object->isMenu())
1020         objectAttributes = menuAttrs;
1021     else if (m_object->isMenuBar())
1022         objectAttributes = menuBarAttrs;
1023     else if (m_object->isMenuButton())
1024         objectAttributes = menuButtonAttrs;
1025     else if (m_object->isMenuItem())
1026         objectAttributes = menuItemAttrs;
1027     
1028     NSArray *additionalAttributes = [self additionalAccessibilityAttributeNames];
1029     if ([additionalAttributes count])
1030         objectAttributes = [objectAttributes arrayByAddingObjectsFromArray:additionalAttributes];
1031     
1032     return objectAttributes;
1033 }
1034
1035 - (VisiblePositionRange)visiblePositionRangeForTextMarkerRange:(WebCoreTextMarkerRange*) textMarkerRange
1036 {
1037     if (!textMarkerRange)
1038         return VisiblePositionRange();
1039     AXObjectCache* cache = m_object->axObjectCache();
1040     return VisiblePositionRange(visiblePositionForStartOfTextMarkerRange(cache, textMarkerRange), visiblePositionForEndOfTextMarkerRange(cache, textMarkerRange));
1041 }
1042
1043 - (NSArray*)renderWidgetChildren
1044 {
1045     Widget* widget = m_object->widget();
1046     if (!widget)
1047         return nil;
1048     return [(widget->platformWidget()) accessibilityAttributeValue: NSAccessibilityChildrenAttribute];
1049 }
1050
1051 - (id)remoteAccessibilityParentObject
1052 {
1053     if (!m_object || !m_object->document())
1054         return nil;
1055     
1056     return m_object->document()->frame()->loader()->client()->accessibilityRemoteObject();
1057 }
1058
1059 static void convertToVector(NSArray* array, AccessibilityObject::AccessibilityChildrenVector& vector)
1060 {
1061     unsigned length = [array count];
1062     vector.reserveInitialCapacity(length);
1063     for (unsigned i = 0; i < length; ++i) {
1064         AccessibilityObject* obj = [[array objectAtIndex:i] accessibilityObject];
1065         if (obj)
1066             vector.append(obj);
1067     }
1068 }
1069
1070 static NSMutableArray* convertToNSArray(const AccessibilityObject::AccessibilityChildrenVector& vector)
1071 {
1072     unsigned length = vector.size();
1073     NSMutableArray* array = [NSMutableArray arrayWithCapacity: length];
1074     for (unsigned i = 0; i < length; ++i) {
1075         AccessibilityObjectWrapper* wrapper = vector[i]->wrapper();
1076         ASSERT(wrapper);
1077         if (wrapper) {
1078             // we want to return the attachment view instead of the object representing the attachment.
1079             // otherwise, we get palindrome errors in the AX hierarchy
1080             if (vector[i]->isAttachment() && [wrapper attachmentView])
1081                 [array addObject:[wrapper attachmentView]];
1082             else
1083                 [array addObject:wrapper];
1084         }
1085     }
1086     return array;
1087 }
1088
1089 - (WebCoreTextMarkerRange*)textMarkerRangeForSelection
1090 {
1091     VisibleSelection selection = m_object->selection();
1092     if (selection.isNone())
1093         return nil;
1094     return [self textMarkerRangeFromVisiblePositions:selection.visibleStart() endPosition:selection.visibleEnd()];
1095 }
1096
1097 - (NSValue*)position
1098 {
1099     IntRect rect = m_object->elementRect();
1100     NSPoint point;
1101     
1102     FrameView* frameView = m_object->documentFrameView();
1103     id remoteParent = [self remoteAccessibilityParentObject];
1104     if (remoteParent) {
1105         point = NSMakePoint(rect.x(), rect.y());
1106         
1107         NSPoint remotePosition = [[remoteParent accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue];
1108         NSSize remoteSize = [[remoteParent accessibilityAttributeValue:NSAccessibilitySizeAttribute] sizeValue];
1109
1110         // Get the y position of the WKView (we have to screen-flip and go from bottom left to top left).
1111         CGFloat screenHeight = [[[NSScreen screens] objectAtIndex:0] frame].size.height;
1112         remotePosition.y = (screenHeight - remotePosition.y) - remoteSize.height;
1113         
1114         NSPoint scrollPosition = NSMakePoint(0, 0);
1115         if (frameView && !m_object->isScrollbar() && !m_object->isScrollView()) {
1116             IntPoint frameScrollPos = frameView->scrollPosition();
1117             scrollPosition = NSMakePoint(frameScrollPos.x(), frameScrollPos.y());
1118         }
1119         
1120         point.x += remotePosition.x - scrollPosition.x;
1121         // Set the new position, which means getting bottom y, and then flipping to screen coordinates.
1122         point.y = screenHeight - (point.y + remotePosition.y + rect.height() - scrollPosition.y);
1123     } else {
1124         // The Cocoa accessibility API wants the lower-left corner.
1125         point = NSMakePoint(rect.x(), rect.bottom());
1126         
1127         if (frameView) {
1128             NSView* view = frameView->documentView();
1129             point = [[view window] convertBaseToScreen:[view convertPoint: point toView:nil]];
1130         }
1131     }
1132
1133     return [NSValue valueWithPoint:point];
1134 }
1135
1136 typedef HashMap<int, NSString*> AccessibilityRoleMap;
1137
1138 static const AccessibilityRoleMap& createAccessibilityRoleMap()
1139 {
1140     struct RoleEntry {
1141         AccessibilityRole value;
1142         NSString* string;
1143     };
1144     
1145     static const RoleEntry roles[] = {
1146         { UnknownRole, NSAccessibilityUnknownRole },
1147         { ButtonRole, NSAccessibilityButtonRole },
1148         { RadioButtonRole, NSAccessibilityRadioButtonRole },
1149         { CheckBoxRole, NSAccessibilityCheckBoxRole },
1150         { SliderRole, NSAccessibilitySliderRole },
1151         { TabGroupRole, NSAccessibilityTabGroupRole },
1152         { TextFieldRole, NSAccessibilityTextFieldRole },
1153         { StaticTextRole, NSAccessibilityStaticTextRole },
1154         { TextAreaRole, NSAccessibilityTextAreaRole },
1155         { ScrollAreaRole, NSAccessibilityScrollAreaRole },
1156         { PopUpButtonRole, NSAccessibilityPopUpButtonRole },
1157         { MenuButtonRole, NSAccessibilityMenuButtonRole },
1158         { TableRole, NSAccessibilityTableRole },
1159         { ApplicationRole, NSAccessibilityApplicationRole },
1160         { GroupRole, NSAccessibilityGroupRole },
1161         { RadioGroupRole, NSAccessibilityRadioGroupRole },
1162         { ListRole, NSAccessibilityListRole },
1163         { DirectoryRole, NSAccessibilityListRole },
1164         { ScrollBarRole, NSAccessibilityScrollBarRole },
1165         { ValueIndicatorRole, NSAccessibilityValueIndicatorRole },
1166         { ImageRole, NSAccessibilityImageRole },
1167         { MenuBarRole, NSAccessibilityMenuBarRole },
1168         { MenuRole, NSAccessibilityMenuRole },
1169         { MenuItemRole, NSAccessibilityMenuItemRole },
1170         { ColumnRole, NSAccessibilityColumnRole },
1171         { RowRole, NSAccessibilityRowRole },
1172         { ToolbarRole, NSAccessibilityToolbarRole },
1173         { BusyIndicatorRole, NSAccessibilityBusyIndicatorRole },
1174         { ProgressIndicatorRole, NSAccessibilityProgressIndicatorRole },
1175         { WindowRole, NSAccessibilityWindowRole },
1176         { DrawerRole, NSAccessibilityDrawerRole },
1177         { SystemWideRole, NSAccessibilitySystemWideRole },
1178         { OutlineRole, NSAccessibilityOutlineRole },
1179         { IncrementorRole, NSAccessibilityIncrementorRole },
1180         { BrowserRole, NSAccessibilityBrowserRole },
1181         { ComboBoxRole, NSAccessibilityComboBoxRole },
1182         { SplitGroupRole, NSAccessibilitySplitGroupRole },
1183         { SplitterRole, NSAccessibilitySplitterRole },
1184         { ColorWellRole, NSAccessibilityColorWellRole },
1185         { GrowAreaRole, NSAccessibilityGrowAreaRole },
1186         { SheetRole, NSAccessibilitySheetRole },
1187         { HelpTagRole, NSAccessibilityHelpTagRole },
1188         { MatteRole, NSAccessibilityMatteRole }, 
1189         { RulerRole, NSAccessibilityRulerRole },
1190         { RulerMarkerRole, NSAccessibilityRulerMarkerRole },
1191         { LinkRole, NSAccessibilityLinkRole },
1192 #ifndef BUILDING_ON_TIGER        
1193         { DisclosureTriangleRole, NSAccessibilityDisclosureTriangleRole },
1194         { GridRole, NSAccessibilityGridRole },
1195 #endif
1196         { WebCoreLinkRole, NSAccessibilityLinkRole }, 
1197         { ImageMapLinkRole, NSAccessibilityLinkRole },
1198         { ImageMapRole, @"AXImageMap" },
1199         { ListMarkerRole, @"AXListMarker" },
1200         { WebAreaRole, @"AXWebArea" },
1201         { HeadingRole, @"AXHeading" },
1202         { ListBoxRole, NSAccessibilityListRole },
1203         { ListBoxOptionRole, NSAccessibilityStaticTextRole },
1204 #if ACCESSIBILITY_TABLES
1205         { CellRole, NSAccessibilityCellRole },
1206 #else
1207         { CellRole, NSAccessibilityGroupRole },
1208 #endif
1209         { TableHeaderContainerRole, NSAccessibilityGroupRole },
1210         { DefinitionListDefinitionRole, NSAccessibilityGroupRole },
1211         { DefinitionListTermRole, NSAccessibilityGroupRole },
1212         { SliderThumbRole, NSAccessibilityValueIndicatorRole },
1213         { LandmarkApplicationRole, NSAccessibilityGroupRole },
1214         { LandmarkBannerRole, NSAccessibilityGroupRole },
1215         { LandmarkComplementaryRole, NSAccessibilityGroupRole },
1216         { LandmarkContentInfoRole, NSAccessibilityGroupRole },
1217         { LandmarkMainRole, NSAccessibilityGroupRole },
1218         { LandmarkNavigationRole, NSAccessibilityGroupRole },
1219         { LandmarkSearchRole, NSAccessibilityGroupRole },
1220         { ApplicationAlertRole, NSAccessibilityGroupRole },
1221         { ApplicationAlertDialogRole, NSAccessibilityGroupRole },
1222         { ApplicationDialogRole, NSAccessibilityGroupRole },
1223         { ApplicationLogRole, NSAccessibilityGroupRole },
1224         { ApplicationMarqueeRole, NSAccessibilityGroupRole },
1225         { ApplicationStatusRole, NSAccessibilityGroupRole },
1226         { ApplicationTimerRole, NSAccessibilityGroupRole },
1227         { DocumentRole, NSAccessibilityGroupRole },
1228         { DocumentArticleRole, NSAccessibilityGroupRole },
1229         { DocumentMathRole, NSAccessibilityGroupRole },
1230         { DocumentNoteRole, NSAccessibilityGroupRole },
1231         { DocumentRegionRole, NSAccessibilityGroupRole },
1232         { UserInterfaceTooltipRole, NSAccessibilityGroupRole },
1233         { TabRole, NSAccessibilityRadioButtonRole },
1234         { TabListRole, NSAccessibilityTabGroupRole },
1235         { TabPanelRole, NSAccessibilityGroupRole },
1236         { TreeRole, NSAccessibilityOutlineRole },
1237         { TreeItemRole, NSAccessibilityRowRole },
1238         { ListItemRole, NSAccessibilityGroupRole }
1239     };
1240     AccessibilityRoleMap& roleMap = *new AccessibilityRoleMap;
1241     
1242     const unsigned numRoles = sizeof(roles) / sizeof(roles[0]);
1243     for (unsigned i = 0; i < numRoles; ++i)
1244         roleMap.set(roles[i].value, roles[i].string);
1245     return roleMap;
1246 }
1247
1248 static NSString* roleValueToNSString(AccessibilityRole value)
1249 {
1250     ASSERT(value);
1251     static const AccessibilityRoleMap& roleMap = createAccessibilityRoleMap();
1252     return roleMap.get(value);
1253 }
1254
1255 - (NSString*)role
1256 {
1257     if (m_object->isAttachment())
1258         return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleAttribute];
1259     NSString* string = roleValueToNSString(m_object->roleValue());
1260     if (string != nil)
1261         return string;
1262     return NSAccessibilityUnknownRole;
1263 }
1264
1265 - (NSString*)subrole
1266 {
1267     if (m_object->isPasswordField())
1268         return NSAccessibilitySecureTextFieldSubrole;
1269     
1270     if (m_object->isAttachment()) {
1271         NSView* attachView = [self attachmentView];
1272         if ([[attachView accessibilityAttributeNames] containsObject:NSAccessibilitySubroleAttribute]) {
1273             return [attachView accessibilityAttributeValue:NSAccessibilitySubroleAttribute];
1274         }
1275     }
1276     
1277     if (m_object->isTreeItem())
1278         return NSAccessibilityOutlineRowSubrole;
1279     
1280     if (m_object->isList()) {
1281         AccessibilityList* listObject = static_cast<AccessibilityList*>(m_object);
1282         if (listObject->isUnorderedList() || listObject->isOrderedList())
1283             return NSAccessibilityContentListSubrole;
1284         if (listObject->isDefinitionList())
1285             return NSAccessibilityDefinitionListSubrole;
1286     }
1287     
1288     // ARIA content subroles.
1289     switch (m_object->roleValue()) {
1290         case LandmarkApplicationRole:
1291             return @"AXLandmarkApplication";
1292         case LandmarkBannerRole:
1293             return @"AXLandmarkBanner";
1294         case LandmarkComplementaryRole:
1295             return @"AXLandmarkComplementary";
1296         case LandmarkContentInfoRole:
1297             return @"AXLandmarkContentInfo";
1298         case LandmarkMainRole:
1299             return @"AXLandmarkMain";
1300         case LandmarkNavigationRole:
1301             return @"AXLandmarkNavigation";
1302         case LandmarkSearchRole:
1303             return @"AXLandmarkSearch";
1304         case ApplicationAlertRole:
1305             return @"AXApplicationAlert";
1306         case ApplicationAlertDialogRole:
1307             return @"AXApplicationAlertDialog";
1308         case ApplicationDialogRole:
1309             return @"AXApplicationDialog";
1310         case ApplicationLogRole:
1311             return @"AXApplicationLog";
1312         case ApplicationMarqueeRole:
1313             return @"AXApplicationMarquee";
1314         case ApplicationStatusRole:
1315             return @"AXApplicationStatus";
1316         case ApplicationTimerRole:
1317             return @"AXApplicationTimer";
1318         case DocumentRole:
1319             return @"AXDocument";
1320         case DocumentArticleRole:
1321             return @"AXDocumentArticle";
1322         case DocumentMathRole:
1323             return @"AXDocumentMath";
1324         case DocumentNoteRole:
1325             return @"AXDocumentNote";
1326         case DocumentRegionRole:
1327             return @"AXDocumentRegion";
1328         case UserInterfaceTooltipRole:
1329             return @"AXUserInterfaceTooltip";
1330         case TabPanelRole:
1331             return @"AXTabPanel";
1332         case DefinitionListTermRole:
1333             return @"AXTerm";
1334         case DefinitionListDefinitionRole:
1335             return @"AXDefinition";
1336         // Default doesn't return anything, so roles defined below can be chosen.
1337         default:
1338             break;
1339     }
1340     
1341     if (m_object->isMediaTimeline())
1342         return NSAccessibilityTimelineSubrole;
1343
1344     return nil;
1345 }
1346
1347 - (NSString*)roleDescription
1348 {
1349     if (!m_object)
1350         return nil;
1351
1352     // attachments have the AXImage role, but a different subrole
1353     if (m_object->isAttachment())
1354         return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleDescriptionAttribute];
1355     
1356     NSString* axRole = [self role];
1357     
1358     if ([axRole isEqualToString:NSAccessibilityGroupRole]) {
1359         switch (m_object->roleValue()) {
1360             default:
1361                 return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, [self subrole]);
1362             case LandmarkApplicationRole:
1363                 return AXARIAContentGroupText(@"ARIALandmarkApplication");
1364             case LandmarkBannerRole:
1365                 return AXARIAContentGroupText(@"ARIALandmarkBanner");
1366             case LandmarkComplementaryRole:
1367                 return AXARIAContentGroupText(@"ARIALandmarkComplementary");
1368             case LandmarkContentInfoRole:
1369                 return AXARIAContentGroupText(@"ARIALandmarkContentInfo");
1370             case LandmarkMainRole:
1371                 return AXARIAContentGroupText(@"ARIALandmarkMain");
1372             case LandmarkNavigationRole:
1373                 return AXARIAContentGroupText(@"ARIALandmarkNavigation");
1374             case LandmarkSearchRole:
1375                 return AXARIAContentGroupText(@"ARIALandmarkSearch");
1376             case ApplicationAlertRole:
1377                 return AXARIAContentGroupText(@"ARIAApplicationAlert");
1378             case ApplicationAlertDialogRole:
1379                 return AXARIAContentGroupText(@"ARIAApplicationAlertDialog");
1380             case ApplicationDialogRole:
1381                 return AXARIAContentGroupText(@"ARIAApplicationDialog");
1382             case ApplicationLogRole:
1383                 return AXARIAContentGroupText(@"ARIAApplicationLog");
1384             case ApplicationMarqueeRole:
1385                 return AXARIAContentGroupText(@"ARIAApplicationMarquee");
1386             case ApplicationStatusRole:
1387                 return AXARIAContentGroupText(@"ARIAApplicationStatus");
1388             case ApplicationTimerRole:
1389                 return AXARIAContentGroupText(@"ARIAApplicationTimer");
1390             case DocumentRole:
1391                 return AXARIAContentGroupText(@"ARIADocument");
1392             case DocumentArticleRole:
1393                 return AXARIAContentGroupText(@"ARIADocumentArticle");
1394             case DocumentMathRole:
1395                 return AXARIAContentGroupText(@"ARIADocumentMath");
1396             case DocumentNoteRole:
1397                 return AXARIAContentGroupText(@"ARIADocumentNote");
1398             case DocumentRegionRole:
1399                 return AXARIAContentGroupText(@"ARIADocumentRegion");
1400             case UserInterfaceTooltipRole:
1401                 return AXARIAContentGroupText(@"ARIAUserInterfaceTooltip");
1402             case TabPanelRole:
1403                 return AXARIAContentGroupText(@"ARIATabPanel");
1404             case DefinitionListTermRole:
1405                 return AXDefinitionListTermText();
1406             case DefinitionListDefinitionRole:
1407                 return AXDefinitionListDefinitionText();
1408         }
1409     }        
1410     
1411     if ([axRole isEqualToString:@"AXWebArea"])
1412         return AXWebAreaText();
1413     
1414     if ([axRole isEqualToString:@"AXLink"])
1415         return AXLinkText();
1416     
1417     if ([axRole isEqualToString:@"AXListMarker"])
1418         return AXListMarkerText();
1419     
1420     if ([axRole isEqualToString:@"AXImageMap"])
1421         return AXImageMapText();
1422
1423     if ([axRole isEqualToString:@"AXHeading"])
1424         return AXHeadingText();
1425
1426     // AppKit also returns AXTab for the role description for a tab item.
1427     if (m_object->isTabItem())
1428         return NSAccessibilityRoleDescription(@"AXTab", nil);
1429     
1430     // We should try the system default role description for all other roles.
1431     // If we get the same string back, then as a last resort, return unknown.
1432     NSString* defaultRoleDescription = NSAccessibilityRoleDescription(axRole, [self subrole]);
1433     if (![defaultRoleDescription isEqualToString:axRole])
1434         return defaultRoleDescription;
1435
1436     return NSAccessibilityRoleDescription(NSAccessibilityUnknownRole, nil);
1437 }
1438
1439 - (id)scrollViewParent
1440 {
1441     if (!m_object || !m_object->isAccessibilityScrollView())
1442         return nil;
1443     
1444     // If this scroll view provides it's parent object (because it's a sub-frame), then
1445     // we should not find the remoteAccessibilityParent.
1446     if (m_object->parentObject())
1447         return nil;
1448     
1449     AccessibilityScrollView* scrollView = toAccessibilityScrollView(m_object);
1450     ScrollView* scroll = scrollView->scrollView();
1451     if (!scroll)
1452         return nil;
1453     
1454     if (scroll->platformWidget())
1455         return scroll->platformWidget();
1456
1457     return [self remoteAccessibilityParentObject];
1458 }
1459
1460 // FIXME: split up this function in a better way.  
1461 // suggestions: Use a hash table that maps attribute names to function calls,
1462 // or maybe pointers to member functions
1463 - (id)accessibilityAttributeValue:(NSString*)attributeName
1464 {
1465     if (![self updateObjectBackingStore])
1466         return nil;
1467     
1468     if ([attributeName isEqualToString: NSAccessibilityRoleAttribute])
1469         return [self role];
1470
1471     if ([attributeName isEqualToString: NSAccessibilitySubroleAttribute])
1472         return [self subrole];
1473
1474     if ([attributeName isEqualToString: NSAccessibilityRoleDescriptionAttribute])
1475         return [self roleDescription];
1476
1477     if ([attributeName isEqualToString: NSAccessibilityParentAttribute]) {
1478
1479         // This will return the parent of the AXWebArea, if this is a web area.
1480         id scrollViewParent = [self scrollViewParent];
1481         if (scrollViewParent)
1482             return scrollViewParent;
1483         
1484         // Tree item (changed to AXRows) can only report the tree (AXOutline) as its parent.
1485         if (m_object->isTreeItem()) {
1486             AccessibilityObject* parent = m_object->parentObjectUnignored();
1487             while (parent) {
1488                 if (parent->isTree())
1489                     return parent->wrapper();
1490                 parent = parent->parentObjectUnignored();
1491             }
1492         }
1493         
1494         AccessibilityObject* parent = m_object->parentObjectUnignored();
1495         if (parent)
1496             return parent->wrapper();
1497         return nil;
1498     }
1499
1500     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
1501         if (m_object->children().isEmpty()) {
1502             NSArray* children = [self renderWidgetChildren];
1503             if (children != nil)
1504                 return children;
1505         }
1506
1507         // The tree's (AXOutline) children are supposed to be its rows and columns.
1508         // The ARIA spec doesn't have columns, so we just need rows.
1509         if (m_object->isTree())
1510             return [self accessibilityAttributeValue:NSAccessibilityRowsAttribute];
1511
1512         // A tree item should only expose its content as its children (not its rows)
1513         if (m_object->isTreeItem()) {
1514             AccessibilityObject::AccessibilityChildrenVector contentCopy;
1515             m_object->ariaTreeItemContent(contentCopy);
1516             return convertToNSArray(contentCopy);
1517         }
1518         
1519         return convertToNSArray(m_object->children());
1520     }
1521     
1522     if ([attributeName isEqualToString: NSAccessibilitySelectedChildrenAttribute]) {
1523         if (m_object->isListBox()) {
1524             AccessibilityObject::AccessibilityChildrenVector selectedChildrenCopy;
1525             m_object->selectedChildren(selectedChildrenCopy);
1526             return convertToNSArray(selectedChildrenCopy);
1527         }
1528         return nil;
1529     }
1530     
1531     if ([attributeName isEqualToString: NSAccessibilityVisibleChildrenAttribute]) {
1532         if (m_object->isListBox()) {
1533             AccessibilityObject::AccessibilityChildrenVector visibleChildrenCopy;
1534             m_object->visibleChildren(visibleChildrenCopy);
1535             return convertToNSArray(visibleChildrenCopy);
1536         }
1537         else if (m_object->isList())
1538             return [self accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
1539
1540         return nil;
1541     }
1542     
1543     
1544     if (m_object->isWebArea()) {
1545         if ([attributeName isEqualToString:@"AXLinkUIElements"]) {
1546             AccessibilityObject::AccessibilityChildrenVector links;
1547             static_cast<AccessibilityRenderObject*>(m_object)->getDocumentLinks(links);
1548             return convertToNSArray(links);
1549         }
1550         if ([attributeName isEqualToString:@"AXLoaded"])
1551             return [NSNumber numberWithBool:m_object->isLoaded()];
1552         if ([attributeName isEqualToString:@"AXLayoutCount"])
1553             return [NSNumber numberWithInt:m_object->layoutCount()];
1554         if ([attributeName isEqualToString:NSAccessibilityLoadingProgressAttribute])
1555             return [NSNumber numberWithDouble:m_object->estimatedLoadingProgress()];
1556     }
1557     
1558     if (m_object->isTextControl()) {
1559         if ([attributeName isEqualToString: NSAccessibilityNumberOfCharactersAttribute]) {
1560             int length = m_object->textLength();
1561             if (length < 0)
1562                 return nil;
1563             return [NSNumber numberWithUnsignedInt:length];
1564         }
1565         if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute]) {
1566             String selectedText = m_object->selectedText();
1567             if (selectedText.isNull())
1568                 return nil;
1569             return (NSString*)selectedText;
1570         }
1571         if ([attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute]) {
1572             PlainTextRange textRange = m_object->selectedTextRange();
1573             if (textRange.isNull())
1574                 return [NSValue valueWithRange:NSMakeRange(0, 0)];
1575             return [NSValue valueWithRange:NSMakeRange(textRange.start, textRange.length)];
1576         }
1577         // TODO: Get actual visible range. <rdar://problem/4712101>
1578         if ([attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute])
1579             return m_object->isPasswordField() ? nil : [NSValue valueWithRange: NSMakeRange(0, m_object->textLength())];
1580         if ([attributeName isEqualToString: NSAccessibilityInsertionPointLineNumberAttribute]) {
1581             // if selectionEnd > 0, then there is selected text and this question should not be answered
1582             if (m_object->isPasswordField() || m_object->selectionEnd() > 0)
1583                 return nil;
1584             int lineNumber = m_object->lineForPosition(m_object->visiblePositionForIndex(m_object->selectionStart(), true));
1585             if (lineNumber < 0)
1586                 return nil;
1587             return [NSNumber numberWithInt:lineNumber];
1588         }
1589     }
1590     
1591     if ([attributeName isEqualToString: NSAccessibilityURLAttribute]) {
1592         KURL url = m_object->url();
1593         if (url.isNull())
1594             return nil;
1595         return (NSURL*)url;
1596     }
1597
1598     if ([attributeName isEqualToString: @"AXVisited"])
1599         return [NSNumber numberWithBool: m_object->isVisited()];
1600     
1601     if ([attributeName isEqualToString: NSAccessibilityTitleAttribute]) {
1602         if (m_object->isAttachment()) {
1603             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityTitleAttribute]) 
1604                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityTitleAttribute];
1605         }
1606         return m_object->title();
1607     }
1608     
1609     if ([attributeName isEqualToString: NSAccessibilityDescriptionAttribute]) {
1610         if (m_object->isAttachment()) {
1611             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityDescriptionAttribute])
1612                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityDescriptionAttribute];
1613         }
1614         return m_object->accessibilityDescription();
1615     }
1616
1617     if ([attributeName isEqualToString: NSAccessibilityValueAttribute]) {
1618         if (m_object->isAttachment()) {
1619             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityValueAttribute]) 
1620                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityValueAttribute];
1621         }
1622         if (m_object->isProgressIndicator() || m_object->isSlider() || m_object->isScrollbar())
1623             return [NSNumber numberWithFloat:m_object->valueForRange()];
1624         if (m_object->roleValue() == SliderThumbRole)
1625             return [NSNumber numberWithFloat:m_object->parentObject()->valueForRange()];
1626         if (m_object->isHeading())
1627             return [NSNumber numberWithInt:m_object->headingLevel()];
1628         
1629         if (m_object->isCheckboxOrRadio()) {
1630             switch (m_object->checkboxOrRadioValue()) {
1631             case ButtonStateOff:
1632                 return [NSNumber numberWithInt:0];
1633             case ButtonStateOn:
1634                 return [NSNumber numberWithInt:1];
1635             case ButtonStateMixed:
1636                 return [NSNumber numberWithInt:2];
1637             }
1638         }
1639
1640         // radio groups return the selected radio button as the AXValue
1641         if (m_object->isRadioGroup()) {
1642             AccessibilityObject* radioButton = m_object->selectedRadioButton();
1643             if (!radioButton)
1644                 return nil;
1645             return radioButton->wrapper();
1646         }
1647         
1648         if (m_object->isTabList()) {
1649             AccessibilityObject* tabItem = m_object->selectedTabItem();
1650             if (!tabItem)
1651                 return nil;
1652             return tabItem->wrapper();
1653         }
1654         
1655         if (m_object->isTabItem())
1656             return [NSNumber numberWithInt:m_object->isSelected()];
1657         
1658         return m_object->stringValue();
1659     }
1660
1661     if ([attributeName isEqualToString: NSAccessibilityMinValueAttribute])
1662         return [NSNumber numberWithFloat:m_object->minValueForRange()];
1663
1664     if ([attributeName isEqualToString: NSAccessibilityMaxValueAttribute])
1665         return [NSNumber numberWithFloat:m_object->maxValueForRange()];
1666
1667     if ([attributeName isEqualToString: NSAccessibilityHelpAttribute])
1668         return m_object->helpText();
1669
1670     if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute])
1671         return [NSNumber numberWithBool: m_object->isFocused()];
1672
1673     if ([attributeName isEqualToString: NSAccessibilityEnabledAttribute])
1674         return [NSNumber numberWithBool: m_object->isEnabled()];
1675
1676     if ([attributeName isEqualToString: NSAccessibilitySizeAttribute]) {
1677         IntSize s = m_object->size();
1678         return [NSValue valueWithSize: NSMakeSize(s.width(), s.height())];
1679     }
1680
1681     if ([attributeName isEqualToString: NSAccessibilityPositionAttribute])
1682         return [self position];
1683
1684     if ([attributeName isEqualToString: NSAccessibilityWindowAttribute] ||
1685         [attributeName isEqualToString: NSAccessibilityTopLevelUIElementAttribute]) {
1686         
1687         id remoteParent = [self remoteAccessibilityParentObject];
1688         if (remoteParent)
1689             return [remoteParent accessibilityAttributeValue:attributeName];
1690         
1691         FrameView* fv = m_object->documentFrameView();
1692         if (fv)
1693             return [fv->platformWidget() window];
1694         return nil;
1695     }
1696     
1697     if ([attributeName isEqualToString:NSAccessibilityAccessKeyAttribute]) {
1698         AtomicString accessKey = m_object->accessKey();
1699         if (accessKey.isNull())
1700             return nil;
1701         return accessKey;
1702     }
1703     
1704     if ([attributeName isEqualToString:NSAccessibilityTabsAttribute]) {
1705         if (m_object->isTabList()) {
1706             AccessibilityObject::AccessibilityChildrenVector tabsChildren;
1707             m_object->tabChildren(tabsChildren);
1708             return convertToNSArray(tabsChildren);
1709         }
1710     }
1711     
1712     if ([attributeName isEqualToString:NSAccessibilityContentsAttribute]) {
1713         // The contents of a tab list are all the children except the tabs.
1714         if (m_object->isTabList()) {
1715             AccessibilityObject::AccessibilityChildrenVector children = m_object->children();
1716             AccessibilityObject::AccessibilityChildrenVector tabsChildren;
1717             m_object->tabChildren(tabsChildren);
1718
1719             AccessibilityObject::AccessibilityChildrenVector contents;
1720             unsigned childrenSize = children.size();
1721             for (unsigned k = 0; k < childrenSize; ++k) {
1722                 if (tabsChildren.find(children[k]) == WTF::notFound)
1723                     contents.append(children[k]);
1724             }
1725             return convertToNSArray(contents);
1726         } else if (m_object->isScrollView()) {
1727             AccessibilityObject::AccessibilityChildrenVector children = m_object->children();
1728             
1729             // A scrollView's contents are everything except the scroll bars.
1730             AccessibilityObject::AccessibilityChildrenVector contents;
1731             unsigned childrenSize = children.size();
1732             for (unsigned k = 0; k < childrenSize; ++k) {
1733                 if (!children[k]->isScrollbar())
1734                     contents.append(children[k]);
1735             }
1736             return convertToNSArray(contents);            
1737         }
1738     }    
1739     
1740     if (m_object->isAccessibilityTable()) {
1741         // TODO: distinguish between visible and non-visible rows
1742         if ([attributeName isEqualToString:NSAccessibilityRowsAttribute] || 
1743             [attributeName isEqualToString:NSAccessibilityVisibleRowsAttribute]) {
1744             return convertToNSArray(static_cast<AccessibilityTable*>(m_object)->rows());
1745         }
1746         // TODO: distinguish between visible and non-visible columns
1747         if ([attributeName isEqualToString:NSAccessibilityColumnsAttribute] || 
1748             [attributeName isEqualToString:NSAccessibilityVisibleColumnsAttribute]) {
1749             return convertToNSArray(static_cast<AccessibilityTable*>(m_object)->columns());
1750         }
1751         
1752         if ([attributeName isEqualToString:NSAccessibilitySelectedRowsAttribute]) {
1753             AccessibilityObject::AccessibilityChildrenVector selectedChildrenCopy;
1754             m_object->selectedChildren(selectedChildrenCopy);
1755             return convertToNSArray(selectedChildrenCopy);
1756         }
1757         
1758         // HTML tables don't support these
1759         if ([attributeName isEqualToString:NSAccessibilitySelectedColumnsAttribute] || 
1760             [attributeName isEqualToString:NSAccessibilitySelectedCellsAttribute])
1761             return nil;
1762         
1763         if ([attributeName isEqualToString:(NSString *)kAXColumnHeaderUIElementsAttribute]) {
1764             AccessibilityObject::AccessibilityChildrenVector columnHeaders;
1765             static_cast<AccessibilityTable*>(m_object)->columnHeaders(columnHeaders);
1766             return convertToNSArray(columnHeaders);            
1767         }
1768         
1769         if ([attributeName isEqualToString:NSAccessibilityHeaderAttribute]) {
1770             AccessibilityObject* headerContainer = static_cast<AccessibilityTable*>(m_object)->headerContainer();
1771             if (headerContainer)
1772                 return headerContainer->wrapper();
1773             return nil;
1774         }
1775
1776         if ([attributeName isEqualToString:NSAccessibilityRowHeaderUIElementsAttribute]) {
1777             AccessibilityObject::AccessibilityChildrenVector rowHeaders;
1778             static_cast<AccessibilityTable*>(m_object)->rowHeaders(rowHeaders);
1779             return convertToNSArray(rowHeaders);                        
1780         }
1781         
1782         if ([attributeName isEqualToString:NSAccessibilityVisibleCellsAttribute]) {
1783             AccessibilityObject::AccessibilityChildrenVector cells;
1784             static_cast<AccessibilityTable*>(m_object)->cells(cells);
1785             return convertToNSArray(cells);
1786         }        
1787     }
1788     
1789     if (m_object->isTableColumn()) {
1790         if ([attributeName isEqualToString:NSAccessibilityIndexAttribute])
1791             return [NSNumber numberWithInt:static_cast<AccessibilityTableColumn*>(m_object)->columnIndex()];
1792         
1793         // rows attribute for a column is the list of all the elements in that column at each row
1794         if ([attributeName isEqualToString:NSAccessibilityRowsAttribute] || 
1795             [attributeName isEqualToString:NSAccessibilityVisibleRowsAttribute]) {
1796             return convertToNSArray(static_cast<AccessibilityTableColumn*>(m_object)->children());
1797         }
1798         if ([attributeName isEqualToString:NSAccessibilityHeaderAttribute]) {
1799             AccessibilityObject* header = static_cast<AccessibilityTableColumn*>(m_object)->headerObject();
1800             if (!header)
1801                 return nil;
1802             return header->wrapper();
1803         }
1804     }
1805     
1806     if (m_object->isTableCell()) {
1807         if ([attributeName isEqualToString:NSAccessibilityRowIndexRangeAttribute]) {
1808             pair<int, int> rowRange;
1809             static_cast<AccessibilityTableCell*>(m_object)->rowIndexRange(rowRange);
1810             return [NSValue valueWithRange:NSMakeRange(rowRange.first, rowRange.second)];
1811         }  
1812         if ([attributeName isEqualToString:NSAccessibilityColumnIndexRangeAttribute]) {
1813             pair<int, int> columnRange;
1814             static_cast<AccessibilityTableCell*>(m_object)->columnIndexRange(columnRange);
1815             return [NSValue valueWithRange:NSMakeRange(columnRange.first, columnRange.second)];
1816         }  
1817     }
1818     
1819     if (m_object->isTree()) {
1820         if ([attributeName isEqualToString:NSAccessibilitySelectedRowsAttribute]) {
1821             AccessibilityObject::AccessibilityChildrenVector selectedChildrenCopy;
1822             m_object->selectedChildren(selectedChildrenCopy);
1823             return convertToNSArray(selectedChildrenCopy);
1824         }
1825         if ([attributeName isEqualToString:NSAccessibilityRowsAttribute]) {
1826             AccessibilityObject::AccessibilityChildrenVector rowsCopy;
1827             m_object->ariaTreeRows(rowsCopy);
1828             return convertToNSArray(rowsCopy);            
1829         }
1830         
1831         // TreeRoles do not support columns, but Mac AX expects to be able to ask about columns at the least.
1832         if ([attributeName isEqualToString:NSAccessibilityColumnsAttribute])
1833             return [NSArray array];
1834     }
1835
1836     if ([attributeName isEqualToString:NSAccessibilityIndexAttribute]) {
1837         if (m_object->isTreeItem()) {
1838             AccessibilityObject* parent = m_object->parentObject();
1839             for (; parent && !parent->isTree(); parent = parent->parentObject())
1840             { }
1841             
1842             if (!parent)
1843                 return nil;
1844             
1845             // Find the index of this item by iterating the parents.
1846             AccessibilityObject::AccessibilityChildrenVector rowsCopy;
1847             parent->ariaTreeRows(rowsCopy);
1848             size_t count = rowsCopy.size();
1849             for (size_t k = 0; k < count; ++k)
1850                 if (rowsCopy[k]->wrapper() == self)
1851                     return [NSNumber numberWithUnsignedInt:k];
1852             
1853             return nil;
1854         }
1855         if (m_object->isTableRow()) {
1856             if ([attributeName isEqualToString:NSAccessibilityIndexAttribute])
1857                 return [NSNumber numberWithInt:static_cast<AccessibilityTableRow*>(m_object)->rowIndex()];
1858         }
1859     }    
1860     
1861     // The rows that are considered inside this row. 
1862     if ([attributeName isEqualToString:NSAccessibilityDisclosedRowsAttribute]) {
1863         if (m_object->isTreeItem()) {
1864             AccessibilityObject::AccessibilityChildrenVector rowsCopy;
1865             m_object->ariaTreeItemDisclosedRows(rowsCopy);
1866             return convertToNSArray(rowsCopy);    
1867         } else if (m_object->isARIATreeGridRow()) {
1868             AccessibilityObject::AccessibilityChildrenVector rowsCopy;
1869             static_cast<AccessibilityARIAGridRow*>(m_object)->disclosedRows(rowsCopy);
1870             return convertToNSArray(rowsCopy);    
1871         }
1872     }
1873     
1874     // The row that contains this row. It should be the same as the first parent that is a treeitem.
1875     if ([attributeName isEqualToString:NSAccessibilityDisclosedByRowAttribute]) {
1876         if (m_object->isTreeItem()) {
1877             AccessibilityObject* parent = m_object->parentObject();
1878             while (parent) {
1879                 if (parent->isTreeItem())
1880                     return parent->wrapper();
1881                 // If the parent is the tree itself, then this value == nil.
1882                 if (parent->isTree())
1883                     return nil;
1884                 parent = parent->parentObject();
1885             }
1886             return nil;
1887         } else if (m_object->isARIATreeGridRow()) {
1888             AccessibilityObject* row = static_cast<AccessibilityARIAGridRow*>(m_object)->disclosedByRow();
1889             if (!row)
1890                 return nil;
1891             return row->wrapper();
1892         }
1893     }
1894
1895     if ([attributeName isEqualToString:NSAccessibilityDisclosureLevelAttribute])
1896         return [NSNumber numberWithInt:m_object->hierarchicalLevel()];
1897     if ([attributeName isEqualToString:NSAccessibilityDisclosingAttribute])
1898         return [NSNumber numberWithBool:m_object->isExpanded()];
1899     
1900     if ((m_object->isListBox() || m_object->isList()) && [attributeName isEqualToString:NSAccessibilityOrientationAttribute])
1901         return NSAccessibilityVerticalOrientationValue;
1902
1903     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"])
1904         return [self textMarkerRangeForSelection];
1905     
1906     if (m_object->isAccessibilityRenderObject()) {
1907         RenderObject* renderer = static_cast<AccessibilityRenderObject*>(m_object)->renderer();
1908         if (!renderer)
1909             return nil;
1910         
1911         if ([attributeName isEqualToString: @"AXStartTextMarker"])
1912             return [self textMarkerForVisiblePosition:startOfDocument(renderer->document())];
1913         if ([attributeName isEqualToString: @"AXEndTextMarker"])
1914             return [self textMarkerForVisiblePosition:endOfDocument(renderer->document())];
1915
1916         if ([attributeName isEqualToString:NSAccessibilityBlockQuoteLevelAttribute])
1917             return [NSNumber numberWithInt:blockquoteLevel(renderer)];
1918     } else {
1919         if ([attributeName isEqualToString:NSAccessibilityBlockQuoteLevelAttribute]) {
1920             AccessibilityObject* parent = m_object->parentObjectUnignored();
1921             if (!parent)
1922                 return [NSNumber numberWithInt:0];
1923             return [parent->wrapper() accessibilityAttributeValue:NSAccessibilityBlockQuoteLevelAttribute];        
1924         }
1925     }
1926     
1927     if ([attributeName isEqualToString: NSAccessibilityLinkedUIElementsAttribute]) {
1928         AccessibilityObject::AccessibilityChildrenVector linkedUIElements;
1929         m_object->linkedUIElements(linkedUIElements);
1930         if (linkedUIElements.size() == 0)
1931             return nil;
1932         return convertToNSArray(linkedUIElements);
1933     }
1934
1935     if ([attributeName isEqualToString: NSAccessibilitySelectedAttribute])
1936         return [NSNumber numberWithBool:m_object->isSelected()];
1937
1938     if ([attributeName isEqualToString: NSAccessibilityServesAsTitleForUIElementsAttribute] && m_object->isMenuButton()) {
1939         AccessibilityObject* uiElement = static_cast<AccessibilityRenderObject*>(m_object)->menuForMenuButton();
1940         if (uiElement)
1941             return [NSArray arrayWithObject:uiElement->wrapper()];
1942     }
1943
1944     if ([attributeName isEqualToString:NSAccessibilityTitleUIElementAttribute]) {
1945         AccessibilityObject* obj = m_object->titleUIElement();
1946         if (obj)
1947             return obj->wrapper();
1948         return nil;
1949     }
1950     
1951     if ([attributeName isEqualToString:NSAccessibilityValueDescriptionAttribute])
1952         return m_object->valueDescription();
1953     
1954     if ([attributeName isEqualToString:NSAccessibilityOrientationAttribute]) {
1955         AccessibilityOrientation elementOrientation = m_object->orientation();
1956         if (elementOrientation == AccessibilityOrientationVertical)
1957             return NSAccessibilityVerticalOrientationValue;
1958         if (elementOrientation == AccessibilityOrientationHorizontal)
1959             return NSAccessibilityHorizontalOrientationValue;
1960         return nil;
1961     }
1962     
1963     if ([attributeName isEqualToString:NSAccessibilityHorizontalScrollBarAttribute]) {
1964         AccessibilityObject* scrollBar = m_object->scrollBar(AccessibilityOrientationHorizontal);
1965         if (scrollBar)
1966             return scrollBar->wrapper();
1967         return nil;
1968     }
1969     if ([attributeName isEqualToString:NSAccessibilityVerticalScrollBarAttribute]) {
1970         AccessibilityObject* scrollBar = m_object->scrollBar(AccessibilityOrientationVertical);
1971         if (scrollBar)
1972             return scrollBar->wrapper();
1973         return nil;
1974     }
1975     
1976     if ([attributeName isEqualToString:NSAccessibilityLanguageAttribute]) 
1977         return m_object->language();
1978     
1979     if ([attributeName isEqualToString:NSAccessibilityExpandedAttribute])
1980         return [NSNumber numberWithBool:m_object->isExpanded()];
1981     
1982     if ([attributeName isEqualToString:NSAccessibilityRequiredAttribute])
1983         return [NSNumber numberWithBool:m_object->isRequired()];
1984
1985     if ([attributeName isEqualToString:NSAccessibilityInvalidAttribute])
1986         return m_object->invalidStatus();
1987     
1988     if ([attributeName isEqualToString:NSAccessibilityOwnsAttribute]) {
1989         AccessibilityObject::AccessibilityChildrenVector ariaOwns;
1990         m_object->ariaOwnsElements(ariaOwns);
1991         return convertToNSArray(ariaOwns);
1992     }
1993     
1994     if ([attributeName isEqualToString:NSAccessibilityGrabbedAttribute])
1995         return [NSNumber numberWithBool:m_object->isARIAGrabbed()];
1996     
1997     if ([attributeName isEqualToString:NSAccessibilityDropEffectsAttribute]) {
1998         Vector<String> dropEffects;
1999         m_object->determineARIADropEffects(dropEffects);
2000         size_t length = dropEffects.size();
2001
2002         NSMutableArray* dropEffectsArray = [NSMutableArray arrayWithCapacity:length];
2003         for (size_t i = 0; i < length; ++i)
2004             [dropEffectsArray addObject:dropEffects[i]];
2005         return dropEffectsArray;
2006     }
2007     
2008     if ([attributeName isEqualToString:NSAccessibilityPlaceholderValueAttribute])
2009         return m_object->placeholderValue();
2010     
2011     if ([attributeName isEqualToString:NSAccessibilityHasPopupAttribute])
2012         return [NSNumber numberWithBool:m_object->ariaHasPopup()];
2013     
2014     // ARIA Live region attributes.
2015     if ([attributeName isEqualToString:NSAccessibilityARIALiveAttribute])
2016         return m_object->ariaLiveRegionStatus();
2017     if ([attributeName isEqualToString:NSAccessibilityARIARelevantAttribute])
2018          return m_object->ariaLiveRegionRelevant();
2019     if ([attributeName isEqualToString:NSAccessibilityARIAAtomicAttribute])
2020         return [NSNumber numberWithBool:m_object->ariaLiveRegionAtomic()];
2021     if ([attributeName isEqualToString:NSAccessibilityARIABusyAttribute])
2022         return [NSNumber numberWithBool:m_object->ariaLiveRegionBusy()];
2023     
2024     // this is used only by DumpRenderTree for testing
2025     if ([attributeName isEqualToString:@"AXClickPoint"])
2026         return [NSValue valueWithPoint:m_object->clickPoint()];
2027     
2028     // This is used by DRT to verify CSS3 speech works.
2029     if ([attributeName isEqualToString:@"AXDRTSpeechAttribute"]) {
2030         ESpeak speakProperty = m_object->speakProperty();
2031         switch (speakProperty) {
2032         case SpeakNone:
2033             return @"none";
2034         case SpeakSpellOut:
2035             return @"spell-out";
2036         case SpeakDigits:
2037             return @"digits";
2038         case SpeakLiteralPunctuation:
2039             return @"literal-punctuation";
2040         case SpeakNoPunctuation:
2041             return @"no-punctuation";
2042         default:
2043         case SpeakNormal:
2044             return @"normal";
2045         }
2046     }
2047     
2048     return nil;
2049 }
2050
2051 - (id)accessibilityFocusedUIElement
2052 {
2053     if (![self updateObjectBackingStore])
2054         return nil;
2055
2056     RefPtr<AccessibilityObject> focusedObj = m_object->focusedUIElement();
2057
2058     if (!focusedObj)
2059         return nil;
2060     
2061     return focusedObj->wrapper();
2062 }
2063
2064 - (id)accessibilityHitTest:(NSPoint)point
2065 {
2066     if (![self updateObjectBackingStore])
2067         return nil;
2068
2069     m_object->updateChildrenIfNecessary();
2070     RefPtr<AccessibilityObject> axObject = m_object->accessibilityHitTest(IntPoint(point));
2071     if (axObject)
2072         return NSAccessibilityUnignoredAncestor(axObject->wrapper());
2073     return NSAccessibilityUnignoredAncestor(self);
2074 }
2075
2076 - (BOOL)accessibilityIsAttributeSettable:(NSString*)attributeName
2077 {
2078     if (![self updateObjectBackingStore])
2079         return nil;
2080
2081     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"])
2082         return YES;
2083
2084     if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute])
2085         return m_object->canSetFocusAttribute();
2086
2087     if ([attributeName isEqualToString: NSAccessibilityValueAttribute])
2088         return m_object->canSetValueAttribute();
2089
2090     if ([attributeName isEqualToString: NSAccessibilitySelectedAttribute])
2091         return m_object->canSetSelectedAttribute();
2092     
2093     if ([attributeName isEqualToString: NSAccessibilitySelectedChildrenAttribute])
2094         return m_object->canSetSelectedChildrenAttribute();
2095
2096     if ([attributeName isEqualToString:NSAccessibilityDisclosingAttribute])
2097         return m_object->canSetExpandedAttribute();
2098
2099     if ([attributeName isEqualToString:NSAccessibilitySelectedRowsAttribute])
2100         return YES;
2101
2102     if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute] ||
2103         [attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute] ||
2104         [attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute])
2105         return m_object->canSetTextRangeAttributes();
2106     
2107     if ([attributeName isEqualToString:NSAccessibilityGrabbedAttribute])
2108         return YES;
2109     
2110     return NO;
2111 }
2112
2113 // accessibilityShouldUseUniqueId is an AppKit method we override so that
2114 // objects will be given a unique ID, and therefore allow AppKit to know when they
2115 // become obsolete (e.g. when the user navigates to a new web page, making this one
2116 // unrendered but not deallocated because it is in the back/forward cache).
2117 // It is important to call NSAccessibilityUnregisterUniqueIdForUIElement in the
2118 // appropriate place (e.g. dealloc) to remove these non-retained references from
2119 // AppKit's id mapping tables. We do this in detach by calling unregisterUniqueIdForUIElement.
2120 //
2121 // Registering an object is also required for observing notifications. Only registered objects can be observed.
2122 - (BOOL)accessibilityIsIgnored
2123 {
2124     if (![self updateObjectBackingStore])
2125         return YES;
2126
2127     if (m_object->isAttachment())
2128         return [[self attachmentView] accessibilityIsIgnored];
2129     return m_object->accessibilityIsIgnored();
2130 }
2131
2132 - (NSArray* )accessibilityParameterizedAttributeNames
2133 {
2134     if (![self updateObjectBackingStore])
2135         return nil;
2136
2137     if (m_object->isAttachment()) 
2138         return nil;
2139
2140     static NSArray* paramAttrs = nil;
2141     static NSArray* textParamAttrs = nil;
2142     static NSArray* tableParamAttrs = nil;
2143     if (paramAttrs == nil) {
2144         paramAttrs = [[NSArray alloc] initWithObjects:
2145                       @"AXUIElementForTextMarker",
2146                       @"AXTextMarkerRangeForUIElement",
2147                       @"AXLineForTextMarker",
2148                       @"AXTextMarkerRangeForLine",
2149                       @"AXStringForTextMarkerRange",
2150                       @"AXTextMarkerForPosition",
2151                       @"AXBoundsForTextMarkerRange",
2152                       @"AXAttributedStringForTextMarkerRange",
2153                       @"AXTextMarkerRangeForUnorderedTextMarkers",
2154                       @"AXNextTextMarkerForTextMarker",
2155                       @"AXPreviousTextMarkerForTextMarker",
2156                       @"AXLeftWordTextMarkerRangeForTextMarker",
2157                       @"AXRightWordTextMarkerRangeForTextMarker",
2158                       @"AXLeftLineTextMarkerRangeForTextMarker",
2159                       @"AXRightLineTextMarkerRangeForTextMarker",
2160                       @"AXSentenceTextMarkerRangeForTextMarker",
2161                       @"AXParagraphTextMarkerRangeForTextMarker",
2162                       @"AXNextWordEndTextMarkerForTextMarker",
2163                       @"AXPreviousWordStartTextMarkerForTextMarker",
2164                       @"AXNextLineEndTextMarkerForTextMarker",
2165                       @"AXPreviousLineStartTextMarkerForTextMarker",
2166                       @"AXNextSentenceEndTextMarkerForTextMarker",
2167                       @"AXPreviousSentenceStartTextMarkerForTextMarker",
2168                       @"AXNextParagraphEndTextMarkerForTextMarker",
2169                       @"AXPreviousParagraphStartTextMarkerForTextMarker",
2170                       @"AXStyleTextMarkerRangeForTextMarker",
2171                       @"AXLengthForTextMarkerRange",
2172                       NSAccessibilityBoundsForRangeParameterizedAttribute,
2173                       NSAccessibilityStringForRangeParameterizedAttribute,
2174                       nil];
2175     }
2176
2177     if (textParamAttrs == nil) {
2178         NSMutableArray* tempArray = [[NSMutableArray alloc] initWithArray:paramAttrs];
2179         [tempArray addObject:(NSString*)kAXLineForIndexParameterizedAttribute];
2180         [tempArray addObject:(NSString*)kAXRangeForLineParameterizedAttribute];
2181         [tempArray addObject:(NSString*)kAXStringForRangeParameterizedAttribute];
2182         [tempArray addObject:(NSString*)kAXRangeForPositionParameterizedAttribute];
2183         [tempArray addObject:(NSString*)kAXRangeForIndexParameterizedAttribute];
2184         [tempArray addObject:(NSString*)kAXBoundsForRangeParameterizedAttribute];
2185         [tempArray addObject:(NSString*)kAXRTFForRangeParameterizedAttribute];
2186         [tempArray addObject:(NSString*)kAXAttributedStringForRangeParameterizedAttribute];
2187         [tempArray addObject:(NSString*)kAXStyleRangeForIndexParameterizedAttribute];
2188         textParamAttrs = [[NSArray alloc] initWithArray:tempArray];
2189         [tempArray release];
2190     }
2191     if (tableParamAttrs == nil) {
2192         NSMutableArray* tempArray = [[NSMutableArray alloc] initWithArray:paramAttrs];
2193         [tempArray addObject:NSAccessibilityCellForColumnAndRowParameterizedAttribute];
2194         tableParamAttrs = [[NSArray alloc] initWithArray:tempArray];
2195         [tempArray release];
2196     }
2197     
2198     if (m_object->isPasswordField())
2199         return [NSArray array];
2200     
2201     if (!m_object->isAccessibilityRenderObject())
2202         return paramAttrs;
2203
2204     if (m_object->isTextControl())
2205         return textParamAttrs;
2206     
2207     if (m_object->isAccessibilityTable())
2208         return tableParamAttrs;
2209     
2210     if (m_object->isMenuRelated())
2211         return nil;
2212
2213     return paramAttrs;
2214 }
2215
2216 - (void)accessibilityPerformPressAction
2217 {
2218     if (![self updateObjectBackingStore])
2219         return;
2220
2221     if (m_object->isAttachment())
2222         [[self attachmentView] accessibilityPerformAction:NSAccessibilityPressAction];
2223     else
2224         m_object->press();    
2225 }
2226
2227 - (void)accessibilityPerformIncrementAction
2228 {
2229     if (![self updateObjectBackingStore])
2230         return;
2231
2232     if (m_object->isAttachment())
2233         [[self attachmentView] accessibilityPerformAction:NSAccessibilityIncrementAction];
2234     else
2235         m_object->increment();    
2236 }
2237
2238 - (void)accessibilityPerformDecrementAction
2239 {
2240     if (![self updateObjectBackingStore])
2241         return;
2242
2243     if (m_object->isAttachment())
2244         [[self attachmentView] accessibilityPerformAction:NSAccessibilityDecrementAction];
2245     else
2246         m_object->decrement();    
2247 }
2248
2249 - (void)accessibilityPerformShowMenuAction
2250 {
2251     if (m_object->roleValue() == ComboBoxRole)
2252         m_object->setIsExpanded(true);
2253     else {
2254         // This needs to be performed in an iteration of the run loop that did not start from an AX call. 
2255         // If it's the same run loop iteration, the menu open notification won't be sent
2256         [self performSelector:@selector(accessibilityShowContextMenu) withObject:nil afterDelay:0.0];
2257     }
2258 }
2259
2260 - (void)accessibilityShowContextMenu
2261 {    
2262     FrameView* frameView = m_object->documentFrameView();
2263     if (!frameView)
2264         return;
2265
2266     // simulate a click in the middle of the object
2267     IntPoint clickPoint = m_object->clickPoint();
2268     NSPoint nsClickPoint = NSMakePoint(clickPoint.x(), clickPoint.y());
2269     
2270     NSView* view = nil;
2271     if (m_object->isAttachment())
2272         view = [self attachmentView];
2273     else
2274         view = frameView->documentView();
2275     
2276     if (!view)
2277         return;
2278     
2279     NSPoint nsScreenPoint = [view convertPoint:nsClickPoint toView:nil];
2280     
2281     // Show the contextual menu for this event.
2282     NSEvent* event = [NSEvent mouseEventWithType:NSRightMouseDown location:nsScreenPoint modifierFlags:0 timestamp:0 windowNumber:[[view window] windowNumber] context:0 eventNumber:0 clickCount:1 pressure:1];
2283     NSMenu* menu = [view menuForEvent:event];
2284     
2285     if (menu)
2286         [NSMenu popUpContextMenu:menu withEvent:event forView:view];    
2287 }
2288
2289 - (void)accessibilityPerformAction:(NSString*)action
2290 {
2291     if (![self updateObjectBackingStore])
2292         return;
2293
2294     if ([action isEqualToString:NSAccessibilityPressAction])
2295         [self accessibilityPerformPressAction];
2296     
2297     else if ([action isEqualToString:NSAccessibilityShowMenuAction])
2298         [self accessibilityPerformShowMenuAction];
2299
2300     else if ([action isEqualToString:NSAccessibilityIncrementAction])
2301         [self accessibilityPerformIncrementAction];
2302
2303     else if ([action isEqualToString:NSAccessibilityDecrementAction])
2304         [self accessibilityPerformDecrementAction];
2305 }
2306
2307 - (void)accessibilitySetValue:(id)value forAttribute:(NSString*)attributeName
2308 {
2309     if (![self updateObjectBackingStore])
2310         return;
2311
2312     WebCoreTextMarkerRange* textMarkerRange = nil;
2313     NSNumber*               number = nil;
2314     NSString*               string = nil;
2315     NSRange                 range = {0, 0};
2316     NSArray*                array = nil;
2317     
2318     // decode the parameter
2319     if ([[WebCoreViewFactory sharedFactory] objectIsTextMarkerRange:value])
2320         textMarkerRange = (WebCoreTextMarkerRange*) value;
2321
2322     else if ([value isKindOfClass:[NSNumber self]])
2323         number = value;
2324
2325     else if ([value isKindOfClass:[NSString self]])
2326         string = value;
2327     
2328     else if ([value isKindOfClass:[NSValue self]])
2329         range = [value rangeValue];
2330     
2331     else if ([value isKindOfClass:[NSArray self]])
2332         array = value;
2333     
2334     // handle the command
2335     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"]) {
2336         ASSERT(textMarkerRange);
2337         m_object->setSelectedVisiblePositionRange([self visiblePositionRangeForTextMarkerRange:textMarkerRange]);        
2338     } else if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute]) {
2339         ASSERT(number);
2340         m_object->setFocused([number intValue] != 0);
2341     } else if ([attributeName isEqualToString: NSAccessibilityValueAttribute]) {
2342         if (number && m_object->canSetNumericValue())
2343             m_object->setValue([number floatValue]);
2344         else if (string)
2345             m_object->setValue(string);
2346     } else if ([attributeName isEqualToString: NSAccessibilitySelectedAttribute]) {
2347         if (!number)
2348             return;
2349         m_object->setSelected([number boolValue]);
2350     } else if ([attributeName isEqualToString: NSAccessibilitySelectedChildrenAttribute]) {
2351         if (!array || m_object->roleValue() != ListBoxRole)
2352             return;
2353         AccessibilityObject::AccessibilityChildrenVector selectedChildren;
2354         convertToVector(array, selectedChildren);
2355         static_cast<AccessibilityListBox*>(m_object)->setSelectedChildren(selectedChildren);
2356     } else if (m_object->isTextControl()) {
2357         if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute]) {
2358             m_object->setSelectedText(string);
2359         } else if ([attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute]) {
2360             m_object->setSelectedTextRange(PlainTextRange(range.location, range.length));
2361         } else if ([attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute]) {
2362             m_object->makeRangeVisible(PlainTextRange(range.location, range.length));
2363         }
2364     } else if ([attributeName isEqualToString:NSAccessibilityDisclosingAttribute])
2365         m_object->setIsExpanded([number boolValue]);
2366     else if ([attributeName isEqualToString:NSAccessibilitySelectedRowsAttribute]) {
2367         AccessibilityObject::AccessibilityChildrenVector selectedRows;
2368         convertToVector(array, selectedRows);
2369         if (m_object->isTree() || m_object->isAccessibilityTable())
2370             m_object->setSelectedRows(selectedRows);
2371     } else if ([attributeName isEqualToString:NSAccessibilityGrabbedAttribute])
2372         m_object->setARIAGrabbed([number boolValue]);
2373 }
2374
2375 static RenderObject* rendererForView(NSView* view)
2376 {
2377     if (![view conformsToProtocol:@protocol(WebCoreFrameView)])
2378         return 0;
2379
2380     NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view;
2381     Frame* frame = [frameView _web_frame];
2382     if (!frame)
2383         return 0;
2384
2385     Node* node = frame->document()->ownerElement();
2386     if (!node)
2387         return 0;
2388
2389     return node->renderer();
2390 }
2391
2392 - (id)_accessibilityParentForSubview:(NSView*)subview
2393 {   
2394     RenderObject* renderer = rendererForView(subview);
2395     if (!renderer)
2396         return nil;
2397
2398     AccessibilityObject* obj = renderer->document()->axObjectCache()->getOrCreate(renderer);
2399     if (obj)
2400         return obj->parentObjectUnignored()->wrapper();
2401     return nil;
2402 }
2403
2404 - (NSString*)accessibilityActionDescription:(NSString*)action
2405 {
2406     // we have no custom actions
2407     return NSAccessibilityActionDescription(action);
2408 }
2409
2410 // The CFAttributedStringType representation of the text associated with this accessibility
2411 // object that is specified by the given range.
2412 - (NSAttributedString*)doAXAttributedStringForRange:(NSRange)range
2413 {
2414     PlainTextRange textRange = PlainTextRange(range.location, range.length);
2415     VisiblePositionRange visiblePosRange = m_object->visiblePositionRangeForRange(textRange);
2416     return [self doAXAttributedStringForTextMarkerRange:[self textMarkerRangeFromVisiblePositions:visiblePosRange.start endPosition:visiblePosRange.end]];
2417 }
2418
2419 // The RTF representation of the text associated with this accessibility object that is
2420 // specified by the given range.
2421 - (NSData*)doAXRTFForRange:(NSRange)range
2422 {
2423     NSAttributedString* attrString = [self doAXAttributedStringForRange:range];
2424     return [attrString RTFFromRange: NSMakeRange(0, [attrString length]) documentAttributes: nil];
2425 }
2426
2427 - (id)accessibilityAttributeValue:(NSString*)attribute forParameter:(id)parameter
2428 {
2429     WebCoreTextMarker* textMarker = nil;
2430     WebCoreTextMarkerRange* textMarkerRange = nil;
2431     NSNumber* number = nil;
2432     NSArray* array = nil;
2433     RefPtr<AccessibilityObject> uiElement = 0;
2434     NSPoint point = NSZeroPoint;
2435     bool pointSet = false;
2436     NSRange range = {0, 0};
2437     bool rangeSet = false;
2438     
2439     // basic parameter validation
2440     if (!m_object || !attribute || !parameter)
2441         return nil;
2442
2443     if (![self updateObjectBackingStore])
2444         return nil;
2445     
2446     // common parameter type check/casting.  Nil checks in handlers catch wrong type case.
2447     // NOTE: This assumes nil is not a valid parameter, because it is indistinguishable from
2448     // a parameter of the wrong type.
2449     if ([[WebCoreViewFactory sharedFactory] objectIsTextMarker:parameter])
2450         textMarker = (WebCoreTextMarker*) parameter;
2451
2452     else if ([[WebCoreViewFactory sharedFactory] objectIsTextMarkerRange:parameter])
2453         textMarkerRange = (WebCoreTextMarkerRange*) parameter;
2454
2455     else if ([parameter isKindOfClass:[AccessibilityObjectWrapper self]])
2456         uiElement = [(AccessibilityObjectWrapper*)parameter accessibilityObject];
2457
2458     else if ([parameter isKindOfClass:[NSNumber self]])
2459         number = parameter;
2460
2461     else if ([parameter isKindOfClass:[NSArray self]])
2462         array = parameter;
2463
2464     else if ([parameter isKindOfClass:[NSValue self]] && strcmp([(NSValue*)parameter objCType], @encode(NSPoint)) == 0) {
2465         pointSet = true;
2466         point = [(NSValue*)parameter pointValue];
2467
2468     } else if ([parameter isKindOfClass:[NSValue self]] && strcmp([(NSValue*)parameter objCType], @encode(NSRange)) == 0) {
2469         rangeSet = true;
2470         range = [(NSValue*)parameter rangeValue];
2471     } else {
2472         // Attribute type is not supported. Allow super to handle.
2473         return [super accessibilityAttributeValue:attribute forParameter:parameter];
2474     }
2475     
2476     // dispatch
2477     if ([attribute isEqualToString:@"AXUIElementForTextMarker"]) {
2478         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2479         AccessibilityObject* axObject = m_object->accessibilityObjectForPosition(visiblePos);
2480         if (!axObject)
2481             return nil;
2482         return axObject->wrapper();
2483     }
2484
2485     if ([attribute isEqualToString:@"AXTextMarkerRangeForUIElement"]) {
2486         VisiblePositionRange vpRange = uiElement.get()->visiblePositionRange();
2487         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2488     }
2489
2490     if ([attribute isEqualToString:@"AXLineForTextMarker"]) {
2491         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2492         return [NSNumber numberWithUnsignedInt:m_object->lineForPosition(visiblePos)];
2493     }
2494
2495     if ([attribute isEqualToString:@"AXTextMarkerRangeForLine"]) {
2496         VisiblePositionRange vpRange = m_object->visiblePositionRangeForLine([number intValue]);
2497         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2498     }
2499
2500     if ([attribute isEqualToString:@"AXStringForTextMarkerRange"]) {
2501         VisiblePositionRange visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
2502         return m_object->stringForVisiblePositionRange(visiblePosRange);
2503     }
2504
2505     if ([attribute isEqualToString:@"AXTextMarkerForPosition"]) {
2506         IntPoint webCorePoint = IntPoint(point);
2507         return pointSet ? [self textMarkerForVisiblePosition:m_object->visiblePositionForPoint(webCorePoint)] : nil;
2508     }
2509
2510     if ([attribute isEqualToString:@"AXBoundsForTextMarkerRange"]) {
2511         VisiblePositionRange visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
2512         NSRect rect = m_object->boundsForVisiblePositionRange(visiblePosRange);
2513         return [NSValue valueWithRect:rect];
2514     }
2515     
2516     if ([attribute isEqualToString:NSAccessibilityBoundsForRangeParameterizedAttribute]) {
2517         VisiblePosition start = m_object->visiblePositionForIndex(range.location);
2518         VisiblePosition end = m_object->visiblePositionForIndex(range.location+range.length);
2519         if (start.isNull() || end.isNull())
2520             return nil;
2521         NSRect rect = m_object->boundsForVisiblePositionRange(VisiblePositionRange(start, end));
2522         return [NSValue valueWithRect:rect];
2523     }
2524     
2525     if ([attribute isEqualToString:NSAccessibilityStringForRangeParameterizedAttribute]) {
2526         VisiblePosition start = m_object->visiblePositionForIndex(range.location);
2527         VisiblePosition end = m_object->visiblePositionForIndex(range.location+range.length);
2528         if (start.isNull() || end.isNull())
2529             return nil;
2530         return m_object->stringForVisiblePositionRange(VisiblePositionRange(start, end));
2531     }
2532
2533     if ([attribute isEqualToString:@"AXAttributedStringForTextMarkerRange"])
2534         return [self doAXAttributedStringForTextMarkerRange:textMarkerRange];
2535
2536     if ([attribute isEqualToString:@"AXTextMarkerRangeForUnorderedTextMarkers"]) {
2537         if ([array count] < 2)
2538             return nil;
2539
2540         WebCoreTextMarker* textMarker1 = (WebCoreTextMarker*) [array objectAtIndex:0];
2541         WebCoreTextMarker* textMarker2 = (WebCoreTextMarker*) [array objectAtIndex:1];
2542         if (![[WebCoreViewFactory sharedFactory] objectIsTextMarker:textMarker1] 
2543             || ![[WebCoreViewFactory sharedFactory] objectIsTextMarker:textMarker2])
2544             return nil;
2545
2546         VisiblePosition visiblePos1 = [self visiblePositionForTextMarker:(textMarker1)];
2547         VisiblePosition visiblePos2 = [self visiblePositionForTextMarker:(textMarker2)];
2548         VisiblePositionRange vpRange = m_object->visiblePositionRangeForUnorderedPositions(visiblePos1, visiblePos2);
2549         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2550     }
2551
2552     if ([attribute isEqualToString:@"AXNextTextMarkerForTextMarker"]) {
2553         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2554         return [self textMarkerForVisiblePosition:m_object->nextVisiblePosition(visiblePos)];
2555     }
2556
2557     if ([attribute isEqualToString:@"AXPreviousTextMarkerForTextMarker"]) {
2558         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2559         return [self textMarkerForVisiblePosition:m_object->previousVisiblePosition(visiblePos)];
2560     }
2561
2562     if ([attribute isEqualToString:@"AXLeftWordTextMarkerRangeForTextMarker"]) {
2563         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2564         VisiblePositionRange vpRange = m_object->positionOfLeftWord(visiblePos);
2565         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2566     }
2567
2568     if ([attribute isEqualToString:@"AXRightWordTextMarkerRangeForTextMarker"]) {
2569         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2570         VisiblePositionRange vpRange = m_object->positionOfRightWord(visiblePos);
2571         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2572     }
2573
2574     if ([attribute isEqualToString:@"AXLeftLineTextMarkerRangeForTextMarker"]) {
2575         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2576         VisiblePositionRange vpRange = m_object->leftLineVisiblePositionRange(visiblePos);
2577         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2578     }
2579
2580     if ([attribute isEqualToString:@"AXRightLineTextMarkerRangeForTextMarker"]) {
2581         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2582         VisiblePositionRange vpRange = m_object->rightLineVisiblePositionRange(visiblePos);
2583         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2584     }
2585
2586     if ([attribute isEqualToString:@"AXSentenceTextMarkerRangeForTextMarker"]) {
2587         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2588         VisiblePositionRange vpRange = m_object->sentenceForPosition(visiblePos);
2589         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2590     }
2591
2592     if ([attribute isEqualToString:@"AXParagraphTextMarkerRangeForTextMarker"]) {
2593         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2594         VisiblePositionRange vpRange = m_object->paragraphForPosition(visiblePos);
2595         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2596     }
2597
2598     if ([attribute isEqualToString:@"AXNextWordEndTextMarkerForTextMarker"]) {
2599         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2600         return [self textMarkerForVisiblePosition:m_object->nextWordEnd(visiblePos)];
2601     }
2602     
2603     if ([attribute isEqualToString:@"AXPreviousWordStartTextMarkerForTextMarker"]) {
2604         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2605         return [self textMarkerForVisiblePosition:m_object->previousWordStart(visiblePos)];
2606     }
2607
2608     if ([attribute isEqualToString:@"AXNextLineEndTextMarkerForTextMarker"]) {
2609         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2610         return [self textMarkerForVisiblePosition:m_object->nextLineEndPosition(visiblePos)];
2611     }
2612
2613     if ([attribute isEqualToString:@"AXPreviousLineStartTextMarkerForTextMarker"]) {
2614         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2615         return [self textMarkerForVisiblePosition:m_object->previousLineStartPosition(visiblePos)];
2616     }
2617
2618     if ([attribute isEqualToString:@"AXNextSentenceEndTextMarkerForTextMarker"]) {
2619         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2620         return [self textMarkerForVisiblePosition:m_object->nextSentenceEndPosition(visiblePos)];
2621     }
2622
2623     if ([attribute isEqualToString:@"AXPreviousSentenceStartTextMarkerForTextMarker"]) {
2624         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2625         return [self textMarkerForVisiblePosition:m_object->previousSentenceStartPosition(visiblePos)];
2626     }
2627
2628     if ([attribute isEqualToString:@"AXNextParagraphEndTextMarkerForTextMarker"]) {
2629         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2630         return [self textMarkerForVisiblePosition:m_object->nextParagraphEndPosition(visiblePos)];
2631     }
2632
2633     if ([attribute isEqualToString:@"AXPreviousParagraphStartTextMarkerForTextMarker"]) {
2634         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2635         return [self textMarkerForVisiblePosition:m_object->previousParagraphStartPosition(visiblePos)];
2636     }
2637
2638     if ([attribute isEqualToString:@"AXStyleTextMarkerRangeForTextMarker"]) {
2639         VisiblePosition visiblePos = [self visiblePositionForTextMarker:(textMarker)];
2640         VisiblePositionRange vpRange = m_object->styleRangeForPosition(visiblePos);
2641         return [self textMarkerRangeFromVisiblePositions:vpRange.start endPosition:vpRange.end];
2642     }
2643
2644     if ([attribute isEqualToString:@"AXLengthForTextMarkerRange"]) {
2645         VisiblePositionRange visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
2646         int length = m_object->lengthForVisiblePositionRange(visiblePosRange);
2647         if (length < 0)
2648             return nil;
2649         return [NSNumber numberWithInt:length];
2650     }
2651
2652     // Used only by DumpRenderTree (so far).
2653     if ([attribute isEqualToString:@"AXStartTextMarkerForTextMarkerRange"]) {
2654         VisiblePositionRange visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
2655         return [self textMarkerForVisiblePosition:visiblePosRange.start];
2656     }
2657
2658     if ([attribute isEqualToString:@"AXEndTextMarkerForTextMarkerRange"]) {
2659         VisiblePositionRange visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
2660         return [self textMarkerForVisiblePosition:visiblePosRange.end];
2661     }
2662     
2663     if (m_object->isAccessibilityTable()) {
2664         if ([attribute isEqualToString:NSAccessibilityCellForColumnAndRowParameterizedAttribute]) {
2665             if (array == nil || [array count] != 2)
2666                 return nil;
2667             AccessibilityTableCell* cell = static_cast<AccessibilityTable*>(m_object)->cellForColumnAndRow([[array objectAtIndex:0] unsignedIntValue], [[array objectAtIndex:1] unsignedIntValue]);
2668             if (!cell)
2669                 return nil;
2670             
2671             return cell->wrapper();
2672         }
2673     }
2674
2675     if (m_object->isTextControl()) {
2676         if ([attribute isEqualToString: (NSString *)kAXLineForIndexParameterizedAttribute]) {
2677             int lineNumber = m_object->doAXLineForIndex([number intValue]);
2678             if (lineNumber < 0)
2679                 return nil;
2680             return [NSNumber numberWithUnsignedInt:lineNumber];
2681         }
2682
2683         if ([attribute isEqualToString: (NSString *)kAXRangeForLineParameterizedAttribute]) {
2684             PlainTextRange textRange = m_object->doAXRangeForLine([number intValue]);
2685             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
2686         }
2687
2688         if ([attribute isEqualToString: (NSString*)kAXStringForRangeParameterizedAttribute]) {
2689             PlainTextRange plainTextRange = PlainTextRange(range.location, range.length);
2690             return rangeSet ? (id)(m_object->doAXStringForRange(plainTextRange)) : nil;
2691         }
2692
2693         if ([attribute isEqualToString: (NSString*)kAXRangeForPositionParameterizedAttribute]) {
2694             if (!pointSet)
2695                 return nil;
2696             IntPoint webCorePoint = IntPoint(point);
2697             PlainTextRange textRange = m_object->doAXRangeForPosition(webCorePoint);
2698             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
2699         }
2700
2701         if ([attribute isEqualToString: (NSString*)kAXRangeForIndexParameterizedAttribute]) {
2702             PlainTextRange textRange = m_object->doAXRangeForIndex([number intValue]);
2703             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
2704         }
2705
2706         if ([attribute isEqualToString: (NSString*)kAXBoundsForRangeParameterizedAttribute]) {
2707             if (!rangeSet)
2708                 return nil;
2709             PlainTextRange plainTextRange = PlainTextRange(range.location, range.length);
2710             NSRect rect = m_object->doAXBoundsForRange(plainTextRange);
2711             return [NSValue valueWithRect:rect];
2712         }
2713
2714         if ([attribute isEqualToString: (NSString*)kAXRTFForRangeParameterizedAttribute])
2715             return rangeSet ? [self doAXRTFForRange:range] : nil;
2716
2717         if ([attribute isEqualToString: (NSString*)kAXAttributedStringForRangeParameterizedAttribute])
2718             return rangeSet ? [self doAXAttributedStringForRange:range] : nil;
2719
2720         if ([attribute isEqualToString: (NSString*)kAXStyleRangeForIndexParameterizedAttribute]) {
2721             PlainTextRange textRange = m_object->doAXStyleRangeForIndex([number intValue]);
2722             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
2723         }
2724     }
2725
2726     // There are some parameters that super handles that are not explicitly returned by the list of the element's attributes.
2727     // In that case it must be passed to super. 
2728     return [super accessibilityAttributeValue:attribute forParameter:parameter];
2729 }
2730
2731 - (BOOL)accessibilityShouldUseUniqueId
2732 {
2733     return m_object->accessibilityShouldUseUniqueId();
2734 }
2735
2736 // API that AppKit uses for faster access
2737 - (NSUInteger)accessibilityIndexOfChild:(id)child
2738 {
2739     if (![self updateObjectBackingStore])
2740         return NSNotFound;
2741     
2742     // Tree objects return their rows as their children. We can use the original method
2743     // here, because we won't gain any speed up.
2744     if (m_object->isTree())
2745         return [super accessibilityIndexOfChild:child];
2746        
2747     const AccessibilityObject::AccessibilityChildrenVector& children = m_object->children();
2748        
2749     if (children.isEmpty())
2750         return [[self renderWidgetChildren] indexOfObject:child];
2751     
2752     unsigned count = children.size();
2753     for (unsigned k = 0; k < count; ++k) {
2754         AccessibilityObjectWrapper* wrapper = children[k]->wrapper();
2755         if (wrapper == child || (children[k]->isAttachment() && [wrapper attachmentView] == child)) 
2756             return k;
2757     }
2758
2759     return NSNotFound;
2760 }
2761
2762 - (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute
2763 {
2764     if (![self updateObjectBackingStore])
2765         return 0;
2766     
2767     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2768         // Tree items object returns a different set of children than those that are in children()
2769         // because an AXOutline (the mac role is becomes) has some odd stipulations.
2770         if (m_object->isTree() || m_object->isTreeItem())
2771             return [[self accessibilityAttributeValue:NSAccessibilityChildrenAttribute] count];
2772         
2773         const AccessibilityObject::AccessibilityChildrenVector& children = m_object->children();
2774         if (children.isEmpty())
2775             return [[self renderWidgetChildren] count];
2776         
2777         return children.size();
2778     }
2779     
2780     return [super accessibilityArrayAttributeCount:attribute];
2781 }
2782
2783 - (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute index:(NSUInteger)index maxCount:(NSUInteger)maxCount 
2784 {
2785     if (![self updateObjectBackingStore])
2786         return nil;
2787     
2788     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
2789         if (m_object->children().isEmpty()) {
2790             NSArray *children = [self renderWidgetChildren];
2791             if (!children) 
2792                 return nil;
2793             
2794             NSUInteger childCount = [children count];
2795             if (index >= childCount)
2796                 return nil;
2797             
2798             NSUInteger arrayLength = min(childCount - index, maxCount);
2799             return [children subarrayWithRange:NSMakeRange(index, arrayLength)];
2800         } else if (m_object->isTree()) {
2801             // Tree objects return their rows as their children. We can use the original method in this case.
2802             return [super accessibilityArrayAttributeValues:attribute index:index maxCount:maxCount];
2803         }
2804         
2805         const AccessibilityObject::AccessibilityChildrenVector& children = m_object->children();
2806         unsigned childCount = children.size();
2807         if (index >= childCount)
2808             return nil;
2809         
2810         unsigned available = min(childCount - index, maxCount);
2811         
2812         NSMutableArray *subarray = [NSMutableArray arrayWithCapacity:available];
2813         for (unsigned added = 0; added < available; ++index, ++added) {
2814             AccessibilityObjectWrapper* wrapper = children[index]->wrapper();
2815             if (wrapper) {
2816                 // The attachment view should be returned, otherwise AX palindrome errors occur.
2817                 if (children[index]->isAttachment() && [wrapper attachmentView])
2818                     [subarray addObject:[wrapper attachmentView]];
2819                 else
2820                     [subarray addObject:wrapper];
2821             }
2822         }
2823         
2824         return subarray;
2825     }
2826     
2827     return [super accessibilityArrayAttributeValues:attribute index:index maxCount:maxCount];
2828 }
2829
2830 // This is set by DRT when it wants to listen for notifications.
2831 static BOOL accessibilityShouldRepostNotifications;
2832 - (void)accessibilitySetShouldRepostNotifications:(BOOL)repost
2833 {
2834     accessibilityShouldRepostNotifications = repost;
2835 }
2836
2837 - (void)accessibilityPostedNotification:(NSString *)notificationName
2838 {
2839     if (accessibilityShouldRepostNotifications) {
2840         NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:notificationName, @"notificationName", nil];
2841         [[NSNotificationCenter defaultCenter] postNotificationName:@"AXDRTNotification" object:nil userInfo:userInfo];
2842     }
2843 }
2844
2845 @end
2846
2847 #endif // HAVE(ACCESSIBILITY)