AccessibilityObjectWrapper.mm 94.6 KB
Newer Older
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1
/*
2
 * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
alice.liu@apple.com's avatar
alice.liu@apple.com committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
28

alice.liu@apple.com's avatar
alice.liu@apple.com committed
29 30 31
#import "config.h"
#import "AccessibilityObjectWrapper.h"

32 33
#if HAVE(ACCESSIBILITY)

alice.liu@apple.com's avatar
alice.liu@apple.com committed
34
#import "AXObjectCache.h"
35
#import "AccessibilityListBox.h"
36
#import "AccessibilityList.h"
37
#import "AccessibilityRenderObject.h"
38 39 40 41
#import "AccessibilityTable.h"
#import "AccessibilityTableCell.h"
#import "AccessibilityTableRow.h"
#import "AccessibilityTableColumn.h"
42
#import "ColorMac.h"
alice.liu@apple.com's avatar
alice.liu@apple.com committed
43 44
#import "Frame.h"
#import "HTMLAnchorElement.h"
45
#import "HTMLAreaElement.h"
alice.liu@apple.com's avatar
alice.liu@apple.com committed
46 47 48
#import "HTMLImageElement.h"
#import "HTMLInputElement.h"
#import "HTMLTextAreaElement.h"
49
#import "LocalizedStrings.h"
alice.liu@apple.com's avatar
alice.liu@apple.com committed
50 51 52 53
#import "RenderTextControl.h"
#import "RenderView.h"
#import "RenderWidget.h"
#import "SelectionController.h"
54
#import "SimpleFontData.h"
alice.liu@apple.com's avatar
alice.liu@apple.com committed
55 56 57 58 59 60
#import "TextIterator.h"
#import "WebCoreFrameView.h"
#import "WebCoreObjCExtras.h"
#import "WebCoreViewFactory.h"
#import "htmlediting.h"
#import "visible_units.h"
ap@webkit.org's avatar
ap@webkit.org committed
61
#import <runtime/InitializeThreading.h>
alice.liu@apple.com's avatar
alice.liu@apple.com committed
62 63 64

using namespace WebCore;
using namespace HTMLNames;
65
using namespace std;
66 67

// Cell Tables
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#ifndef NSAccessibilitySelectedCellsAttribute
#define NSAccessibilitySelectedCellsAttribute @"AXSelectedCells"
#endif

#ifndef NSAccessibilityVisibleCellsAttribute
#define NSAccessibilityVisibleCellsAttribute @"AXVisibleCells"
#endif

#ifndef NSAccessibilityRowHeaderUIElementsAttribute
#define NSAccessibilityRowHeaderUIElementsAttribute @"AXRowHeaderUIElements"
#endif

#ifndef NSAccessibilityRowIndexRangeAttribute
#define NSAccessibilityRowIndexRangeAttribute @"AXRowIndexRange"
#endif

#ifndef NSAccessibilityColumnIndexRangeAttribute
#define NSAccessibilityColumnIndexRangeAttribute @"AXColumnIndexRange"
#endif

#ifndef NSAccessibilityCellForColumnAndRowParameterizedAttribute
#define NSAccessibilityCellForColumnAndRowParameterizedAttribute @"AXCellForColumnAndRow"
#endif

#ifndef NSAccessibilityCellRole
#define NSAccessibilityCellRole @"AXCell"
#endif

96 97 98 99 100 101 102 103 104
// Lists
#ifndef NSAccessibilityContentListSubrole
#define NSAccessibilityContentListSubrole @"AXContentList"
#endif

#ifndef NSAccessibilityDefinitionListSubrole
#define NSAccessibilityDefinitionListSubrole @"AXDefinitionList"
#endif

105 106 107 108 109
// Miscellaneous
#ifndef NSAccessibilityBlockQuoteLevelAttribute
#define NSAccessibilityBlockQuoteLevelAttribute @"AXBlockQuoteLevel"
#endif

110 111 112 113
#ifndef NSAccessibilityAccessKeyAttribute
#define NSAccessibilityAccessKeyAttribute @"AXAccessKey"
#endif

114 115 116 117
#ifndef NSAccessibilityLanguageAttribute
#define NSAccessibilityLanguageAttribute @"AXLanguage"
#endif

118 119 120 121
#ifndef NSAccessibilityRequiredAttribute
#define NSAccessibilityRequiredAttribute @"AXRequired"
#endif

cfleizach@apple.com's avatar
cfleizach@apple.com committed
122 123
#ifdef BUILDING_ON_TIGER
typedef unsigned NSUInteger;
cfleizach@apple.com's avatar
cfleizach@apple.com committed
124
#define NSAccessibilityValueDescriptionAttribute @"AXValueDescription"
125
#define NSAccessibilityTimelineSubrole @"AXTimeline"
cfleizach@apple.com's avatar
cfleizach@apple.com committed
126 127
#endif

128 129 130 131 132 133 134 135
@interface NSObject (WebKitAccessibilityArrayCategory)

- (NSUInteger)accessibilityIndexOfChild:(id)child;
- (NSUInteger)accessibilityArrayAttributeCount:(NSString *)attribute;
- (NSArray *)accessibilityArrayAttributeValues:(NSString *)attribute index:(NSUInteger)index maxCount:(NSUInteger)maxCount;

@end

alice.liu@apple.com's avatar
alice.liu@apple.com committed
136 137 138 139
@implementation AccessibilityObjectWrapper

+ (void)initialize
{
ap@webkit.org's avatar
ap@webkit.org committed
140 141
    JSC::initializeThreading();
#ifndef BUILDING_ON_TIGER
alice.liu@apple.com's avatar
alice.liu@apple.com committed
142 143
    WebCoreObjCFinalizeOnMainThread(self);
#endif
ap@webkit.org's avatar
ap@webkit.org committed
144
}
alice.liu@apple.com's avatar
alice.liu@apple.com committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

- (id)initWithAccessibilityObject:(AccessibilityObject*)axObject
{
    [super init];

    m_object = axObject;
    return self;
}

- (void)unregisterUniqueIdForUIElement
{
    [[WebCoreViewFactory sharedFactory] unregisterUniqueIdForUIElement:self];
}

- (void)detach
{
    // Send unregisterUniqueIdForUIElement unconditionally because if it is
    // ever accidently not done (via other bugs in our AX implementation) you
    // end up with a crash like <rdar://problem/4273149>.  It is safe and not
    // expensive to send even if the object is not registered.
    [self unregisterUniqueIdForUIElement];
    m_object = 0;
}

- (AccessibilityObject*)accessibilityObject
{
    return m_object;
}

174 175 176 177 178 179
- (NSView*)attachmentView
{
    ASSERT(m_object->isAttachment());
    Widget* widget = m_object->widgetForAttachmentView();
    if (!widget)
        return nil;
180
    return NSAccessibilityUnignoredDescendant(widget->platformWidget());
181 182 183 184 185
}

static WebCoreTextMarker* textMarkerForVisiblePosition(const VisiblePosition& visiblePos)
{
    TextMarkerData textMarkerData;
186 187 188
    AXObjectCache::textMarkerDataForVisiblePosition(textMarkerData, visiblePos);
    if (!textMarkerData.axID)
        return nil;
189
    
190 191 192 193 194 195 196 197
    return [[WebCoreViewFactory sharedFactory] textMarkerWithBytes:&textMarkerData length:sizeof(textMarkerData)];
}

static VisiblePosition visiblePositionForTextMarker(WebCoreTextMarker* textMarker)
{
    TextMarkerData textMarkerData;
    if (![[WebCoreViewFactory sharedFactory] getBytes:&textMarkerData fromTextMarker:textMarker length:sizeof(textMarkerData)])
        return VisiblePosition();
198
    
199
    return AXObjectCache::visiblePositionForTextMarkerData(textMarkerData);
200 201 202 203 204 205 206 207 208 209 210 211 212 213
}

static VisiblePosition visiblePositionForStartOfTextMarkerRange(WebCoreTextMarkerRange* textMarkerRange)
{
    return visiblePositionForTextMarker([[WebCoreViewFactory sharedFactory] startOfTextMarkerRange:textMarkerRange]);
}

static VisiblePosition visiblePositionForEndOfTextMarkerRange(WebCoreTextMarkerRange* textMarkerRange)
{
    return visiblePositionForTextMarker([[WebCoreViewFactory sharedFactory] endOfTextMarkerRange:textMarkerRange]);
}

static WebCoreTextMarkerRange* textMarkerRangeFromMarkers(WebCoreTextMarker* textMarker1, WebCoreTextMarker* textMarker2)
{
214 215 216
    if (!textMarker1 || !textMarker2)
        return nil;
        
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    return [[WebCoreViewFactory sharedFactory] textMarkerRangeWithStart:textMarker1 end:textMarker2];
}

static void AXAttributeStringSetFont(NSMutableAttributedString* attrString, NSString* attribute, NSFont* font, NSRange range)
{
    NSDictionary* dict;
    
    if (font) {
        dict = [NSDictionary dictionaryWithObjectsAndKeys:
            [font fontName]                             , NSAccessibilityFontNameKey,
            [font familyName]                           , NSAccessibilityFontFamilyKey,
            [font displayName]                          , NSAccessibilityVisibleNameKey,
            [NSNumber numberWithFloat:[font pointSize]] , NSAccessibilityFontSizeKey,
        nil];

        [attrString addAttribute:attribute value:dict range:range];
    } else
        [attrString removeAttribute:attribute range:range];
    
}

static CGColorRef CreateCGColorIfDifferent(NSColor* nsColor, CGColorRef existingColor)
{
    // get color information assuming NSDeviceRGBColorSpace 
    NSColor* rgbColor = [nsColor colorUsingColorSpaceName:NSDeviceRGBColorSpace];
    if (rgbColor == nil)
        rgbColor = [NSColor blackColor];
    CGFloat components[4];
    [rgbColor getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
    
    // create a new CGColorRef to return
248
    CGColorSpaceRef cgColorSpace = CGColorSpaceCreateDeviceRGB();
249 250 251 252
    CGColorRef cgColor = CGColorCreate(cgColorSpace, components);
    CGColorSpaceRelease(cgColorSpace);
    
    // check for match with existing color
253 254 255 256 257
    if (existingColor && CGColorEqualToColor(cgColor, existingColor)) {
        CGColorRelease(cgColor);
        cgColor = 0;
    }
    
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    return cgColor;
}

static void AXAttributeStringSetColor(NSMutableAttributedString* attrString, NSString* attribute, NSColor* color, NSRange range)
{
    if (color) {
        CGColorRef existingColor = (CGColorRef) [attrString attribute:attribute atIndex:range.location effectiveRange:nil];
        CGColorRef cgColor = CreateCGColorIfDifferent(color, existingColor);
        if (cgColor) {
            [attrString addAttribute:attribute value:(id)cgColor range:range];
            CGColorRelease(cgColor);
        }
    } else
        [attrString removeAttribute:attribute range:range];
}

static void AXAttributeStringSetNumber(NSMutableAttributedString* attrString, NSString* attribute, NSNumber* number, NSRange range)
{
    if (number)
        [attrString addAttribute:attribute value:number range:range];
    else
        [attrString removeAttribute:attribute range:range];
}

static void AXAttributeStringSetStyle(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
{
    RenderStyle* style = renderer->style();

    // set basic font info
    AXAttributeStringSetFont(attrString, NSAccessibilityFontTextAttribute, style->font().primaryFont()->getNSFont(), range);

    // set basic colors
    AXAttributeStringSetColor(attrString, NSAccessibilityForegroundColorTextAttribute, nsColor(style->color()), range);
    AXAttributeStringSetColor(attrString, NSAccessibilityBackgroundColorTextAttribute, nsColor(style->backgroundColor()), range);

    // set super/sub scripting
    EVerticalAlign alignment = style->verticalAlign();
    if (alignment == SUB)
        AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:(-1)], range);
    else if (alignment == SUPER)
        AXAttributeStringSetNumber(attrString, NSAccessibilitySuperscriptTextAttribute, [NSNumber numberWithInt:1], range);
    else
        [attrString removeAttribute:NSAccessibilitySuperscriptTextAttribute range:range];
    
    // set shadow
    if (style->textShadow())
        AXAttributeStringSetNumber(attrString, NSAccessibilityShadowTextAttribute, [NSNumber numberWithBool:YES], range);
    else
        [attrString removeAttribute:NSAccessibilityShadowTextAttribute range:range];
    
    // set underline and strikethrough
    int decor = style->textDecorationsInEffect();
    if ((decor & UNDERLINE) == 0) {
        [attrString removeAttribute:NSAccessibilityUnderlineTextAttribute range:range];
        [attrString removeAttribute:NSAccessibilityUnderlineColorTextAttribute range:range];
    }
    
    if ((decor & LINE_THROUGH) == 0) {
        [attrString removeAttribute:NSAccessibilityStrikethroughTextAttribute range:range];
        [attrString removeAttribute:NSAccessibilityStrikethroughColorTextAttribute range:range];
    }

    if ((decor & (UNDERLINE | LINE_THROUGH)) != 0) {
        // find colors using quirk mode approach (strict mode would use current
        // color for all but the root line box, which would use getTextDecorationColors)
        Color underline, overline, linethrough;
        renderer->getTextDecorationColors(decor, underline, overline, linethrough);
        
        if ((decor & UNDERLINE) != 0) {
            AXAttributeStringSetNumber(attrString, NSAccessibilityUnderlineTextAttribute, [NSNumber numberWithBool:YES], range);
            AXAttributeStringSetColor(attrString, NSAccessibilityUnderlineColorTextAttribute, nsColor(underline), range);
        }

        if ((decor & LINE_THROUGH) != 0) {
            AXAttributeStringSetNumber(attrString, NSAccessibilityStrikethroughTextAttribute, [NSNumber numberWithBool:YES], range);
            AXAttributeStringSetColor(attrString, NSAccessibilityStrikethroughColorTextAttribute, nsColor(linethrough), range);
        }
    }
}

static int blockquoteLevel(RenderObject* renderer)
{
340 341 342
    if (!renderer)
        return 0;
    
343
    int result = 0;
344
    for (Node* node = renderer->node(); node; node = node->parent()) {
345 346 347 348 349 350 351 352 353 354 355 356
        if (node->hasTagName(blockquoteTag))
            result += 1;
    }
    
    return result;
}

static void AXAttributeStringSetBlockquoteLevel(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
{
    int quoteLevel = blockquoteLevel(renderer);
    
    if (quoteLevel)
357
        [attrString addAttribute:NSAccessibilityBlockQuoteLevelAttribute value:[NSNumber numberWithInt:quoteLevel] range:range];
358
    else
359
        [attrString removeAttribute:NSAccessibilityBlockQuoteLevelAttribute range:range];
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
}

static void AXAttributeStringSetSpelling(NSMutableAttributedString* attrString, Node* node, int offset, NSRange range)
{
    Vector<DocumentMarker> markers = node->renderer()->document()->markersForNode(node);
    Vector<DocumentMarker>::iterator markerIt = markers.begin();

    unsigned endOffset = (unsigned)offset + range.length;
    for ( ; markerIt != markers.end(); markerIt++) {
        DocumentMarker marker = *markerIt;
        
        if (marker.type != DocumentMarker::Spelling)
            continue;
        
        if (marker.endOffset <= (unsigned)offset)
            continue;
        
        if (marker.startOffset > endOffset)
            break;
        
        // add misspelling attribute for the intersection of the marker and the range
        int rStart = range.location + (marker.startOffset - offset);
382
        int rLength = min(marker.endOffset, endOffset) - marker.startOffset;
383 384 385 386 387 388 389 390
        NSRange spellRange = NSMakeRange(rStart, rLength);
        AXAttributeStringSetNumber(attrString, NSAccessibilityMisspelledTextAttribute, [NSNumber numberWithBool:YES], spellRange);
        
        if (marker.endOffset > endOffset + 1)
            break;
    }
}

391
static void AXAttributeStringSetHeadingLevel(NSMutableAttributedString* attrString, RenderObject* renderer, NSRange range)
392
{
393 394 395 396 397
    if (!renderer)
        return;
    
    AccessibilityObject* parentObject = renderer->document()->axObjectCache()->getOrCreate(renderer->parent());
    int parentHeadingLevel = parentObject->headingLevel();
398 399 400 401 402 403 404 405 406
    
    if (parentHeadingLevel)
        [attrString addAttribute:@"AXHeadingLevel" value:[NSNumber numberWithInt:parentHeadingLevel] range:range];
    else
        [attrString removeAttribute:@"AXHeadingLevel" range:range];
}

static void AXAttributeStringSetElement(NSMutableAttributedString* attrString, NSString* attribute, AccessibilityObject* object, NSRange range)
{
407
    if (object && object->isAccessibilityRenderObject()) {
408
        // make a serialiazable AX object
409 410
        
        RenderObject* renderer = static_cast<AccessibilityRenderObject*>(object)->renderer();
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        if (!renderer)
            return;
        
        Document* doc = renderer->document();
        if (!doc)
            return;
        
        AXObjectCache* cache = doc->axObjectCache();
        if (!cache)
            return;

        AXUIElementRef axElement = [[WebCoreViewFactory sharedFactory] AXUIElementForElement:object->wrapper()];
        if (axElement) {
            [attrString addAttribute:attribute value:(id)axElement range:range];
            CFRelease(axElement);
        }
    } else
        [attrString removeAttribute:attribute range:range];
}

431
static void AXAttributedStringAppendText(NSMutableAttributedString* attrString, Node* node, int offset, const UChar* chars, int length)
432 433 434 435
{
    // skip invisible text
    if (!node->renderer())
        return;
436

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    // easier to calculate the range before appending the string
    NSRange attrStringRange = NSMakeRange([attrString length], length);
    
    // append the string from this node
    [[attrString mutableString] appendString:[NSString stringWithCharacters:chars length:length]];

    // add new attributes and remove irrelevant inherited ones
    // NOTE: color attributes are handled specially because -[NSMutableAttributedString addAttribute: value: range:] does not merge
    // identical colors.  Workaround is to not replace an existing color attribute if it matches what we are adding.  This also means
    // we cannot just pre-remove all inherited attributes on the appended string, so we have to remove the irrelevant ones individually.

    // remove inherited attachment from prior AXAttributedStringAppendReplaced
    [attrString removeAttribute:NSAccessibilityAttachmentTextAttribute range:attrStringRange];
    
    // set new attributes
    AXAttributeStringSetStyle(attrString, node->renderer(), attrStringRange);
453
    AXAttributeStringSetHeadingLevel(attrString, node->renderer(), attrStringRange);
454
    AXAttributeStringSetBlockquoteLevel(attrString, node->renderer(), attrStringRange);
455
    AXAttributeStringSetElement(attrString, NSAccessibilityLinkTextAttribute, AccessibilityObject::anchorElementForNode(node), attrStringRange);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    
    // do spelling last because it tends to break up the range
    AXAttributeStringSetSpelling(attrString, node, offset, attrStringRange);
}

static NSString* nsStringForReplacedNode(Node* replacedNode)
{
    // we should always be given a rendered node and a replaced node, but be safe
    // replaced nodes are either attachments (widgets) or images
    if (!replacedNode || !replacedNode->renderer() || !replacedNode->renderer()->isReplaced() || replacedNode->isTextNode()) {
        ASSERT_NOT_REACHED();
        return nil;
    }

    // create an AX object, but skip it if it is not supposed to be seen
471
    RefPtr<AccessibilityObject> obj = replacedNode->renderer()->document()->axObjectCache()->getOrCreate(replacedNode->renderer());
472 473 474 475 476 477 478 479 480 481
    if (obj->accessibilityIsIgnored())
        return nil;
    
    // use the attachmentCharacter to represent the replaced node
    const UniChar attachmentChar = NSAttachmentCharacter;
    return [NSString stringWithCharacters:&attachmentChar length:1];
}

- (NSAttributedString*)doAXAttributedStringForTextMarkerRange:(WebCoreTextMarkerRange*)textMarkerRange
{
482 483 484
    if (!m_object)
        return nil;
    
485 486 487 488 489 490 491 492 493
    // extract the start and end VisiblePosition
    VisiblePosition startVisiblePosition = visiblePositionForStartOfTextMarkerRange(textMarkerRange);
    if (startVisiblePosition.isNull())
        return nil;

    VisiblePosition endVisiblePosition = visiblePositionForEndOfTextMarkerRange(textMarkerRange);
    if (endVisiblePosition.isNull())
        return nil;

494
    VisiblePositionRange visiblePositionRange(startVisiblePosition, endVisiblePosition);
495 496 497 498 499 500 501 502 503 504 505 506
    // iterate over the range to build the AX attributed string
    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] init];
    TextIterator it(makeRange(startVisiblePosition, endVisiblePosition).get());
    while (!it.atEnd()) {
        // locate the node and starting offset for this range
        int exception = 0;
        Node* node = it.range()->startContainer(exception);
        ASSERT(node == it.range()->endContainer(exception));
        int offset = it.range()->startOffset(exception);

        // non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
        if (it.length() != 0) {
507 508 509 510 511
            // Add the text of the list marker item if necessary.
            String listMarkerText = m_object->listMarkerTextForNodeAndPosition(node, VisiblePosition(it.range()->startPosition()));
            if (!listMarkerText.isEmpty())
                AXAttributedStringAppendText(attrString, node, offset, listMarkerText.characters(), listMarkerText.length());
            
512
            AXAttributedStringAppendText(attrString, node, offset, it.characters(), it.length());
513 514 515 516 517 518 519 520 521 522 523 524 525
        } else {
            Node* replacedNode = node->childNode(offset);
            NSString *attachmentString = nsStringForReplacedNode(replacedNode);
            if (attachmentString) {
                NSRange attrStringRange = NSMakeRange([attrString length], [attachmentString length]);

                // append the placeholder string
                [[attrString mutableString] appendString:attachmentString];

                // remove all inherited attributes
                [attrString setAttributes:nil range:attrStringRange];

                // add the attachment attribute
526
                AccessibilityObject* obj = replacedNode->renderer()->document()->axObjectCache()->getOrCreate(replacedNode->renderer());
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
                AXAttributeStringSetElement(attrString, NSAccessibilityAttachmentTextAttribute, obj, attrStringRange);
            }
        }
        it.advance();
    }

    return [attrString autorelease];
}

static WebCoreTextMarkerRange* textMarkerRangeFromVisiblePositions(VisiblePosition startPosition, VisiblePosition endPosition)
{
    WebCoreTextMarker* startTextMarker = textMarkerForVisiblePosition(startPosition);
    WebCoreTextMarker* endTextMarker   = textMarkerForVisiblePosition(endPosition);
    return textMarkerRangeFromMarkers(startTextMarker, endTextMarker);
}

alice.liu@apple.com's avatar
alice.liu@apple.com committed
543 544
- (NSArray*)accessibilityActionNames
{
545 546 547
    if (!m_object)
        return nil;

548
    m_object->updateBackingStore();
549 550
    if (!m_object)
        return nil;
551

552 553
    static NSArray* actionElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityPressAction, NSAccessibilityShowMenuAction, nil];
    static NSArray* defaultElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityShowMenuAction, nil];
554
    static NSArray* menuElementActions = [[NSArray alloc] initWithObjects: NSAccessibilityCancelAction, NSAccessibilityPressAction, nil];
cfleizach@apple.com's avatar
cfleizach@apple.com committed
555 556
    static NSArray* sliderActions = [[NSArray alloc] initWithObjects: NSAccessibilityIncrementAction, NSAccessibilityDecrementAction, nil];

557 558 559
    NSArray *actions;
    if (m_object->actionElement()) 
        actions = actionElementActions;
560 561
    else if (m_object->isMenuRelated())
        actions = menuElementActions;
cfleizach@apple.com's avatar
cfleizach@apple.com committed
562 563
    else if (m_object->isSlider())
        actions = sliderActions;
564 565 566 567
    else if (m_object->isAttachment())
        actions = [[self attachmentView] accessibilityActionNames];
    else
        actions = defaultElementActions;
alice.liu@apple.com's avatar
alice.liu@apple.com committed
568 569 570 571 572 573

    return actions;
}

- (NSArray*)accessibilityAttributeNames
{
574 575 576
    if (!m_object)
        return nil;
    
577
    m_object->updateBackingStore();
578 579
    if (!m_object)
        return nil;
580
    
alice.liu@apple.com's avatar
alice.liu@apple.com committed
581
    if (m_object->isAttachment())
582
        return [[self attachmentView] accessibilityAttributeNames];
583

alice.liu@apple.com's avatar
alice.liu@apple.com committed
584 585 586 587
    static NSArray* attributes = nil;
    static NSArray* anchorAttrs = nil;
    static NSArray* webAreaAttrs = nil;
    static NSArray* textAttrs = nil;
588
    static NSArray* listBoxAttrs = nil;
bdakin@apple.com's avatar
bdakin@apple.com committed
589
    static NSArray* rangeAttrs = nil;
590 591 592 593 594
    static NSArray* commonMenuAttrs = nil;
    static NSArray* menuAttrs = nil;
    static NSArray* menuBarAttrs = nil;
    static NSArray* menuItemAttrs = nil;
    static NSArray* menuButtonAttrs = nil;
595
    static NSArray* controlAttrs = nil;
596 597 598 599
    static NSArray* tableAttrs = nil;
    static NSArray* tableRowAttrs = nil;
    static NSArray* tableColAttrs = nil;
    static NSArray* tableCellAttrs = nil;
600
    static NSArray* groupAttrs = nil;
601
    static NSArray* inputImageAttrs = nil;
602
    static NSArray* passwordFieldAttrs = nil;
alice.liu@apple.com's avatar
alice.liu@apple.com committed
603 604 605
    NSMutableArray* tempArray;
    if (attributes == nil) {
        attributes = [[NSArray alloc] initWithObjects: NSAccessibilityRoleAttribute,
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
                      NSAccessibilitySubroleAttribute,
                      NSAccessibilityRoleDescriptionAttribute,
                      NSAccessibilityChildrenAttribute,
                      NSAccessibilityHelpAttribute,
                      NSAccessibilityParentAttribute,
                      NSAccessibilityPositionAttribute,
                      NSAccessibilitySizeAttribute,
                      NSAccessibilityTitleAttribute,
                      NSAccessibilityDescriptionAttribute,
                      NSAccessibilityValueAttribute,
                      NSAccessibilityFocusedAttribute,
                      NSAccessibilityEnabledAttribute,
                      NSAccessibilityWindowAttribute,
                      @"AXSelectedTextMarkerRange",
                      @"AXStartTextMarker",
                      @"AXEndTextMarker",
                      @"AXVisited",
                      NSAccessibilityLinkedUIElementsAttribute,
                      NSAccessibilitySelectedAttribute,
625
                      NSAccessibilityBlockQuoteLevelAttribute,
626
                      NSAccessibilityTopLevelUIElementAttribute,
627
                      nil];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
628
    }
629 630 631 632 633 634 635 636 637 638
    if (commonMenuAttrs == nil) {
        commonMenuAttrs = [[NSArray alloc] initWithObjects: NSAccessibilityRoleAttribute,
                            NSAccessibilityRoleDescriptionAttribute,
                            NSAccessibilityChildrenAttribute,
                            NSAccessibilityParentAttribute,
                            NSAccessibilityEnabledAttribute,
                            NSAccessibilityPositionAttribute,
                            NSAccessibilitySizeAttribute,
                            nil];
    }
alice.liu@apple.com's avatar
alice.liu@apple.com committed
639 640 641
    if (anchorAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityURLAttribute];
642
        [tempArray addObject:NSAccessibilityAccessKeyAttribute];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
643 644 645 646 647 648 649 650
        anchorAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (webAreaAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:@"AXLinkUIElements"];
        [tempArray addObject:@"AXLoaded"];
        [tempArray addObject:@"AXLayoutCount"];
651
        [tempArray addObject:NSAccessibilityURLAttribute];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
652 653 654 655 656 657 658 659 660 661
        webAreaAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (textAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityNumberOfCharactersAttribute];
        [tempArray addObject:NSAccessibilitySelectedTextAttribute];
        [tempArray addObject:NSAccessibilitySelectedTextRangeAttribute];
        [tempArray addObject:NSAccessibilityVisibleCharacterRangeAttribute];
        [tempArray addObject:NSAccessibilityInsertionPointLineNumberAttribute];
662
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
663
        [tempArray addObject:NSAccessibilityAccessKeyAttribute];
664
        [tempArray addObject:NSAccessibilityRequiredAttribute];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
665 666 667
        textAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
668 669 670 671 672
    if (listBoxAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
        [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
        [tempArray addObject:NSAccessibilityOrientationAttribute];
673
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
674
        [tempArray addObject:NSAccessibilityAccessKeyAttribute];
675
        [tempArray addObject:NSAccessibilityRequiredAttribute];
676 677 678
        listBoxAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
bdakin@apple.com's avatar
bdakin@apple.com committed
679
    if (rangeAttrs == nil) {
680 681 682 683 684
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityTopLevelUIElementAttribute];
        [tempArray addObject:NSAccessibilityValueAttribute];
        [tempArray addObject:NSAccessibilityMinValueAttribute];
        [tempArray addObject:NSAccessibilityMaxValueAttribute];
cfleizach@apple.com's avatar
cfleizach@apple.com committed
685
        [tempArray addObject:NSAccessibilityOrientationAttribute];
686
        [tempArray addObject:NSAccessibilityValueDescriptionAttribute];
bdakin@apple.com's avatar
bdakin@apple.com committed
687
        rangeAttrs = [[NSArray alloc] initWithArray:tempArray];
688 689
        [tempArray release];
    }
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
    if (menuBarAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
        [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
        [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
        menuBarAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (menuAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
        [tempArray addObject:NSAccessibilitySelectedChildrenAttribute];
        [tempArray addObject:NSAccessibilityVisibleChildrenAttribute];
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
        menuAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (menuItemAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:commonMenuAttrs];
        [tempArray addObject:NSAccessibilityTitleAttribute];
        [tempArray addObject:NSAccessibilityHelpAttribute];
        [tempArray addObject:NSAccessibilitySelectedAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemCmdCharAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemCmdVirtualKeyAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemCmdGlyphAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemCmdModifiersAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemMarkCharAttribute];
        [tempArray addObject:(NSString*)kAXMenuItemPrimaryUIElementAttribute];
        [tempArray addObject:NSAccessibilityServesAsTitleForUIElementsAttribute];
        menuItemAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (menuButtonAttrs == nil) {
        menuButtonAttrs = [[NSArray alloc] initWithObjects:NSAccessibilityRoleAttribute,
            NSAccessibilityRoleDescriptionAttribute,
            NSAccessibilityParentAttribute,
            NSAccessibilityPositionAttribute,
            NSAccessibilitySizeAttribute,
            NSAccessibilityWindowAttribute,
            NSAccessibilityTopLevelUIElementAttribute,
            NSAccessibilityEnabledAttribute,
            NSAccessibilityFocusedAttribute,
            NSAccessibilityTitleAttribute,
            NSAccessibilityChildrenAttribute, nil];
    }
734 735 736
    if (controlAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
737
        [tempArray addObject:NSAccessibilityAccessKeyAttribute];
738
        [tempArray addObject:NSAccessibilityRequiredAttribute];
739 740 741
        controlAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    if (tableAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityRowsAttribute];
        [tempArray addObject:NSAccessibilityVisibleRowsAttribute];
        [tempArray addObject:NSAccessibilityColumnsAttribute];
        [tempArray addObject:NSAccessibilityVisibleColumnsAttribute];
        [tempArray addObject:NSAccessibilityVisibleCellsAttribute];
        [tempArray addObject:(NSString *)kAXColumnHeaderUIElementsAttribute];
        [tempArray addObject:NSAccessibilityRowHeaderUIElementsAttribute];
        [tempArray addObject:NSAccessibilityHeaderAttribute];
        tableAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (tableRowAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityIndexAttribute];
        tableRowAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (tableColAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityIndexAttribute];
        [tempArray addObject:NSAccessibilityHeaderAttribute];
        [tempArray addObject:NSAccessibilityRowsAttribute];
        [tempArray addObject:NSAccessibilityVisibleRowsAttribute];
        tableColAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
    if (tableCellAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityRowIndexRangeAttribute];
        [tempArray addObject:NSAccessibilityColumnIndexRangeAttribute];
        tableCellAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];        
    }
777 778 779 780 781 782
    if (groupAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
        groupAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
783 784 785
    if (inputImageAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:controlAttrs];
        [tempArray addObject:NSAccessibilityURLAttribute];
786
        [tempArray addObject:NSAccessibilityAccessKeyAttribute];
787 788 789
        inputImageAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
790 791 792
    if (passwordFieldAttrs == nil) {
        tempArray = [[NSMutableArray alloc] initWithArray:attributes];
        [tempArray addObject:NSAccessibilityTitleUIElementAttribute];
793
        [tempArray addObject:NSAccessibilityRequiredAttribute];
794 795 796
        passwordFieldAttrs = [[NSArray alloc] initWithArray:tempArray];
        [tempArray release];
    }
797
    
alice.liu@apple.com's avatar
alice.liu@apple.com committed
798
    if (m_object->isPasswordField())
799
        return passwordFieldAttrs;
alice.liu@apple.com's avatar
alice.liu@apple.com committed
800 801 802 803 804 805 806

    if (m_object->isWebArea())
        return webAreaAttrs;
    
    if (m_object->isTextControl())
        return textAttrs;

807
    if (m_object->isAnchor() || m_object->isImage() || m_object->isLink())
alice.liu@apple.com's avatar
alice.liu@apple.com committed
808 809
        return anchorAttrs;

810 811 812 813 814 815 816 817 818
    if (m_object->isDataTable())
        return tableAttrs;
    if (m_object->isTableRow())
        return tableRowAttrs;
    if (m_object->isTableColumn())
        return tableColAttrs;
    if (m_object->isTableCell())
        return tableCellAttrs;
    
819
    if (m_object->isListBox() || m_object->isList())
820 821
        return listBoxAttrs;

bdakin@apple.com's avatar
bdakin@apple.com committed
822 823
    if (m_object->isProgressIndicator() || m_object->isSlider())
        return rangeAttrs;
824

825 826 827
    if (m_object->isInputImage())
        return inputImageAttrs;
    
828 829 830
    if (m_object->isControl())
        return controlAttrs;
    
831 832 833
    if (m_object->isGroup())
        return groupAttrs;
    
834 835 836 837 838 839 840 841 842
    if (m_object->isMenu())
        return menuAttrs;
    if (m_object->isMenuBar())
        return menuBarAttrs;
    if (m_object->isMenuButton())
        return menuButtonAttrs;
    if (m_object->isMenuItem())
        return menuItemAttrs;

alice.liu@apple.com's avatar
alice.liu@apple.com committed
843 844 845 846 847
    return attributes;
}

- (VisiblePositionRange)visiblePositionRangeForTextMarkerRange:(WebCoreTextMarkerRange*) textMarkerRange
{
848
    return VisiblePositionRange(visiblePositionForStartOfTextMarkerRange(textMarkerRange), visiblePositionForEndOfTextMarkerRange(textMarkerRange));
alice.liu@apple.com's avatar
alice.liu@apple.com committed
849 850 851 852 853 854 855
}

- (NSArray*)renderWidgetChildren
{
    Widget* widget = m_object->widget();
    if (!widget)
        return nil;
856
    return [(widget->platformWidget()) accessibilityAttributeValue: NSAccessibilityChildrenAttribute];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
857 858
}

859 860 861
static void convertToVector(NSArray* array, AccessibilityObject::AccessibilityChildrenVector& vector)
{
    unsigned length = [array count];
darin@apple.com's avatar
darin@apple.com committed
862
    vector.reserveInitialCapacity(length);
863 864 865 866 867 868 869 870
    for (unsigned i = 0; i < length; ++i) {
        AccessibilityObject* obj = [[array objectAtIndex:i] accessibilityObject];
        if (obj)
            vector.append(obj);
    }
}

static NSMutableArray* convertToNSArray(const AccessibilityObject::AccessibilityChildrenVector& vector)
alice.liu@apple.com's avatar
alice.liu@apple.com committed
871 872 873
{
    unsigned length = vector.size();
    NSMutableArray* array = [NSMutableArray arrayWithCapacity: length];
874
    for (unsigned i = 0; i < length; ++i) {
875 876 877 878 879 880 881 882 883 884
        AccessibilityObjectWrapper* wrapper = vector[i]->wrapper();
        ASSERT(wrapper);
        if (wrapper) {
            // we want to return the attachment view instead of the object representing the attachment.
            // otherwise, we get palindrome errors in the AX hierarchy
            if (vector[i]->isAttachment() && [wrapper attachmentView])
                [array addObject:[wrapper attachmentView]];
            else
                [array addObject:wrapper];
        }
885
    }
alice.liu@apple.com's avatar
alice.liu@apple.com committed
886 887 888
    return array;
}

889 890
- (WebCoreTextMarkerRange*)textMarkerRangeForSelection
{
891
    VisibleSelection selection = m_object->selection();
892 893 894 895 896 897 898
    if (selection.isNone())
        return nil;
    return textMarkerRangeFromVisiblePositions(selection.visibleStart(), selection.visibleEnd());
}

- (NSValue*)position
{
899
    IntRect rect = m_object->elementRect();
900 901 902
    
    // The Cocoa accessibility API wants the lower-left corner.
    NSPoint point = NSMakePoint(rect.x(), rect.bottom());
alice.liu@apple.com's avatar
alice.liu@apple.com committed
903
    FrameView* frameView = m_object->documentFrameView();
904
    if (frameView) {
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
        NSView* view = frameView->documentView();
        point = [[view window] convertBaseToScreen: [view convertPoint: point toView:nil]];
    }

    return [NSValue valueWithPoint: point];
}

typedef HashMap<int, NSString*> AccessibilityRoleMap;

static const AccessibilityRoleMap& createAccessibilityRoleMap()
{
    struct RoleEntry {
        AccessibilityRole value;
        NSString* string;
    };
    
    static const RoleEntry roles[] = {
        { UnknownRole, NSAccessibilityUnknownRole },
        { ButtonRole, NSAccessibilityButtonRole },
        { RadioButtonRole, NSAccessibilityRadioButtonRole },
        { CheckBoxRole, NSAccessibilityCheckBoxRole },
        { SliderRole, NSAccessibilitySliderRole },
        { TabGroupRole, NSAccessibilityTabGroupRole },
        { TextFieldRole, NSAccessibilityTextFieldRole },
        { StaticTextRole, NSAccessibilityStaticTextRole },
        { TextAreaRole, NSAccessibilityTextAreaRole },
        { ScrollAreaRole, NSAccessibilityScrollAreaRole },
        { PopUpButtonRole, NSAccessibilityPopUpButtonRole },
        { MenuButtonRole, NSAccessibilityMenuButtonRole },
        { TableRole, NSAccessibilityTableRole },
        { ApplicationRole, NSAccessibilityApplicationRole },
        { GroupRole, NSAccessibilityGroupRole },
        { RadioGroupRole, NSAccessibilityRadioGroupRole },
        { ListRole, NSAccessibilityListRole },
        { ScrollBarRole, NSAccessibilityScrollBarRole },
        { ValueIndicatorRole, NSAccessibilityValueIndicatorRole },
        { ImageRole, NSAccessibilityImageRole },
        { MenuBarRole, NSAccessibilityMenuBarRole },
        { MenuRole, NSAccessibilityMenuRole },
        { MenuItemRole, NSAccessibilityMenuItemRole },
        { ColumnRole, NSAccessibilityColumnRole },
        { RowRole, NSAccessibilityRowRole },
        { ToolbarRole, NSAccessibilityToolbarRole },
        { BusyIndicatorRole, NSAccessibilityBusyIndicatorRole },
        { ProgressIndicatorRole, NSAccessibilityProgressIndicatorRole },
        { WindowRole, NSAccessibilityWindowRole },
        { DrawerRole, NSAccessibilityDrawerRole },
        { SystemWideRole, NSAccessibilitySystemWideRole },
        { OutlineRole, NSAccessibilityOutlineRole },
        { IncrementorRole, NSAccessibilityIncrementorRole },
        { BrowserRole, NSAccessibilityBrowserRole },
        { ComboBoxRole, NSAccessibilityComboBoxRole },
        { SplitGroupRole, NSAccessibilitySplitGroupRole },
        { SplitterRole, NSAccessibilitySplitterRole },
        { ColorWellRole, NSAccessibilityColorWellRole },
        { GrowAreaRole, NSAccessibilityGrowAreaRole },
        { SheetRole, NSAccessibilitySheetRole },
        { HelpTagRole, NSAccessibilityHelpTagRole },
        { MatteRole, NSAccessibilityMatteRole }, 
        { RulerRole, NSAccessibilityRulerRole },
        { RulerMarkerRole, NSAccessibilityRulerMarkerRole },
        { LinkRole, NSAccessibilityLinkRole },
#ifndef BUILDING_ON_TIGER        
        { DisclosureTriangleRole, NSAccessibilityDisclosureTriangleRole },
        { GridRole, NSAccessibilityGridRole },
#endif
971 972
        { WebCoreLinkRole, NSAccessibilityLinkRole }, 
        { ImageMapLinkRole, NSAccessibilityLinkRole },
973 974 975
        { ImageMapRole, @"AXImageMap" },
        { ListMarkerRole, @"AXListMarker" },
        { WebAreaRole, @"AXWebArea" },
976 977
        { HeadingRole, @"AXHeading" },
        { ListBoxRole, NSAccessibilityListRole },
978
        { ListBoxOptionRole, NSAccessibilityStaticTextRole },
979
#if ACCESSIBILITY_TABLES
980
        { CellRole, NSAccessibilityCellRole },
981 982
#else
        { CellRole, NSAccessibilityGroupRole },
983
#endif
984 985
        { TableHeaderContainerRole, NSAccessibilityGroupRole },
        { DefinitionListDefinitionRole, NSAccessibilityGroupRole },
986
        { DefinitionListTermRole, NSAccessibilityGroupRole },
987
        { SliderThumbRole, NSAccessibilityValueIndicatorRole },
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
        { LandmarkApplicationRole, NSAccessibilityGroupRole },
        { LandmarkBannerRole, NSAccessibilityGroupRole },
        { LandmarkComplementaryRole, NSAccessibilityGroupRole },
        { LandmarkContentInfoRole, NSAccessibilityGroupRole },
        { LandmarkMainRole, NSAccessibilityGroupRole },
        { LandmarkNavigationRole, NSAccessibilityGroupRole },
        { LandmarkSearchRole, NSAccessibilityGroupRole },
        { ApplicationLogRole, NSAccessibilityGroupRole },
        { ApplicationMarqueeRole, NSAccessibilityGroupRole },
        { ApplicationStatusRole, NSAccessibilityGroupRole },
        { ApplicationTimerRole, NSAccessibilityGroupRole },
        { DocumentRole, NSAccessibilityGroupRole },
        { DocumentArticleRole, NSAccessibilityGroupRole },
        { DocumentNoteRole, NSAccessibilityGroupRole },
        { DocumentRegionRole, NSAccessibilityGroupRole },
        { UserInterfaceTooltipRole, NSAccessibilityGroupRole },
1004 1005
        

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    };
    AccessibilityRoleMap& roleMap = *new AccessibilityRoleMap;
    
    const unsigned numRoles = sizeof(roles) / sizeof(roles[0]);
    for (unsigned i = 0; i < numRoles; ++i)
        roleMap.set(roles[i].value, roles[i].string);
    return roleMap;
}

static NSString* roleValueToNSString(AccessibilityRole value)
{
    ASSERT(value);
    static const AccessibilityRoleMap& roleMap = createAccessibilityRoleMap();
    return roleMap.get(value);
}

- (NSString*)role
{
    if (m_object->isAttachment())
        return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleAttribute];
    NSString* string = roleValueToNSString(m_object->roleValue());
    if (string != nil)
        return string;
    return NSAccessibilityUnknownRole;
}

- (NSString*)subrole
{
    if (m_object->isPasswordField())
        return NSAccessibilitySecureTextFieldSubrole;
    
    if (m_object->isAttachment()) {
        NSView* attachView = [self attachmentView];
        if ([[attachView accessibilityAttributeNames] containsObject:NSAccessibilitySubroleAttribute]) {
            return [attachView accessibilityAttributeValue:NSAccessibilitySubroleAttribute];
        }
    }
1043 1044 1045 1046 1047 1048 1049 1050 1051
    
    if (m_object->isList()) {
        AccessibilityList* listObject = static_cast<AccessibilityList*>(m_object);
        if (listObject->isUnorderedList() || listObject->isOrderedList())
            return NSAccessibilityContentListSubrole;
        if (listObject->isDefinitionList())
            return NSAccessibilityDefinitionListSubrole;
    }
    
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    // ARIA content subroles.
    switch (m_object->roleValue()) {
        case LandmarkApplicationRole:
            return @"AXLandmarkApplication";
        case LandmarkBannerRole:
            return @"AXLandmarkBanner";
        case LandmarkComplementaryRole:
            return @"AXLandmarkComplementary";
        case LandmarkContentInfoRole:
            return @"AXLandmarkContentInfo";
        case LandmarkMainRole:
            return @"AXLandmarkMain";
        case LandmarkNavigationRole:
            return @"AXLandmarkNavigation";
        case LandmarkSearchRole:
            return @"AXLandmarkSearch";
        case ApplicationLogRole:
            return @"AXApplicationLog";
        case ApplicationMarqueeRole:
            return @"AXApplicationMarquee";
        case ApplicationStatusRole:
            return @"AXApplicationStatus";
        case ApplicationTimerRole:
            return @"AXApplicationTimer";
        case DocumentRole:
            return @"AXDocument";
        case DocumentArticleRole:
            return @"AXDocumentArticle";
        case DocumentNoteRole:
            return @"AXDocumentNote";
        case DocumentRegionRole:
            return @"AXDocumentRegion";
        case UserInterfaceTooltipRole:
            return @"AXUserInterfaceTooltip";
        default:
            return nil;
    }
    
1090 1091 1092
    if (m_object->isMediaTimeline())
        return NSAccessibilityTimelineSubrole;

1093 1094 1095 1096 1097
    return nil;
}

- (NSString*)roleDescription
{
1098
    if (!m_object)
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        return nil;

    // attachments have the AXImage role, but a different subrole
    if (m_object->isAttachment())
        return [[self attachmentView] accessibilityAttributeValue:NSAccessibilityRoleDescriptionAttribute];
    
    // FIXME 3447564: It would be better to call some AppKit API to get these strings
    // (which would be the best way to localize them)
    
    NSString* axRole = [self role];
    if ([axRole isEqualToString:NSAccessibilityButtonRole])
        return NSAccessibilityRoleDescription(NSAccessibilityButtonRole, [self subrole]);
    
    if ([axRole isEqualToString:NSAccessibilityPopUpButtonRole])
        return NSAccessibilityRoleDescription(NSAccessibilityPopUpButtonRole, [self subrole]);
1114

1115 1116 1117 1118 1119 1120
    if ([axRole isEqualToString:NSAccessibilityStaticTextRole])
        return NSAccessibilityRoleDescription(NSAccessibilityStaticTextRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityImageRole])
        return NSAccessibilityRoleDescription(NSAccessibilityImageRole, [self subrole]);
    
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    if ([axRole isEqualToString:NSAccessibilityGroupRole]) {
        switch (m_object->roleValue()) {
            default:
                return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, [self subrole]);
            case LandmarkApplicationRole:
                return AXARIAContentGroupText(@"ARIALandmarkApplication");
            case LandmarkBannerRole:
                return AXARIAContentGroupText(@"ARIALandmarkBanner");
            case LandmarkComplementaryRole:
                return AXARIAContentGroupText(@"ARIALandmarkComplementary");
            case LandmarkContentInfoRole:
                return AXARIAContentGroupText(@"ARIALandmarkContentInfo");
            case LandmarkMainRole:
                return AXARIAContentGroupText(@"ARIALandmarkMain");
            case LandmarkNavigationRole:
                return AXARIAContentGroupText(@"ARIALandmarkNavigation");
            case LandmarkSearchRole:
                return AXARIAContentGroupText(@"ARIALandmarkSearch");
            case ApplicationLogRole:
                return AXARIAContentGroupText(@"ARIAApplicationLog");
            case ApplicationMarqueeRole:
                return AXARIAContentGroupText(@"ARIAApplicationMarquee");
            case ApplicationStatusRole:
                return AXARIAContentGroupText(@"ARIAApplicationStatus");
            case ApplicationTimerRole:
                return AXARIAContentGroupText(@"ARIAApplicationTimer");
            case DocumentRole:
                return AXARIAContentGroupText(@"ARIADocument");
            case DocumentArticleRole:
                return AXARIAContentGroupText(@"ARIADocumentArticle");
            case DocumentNoteRole:
                return AXARIAContentGroupText(@"ARIADocumentNote");
            case DocumentRegionRole:
                return AXARIAContentGroupText(@"ARIADocumentRegion");
            case UserInterfaceTooltipRole:
                return AXARIAContentGroupText(@"ARIAUserInterfaceTooltip");
        }
    }        
1159 1160 1161
    
    if ([axRole isEqualToString:NSAccessibilityCheckBoxRole])
        return NSAccessibilityRoleDescription(NSAccessibilityCheckBoxRole, [self subrole]);
1162

1163 1164
    if ([axRole isEqualToString:NSAccessibilityRadioButtonRole])
        return NSAccessibilityRoleDescription(NSAccessibilityRadioButtonRole, [self subrole]);
1165

1166 1167 1168
    if ([axRole isEqualToString:NSAccessibilityRadioGroupRole])
        return NSAccessibilityRoleDescription(NSAccessibilityRadioGroupRole, [self subrole]);

1169 1170 1171 1172 1173 1174
    if ([axRole isEqualToString:NSAccessibilityTextFieldRole])
        return NSAccessibilityRoleDescription(NSAccessibilityTextFieldRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityTextAreaRole])
        return NSAccessibilityRoleDescription(NSAccessibilityTextAreaRole, [self subrole]);

1175 1176 1177
    if ([axRole isEqualToString:NSAccessibilityListRole])
        return NSAccessibilityRoleDescription(NSAccessibilityListRole, [self subrole]);
    
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    if ([axRole isEqualToString:NSAccessibilityTableRole])
        return NSAccessibilityRoleDescription(NSAccessibilityTableRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityRowRole])
        return NSAccessibilityRoleDescription(NSAccessibilityRowRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityColumnRole])
        return NSAccessibilityRoleDescription(NSAccessibilityColumnRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityCellRole])
        return NSAccessibilityRoleDescription(NSAccessibilityCellRole, [self subrole]);

1190 1191 1192 1193 1194 1195
    if ([axRole isEqualToString:NSAccessibilitySliderRole])
        return NSAccessibilityRoleDescription(NSAccessibilitySliderRole, [self subrole]);

    if ([axRole isEqualToString:NSAccessibilityValueIndicatorRole])
        return NSAccessibilityRoleDescription(NSAccessibilityValueIndicatorRole, [self subrole]);

1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    if ([axRole isEqualToString:@"AXWebArea"])
        return AXWebAreaText();
    
    if ([axRole isEqualToString:@"AXLink"])
        return AXLinkText();
    
    if ([axRole isEqualToString:@"AXListMarker"])
        return AXListMarkerText();
    
    if ([axRole isEqualToString:@"AXImageMap"])
        return AXImageMapText();

    if ([axRole isEqualToString:@"AXHeading"])
        return AXHeadingText();
1210 1211 1212 1213 1214 1215 1216
        
    if ([axRole isEqualToString:(NSString*)kAXMenuBarItemRole] ||
        [axRole isEqualToString:NSAccessibilityMenuRole])
        return nil;

    if ([axRole isEqualToString:NSAccessibilityMenuButtonRole])
        return NSAccessibilityRoleDescription(NSAccessibilityMenuButtonRole, [self subrole]);
1217
    
1218 1219
    if ([axRole isEqualToString:NSAccessibilityToolbarRole])
        return NSAccessibilityRoleDescription(NSAccessibilityToolbarRole, [self subrole]);
1220

1221 1222 1223
    if ([axRole isEqualToString:NSAccessibilitySplitterRole])
        return NSAccessibilityRoleDescription(NSAccessibilitySplitterRole, [self subrole]);
    
1224 1225 1226
    return NSAccessibilityRoleDescription(NSAccessibilityUnknownRole, nil);
}

alice.liu@apple.com's avatar
alice.liu@apple.com committed
1227 1228 1229 1230 1231
// FIXME: split up this function in a better way.  
// suggestions: Use a hash table that maps attribute names to function calls,
// or maybe pointers to member functions
- (id)accessibilityAttributeValue:(NSString*)attributeName
{
1232
    if (!m_object)
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1233 1234
        return nil;

1235
    m_object->updateBackingStore();
1236 1237
    if (!m_object)
        return nil;
1238
    
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1239
    if ([attributeName isEqualToString: NSAccessibilityRoleAttribute])
1240
        return [self role];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1241 1242

    if ([attributeName isEqualToString: NSAccessibilitySubroleAttribute])
1243
        return [self subrole];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1244 1245

    if ([attributeName isEqualToString: NSAccessibilityRoleDescriptionAttribute])
1246
        return [self roleDescription];
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1247 1248

    if ([attributeName isEqualToString: NSAccessibilityParentAttribute]) {
1249 1250 1251
        if (m_object->isAccessibilityRenderObject()) {
            FrameView* fv = static_cast<AccessibilityRenderObject*>(m_object)->frameViewIfRenderView();
            if (fv)
hyatt@apple.com's avatar
hyatt@apple.com committed
1252
                return fv->platformWidget();
1253 1254
        }
        
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1255 1256 1257 1258
        return m_object->parentObjectUnignored()->wrapper();
    }

    if ([attributeName isEqualToString: NSAccessibilityChildrenAttribute]) {
1259
        if (m_object->children().isEmpty()) {
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1260 1261 1262 1263 1264 1265
            NSArray* children = [self renderWidgetChildren];
            if (children != nil)
                return children;
        }
        return convertToNSArray(m_object->children());
    }
1266
    
1267 1268 1269 1270 1271 1272 1273
    if ([attributeName isEqualToString: NSAccessibilitySelectedChildrenAttribute]) {
        if (m_object->isListBox()) {
            AccessibilityObject::AccessibilityChildrenVector selectedChildrenCopy;
            m_object->selectedChildren(selectedChildrenCopy);
            return convertToNSArray(selectedChildrenCopy);
        }
        return nil;
1274
    }
1275
    
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    if ([attributeName isEqualToString: NSAccessibilityVisibleChildrenAttribute]) {
        if (m_object->isListBox()) {
            AccessibilityObject::AccessibilityChildrenVector visibleChildrenCopy;
            m_object->visibleChildren(visibleChildrenCopy);
            return convertToNSArray(visibleChildrenCopy);
        }
        else if (m_object->isList())
            return [self accessibilityAttributeValue:NSAccessibilityChildrenAttribute];

        return nil;
1286
    }
1287 1288
    
    
alice.liu@apple.com's avatar
alice.liu@apple.com committed
1289 1290
    if (m_object->isWebArea()) {
        if ([attributeName isEqualToString: @"AXLinkUIElements"]) {
1291
            AccessibilityObject::AccessibilityChildrenVector links;