0522f871e490da215320da23149709e3abc53e2a
[WebKit-https.git] / WebKit / gtk / WebCoreSupport / EditorClientGtk.cpp
1 /*
2  *  Copyright (C) 2007 Alp Toker <alp@atoker.com>
3  *  Copyright (C) 2008 Nuanti Ltd.
4  *  Copyright (C) 2009 Diego Escalante Urrelo <diegoe@gnome.org>
5  *  Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
6  *  Copyright (C) 2009, 2010 Igalia S.L.
7  *  Copyright (C) 2010, Martin Robinson <mrobinson@webkit.org>
8  *
9  *  This library is free software; you can redistribute it and/or
10  *  modify it under the terms of the GNU Lesser General Public
11  *  License as published by the Free Software Foundation; either
12  *  version 2 of the License, or (at your option) any later version.
13  *
14  *  This library is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *  Lesser General Public License for more details.
18  *
19  *  You should have received a copy of the GNU Lesser General Public
20  *  License along with this library; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  */
23
24 #include "config.h"
25 #include "EditorClientGtk.h"
26
27 #include "DataObjectGtk.h"
28 #include "EditCommand.h"
29 #include "Editor.h"
30 #include <enchant.h>
31 #include "EventNames.h"
32 #include "FocusController.h"
33 #include "Frame.h"
34 #include <glib.h>
35 #include "KeyboardEvent.h"
36 #include "markup.h"
37 #include "NotImplemented.h"
38 #include "Page.h"
39 #include "PasteboardHelperGtk.h"
40 #include "PlatformKeyboardEvent.h"
41 #include "WebKitDOMBinding.h"
42 #include "WebKitDOMCSSStyleDeclarationPrivate.h"
43 #include "WebKitDOMHTMLElementPrivate.h"
44 #include "WebKitDOMNodePrivate.h"
45 #include "WebKitDOMRangePrivate.h"
46 #include "WindowsKeyboardCodes.h"
47 #include "webkitmarshal.h"
48 #include "webkitprivate.h"
49 #include "webkitwebsettingsprivate.h"
50 #include "webkitwebviewprivate.h"
51 #include <wtf/text/CString.h>
52
53 // Arbitrary depth limit for the undo stack, to keep it from using
54 // unbounded memory.  This is the maximum number of distinct undoable
55 // actions -- unbroken stretches of typed characters are coalesced
56 // into a single action.
57 #define maximumUndoStackDepth 1000
58
59 using namespace WebCore;
60
61 namespace WebKit {
62
63 static void imContextCommitted(GtkIMContext* context, const gchar* compositionString, EditorClient* client)
64 {
65     Frame* frame = core(client->webView())->focusController()->focusedOrMainFrame();
66     if (!frame || !frame->editor()->canEdit())
67         return;
68
69     // If this signal fires during a keydown event when we are not in the middle
70     // of a composition, then treat this 'commit' as a normal key event and just
71     // change the editable area right before the keypress event.
72     if (client->treatContextCommitAsKeyEvent()) {
73         client->updatePendingComposition(compositionString);
74         return;
75     }
76
77     // If this signal fires during a mousepress event when we are in the middle
78     // of a composition, skip this 'commit' because the composition is already confirmed. 
79     if (client->preventNextCompositionCommit()) 
80         return;
81  
82     frame->editor()->confirmComposition(String::fromUTF8(compositionString));
83     client->clearPendingComposition();
84 }
85
86 static void imContextPreeditChanged(GtkIMContext* context, EditorClient* client)
87 {
88     Frame* frame = core(client->webView())->focusController()->focusedOrMainFrame();
89     if (!frame || !frame->editor()->canEdit())
90         return;
91
92     // We ignore the provided PangoAttrList for now.
93     GOwnPtr<gchar> newPreedit(0);
94     gtk_im_context_get_preedit_string(context, &newPreedit.outPtr(), 0, 0);
95
96     String preeditString = String::fromUTF8(newPreedit.get());
97     Vector<CompositionUnderline> underlines;
98     underlines.append(CompositionUnderline(0, preeditString.length(), Color(0, 0, 0), false));
99     frame->editor()->setComposition(preeditString, underlines, 0, 0);
100 }
101
102 static void backspaceCallback(GtkWidget* widget, EditorClient* client)
103 {
104     g_signal_stop_emission_by_name(widget, "backspace");
105     client->addPendingEditorCommand("DeleteBackward");
106 }
107
108 static void selectAllCallback(GtkWidget* widget, gboolean select, EditorClient* client)
109 {
110     g_signal_stop_emission_by_name(widget, "select-all");
111     client->addPendingEditorCommand(select ? "SelectAll" : "Unselect");
112 }
113
114 static void cutClipboardCallback(GtkWidget* widget, EditorClient* client)
115 {
116     g_signal_stop_emission_by_name(widget, "cut-clipboard");
117     client->addPendingEditorCommand("Cut");
118 }
119
120 static void copyClipboardCallback(GtkWidget* widget, EditorClient* client)
121 {
122     g_signal_stop_emission_by_name(widget, "copy-clipboard");
123     client->addPendingEditorCommand("Copy");
124 }
125
126 static void pasteClipboardCallback(GtkWidget* widget, EditorClient* client)
127 {
128     g_signal_stop_emission_by_name(widget, "paste-clipboard");
129     client->addPendingEditorCommand("Paste");
130 }
131
132 static void toggleOverwriteCallback(GtkWidget* widget, EditorClient*)
133 {
134     // We don't support toggling the overwrite mode, but the default callback expects
135     // the GtkTextView to have a layout, so we handle this signal just to stop it.
136     g_signal_stop_emission_by_name(widget, "toggle-overwrite");
137 }
138
139 // GTK+ will still send these signals to the web view. So we can safely stop signal
140 // emission without breaking accessibility.
141 static void popupMenuCallback(GtkWidget* widget, EditorClient*)
142 {
143     g_signal_stop_emission_by_name(widget, "popup-menu");
144 }
145
146 static void showHelpCallback(GtkWidget* widget, EditorClient*)
147 {
148     g_signal_stop_emission_by_name(widget, "show-help");
149 }
150
151 static const char* const gtkDeleteCommands[][2] = {
152     { "DeleteBackward",               "DeleteForward"                        }, // Characters
153     { "DeleteWordBackward",           "DeleteWordForward"                    }, // Word ends
154     { "DeleteWordBackward",           "DeleteWordForward"                    }, // Words
155     { "DeleteToBeginningOfLine",      "DeleteToEndOfLine"                    }, // Lines
156     { "DeleteToBeginningOfLine",      "DeleteToEndOfLine"                    }, // Line ends
157     { "DeleteToBeginningOfParagraph", "DeleteToEndOfParagraph"               }, // Paragraph ends
158     { "DeleteToBeginningOfParagraph", "DeleteToEndOfParagraph"               }, // Paragraphs
159     { 0,                              0                                      } // Whitespace (M-\ in Emacs)
160 };
161
162 static void deleteFromCursorCallback(GtkWidget* widget, GtkDeleteType deleteType, gint count, EditorClient* client)
163 {
164     g_signal_stop_emission_by_name(widget, "delete-from-cursor");
165     int direction = count > 0 ? 1 : 0;
166
167     // Ensuring that deleteType <= G_N_ELEMENTS here results in a compiler warning
168     // that the condition is always true.
169
170     if (deleteType == GTK_DELETE_WORDS) {
171         if (!direction) {
172             client->addPendingEditorCommand("MoveWordForward");
173             client->addPendingEditorCommand("MoveWordBackward");
174         } else {
175             client->addPendingEditorCommand("MoveWordBackward");
176             client->addPendingEditorCommand("MoveWordForward");
177         }
178     } else if (deleteType == GTK_DELETE_DISPLAY_LINES) {
179         if (!direction)
180             client->addPendingEditorCommand("MoveToBeginningOfLine");
181         else
182             client->addPendingEditorCommand("MoveToEndOfLine");
183     } else if (deleteType == GTK_DELETE_PARAGRAPHS) {
184         if (!direction)
185             client->addPendingEditorCommand("MoveToBeginningOfParagraph");
186         else
187             client->addPendingEditorCommand("MoveToEndOfParagraph");
188     }
189
190     const char* rawCommand = gtkDeleteCommands[deleteType][direction];
191     if (!rawCommand)
192       return;
193
194     for (int i = 0; i < abs(count); i++)
195         client->addPendingEditorCommand(rawCommand);
196 }
197
198 static const char* const gtkMoveCommands[][4] = {
199     { "MoveBackward",                                   "MoveForward",
200       "MoveBackwardAndModifySelection",                 "MoveForwardAndModifySelection"             }, // Forward/backward grapheme
201     { "MoveLeft",                                       "MoveRight",
202       "MoveBackwardAndModifySelection",                 "MoveForwardAndModifySelection"             }, // Left/right grapheme
203     { "MoveWordBackward",                               "MoveWordForward",
204       "MoveWordBackwardAndModifySelection",             "MoveWordForwardAndModifySelection"         }, // Forward/backward word
205     { "MoveUp",                                         "MoveDown",
206       "MoveUpAndModifySelection",                       "MoveDownAndModifySelection"                }, // Up/down line
207     { "MoveToBeginningOfLine",                          "MoveToEndOfLine",
208       "MoveToBeginningOfLineAndModifySelection",        "MoveToEndOfLineAndModifySelection"         }, // Up/down line ends
209     { "MoveParagraphForward",                           "MoveParagraphBackward",
210       "MoveParagraphForwardAndModifySelection",         "MoveParagraphBackwardAndModifySelection"   }, // Up/down paragraphs
211     { "MoveToBeginningOfParagraph",                     "MoveToEndOfParagraph",
212       "MoveToBeginningOfParagraphAndModifySelection",   "MoveToEndOfParagraphAndModifySelection"    }, // Up/down paragraph ends.
213     { "MovePageUp",                                     "MovePageDown",
214       "MovePageUpAndModifySelection",                   "MovePageDownAndModifySelection"            }, // Up/down page
215     { "MoveToBeginningOfDocument",                      "MoveToEndOfDocument",
216       "MoveToBeginningOfDocumentAndModifySelection",    "MoveToEndOfDocumentAndModifySelection"     }, // Begin/end of buffer
217     { 0,                                                0,
218       0,                                                0                                           } // Horizontal page movement
219 };
220
221 static void moveCursorCallback(GtkWidget* widget, GtkMovementStep step, gint count, gboolean extendSelection, EditorClient* client)
222 {
223     g_signal_stop_emission_by_name(widget, "move-cursor");
224     int direction = count > 0 ? 1 : 0;
225     if (extendSelection)
226         direction += 2;
227
228     if (static_cast<unsigned>(step) >= G_N_ELEMENTS(gtkMoveCommands))
229         return;
230
231     const char* rawCommand = gtkMoveCommands[step][direction];
232     if (!rawCommand)
233         return;
234
235     for (int i = 0; i < abs(count); i++)
236         client->addPendingEditorCommand(rawCommand);
237 }
238
239 void EditorClient::updatePendingComposition(const gchar* newComposition)
240 {
241     // The IMContext may signal more than one completed composition in a row,
242     // in which case we want to append them, rather than overwrite the old one.
243     if (!m_pendingComposition)
244         m_pendingComposition.set(g_strdup(newComposition));
245     else
246         m_pendingComposition.set(g_strconcat(m_pendingComposition.get(), newComposition, NULL));
247 }
248
249 void EditorClient::willSetInputMethodState()
250 {
251 }
252
253 void EditorClient::setInputMethodState(bool active)
254 {
255     WebKitWebViewPrivate* priv = m_webView->priv;
256
257     if (active)
258         gtk_im_context_focus_in(priv->imContext.get());
259     else
260         gtk_im_context_focus_out(priv->imContext.get());
261
262 #ifdef MAEMO_CHANGES
263     if (active)
264         hildon_gtk_im_context_show(priv->imContext.get());
265     else
266         hildon_gtk_im_context_hide(priv->imContext.get());
267 #endif
268 }
269
270 bool EditorClient::shouldDeleteRange(Range* range)
271 {
272     gboolean accept = TRUE;
273     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
274     g_signal_emit_by_name(m_webView, "should-delete-range", kitRange.get(), &accept);
275     return accept;
276 }
277
278 bool EditorClient::shouldShowDeleteInterface(HTMLElement* element)
279 {
280     gboolean accept = TRUE;
281     PlatformRefPtr<WebKitDOMHTMLElement> kitElement(adoptPlatformRef(kit(element)));
282     g_signal_emit_by_name(m_webView, "should-show-delete-interface-for-element", kitElement.get(), &accept);
283     return accept;
284 }
285
286 bool EditorClient::isContinuousSpellCheckingEnabled()
287 {
288     WebKitWebSettings* settings = webkit_web_view_get_settings(m_webView);
289
290     gboolean enabled;
291     g_object_get(settings, "enable-spell-checking", &enabled, NULL);
292
293     return enabled;
294 }
295
296 bool EditorClient::isGrammarCheckingEnabled()
297 {
298     notImplemented();
299     return false;
300 }
301
302 int EditorClient::spellCheckerDocumentTag()
303 {
304     notImplemented();
305     return 0;
306 }
307
308 bool EditorClient::shouldBeginEditing(WebCore::Range* range)
309 {
310     clearPendingComposition();
311
312     gboolean accept = TRUE;
313     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
314     g_signal_emit_by_name(m_webView, "should-begin-editing", kitRange.get(), &accept);
315     return accept;
316 }
317
318 bool EditorClient::shouldEndEditing(WebCore::Range* range)
319 {
320     clearPendingComposition();
321
322     gboolean accept = TRUE;
323     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
324     g_signal_emit_by_name(m_webView, "should-end-editing", kitRange.get(), &accept);
325     return accept;
326 }
327
328 static WebKitInsertAction kit(EditorInsertAction action)
329 {
330     switch (action) {
331     case EditorInsertActionTyped:
332         return WEBKIT_INSERT_ACTION_TYPED;
333     case EditorInsertActionPasted:
334         return WEBKIT_INSERT_ACTION_PASTED;
335     case EditorInsertActionDropped:
336         return WEBKIT_INSERT_ACTION_DROPPED;
337     }
338     ASSERT_NOT_REACHED();
339     return WEBKIT_INSERT_ACTION_TYPED;
340 }
341
342 bool EditorClient::shouldInsertText(const String& string, Range* range, EditorInsertAction action)
343 {
344     gboolean accept = TRUE;
345     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
346     g_signal_emit_by_name(m_webView, "should-insert-text", string.utf8().data(), kitRange.get(), kit(action), &accept);
347     return accept;
348 }
349
350 static WebKitSelectionAffinity kit(EAffinity affinity)
351 {
352     switch (affinity) {
353     case UPSTREAM:
354         return WEBKIT_SELECTION_AFFINITY_UPSTREAM;
355     case DOWNSTREAM:
356         return WEBKIT_SELECTION_AFFINITY_DOWNSTREAM;
357     }
358     ASSERT_NOT_REACHED();
359     return WEBKIT_SELECTION_AFFINITY_UPSTREAM;
360 }
361
362 bool EditorClient::shouldChangeSelectedRange(Range* fromRange, Range* toRange, EAffinity affinity, bool stillSelecting)
363 {
364     gboolean accept = TRUE;
365     PlatformRefPtr<WebKitDOMRange> kitFromRange(fromRange ? adoptPlatformRef(kit(fromRange)) : 0);
366     PlatformRefPtr<WebKitDOMRange> kitToRange(toRange ? adoptPlatformRef(kit(toRange)) : 0);
367     g_signal_emit_by_name(m_webView, "should-change-selected-range", kitFromRange.get(), kitToRange.get(),
368                           kit(affinity), stillSelecting, &accept);
369     return accept;
370 }
371
372 bool EditorClient::shouldApplyStyle(WebCore::CSSStyleDeclaration* declaration, WebCore::Range* range)
373 {
374     gboolean accept = TRUE;
375     PlatformRefPtr<WebKitDOMCSSStyleDeclaration> kitDeclaration(kit(declaration));
376     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
377     g_signal_emit_by_name(m_webView, "should-apply-style", kitDeclaration.get(), kitRange.get(), &accept);
378     return accept;
379 }
380
381 bool EditorClient::shouldMoveRangeAfterDelete(WebCore::Range*, WebCore::Range*)
382 {
383     notImplemented();
384     return true;
385 }
386
387 void EditorClient::didBeginEditing()
388 {
389     g_signal_emit_by_name(m_webView, "editing-began");
390 }
391
392 void EditorClient::respondToChangedContents()
393 {
394     g_signal_emit_by_name(m_webView, "user-changed-contents");
395 }
396
397 static WebKitWebView* viewSettingClipboard = 0;
398 static void collapseSelection(GtkClipboard* clipboard, WebKitWebView* webView)
399 {
400     if (viewSettingClipboard && viewSettingClipboard == webView)
401         return;
402
403     WebCore::Page* corePage = core(webView);
404     if (!corePage || !corePage->focusController())
405         return;
406
407     Frame* frame = corePage->focusController()->focusedOrMainFrame();
408
409     // Collapse the selection without clearing it
410     ASSERT(frame);
411     frame->selection()->setBase(frame->selection()->extent(), frame->selection()->affinity());
412 }
413
414 #if PLATFORM(X11)
415 static void setSelectionPrimaryClipboardIfNeeded(WebKitWebView* webView)
416 {
417     if (!gtk_widget_has_screen(GTK_WIDGET(webView)))
418         return;
419
420     GtkClipboard* clipboard = gtk_widget_get_clipboard(GTK_WIDGET(webView), GDK_SELECTION_PRIMARY);
421     DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
422     WebCore::Page* corePage = core(webView);
423     Frame* targetFrame = corePage->focusController()->focusedOrMainFrame();
424
425     if (!targetFrame->selection()->isRange())
426         return;
427
428     dataObject->clear();
429     dataObject->setRange(targetFrame->selection()->toNormalizedRange());
430
431     viewSettingClipboard = webView;
432     GClosure* callback = g_cclosure_new_object(G_CALLBACK(collapseSelection), G_OBJECT(webView));
433     g_closure_set_marshal(callback, g_cclosure_marshal_VOID__VOID);
434     pasteboardHelperInstance()->writeClipboardContents(clipboard, callback);
435     viewSettingClipboard = 0;
436 }
437 #endif
438
439 void EditorClient::respondToChangedSelection()
440 {
441     g_signal_emit_by_name(m_webView, "selection-changed");
442
443     WebKitWebViewPrivate* priv = m_webView->priv;
444     WebCore::Page* corePage = core(m_webView);
445     Frame* targetFrame = corePage->focusController()->focusedOrMainFrame();
446
447     if (!targetFrame)
448         return;
449
450     if (targetFrame->editor()->ignoreCompositionSelectionChange())
451         return;
452
453 #if PLATFORM(X11)
454     setSelectionPrimaryClipboardIfNeeded(m_webView);
455 #endif
456
457     if (!targetFrame->editor()->hasComposition())
458         return;
459
460     unsigned start;
461     unsigned end;
462     if (!targetFrame->editor()->getCompositionSelection(start, end)) {
463         // gtk_im_context_reset() clears the composition for us.
464         gtk_im_context_reset(priv->imContext.get());
465         targetFrame->editor()->confirmCompositionWithoutDisturbingSelection();
466     }
467 }
468
469 void EditorClient::didEndEditing()
470 {
471     g_signal_emit_by_name(m_webView, "editing-ended");
472 }
473
474 void EditorClient::didWriteSelectionToPasteboard()
475 {
476     notImplemented();
477 }
478
479 void EditorClient::didSetSelectionTypesForPasteboard()
480 {
481     notImplemented();
482 }
483
484 bool EditorClient::isEditable()
485 {
486     return webkit_web_view_get_editable(m_webView);
487 }
488
489 void EditorClient::registerCommandForUndo(WTF::PassRefPtr<WebCore::EditCommand> command)
490 {
491     if (undoStack.size() == maximumUndoStackDepth)
492         undoStack.removeFirst();
493     if (!m_isInRedo)
494         redoStack.clear();
495     undoStack.append(command);
496 }
497
498 void EditorClient::registerCommandForRedo(WTF::PassRefPtr<WebCore::EditCommand> command)
499 {
500     redoStack.append(command);
501 }
502
503 void EditorClient::clearUndoRedoOperations()
504 {
505     undoStack.clear();
506     redoStack.clear();
507 }
508
509 bool EditorClient::canUndo() const
510 {
511     return !undoStack.isEmpty();
512 }
513
514 bool EditorClient::canRedo() const
515 {
516     return !redoStack.isEmpty();
517 }
518
519 void EditorClient::undo()
520 {
521     if (canUndo()) {
522         RefPtr<WebCore::EditCommand> command(*(--undoStack.end()));
523         undoStack.remove(--undoStack.end());
524         // unapply will call us back to push this command onto the redo stack.
525         command->unapply();
526     }
527 }
528
529 void EditorClient::redo()
530 {
531     if (canRedo()) {
532         RefPtr<WebCore::EditCommand> command(*(--redoStack.end()));
533         redoStack.remove(--redoStack.end());
534
535         ASSERT(!m_isInRedo);
536         m_isInRedo = true;
537         // reapply will call us back to push this command onto the undo stack.
538         command->reapply();
539         m_isInRedo = false;
540     }
541 }
542
543 bool EditorClient::shouldInsertNode(Node* node, Range* range, EditorInsertAction action)
544 {
545     gboolean accept = TRUE;
546     PlatformRefPtr<WebKitDOMRange> kitRange(adoptPlatformRef(kit(range)));
547     PlatformRefPtr<WebKitDOMNode> kitNode(adoptPlatformRef(kit(node)));
548     g_signal_emit_by_name(m_webView, "should-insert-node", kitNode.get(), kitRange.get(), kit(action), &accept);
549     return accept;
550 }
551
552 void EditorClient::pageDestroyed()
553 {
554     delete this;
555 }
556
557 bool EditorClient::smartInsertDeleteEnabled()
558 {
559     notImplemented();
560     return false;
561 }
562
563 bool EditorClient::isSelectTrailingWhitespaceEnabled()
564 {
565     notImplemented();
566     return false;
567 }
568
569 void EditorClient::toggleContinuousSpellChecking()
570 {
571     WebKitWebSettings* settings = webkit_web_view_get_settings(m_webView);
572
573     gboolean enabled;
574     g_object_get(settings, "enable-spell-checking", &enabled, NULL);
575
576     g_object_set(settings, "enable-spell-checking", !enabled, NULL);
577 }
578
579 void EditorClient::toggleGrammarChecking()
580 {
581 }
582
583 static const unsigned CtrlKey = 1 << 0;
584 static const unsigned AltKey = 1 << 1;
585 static const unsigned ShiftKey = 1 << 2;
586
587 struct KeyDownEntry {
588     unsigned virtualKey;
589     unsigned modifiers;
590     const char* name;
591 };
592
593 struct KeyPressEntry {
594     unsigned charCode;
595     unsigned modifiers;
596     const char* name;
597 };
598
599 static const KeyDownEntry keyDownEntries[] = {
600     { 'B',       CtrlKey,            "ToggleBold"                                  },
601     { 'I',       CtrlKey,            "ToggleItalic"                                },
602     { VK_ESCAPE, 0,                  "Cancel"                                      },
603     { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
604     { VK_TAB,    0,                  "InsertTab"                                   },
605     { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
606     { VK_RETURN, 0,                  "InsertNewline"                               },
607     { VK_RETURN, CtrlKey,            "InsertNewline"                               },
608     { VK_RETURN, AltKey,             "InsertNewline"                               },
609     { VK_RETURN, AltKey | ShiftKey,  "InsertNewline"                               },
610 };
611
612 static const KeyPressEntry keyPressEntries[] = {
613     { '\t',   0,                  "InsertTab"                                   },
614     { '\t',   ShiftKey,           "InsertBacktab"                               },
615     { '\r',   0,                  "InsertNewline"                               },
616     { '\r',   CtrlKey,            "InsertNewline"                               },
617     { '\r',   AltKey,             "InsertNewline"                               },
618     { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
619 };
620
621 void EditorClient::generateEditorCommands(const KeyboardEvent* event)
622 {
623     ASSERT(event->type() == eventNames().keydownEvent || event->type() == eventNames().keypressEvent);
624
625     m_pendingEditorCommands.clear();
626
627     // First try to interpret the command as a native GTK+ key binding.
628 #ifdef GTK_API_VERSION_2
629     gtk_bindings_activate_event(GTK_OBJECT(m_nativeWidget.get()), event->keyEvent()->gdkEventKey());
630 #else
631     gtk_bindings_activate_event(G_OBJECT(m_nativeWidget.get()), event->keyEvent()->gdkEventKey());
632 #endif
633     if (m_pendingEditorCommands.size() > 0)
634         return;
635
636     static HashMap<int, const char*> keyDownCommandsMap;
637     static HashMap<int, const char*> keyPressCommandsMap;
638
639     if (keyDownCommandsMap.isEmpty()) {
640         for (unsigned i = 0; i < G_N_ELEMENTS(keyDownEntries); i++)
641             keyDownCommandsMap.set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
642
643         for (unsigned i = 0; i < G_N_ELEMENTS(keyPressEntries); i++)
644             keyPressCommandsMap.set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
645     }
646
647     unsigned modifiers = 0;
648     if (event->shiftKey())
649         modifiers |= ShiftKey;
650     if (event->altKey())
651         modifiers |= AltKey;
652     if (event->ctrlKey())
653         modifiers |= CtrlKey;
654
655
656     if (event->type() == eventNames().keydownEvent) {
657         int mapKey = modifiers << 16 | event->keyCode();
658         if (mapKey)
659             m_pendingEditorCommands.append(keyDownCommandsMap.get(mapKey));
660         return;
661     }
662
663     int mapKey = modifiers << 16 | event->charCode();
664     if (mapKey)
665         m_pendingEditorCommands.append(keyPressCommandsMap.get(mapKey));
666 }
667
668 bool EditorClient::executePendingEditorCommands(Frame* frame, bool allowTextInsertion)
669 {
670     Vector<Editor::Command> commands;
671     for (size_t i = 0; i < m_pendingEditorCommands.size(); i++) {
672         Editor::Command command = frame->editor()->command(m_pendingEditorCommands.at(i));
673         if (command.isTextInsertion() && !allowTextInsertion)
674             return false;
675
676         commands.append(command);
677     }
678
679     bool success = true;
680     for (size_t i = 0; i < commands.size(); i++) {
681         if (!commands.at(i).execute()) {
682             success = false;
683             break;
684         }
685     }
686
687     m_pendingEditorCommands.clear();
688
689     // If we successfully completed all editor commands, then
690     // this signals a canceling of the composition.
691     if (success)
692         clearPendingComposition();
693
694     return success;
695 }
696
697 void EditorClient::handleKeyboardEvent(KeyboardEvent* event)
698 {
699     Node* node = event->target()->toNode();
700     ASSERT(node);
701     Frame* frame = node->document()->frame();
702     ASSERT(frame);
703
704     const PlatformKeyboardEvent* platformEvent = event->keyEvent();
705     if (!platformEvent)
706         return;
707
708     generateEditorCommands(event);
709     if (m_pendingEditorCommands.size() > 0) {
710
711         // During RawKeyDown events if an editor command will insert text, defer
712         // the insertion until the keypress event. We want keydown to bubble up
713         // through the DOM first.
714         if (platformEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
715             if (executePendingEditorCommands(frame, false))
716                 event->setDefaultHandled();
717
718             return;
719         }
720
721         // Only allow text insertion commands if the current node is editable.
722         if (executePendingEditorCommands(frame, frame->editor()->canEdit())) {
723             event->setDefaultHandled();
724             return;
725         }
726     }
727
728     // Don't allow text insertion for nodes that cannot edit.
729     if (!frame->editor()->canEdit())
730         return;
731
732     // This is just a normal text insertion, so wait to execute the insertion
733     // until a keypress event happens. This will ensure that the insertion will not
734     // be reflected in the contents of the field until the keyup DOM event.
735     if (event->type() == eventNames().keypressEvent) {
736
737         // If we have a pending composition at this point, it happened while
738         // filtering a keypress, so we treat it as a normal text insertion.
739         // This will also ensure that if the keypress event handler changed the
740         // currently focused node, the text is still inserted into the original
741         // node (insertText() has this logic, but confirmComposition() does not).
742         if (m_pendingComposition) {
743             frame->editor()->insertText(String::fromUTF8(m_pendingComposition.get()), event);
744             clearPendingComposition();
745             event->setDefaultHandled();
746
747         } else {
748             // Don't insert null or control characters as they can result in unexpected behaviour
749             if (event->charCode() < ' ')
750                 return;
751
752             // Don't insert anything if a modifier is pressed
753             if (platformEvent->ctrlKey() || platformEvent->altKey())
754                 return;
755
756             if (frame->editor()->insertText(platformEvent->text(), event))
757                 event->setDefaultHandled();
758         }
759     }
760 }
761
762 void EditorClient::handleInputMethodKeydown(KeyboardEvent* event)
763 {
764     Frame* targetFrame = core(m_webView)->focusController()->focusedOrMainFrame();
765     if (!targetFrame || !targetFrame->editor()->canEdit())
766         return;
767
768     WebKitWebViewPrivate* priv = m_webView->priv;
769
770     m_preventNextCompositionCommit = false;
771
772     // Some IM contexts (e.g. 'simple') will act as if they filter every
773     // keystroke and just issue a 'commit' signal during handling. In situations
774     // where the 'commit' signal happens during filtering and there is no active
775     // composition, act as if the keystroke was not filtered. The one exception to
776     // this is when the keyval parameter of the GdkKeyEvent is 0, which is often
777     // a key event sent by the IM context for committing the current composition.
778
779     // Here is a typical sequence of events for the 'simple' context:
780     // 1. GDK key press event -> webkit_web_view_key_press_event
781     // 2. Keydown event -> EditorClient::handleInputMethodKeydown
782     //     gtk_im_context_filter_keypress returns true, but there is a pending
783     //     composition so event->preventDefault is not called (below).
784     // 3. Keydown event bubbles through the DOM
785     // 4. Keydown event -> EditorClient::handleKeyboardEvent
786     //     No action taken.
787     // 4. GDK key release event -> webkit_web_view_key_release_event
788     // 5. gtk_im_context_filter_keypress is called on the release event.
789     //     Simple does not filter most key releases, so the event continues.
790     // 6. Keypress event bubbles through the DOM.
791     // 7. Keypress event -> EditorClient::handleKeyboardEvent
792     //     pending composition is inserted.
793     // 8. Keyup event bubbles through the DOM.
794     // 9. Keyup event -> EditorClient::handleKeyboardEvent
795     //     No action taken.
796
797     // There are two situations where we do filter the keystroke:
798     // 1. The IMContext instructed us to filter and we have no pending composition.
799     // 2. The IMContext did not instruct us to filter, but the keystroke caused a
800     //    composition in progress to finish. It seems that sometimes SCIM will finish
801     //    a composition and not mark the keystroke as filtered.
802     m_treatContextCommitAsKeyEvent = (!targetFrame->editor()->hasComposition())
803          && event->keyEvent()->gdkEventKey()->keyval;
804     clearPendingComposition();
805     if ((gtk_im_context_filter_keypress(priv->imContext.get(), event->keyEvent()->gdkEventKey()) && !m_pendingComposition)
806         || (!m_treatContextCommitAsKeyEvent && !targetFrame->editor()->hasComposition()))
807         event->preventDefault();
808
809     m_treatContextCommitAsKeyEvent = false;
810 }
811
812 void EditorClient::handleInputMethodMousePress()
813 {
814     Frame* targetFrame = core(m_webView)->focusController()->focusedOrMainFrame();
815
816     if (!targetFrame || !targetFrame->editor()->canEdit())
817         return;
818
819     WebKitWebViewPrivate* priv = m_webView->priv;
820
821     // When a mouse press fires, the commit signal happens during a composition.
822     // In this case, if the focused node is changed, the commit signal happens in a diffrent node.
823     // Therefore, we need to confirm the current compositon and ignore the next commit signal. 
824     GOwnPtr<gchar> newPreedit(0);
825     gtk_im_context_get_preedit_string(priv->imContext.get(), &newPreedit.outPtr(), 0, 0);
826     
827     if (g_utf8_strlen(newPreedit.get(), -1)) {
828         targetFrame->editor()->confirmComposition();
829         m_preventNextCompositionCommit = true;
830         gtk_im_context_reset(priv->imContext.get());
831     } 
832 }
833
834 EditorClient::EditorClient(WebKitWebView* webView)
835     : m_isInRedo(false)
836     , m_webView(webView)
837     , m_preventNextCompositionCommit(false)
838     , m_treatContextCommitAsKeyEvent(false)
839     , m_nativeWidget(gtk_text_view_new())
840 {
841     WebKitWebViewPrivate* priv = m_webView->priv;
842     g_signal_connect(priv->imContext.get(), "commit", G_CALLBACK(imContextCommitted), this);
843     g_signal_connect(priv->imContext.get(), "preedit-changed", G_CALLBACK(imContextPreeditChanged), this);
844
845     g_signal_connect(m_nativeWidget.get(), "backspace", G_CALLBACK(backspaceCallback), this);
846     g_signal_connect(m_nativeWidget.get(), "cut-clipboard", G_CALLBACK(cutClipboardCallback), this);
847     g_signal_connect(m_nativeWidget.get(), "copy-clipboard", G_CALLBACK(copyClipboardCallback), this);
848     g_signal_connect(m_nativeWidget.get(), "paste-clipboard", G_CALLBACK(pasteClipboardCallback), this);
849     g_signal_connect(m_nativeWidget.get(), "select-all", G_CALLBACK(selectAllCallback), this);
850     g_signal_connect(m_nativeWidget.get(), "move-cursor", G_CALLBACK(moveCursorCallback), this);
851     g_signal_connect(m_nativeWidget.get(), "delete-from-cursor", G_CALLBACK(deleteFromCursorCallback), this);
852     g_signal_connect(m_nativeWidget.get(), "toggle-overwrite", G_CALLBACK(toggleOverwriteCallback), this);
853     g_signal_connect(m_nativeWidget.get(), "popup-menu", G_CALLBACK(popupMenuCallback), this);
854     g_signal_connect(m_nativeWidget.get(), "show-help", G_CALLBACK(showHelpCallback), this);
855 }
856
857 EditorClient::~EditorClient()
858 {
859     WebKitWebViewPrivate* priv = m_webView->priv;
860     g_signal_handlers_disconnect_by_func(priv->imContext.get(), (gpointer)imContextCommitted, this);
861     g_signal_handlers_disconnect_by_func(priv->imContext.get(), (gpointer)imContextPreeditChanged, this);
862 }
863
864 void EditorClient::textFieldDidBeginEditing(Element*)
865 {
866 }
867
868 void EditorClient::textFieldDidEndEditing(Element*)
869 {
870 }
871
872 void EditorClient::textDidChangeInTextField(Element*)
873 {
874 }
875
876 bool EditorClient::doTextFieldCommandFromEvent(Element*, KeyboardEvent*)
877 {
878     return false;
879 }
880
881 void EditorClient::textWillBeDeletedInTextField(Element*)
882 {
883     notImplemented();
884 }
885
886 void EditorClient::textDidChangeInTextArea(Element*)
887 {
888     notImplemented();
889 }
890
891 void EditorClient::ignoreWordInSpellDocument(const String& text)
892 {
893     GSList* dicts = webkit_web_settings_get_enchant_dicts(m_webView);
894
895     for (; dicts; dicts = dicts->next) {
896         EnchantDict* dict = static_cast<EnchantDict*>(dicts->data);
897
898         enchant_dict_add_to_session(dict, text.utf8().data(), -1);
899     }
900 }
901
902 void EditorClient::learnWord(const String& text)
903 {
904     GSList* dicts = webkit_web_settings_get_enchant_dicts(m_webView);
905
906     for (; dicts; dicts = dicts->next) {
907         EnchantDict* dict = static_cast<EnchantDict*>(dicts->data);
908
909         enchant_dict_add_to_personal(dict, text.utf8().data(), -1);
910     }
911 }
912
913 void EditorClient::checkSpellingOfString(const UChar* text, int length, int* misspellingLocation, int* misspellingLength)
914 {
915     GSList* dicts = webkit_web_settings_get_enchant_dicts(m_webView);
916     if (!dicts)
917         return;
918
919     gchar* ctext = g_utf16_to_utf8(const_cast<gunichar2*>(text), length, 0, 0, 0);
920     int utflen = g_utf8_strlen(ctext, -1);
921
922     PangoLanguage* language = pango_language_get_default();
923     PangoLogAttr* attrs = g_new(PangoLogAttr, utflen+1);
924
925     // pango_get_log_attrs uses an aditional position at the end of the text.
926     pango_get_log_attrs(ctext, -1, -1, language, attrs, utflen+1);
927
928     for (int i = 0; i < length+1; i++) {
929         // We go through each character until we find an is_word_start,
930         // then we get into an inner loop to find the is_word_end corresponding
931         // to it.
932         if (attrs[i].is_word_start) {
933             int start = i;
934             int end = i;
935             int wordLength;
936
937             while (attrs[end].is_word_end < 1)
938                 end++;
939
940             wordLength = end - start;
941             // Set the iterator to be at the current word end, so we don't
942             // check characters twice.
943             i = end;
944
945             for (; dicts; dicts = dicts->next) {
946                 EnchantDict* dict = static_cast<EnchantDict*>(dicts->data);
947                 gchar* cstart = g_utf8_offset_to_pointer(ctext, start);
948                 gint bytes = static_cast<gint>(g_utf8_offset_to_pointer(ctext, end) - cstart);
949                 gchar* word = g_new0(gchar, bytes+1);
950                 int result;
951
952                 g_utf8_strncpy(word, cstart, end - start);
953
954                 result = enchant_dict_check(dict, word, -1);
955                 g_free(word);
956                 if (result) {
957                     *misspellingLocation = start;
958                     *misspellingLength = wordLength;
959                 } else {
960                     // Stop checking, this word is ok in at least one dict.
961                     *misspellingLocation = -1;
962                     *misspellingLength = 0;
963                     break;
964                 }
965             }
966         }
967     }
968
969     g_free(attrs);
970     g_free(ctext);
971 }
972
973 String EditorClient::getAutoCorrectSuggestionForMisspelledWord(const String& inputWord)
974 {
975     // This method can be implemented using customized algorithms for the particular browser.
976     // Currently, it computes an empty string.
977     return String();
978 }
979
980 void EditorClient::checkGrammarOfString(const UChar*, int, Vector<GrammarDetail>&, int*, int*)
981 {
982     notImplemented();
983 }
984
985 void EditorClient::updateSpellingUIWithGrammarString(const String&, const GrammarDetail&)
986 {
987     notImplemented();
988 }
989
990 void EditorClient::updateSpellingUIWithMisspelledWord(const String&)
991 {
992     notImplemented();
993 }
994
995 void EditorClient::showSpellingUI(bool)
996 {
997     notImplemented();
998 }
999
1000 bool EditorClient::spellingUIIsShowing()
1001 {
1002     notImplemented();
1003     return false;
1004 }
1005
1006 void EditorClient::getGuessesForWord(const String& word, const String& context, WTF::Vector<String>& guesses)
1007 {
1008     GSList* dicts = webkit_web_settings_get_enchant_dicts(m_webView);
1009     guesses.clear();
1010
1011     for (; dicts; dicts = dicts->next) {
1012         size_t numberOfSuggestions;
1013         size_t i;
1014
1015         EnchantDict* dict = static_cast<EnchantDict*>(dicts->data);
1016         gchar** suggestions = enchant_dict_suggest(dict, word.utf8().data(), -1, &numberOfSuggestions);
1017
1018         for (i = 0; i < numberOfSuggestions && i < 10; i++)
1019             guesses.append(String::fromUTF8(suggestions[i]));
1020
1021         if (numberOfSuggestions > 0)
1022             enchant_dict_free_suggestions(dict, suggestions);
1023     }
1024 }
1025
1026 }