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