02bd13afc5163c0093a336bb0ccb2a4074dea24f
[WebKit-https.git] / WebCore / page / mac / AccessibilityObjectWrapper.mm
1 /*
2  * Copyright (C) 2008 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import "config.h"
30 #import "AccessibilityObjectWrapper.h"
31
32 #import "AXObjectCache.h"
33 #import "AccessibilityListBox.h"
34 #import "AccessibilityRenderObject.h"
35 #import "ColorMac.h"
36 #import "Frame.h"
37 #import "HTMLAnchorElement.h"
38 #import "HTMLAreaElement.h"
39 #import "HTMLImageElement.h"
40 #import "HTMLInputElement.h"
41 #import "HTMLTextAreaElement.h"
42 #import "LocalizedStrings.h"
43 #import "RenderTextControl.h"
44 #import "RenderView.h"
45 #import "RenderWidget.h"
46 #import "SelectionController.h"
47 #import "SimpleFontData.h"
48 #import "TextIterator.h"
49 #import "WebCoreFrameView.h"
50 #import "WebCoreObjCExtras.h"
51 #import "WebCoreViewFactory.h"
52 #import "htmlediting.h"
53 #import "visible_units.h"
54
55 using namespace WebCore;
56 using namespace HTMLNames;
57
58 @implementation AccessibilityObjectWrapper
59
60 #ifndef BUILDING_ON_TIGER
61 + (void)initialize
62 {
63     WebCoreObjCFinalizeOnMainThread(self);
64 }
65 #endif
66
67 - (id)initWithAccessibilityObject:(AccessibilityObject*)axObject
68 {
69     [super init];
70
71     m_object = axObject;
72     return self;
73 }
74
75 - (void)unregisterUniqueIdForUIElement
76 {
77     [[WebCoreViewFactory sharedFactory] unregisterUniqueIdForUIElement:self];
78 }
79
80 - (void)detach
81 {
82     // Send unregisterUniqueIdForUIElement unconditionally because if it is
83     // ever accidently not done (via other bugs in our AX implementation) you
84     // end up with a crash like <rdar://problem/4273149>.  It is safe and not
85     // expensive to send even if the object is not registered.
86     [self unregisterUniqueIdForUIElement];
87     m_object = 0;
88 }
89
90 - (AccessibilityObject*)accessibilityObject
91 {
92     return m_object;
93 }
94
95 - (NSView*)attachmentView
96 {
97     ASSERT(m_object->isAttachment());
98     Widget* widget = m_object->widgetForAttachmentView();
99     if (!widget)
100         return nil;
101     return widget->getView();
102 }
103
104 static WebCoreTextMarker* textMarkerForVisiblePosition(const VisiblePosition& visiblePos)
105 {
106     if (visiblePos.isNull())
107         return nil;
108
109     Position deepPos = visiblePos.deepEquivalent();
110     Node* domNode = deepPos.node();
111     ASSERT(domNode);
112     if (!domNode)
113         return nil;
114
115     if (domNode->isHTMLElement())
116         if (static_cast<HTMLElement*>(domNode)->isPasswordField())
117             return nil;
118
119     // locate the renderer, which must exist for a visible dom node
120     RenderObject* renderer = domNode->renderer();
121     ASSERT(renderer);
122
123     // find or create an accessibility object for this renderer
124     AXObjectCache* cache = renderer->document()->axObjectCache();
125     RefPtr<AccessibilityObject> obj = cache->get(renderer);
126
127     // create a text marker, adding an ID for the AccessibilityObject if needed
128     TextMarkerData textMarkerData;
129     textMarkerData.axID = obj.get()->axObjectID();
130     textMarkerData.node = domNode;
131     textMarkerData.offset = deepPos.offset();
132     textMarkerData.affinity = visiblePos.affinity();
133     return [[WebCoreViewFactory sharedFactory] textMarkerWithBytes:&textMarkerData length:sizeof(textMarkerData)];
134 }
135
136 static VisiblePosition visiblePositionForTextMarker(WebCoreTextMarker* textMarker)
137 {
138     TextMarkerData textMarkerData;
139     
140     if (![[WebCoreViewFactory sharedFactory] getBytes:&textMarkerData fromTextMarker:textMarker length:sizeof(textMarkerData)])
141         return VisiblePosition();
142
143     VisiblePosition visiblePos = VisiblePosition(textMarkerData.node, textMarkerData.offset, textMarkerData.affinity);
144     Position deepPos = visiblePos.deepEquivalent();
145     AXObjectCache* cache = deepPos.node()->renderer()->document()->axObjectCache();
146     if (!cache->isIDinUse(textMarkerData.axID))
147         return VisiblePosition();
148
149     if (deepPos.node() != textMarkerData.node || deepPos.offset() != textMarkerData.offset)
150         return VisiblePosition();
151     
152     return visiblePos;
153 }
154
155 static VisiblePosition visiblePositionForStartOfTextMarkerRange(WebCoreTextMarkerRange* textMarkerRange)
156 {
157     return visiblePositionForTextMarker([[WebCoreViewFactory sharedFactory] startOfTextMarkerRange:textMarkerRange]);
158 }
159
160 static VisiblePosition visiblePositionForEndOfTextMarkerRange(WebCoreTextMarkerRange* textMarkerRange)
161 {
162     return visiblePositionForTextMarker([[WebCoreViewFactory sharedFactory] endOfTextMarkerRange:textMarkerRange]);
163 }
164
165 static WebCoreTextMarkerRange* textMarkerRangeFromMarkers(WebCoreTextMarker* textMarker1, WebCoreTextMarker* textMarker2)
166 {
167     return [[WebCoreViewFactory sharedFactory] textMarkerRangeWithStart:textMarker1 end:textMarker2];
168 }
169
170 static void AXAttributeStringSetFont(NSMutableAttributedString* attrString, NSString* attribute, NSFont* font, NSRange range)
171 {
172     NSDictionary* dict;
173     
174     if (font) {
175         dict = [NSDictionary dictionaryWithObjectsAndKeys:
176             [font fontName]                             , NSAccessibilityFontNameKey,
177             [font familyName]                           , NSAccessibilityFontFamilyKey,
178             [font displayName]                          , NSAccessibilityVisibleNameKey,
179             [NSNumber numberWithFloat:[font pointSize]] , NSAccessibilityFontSizeKey,
180         nil];
181
182         [attrString addAttribute:attribute value:dict range:range];
183     } else
184         [attrString removeAttribute:attribute range:range];
185     
186 }
187
188 static CGColorRef CreateCGColorIfDifferent(NSColor* nsColor, CGColorRef existingColor)
189 {
190     // get color information assuming NSDeviceRGBColorSpace 
191     NSColor* rgbColor = [nsColor colorUsingColorSpaceName:NSDeviceRGBColorSpace];
192     if (rgbColor == nil)
193         rgbColor = [NSColor blackColor];
194     CGFloat components[4];
195     [rgbColor getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
196     
197     // create a new CGColorRef to return
198     CGColorSpaceRef cgColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
199     CGColorRef cgColor = CGColorCreate(cgColorSpace, components);
200     CGColorSpaceRelease(cgColorSpace);
201     CFMakeCollectable(cgColor);
202     
203     // check for match with existing color
204     if (existingColor && CGColorEqualToColor(cgColor, existingColor))
205         cgColor = nil;
206
207     return cgColor;
208 }
209
210 static void AXAttributeStringSetColor(NSMutableAttributedString* attrString, NSString* attribute, NSColor* color, NSRange range)
211 {
212     if (color) {
213         CGColorRef existingColor = (CGColorRef) [attrString attribute:attribute atIndex:range.location effectiveRange:nil];
214         CGColorRef cgColor = CreateCGColorIfDifferent(color, existingColor);
215         if (cgColor) {
216             [attrString addAttribute:attribute value:(id)cgColor range:range];
217             CGColorRelease(cgColor);
218         }
219     } else
220         [attrString removeAttribute:attribute range:range];
221 }
222
223 static void AXAttributeStringSetNumber(NSMutableAttributedString* attrString, NSString* attribute, NSNumber* number, NSRange range)
224 {
225     if (number)
226         [attrString addAttribute:attribute value:number range:range];
227     else
228         [attrString removeAttribute:attribute range:range];
229 }
230
231 static void AXAttributeStringSetStyle(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
232 {
233     RenderStyle* style = renderer->style();
234
235     // set basic font info
236     AXAttributeStringSetFont(attrString, NSAccessibilityFontTextAttribute, style->font().primaryFont()->getNSFont(), range);
237
238     // set basic colors
239     AXAttributeStringSetColor(attrString, NSAccessibilityForegroundColorTextAttribute, nsColor(style->color()), range);
240     AXAttributeStringSetColor(attrString, NSAccessibilityBackgroundColorTextAttribute, nsColor(style->backgroundColor()), range);
241
242     // set super/sub scripting
243     EVerticalAlign alignment = style->verticalAlign();
244     if (alignment == SUB)
245         AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:(-1)], range);
246     else if (alignment == SUPER)
247         AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:1], range);
248     else
249         [attrString removeAttribute:NSAccessibilitySuperscriptTextAttribute range:range];
250     
251     // set shadow
252     if (style->textShadow())
253         AXAttributeStringSetNumber(attrString, NSAccessibilityShadowTextAttribute, [NSNumber numberWithBool:YES], range);
254     else
255         [attrString removeAttribute:NSAccessibilityShadowTextAttribute range:range];
256     
257     // set underline and strikethrough
258     int decor = style->textDecorationsInEffect();
259     if ((decor & UNDERLINE) == 0) {
260         [attrString removeAttribute:NSAccessibilityUnderlineTextAttribute range:range];
261         [attrString removeAttribute:NSAccessibilityUnderlineColorTextAttribute range:range];
262     }
263     
264     if ((decor & LINE_THROUGH) == 0) {
265         [attrString removeAttribute:NSAccessibilityStrikethroughTextAttribute range:range];
266         [attrString removeAttribute:NSAccessibilityStrikethroughColorTextAttribute range:range];
267     }
268
269     if ((decor & (UNDERLINE | LINE_THROUGH)) != 0) {
270         // find colors using quirk mode approach (strict mode would use current
271         // color for all but the root line box, which would use getTextDecorationColors)
272         Color underline, overline, linethrough;
273         renderer->getTextDecorationColors(decor, underline, overline, linethrough);
274         
275         if ((decor & UNDERLINE) != 0) {
276             AXAttributeStringSetNumber(attrString, NSAccessibilityUnderlineTextAttribute, [NSNumber numberWithBool:YES], range);
277             AXAttributeStringSetColor(attrString, NSAccessibilityUnderlineColorTextAttribute, nsColor(underline), range);
278         }
279
280         if ((decor & LINE_THROUGH) != 0) {
281             AXAttributeStringSetNumber(attrString, NSAccessibilityStrikethroughTextAttribute, [NSNumber numberWithBool:YES], range);
282             AXAttributeStringSetColor(attrString, NSAccessibilityStrikethroughColorTextAttribute, nsColor(linethrough), range);
283         }
284     }
285 }
286
287 static int blockquoteLevel(RenderObject* renderer)
288 {
289     int result = 0;
290     for (Node* node = renderer->element(); node; node = node->parent()) {
291         if (node->hasTagName(blockquoteTag))
292             result += 1;
293     }
294     
295     return result;
296 }
297
298 static void AXAttributeStringSetBlockquoteLevel(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
299 {
300     int quoteLevel = blockquoteLevel(renderer);
301     
302     if (quoteLevel)
303         [attrString addAttribute:@"AXBlockQuoteLevel" value:[NSNumber numberWithInt:quoteLevel] range:range];
304     else
305         [attrString removeAttribute:@"AXBlockQuoteLevel" range:range];
306 }
307
308 static void AXAttributeStringSetSpelling(NSMutableAttributedString* attrString, Node* node, int offset, NSRange range)
309 {
310     Vector<DocumentMarker> markers = node->renderer()->document()->markersForNode(node);
311     Vector<DocumentMarker>::iterator markerIt = markers.begin();
312
313     unsigned endOffset = (unsigned)offset + range.length;
314     for ( ; markerIt != markers.end(); markerIt++) {
315         DocumentMarker marker = *markerIt;
316         
317         if (marker.type != DocumentMarker::Spelling)
318             continue;
319         
320         if (marker.endOffset <= (unsigned)offset)
321             continue;
322         
323         if (marker.startOffset > endOffset)
324             break;
325         
326         // add misspelling attribute for the intersection of the marker and the range
327         int rStart = range.location + (marker.startOffset - offset);
328         int rLength = MIN(marker.endOffset, endOffset) - marker.startOffset;
329         NSRange spellRange = NSMakeRange(rStart, rLength);
330         AXAttributeStringSetNumber(attrString, NSAccessibilityMisspelledTextAttribute, [NSNumber numberWithBool:YES], spellRange);
331         
332         if (marker.endOffset > endOffset + 1)
333             break;
334     }
335 }
336
337 static void AXAttributeStringSetHeadingLevel(AccessibilityObject* object, NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
338 {
339     int parentHeadingLevel = AccessibilityRenderObject::headingLevel(renderer->parent()->element());
340     
341     if (parentHeadingLevel)
342         [attrString addAttribute:@"AXHeadingLevel" value:[NSNumber numberWithInt:parentHeadingLevel] range:range];
343     else
344         [attrString removeAttribute:@"AXHeadingLevel" range:range];
345 }
346
347 static AccessibilityObject* AXLinkElementForNode(Node* node)
348 {
349     RenderObject* obj = node->renderer();
350     if (!obj)
351         return 0;
352
353     RefPtr<AccessibilityObject> axObj = obj->document()->axObjectCache()->get(obj);
354     HTMLAnchorElement* anchor = axObj->anchorElement();
355     if (!anchor)
356         return 0;
357
358     RenderObject* anchorRenderer = anchor->renderer();
359     if (!anchorRenderer)
360         return 0;
361     
362     return anchorRenderer->document()->axObjectCache()->get(anchorRenderer);
363 }
364
365 static void AXAttributeStringSetElement(NSMutableAttributedString* attrString, NSString* attribute, AccessibilityObject* object, NSRange range)
366 {
367     if (object && object->isAccessibilityRenderObject()) {
368         // make a serialiazable AX object
369         
370         RenderObject* renderer = static_cast<AccessibilityRenderObject*>(object)->renderer();
371         if (!renderer)
372             return;
373         
374         Document* doc = renderer->document();
375         if (!doc)
376             return;
377         
378         AXObjectCache* cache = doc->axObjectCache();
379         if (!cache)
380             return;
381
382         AXUIElementRef axElement = [[WebCoreViewFactory sharedFactory] AXUIElementForElement:object->wrapper()];
383         if (axElement) {
384             [attrString addAttribute:attribute value:(id)axElement range:range];
385             CFRelease(axElement);
386         }
387     } else
388         [attrString removeAttribute:attribute range:range];
389 }
390
391 static void AXAttributedStringAppendText(AccessibilityObject* object, NSMutableAttributedString* attrString, Node* node, int offset, const UChar* chars, int length)
392 {
393     // skip invisible text
394     if (!node->renderer())
395         return;
396
397     // easier to calculate the range before appending the string
398     NSRange attrStringRange = NSMakeRange([attrString length], length);
399     
400     // append the string from this node
401     [[attrString mutableString] appendString:[NSString stringWithCharacters:chars length:length]];
402
403     // add new attributes and remove irrelevant inherited ones
404     // NOTE: color attributes are handled specially because -[NSMutableAttributedString addAttribute: value: range:] does not merge
405     // identical colors.  Workaround is to not replace an existing color attribute if it matches what we are adding.  This also means
406     // we cannot just pre-remove all inherited attributes on the appended string, so we have to remove the irrelevant ones individually.
407
408     // remove inherited attachment from prior AXAttributedStringAppendReplaced
409     [attrString removeAttribute:NSAccessibilityAttachmentTextAttribute range:attrStringRange];
410     
411     // set new attributes
412     AXAttributeStringSetStyle(attrString, node->renderer(), attrStringRange);
413     AXAttributeStringSetHeadingLevel(object, attrString, node->renderer(), attrStringRange);
414     AXAttributeStringSetBlockquoteLevel(attrString, node->renderer(), attrStringRange);
415     AXAttributeStringSetElement(attrString, NSAccessibilityLinkTextAttribute, AXLinkElementForNode(node), attrStringRange);
416     
417     // do spelling last because it tends to break up the range
418     AXAttributeStringSetSpelling(attrString, node, offset, attrStringRange);
419 }
420
421 static NSString* nsStringForReplacedNode(Node* replacedNode)
422 {
423     // we should always be given a rendered node and a replaced node, but be safe
424     // replaced nodes are either attachments (widgets) or images
425     if (!replacedNode || !replacedNode->renderer() || !replacedNode->renderer()->isReplaced() || replacedNode->isTextNode()) {
426         ASSERT_NOT_REACHED();
427         return nil;
428     }
429
430     // create an AX object, but skip it if it is not supposed to be seen
431     RefPtr<AccessibilityObject> obj = replacedNode->renderer()->document()->axObjectCache()->get(replacedNode->renderer());
432     if (obj->accessibilityIsIgnored())
433         return nil;
434     
435     // use the attachmentCharacter to represent the replaced node
436     const UniChar attachmentChar = NSAttachmentCharacter;
437     return [NSString stringWithCharacters:&attachmentChar length:1];
438 }
439
440 - (NSAttributedString*)doAXAttributedStringForTextMarkerRange:(WebCoreTextMarkerRange*)textMarkerRange
441 {
442     // extract the start and end VisiblePosition
443     VisiblePosition startVisiblePosition = visiblePositionForStartOfTextMarkerRange(textMarkerRange);
444     if (startVisiblePosition.isNull())
445         return nil;
446
447     VisiblePosition endVisiblePosition = visiblePositionForEndOfTextMarkerRange(textMarkerRange);
448     if (endVisiblePosition.isNull())
449         return nil;
450
451     // iterate over the range to build the AX attributed string
452     NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] init];
453     TextIterator it(makeRange(startVisiblePosition, endVisiblePosition).get());
454     while (!it.atEnd()) {
455         // locate the node and starting offset for this range
456         int exception = 0;
457         Node* node = it.range()->startContainer(exception);
458         ASSERT(node == it.range()->endContainer(exception));
459         int offset = it.range()->startOffset(exception);
460
461         // non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
462         if (it.length() != 0) {
463             AXAttributedStringAppendText(m_object, attrString, node, offset, it.characters(), it.length());
464         } else {
465             Node* replacedNode = node->childNode(offset);
466             NSString *attachmentString = nsStringForReplacedNode(replacedNode);
467             if (attachmentString) {
468                 NSRange attrStringRange = NSMakeRange([attrString length], [attachmentString length]);
469
470                 // append the placeholder string
471                 [[attrString mutableString] appendString:attachmentString];
472
473                 // remove all inherited attributes
474                 [attrString setAttributes:nil range:attrStringRange];
475
476                 // add the attachment attribute
477                 AccessibilityObject* obj = replacedNode->renderer()->document()->axObjectCache()->get(replacedNode->renderer());
478                 AXAttributeStringSetElement(attrString, NSAccessibilityAttachmentTextAttribute, obj, attrStringRange);
479             }
480         }
481         it.advance();
482     }
483
484     return [attrString autorelease];
485 }
486
487 static WebCoreTextMarkerRange* textMarkerRangeFromVisiblePositions(VisiblePosition startPosition, VisiblePosition endPosition)
488 {
489     WebCoreTextMarker* startTextMarker = textMarkerForVisiblePosition(startPosition);
490     WebCoreTextMarker* endTextMarker   = textMarkerForVisiblePosition(endPosition);
491     return textMarkerRangeFromMarkers(startTextMarker, endTextMarker);
492 }
493
494 - (NSArray*)accessibilityActionNames
495 {
496     static NSArray* actions = nil;
497     
498     if (actions == nil) {
499         if (m_object->actionElement()) 
500             actions = [[NSArray alloc] initWithObjects: NSAccessibilityPressAction, nil];
501         else if (m_object->isAttachment())
502             actions = [[[self attachmentView] accessibilityActionNames] retain];
503     }
504
505     return actions;
506 }
507
508 - (NSArray*)accessibilityAttributeNames
509 {
510     if (m_object->isAttachment())
511         return [[self attachmentView] accessibilityAttributeNames];
512
513     static NSArray* attributes = nil;
514     static NSArray* anchorAttrs = nil;
515     static NSArray* webAreaAttrs = nil;
516     static NSArray* textAttrs = nil;
517     static NSArray* listBoxAttrs = nil;
518     NSMutableArray* tempArray;
519     if (attributes == nil) {
520         attributes = [[NSArray alloc] initWithObjects: NSAccessibilityRoleAttribute,
521                       NSAccessibilitySubroleAttribute,
522                       NSAccessibilityRoleDescriptionAttribute,
523                       NSAccessibilityChildrenAttribute,
524                       NSAccessibilityHelpAttribute,
525                       NSAccessibilityParentAttribute,
526                       NSAccessibilityPositionAttribute,
527                       NSAccessibilitySizeAttribute,
528                       NSAccessibilityTitleAttribute,
529                       NSAccessibilityDescriptionAttribute,
530                       NSAccessibilityValueAttribute,
531                       NSAccessibilityFocusedAttribute,
532                       NSAccessibilityEnabledAttribute,
533                       NSAccessibilityWindowAttribute,
534                       @"AXSelectedTextMarkerRange",
535                       @"AXStartTextMarker",
536                       @"AXEndTextMarker",
537                       @"AXVisited",
538                       NSAccessibilityLinkedUIElementsAttribute,
539                       NSAccessibilitySelectedAttribute,
540                       @"AXBlockQuoteLevel",
541                       nil];
542     }
543     if (anchorAttrs == nil) {
544         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
545         [tempArray addObject:NSAccessibilityURLAttribute];
546         anchorAttrs = [[NSArray alloc] initWithArray:tempArray];
547         [tempArray release];
548     }
549     if (webAreaAttrs == nil) {
550         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
551         [tempArray addObject:@"AXLinkUIElements"];
552         [tempArray addObject:@"AXLoaded"];
553         [tempArray addObject:@"AXLayoutCount"];
554         [tempArray addObject:NSAccessibilityURLAttribute];
555         webAreaAttrs = [[NSArray alloc] initWithArray:tempArray];
556         [tempArray release];
557     }
558     if (textAttrs == nil) {
559         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
560         [tempArray addObject:NSAccessibilityNumberOfCharactersAttribute];
561         [tempArray addObject:NSAccessibilitySelectedTextAttribute];
562         [tempArray addObject:NSAccessibilitySelectedTextRangeAttribute];
563         [tempArray addObject:NSAccessibilityVisibleCharacterRangeAttribute];
564         [tempArray addObject:NSAccessibilityInsertionPointLineNumberAttribute];
565         textAttrs = [[NSArray alloc] initWithArray:tempArray];
566         [tempArray release];
567     }
568     if (listBoxAttrs == nil) {
569         tempArray = [[NSMutableArray alloc] initWithArray:attributes];
570         [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
571         [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
572         [tempArray addObject:NSAccessibilityOrientationAttribute];
573         listBoxAttrs = [[NSArray alloc] initWithArray:tempArray];
574         [tempArray release];
575     }
576     
577     if (m_object->isPasswordField())
578         return attributes;
579
580     if (m_object->isWebArea())
581         return webAreaAttrs;
582     
583     if (m_object->isTextControl())
584         return textAttrs;
585
586     if (m_object->isAnchor() || m_object->isImage())
587         return anchorAttrs;
588
589     if (m_object->isListBox())
590         return listBoxAttrs;
591
592     return attributes;
593 }
594
595 - (VisiblePositionRange)visiblePositionRangeForTextMarkerRange:(WebCoreTextMarkerRange*) textMarkerRange
596 {
597     return VisiblePositionRange(visiblePositionForStartOfTextMarkerRange(textMarkerRange), visiblePositionForEndOfTextMarkerRange(textMarkerRange));
598 }
599
600 - (NSArray*)renderWidgetChildren
601 {
602     Widget* widget = m_object->widget();
603     if (!widget)
604         return nil;
605     return [(widget->getOuterView()) accessibilityAttributeValue: NSAccessibilityChildrenAttribute];
606 }
607
608 static NSMutableArray* convertToNSArray(const Vector<RefPtr<AccessibilityObject> >& vector)
609 {
610     unsigned length = vector.size();
611     NSMutableArray* array = [NSMutableArray arrayWithCapacity: length];
612     for (unsigned i = 0; i < length; ++i)
613         [array addObject:vector[i]->wrapper()];
614     return array;
615 }
616
617 - (WebCoreTextMarkerRange*)textMarkerRangeForSelection
618 {
619     Selection selection = m_object->selection();
620     if (selection.isNone())
621         return nil;
622     return textMarkerRangeFromVisiblePositions(selection.visibleStart(), selection.visibleEnd());
623 }
624
625 - (NSValue*)position
626 {
627     IntRect rect = m_object->elementRect();
628     
629     // The Cocoa accessibility API wants the lower-left corner.
630     NSPoint point = NSMakePoint(rect.x(), rect.bottom());
631     FrameView* frameView = m_object->documentFrameView();
632     if (frameView) {
633         NSView* view = frameView->documentView();
634         point = [[view window] convertBaseToScreen: [view convertPoint: point toView:nil]];
635     }
636
637     return [NSValue valueWithPoint: point];
638 }
639
640 typedef HashMap<int, NSString*> AccessibilityRoleMap;
641
642 static const AccessibilityRoleMap& createAccessibilityRoleMap()
643 {
644     struct RoleEntry {
645         AccessibilityRole value;
646         NSString* string;
647     };
648     
649     static const RoleEntry roles[] = {
650         { UnknownRole, NSAccessibilityUnknownRole },
651         { ButtonRole, NSAccessibilityButtonRole },
652         { RadioButtonRole, NSAccessibilityRadioButtonRole },
653         { CheckBoxRole, NSAccessibilityCheckBoxRole },
654         { SliderRole, NSAccessibilitySliderRole },
655         { TabGroupRole, NSAccessibilityTabGroupRole },
656         { TextFieldRole, NSAccessibilityTextFieldRole },
657         { StaticTextRole, NSAccessibilityStaticTextRole },
658         { TextAreaRole, NSAccessibilityTextAreaRole },
659         { ScrollAreaRole, NSAccessibilityScrollAreaRole },
660         { PopUpButtonRole, NSAccessibilityPopUpButtonRole },
661         { MenuButtonRole, NSAccessibilityMenuButtonRole },
662         { TableRole, NSAccessibilityTableRole },
663         { ApplicationRole, NSAccessibilityApplicationRole },
664         { GroupRole, NSAccessibilityGroupRole },
665         { RadioGroupRole, NSAccessibilityRadioGroupRole },
666         { ListRole, NSAccessibilityListRole },
667         { ScrollBarRole, NSAccessibilityScrollBarRole },
668         { ValueIndicatorRole, NSAccessibilityValueIndicatorRole },
669         { ImageRole, NSAccessibilityImageRole },
670         { MenuBarRole, NSAccessibilityMenuBarRole },
671         { MenuRole, NSAccessibilityMenuRole },
672         { MenuItemRole, NSAccessibilityMenuItemRole },
673         { ColumnRole, NSAccessibilityColumnRole },
674         { RowRole, NSAccessibilityRowRole },
675         { ToolbarRole, NSAccessibilityToolbarRole },
676         { BusyIndicatorRole, NSAccessibilityBusyIndicatorRole },
677         { ProgressIndicatorRole, NSAccessibilityProgressIndicatorRole },
678         { WindowRole, NSAccessibilityWindowRole },
679         { DrawerRole, NSAccessibilityDrawerRole },
680         { SystemWideRole, NSAccessibilitySystemWideRole },
681         { OutlineRole, NSAccessibilityOutlineRole },
682         { IncrementorRole, NSAccessibilityIncrementorRole },
683         { BrowserRole, NSAccessibilityBrowserRole },
684         { ComboBoxRole, NSAccessibilityComboBoxRole },
685         { SplitGroupRole, NSAccessibilitySplitGroupRole },
686         { SplitterRole, NSAccessibilitySplitterRole },
687         { ColorWellRole, NSAccessibilityColorWellRole },
688         { GrowAreaRole, NSAccessibilityGrowAreaRole },
689         { SheetRole, NSAccessibilitySheetRole },
690         { HelpTagRole, NSAccessibilityHelpTagRole },
691         { MatteRole, NSAccessibilityMatteRole }, 
692         { RulerRole, NSAccessibilityRulerRole },
693         { RulerMarkerRole, NSAccessibilityRulerMarkerRole },
694         { LinkRole, NSAccessibilityLinkRole },
695 #ifndef BUILDING_ON_TIGER        
696         { DisclosureTriangleRole, NSAccessibilityDisclosureTriangleRole },
697         { GridRole, NSAccessibilityGridRole },
698 #endif
699         { WebCoreLinkRole, @"AXLink" }, // why isn't this just NSAccessibilityLinkRole ?
700         { ImageMapRole, @"AXImageMap" },
701         { ListMarkerRole, @"AXListMarker" },
702         { WebAreaRole, @"AXWebArea" },
703         { HeadingRole, @"AXHeading" },
704         { ListBoxRole, NSAccessibilityListRole },
705         { ListBoxOptionRole, NSAccessibilityStaticTextRole }
706     };
707     AccessibilityRoleMap& roleMap = *new AccessibilityRoleMap;
708     
709     const unsigned numRoles = sizeof(roles) / sizeof(roles[0]);
710     for (unsigned i = 0; i < numRoles; ++i)
711         roleMap.set(roles[i].value, roles[i].string);
712     return roleMap;
713 }
714
715 static NSString* roleValueToNSString(AccessibilityRole value)
716 {
717     ASSERT(value);
718     static const AccessibilityRoleMap& roleMap = createAccessibilityRoleMap();
719     return roleMap.get(value);
720 }
721
722 - (NSString*)role
723 {
724     if (m_object->isAttachment())
725         return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleAttribute];
726     NSString* string = roleValueToNSString(m_object->roleValue());
727     if (string != nil)
728         return string;
729     return NSAccessibilityUnknownRole;
730 }
731
732 - (NSString*)subrole
733 {
734     if (m_object->isPasswordField())
735         return NSAccessibilitySecureTextFieldSubrole;
736     
737     if (m_object->isAttachment()) {
738         NSView* attachView = [self attachmentView];
739         if ([[attachView accessibilityAttributeNames] containsObject:NSAccessibilitySubroleAttribute]) {
740             return [attachView accessibilityAttributeValue:NSAccessibilitySubroleAttribute];
741         }
742     }
743
744     return nil;
745 }
746
747 - (NSString*)roleDescription
748 {
749     if (!m_object)
750         return nil;
751
752     // attachments have the AXImage role, but a different subrole
753     if (m_object->isAttachment())
754         return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleDescriptionAttribute];
755     
756     // FIXME 3447564: It would be better to call some AppKit API to get these strings
757     // (which would be the best way to localize them)
758     
759     NSString* axRole = [self role];
760     if ([axRole isEqualToString:NSAccessibilityButtonRole])
761         return NSAccessibilityRoleDescription(NSAccessibilityButtonRole, [self subrole]);
762     
763     if ([axRole isEqualToString:NSAccessibilityPopUpButtonRole])
764         return NSAccessibilityRoleDescription(NSAccessibilityPopUpButtonRole, [self subrole]);
765
766     if ([axRole isEqualToString:NSAccessibilityStaticTextRole])
767         return NSAccessibilityRoleDescription(NSAccessibilityStaticTextRole, [self subrole]);
768
769     if ([axRole isEqualToString:NSAccessibilityImageRole])
770         return NSAccessibilityRoleDescription(NSAccessibilityImageRole, [self subrole]);
771     
772     if ([axRole isEqualToString:NSAccessibilityGroupRole])
773         return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, [self subrole]);
774     
775     if ([axRole isEqualToString:NSAccessibilityCheckBoxRole])
776         return NSAccessibilityRoleDescription(NSAccessibilityCheckBoxRole, [self subrole]);
777
778     if ([axRole isEqualToString:NSAccessibilityRadioButtonRole])
779         return NSAccessibilityRoleDescription(NSAccessibilityRadioButtonRole, [self subrole]);
780
781     if ([axRole isEqualToString:NSAccessibilityTextFieldRole])
782         return NSAccessibilityRoleDescription(NSAccessibilityTextFieldRole, [self subrole]);
783
784     if ([axRole isEqualToString:NSAccessibilityTextAreaRole])
785         return NSAccessibilityRoleDescription(NSAccessibilityTextAreaRole, [self subrole]);
786
787     if ([axRole isEqualToString:NSAccessibilityListRole])
788         return NSAccessibilityRoleDescription(NSAccessibilityListRole, [self subrole]);
789     
790     if ([axRole isEqualToString:@"AXWebArea"])
791         return AXWebAreaText();
792     
793     if ([axRole isEqualToString:@"AXLink"])
794         return AXLinkText();
795     
796     if ([axRole isEqualToString:@"AXListMarker"])
797         return AXListMarkerText();
798     
799     if ([axRole isEqualToString:@"AXImageMap"])
800         return AXImageMapText();
801
802     if ([axRole isEqualToString:@"AXHeading"])
803         return AXHeadingText();
804     
805     return NSAccessibilityRoleDescription(NSAccessibilityUnknownRole, nil);
806 }
807
808 // FIXME: split up this function in a better way.  
809 // suggestions: Use a hash table that maps attribute names to function calls,
810 // or maybe pointers to member functions
811 - (id)accessibilityAttributeValue:(NSString*)attributeName
812 {
813     if (!m_object)
814         return nil;
815
816     if ([attributeName isEqualToString: NSAccessibilityRoleAttribute])
817         return [self role];
818
819     if ([attributeName isEqualToString: NSAccessibilitySubroleAttribute])
820         return [self subrole];
821
822     if ([attributeName isEqualToString: NSAccessibilityRoleDescriptionAttribute])
823         return [self roleDescription];
824
825     if ([attributeName isEqualToString: NSAccessibilityParentAttribute]) {
826         if (m_object->isAccessibilityRenderObject()) {
827             FrameView* fv = static_cast<AccessibilityRenderObject*>(m_object)->frameViewIfRenderView();
828             if (fv)
829                 return fv->getView();
830         }
831         
832         return m_object->parentObjectUnignored()->wrapper();
833     }
834
835     if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
836         if (m_object->children().isEmpty()) {
837             NSArray* children = [self renderWidgetChildren];
838             if (children != nil)
839                 return children;
840         }
841         return convertToNSArray(m_object->children());
842     }
843     
844     if ([attributeName isEqualToString: NSAccessibilitySelectedChildrenAttribute] && m_object->isListBox())
845         return convertToNSArray(static_cast<AccessibilityListBox*>(m_object)->selectedChildren());
846     
847     if ([attributeName isEqualToString: NSAccessibilityVisibleChildrenAttribute] && m_object->isListBox())
848         return convertToNSArray(static_cast<AccessibilityListBox*>(m_object)->visibleChildren());
849     
850     
851     if (m_object->isWebArea()) {
852         if ([attributeName isEqualToString: @"AXLinkUIElements"]) {
853             Vector<RefPtr<AccessibilityObject> > links;
854             m_object->getDocumentLinks(links);
855             return convertToNSArray(links);
856         }
857         if ([attributeName isEqualToString: @"AXLoaded"])
858             return [NSNumber numberWithBool: m_object->isLoaded()];
859         if ([attributeName isEqualToString: @"AXLayoutCount"])
860             return [NSNumber numberWithInt: m_object->layoutCount()];
861     }
862     
863     if (m_object->isTextControl()) {
864         if ([attributeName isEqualToString: NSAccessibilityNumberOfCharactersAttribute]) {
865             int length = m_object->textLength();
866             if (length < 0)
867                 return nil;
868             return [NSNumber numberWithUnsignedInt:length];
869         }
870         if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute]) {
871             String selectedText = m_object->selectedText();
872             if (selectedText.isNull())
873                 return nil;
874             return (NSString*)selectedText;
875         }
876         if ([attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute]) {
877             PlainTextRange textRange = m_object->selectedTextRange();
878             if (textRange.isNull())
879                 return nil;
880             return [NSValue valueWithRange:NSMakeRange(textRange.start, textRange.length)];
881         }
882         // TODO: Get actual visible range. <rdar://problem/4712101>
883         if ([attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute])
884             return m_object->isPasswordField() ? nil : [NSValue valueWithRange: NSMakeRange(0, m_object->textLength())];
885         if ([attributeName isEqualToString: NSAccessibilityInsertionPointLineNumberAttribute]) {
886             if (m_object->isPasswordField() || m_object->selectionStart() != m_object->selectionEnd())
887                 return nil;
888             return [NSNumber numberWithInt:m_object->doAXLineForTextMarker(m_object->textMarkerForIndex(m_object->selectionStart(), true))];
889         }
890     }
891     
892     if ([attributeName isEqualToString: NSAccessibilityURLAttribute]) {
893         KURL url = m_object->url();
894         if (url.isNull())
895             return nil;
896         return (NSURL*)url;
897     }
898
899     if ([attributeName isEqualToString: @"AXVisited"])
900         return [NSNumber numberWithBool: m_object->isVisited()];
901     
902     if ([attributeName isEqualToString: NSAccessibilityTitleAttribute]) {
903         if (m_object->isAttachment()) {
904             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityTitleAttribute]) 
905                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityTitleAttribute];
906         }
907         return m_object->title();
908     }
909     
910     if ([attributeName isEqualToString: NSAccessibilityDescriptionAttribute]) {
911         if (m_object->isAttachment()) {
912             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityDescriptionAttribute])
913                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityDescriptionAttribute];
914         }
915         return m_object->accessibilityDescription();
916     }
917     
918     if ([attributeName isEqualToString: NSAccessibilityValueAttribute]) {
919         if (m_object->isAttachment()) {
920             if ([[[self attachmentView] accessibilityAttributeNames] containsObject:NSAccessibilityValueAttribute]) 
921                 return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityValueAttribute];
922         }    
923         if (m_object->hasIntValue())
924             return [NSNumber numberWithInt:m_object->intValue()];
925         return m_object->stringValue();
926     }
927
928     if ([attributeName isEqualToString: NSAccessibilityHelpAttribute])
929         return m_object->helpText();
930
931     if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute])
932         return [NSNumber numberWithBool: m_object->isFocused()];
933
934     if ([attributeName isEqualToString: NSAccessibilityEnabledAttribute])
935         return [NSNumber numberWithBool: m_object->isEnabled()];
936
937     if ([attributeName isEqualToString: NSAccessibilitySizeAttribute]) {
938         IntSize s = m_object->size();
939         return [NSValue valueWithSize: NSMakeSize(s.width(), s.height())];
940     }
941
942     if ([attributeName isEqualToString: NSAccessibilityPositionAttribute])
943         return [self position];
944
945     if ([attributeName isEqualToString: NSAccessibilityWindowAttribute]) {
946         FrameView* fv = m_object->documentFrameView();
947         if (fv)
948             return [fv->getView() window];
949         return nil;
950     }
951     
952     if (m_object->isListBox() && [attributeName isEqualToString:NSAccessibilityOrientationAttribute])
953         return NSAccessibilityVerticalOrientationValue;
954
955     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"])
956         return [self textMarkerRangeForSelection];
957     
958     if (m_object->isAccessibilityRenderObject()) {
959         RenderObject* renderer = static_cast<AccessibilityRenderObject*>(m_object)->renderer();
960         if (!renderer)
961             return nil;
962         
963         if ([attributeName isEqualToString: @"AXStartTextMarker"])
964             return textMarkerForVisiblePosition(startOfDocument(renderer->document()));
965         if ([attributeName isEqualToString: @"AXEndTextMarker"])
966             return textMarkerForVisiblePosition(endOfDocument(renderer->document()));
967
968         if ([attributeName isEqualToString: @"AXBlockQuoteLevel"])
969             return [NSNumber numberWithInt:blockquoteLevel(renderer)];
970     }
971     
972     if ([attributeName isEqualToString: NSAccessibilityLinkedUIElementsAttribute]) {
973         AccessibilityObject* obj = m_object->linkedUIElement();
974         if (obj)
975             return (id) obj->wrapper();
976         return nil;
977     }
978
979     if ([attributeName isEqualToString: NSAccessibilitySelectedAttribute])
980         return [NSNumber numberWithBool:m_object->isSelected()];
981     
982     return nil;
983 }
984
985 - (id)accessibilityFocusedUIElement
986 {
987     RefPtr<AccessibilityObject> focusedObj = m_object->focusedUIElement();
988
989     if (!focusedObj)
990         return nil;
991     
992     return focusedObj->wrapper();
993 }
994
995 - (id)accessibilityHitTest:(NSPoint)point
996 {
997     RefPtr<AccessibilityObject> axObject = m_object->doAccessibilityHitTest(IntPoint(point));
998     if (axObject)
999         return NSAccessibilityUnignoredAncestor(axObject->wrapper());
1000     return NSAccessibilityUnignoredAncestor(self);
1001 }
1002
1003 - (BOOL)accessibilityIsAttributeSettable:(NSString*)attributeName
1004 {
1005     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"])
1006         return YES;
1007
1008     if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute])
1009         return m_object->canSetFocusAttribute();
1010
1011     if ([attributeName isEqualToString: NSAccessibilityValueAttribute])
1012         return m_object->canSetValueAttribute();
1013
1014     if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute] ||
1015         [attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute] ||
1016         [attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute])
1017         return m_object->canSetTextRangeAttributes();
1018     
1019     return NO;
1020 }
1021
1022 // accessibilityShouldUseUniqueId is an AppKit method we override so that
1023 // objects will be given a unique ID, and therefore allow AppKit to know when they
1024 // become obsolete (e.g. when the user navigates to a new web page, making this one
1025 // unrendered but not deallocated because it is in the back/forward cache).
1026 // It is important to call NSAccessibilityUnregisterUniqueIdForUIElement in the
1027 // appropriate place (e.g. dealloc) to remove these non-retained references from
1028 // AppKit's id mapping tables. We do this in detach by calling unregisterUniqueIdForUIElement.
1029 //
1030 // Registering an object is also required for observing notifications. Only registered objects can be observed.
1031 - (BOOL)accessibilityIsIgnored
1032 {
1033     if (m_object->isAttachment())
1034         return [[self attachmentView] accessibilityIsIgnored];
1035     return m_object->accessibilityIsIgnored();
1036 }
1037
1038 - (NSArray* )accessibilityParameterizedAttributeNames
1039 {
1040     if (m_object->isAttachment()) 
1041         return nil;
1042
1043     static NSArray* paramAttrs = nil;
1044     static NSArray* textParamAttrs = nil;
1045     if (paramAttrs == nil) {
1046         paramAttrs = [[NSArray alloc] initWithObjects:
1047                       @"AXUIElementForTextMarker",
1048                       @"AXTextMarkerRangeForUIElement",
1049                       @"AXLineForTextMarker",
1050                       @"AXTextMarkerRangeForLine",
1051                       @"AXStringForTextMarkerRange",
1052                       @"AXTextMarkerForPosition",
1053                       @"AXBoundsForTextMarkerRange",
1054                       @"AXAttributedStringForTextMarkerRange",
1055                       @"AXTextMarkerRangeForUnorderedTextMarkers",
1056                       @"AXNextTextMarkerForTextMarker",
1057                       @"AXPreviousTextMarkerForTextMarker",
1058                       @"AXLeftWordTextMarkerRangeForTextMarker",
1059                       @"AXRightWordTextMarkerRangeForTextMarker",
1060                       @"AXLeftLineTextMarkerRangeForTextMarker",
1061                       @"AXRightLineTextMarkerRangeForTextMarker",
1062                       @"AXSentenceTextMarkerRangeForTextMarker",
1063                       @"AXParagraphTextMarkerRangeForTextMarker",
1064                       @"AXNextWordEndTextMarkerForTextMarker",
1065                       @"AXPreviousWordStartTextMarkerForTextMarker",
1066                       @"AXNextLineEndTextMarkerForTextMarker",
1067                       @"AXPreviousLineStartTextMarkerForTextMarker",
1068                       @"AXNextSentenceEndTextMarkerForTextMarker",
1069                       @"AXPreviousSentenceStartTextMarkerForTextMarker",
1070                       @"AXNextParagraphEndTextMarkerForTextMarker",
1071                       @"AXPreviousParagraphStartTextMarkerForTextMarker",
1072                       @"AXStyleTextMarkerRangeForTextMarker",
1073                       @"AXLengthForTextMarkerRange",
1074                       nil];
1075     }
1076
1077     if (textParamAttrs == nil) {
1078         NSMutableArray* tempArray = [[NSMutableArray alloc] initWithArray:paramAttrs];
1079         [tempArray addObject:(NSString*)kAXLineForIndexParameterizedAttribute];
1080         [tempArray addObject:(NSString*)kAXRangeForLineParameterizedAttribute];
1081         [tempArray addObject:(NSString*)kAXStringForRangeParameterizedAttribute];
1082         [tempArray addObject:(NSString*)kAXRangeForPositionParameterizedAttribute];
1083         [tempArray addObject:(NSString*)kAXRangeForIndexParameterizedAttribute];
1084         [tempArray addObject:(NSString*)kAXBoundsForRangeParameterizedAttribute];
1085         [tempArray addObject:(NSString*)kAXRTFForRangeParameterizedAttribute];
1086         [tempArray addObject:(NSString*)kAXAttributedStringForRangeParameterizedAttribute];
1087         [tempArray addObject:(NSString*)kAXStyleRangeForIndexParameterizedAttribute];
1088         textParamAttrs = [[NSArray alloc] initWithArray:tempArray];
1089         [tempArray release];
1090     }
1091     
1092     if (m_object->isPasswordField())
1093         return [NSArray array];
1094     
1095     if (!m_object->isAccessibilityRenderObject())
1096         return paramAttrs;
1097
1098     if (m_object->isTextControl())
1099         return textParamAttrs;
1100
1101     return paramAttrs;
1102 }
1103
1104 - (void)accessibilityPerformAction:(NSString*)action
1105 {
1106     if (![action isEqualToString:NSAccessibilityPressAction])
1107         return;
1108     
1109     if (m_object->isAttachment())
1110         [[self attachmentView] accessibilityPerformAction:NSAccessibilityPressAction];
1111
1112     m_object->press();
1113 }
1114
1115 - (void)accessibilitySetValue:(id)value forAttribute:(NSString*)attributeName
1116 {
1117     WebCoreTextMarkerRange* textMarkerRange = nil;
1118     NSNumber*               number = nil;
1119     NSString*               string = nil;
1120     NSRange                 range = {0, 0};
1121
1122     // decode the parameter
1123     if ([[WebCoreViewFactory sharedFactory] objectIsTextMarkerRange:value])
1124         textMarkerRange = (WebCoreTextMarkerRange*) value;
1125
1126     else if ([value isKindOfClass:[NSNumber self]])
1127         number = value;
1128
1129     else if ([value isKindOfClass:[NSString self]])
1130         string = value;
1131     
1132     else if ([value isKindOfClass:[NSValue self]])
1133         range = [value rangeValue];
1134     
1135     // handle the command
1136     if ([attributeName isEqualToString: @"AXSelectedTextMarkerRange"]) {
1137         ASSERT(textMarkerRange);
1138         m_object->doSetAXSelectedTextMarkerRange([self visiblePositionRangeForTextMarkerRange:textMarkerRange]);        
1139     } else if ([attributeName isEqualToString: NSAccessibilityFocusedAttribute]) {
1140         ASSERT(number);
1141         m_object->setFocused([number intValue] != 0);
1142     } else if ([attributeName isEqualToString: NSAccessibilityValueAttribute]) {
1143         if (!string)
1144             return;
1145         m_object->setValue(string);
1146     } else if (m_object->isTextControl()) {
1147         if ([attributeName isEqualToString: NSAccessibilitySelectedTextAttribute]) {
1148             m_object->setSelectedText(string);
1149         } else if ([attributeName isEqualToString: NSAccessibilitySelectedTextRangeAttribute]) {
1150             m_object->setSelectedTextRange(PlainTextRange(range.location, range.length));
1151         } else if ([attributeName isEqualToString: NSAccessibilityVisibleCharacterRangeAttribute]) {
1152             m_object->makeRangeVisible(PlainTextRange(range.location, range.length));
1153         }
1154     }
1155 }
1156
1157 static RenderObject* rendererForView(NSView* view)
1158 {
1159     if (![view conformsToProtocol:@protocol(WebCoreFrameView)])
1160         return 0;
1161
1162     NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view;
1163     Frame* frame = [frameView _web_frame];
1164     if (!frame)
1165         return 0;
1166
1167     Node* node = frame->document()->ownerElement();
1168     if (!node)
1169         return 0;
1170
1171     return node->renderer();
1172 }
1173
1174 - (id)_accessibilityParentForSubview:(NSView*)subview
1175 {   
1176     RenderObject* renderer = rendererForView(subview);
1177     if (!renderer)
1178         return nil;
1179
1180     AccessibilityObject* obj = renderer->document()->axObjectCache()->get(renderer);
1181     if (obj)
1182         return obj->parentObjectUnignored()->wrapper();
1183     return nil;
1184 }
1185
1186 - (NSString*)accessibilityActionDescription:(NSString*)action
1187 {
1188     // we have no custom actions
1189     return NSAccessibilityActionDescription(action);
1190 }
1191
1192 // The CFAttributedStringType representation of the text associated with this accessibility
1193 // object that is specified by the given range.
1194 - (NSAttributedString*)doAXAttributedStringForRange:(NSRange)range
1195 {
1196     PlainTextRange textRange = PlainTextRange(range.location, range.length);
1197     VisiblePositionRange visiblePosRange = m_object->textMarkerRangeForRange(textRange);
1198     return [self doAXAttributedStringForTextMarkerRange:textMarkerRangeFromVisiblePositions(visiblePosRange.start, visiblePosRange.end)];
1199 }
1200
1201 // The RTF representation of the text associated with this accessibility object that is
1202 // specified by the given range.
1203 - (NSData*)doAXRTFForRange:(NSRange)range
1204 {
1205     NSAttributedString* attrString = [self doAXAttributedStringForRange:range];
1206     return [attrString RTFFromRange: NSMakeRange(0, [attrString length]) documentAttributes: nil];
1207 }
1208
1209 - (id)accessibilityAttributeValue:(NSString*)attribute forParameter:(id)parameter
1210 {
1211     WebCoreTextMarker* textMarker = nil;
1212     WebCoreTextMarkerRange* textMarkerRange = nil;
1213     NSNumber* number = nil;
1214     NSArray* array = nil;
1215     RefPtr<AccessibilityObject> uiElement = 0;
1216     NSPoint point = NSZeroPoint;
1217     bool pointSet = false;
1218     NSRange range = {0, 0};
1219     bool rangeSet = false;
1220     
1221     // basic parameter validation
1222     if (!m_object || !attribute || !parameter)
1223         return nil;
1224
1225     // common parameter type check/casting.  Nil checks in handlers catch wrong type case.
1226     // NOTE: This assumes nil is not a valid parameter, because it is indistinguishable from
1227     // a parameter of the wrong type.
1228     if ([[WebCoreViewFactory sharedFactory] objectIsTextMarker:parameter])
1229         textMarker = (WebCoreTextMarker*) parameter;
1230
1231     else if ([[WebCoreViewFactory sharedFactory] objectIsTextMarkerRange:parameter])
1232         textMarkerRange = (WebCoreTextMarkerRange*) parameter;
1233
1234     else if ([parameter isKindOfClass:[AccessibilityObjectWrapper self]])
1235         uiElement = [(AccessibilityObjectWrapper*)parameter accessibilityObject];
1236
1237     else if ([parameter isKindOfClass:[NSNumber self]])
1238         number = parameter;
1239
1240     else if ([parameter isKindOfClass:[NSArray self]])
1241         array = parameter;
1242
1243     else if ([parameter isKindOfClass:[NSValue self]] && strcmp([(NSValue*)parameter objCType], @encode(NSPoint)) == 0) {
1244         pointSet = true;
1245         point = [(NSValue*)parameter pointValue];
1246
1247     } else if ([parameter isKindOfClass:[NSValue self]] && strcmp([(NSValue*)parameter objCType], @encode(NSRange)) == 0) {
1248         rangeSet = true;
1249         range = [(NSValue*)parameter rangeValue];
1250
1251     } else {
1252         // got a parameter of a type we never use
1253         // NOTE: No ASSERT_NOT_REACHED because this can happen accidentally
1254         // while using accesstool (e.g.), forcing you to start over
1255         return nil;
1256     }
1257     
1258     // Convert values to WebCore types
1259     // FIXME: prepping all of these values as WebCore types is unnecessary in many 
1260     // cases. Re-organization of this function or performing the conversion on a 
1261     // need basis are possible improvements. 
1262     VisiblePosition visiblePos;
1263     if (textMarker)
1264         visiblePos = visiblePositionForTextMarker(textMarker);
1265     int intNumber = [number intValue];
1266     VisiblePositionRange visiblePosRange;
1267     if (textMarkerRange)
1268         visiblePosRange = [self visiblePositionRangeForTextMarkerRange:textMarkerRange];
1269     IntPoint webCorePoint = IntPoint(point);
1270     PlainTextRange plainTextRange = PlainTextRange(range.location, range.length);
1271
1272     // dispatch
1273     if ([attribute isEqualToString: @"AXUIElementForTextMarker"])
1274         return m_object->doAXUIElementForTextMarker(visiblePos)->wrapper();
1275
1276     if ([attribute isEqualToString: @"AXTextMarkerRangeForUIElement"]) {
1277         VisiblePositionRange vpRange = uiElement.get()->visiblePositionRange();
1278         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1279     }
1280
1281     if ([attribute isEqualToString: @"AXLineForTextMarker"])
1282         return [NSNumber numberWithUnsignedInt:m_object->doAXLineForTextMarker(visiblePos)];
1283
1284     if ([attribute isEqualToString: @"AXTextMarkerRangeForLine"]) {
1285         VisiblePositionRange vpRange = m_object->doAXTextMarkerRangeForLine(intNumber);
1286         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1287     }
1288
1289     if ([attribute isEqualToString: @"AXStringForTextMarkerRange"])
1290         return m_object->doAXStringForTextMarkerRange(visiblePosRange);
1291
1292     if ([attribute isEqualToString: @"AXTextMarkerForPosition"])
1293         return pointSet ? textMarkerForVisiblePosition(m_object->doAXTextMarkerForPosition(webCorePoint)) : nil;
1294
1295     if ([attribute isEqualToString: @"AXBoundsForTextMarkerRange"]) {
1296         NSRect rect = m_object->doAXBoundsForTextMarkerRange(visiblePosRange);
1297         return [NSValue valueWithRect:rect];
1298     }
1299
1300     if ([attribute isEqualToString: @"AXAttributedStringForTextMarkerRange"])
1301         return [self doAXAttributedStringForTextMarkerRange:textMarkerRange];
1302
1303     if ([attribute isEqualToString: @"AXTextMarkerRangeForUnorderedTextMarkers"]) {
1304         if ([array count] < 2)
1305             return nil;
1306
1307         WebCoreTextMarker* textMarker1 = (WebCoreTextMarker*) [array objectAtIndex:0];
1308         WebCoreTextMarker* textMarker2 = (WebCoreTextMarker*) [array objectAtIndex:1];
1309         if (![[WebCoreViewFactory sharedFactory] objectIsTextMarker:textMarker1] 
1310             || ![[WebCoreViewFactory sharedFactory] objectIsTextMarker:textMarker2])
1311             return nil;
1312
1313         VisiblePosition visiblePos1 = visiblePositionForTextMarker(textMarker1);
1314         VisiblePosition visiblePos2 = visiblePositionForTextMarker(textMarker2);
1315         VisiblePositionRange vpRange = m_object->doAXTextMarkerRangeForUnorderedTextMarkers(visiblePos1, visiblePos2);
1316         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1317     }
1318
1319     if ([attribute isEqualToString: @"AXNextTextMarkerForTextMarker"])
1320         return textMarkerForVisiblePosition(m_object->doAXNextTextMarkerForTextMarker(visiblePos));
1321
1322     if ([attribute isEqualToString: @"AXPreviousTextMarkerForTextMarker"])
1323         return textMarkerForVisiblePosition(m_object->doAXPreviousTextMarkerForTextMarker(visiblePos));
1324
1325     if ([attribute isEqualToString: @"AXLeftWordTextMarkerRangeForTextMarker"]) {
1326         VisiblePositionRange vpRange = m_object->doAXLeftWordTextMarkerRangeForTextMarker(visiblePos);
1327         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1328     }
1329
1330     if ([attribute isEqualToString: @"AXRightWordTextMarkerRangeForTextMarker"]) {
1331         VisiblePositionRange vpRange = m_object->doAXRightWordTextMarkerRangeForTextMarker(visiblePos);
1332         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1333     }
1334
1335     if ([attribute isEqualToString: @"AXLeftLineTextMarkerRangeForTextMarker"]) {
1336         VisiblePositionRange vpRange = m_object->doAXLeftLineTextMarkerRangeForTextMarker(visiblePos);
1337         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1338     }
1339
1340     if ([attribute isEqualToString: @"AXRightLineTextMarkerRangeForTextMarker"]) {
1341         VisiblePositionRange vpRange = m_object->doAXRightLineTextMarkerRangeForTextMarker(visiblePos);
1342         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1343     }
1344
1345     if ([attribute isEqualToString: @"AXSentenceTextMarkerRangeForTextMarker"]) {
1346         VisiblePositionRange vpRange = m_object->doAXSentenceTextMarkerRangeForTextMarker(visiblePos);
1347         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1348     }
1349
1350     if ([attribute isEqualToString: @"AXParagraphTextMarkerRangeForTextMarker"]) {
1351         VisiblePositionRange vpRange = m_object->doAXParagraphTextMarkerRangeForTextMarker(visiblePos);
1352         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1353     }
1354
1355     if ([attribute isEqualToString: @"AXNextWordEndTextMarkerForTextMarker"])
1356         return textMarkerForVisiblePosition(m_object->doAXNextWordEndTextMarkerForTextMarker(visiblePos));
1357
1358     if ([attribute isEqualToString: @"AXPreviousWordStartTextMarkerForTextMarker"])
1359         return textMarkerForVisiblePosition(m_object->doAXPreviousWordStartTextMarkerForTextMarker(visiblePos));
1360
1361     if ([attribute isEqualToString: @"AXNextLineEndTextMarkerForTextMarker"])
1362         return textMarkerForVisiblePosition(m_object->doAXNextLineEndTextMarkerForTextMarker(visiblePos));
1363
1364     if ([attribute isEqualToString: @"AXPreviousLineStartTextMarkerForTextMarker"])
1365         return textMarkerForVisiblePosition(m_object->doAXPreviousLineStartTextMarkerForTextMarker(visiblePos));
1366
1367     if ([attribute isEqualToString: @"AXNextSentenceEndTextMarkerForTextMarker"])
1368         return textMarkerForVisiblePosition(m_object->doAXNextSentenceEndTextMarkerForTextMarker(visiblePos));
1369
1370     if ([attribute isEqualToString: @"AXPreviousSentenceStartTextMarkerForTextMarker"])
1371         return textMarkerForVisiblePosition(m_object->doAXPreviousSentenceStartTextMarkerForTextMarker(visiblePos));
1372
1373     if ([attribute isEqualToString: @"AXNextParagraphEndTextMarkerForTextMarker"])
1374         return textMarkerForVisiblePosition(m_object->doAXNextParagraphEndTextMarkerForTextMarker(visiblePos));
1375
1376     if ([attribute isEqualToString: @"AXPreviousParagraphStartTextMarkerForTextMarker"])
1377         return textMarkerForVisiblePosition(m_object->doAXPreviousParagraphStartTextMarkerForTextMarker(visiblePos));
1378
1379     if ([attribute isEqualToString: @"AXStyleTextMarkerRangeForTextMarker"]) {
1380         VisiblePositionRange vpRange = m_object->doAXStyleTextMarkerRangeForTextMarker(visiblePos);
1381         return (id)textMarkerRangeFromVisiblePositions(vpRange.start, vpRange.end);
1382     }
1383
1384     if ([attribute isEqualToString: @"AXLengthForTextMarkerRange"]) {
1385         int length = m_object->doAXLengthForTextMarkerRange(visiblePosRange);
1386         if (length < 0)
1387             return nil;
1388         return [NSNumber numberWithInt:length];
1389     }
1390
1391     if (m_object->isTextControl()) {
1392         if ([attribute isEqualToString: (NSString*)kAXLineForIndexParameterizedAttribute])
1393             return [NSNumber numberWithUnsignedInt: m_object->doAXLineForIndex(intNumber)];
1394
1395         if ([attribute isEqualToString: (NSString*)kAXRangeForLineParameterizedAttribute]) {
1396             PlainTextRange textRange = m_object->doAXRangeForLine(intNumber);
1397             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
1398         }
1399
1400         if ([attribute isEqualToString: (NSString*)kAXStringForRangeParameterizedAttribute])
1401             return rangeSet ? (id)(m_object->doAXStringForRange(plainTextRange)) : nil;
1402
1403         if ([attribute isEqualToString: (NSString*)kAXRangeForPositionParameterizedAttribute]) {
1404             if (!pointSet)
1405                 return nil;
1406             PlainTextRange textRange = m_object->doAXRangeForPosition(webCorePoint);
1407             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
1408         }
1409
1410         if ([attribute isEqualToString: (NSString*)kAXRangeForIndexParameterizedAttribute]) {
1411             PlainTextRange textRange = m_object->doAXRangeForIndex(intNumber);
1412             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
1413         }
1414
1415         if ([attribute isEqualToString: (NSString*)kAXBoundsForRangeParameterizedAttribute]) {
1416             if (!rangeSet)
1417                 return nil;
1418             NSRect rect = m_object->doAXBoundsForRange(plainTextRange);
1419             return [NSValue valueWithRect:rect];
1420         }
1421
1422         if ([attribute isEqualToString: (NSString*)kAXRTFForRangeParameterizedAttribute])
1423             return rangeSet ? [self doAXRTFForRange:range] : nil;
1424
1425         if ([attribute isEqualToString: (NSString*)kAXAttributedStringForRangeParameterizedAttribute])
1426             return rangeSet ? [self doAXAttributedStringForRange:range] : nil;
1427
1428         if ([attribute isEqualToString: (NSString*)kAXStyleRangeForIndexParameterizedAttribute]) {
1429             PlainTextRange textRange = m_object->doAXStyleRangeForIndex(intNumber);
1430             return [NSValue valueWithRange: NSMakeRange(textRange.start, textRange.length)];
1431         }
1432     }
1433
1434     return nil;
1435 }
1436
1437 - (BOOL)accessibilityShouldUseUniqueId
1438 {
1439     return m_object->accessibilityShouldUseUniqueId();
1440 }
1441
1442 @end