Source/WebCore: Enable grammar checking on Chromium when we paste text (Take 2)
[WebKit-https.git] / Source / WebKit / chromium / src / EditorClientImpl.cpp
1 /*
2  * Copyright (C) 2006, 2007 Apple, Inc.  All rights reserved.
3  * Copyright (C) 2012 Google, Inc.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "EditorClientImpl.h"
29
30 #include "Document.h"
31 #include "Editor.h"
32 #include "EventHandler.h"
33 #include "EventNames.h"
34 #include "Frame.h"
35 #include "HTMLInputElement.h"
36 #include "HTMLNames.h"
37 #include "KeyboardCodes.h"
38 #include "KeyboardEvent.h"
39 #include "PlatformKeyboardEvent.h"
40 #include "PlatformString.h"
41 #include "RenderObject.h"
42 #include "Settings.h"
43 #include "SpellChecker.h"
44 #include "UndoStep.h"
45
46 #include "DOMUtilitiesPrivate.h"
47 #include "WebAutofillClient.h"
48 #include "WebEditingAction.h"
49 #include "WebElement.h"
50 #include "WebFrameClient.h"
51 #include "WebFrameImpl.h"
52 #include "WebKit.h"
53 #include "WebInputElement.h"
54 #include "WebInputEventConversion.h"
55 #include "WebNode.h"
56 #include "WebPermissionClient.h"
57 #include "WebRange.h"
58 #include "WebSpellCheckClient.h"
59 #include "WebTextAffinity.h"
60 #include "WebTextCheckingCompletionImpl.h"
61 #include "WebTextCheckingResult.h"
62 #include "WebViewClient.h"
63 #include "WebViewImpl.h"
64
65 using namespace WebCore;
66
67 namespace WebKit {
68
69 // Arbitrary depth limit for the undo stack, to keep it from using
70 // unbounded memory.  This is the maximum number of distinct undoable
71 // actions -- unbroken stretches of typed characters are coalesced
72 // into a single action.
73 static const size_t maximumUndoStackDepth = 1000;
74
75 EditorClientImpl::EditorClientImpl(WebViewImpl* webview)
76     : m_webView(webview)
77     , m_inRedo(false)
78     , m_spellCheckThisFieldStatus(SpellCheckAutomatic)
79 {
80 }
81
82 EditorClientImpl::~EditorClientImpl()
83 {
84 }
85
86 void EditorClientImpl::pageDestroyed()
87 {
88     // Our lifetime is bound to the WebViewImpl.
89 }
90
91 void EditorClientImpl::frameWillDetachPage(WebCore::Frame* frame)
92 {
93     HashSet<WebTextCheckingCompletionImpl*> validRequests;
94
95     for (HashSet<WebTextCheckingCompletionImpl*>::iterator i = m_pendingTextChecks.begin();
96          i != m_pendingTextChecks.end(); ++i) {
97         if (frame->editor()->spellChecker() == (*i)->spellChecker())
98             (*i)->invalidate();
99         else
100             validRequests.add(*i);
101     }
102
103     m_pendingTextChecks.swap(validRequests);
104 }
105
106 bool EditorClientImpl::shouldShowDeleteInterface(HTMLElement* elem)
107 {
108     // Normally, we don't care to show WebCore's deletion UI, so we only enable
109     // it if in testing mode and the test specifically requests it by using this
110     // magic class name.
111     return layoutTestMode()
112            && elem->getAttribute(HTMLNames::classAttr) == "needsDeletionUI";
113 }
114
115 bool EditorClientImpl::smartInsertDeleteEnabled()
116 {
117     if (m_webView->client())
118         return m_webView->client()->isSmartInsertDeleteEnabled();
119     return true;
120 }
121
122 bool EditorClientImpl::isSelectTrailingWhitespaceEnabled()
123 {
124     if (m_webView->client())
125         return m_webView->client()->isSelectTrailingWhitespaceEnabled();
126 #if OS(WINDOWS)
127     return true;
128 #else
129     return false;
130 #endif
131 }
132
133 bool EditorClientImpl::shouldSpellcheckByDefault()
134 {
135     // Spellcheck should be enabled for all editable areas (such as textareas,
136     // contentEditable regions, and designMode docs), except text inputs.
137     const Frame* frame = m_webView->focusedWebCoreFrame();
138     if (!frame)
139         return false;
140     const Editor* editor = frame->editor();
141     if (!editor)
142         return false;
143     if (editor->isSpellCheckingEnabledInFocusedNode())
144         return true;
145     const Document* document = frame->document();
146     if (!document)
147         return false;
148     const Node* node = document->focusedNode();
149     // If |node| is null, we default to allowing spellchecking. This is done in
150     // order to mitigate the issue when the user clicks outside the textbox, as a
151     // result of which |node| becomes null, resulting in all the spell check
152     // markers being deleted. Also, the Frame will decide not to do spellchecking
153     // if the user can't edit - so returning true here will not cause any problems
154     // to the Frame's behavior.
155     if (!node)
156         return true;
157     const RenderObject* renderer = node->renderer();
158     if (!renderer)
159         return false;
160
161     return !renderer->isTextField();
162 }
163
164 bool EditorClientImpl::isContinuousSpellCheckingEnabled()
165 {
166     if (m_spellCheckThisFieldStatus == SpellCheckForcedOff)
167         return false;
168     if (m_spellCheckThisFieldStatus == SpellCheckForcedOn)
169         return true;
170     return shouldSpellcheckByDefault();
171 }
172
173 void EditorClientImpl::toggleContinuousSpellChecking()
174 {
175     if (isContinuousSpellCheckingEnabled())
176         m_spellCheckThisFieldStatus = SpellCheckForcedOff;
177     else
178         m_spellCheckThisFieldStatus = SpellCheckForcedOn;
179 }
180
181 bool EditorClientImpl::isGrammarCheckingEnabled()
182 {
183     const Frame* frame = m_webView->focusedWebCoreFrame();
184     return frame && frame->settings() && frame->settings()->asynchronousSpellCheckingEnabled();
185 }
186
187 void EditorClientImpl::toggleGrammarChecking()
188 {
189     notImplemented();
190 }
191
192 int EditorClientImpl::spellCheckerDocumentTag()
193 {
194     ASSERT_NOT_REACHED();
195     return 0;
196 }
197
198 bool EditorClientImpl::shouldBeginEditing(Range* range)
199 {
200     if (m_webView->client())
201         return m_webView->client()->shouldBeginEditing(WebRange(range));
202     return true;
203 }
204
205 bool EditorClientImpl::shouldEndEditing(Range* range)
206 {
207     if (m_webView->client())
208         return m_webView->client()->shouldEndEditing(WebRange(range));
209     return true;
210 }
211
212 bool EditorClientImpl::shouldInsertNode(Node* node,
213                                         Range* range,
214                                         EditorInsertAction action)
215 {
216     if (m_webView->client()) {
217         return m_webView->client()->shouldInsertNode(WebNode(node),
218                                                      WebRange(range),
219                                                      static_cast<WebEditingAction>(action));
220     }
221     return true;
222 }
223
224 bool EditorClientImpl::shouldInsertText(const String& text,
225                                         Range* range,
226                                         EditorInsertAction action)
227 {
228     if (m_webView->client()) {
229         return m_webView->client()->shouldInsertText(WebString(text),
230                                                      WebRange(range),
231                                                      static_cast<WebEditingAction>(action));
232     }
233     return true;
234 }
235
236
237 bool EditorClientImpl::shouldDeleteRange(Range* range)
238 {
239     if (m_webView->client())
240         return m_webView->client()->shouldDeleteRange(WebRange(range));
241     return true;
242 }
243
244 bool EditorClientImpl::shouldChangeSelectedRange(Range* fromRange,
245                                                  Range* toRange,
246                                                  EAffinity affinity,
247                                                  bool stillSelecting)
248 {
249     if (m_webView->client()) {
250         return m_webView->client()->shouldChangeSelectedRange(WebRange(fromRange),
251                                                               WebRange(toRange),
252                                                               static_cast<WebTextAffinity>(affinity),
253                                                               stillSelecting);
254     }
255     return true;
256 }
257
258 bool EditorClientImpl::shouldApplyStyle(StylePropertySet* style, Range* range)
259 {
260     if (m_webView->client()) {
261         // FIXME: Pass a reference to the CSSStyleDeclaration somehow.
262         return m_webView->client()->shouldApplyStyle(WebString(), WebRange(range));
263     }
264     return true;
265 }
266
267 bool EditorClientImpl::shouldMoveRangeAfterDelete(Range* range,
268                                                   Range* rangeToBeReplaced)
269 {
270     return true;
271 }
272
273 void EditorClientImpl::didBeginEditing()
274 {
275     if (m_webView->client())
276         m_webView->client()->didBeginEditing();
277 }
278
279 void EditorClientImpl::respondToChangedSelection(Frame* frame)
280 {
281     if (m_webView->client()) {
282         if (frame)
283             m_webView->client()->didChangeSelection(!frame->selection()->isRange());
284     }
285 }
286
287 void EditorClientImpl::respondToChangedContents()
288 {
289     if (m_webView->client())
290         m_webView->client()->didChangeContents();
291 }
292
293 void EditorClientImpl::didEndEditing()
294 {
295     if (m_webView->client())
296         m_webView->client()->didEndEditing();
297 }
298
299 void EditorClientImpl::didWriteSelectionToPasteboard()
300 {
301 }
302
303 void EditorClientImpl::didSetSelectionTypesForPasteboard()
304 {
305 }
306
307 void EditorClientImpl::registerUndoStep(PassRefPtr<UndoStep> step)
308 {
309     if (m_undoStack.size() == maximumUndoStackDepth)
310         m_undoStack.removeFirst(); // drop oldest item off the far end
311     if (!m_inRedo)
312         m_redoStack.clear();
313     m_undoStack.append(step);
314 }
315
316 void EditorClientImpl::registerRedoStep(PassRefPtr<UndoStep> step)
317 {
318     m_redoStack.append(step);
319 }
320
321 void EditorClientImpl::clearUndoRedoOperations()
322 {
323     m_undoStack.clear();
324     m_redoStack.clear();
325 }
326
327 bool EditorClientImpl::canCopyCut(Frame* frame, bool defaultValue) const
328 {
329     if (!m_webView->permissionClient())
330         return defaultValue;
331     return m_webView->permissionClient()->allowWriteToClipboard(WebFrameImpl::fromFrame(frame), defaultValue);
332 }
333
334 bool EditorClientImpl::canPaste(Frame* frame, bool defaultValue) const
335 {
336     if (!m_webView->permissionClient())
337         return defaultValue;
338     return m_webView->permissionClient()->allowReadFromClipboard(WebFrameImpl::fromFrame(frame), defaultValue);
339 }
340
341 bool EditorClientImpl::canUndo() const
342 {
343     return !m_undoStack.isEmpty();
344 }
345
346 bool EditorClientImpl::canRedo() const
347 {
348     return !m_redoStack.isEmpty();
349 }
350
351 void EditorClientImpl::undo()
352 {
353     if (canUndo()) {
354         UndoManagerStack::iterator back = --m_undoStack.end();
355         RefPtr<UndoStep> step(*back);
356         m_undoStack.remove(back);
357         step->unapply();
358         // unapply will call us back to push this command onto the redo stack.
359     }
360 }
361
362 void EditorClientImpl::redo()
363 {
364     if (canRedo()) {
365         UndoManagerStack::iterator back = --m_redoStack.end();
366         RefPtr<UndoStep> step(*back);
367         m_redoStack.remove(back);
368
369         ASSERT(!m_inRedo);
370         m_inRedo = true;
371         step->reapply();
372         // reapply will call us back to push this command onto the undo stack.
373         m_inRedo = false;
374     }
375 }
376
377 //
378 // The below code was adapted from the WebKit file webview.cpp
379 //
380
381 static const unsigned CtrlKey = 1 << 0;
382 static const unsigned AltKey = 1 << 1;
383 static const unsigned ShiftKey = 1 << 2;
384 static const unsigned MetaKey = 1 << 3;
385 #if OS(DARWIN)
386 // Aliases for the generic key defintions to make kbd shortcuts definitions more
387 // readable on OS X.
388 static const unsigned OptionKey  = AltKey;
389
390 // Do not use this constant for anything but cursor movement commands. Keys
391 // with cmd set have their |isSystemKey| bit set, so chances are the shortcut
392 // will not be executed. Another, less important, reason is that shortcuts
393 // defined in the renderer do not blink the menu item that they triggered.  See
394 // http://crbug.com/25856 and the bugs linked from there for details.
395 static const unsigned CommandKey = MetaKey;
396 #endif
397
398 // Keys with special meaning. These will be delegated to the editor using
399 // the execCommand() method
400 struct KeyDownEntry {
401     unsigned virtualKey;
402     unsigned modifiers;
403     const char* name;
404 };
405
406 struct KeyPressEntry {
407     unsigned charCode;
408     unsigned modifiers;
409     const char* name;
410 };
411
412 static const KeyDownEntry keyDownEntries[] = {
413     { VKEY_LEFT,   0,                  "MoveLeft"                             },
414     { VKEY_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"           },
415 #if OS(DARWIN)
416     { VKEY_LEFT,   OptionKey,          "MoveWordLeft"                         },
417     { VKEY_LEFT,   OptionKey | ShiftKey,
418         "MoveWordLeftAndModifySelection"                                      },
419 #else
420     { VKEY_LEFT,   CtrlKey,            "MoveWordLeft"                         },
421     { VKEY_LEFT,   CtrlKey | ShiftKey,
422         "MoveWordLeftAndModifySelection"                                      },
423 #endif
424     { VKEY_RIGHT,  0,                  "MoveRight"                            },
425     { VKEY_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"          },
426 #if OS(DARWIN)
427     { VKEY_RIGHT,  OptionKey,          "MoveWordRight"                        },
428     { VKEY_RIGHT,  OptionKey | ShiftKey,
429       "MoveWordRightAndModifySelection"                                       },
430 #else
431     { VKEY_RIGHT,  CtrlKey,            "MoveWordRight"                        },
432     { VKEY_RIGHT,  CtrlKey | ShiftKey,
433       "MoveWordRightAndModifySelection"                                       },
434 #endif
435     { VKEY_UP,     0,                  "MoveUp"                               },
436     { VKEY_UP,     ShiftKey,           "MoveUpAndModifySelection"             },
437     { VKEY_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"         },
438     { VKEY_DOWN,   0,                  "MoveDown"                             },
439     { VKEY_DOWN,   ShiftKey,           "MoveDownAndModifySelection"           },
440     { VKEY_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"       },
441 #if !OS(DARWIN)
442     { VKEY_PRIOR,  0,                  "MovePageUp"                           },
443     { VKEY_NEXT,   0,                  "MovePageDown"                         },
444 #endif
445     { VKEY_HOME,   0,                  "MoveToBeginningOfLine"                },
446     { VKEY_HOME,   ShiftKey,
447         "MoveToBeginningOfLineAndModifySelection"                             },
448 #if OS(DARWIN)
449     { VKEY_LEFT,   CommandKey,         "MoveToBeginningOfLine"                },
450     { VKEY_LEFT,   CommandKey | ShiftKey,
451       "MoveToBeginningOfLineAndModifySelection"                               },
452     { VKEY_PRIOR,  OptionKey,          "MovePageUp"                           },
453     { VKEY_NEXT,   OptionKey,          "MovePageDown"                         },
454 #endif
455 #if OS(DARWIN)
456     { VKEY_UP,     CommandKey,         "MoveToBeginningOfDocument"            },
457     { VKEY_UP,     CommandKey | ShiftKey,
458         "MoveToBeginningOfDocumentAndModifySelection"                         },
459 #else
460     { VKEY_HOME,   CtrlKey,            "MoveToBeginningOfDocument"            },
461     { VKEY_HOME,   CtrlKey | ShiftKey,
462         "MoveToBeginningOfDocumentAndModifySelection"                         },
463 #endif
464     { VKEY_END,    0,                  "MoveToEndOfLine"                      },
465     { VKEY_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"    },
466 #if OS(DARWIN)
467     { VKEY_DOWN,   CommandKey,         "MoveToEndOfDocument"                  },
468     { VKEY_DOWN,   CommandKey | ShiftKey,
469         "MoveToEndOfDocumentAndModifySelection"                               },
470 #else
471     { VKEY_END,    CtrlKey,            "MoveToEndOfDocument"                  },
472     { VKEY_END,    CtrlKey | ShiftKey,
473         "MoveToEndOfDocumentAndModifySelection"                               },
474 #endif
475 #if OS(DARWIN)
476     { VKEY_RIGHT,  CommandKey,         "MoveToEndOfLine"                      },
477     { VKEY_RIGHT,  CommandKey | ShiftKey,
478         "MoveToEndOfLineAndModifySelection"                                   },
479 #endif
480     { VKEY_BACK,   0,                  "DeleteBackward"                       },
481     { VKEY_BACK,   ShiftKey,           "DeleteBackward"                       },
482     { VKEY_DELETE, 0,                  "DeleteForward"                        },
483 #if OS(DARWIN)
484     { VKEY_BACK,   OptionKey,          "DeleteWordBackward"                   },
485     { VKEY_DELETE, OptionKey,          "DeleteWordForward"                    },
486 #else
487     { VKEY_BACK,   CtrlKey,            "DeleteWordBackward"                   },
488     { VKEY_DELETE, CtrlKey,            "DeleteWordForward"                    },
489 #endif
490     { 'B',         CtrlKey,            "ToggleBold"                           },
491     { 'I',         CtrlKey,            "ToggleItalic"                         },
492     { 'U',         CtrlKey,            "ToggleUnderline"                      },
493     { VKEY_ESCAPE, 0,                  "Cancel"                               },
494     { VKEY_OEM_PERIOD, CtrlKey,        "Cancel"                               },
495     { VKEY_TAB,    0,                  "InsertTab"                            },
496     { VKEY_TAB,    ShiftKey,           "InsertBacktab"                        },
497     { VKEY_RETURN, 0,                  "InsertNewline"                        },
498     { VKEY_RETURN, CtrlKey,            "InsertNewline"                        },
499     { VKEY_RETURN, AltKey,             "InsertNewline"                        },
500     { VKEY_RETURN, AltKey | ShiftKey,  "InsertNewline"                        },
501     { VKEY_RETURN, ShiftKey,           "InsertLineBreak"                      },
502     { VKEY_INSERT, CtrlKey,            "Copy"                                 },
503     { VKEY_INSERT, ShiftKey,           "Paste"                                },
504     { VKEY_DELETE, ShiftKey,           "Cut"                                  },
505 #if !OS(DARWIN)
506     // On OS X, we pipe these back to the browser, so that it can do menu item
507     // blinking.
508     { 'C',         CtrlKey,            "Copy"                                 },
509     { 'V',         CtrlKey,            "Paste"                                },
510     { 'V',         CtrlKey | ShiftKey, "PasteAndMatchStyle"                   },
511     { 'X',         CtrlKey,            "Cut"                                  },
512     { 'A',         CtrlKey,            "SelectAll"                            },
513     { 'Z',         CtrlKey,            "Undo"                                 },
514     { 'Z',         CtrlKey | ShiftKey, "Redo"                                 },
515     { 'Y',         CtrlKey,            "Redo"                                 },
516 #endif
517 };
518
519 static const KeyPressEntry keyPressEntries[] = {
520     { '\t',   0,                  "InsertTab"                                 },
521     { '\t',   ShiftKey,           "InsertBacktab"                             },
522     { '\r',   0,                  "InsertNewline"                             },
523     { '\r',   CtrlKey,            "InsertNewline"                             },
524     { '\r',   ShiftKey,           "InsertLineBreak"                           },
525     { '\r',   AltKey,             "InsertNewline"                             },
526     { '\r',   AltKey | ShiftKey,  "InsertNewline"                             },
527 };
528
529 const char* EditorClientImpl::interpretKeyEvent(const KeyboardEvent* evt)
530 {
531     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
532     if (!keyEvent)
533         return "";
534
535     static HashMap<int, const char*>* keyDownCommandsMap = 0;
536     static HashMap<int, const char*>* keyPressCommandsMap = 0;
537
538     if (!keyDownCommandsMap) {
539         keyDownCommandsMap = new HashMap<int, const char*>;
540         keyPressCommandsMap = new HashMap<int, const char*>;
541
542         for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
543             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey,
544                                     keyDownEntries[i].name);
545         }
546
547         for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
548             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode,
549                                      keyPressEntries[i].name);
550         }
551     }
552
553     unsigned modifiers = 0;
554     if (keyEvent->shiftKey())
555         modifiers |= ShiftKey;
556     if (keyEvent->altKey())
557         modifiers |= AltKey;
558     if (keyEvent->ctrlKey())
559         modifiers |= CtrlKey;
560     if (keyEvent->metaKey())
561         modifiers |= MetaKey;
562
563     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
564         int mapKey = modifiers << 16 | evt->keyCode();
565         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
566     }
567
568     int mapKey = modifiers << 16 | evt->charCode();
569     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
570 }
571
572 bool EditorClientImpl::handleEditingKeyboardEvent(KeyboardEvent* evt)
573 {
574     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
575     // do not treat this as text input if it's a system key event
576     if (!keyEvent || keyEvent->isSystemKey())
577         return false;
578
579     Frame* frame = evt->target()->toNode()->document()->frame();
580     if (!frame)
581         return false;
582
583     String commandName = interpretKeyEvent(evt);
584     Editor::Command command = frame->editor()->command(commandName);
585
586     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
587         // WebKit doesn't have enough information about mode to decide how
588         // commands that just insert text if executed via Editor should be treated,
589         // so we leave it upon WebCore to either handle them immediately
590         // (e.g. Tab that changes focus) or let a keypress event be generated
591         // (e.g. Tab that inserts a Tab character, or Enter).
592         if (command.isTextInsertion() || commandName.isEmpty())
593             return false;
594         if (command.execute(evt)) {
595             if (m_webView->client())
596                 m_webView->client()->didExecuteCommand(WebString(commandName));
597             return true;
598         }
599         return false;
600     }
601
602     if (command.execute(evt)) {
603         if (m_webView->client())
604             m_webView->client()->didExecuteCommand(WebString(commandName));
605         return true;
606     }
607
608     // Here we need to filter key events.
609     // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
610     // In Webkit, EditorClient::handleKeyboardEvent in
611     // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
612     // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
613     // These key events should not emit text insert event.
614     // Alt key would be used to insert alternative character, so we should let
615     // through. Also note that Ctrl-Alt combination equals to AltGr key which is
616     // also used to insert alternative character.
617     // http://code.google.com/p/chromium/issues/detail?id=10846
618     // Windows sets both alt and meta are on when "Alt" key pressed.
619     // http://code.google.com/p/chromium/issues/detail?id=2215
620     // Also, we should not rely on an assumption that keyboards don't
621     // send ASCII characters when pressing a control key on Windows,
622     // which may be configured to do it so by user.
623     // See also http://en.wikipedia.org/wiki/Keyboard_Layout
624     // FIXME(ukai): investigate more detail for various keyboard layout.
625     if (evt->keyEvent()->text().length() == 1) {
626         UChar ch = evt->keyEvent()->text()[0U];
627
628         // Don't insert null or control characters as they can result in
629         // unexpected behaviour
630         if (ch < ' ')
631             return false;
632 #if !OS(WINDOWS)
633         // Don't insert ASCII character if ctrl w/o alt or meta is on.
634         // On Mac, we should ignore events when meta is on (Command-<x>).
635         if (ch < 0x80) {
636             if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
637                 return false;
638 #if OS(DARWIN)
639             if (evt->keyEvent()->metaKey())
640             return false;
641 #endif
642         }
643 #endif
644     }
645
646     if (!frame->editor()->canEdit())
647         return false;
648
649     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
650 }
651
652 void EditorClientImpl::handleKeyboardEvent(KeyboardEvent* evt)
653 {
654     // Give the embedder a chance to handle the keyboard event.
655     if ((m_webView->client()
656          && m_webView->client()->handleCurrentKeyboardEvent())
657         || handleEditingKeyboardEvent(evt))
658         evt->setDefaultHandled();
659 }
660
661 void EditorClientImpl::handleInputMethodKeydown(KeyboardEvent* keyEvent)
662 {
663     // We handle IME within chrome.
664 }
665
666 void EditorClientImpl::textFieldDidBeginEditing(Element* element)
667 {
668 }
669
670 void EditorClientImpl::textFieldDidEndEditing(Element* element)
671 {
672     HTMLInputElement* inputElement = toHTMLInputElement(element);
673     if (m_webView->autofillClient() && inputElement)
674         m_webView->autofillClient()->textFieldDidEndEditing(WebInputElement(inputElement));
675
676     // Notification that focus was lost.  Be careful with this, it's also sent
677     // when the page is being closed.
678
679     // Hide any showing popup.
680     m_webView->hideAutofillPopup();
681 }
682
683 void EditorClientImpl::textDidChangeInTextField(Element* element)
684 {
685     ASSERT(element->hasLocalName(HTMLNames::inputTag));
686     HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(element);
687     if (m_webView->autofillClient())
688         m_webView->autofillClient()->textFieldDidChange(WebInputElement(inputElement));
689 }
690
691 bool EditorClientImpl::doTextFieldCommandFromEvent(Element* element,
692                                                    KeyboardEvent* event)
693 {
694     HTMLInputElement* inputElement = toHTMLInputElement(element);
695     if (m_webView->autofillClient() && inputElement) {
696         m_webView->autofillClient()->textFieldDidReceiveKeyDown(WebInputElement(inputElement),
697                                                                 WebKeyboardEventBuilder(*event));
698     }
699
700     // The Mac code appears to use this method as a hook to implement special
701     // keyboard commands specific to Safari's auto-fill implementation.  We
702     // just return false to allow the default action.
703     return false;
704 }
705
706 void EditorClientImpl::textWillBeDeletedInTextField(Element*)
707 {
708 }
709
710 void EditorClientImpl::textDidChangeInTextArea(Element*)
711 {
712 }
713
714 bool EditorClientImpl::shouldEraseMarkersAfterChangeSelection(TextCheckingType type) const
715 {
716     const Frame* frame = m_webView->focusedWebCoreFrame();
717     return !frame || !frame->settings() || !frame->settings()->asynchronousSpellCheckingEnabled();
718 }
719
720 void EditorClientImpl::ignoreWordInSpellDocument(const String&)
721 {
722     notImplemented();
723 }
724
725 void EditorClientImpl::learnWord(const String&)
726 {
727     notImplemented();
728 }
729
730 void EditorClientImpl::checkSpellingOfString(const UChar* text, int length,
731                                              int* misspellingLocation,
732                                              int* misspellingLength)
733 {
734     // SpellCheckWord will write (0, 0) into the output vars, which is what our
735     // caller expects if the word is spelled correctly.
736     int spellLocation = -1;
737     int spellLength = 0;
738
739     // Check to see if the provided text is spelled correctly.
740     if (isContinuousSpellCheckingEnabled() && m_webView->spellCheckClient())
741         m_webView->spellCheckClient()->spellCheck(WebString(text, length), spellLocation, spellLength, 0);
742     else {
743         spellLocation = 0;
744         spellLength = 0;
745     }
746
747     // Note: the Mac code checks if the pointers are null before writing to them,
748     // so we do too.
749     if (misspellingLocation)
750         *misspellingLocation = spellLocation;
751     if (misspellingLength)
752         *misspellingLength = spellLength;
753 }
754
755 void EditorClientImpl::requestCheckingOfString(SpellChecker* sender, const WebCore::TextCheckingRequest& request)
756 {
757     if (!m_webView->spellCheckClient())
758         return;
759
760     WebTextCheckingCompletionImpl* completion = new WebTextCheckingCompletionImpl(request.sequence(), sender, this);
761     m_pendingTextChecks.add(completion);
762     m_webView->spellCheckClient()->requestCheckingOfText(request.text(), completion);
763 }
764
765 void EditorClientImpl::didCheckString(WebTextCheckingCompletionImpl* completion)
766 {
767     m_pendingTextChecks.remove(completion);
768 }
769
770 String EditorClientImpl::getAutoCorrectSuggestionForMisspelledWord(const String& misspelledWord)
771 {
772     if (!(isContinuousSpellCheckingEnabled() && m_webView->client()))
773         return String();
774
775     // Do not autocorrect words with capital letters in it except the
776     // first letter. This will remove cases changing "IMB" to "IBM".
777     for (size_t i = 1; i < misspelledWord.length(); i++) {
778         if (u_isupper(static_cast<UChar32>(misspelledWord[i])))
779             return String();
780     }
781
782     if (m_webView->spellCheckClient())
783         return m_webView->spellCheckClient()->autoCorrectWord(WebString(misspelledWord));
784     return String();
785 }
786
787 void EditorClientImpl::checkGrammarOfString(const UChar*, int length,
788                                             WTF::Vector<GrammarDetail>&,
789                                             int* badGrammarLocation,
790                                             int* badGrammarLength)
791 {
792     notImplemented();
793     if (badGrammarLocation)
794         *badGrammarLocation = -1;
795     if (badGrammarLength)
796         *badGrammarLength = 0;
797 }
798
799 void EditorClientImpl::checkTextOfParagraph(const UChar* text, int length,
800                                             TextCheckingTypeMask mask,
801                                             WTF::Vector<TextCheckingResult>& results)
802 {
803     if (!m_webView->spellCheckClient())
804         return;
805
806     WebTextCheckingTypeMask webMask = static_cast<WebTextCheckingTypeMask>(mask);
807     WebVector<WebTextCheckingResult> webResults;
808     m_webView->spellCheckClient()->checkTextOfParagraph(WebString(text, length), webMask, &webResults);
809
810     results.resize(webResults.size());
811     for (size_t i = 0; i < webResults.size(); ++i)
812         results[i] = webResults[i];
813 }
814
815 void EditorClientImpl::updateSpellingUIWithGrammarString(const String&,
816                                                          const GrammarDetail& detail)
817 {
818     notImplemented();
819 }
820
821 void EditorClientImpl::updateSpellingUIWithMisspelledWord(const String& misspelledWord)
822 {
823     if (m_webView->spellCheckClient())
824         m_webView->spellCheckClient()->updateSpellingUIWithMisspelledWord(WebString(misspelledWord));
825 }
826
827 void EditorClientImpl::showSpellingUI(bool show)
828 {
829     if (m_webView->spellCheckClient())
830         m_webView->spellCheckClient()->showSpellingUI(show);
831 }
832
833 bool EditorClientImpl::spellingUIIsShowing()
834 {
835     if (m_webView->spellCheckClient())
836         return m_webView->spellCheckClient()->isShowingSpellingUI();
837     return false;
838 }
839
840 void EditorClientImpl::getGuessesForWord(const String& word,
841                                          const String& context,
842                                          WTF::Vector<String>& guesses)
843 {
844     notImplemented();
845 }
846
847 void EditorClientImpl::willSetInputMethodState()
848 {
849     if (m_webView->client())
850         m_webView->client()->resetInputMethod();
851 }
852
853 void EditorClientImpl::setInputMethodState(bool)
854 {
855 }
856
857 } // namesace WebKit