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