initial import
[vuplus_webkit] / 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 "EditCommand.h"
32 #include "Editor.h"
33 #include "EventHandler.h"
34 #include "EventNames.h"
35 #include "Frame.h"
36 #include "HTMLInputElement.h"
37 #include "HTMLNames.h"
38 #include "KeyboardCodes.h"
39 #include "KeyboardEvent.h"
40 #include "PlatformKeyboardEvent.h"
41 #include "PlatformString.h"
42 #include "RenderObject.h"
43 #include "SpellChecker.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()
264 {
265     if (m_webView->client()) {
266         Frame* frame = m_webView->focusedWebCoreFrame();
267         if (frame)
268             m_webView->client()->didChangeSelection(!frame->selection()->isRange());
269     }
270 }
271
272 void EditorClientImpl::respondToChangedContents()
273 {
274     if (m_webView->client())
275         m_webView->client()->didChangeContents();
276 }
277
278 void EditorClientImpl::didEndEditing()
279 {
280     if (m_webView->client())
281         m_webView->client()->didEndEditing();
282 }
283
284 void EditorClientImpl::didWriteSelectionToPasteboard()
285 {
286 }
287
288 void EditorClientImpl::didSetSelectionTypesForPasteboard()
289 {
290 }
291
292 void EditorClientImpl::registerCommandForUndo(PassRefPtr<EditCommand> command)
293 {
294     if (m_undoStack.size() == maximumUndoStackDepth)
295         m_undoStack.removeFirst(); // drop oldest item off the far end
296     if (!m_inRedo)
297         m_redoStack.clear();
298     m_undoStack.append(command);
299 }
300
301 void EditorClientImpl::registerCommandForRedo(PassRefPtr<EditCommand> command)
302 {
303     m_redoStack.append(command);
304 }
305
306 void EditorClientImpl::clearUndoRedoOperations()
307 {
308     m_undoStack.clear();
309     m_redoStack.clear();
310 }
311
312 bool EditorClientImpl::canCopyCut(Frame* frame, bool defaultValue) const
313 {
314     if (!m_webView->permissionClient())
315         return defaultValue;
316     return m_webView->permissionClient()->allowWriteToClipboard(WebFrameImpl::fromFrame(frame), defaultValue);
317 }
318
319 bool EditorClientImpl::canPaste(Frame* frame, bool defaultValue) const
320 {
321     if (!m_webView->permissionClient())
322         return defaultValue;
323     return m_webView->permissionClient()->allowReadFromClipboard(WebFrameImpl::fromFrame(frame), defaultValue);
324 }
325
326 bool EditorClientImpl::canUndo() const
327 {
328     return !m_undoStack.isEmpty();
329 }
330
331 bool EditorClientImpl::canRedo() const
332 {
333     return !m_redoStack.isEmpty();
334 }
335
336 void EditorClientImpl::undo()
337 {
338     if (canUndo()) {
339         EditCommandStack::iterator back = --m_undoStack.end();
340         RefPtr<EditCommand> command(*back);
341         m_undoStack.remove(back);
342         command->unapply();
343         // unapply will call us back to push this command onto the redo stack.
344     }
345 }
346
347 void EditorClientImpl::redo()
348 {
349     if (canRedo()) {
350         EditCommandStack::iterator back = --m_redoStack.end();
351         RefPtr<EditCommand> command(*back);
352         m_redoStack.remove(back);
353
354         ASSERT(!m_inRedo);
355         m_inRedo = true;
356         command->reapply();
357         // reapply will call us back to push this command onto the undo stack.
358         m_inRedo = false;
359     }
360 }
361
362 //
363 // The below code was adapted from the WebKit file webview.cpp
364 //
365
366 static const unsigned CtrlKey = 1 << 0;
367 static const unsigned AltKey = 1 << 1;
368 static const unsigned ShiftKey = 1 << 2;
369 static const unsigned MetaKey = 1 << 3;
370 #if OS(DARWIN)
371 // Aliases for the generic key defintions to make kbd shortcuts definitions more
372 // readable on OS X.
373 static const unsigned OptionKey  = AltKey;
374
375 // Do not use this constant for anything but cursor movement commands. Keys
376 // with cmd set have their |isSystemKey| bit set, so chances are the shortcut
377 // will not be executed. Another, less important, reason is that shortcuts
378 // defined in the renderer do not blink the menu item that they triggered.  See
379 // http://crbug.com/25856 and the bugs linked from there for details.
380 static const unsigned CommandKey = MetaKey;
381 #endif
382
383 // Keys with special meaning. These will be delegated to the editor using
384 // the execCommand() method
385 struct KeyDownEntry {
386     unsigned virtualKey;
387     unsigned modifiers;
388     const char* name;
389 };
390
391 struct KeyPressEntry {
392     unsigned charCode;
393     unsigned modifiers;
394     const char* name;
395 };
396
397 static const KeyDownEntry keyDownEntries[] = {
398     { VKEY_LEFT,   0,                  "MoveLeft"                             },
399     { VKEY_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"           },
400 #if OS(DARWIN)
401     { VKEY_LEFT,   OptionKey,          "MoveWordLeft"                         },
402     { VKEY_LEFT,   OptionKey | ShiftKey,
403         "MoveWordLeftAndModifySelection"                                      },
404 #else
405     { VKEY_LEFT,   CtrlKey,            "MoveWordLeft"                         },
406     { VKEY_LEFT,   CtrlKey | ShiftKey,
407         "MoveWordLeftAndModifySelection"                                      },
408 #endif
409     { VKEY_RIGHT,  0,                  "MoveRight"                            },
410     { VKEY_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"          },
411 #if OS(DARWIN)
412     { VKEY_RIGHT,  OptionKey,          "MoveWordRight"                        },
413     { VKEY_RIGHT,  OptionKey | ShiftKey,
414       "MoveWordRightAndModifySelection"                                       },
415 #else
416     { VKEY_RIGHT,  CtrlKey,            "MoveWordRight"                        },
417     { VKEY_RIGHT,  CtrlKey | ShiftKey,
418       "MoveWordRightAndModifySelection"                                       },
419 #endif
420     { VKEY_UP,     0,                  "MoveUp"                               },
421     { VKEY_UP,     ShiftKey,           "MoveUpAndModifySelection"             },
422     { VKEY_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"         },
423     { VKEY_DOWN,   0,                  "MoveDown"                             },
424     { VKEY_DOWN,   ShiftKey,           "MoveDownAndModifySelection"           },
425     { VKEY_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"       },
426 #if !OS(DARWIN)
427     { VKEY_PRIOR,  0,                  "MovePageUp"                           },
428     { VKEY_NEXT,   0,                  "MovePageDown"                         },
429 #endif
430     { VKEY_HOME,   0,                  "MoveToBeginningOfLine"                },
431     { VKEY_HOME,   ShiftKey,
432         "MoveToBeginningOfLineAndModifySelection"                             },
433 #if OS(DARWIN)
434     { VKEY_LEFT,   CommandKey,         "MoveToBeginningOfLine"                },
435     { VKEY_LEFT,   CommandKey | ShiftKey,
436       "MoveToBeginningOfLineAndModifySelection"                               },
437     { VKEY_PRIOR,  OptionKey,          "MovePageUp"                           },
438     { VKEY_NEXT,   OptionKey,          "MovePageDown"                         },
439 #endif
440 #if OS(DARWIN)
441     { VKEY_UP,     CommandKey,         "MoveToBeginningOfDocument"            },
442     { VKEY_UP,     CommandKey | ShiftKey,
443         "MoveToBeginningOfDocumentAndModifySelection"                         },
444 #else
445     { VKEY_HOME,   CtrlKey,            "MoveToBeginningOfDocument"            },
446     { VKEY_HOME,   CtrlKey | ShiftKey,
447         "MoveToBeginningOfDocumentAndModifySelection"                         },
448 #endif
449     { VKEY_END,    0,                  "MoveToEndOfLine"                      },
450     { VKEY_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"    },
451 #if OS(DARWIN)
452     { VKEY_DOWN,   CommandKey,         "MoveToEndOfDocument"                  },
453     { VKEY_DOWN,   CommandKey | ShiftKey,
454         "MoveToEndOfDocumentAndModifySelection"                               },
455 #else
456     { VKEY_END,    CtrlKey,            "MoveToEndOfDocument"                  },
457     { VKEY_END,    CtrlKey | ShiftKey,
458         "MoveToEndOfDocumentAndModifySelection"                               },
459 #endif
460 #if OS(DARWIN)
461     { VKEY_RIGHT,  CommandKey,         "MoveToEndOfLine"                      },
462     { VKEY_RIGHT,  CommandKey | ShiftKey,
463         "MoveToEndOfLineAndModifySelection"                                   },
464 #endif
465     { VKEY_BACK,   0,                  "DeleteBackward"                       },
466     { VKEY_BACK,   ShiftKey,           "DeleteBackward"                       },
467     { VKEY_DELETE, 0,                  "DeleteForward"                        },
468 #if OS(DARWIN)
469     { VKEY_BACK,   OptionKey,          "DeleteWordBackward"                   },
470     { VKEY_DELETE, OptionKey,          "DeleteWordForward"                    },
471 #else
472     { VKEY_BACK,   CtrlKey,            "DeleteWordBackward"                   },
473     { VKEY_DELETE, CtrlKey,            "DeleteWordForward"                    },
474 #endif
475     { 'B',         CtrlKey,            "ToggleBold"                           },
476     { 'I',         CtrlKey,            "ToggleItalic"                         },
477     { 'U',         CtrlKey,            "ToggleUnderline"                      },
478     { VKEY_ESCAPE, 0,                  "Cancel"                               },
479     { VKEY_OEM_PERIOD, CtrlKey,        "Cancel"                               },
480     { VKEY_TAB,    0,                  "InsertTab"                            },
481     { VKEY_TAB,    ShiftKey,           "InsertBacktab"                        },
482     { VKEY_RETURN, 0,                  "InsertNewline"                        },
483     { VKEY_RETURN, CtrlKey,            "InsertNewline"                        },
484     { VKEY_RETURN, AltKey,             "InsertNewline"                        },
485     { VKEY_RETURN, AltKey | ShiftKey,  "InsertNewline"                        },
486     { VKEY_RETURN, ShiftKey,           "InsertLineBreak"                      },
487     { VKEY_INSERT, CtrlKey,            "Copy"                                 },
488     { VKEY_INSERT, ShiftKey,           "Paste"                                },
489     { VKEY_DELETE, ShiftKey,           "Cut"                                  },
490 #if !OS(DARWIN)
491     // On OS X, we pipe these back to the browser, so that it can do menu item
492     // blinking.
493     { 'C',         CtrlKey,            "Copy"                                 },
494     { 'V',         CtrlKey,            "Paste"                                },
495     { 'V',         CtrlKey | ShiftKey, "PasteAndMatchStyle"                   },
496     { 'X',         CtrlKey,            "Cut"                                  },
497     { 'A',         CtrlKey,            "SelectAll"                            },
498     { 'Z',         CtrlKey,            "Undo"                                 },
499     { 'Z',         CtrlKey | ShiftKey, "Redo"                                 },
500     { 'Y',         CtrlKey,            "Redo"                                 },
501 #endif
502 };
503
504 static const KeyPressEntry keyPressEntries[] = {
505     { '\t',   0,                  "InsertTab"                                 },
506     { '\t',   ShiftKey,           "InsertBacktab"                             },
507     { '\r',   0,                  "InsertNewline"                             },
508     { '\r',   CtrlKey,            "InsertNewline"                             },
509     { '\r',   ShiftKey,           "InsertLineBreak"                           },
510     { '\r',   AltKey,             "InsertNewline"                             },
511     { '\r',   AltKey | ShiftKey,  "InsertNewline"                             },
512 };
513
514 const char* EditorClientImpl::interpretKeyEvent(const KeyboardEvent* evt)
515 {
516     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
517     if (!keyEvent)
518         return "";
519
520     static HashMap<int, const char*>* keyDownCommandsMap = 0;
521     static HashMap<int, const char*>* keyPressCommandsMap = 0;
522
523     if (!keyDownCommandsMap) {
524         keyDownCommandsMap = new HashMap<int, const char*>;
525         keyPressCommandsMap = new HashMap<int, const char*>;
526
527         for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
528             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey,
529                                     keyDownEntries[i].name);
530         }
531
532         for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
533             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode,
534                                      keyPressEntries[i].name);
535         }
536     }
537
538     unsigned modifiers = 0;
539     if (keyEvent->shiftKey())
540         modifiers |= ShiftKey;
541     if (keyEvent->altKey())
542         modifiers |= AltKey;
543     if (keyEvent->ctrlKey())
544         modifiers |= CtrlKey;
545     if (keyEvent->metaKey())
546         modifiers |= MetaKey;
547
548     if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
549         int mapKey = modifiers << 16 | evt->keyCode();
550         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
551     }
552
553     int mapKey = modifiers << 16 | evt->charCode();
554     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
555 }
556
557 bool EditorClientImpl::handleEditingKeyboardEvent(KeyboardEvent* evt)
558 {
559     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
560     // do not treat this as text input if it's a system key event
561     if (!keyEvent || keyEvent->isSystemKey())
562         return false;
563
564     Frame* frame = evt->target()->toNode()->document()->frame();
565     if (!frame)
566         return false;
567
568     String commandName = interpretKeyEvent(evt);
569     Editor::Command command = frame->editor()->command(commandName);
570
571     if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
572         // WebKit doesn't have enough information about mode to decide how
573         // commands that just insert text if executed via Editor should be treated,
574         // so we leave it upon WebCore to either handle them immediately
575         // (e.g. Tab that changes focus) or let a keypress event be generated
576         // (e.g. Tab that inserts a Tab character, or Enter).
577         if (command.isTextInsertion() || commandName.isEmpty())
578             return false;
579         if (command.execute(evt)) {
580             if (m_webView->client())
581                 m_webView->client()->didExecuteCommand(WebString(commandName));
582             return true;
583         }
584         return false;
585     }
586
587     if (command.execute(evt)) {
588         if (m_webView->client())
589             m_webView->client()->didExecuteCommand(WebString(commandName));
590         return true;
591     }
592
593     // Here we need to filter key events.
594     // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
595     // In Webkit, EditorClient::handleKeyboardEvent in
596     // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
597     // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
598     // These key events should not emit text insert event.
599     // Alt key would be used to insert alternative character, so we should let
600     // through. Also note that Ctrl-Alt combination equals to AltGr key which is
601     // also used to insert alternative character.
602     // http://code.google.com/p/chromium/issues/detail?id=10846
603     // Windows sets both alt and meta are on when "Alt" key pressed.
604     // http://code.google.com/p/chromium/issues/detail?id=2215
605     // Also, we should not rely on an assumption that keyboards don't
606     // send ASCII characters when pressing a control key on Windows,
607     // which may be configured to do it so by user.
608     // See also http://en.wikipedia.org/wiki/Keyboard_Layout
609     // FIXME(ukai): investigate more detail for various keyboard layout.
610     if (evt->keyEvent()->text().length() == 1) {
611         UChar ch = evt->keyEvent()->text()[0U];
612
613         // Don't insert null or control characters as they can result in
614         // unexpected behaviour
615         if (ch < ' ')
616             return false;
617 #if !OS(WINDOWS)
618         // Don't insert ASCII character if ctrl w/o alt or meta is on.
619         // On Mac, we should ignore events when meta is on (Command-<x>).
620         if (ch < 0x80) {
621             if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
622                 return false;
623 #if OS(DARWIN)
624             if (evt->keyEvent()->metaKey())
625             return false;
626 #endif
627         }
628 #endif
629     }
630
631     if (!frame->editor()->canEdit())
632         return false;
633
634     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
635 }
636
637 void EditorClientImpl::handleKeyboardEvent(KeyboardEvent* evt)
638 {
639     // Give the embedder a chance to handle the keyboard event.
640     if ((m_webView->client()
641          && m_webView->client()->handleCurrentKeyboardEvent())
642         || handleEditingKeyboardEvent(evt))
643         evt->setDefaultHandled();
644 }
645
646 void EditorClientImpl::handleInputMethodKeydown(KeyboardEvent* keyEvent)
647 {
648     // We handle IME within chrome.
649 }
650
651 void EditorClientImpl::textFieldDidBeginEditing(Element* element)
652 {
653 }
654
655 void EditorClientImpl::textFieldDidEndEditing(Element* element)
656 {
657     HTMLInputElement* inputElement = toHTMLInputElement(element);
658     if (m_webView->autofillClient() && inputElement)
659         m_webView->autofillClient()->textFieldDidEndEditing(WebInputElement(inputElement));
660
661     // Notification that focus was lost.  Be careful with this, it's also sent
662     // when the page is being closed.
663
664     // Hide any showing popup.
665     m_webView->hideAutofillPopup();
666 }
667
668 void EditorClientImpl::textDidChangeInTextField(Element* element)
669 {
670     ASSERT(element->hasLocalName(HTMLNames::inputTag));
671     HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(element);
672     if (m_webView->autofillClient())
673         m_webView->autofillClient()->textFieldDidChange(WebInputElement(inputElement));
674 }
675
676 bool EditorClientImpl::doTextFieldCommandFromEvent(Element* element,
677                                                    KeyboardEvent* event)
678 {
679     HTMLInputElement* inputElement = toHTMLInputElement(element);
680     if (m_webView->autofillClient() && inputElement) {
681         m_webView->autofillClient()->textFieldDidReceiveKeyDown(WebInputElement(inputElement),
682                                                                 WebKeyboardEventBuilder(*event));
683     }
684
685     // The Mac code appears to use this method as a hook to implement special
686     // keyboard commands specific to Safari's auto-fill implementation.  We
687     // just return false to allow the default action.
688     return false;
689 }
690
691 void EditorClientImpl::textWillBeDeletedInTextField(Element*)
692 {
693 }
694
695 void EditorClientImpl::textDidChangeInTextArea(Element*)
696 {
697 }
698
699 void EditorClientImpl::ignoreWordInSpellDocument(const String&)
700 {
701     notImplemented();
702 }
703
704 void EditorClientImpl::learnWord(const String&)
705 {
706     notImplemented();
707 }
708
709 void EditorClientImpl::checkSpellingOfString(const UChar* text, int length,
710                                              int* misspellingLocation,
711                                              int* misspellingLength)
712 {
713     // SpellCheckWord will write (0, 0) into the output vars, which is what our
714     // caller expects if the word is spelled correctly.
715     int spellLocation = -1;
716     int spellLength = 0;
717
718     // Check to see if the provided text is spelled correctly.
719     if (isContinuousSpellCheckingEnabled() && m_webView->spellCheckClient())
720         m_webView->spellCheckClient()->spellCheck(WebString(text, length), spellLocation, spellLength, 0);
721     else {
722         spellLocation = 0;
723         spellLength = 0;
724     }
725
726     // Note: the Mac code checks if the pointers are null before writing to them,
727     // so we do too.
728     if (misspellingLocation)
729         *misspellingLocation = spellLocation;
730     if (misspellingLength)
731         *misspellingLength = spellLength;
732 }
733
734 void EditorClientImpl::requestCheckingOfString(SpellChecker* sender, int identifier, TextCheckingTypeMask, const String& text)
735 {
736     if (m_webView->spellCheckClient())
737         m_webView->spellCheckClient()->requestCheckingOfText(text, new WebTextCheckingCompletionImpl(identifier, sender));
738 }
739
740 String EditorClientImpl::getAutoCorrectSuggestionForMisspelledWord(const String& misspelledWord)
741 {
742     if (!(isContinuousSpellCheckingEnabled() && m_webView->client()))
743         return String();
744
745     // Do not autocorrect words with capital letters in it except the
746     // first letter. This will remove cases changing "IMB" to "IBM".
747     for (size_t i = 1; i < misspelledWord.length(); i++) {
748         if (u_isupper(static_cast<UChar32>(misspelledWord[i])))
749             return String();
750     }
751
752     if (m_webView->spellCheckClient())
753         return m_webView->spellCheckClient()->autoCorrectWord(WebString(misspelledWord));
754     return String();
755 }
756
757 void EditorClientImpl::checkGrammarOfString(const UChar*, int length,
758                                             WTF::Vector<GrammarDetail>&,
759                                             int* badGrammarLocation,
760                                             int* badGrammarLength)
761 {
762     notImplemented();
763     if (badGrammarLocation)
764         *badGrammarLocation = 0;
765     if (badGrammarLength)
766         *badGrammarLength = 0;
767 }
768
769 void EditorClientImpl::updateSpellingUIWithGrammarString(const String&,
770                                                          const GrammarDetail& detail)
771 {
772     notImplemented();
773 }
774
775 void EditorClientImpl::updateSpellingUIWithMisspelledWord(const String& misspelledWord)
776 {
777     if (m_webView->spellCheckClient())
778         m_webView->spellCheckClient()->updateSpellingUIWithMisspelledWord(WebString(misspelledWord));
779 }
780
781 void EditorClientImpl::showSpellingUI(bool show)
782 {
783     if (m_webView->spellCheckClient())
784         m_webView->spellCheckClient()->showSpellingUI(show);
785 }
786
787 bool EditorClientImpl::spellingUIIsShowing()
788 {
789     if (m_webView->spellCheckClient())
790         return m_webView->spellCheckClient()->isShowingSpellingUI();
791     return false;
792 }
793
794 void EditorClientImpl::getGuessesForWord(const String& word,
795                                          const String& context,
796                                          WTF::Vector<String>& guesses)
797 {
798     notImplemented();
799 }
800
801 void EditorClientImpl::willSetInputMethodState()
802 {
803     if (m_webView->client())
804         m_webView->client()->resetInputMethod();
805 }
806
807 void EditorClientImpl::setInputMethodState(bool)
808 {
809 }
810
811 } // namesace WebKit