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