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