2009-12-07 Joanmarie Diggs <joanmarie.diggs@gmail.com>
[WebKit-https.git] / WebCore / accessibility / gtk / AccessibilityObjectWrapperAtk.cpp
1 /*
2  * Copyright (C) 2008 Nuanti Ltd.
3  * Copyright (C) 2009 Igalia S.L.
4  * Copyright (C) 2009 Jan Alonzo
5  *
6  * Portions from Mozilla a11y, copyright as follows:
7  *
8  * The Original Code is mozilla.org code.
9  *
10  * The Initial Developer of the Original Code is
11  * Sun Microsystems, Inc.
12  * Portions created by the Initial Developer are Copyright (C) 2002
13  * the Initial Developer. All Rights Reserved.
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Library General Public
17  * License as published by the Free Software Foundation; either
18  * version 2 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Library General Public License for more details.
24  *
25  * You should have received a copy of the GNU Library General Public License
26  * along with this library; see the file COPYING.LIB.  If not, write to
27  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28  * Boston, MA 02110-1301, USA.
29  */
30
31 #include "config.h"
32 #include "AccessibilityObjectWrapperAtk.h"
33
34 #if HAVE(ACCESSIBILITY)
35
36 #include "AXObjectCache.h"
37 #include "AccessibilityListBox.h"
38 #include "AccessibilityListBoxOption.h"
39 #include "AccessibilityRenderObject.h"
40 #include "AccessibilityTable.h"
41 #include "AccessibilityTableCell.h"
42 #include "AccessibilityTableColumn.h"
43 #include "AccessibilityTableRow.h"
44 #include "AtomicString.h"
45 #include "CString.h"
46 #include "Document.h"
47 #include "DocumentType.h"
48 #include "Editor.h"
49 #include "Frame.h"
50 #include "FrameView.h"
51 #include "HostWindow.h"
52 #include "HTMLNames.h"
53 #include "HTMLTableCaptionElement.h"
54 #include "HTMLTableElement.h"
55 #include "InlineTextBox.h"
56 #include "IntRect.h"
57 #include "NotImplemented.h"
58 #include "RenderText.h"
59 #include "TextEncoding.h"
60
61 #include <atk/atk.h>
62 #include <glib.h>
63 #include <glib/gprintf.h>
64 #include <libgail-util/gail-util.h>
65 #include <pango/pango.h>
66
67 using namespace WebCore;
68
69 static AccessibilityObject* fallbackObject()
70 {
71     static AXObjectCache* fallbackCache = new AXObjectCache;
72     static AccessibilityObject* object = 0;
73     if (!object) {
74         // FIXME: using fallbackCache->getOrCreate(ListBoxOptionRole) is a hack
75         object = fallbackCache->getOrCreate(ListBoxOptionRole);
76         object->ref();
77     }
78
79     return object;
80 }
81
82 // Used to provide const char* returns.
83 static const char* returnString(const String& str)
84 {
85     static CString returnedString;
86     returnedString = str.utf8();
87     return returnedString.data();
88 }
89
90 static AccessibilityObject* core(WebKitAccessible* accessible)
91 {
92     if (!accessible)
93         return 0;
94
95     return accessible->m_object;
96 }
97
98 static AccessibilityObject* core(AtkObject* object)
99 {
100     if (!WEBKIT_IS_ACCESSIBLE(object))
101         return 0;
102
103     return core(WEBKIT_ACCESSIBLE(object));
104 }
105
106 static AccessibilityObject* core(AtkAction* action)
107 {
108     return core(ATK_OBJECT(action));
109 }
110
111 static AccessibilityObject* core(AtkSelection* selection)
112 {
113     return core(ATK_OBJECT(selection));
114 }
115
116 static AccessibilityObject* core(AtkText* text)
117 {
118     return core(ATK_OBJECT(text));
119 }
120
121 static AccessibilityObject* core(AtkEditableText* text)
122 {
123     return core(ATK_OBJECT(text));
124 }
125
126 static AccessibilityObject* core(AtkComponent* component)
127 {
128     return core(ATK_OBJECT(component));
129 }
130
131 static AccessibilityObject* core(AtkImage* image)
132 {
133     return core(ATK_OBJECT(image));
134 }
135
136 static AccessibilityObject* core(AtkTable* table)
137 {
138     return core(ATK_OBJECT(table));
139 }
140
141 static AccessibilityObject* core(AtkDocument* document)
142 {
143     return core(ATK_OBJECT(document));
144 }
145
146 static const gchar* nameFromChildren(AccessibilityObject* object)
147 {
148     if (!object)
149         return 0;
150
151     AccessibilityRenderObject::AccessibilityChildrenVector children = object->children();
152     // Currently, object->stringValue() should be an empty String. This might not be the case down the road.
153     String name = object->stringValue();
154     for (unsigned i = 0; i < children.size(); ++i)
155         name += children.at(i).get()->stringValue();
156     return returnString(name);
157 }
158
159 static const gchar* webkit_accessible_get_name(AtkObject* object)
160 {
161     AccessibilityObject* coreObject = core(object);
162     if (!coreObject->isAccessibilityRenderObject())
163         return returnString(coreObject->stringValue());
164
165     AccessibilityRenderObject* renderObject = static_cast<AccessibilityRenderObject*>(coreObject);
166     if (coreObject->isControl()) {
167         AccessibilityObject* label = renderObject->correspondingLabelForControlElement();
168         if (label)
169             return returnString(nameFromChildren(label));
170     }
171
172     if (renderObject->isImage() || renderObject->isInputImage()) {
173         Node* node = renderObject->renderer()->node();
174         if (node && node->isHTMLElement()) {
175             // Get the attribute rather than altText String so as not to fall back on title.
176             String alt = static_cast<HTMLElement*>(node)->getAttribute(HTMLNames::altAttr);
177             if (!alt.isEmpty())
178                 return returnString(alt);
179         }
180     }
181
182     return returnString(coreObject->stringValue());
183 }
184
185 static const gchar* webkit_accessible_get_description(AtkObject* object)
186 {
187     AccessibilityObject* coreObject = core(object);
188     Node* node = 0;
189     if (coreObject->isAccessibilityRenderObject())
190         node = static_cast<AccessibilityRenderObject*>(coreObject)->renderer()->node();
191     if (!node || !node->isHTMLElement() || coreObject->ariaRoleAttribute() != UnknownRole)
192         return returnString(coreObject->accessibilityDescription());
193
194     // atk_table_get_summary returns an AtkObject. We have no summary object, so expose summary here.
195     if (coreObject->roleValue() == TableRole) {
196         String summary = static_cast<HTMLTableElement*>(node)->summary();
197         if (!summary.isEmpty())
198             return returnString(summary);
199     }
200
201     // The title attribute should be reliably available as the object's descripton.
202     // We do not want to fall back on other attributes in its absence. See bug 25524.
203     String title = static_cast<HTMLElement*>(node)->title();
204     if (!title.isEmpty())
205         return returnString(title);
206
207     return returnString(coreObject->accessibilityDescription());
208 }
209
210 static void setAtkRelationSetFromCoreObject(AccessibilityObject* coreObject, AtkRelationSet* relationSet)
211 {
212     AccessibilityRenderObject* accObject = static_cast<AccessibilityRenderObject*>(coreObject);
213     if (accObject->isControl()) {
214         AccessibilityObject* label = accObject->correspondingLabelForControlElement();
215         if (label)
216             atk_relation_set_add_relation_by_type(relationSet, ATK_RELATION_LABELLED_BY, label->wrapper());
217     } else {
218         AccessibilityObject* control = accObject->correspondingControlForLabelElement();
219         if (control)
220             atk_relation_set_add_relation_by_type(relationSet, ATK_RELATION_LABEL_FOR, control->wrapper());
221     }
222 }
223
224 static gpointer webkit_accessible_parent_class = 0;
225
226 static AtkObject* atkParentOfWebView(AtkObject* object)
227 {
228     AccessibilityObject* coreParent = core(object)->parentObjectUnignored();
229
230     // The top level web view claims to not have a parent. This makes it
231     // impossible for assistive technologies to ascend the accessible
232     // hierarchy all the way to the application. (Bug 30489)
233     if (!coreParent && core(object)->isWebArea()) {
234         HostWindow* hostWindow = core(object)->document()->view()->hostWindow();
235         if (hostWindow) {
236             PlatformPageClient webView = hostWindow->platformPageClient();
237             if (webView) {
238                 GtkWidget* webViewParent = gtk_widget_get_parent(webView);
239                 if (webViewParent)
240                     return gtk_widget_get_accessible(webViewParent);
241             }
242         }
243     }
244
245     if (!coreParent)
246         return 0;
247
248     return coreParent->wrapper();
249 }
250
251 static AtkObject* webkit_accessible_get_parent(AtkObject* object)
252 {
253     AccessibilityObject* coreParent = core(object)->parentObjectUnignored();
254     if (!coreParent && core(object)->isWebArea())
255         return atkParentOfWebView(object);
256
257     if (!coreParent)
258         return 0;
259
260     return coreParent->wrapper();
261 }
262
263 static gint webkit_accessible_get_n_children(AtkObject* object)
264 {
265     return core(object)->children().size();
266 }
267
268 static AtkObject* webkit_accessible_ref_child(AtkObject* object, gint index)
269 {
270     AccessibilityObject* coreObject = core(object);
271     AccessibilityObject::AccessibilityChildrenVector children = coreObject->children();
272     if (index < 0 || static_cast<unsigned>(index) >= children.size())
273         return 0;
274
275     AccessibilityObject* coreChild = children.at(index).get();
276
277     if (!coreChild)
278         return 0;
279
280     AtkObject* child = coreChild->wrapper();
281     atk_object_set_parent(child, object);
282     g_object_ref(child);
283
284     return child;
285 }
286
287 static gint webkit_accessible_get_index_in_parent(AtkObject* object)
288 {
289     AccessibilityObject* coreObject = core(object);
290     AccessibilityObject* parent = coreObject->parentObjectUnignored();
291
292     if (!parent && core(object)->isWebArea()) {
293         AtkObject* atkParent = atkParentOfWebView(object);
294         if (!atkParent)
295             return -1;
296
297         unsigned count = atk_object_get_n_accessible_children(atkParent);
298         for (unsigned i = 0; i < count; ++i) {
299             AtkObject* child = atk_object_ref_accessible_child(atkParent, i);
300             bool childIsObject = child == object;
301             g_object_unref(child);
302             if (childIsObject)
303                 return i;
304         }
305     }
306
307     AccessibilityObject::AccessibilityChildrenVector children = parent->children();
308     unsigned count = children.size();
309     for (unsigned i = 0; i < count; ++i) {
310         if (children[i] == coreObject)
311             return i;
312     }
313
314     return -1;
315 }
316
317 static AtkAttributeSet* addAttributeToSet(AtkAttributeSet* attributeSet, const char* name, const char* value)
318 {
319     AtkAttribute* attribute = static_cast<AtkAttribute*>(g_malloc(sizeof(AtkAttribute)));
320     attribute->name = g_strdup(name);
321     attribute->value = g_strdup(value);
322     attributeSet = g_slist_prepend(attributeSet, attribute);
323
324     return attributeSet;
325 }
326
327 static AtkAttributeSet* webkit_accessible_get_attributes(AtkObject* object)
328 {
329     AtkAttributeSet* attributeSet = 0;
330
331     int headingLevel = core(object)->headingLevel();
332     if (headingLevel) {
333         String value = String::number(headingLevel);
334         attributeSet = addAttributeToSet(attributeSet, "level", value.utf8().data());
335     }
336     return attributeSet;
337 }
338
339 static AtkRole atkRole(AccessibilityRole role)
340 {
341     switch (role) {
342     case UnknownRole:
343         return ATK_ROLE_UNKNOWN;
344     case ButtonRole:
345         return ATK_ROLE_PUSH_BUTTON;
346     case RadioButtonRole:
347         return ATK_ROLE_RADIO_BUTTON;
348     case CheckBoxRole:
349         return ATK_ROLE_CHECK_BOX;
350     case SliderRole:
351         return ATK_ROLE_SLIDER;
352     case TabGroupRole:
353         return ATK_ROLE_PAGE_TAB_LIST;
354     case TextFieldRole:
355     case TextAreaRole:
356         return ATK_ROLE_ENTRY;
357     case StaticTextRole:
358         return ATK_ROLE_TEXT;
359     case OutlineRole:
360         return ATK_ROLE_TREE;
361     case MenuBarRole:
362         return ATK_ROLE_MENU_BAR;
363     case MenuRole:
364         return ATK_ROLE_MENU;
365     case MenuItemRole:
366         return ATK_ROLE_MENU_ITEM;
367     case ColumnRole:
368         //return ATK_ROLE_TABLE_COLUMN_HEADER; // Is this right?
369         return ATK_ROLE_UNKNOWN; // Matches Mozilla
370     case RowRole:
371         //return ATK_ROLE_TABLE_ROW_HEADER; // Is this right?
372         return ATK_ROLE_LIST_ITEM; // Matches Mozilla
373     case ToolbarRole:
374         return ATK_ROLE_TOOL_BAR;
375     case BusyIndicatorRole:
376         return ATK_ROLE_PROGRESS_BAR; // Is this right?
377     case ProgressIndicatorRole:
378         //return ATK_ROLE_SPIN_BUTTON; // Some confusion about this role in AccessibilityRenderObject.cpp
379         return ATK_ROLE_PROGRESS_BAR;
380     case WindowRole:
381         return ATK_ROLE_WINDOW;
382     case ComboBoxRole:
383         return ATK_ROLE_COMBO_BOX;
384     case SplitGroupRole:
385         return ATK_ROLE_SPLIT_PANE;
386     case SplitterRole:
387         return ATK_ROLE_SEPARATOR;
388     case ColorWellRole:
389         return ATK_ROLE_COLOR_CHOOSER;
390     case ListRole:
391         return ATK_ROLE_LIST;
392     case ScrollBarRole:
393         return ATK_ROLE_SCROLL_BAR;
394     case GridRole: // Is this right?
395     case TableRole:
396         return ATK_ROLE_TABLE;
397     case ApplicationRole:
398         return ATK_ROLE_APPLICATION;
399     case GroupRole:
400     case RadioGroupRole:
401         return ATK_ROLE_PANEL;
402     case CellRole:
403         return ATK_ROLE_TABLE_CELL;
404     case LinkRole:
405     case WebCoreLinkRole:
406     case ImageMapLinkRole:
407         return ATK_ROLE_LINK;
408     case ImageMapRole:
409     case ImageRole:
410         return ATK_ROLE_IMAGE;
411     case ListMarkerRole:
412         return ATK_ROLE_TEXT;
413     case WebAreaRole:
414         //return ATK_ROLE_HTML_CONTAINER; // Is this right?
415         return ATK_ROLE_DOCUMENT_FRAME;
416     case HeadingRole:
417         return ATK_ROLE_HEADING;
418     case ListBoxRole:
419         return ATK_ROLE_LIST;
420     case ListBoxOptionRole:
421         return ATK_ROLE_LIST_ITEM;
422     default:
423         return ATK_ROLE_UNKNOWN;
424     }
425 }
426
427 static AtkRole webkit_accessible_get_role(AtkObject* object)
428 {
429     AccessibilityObject* axObject = core(object);
430
431     if (!axObject)
432         return ATK_ROLE_UNKNOWN;
433
434     // WebCore does not seem to have a role for list items
435     if (axObject->isGroup()) {
436         AccessibilityObject* parent = axObject->parentObjectUnignored();
437         if (parent && parent->isList())
438             return ATK_ROLE_LIST_ITEM;
439     }
440
441     // WebCore does not know about paragraph role, label role, or section role
442     if (axObject->isAccessibilityRenderObject()) {
443         Node* node = static_cast<AccessibilityRenderObject*>(axObject)->renderer()->node();
444         if (node) {
445             if (node->hasTagName(HTMLNames::pTag))
446                 return ATK_ROLE_PARAGRAPH;
447             if (node->hasTagName(HTMLNames::labelTag))
448                 return ATK_ROLE_LABEL;
449             if (node->hasTagName(HTMLNames::divTag))
450                 return ATK_ROLE_SECTION;
451         }
452     }
453
454     // Note: Why doesn't WebCore have a password field for this
455     if (axObject->isPasswordField())
456         return ATK_ROLE_PASSWORD_TEXT;
457
458     return atkRole(axObject->roleValue());
459 }
460
461 static void setAtkStateSetFromCoreObject(AccessibilityObject* coreObject, AtkStateSet* stateSet)
462 {
463     AccessibilityObject* parent = coreObject->parentObject();
464     bool isListBoxOption = parent && parent->isListBox();
465
466     // Please keep the state list in alphabetical order
467     if (coreObject->isChecked())
468         atk_state_set_add_state(stateSet, ATK_STATE_CHECKED);
469
470     // FIXME: isReadOnly does not seem to do the right thing for
471     // controls, so check explicitly for them. In addition, because
472     // isReadOnly is false for listBoxOptions, we need to add one
473     // more check so that we do not present them as being "editable".
474     if ((!coreObject->isReadOnly() ||
475         (coreObject->isControl() && coreObject->canSetValueAttribute())) &&
476         !isListBoxOption)
477         atk_state_set_add_state(stateSet, ATK_STATE_EDITABLE);
478
479     // FIXME: Put both ENABLED and SENSITIVE together here for now
480     if (coreObject->isEnabled()) {
481         atk_state_set_add_state(stateSet, ATK_STATE_ENABLED);
482         atk_state_set_add_state(stateSet, ATK_STATE_SENSITIVE);
483     }
484
485     if (coreObject->canSetFocusAttribute())
486         atk_state_set_add_state(stateSet, ATK_STATE_FOCUSABLE);
487
488     if (coreObject->isFocused())
489         atk_state_set_add_state(stateSet, ATK_STATE_FOCUSED);
490
491     // TODO: ATK_STATE_HORIZONTAL
492
493     if (coreObject->isIndeterminate())
494         atk_state_set_add_state(stateSet, ATK_STATE_INDETERMINATE);
495
496     if (coreObject->isMultiSelect())
497         atk_state_set_add_state(stateSet, ATK_STATE_MULTISELECTABLE);
498
499     // TODO: ATK_STATE_OPAQUE
500
501     if (coreObject->isPressed())
502         atk_state_set_add_state(stateSet, ATK_STATE_PRESSED);
503
504     // TODO: ATK_STATE_SELECTABLE_TEXT
505
506     if (coreObject->canSetSelectedAttribute()) {
507         atk_state_set_add_state(stateSet, ATK_STATE_SELECTABLE);
508         // Items in focusable lists in Gtk have both STATE_SELECT{ABLE,ED}
509         // and STATE_FOCUS{ABLE,ED}. We'll fake the latter based on the
510         // former.
511         if (isListBoxOption)
512             atk_state_set_add_state(stateSet, ATK_STATE_FOCUSABLE);
513     }
514
515     if (coreObject->isSelected()) {
516         atk_state_set_add_state(stateSet, ATK_STATE_SELECTED);
517         // Items in focusable lists in Gtk have both STATE_SELECT{ABLE,ED}
518         // and STATE_FOCUS{ABLE,ED}. We'll fake the latter based on the
519         // former.
520         if (isListBoxOption)
521             atk_state_set_add_state(stateSet, ATK_STATE_FOCUSED);
522     }
523
524     // FIXME: Group both SHOWING and VISIBLE here for now
525     // Not sure how to handle this in WebKit, see bug
526     // http://bugzilla.gnome.org/show_bug.cgi?id=509650 for other
527     // issues with SHOWING vs VISIBLE within GTK+
528     if (!coreObject->isOffScreen()) {
529         atk_state_set_add_state(stateSet, ATK_STATE_SHOWING);
530         atk_state_set_add_state(stateSet, ATK_STATE_VISIBLE);
531     }
532
533     // Mutually exclusive, so we group these two
534     if (coreObject->roleValue() == TextFieldRole)
535         atk_state_set_add_state(stateSet, ATK_STATE_SINGLE_LINE);
536     else if (coreObject->roleValue() == TextAreaRole)
537         atk_state_set_add_state(stateSet, ATK_STATE_MULTI_LINE);
538
539     // TODO: ATK_STATE_SENSITIVE
540
541     // TODO: ATK_STATE_VERTICAL
542
543     if (coreObject->isVisited())
544         atk_state_set_add_state(stateSet, ATK_STATE_VISITED);
545 }
546
547 static AtkStateSet* webkit_accessible_ref_state_set(AtkObject* object)
548 {
549     AtkStateSet* stateSet = ATK_OBJECT_CLASS(webkit_accessible_parent_class)->ref_state_set(object);
550     AccessibilityObject* coreObject = core(object);
551
552     if (coreObject == fallbackObject()) {
553         atk_state_set_add_state(stateSet, ATK_STATE_DEFUNCT);
554         return stateSet;
555     }
556
557     setAtkStateSetFromCoreObject(coreObject, stateSet);
558
559     return stateSet;
560 }
561
562 static AtkRelationSet* webkit_accessible_ref_relation_set(AtkObject* object)
563 {
564     AtkRelationSet* relationSet = ATK_OBJECT_CLASS(webkit_accessible_parent_class)->ref_relation_set(object);
565     AccessibilityObject* coreObject = core(object);
566
567     setAtkRelationSetFromCoreObject(coreObject, relationSet);
568
569     return relationSet;
570 }
571
572 static void webkit_accessible_init(AtkObject* object, gpointer data)
573 {
574     if (ATK_OBJECT_CLASS(webkit_accessible_parent_class)->initialize)
575         ATK_OBJECT_CLASS(webkit_accessible_parent_class)->initialize(object, data);
576
577     WEBKIT_ACCESSIBLE(object)->m_object = reinterpret_cast<AccessibilityObject*>(data);
578 }
579
580 static void webkit_accessible_finalize(GObject* object)
581 {
582     // This is a good time to clear the return buffer.
583     returnString(String());
584
585     G_OBJECT_CLASS(webkit_accessible_parent_class)->finalize(object);
586 }
587
588 static void webkit_accessible_class_init(AtkObjectClass* klass)
589 {
590     GObjectClass* gobjectClass = G_OBJECT_CLASS(klass);
591
592     webkit_accessible_parent_class = g_type_class_peek_parent(klass);
593
594     gobjectClass->finalize = webkit_accessible_finalize;
595
596     klass->initialize = webkit_accessible_init;
597     klass->get_name = webkit_accessible_get_name;
598     klass->get_description = webkit_accessible_get_description;
599     klass->get_parent = webkit_accessible_get_parent;
600     klass->get_n_children = webkit_accessible_get_n_children;
601     klass->ref_child = webkit_accessible_ref_child;
602     klass->get_role = webkit_accessible_get_role;
603     klass->ref_state_set = webkit_accessible_ref_state_set;
604     klass->get_index_in_parent = webkit_accessible_get_index_in_parent;
605     klass->get_attributes = webkit_accessible_get_attributes;
606     klass->ref_relation_set = webkit_accessible_ref_relation_set;
607 }
608
609 GType
610 webkit_accessible_get_type(void)
611 {
612     static volatile gsize type_volatile = 0;
613
614     if (g_once_init_enter(&type_volatile)) {
615         static const GTypeInfo tinfo = {
616             sizeof(WebKitAccessibleClass),
617             (GBaseInitFunc) 0,
618             (GBaseFinalizeFunc) 0,
619             (GClassInitFunc) webkit_accessible_class_init,
620             (GClassFinalizeFunc) 0,
621             0, /* class data */
622             sizeof(WebKitAccessible), /* instance size */
623             0, /* nb preallocs */
624             (GInstanceInitFunc) 0,
625             0 /* value table */
626         };
627
628         GType type = g_type_register_static(ATK_TYPE_OBJECT,
629                                             "WebKitAccessible", &tinfo, GTypeFlags(0));
630         g_once_init_leave(&type_volatile, type);
631     }
632
633     return type_volatile;
634 }
635
636 static gboolean webkit_accessible_action_do_action(AtkAction* action, gint i)
637 {
638     g_return_val_if_fail(i == 0, FALSE);
639     return core(action)->performDefaultAction();
640 }
641
642 static gint webkit_accessible_action_get_n_actions(AtkAction* action)
643 {
644     return 1;
645 }
646
647 static const gchar* webkit_accessible_action_get_description(AtkAction* action, gint i)
648 {
649     g_return_val_if_fail(i == 0, 0);
650     // TODO: Need a way to provide/localize action descriptions.
651     notImplemented();
652     return "";
653 }
654
655 static const gchar* webkit_accessible_action_get_keybinding(AtkAction* action, gint i)
656 {
657     g_return_val_if_fail(i == 0, 0);
658     // FIXME: Construct a proper keybinding string.
659     return returnString(core(action)->accessKey().string());
660 }
661
662 static const gchar* webkit_accessible_action_get_name(AtkAction* action, gint i)
663 {
664     g_return_val_if_fail(i == 0, 0);
665     return returnString(core(action)->actionVerb());
666 }
667
668 static void atk_action_interface_init(AtkActionIface* iface)
669 {
670     iface->do_action = webkit_accessible_action_do_action;
671     iface->get_n_actions = webkit_accessible_action_get_n_actions;
672     iface->get_description = webkit_accessible_action_get_description;
673     iface->get_keybinding = webkit_accessible_action_get_keybinding;
674     iface->get_name = webkit_accessible_action_get_name;
675 }
676
677 // Selection (for controls)
678
679 static AccessibilityObject* optionFromList(AtkSelection* selection, gint i)
680 {
681     AccessibilityObject* coreSelection = core(selection);
682     if (!coreSelection || i < 0)
683         return 0;
684
685     AccessibilityRenderObject::AccessibilityChildrenVector options = core(selection)->children();
686     if (i < static_cast<gint>(options.size()))
687         return options.at(i).get();
688
689     return 0;
690 }
691
692 static AccessibilityObject* optionFromSelection(AtkSelection* selection, gint i)
693 {
694     // i is the ith selection as opposed to the ith child.
695
696     AccessibilityObject* coreSelection = core(selection);
697     if (!coreSelection || i < 0)
698         return 0;
699
700     AccessibilityRenderObject::AccessibilityChildrenVector selectedItems;
701     if (coreSelection->isListBox())
702         static_cast<AccessibilityListBox*>(coreSelection)->selectedChildren(selectedItems);
703
704     // TODO: Combo boxes
705
706     if (i < static_cast<gint>(selectedItems.size()))
707         return selectedItems.at(i).get();
708
709     return 0;
710 }
711
712 static gboolean webkit_accessible_selection_add_selection(AtkSelection* selection, gint i)
713 {
714     AccessibilityObject* option = optionFromList(selection, i);
715     if (option && core(selection)->isListBox()) {
716         AccessibilityListBoxOption* listBoxOption = static_cast<AccessibilityListBoxOption*>(option);
717         listBoxOption->setSelected(true);
718         return listBoxOption->isSelected();
719     }
720
721     return false;
722 }
723
724 static gboolean webkit_accessible_selection_clear_selection(AtkSelection* selection)
725 {
726     AccessibilityObject* coreSelection = core(selection);
727     if (!coreSelection)
728         return false;
729
730     AccessibilityRenderObject::AccessibilityChildrenVector selectedItems;
731     if (coreSelection->isListBox()) {
732         // Set the list of selected items to an empty list; then verify that it worked.
733         AccessibilityListBox* listBox = static_cast<AccessibilityListBox*>(coreSelection);
734         listBox->setSelectedChildren(selectedItems);
735         listBox->selectedChildren(selectedItems);
736         return selectedItems.size() == 0;
737     }
738     return false;
739 }
740
741 static AtkObject* webkit_accessible_selection_ref_selection(AtkSelection* selection, gint i)
742 {
743     AccessibilityObject* option = optionFromSelection(selection, i);
744     if (option) {
745         AtkObject* child = option->wrapper();
746         g_object_ref(child);
747         return child;
748     }
749
750     return 0;
751 }
752
753 static gint webkit_accessible_selection_get_selection_count(AtkSelection* selection)
754 {
755     AccessibilityObject* coreSelection = core(selection);
756     if (coreSelection && coreSelection->isListBox()) {
757         AccessibilityRenderObject::AccessibilityChildrenVector selectedItems;
758         static_cast<AccessibilityListBox*>(coreSelection)->selectedChildren(selectedItems);
759         return static_cast<gint>(selectedItems.size());
760     }
761
762     return 0;
763 }
764
765 static gboolean webkit_accessible_selection_is_child_selected(AtkSelection* selection, gint i)
766 {
767     AccessibilityObject* option = optionFromList(selection, i);
768     if (option && core(selection)->isListBox())
769         return static_cast<AccessibilityListBoxOption*>(option)->isSelected();
770
771     return false;
772 }
773
774 static gboolean webkit_accessible_selection_remove_selection(AtkSelection* selection, gint i)
775 {
776     // TODO: This is only getting called if i == 0. What is preventing the rest?
777     AccessibilityObject* option = optionFromSelection(selection, i);
778     if (option && core(selection)->isListBox()) {
779         AccessibilityListBoxOption* listBoxOption = static_cast<AccessibilityListBoxOption*>(option);
780         listBoxOption->setSelected(false);
781         return !listBoxOption->isSelected();
782     }
783
784     return false;
785 }
786
787 static gboolean webkit_accessible_selection_select_all_selection(AtkSelection* selection)
788 {
789     AccessibilityObject* coreSelection = core(selection);
790     if (!coreSelection || !coreSelection->isMultiSelect())
791         return false;
792
793     AccessibilityRenderObject::AccessibilityChildrenVector children = coreSelection->children();
794     if (coreSelection->isListBox()) {
795         AccessibilityListBox* listBox = static_cast<AccessibilityListBox*>(coreSelection);
796         listBox->setSelectedChildren(children);
797         AccessibilityRenderObject::AccessibilityChildrenVector selectedItems;
798         listBox->selectedChildren(selectedItems);
799         return selectedItems.size() == children.size();
800     }
801
802     return false;
803 }
804
805 static void atk_selection_interface_init(AtkSelectionIface* iface)
806 {
807     iface->add_selection = webkit_accessible_selection_add_selection;
808     iface->clear_selection = webkit_accessible_selection_clear_selection;
809     iface->ref_selection = webkit_accessible_selection_ref_selection;
810     iface->get_selection_count = webkit_accessible_selection_get_selection_count;
811     iface->is_child_selected = webkit_accessible_selection_is_child_selected;
812     iface->remove_selection = webkit_accessible_selection_remove_selection;
813     iface->select_all_selection = webkit_accessible_selection_select_all_selection;
814 }
815
816 // Text
817
818 static gchar* webkit_accessible_text_get_text(AtkText* text, gint startOffset, gint endOffset)
819 {
820     AccessibilityObject* coreObject = core(text);
821     String ret;
822     unsigned start = startOffset;
823     if (endOffset == -1)
824         endOffset = coreObject->stringValue().length();
825     int length = endOffset - startOffset;
826
827     if (coreObject->isTextControl())
828         ret = coreObject->doAXStringForRange(PlainTextRange(start, length));
829     else
830         ret = coreObject->textUnderElement().substring(start, length);
831
832     return g_strdup(ret.utf8().data());
833 }
834
835 static GailTextUtil* getGailTextUtilForAtk(AtkText* textObject)
836 {
837     gpointer data = g_object_get_data(G_OBJECT(textObject), "webkit-accessible-gail-text-util");
838     if (data)
839         return static_cast<GailTextUtil*>(data);
840
841     GailTextUtil* gailTextUtil = gail_text_util_new();
842     gail_text_util_text_setup(gailTextUtil, webkit_accessible_text_get_text(textObject, 0, -1));
843     g_object_set_data_full(G_OBJECT(textObject), "webkit-accessible-gail-text-util", gailTextUtil, g_object_unref);
844     return gailTextUtil;
845 }
846
847 static gchar* utf8Substr(const gchar* string, gint start, gint end)
848 {
849     ASSERT(string);
850     glong strLen = g_utf8_strlen(string, -1);
851     if (start > strLen || end > strLen)
852         return 0;
853     gchar* startPtr = g_utf8_offset_to_pointer(string, start);
854     gsize lenInBytes = g_utf8_offset_to_pointer(string, end) -  startPtr + 1;
855     gchar* output = static_cast<gchar*>(g_malloc0(lenInBytes + 1));
856     return g_utf8_strncpy(output, startPtr, end - start + 1);
857 }
858
859 // This function is not completely general, is it's tied to the
860 // internals of WebCore's text presentation.
861 static gchar* convertUniCharToUTF8(const UChar* characters, gint length, int from, int to)
862 {
863     CString stringUTF8 = UTF8Encoding().encode(characters, length, QuestionMarksForUnencodables);
864     gchar* utf8String = utf8Substr(stringUTF8.data(), from, to);
865     if (!g_utf8_validate(utf8String, -1, 0)) {
866         g_free(utf8String);
867         return 0;
868     }
869     gsize len = strlen(utf8String);
870     GString* ret = g_string_new_len(0, len);
871     gchar* ptr = utf8String;
872
873     // WebCore introduces line breaks in the text that do not reflect
874     // the layout you see on the screen, replace them with spaces
875     while (len > 0) {
876         gint index, start;
877         pango_find_paragraph_boundary(ptr, len, &index, &start);
878         g_string_append_len(ret, ptr, index);
879         if (index == start)
880             break;
881         g_string_append_c(ret, ' ');
882         ptr += start;
883         len -= start;
884     }
885
886     g_free(utf8String);
887     return g_string_free(ret, FALSE);
888 }
889
890 static PangoLayout* getPangoLayoutForAtk(AtkText* textObject)
891 {
892     AccessibilityObject* coreObject = core(textObject);
893
894     HostWindow* hostWindow = coreObject->document()->view()->hostWindow();
895     if (!hostWindow)
896         return 0;
897     PlatformPageClient webView = hostWindow->platformPageClient();
898     if (!webView)
899         return 0;
900
901     GString* str = g_string_new(0);
902
903     AccessibilityRenderObject* accObject = static_cast<AccessibilityRenderObject*>(coreObject);
904     if (!accObject)
905         return 0;
906     RenderText* renderText = toRenderText(accObject->renderer());
907     if (!renderText)
908         return 0;
909
910     // Create a string with the layout as it appears on the screen
911     InlineTextBox* box = renderText->firstTextBox();
912     while (box) {
913         gchar* text = convertUniCharToUTF8(renderText->characters(), renderText->textLength(), box->start(), box->end());
914         g_string_append(str, text);
915         // Newline chars in the source result in separate text boxes, so check
916         // before adding a newline in the layout. See bug 25415 comment #78.
917         if (!box->nextOnLineExists())
918             g_string_append(str, "\n");
919         box = box->nextTextBox();
920     }
921
922     PangoLayout* layout = gtk_widget_create_pango_layout(static_cast<GtkWidget*>(webView), g_string_free(str, FALSE));
923     g_object_set_data_full(G_OBJECT(textObject), "webkit-accessible-pango-layout", layout, g_object_unref);
924     return layout;
925 }
926
927 static gchar* webkit_accessible_text_get_text_after_offset(AtkText* text, gint offset, AtkTextBoundary boundaryType, gint* startOffset, gint* endOffset)
928 {
929     return gail_text_util_get_text(getGailTextUtilForAtk(text), getPangoLayoutForAtk(text), GAIL_AFTER_OFFSET, boundaryType, offset, startOffset, endOffset);
930 }
931
932 static gchar* webkit_accessible_text_get_text_at_offset(AtkText* text, gint offset, AtkTextBoundary boundaryType, gint* startOffset, gint* endOffset)
933 {
934     return gail_text_util_get_text(getGailTextUtilForAtk(text), getPangoLayoutForAtk(text), GAIL_AT_OFFSET, boundaryType, offset, startOffset, endOffset);
935 }
936
937 static gchar* webkit_accessible_text_get_text_before_offset(AtkText* text, gint offset, AtkTextBoundary boundaryType, gint* startOffset, gint* endOffset)
938 {
939     return gail_text_util_get_text(getGailTextUtilForAtk(text), getPangoLayoutForAtk(text), GAIL_BEFORE_OFFSET, boundaryType, offset, startOffset, endOffset);
940 }
941
942 static gunichar webkit_accessible_text_get_character_at_offset(AtkText* text, gint offset)
943 {
944     notImplemented();
945     return 0;
946 }
947
948 static gint webkit_accessible_text_get_caret_offset(AtkText* text)
949 {
950     // TODO: Verify this for RTL text.
951     return core(text)->selection().end().offsetInContainerNode();
952 }
953
954 static AtkAttributeSet* webkit_accessible_text_get_run_attributes(AtkText* text, gint offset, gint* start_offset, gint* end_offset)
955 {
956     notImplemented();
957     return 0;
958 }
959
960 static AtkAttributeSet* webkit_accessible_text_get_default_attributes(AtkText* text)
961 {
962     notImplemented();
963     return 0;
964 }
965
966 static void webkit_accessible_text_get_character_extents(AtkText* text, gint offset, gint* x, gint* y, gint* width, gint* height, AtkCoordType coords)
967 {
968     IntRect extents = core(text)->doAXBoundsForRange(PlainTextRange(offset, 1));
969     // FIXME: Use the AtkCoordType
970     // Requires WebCore::ScrollView::contentsToScreen() to be implemented
971
972 #if 0
973     switch(coords) {
974     case ATK_XY_SCREEN:
975         extents = core(text)->document()->view()->contentsToScreen(extents);
976         break;
977     case ATK_XY_WINDOW:
978         // No-op
979         break;
980     }
981 #endif
982
983     *x = extents.x();
984     *y = extents.y();
985     *width = extents.width();
986     *height = extents.height();
987 }
988
989 static gint webkit_accessible_text_get_character_count(AtkText* text)
990 {
991     AccessibilityObject* coreObject = core(text);
992
993     if (coreObject->isTextControl())
994         return coreObject->textLength();
995     else
996         return coreObject->textUnderElement().length();
997 }
998
999 static gint webkit_accessible_text_get_offset_at_point(AtkText* text, gint x, gint y, AtkCoordType coords)
1000 {
1001     // FIXME: Use the AtkCoordType
1002     // TODO: Is it correct to ignore range.length?
1003     IntPoint pos(x, y);
1004     PlainTextRange range = core(text)->doAXRangeForPosition(pos);
1005     return range.start;
1006 }
1007
1008 static bool selectionBelongsToObject(AccessibilityObject* coreObject, VisibleSelection& selection)
1009 {
1010     if (!coreObject->isAccessibilityRenderObject())
1011         return false;
1012
1013     Node* node = static_cast<AccessibilityRenderObject*>(coreObject)->renderer()->node();
1014     return node == selection.base().containerNode();
1015 }
1016
1017 static gint webkit_accessible_text_get_n_selections(AtkText* text)
1018 {
1019     AccessibilityObject* coreObject = core(text);
1020     VisibleSelection selection = coreObject->selection();
1021
1022     // We don't support multiple selections for now, so there's only
1023     // two possibilities
1024     // Also, we don't want to do anything if the selection does not
1025     // belong to the currently selected object. We have to check since
1026     // there's no way to get the selection for a given object, only
1027     // the global one (the API is a bit confusing)
1028     return !selectionBelongsToObject(coreObject, selection) || selection.isNone() ? 0 : 1;
1029 }
1030
1031 static gchar* webkit_accessible_text_get_selection(AtkText* text, gint selection_num, gint* start_offset, gint* end_offset)
1032 {
1033     AccessibilityObject* coreObject = core(text);
1034     VisibleSelection selection = coreObject->selection();
1035
1036     // WebCore does not support multiple selection, so anything but 0 does not make sense for now.
1037     // Also, we don't want to do anything if the selection does not
1038     // belong to the currently selected object. We have to check since
1039     // there's no way to get the selection for a given object, only
1040     // the global one (the API is a bit confusing)
1041     if (selection_num != 0 || !selectionBelongsToObject(coreObject, selection)) {
1042         *start_offset = *end_offset = 0;
1043         return 0;
1044     }
1045
1046     *start_offset = selection.start().offsetInContainerNode();
1047     *end_offset = selection.end().offsetInContainerNode();
1048
1049     return webkit_accessible_text_get_text(text, *start_offset, *end_offset);
1050 }
1051
1052 static gboolean webkit_accessible_text_add_selection(AtkText* text, gint start_offset, gint end_offset)
1053 {
1054     notImplemented();
1055     return FALSE;
1056 }
1057
1058 static gboolean webkit_accessible_text_remove_selection(AtkText* text, gint selection_num)
1059 {
1060     notImplemented();
1061     return FALSE;
1062 }
1063
1064 static gboolean webkit_accessible_text_set_selection(AtkText* text, gint selection_num, gint start_offset, gint end_offset)
1065 {
1066     notImplemented();
1067     return FALSE;
1068 }
1069
1070 static gboolean webkit_accessible_text_set_caret_offset(AtkText* text, gint offset)
1071 {
1072     AccessibilityObject* coreObject = core(text);
1073
1074     // FIXME: We need to reimplement visiblePositionRangeForRange here
1075     // because the actual function checks the offset is within the
1076     // boundaries of text().length(), but text() only works for text
1077     // controls...
1078     VisiblePosition startPosition = coreObject->visiblePositionForIndex(offset);
1079     startPosition.setAffinity(DOWNSTREAM);
1080     VisiblePosition endPosition = coreObject->visiblePositionForIndex(offset);
1081     VisiblePositionRange range = VisiblePositionRange(startPosition, endPosition);
1082
1083     coreObject->setSelectedVisiblePositionRange(range);
1084     return TRUE;
1085 }
1086
1087 static void atk_text_interface_init(AtkTextIface* iface)
1088 {
1089     iface->get_text = webkit_accessible_text_get_text;
1090     iface->get_text_after_offset = webkit_accessible_text_get_text_after_offset;
1091     iface->get_text_at_offset = webkit_accessible_text_get_text_at_offset;
1092     iface->get_character_at_offset = webkit_accessible_text_get_character_at_offset;
1093     iface->get_text_before_offset = webkit_accessible_text_get_text_before_offset;
1094     iface->get_caret_offset = webkit_accessible_text_get_caret_offset;
1095     iface->get_run_attributes = webkit_accessible_text_get_run_attributes;
1096     iface->get_default_attributes = webkit_accessible_text_get_default_attributes;
1097     iface->get_character_extents = webkit_accessible_text_get_character_extents;
1098     iface->get_character_count = webkit_accessible_text_get_character_count;
1099     iface->get_offset_at_point = webkit_accessible_text_get_offset_at_point;
1100     iface->get_n_selections = webkit_accessible_text_get_n_selections;
1101     iface->get_selection = webkit_accessible_text_get_selection;
1102
1103     // set methods
1104     iface->add_selection = webkit_accessible_text_add_selection;
1105     iface->remove_selection = webkit_accessible_text_remove_selection;
1106     iface->set_selection = webkit_accessible_text_set_selection;
1107     iface->set_caret_offset = webkit_accessible_text_set_caret_offset;
1108 }
1109
1110 // EditableText
1111
1112 static gboolean webkit_accessible_editable_text_set_run_attributes(AtkEditableText* text, AtkAttributeSet* attrib_set, gint start_offset, gint end_offset)
1113 {
1114     notImplemented();
1115     return FALSE;
1116 }
1117
1118 static void webkit_accessible_editable_text_set_text_contents(AtkEditableText* text, const gchar* string)
1119 {
1120     // FIXME: string nullcheck?
1121     core(text)->setValue(String::fromUTF8(string));
1122 }
1123
1124 static void webkit_accessible_editable_text_insert_text(AtkEditableText* text, const gchar* string, gint length, gint* position)
1125 {
1126     // FIXME: string nullcheck?
1127
1128     AccessibilityObject* coreObject = core(text);
1129     // FIXME: Not implemented in WebCore
1130     //coreObject->setSelectedTextRange(PlainTextRange(*position, 0));
1131     //coreObject->setSelectedText(String::fromUTF8(string));
1132
1133     if (!coreObject->document() || !coreObject->document()->frame())
1134         return;
1135     coreObject->setSelectedVisiblePositionRange(coreObject->visiblePositionRangeForRange(PlainTextRange(*position, 0)));
1136     coreObject->setFocused(true);
1137     // FIXME: We should set position to the actual inserted text length, which may be less than that requested.
1138     if (coreObject->document()->frame()->editor()->insertTextWithoutSendingTextEvent(String::fromUTF8(string), false, 0))
1139         *position += length;
1140 }
1141
1142 static void webkit_accessible_editable_text_copy_text(AtkEditableText* text, gint start_pos, gint end_pos)
1143 {
1144     notImplemented();
1145 }
1146
1147 static void webkit_accessible_editable_text_cut_text(AtkEditableText* text, gint start_pos, gint end_pos)
1148 {
1149     notImplemented();
1150 }
1151
1152 static void webkit_accessible_editable_text_delete_text(AtkEditableText* text, gint start_pos, gint end_pos)
1153 {
1154     AccessibilityObject* coreObject = core(text);
1155     // FIXME: Not implemented in WebCore
1156     //coreObject->setSelectedTextRange(PlainTextRange(start_pos, end_pos - start_pos));
1157     //coreObject->setSelectedText(String());
1158
1159     if (!coreObject->document() || !coreObject->document()->frame())
1160         return;
1161     coreObject->setSelectedVisiblePositionRange(coreObject->visiblePositionRangeForRange(PlainTextRange(start_pos, end_pos - start_pos)));
1162     coreObject->setFocused(true);
1163     coreObject->document()->frame()->editor()->performDelete();
1164 }
1165
1166 static void webkit_accessible_editable_text_paste_text(AtkEditableText* text, gint position)
1167 {
1168     notImplemented();
1169 }
1170
1171 static void atk_editable_text_interface_init(AtkEditableTextIface* iface)
1172 {
1173     iface->set_run_attributes = webkit_accessible_editable_text_set_run_attributes;
1174     iface->set_text_contents = webkit_accessible_editable_text_set_text_contents;
1175     iface->insert_text = webkit_accessible_editable_text_insert_text;
1176     iface->copy_text = webkit_accessible_editable_text_copy_text;
1177     iface->cut_text = webkit_accessible_editable_text_cut_text;
1178     iface->delete_text = webkit_accessible_editable_text_delete_text;
1179     iface->paste_text = webkit_accessible_editable_text_paste_text;
1180 }
1181
1182 static void contentsToAtk(AccessibilityObject* coreObject, AtkCoordType coordType, IntRect rect, gint* x, gint* y, gint* width = 0, gint* height = 0)
1183 {
1184     FrameView* frameView = coreObject->documentFrameView();
1185
1186     if (frameView) {
1187         switch (coordType) {
1188         case ATK_XY_WINDOW:
1189             rect = frameView->contentsToWindow(rect);
1190             break;
1191         case ATK_XY_SCREEN:
1192             rect = frameView->contentsToScreen(rect);
1193             break;
1194         }
1195     }
1196
1197     if (x)
1198         *x = rect.x();
1199     if (y)
1200         *y = rect.y();
1201     if (width)
1202         *width = rect.width();
1203     if (height)
1204         *height = rect.height();
1205 }
1206
1207 static IntPoint atkToContents(AccessibilityObject* coreObject, AtkCoordType coordType, gint x, gint y)
1208 {
1209     IntPoint pos(x, y);
1210
1211     FrameView* frameView = coreObject->documentFrameView();
1212     if (frameView) {
1213         switch (coordType) {
1214         case ATK_XY_SCREEN:
1215             return frameView->screenToContents(pos);
1216         case ATK_XY_WINDOW:
1217             return frameView->windowToContents(pos);
1218         }
1219     }
1220
1221     return pos;
1222 }
1223
1224 static AtkObject* webkit_accessible_component_ref_accessible_at_point(AtkComponent* component, gint x, gint y, AtkCoordType coordType)
1225 {
1226     IntPoint pos = atkToContents(core(component), coordType, x, y);
1227     AccessibilityObject* target = core(component)->doAccessibilityHitTest(pos);
1228     if (!target)
1229         return 0;
1230     g_object_ref(target->wrapper());
1231     return target->wrapper();
1232 }
1233
1234 static void webkit_accessible_component_get_extents(AtkComponent* component, gint* x, gint* y, gint* width, gint* height, AtkCoordType coordType)
1235 {
1236     IntRect rect = core(component)->elementRect();
1237     contentsToAtk(core(component), coordType, rect, x, y, width, height);
1238 }
1239
1240 static gboolean webkit_accessible_component_grab_focus(AtkComponent* component)
1241 {
1242     core(component)->setFocused(true);
1243     return core(component)->isFocused();
1244 }
1245
1246 static void atk_component_interface_init(AtkComponentIface* iface)
1247 {
1248     iface->ref_accessible_at_point = webkit_accessible_component_ref_accessible_at_point;
1249     iface->get_extents = webkit_accessible_component_get_extents;
1250     iface->grab_focus = webkit_accessible_component_grab_focus;
1251 }
1252
1253 // Image
1254
1255 static void webkit_accessible_image_get_image_position(AtkImage* image, gint* x, gint* y, AtkCoordType coordType)
1256 {
1257     IntRect rect = core(image)->elementRect();
1258     contentsToAtk(core(image), coordType, rect, x, y);
1259 }
1260
1261 static const gchar* webkit_accessible_image_get_image_description(AtkImage* image)
1262 {
1263     return returnString(core(image)->accessibilityDescription());
1264 }
1265
1266 static void webkit_accessible_image_get_image_size(AtkImage* image, gint* width, gint* height)
1267 {
1268     IntSize size = core(image)->size();
1269
1270     if (width)
1271         *width = size.width();
1272     if (height)
1273         *height = size.height();
1274 }
1275
1276 static void atk_image_interface_init(AtkImageIface* iface)
1277 {
1278     iface->get_image_position = webkit_accessible_image_get_image_position;
1279     iface->get_image_description = webkit_accessible_image_get_image_description;
1280     iface->get_image_size = webkit_accessible_image_get_image_size;
1281 }
1282
1283 // Table
1284
1285 static AccessibilityTableCell* cell(AtkTable* table, guint row, guint column)
1286 {
1287     AccessibilityObject* accTable = core(table);
1288     if (accTable->isAccessibilityRenderObject())
1289         return static_cast<AccessibilityTable*>(accTable)->cellForColumnAndRow(column, row);
1290     return 0;
1291 }
1292
1293 static gint cellIndex(AccessibilityTableCell* axCell, AccessibilityTable* axTable)
1294 {
1295     // Calculate the cell's index as if we had a traditional Gtk+ table in
1296     // which cells are all direct children of the table, arranged row-first.
1297     AccessibilityObject::AccessibilityChildrenVector allCells;
1298     axTable->cells(allCells);
1299     AccessibilityObject::AccessibilityChildrenVector::iterator position;
1300     position = std::find(allCells.begin(), allCells.end(), axCell);
1301     if (position == allCells.end())
1302         return -1;
1303     return position - allCells.begin();
1304 }
1305
1306 static AccessibilityTableCell* cellAtIndex(AtkTable* table, gint index)
1307 {
1308     AccessibilityObject* accTable = core(table);
1309     if (accTable->isAccessibilityRenderObject()) {
1310         AccessibilityObject::AccessibilityChildrenVector allCells;
1311         static_cast<AccessibilityTable*>(accTable)->cells(allCells);
1312         if (0 <= index && static_cast<unsigned>(index) < allCells.size()) {
1313             AccessibilityObject* accCell = allCells.at(index).get();
1314             return static_cast<AccessibilityTableCell*>(accCell);
1315         }
1316     }
1317     return 0;
1318 }
1319
1320 static AtkObject* webkit_accessible_table_ref_at(AtkTable* table, gint row, gint column)
1321 {
1322     AccessibilityTableCell* axCell = cell(table, row, column);
1323     if (!axCell)
1324         return 0;
1325     return axCell->wrapper();
1326 }
1327
1328 static gint webkit_accessible_table_get_index_at(AtkTable* table, gint row, gint column)
1329 {
1330     AccessibilityTableCell* axCell = cell(table, row, column);
1331     AccessibilityTable* axTable = static_cast<AccessibilityTable*>(core(table));
1332     return cellIndex(axCell, axTable);
1333 }
1334
1335 static gint webkit_accessible_table_get_column_at_index(AtkTable* table, gint index)
1336 {
1337     AccessibilityTableCell* axCell = cellAtIndex(table, index);
1338     if (axCell){
1339         pair<int, int> columnRange;
1340         axCell->columnIndexRange(columnRange);
1341         return columnRange.first;
1342     }
1343     return -1;
1344 }
1345
1346 static gint webkit_accessible_table_get_row_at_index(AtkTable* table, gint index)
1347 {
1348     AccessibilityTableCell* axCell = cellAtIndex(table, index);
1349     if (axCell){
1350         pair<int, int> rowRange;
1351         axCell->rowIndexRange(rowRange);
1352         return rowRange.first;
1353     }
1354     return -1;
1355 }
1356
1357 static gint webkit_accessible_table_get_n_columns(AtkTable* table)
1358 {
1359     AccessibilityObject* accTable = core(table);
1360     if (accTable->isAccessibilityRenderObject())
1361         return static_cast<AccessibilityTable*>(accTable)->columnCount();
1362     return 0;
1363 }
1364
1365 static gint webkit_accessible_table_get_n_rows(AtkTable* table)
1366 {
1367     AccessibilityObject* accTable = core(table);
1368     if (accTable->isAccessibilityRenderObject())
1369         return static_cast<AccessibilityTable*>(accTable)->rowCount();
1370     return 0;
1371 }
1372
1373 static gint webkit_accessible_table_get_column_extent_at(AtkTable* table, gint row, gint column)
1374 {
1375     AccessibilityTableCell* axCell = cell(table, row, column);
1376     if (axCell) {
1377         pair<int, int> columnRange;
1378         axCell->columnIndexRange(columnRange);
1379         return columnRange.second;
1380     }
1381     return 0;
1382 }
1383
1384 static gint webkit_accessible_table_get_row_extent_at(AtkTable* table, gint row, gint column)
1385 {
1386     AccessibilityTableCell* axCell = cell(table, row, column);
1387     if (axCell) {
1388         pair<int, int> rowRange;
1389         axCell->rowIndexRange(rowRange);
1390         return rowRange.second;
1391     }
1392     return 0;
1393 }
1394
1395 static AtkObject* webkit_accessible_table_get_column_header(AtkTable* table, gint column)
1396 {
1397     // FIXME: This needs to be implemented.
1398     notImplemented();
1399     return 0;
1400 }
1401
1402 static AtkObject* webkit_accessible_table_get_row_header(AtkTable* table, gint row)
1403 {
1404     AccessibilityObject* accTable = core(table);
1405     if (accTable->isAccessibilityRenderObject()) {
1406         AccessibilityObject::AccessibilityChildrenVector allRowHeaders;
1407         static_cast<AccessibilityTable*>(accTable)->rowHeaders(allRowHeaders);
1408
1409         unsigned rowCount = allRowHeaders.size();
1410         for (unsigned k = 0; k < rowCount; ++k) {
1411             AccessibilityObject* rowObject = allRowHeaders[k]->parentObject();
1412             if (static_cast<AccessibilityTableRow*>(rowObject)->rowIndex() == row)
1413                 return allRowHeaders[k]->wrapper();
1414         }
1415     }
1416     return 0;
1417 }
1418
1419 static AtkObject* webkit_accessible_table_get_caption(AtkTable* table)
1420 {
1421     AccessibilityObject* accTable = core(table);
1422     if (accTable->isAccessibilityRenderObject()) {
1423         Node* node = static_cast<AccessibilityRenderObject*>(accTable)->renderer()->node();
1424         if (node && node->hasTagName(HTMLNames::tableTag)) {
1425             HTMLTableCaptionElement* caption = static_cast<HTMLTableElement*>(node)->caption();
1426             if (caption)
1427                 return AccessibilityObject::firstAccessibleObjectFromNode(caption->renderer()->node())->wrapper();
1428         }
1429     }
1430     return 0;
1431 }
1432
1433 static const gchar* webkit_accessible_table_get_column_description(AtkTable* table, gint column)
1434 {
1435     AtkObject* columnHeader = atk_table_get_column_header(table, column);
1436     if (columnHeader)
1437         return returnString(nameFromChildren(core(columnHeader)));
1438
1439     return 0;
1440 }
1441
1442 static const gchar* webkit_accessible_table_get_row_description(AtkTable* table, gint row)
1443 {
1444     AtkObject* rowHeader = atk_table_get_row_header(table, row);
1445     if (rowHeader)
1446         return returnString(nameFromChildren(core(rowHeader)));
1447
1448     return 0;
1449 }
1450
1451 static void atk_table_interface_init(AtkTableIface* iface)
1452 {
1453     iface->ref_at = webkit_accessible_table_ref_at;
1454     iface->get_index_at = webkit_accessible_table_get_index_at;
1455     iface->get_column_at_index = webkit_accessible_table_get_column_at_index;
1456     iface->get_row_at_index = webkit_accessible_table_get_row_at_index;
1457     iface->get_n_columns = webkit_accessible_table_get_n_columns;
1458     iface->get_n_rows = webkit_accessible_table_get_n_rows;
1459     iface->get_column_extent_at = webkit_accessible_table_get_column_extent_at;
1460     iface->get_row_extent_at = webkit_accessible_table_get_row_extent_at;
1461     iface->get_column_header = webkit_accessible_table_get_column_header;
1462     iface->get_row_header = webkit_accessible_table_get_row_header;
1463     iface->get_caption = webkit_accessible_table_get_caption;
1464     iface->get_column_description = webkit_accessible_table_get_column_description;
1465     iface->get_row_description = webkit_accessible_table_get_row_description;
1466 }
1467
1468 static const gchar* documentAttributeValue(AtkDocument* document, const gchar* attribute)
1469 {
1470     Document* coreDocument = core(document)->document();
1471     if (!coreDocument)
1472         return 0;
1473
1474     String value = String();
1475     if (!g_ascii_strcasecmp(attribute, "DocType") && coreDocument->doctype())
1476         value = coreDocument->doctype()->name();
1477     else if (!g_ascii_strcasecmp(attribute, "Encoding"))
1478         value = coreDocument->charset();
1479     else if (!g_ascii_strcasecmp(attribute, "URI"))
1480         value = coreDocument->documentURI();
1481     if (!value.isEmpty())
1482         return returnString(value);
1483
1484     return 0;
1485 }
1486
1487 static const gchar* webkit_accessible_document_get_attribute_value(AtkDocument* document, const gchar* attribute)
1488 {
1489     return documentAttributeValue(document, attribute);
1490 }
1491
1492 static AtkAttributeSet* webkit_accessible_document_get_attributes(AtkDocument* document)
1493 {
1494     AtkAttributeSet* attributeSet = 0;
1495     const gchar* attributes [] = {"DocType", "Encoding", "URI"};
1496
1497     for (unsigned i = 0; i < G_N_ELEMENTS(attributes); i++) {
1498         const gchar* value = documentAttributeValue(document, attributes[i]);
1499         if (value)
1500             attributeSet = addAttributeToSet(attributeSet, attributes[i], value);
1501     }
1502
1503     return attributeSet;
1504 }
1505
1506 static const gchar* webkit_accessible_document_get_locale(AtkDocument* document)
1507 {
1508
1509     // TODO: Should we fall back on lang xml:lang when the following comes up empty?
1510     String language = static_cast<AccessibilityRenderObject*>(core(document))->language();
1511     if (!language.isEmpty())
1512         return returnString(language);
1513
1514     return 0;
1515 }
1516
1517 static void atk_document_interface_init(AtkDocumentIface* iface)
1518 {
1519     iface->get_document_attribute_value = webkit_accessible_document_get_attribute_value;
1520     iface->get_document_attributes = webkit_accessible_document_get_attributes;
1521     iface->get_document_locale = webkit_accessible_document_get_locale;
1522 }
1523
1524 static const GInterfaceInfo AtkInterfacesInitFunctions[] = {
1525     {(GInterfaceInitFunc)atk_action_interface_init,
1526      (GInterfaceFinalizeFunc) 0, 0},
1527     {(GInterfaceInitFunc)atk_selection_interface_init,
1528      (GInterfaceFinalizeFunc) 0, 0},
1529     {(GInterfaceInitFunc)atk_editable_text_interface_init,
1530      (GInterfaceFinalizeFunc) 0, 0},
1531     {(GInterfaceInitFunc)atk_text_interface_init,
1532      (GInterfaceFinalizeFunc) 0, 0},
1533     {(GInterfaceInitFunc)atk_component_interface_init,
1534      (GInterfaceFinalizeFunc) 0, 0},
1535     {(GInterfaceInitFunc)atk_image_interface_init,
1536      (GInterfaceFinalizeFunc) 0, 0},
1537     {(GInterfaceInitFunc)atk_table_interface_init,
1538      (GInterfaceFinalizeFunc) 0, 0},
1539     {(GInterfaceInitFunc)atk_document_interface_init,
1540      (GInterfaceFinalizeFunc) 0, 0}
1541 };
1542
1543 enum WAIType {
1544     WAI_ACTION,
1545     WAI_SELECTION,
1546     WAI_EDITABLE_TEXT,
1547     WAI_TEXT,
1548     WAI_COMPONENT,
1549     WAI_IMAGE,
1550     WAI_TABLE,
1551     WAI_DOCUMENT
1552 };
1553
1554 static GType GetAtkInterfaceTypeFromWAIType(WAIType type)
1555 {
1556   switch (type) {
1557   case WAI_ACTION:
1558       return ATK_TYPE_ACTION;
1559   case WAI_SELECTION:
1560       return ATK_TYPE_SELECTION;
1561   case WAI_EDITABLE_TEXT:
1562       return ATK_TYPE_EDITABLE_TEXT;
1563   case WAI_TEXT:
1564       return ATK_TYPE_TEXT;
1565   case WAI_COMPONENT:
1566       return ATK_TYPE_COMPONENT;
1567   case WAI_IMAGE:
1568       return ATK_TYPE_IMAGE;
1569   case WAI_TABLE:
1570       return ATK_TYPE_TABLE;
1571   case WAI_DOCUMENT:
1572       return ATK_TYPE_DOCUMENT;
1573   }
1574
1575   return G_TYPE_INVALID;
1576 }
1577
1578 static guint16 getInterfaceMaskFromObject(AccessibilityObject* coreObject)
1579 {
1580     guint16 interfaceMask = 0;
1581
1582     // Component interface is always supported
1583     interfaceMask |= 1 << WAI_COMPONENT;
1584
1585     // Action
1586     if (!coreObject->actionVerb().isEmpty())
1587         interfaceMask |= 1 << WAI_ACTION;
1588
1589     // Selection
1590     if (coreObject->isListBox())
1591         interfaceMask |= 1 << WAI_SELECTION;
1592
1593     // Text & Editable Text
1594     AccessibilityRole role = coreObject->roleValue();
1595
1596     if (role == StaticTextRole)
1597         interfaceMask |= 1 << WAI_TEXT;
1598     else if (coreObject->isAccessibilityRenderObject() && coreObject->isTextControl()) {
1599         interfaceMask |= 1 << WAI_TEXT;
1600         if (!coreObject->isReadOnly())
1601             interfaceMask |= 1 << WAI_EDITABLE_TEXT;
1602     }
1603
1604     // Image
1605     if (coreObject->isImage())
1606         interfaceMask |= 1 << WAI_IMAGE;
1607
1608     // Table
1609     if (role == TableRole)
1610         interfaceMask |= 1 << WAI_TABLE;
1611
1612     // Document
1613     if (role == WebAreaRole)
1614         interfaceMask |= 1 << WAI_DOCUMENT;
1615
1616     return interfaceMask;
1617 }
1618
1619 static const char* getUniqueAccessibilityTypeName(guint16 interfaceMask)
1620 {
1621 #define WAI_TYPE_NAME_LEN (30) /* Enough for prefix + 5 hex characters (max) */
1622     static char name[WAI_TYPE_NAME_LEN + 1];
1623
1624     g_sprintf(name, "WAIType%x", interfaceMask);
1625     name[WAI_TYPE_NAME_LEN] = '\0';
1626
1627     return name;
1628 }
1629
1630 static GType getAccessibilityTypeFromObject(AccessibilityObject* coreObject)
1631 {
1632     static const GTypeInfo typeInfo = {
1633         sizeof(WebKitAccessibleClass),
1634         (GBaseInitFunc) 0,
1635         (GBaseFinalizeFunc) 0,
1636         (GClassInitFunc) 0,
1637         (GClassFinalizeFunc) 0,
1638         0, /* class data */
1639         sizeof(WebKitAccessible), /* instance size */
1640         0, /* nb preallocs */
1641         (GInstanceInitFunc) 0,
1642         0 /* value table */
1643     };
1644
1645     guint16 interfaceMask = getInterfaceMaskFromObject(coreObject);
1646     const char* atkTypeName = getUniqueAccessibilityTypeName(interfaceMask);
1647     GType type = g_type_from_name(atkTypeName);
1648     if (type)
1649         return type;
1650
1651     type = g_type_register_static(WEBKIT_TYPE_ACCESSIBLE,
1652                                   atkTypeName,
1653                                   &typeInfo, GTypeFlags(0));
1654     for (guint i = 0; i < G_N_ELEMENTS(AtkInterfacesInitFunctions); i++) {
1655         if (interfaceMask & (1 << i))
1656             g_type_add_interface_static(type,
1657                                         GetAtkInterfaceTypeFromWAIType(static_cast<WAIType>(i)),
1658                                         &AtkInterfacesInitFunctions[i]);
1659     }
1660
1661     return type;
1662 }
1663
1664 WebKitAccessible* webkit_accessible_new(AccessibilityObject* coreObject)
1665 {
1666     GType type = getAccessibilityTypeFromObject(coreObject);
1667     AtkObject* object = static_cast<AtkObject*>(g_object_new(type, 0));
1668
1669     atk_object_initialize(object, coreObject);
1670
1671     return WEBKIT_ACCESSIBLE(object);
1672 }
1673
1674 AccessibilityObject* webkit_accessible_get_accessibility_object(WebKitAccessible* accessible)
1675 {
1676     return accessible->m_object;
1677 }
1678
1679 void webkit_accessible_detach(WebKitAccessible* accessible)
1680 {
1681     ASSERT(accessible->m_object);
1682
1683     // We replace the WebCore AccessibilityObject with a fallback object that
1684     // provides default implementations to avoid repetitive null-checking after
1685     // detachment.
1686     accessible->m_object = fallbackObject();
1687 }
1688
1689 AtkObject* webkit_accessible_get_focused_element(WebKitAccessible* accessible)
1690 {
1691     if (!accessible->m_object)
1692         return 0;
1693
1694     RefPtr<AccessibilityObject> focusedObj = accessible->m_object->focusedUIElement();
1695     if (!focusedObj)
1696         return 0;
1697
1698     return focusedObj->wrapper();
1699 }
1700
1701 #endif // HAVE(ACCESSIBILITY)