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