Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(420)

Side by Side Diff: webkit/api/src/EditorClientImpl.cpp

Issue 330021: Move glue/EditorClientImpl.h/cpp to webkit/api/src (Closed)
Patch Set: Patch 5 Created 11 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « webkit/api/src/EditorClientImpl.h ('k') | webkit/glue/editor_client_impl.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright (C) 2006, 2007 Apple, Inc. All rights reserved.
3 * Copyright (C) 2009 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 "KeyboardCodes.h"
37 #include "HTMLInputElement.h"
38 #include "HTMLNames.h"
39 #include "KeyboardEvent.h"
40 #include "PlatformKeyboardEvent.h"
41 #include "PlatformString.h"
42 #include "RenderObject.h"
43
44 #include "WebEditingAction.h"
45 #include "WebKit.h"
46 #include "WebNode.h"
47 #include "WebRange.h"
48 #include "WebTextAffinity.h"
49 #include "WebViewClient.h"
50 #include "DOMUtilitiesPrivate.h"
51 #include "PasswordAutocompleteListener.h"
52 #include "webkit/glue/webview_impl.h"
53
54 using namespace WebCore;
55
56 namespace WebKit {
57
58 // Arbitrary depth limit for the undo stack, to keep it from using
59 // unbounded memory. This is the maximum number of distinct undoable
60 // actions -- unbroken stretches of typed characters are coalesced
61 // into a single action.
62 static const size_t maximumUndoStackDepth = 1000;
63
64 // The size above which we stop triggering autofill for an input text field
65 // (so to avoid sending long strings through IPC).
66 static const size_t maximumTextSizeForAutofill = 1000;
67
68 EditorClientImpl::EditorClientImpl(WebViewImpl* webview)
69 : m_webView(webview)
70 , m_inRedo(false)
71 , m_backspaceOrDeletePressed(false)
72 , m_spellCheckThisFieldStatus(SpellCheckAutomatic)
73 , m_autofillTimer(this, &EditorClientImpl::doAutofill)
74 {
75 }
76
77 EditorClientImpl::~EditorClientImpl()
78 {
79 }
80
81 void EditorClientImpl::pageDestroyed()
82 {
83 // Our lifetime is bound to the WebViewImpl.
84 }
85
86 bool EditorClientImpl::shouldShowDeleteInterface(HTMLElement* elem)
87 {
88 // Normally, we don't care to show WebCore's deletion UI, so we only enable
89 // it if in testing mode and the test specifically requests it by using this
90 // magic class name.
91 return WebKit::layoutTestMode()
92 && elem->getAttribute(HTMLNames::classAttr) == "needsDeletionUI";
93 }
94
95 bool EditorClientImpl::smartInsertDeleteEnabled()
96 {
97 if (m_webView->client())
98 return m_webView->client()->isSmartInsertDeleteEnabled();
99 return true;
100 }
101
102 bool EditorClientImpl::isSelectTrailingWhitespaceEnabled()
103 {
104 if (m_webView->client())
105 return m_webView->client()->isSelectTrailingWhitespaceEnabled();
106 #if PLATFORM(WIN_OS)
107 return true;
108 #else
109 return false;
110 #endif
111 }
112
113 bool EditorClientImpl::shouldSpellcheckByDefault()
114 {
115 // Spellcheck should be enabled for all editable areas (such as textareas,
116 // contentEditable regions, and designMode docs), except text inputs.
117 const Frame* frame = m_webView->GetFocusedWebCoreFrame();
118 if (!frame)
119 return false;
120 const Editor* editor = frame->editor();
121 if (!editor)
122 return false;
123 if (editor->spellCheckingEnabledInFocusedNode())
124 return true;
125 const Document* document = frame->document();
126 if (!document)
127 return false;
128 const Node* node = document->focusedNode();
129 // If |node| is null, we default to allowing spellchecking. This is done in
130 // order to mitigate the issue when the user clicks outside the textbox, as a
131 // result of which |node| becomes null, resulting in all the spell check
132 // markers being deleted. Also, the Frame will decide not to do spellchecking
133 // if the user can't edit - so returning true here will not cause any problems
134 // to the Frame's behavior.
135 if (!node)
136 return true;
137 const RenderObject* renderer = node->renderer();
138 if (!renderer)
139 return false;
140
141 return !renderer->isTextField();
142 }
143
144 bool EditorClientImpl::isContinuousSpellCheckingEnabled()
145 {
146 if (m_spellCheckThisFieldStatus == SpellCheckForcedOff)
147 return false;
148 if (m_spellCheckThisFieldStatus == SpellCheckForcedOn)
149 return true;
150 return shouldSpellcheckByDefault();
151 }
152
153 void EditorClientImpl::toggleContinuousSpellChecking()
154 {
155 if (isContinuousSpellCheckingEnabled())
156 m_spellCheckThisFieldStatus = SpellCheckForcedOff;
157 else
158 m_spellCheckThisFieldStatus = SpellCheckForcedOn;
159 }
160
161 bool EditorClientImpl::isGrammarCheckingEnabled()
162 {
163 return false;
164 }
165
166 void EditorClientImpl::toggleGrammarChecking()
167 {
168 notImplemented();
169 }
170
171 int EditorClientImpl::spellCheckerDocumentTag()
172 {
173 ASSERT_NOT_REACHED();
174 return 0;
175 }
176
177 bool EditorClientImpl::isEditable()
178 {
179 return false;
180 }
181
182 bool EditorClientImpl::shouldBeginEditing(Range* range)
183 {
184 if (m_webView->client())
185 return m_webView->client()->shouldBeginEditing(WebRange(range));
186 return true;
187 }
188
189 bool EditorClientImpl::shouldEndEditing(Range* range)
190 {
191 if (m_webView->client())
192 return m_webView->client()->shouldEndEditing(WebRange(range));
193 return true;
194 }
195
196 bool EditorClientImpl::shouldInsertNode(Node* node,
197 Range* range,
198 EditorInsertAction action)
199 {
200 if (m_webView->client()) {
201 return m_webView->client()->shouldInsertNode(WebNode(node),
202 WebRange(range),
203 static_cast<WebEditingAction>(action));
204 }
205 return true;
206 }
207
208 bool EditorClientImpl::shouldInsertText(const String& text,
209 Range* range,
210 EditorInsertAction action)
211 {
212 if (m_webView->client()) {
213 return m_webView->client()->shouldInsertText(WebString(text),
214 WebRange(range),
215 static_cast<WebEditingAction>(action));
216 }
217 return true;
218 }
219
220
221 bool EditorClientImpl::shouldDeleteRange(Range* range)
222 {
223 if (m_webView->client())
224 return m_webView->client()->shouldDeleteRange(WebRange(range));
225 return true;
226 }
227
228 bool EditorClientImpl::shouldChangeSelectedRange(Range* fromRange,
229 Range* toRange,
230 EAffinity affinity,
231 bool stillSelecting)
232 {
233 if (m_webView->client()) {
234 return m_webView->client()->shouldChangeSelectedRange(WebRange(fromRange),
235 WebRange(toRange),
236 static_cast<WebTextAffinity>(affinity),
237 stillSelecting);
238 }
239 return true;
240 }
241
242 bool EditorClientImpl::shouldApplyStyle(CSSStyleDeclaration* style,
243 Range* range)
244 {
245 if (m_webView->client()) {
246 // FIXME: Pass a reference to the CSSStyleDeclaration somehow.
247 return m_webView->client()->shouldApplyStyle(WebString(),
248 WebRange(range));
249 }
250 return true;
251 }
252
253 bool EditorClientImpl::shouldMoveRangeAfterDelete(Range* range,
254 Range* rangeToBeReplaced)
255 {
256 return true;
257 }
258
259 void EditorClientImpl::didBeginEditing()
260 {
261 if (m_webView->client())
262 m_webView->client()->didBeginEditing();
263 }
264
265 void EditorClientImpl::respondToChangedSelection()
266 {
267 if (m_webView->client()) {
268 Frame* frame = m_webView->GetFocusedWebCoreFrame();
269 if (frame)
270 m_webView->client()->didChangeSelection(!frame->selection()->isRange());
271 }
272 }
273
274 void EditorClientImpl::respondToChangedContents()
275 {
276 if (m_webView->client())
277 m_webView->client()->didChangeContents();
278 }
279
280 void EditorClientImpl::didEndEditing()
281 {
282 if (m_webView->client())
283 m_webView->client()->didEndEditing();
284 }
285
286 void EditorClientImpl::didWriteSelectionToPasteboard()
287 {
288 }
289
290 void EditorClientImpl::didSetSelectionTypesForPasteboard()
291 {
292 }
293
294 void EditorClientImpl::registerCommandForUndo(PassRefPtr<EditCommand> command)
295 {
296 if (m_undoStack.size() == maximumUndoStackDepth)
297 m_undoStack.removeFirst(); // drop oldest item off the far end
298 if (!m_inRedo)
299 m_redoStack.clear();
300 m_undoStack.append(command);
301 }
302
303 void EditorClientImpl::registerCommandForRedo(PassRefPtr<EditCommand> command)
304 {
305 m_redoStack.append(command);
306 }
307
308 void EditorClientImpl::clearUndoRedoOperations()
309 {
310 m_undoStack.clear();
311 m_redoStack.clear();
312 }
313
314 bool EditorClientImpl::canUndo() const
315 {
316 return !m_undoStack.isEmpty();
317 }
318
319 bool EditorClientImpl::canRedo() const
320 {
321 return !m_redoStack.isEmpty();
322 }
323
324 void EditorClientImpl::undo()
325 {
326 if (canUndo()) {
327 EditCommandStack::iterator back = --m_undoStack.end();
328 RefPtr<EditCommand> command(*back);
329 m_undoStack.remove(back);
330 command->unapply();
331 // unapply will call us back to push this command onto the redo stack.
332 }
333 }
334
335 void EditorClientImpl::redo()
336 {
337 if (canRedo()) {
338 EditCommandStack::iterator back = --m_redoStack.end();
339 RefPtr<EditCommand> command(*back);
340 m_redoStack.remove(back);
341
342 ASSERT(!m_inRedo);
343 m_inRedo = true;
344 command->reapply();
345 // reapply will call us back to push this command onto the undo stack.
346 m_inRedo = false;
347 }
348 }
349
350 //
351 // The below code was adapted from the WebKit file webview.cpp
352 //
353
354 static const unsigned CtrlKey = 1 << 0;
355 static const unsigned AltKey = 1 << 1;
356 static const unsigned ShiftKey = 1 << 2;
357 static const unsigned MetaKey = 1 << 3;
358 #if PLATFORM(DARWIN)
359 // Aliases for the generic key defintions to make kbd shortcuts definitions more
360 // readable on OS X.
361 static const unsigned OptionKey = AltKey;
362 static const unsigned CommandKey = MetaKey;
363 #endif
364
365 // Keys with special meaning. These will be delegated to the editor using
366 // the execCommand() method
367 struct KeyDownEntry {
368 unsigned virtualKey;
369 unsigned modifiers;
370 const char* name;
371 };
372
373 struct KeyPressEntry {
374 unsigned charCode;
375 unsigned modifiers;
376 const char* name;
377 };
378
379 static const KeyDownEntry keyDownEntries[] = {
380 { VKEY_LEFT, 0, "MoveLeft" },
381 { VKEY_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
382 #if PLATFORM(DARWIN)
383 { VKEY_LEFT, OptionKey, "MoveWordLeft" },
384 { VKEY_LEFT, OptionKey | ShiftKey,
385 "MoveWordLeftAndModifySelection" },
386 #else
387 { VKEY_LEFT, CtrlKey, "MoveWordLeft" },
388 { VKEY_LEFT, CtrlKey | ShiftKey,
389 "MoveWordLeftAndModifySelection" },
390 #endif
391 { VKEY_RIGHT, 0, "MoveRight" },
392 { VKEY_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
393 #if PLATFORM(DARWIN)
394 { VKEY_RIGHT, OptionKey, "MoveWordRight" },
395 { VKEY_RIGHT, OptionKey | ShiftKey,
396 "MoveWordRightAndModifySelection" },
397 #else
398 { VKEY_RIGHT, CtrlKey, "MoveWordRight" },
399 { VKEY_RIGHT, CtrlKey | ShiftKey,
400 "MoveWordRightAndModifySelection" },
401 #endif
402 { VKEY_UP, 0, "MoveUp" },
403 { VKEY_UP, ShiftKey, "MoveUpAndModifySelection" },
404 { VKEY_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
405 { VKEY_DOWN, 0, "MoveDown" },
406 { VKEY_DOWN, ShiftKey, "MoveDownAndModifySelection" },
407 { VKEY_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
408 { VKEY_PRIOR, 0, "MovePageUp" },
409 { VKEY_NEXT, 0, "MovePageDown" },
410 { VKEY_HOME, 0, "MoveToBeginningOfLine" },
411 { VKEY_HOME, ShiftKey,
412 "MoveToBeginningOfLineAndModifySelection" },
413 #if PLATFORM(DARWIN)
414 { VKEY_LEFT, CommandKey, "MoveToBeginningOfLine" },
415 { VKEY_LEFT, CommandKey | ShiftKey,
416 "MoveToBeginningOfLineAndModifySelection" },
417 #endif
418 #if PLATFORM(DARWIN)
419 { VKEY_UP, CommandKey, "MoveToBeginningOfDocument" },
420 { VKEY_UP, CommandKey | ShiftKey,
421 "MoveToBeginningOfDocumentAndModifySelection" },
422 #else
423 { VKEY_HOME, CtrlKey, "MoveToBeginningOfDocument" },
424 { VKEY_HOME, CtrlKey | ShiftKey,
425 "MoveToBeginningOfDocumentAndModifySelection" },
426 #endif
427 { VKEY_END, 0, "MoveToEndOfLine" },
428 { VKEY_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
429 #if PLATFORM(DARWIN)
430 { VKEY_DOWN, CommandKey, "MoveToEndOfDocument" },
431 { VKEY_DOWN, CommandKey | ShiftKey,
432 "MoveToEndOfDocumentAndModifySelection" },
433 #else
434 { VKEY_END, CtrlKey, "MoveToEndOfDocument" },
435 { VKEY_END, CtrlKey | ShiftKey,
436 "MoveToEndOfDocumentAndModifySelection" },
437 #endif
438 #if PLATFORM(DARWIN)
439 { VKEY_RIGHT, CommandKey, "MoveToEndOfLine" },
440 { VKEY_RIGHT, CommandKey | ShiftKey,
441 "MoveToEndOfLineAndModifySelection" },
442 #endif
443 { VKEY_BACK, 0, "DeleteBackward" },
444 { VKEY_BACK, ShiftKey, "DeleteBackward" },
445 { VKEY_DELETE, 0, "DeleteForward" },
446 #if PLATFORM(DARWIN)
447 { VKEY_BACK, OptionKey, "DeleteWordBackward" },
448 { VKEY_DELETE, OptionKey, "DeleteWordForward" },
449 #else
450 { VKEY_BACK, CtrlKey, "DeleteWordBackward" },
451 { VKEY_DELETE, CtrlKey, "DeleteWordForward" },
452 #endif
453 { 'B', CtrlKey, "ToggleBold" },
454 { 'I', CtrlKey, "ToggleItalic" },
455 { 'U', CtrlKey, "ToggleUnderline" },
456 { VKEY_ESCAPE, 0, "Cancel" },
457 { VKEY_OEM_PERIOD, CtrlKey, "Cancel" },
458 { VKEY_TAB, 0, "InsertTab" },
459 { VKEY_TAB, ShiftKey, "InsertBacktab" },
460 { VKEY_RETURN, 0, "InsertNewline" },
461 { VKEY_RETURN, CtrlKey, "InsertNewline" },
462 { VKEY_RETURN, AltKey, "InsertNewline" },
463 { VKEY_RETURN, AltKey | ShiftKey, "InsertNewline" },
464 { VKEY_RETURN, ShiftKey, "InsertLineBreak" },
465 { VKEY_INSERT, CtrlKey, "Copy" },
466 { VKEY_INSERT, ShiftKey, "Paste" },
467 { VKEY_DELETE, ShiftKey, "Cut" },
468 #if PLATFORM(DARWIN)
469 { 'C', CommandKey, "Copy" },
470 { 'V', CommandKey, "Paste" },
471 { 'V', CommandKey | ShiftKey,
472 "PasteAndMatchStyle" },
473 { 'X', CommandKey, "Cut" },
474 { 'A', CommandKey, "SelectAll" },
475 { 'Z', CommandKey, "Undo" },
476 { 'Z', CommandKey | ShiftKey,
477 "Redo" },
478 { 'Y', CommandKey, "Redo" },
479 #else
480 { 'C', CtrlKey, "Copy" },
481 { 'V', CtrlKey, "Paste" },
482 { 'V', CtrlKey | ShiftKey, "PasteAndMatchStyle" },
483 { 'X', CtrlKey, "Cut" },
484 { 'A', CtrlKey, "SelectAll" },
485 { 'Z', CtrlKey, "Undo" },
486 { 'Z', CtrlKey | ShiftKey, "Redo" },
487 { 'Y', CtrlKey, "Redo" },
488 #endif
489 };
490
491 static const KeyPressEntry keyPressEntries[] = {
492 { '\t', 0, "InsertTab" },
493 { '\t', ShiftKey, "InsertBacktab" },
494 { '\r', 0, "InsertNewline" },
495 { '\r', CtrlKey, "InsertNewline" },
496 { '\r', ShiftKey, "InsertLineBreak" },
497 { '\r', AltKey, "InsertNewline" },
498 { '\r', AltKey | ShiftKey, "InsertNewline" },
499 };
500
501 const char* EditorClientImpl::interpretKeyEvent(const KeyboardEvent* evt)
502 {
503 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
504 if (!keyEvent)
505 return "";
506
507 static HashMap<int, const char*>* keyDownCommandsMap = 0;
508 static HashMap<int, const char*>* keyPressCommandsMap = 0;
509
510 if (!keyDownCommandsMap) {
511 keyDownCommandsMap = new HashMap<int, const char*>;
512 keyPressCommandsMap = new HashMap<int, const char*>;
513
514 for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
515 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey,
516 keyDownEntries[i].name);
517 }
518
519 for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
520 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode,
521 keyPressEntries[i].name);
522 }
523 }
524
525 unsigned modifiers = 0;
526 if (keyEvent->shiftKey())
527 modifiers |= ShiftKey;
528 if (keyEvent->altKey())
529 modifiers |= AltKey;
530 if (keyEvent->ctrlKey())
531 modifiers |= CtrlKey;
532 if (keyEvent->metaKey())
533 modifiers |= MetaKey;
534
535 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
536 int mapKey = modifiers << 16 | evt->keyCode();
537 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
538 }
539
540 int mapKey = modifiers << 16 | evt->charCode();
541 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
542 }
543
544 bool EditorClientImpl::handleEditingKeyboardEvent(KeyboardEvent* evt)
545 {
546 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
547 // do not treat this as text input if it's a system key event
548 if (!keyEvent || keyEvent->isSystemKey())
549 return false;
550
551 Frame* frame = evt->target()->toNode()->document()->frame();
552 if (!frame)
553 return false;
554
555 String commandName = interpretKeyEvent(evt);
556 Editor::Command command = frame->editor()->command(commandName);
557
558 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
559 // WebKit doesn't have enough information about mode to decide how
560 // commands that just insert text if executed via Editor should be treated,
561 // so we leave it upon WebCore to either handle them immediately
562 // (e.g. Tab that changes focus) or let a keypress event be generated
563 // (e.g. Tab that inserts a Tab character, or Enter).
564 if (command.isTextInsertion() || commandName.isEmpty())
565 return false;
566 if (command.execute(evt)) {
567 if (m_webView->client())
568 m_webView->client()->didExecuteCommand(WebString(commandName));
569 return true;
570 }
571 return false;
572 }
573
574 if (command.execute(evt)) {
575 if (m_webView->client())
576 m_webView->client()->didExecuteCommand(WebString(commandName));
577 return true;
578 }
579
580 // Here we need to filter key events.
581 // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
582 // In Webkit, EditorClient::handleKeyboardEvent in
583 // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
584 // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
585 // These key events should not emit text insert event.
586 // Alt key would be used to insert alternative character, so we should let
587 // through. Also note that Ctrl-Alt combination equals to AltGr key which is
588 // also used to insert alternative character.
589 // http://code.google.com/p/chromium/issues/detail?id=10846
590 // Windows sets both alt and meta are on when "Alt" key pressed.
591 // http://code.google.com/p/chromium/issues/detail?id=2215
592 // Also, we should not rely on an assumption that keyboards don't
593 // send ASCII characters when pressing a control key on Windows,
594 // which may be configured to do it so by user.
595 // See also http://en.wikipedia.org/wiki/Keyboard_Layout
596 // FIXME(ukai): investigate more detail for various keyboard layout.
597 if (evt->keyEvent()->text().length() == 1) {
598 UChar ch = evt->keyEvent()->text()[0U];
599
600 // Don't insert null or control characters as they can result in
601 // unexpected behaviour
602 if (ch < ' ')
603 return false;
604 #if !PLATFORM(WIN_OS)
605 // Don't insert ASCII character if ctrl w/o alt or meta is on.
606 // On Mac, we should ignore events when meta is on (Command-<x>).
607 if (ch < 0x80) {
608 if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
609 return false;
610 #if PLATFORM(DARWIN)
611 if (evt->keyEvent()->metaKey())
612 return false;
613 #endif
614 }
615 #endif
616 }
617
618 if (!frame->editor()->canEdit())
619 return false;
620
621 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
622 }
623
624 void EditorClientImpl::handleKeyboardEvent(KeyboardEvent* evt)
625 {
626 if (evt->keyCode() == VKEY_DOWN
627 || evt->keyCode() == VKEY_UP) {
628 ASSERT(evt->target()->toNode());
629 showFormAutofillForNode(evt->target()->toNode());
630 }
631
632 // Give the embedder a chance to handle the keyboard event.
633 if ((m_webView->client()
634 && m_webView->client()->handleCurrentKeyboardEvent())
635 || handleEditingKeyboardEvent(evt))
636 evt->setDefaultHandled();
637 }
638
639 void EditorClientImpl::handleInputMethodKeydown(KeyboardEvent* keyEvent)
640 {
641 // We handle IME within chrome.
642 }
643
644 void EditorClientImpl::textFieldDidBeginEditing(Element*)
645 {
646 }
647
648 void EditorClientImpl::textFieldDidEndEditing(Element* element)
649 {
650 // Notification that focus was lost. Be careful with this, it's also sent
651 // when the page is being closed.
652
653 // Cancel any pending DoAutofill call.
654 m_autofillArgs.clear();
655 m_autofillTimer.stop();
656
657 // Hide any showing popup.
658 m_webView->HideAutoCompletePopup();
659
660 if (!m_webView->client())
661 return; // The page is getting closed, don't fill the password.
662
663 // Notify any password-listener of the focus change.
664 HTMLInputElement* inputElement = WebKit::toHTMLInputElement(element);
665 if (!inputElement)
666 return;
667
668 WebFrameImpl* webframe = WebFrameImpl::FromFrame(inputElement->document()->frame());
669 PasswordAutocompleteListener* listener = webframe->GetPasswordListener(inputElement);
670 if (!listener)
671 return;
672
673 listener->didBlurInputElement(inputElement->value());
674 }
675
676 void EditorClientImpl::textDidChangeInTextField(Element* element)
677 {
678 ASSERT(element->hasLocalName(HTMLNames::inputTag));
679 // Note that we only show the autofill popup in this case if the caret is at
680 // the end. This matches FireFox and Safari but not IE.
681 autofill(static_cast<HTMLInputElement*>(element), false, false,
682 true);
683 }
684
685 bool EditorClientImpl::showFormAutofillForNode(Node* node)
686 {
687 HTMLInputElement* input_element = WebKit::toHTMLInputElement(node);
darin (slow to review) 2009/10/27 18:20:02 inputElement
688 if (input_element)
689 return autofill(input_element, true, true, false);
690 return false;
691 }
692
693 bool EditorClientImpl::autofill(HTMLInputElement* inputElement,
694 bool autofillFormOnly,
695 bool autofillOnEmptyValue,
696 bool requireCaretAtEnd)
697 {
698 // Cancel any pending DoAutofill call.
699 m_autofillArgs.clear();
700 m_autofillTimer.stop();
701
702 // Let's try to trigger autofill for that field, if applicable.
703 if (!inputElement->isEnabledFormControl() || !inputElement->isTextField()
704 || inputElement->isPasswordField()
705 || !inputElement->autoComplete())
706 return false;
707
708 WebString name = WebKit::nameOfInputElement(inputElement);
709 if (name.length() == 0) // If the field has no name, then we won't have values.
710 return false;
711
712 // Don't attempt to autofill with values that are too large.
713 if (inputElement->value().length() > maximumTextSizeForAutofill)
714 return false;
715
716 m_autofillArgs = new AutofillArgs();
717 m_autofillArgs->inputElement = inputElement;
718 m_autofillArgs->autofillFormOnly = autofillFormOnly;
719 m_autofillArgs->autofillOnEmptyValue = autofillOnEmptyValue;
720 m_autofillArgs->requireCaretAtEnd = requireCaretAtEnd;
721 m_autofillArgs->backspaceOrDeletePressed = m_backspaceOrDeletePressed;
722
723 if (!requireCaretAtEnd)
724 doAutofill(0);
725 else {
726 // We post a task for doing the autofill as the caret position is not set
727 // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976)
728 // and we need it to determine whether or not to trigger autofill.
729 m_autofillTimer.startOneShot(0.0);
730 }
731 return true;
732 }
733
734 void EditorClientImpl::doAutofill(Timer<EditorClientImpl>* timer)
735 {
736 OwnPtr<AutofillArgs> args(m_autofillArgs.release());
737 HTMLInputElement* inputElement = args->inputElement.get();
738
739 const String& value = inputElement->value();
740
741 // Enforce autofill_on_empty_value and caret_at_end.
742
743 bool isCaretAtEnd = true;
744 if (args->requireCaretAtEnd)
745 isCaretAtEnd = inputElement->selectionStart() == inputElement->selectionEnd()
746 && inputElement->selectionEnd() == static_cast<int>(value.length());
747
748 if ((!args->autofillOnEmptyValue && value.isEmpty()) || !isCaretAtEnd) {
749 m_webView->HideAutoCompletePopup();
750 return;
751 }
752
753 // First let's see if there is a password listener for that element.
754 // We won't trigger form autofill in that case, as having both behavior on
755 // a node would be confusing.
756 WebFrameImpl* webframe = WebFrameImpl::FromFrame(inputElement->document()->frame());
757 PasswordAutocompleteListener* listener = webframe->GetPasswordListener(inputElement);
758 if (listener) {
759 if (args->autofillFormOnly)
760 return;
761
762 listener->performInlineAutocomplete(value,
763 args->backspaceOrDeletePressed,
764 true);
765 return;
766 }
767
768 // Then trigger form autofill.
769 WebString name = WebKit::nameOfInputElement(inputElement);
770 ASSERT(static_cast<int>(name.length()) > 0);
771
772 if (m_webView->client())
773 m_webView->client()->queryAutofillSuggestions(WebNode(inputElement),
774 name, WebString(value));
775 }
776
777 void EditorClientImpl::cancelPendingAutofill()
778 {
779 m_autofillArgs.clear();
780 m_autofillTimer.stop();
781 }
782
783 void EditorClientImpl::onAutofillSuggestionAccepted(HTMLInputElement* textField)
784 {
785 WebFrameImpl* webframe = WebFrameImpl::FromFrame(textField->document()->frame());
786 PasswordAutocompleteListener* listener = webframe->GetPasswordListener(textField);
787 // Password listeners need to autocomplete other fields that depend on the
788 // input element with autofill suggestions.
789 if (listener)
790 listener->performInlineAutocomplete(textField->value(), false, false);
791 }
792
793 bool EditorClientImpl::doTextFieldCommandFromEvent(Element* element,
794 KeyboardEvent* event)
795 {
796 // Remember if backspace was pressed for the autofill. It is not clear how to
797 // find if backspace was pressed from textFieldDidBeginEditing and
798 // textDidChangeInTextField as when these methods are called the value of the
799 // input element already contains the type character.
800 m_backspaceOrDeletePressed = event->keyCode() == VKEY_BACK || event->keyCode() == VKEY_DELETE;
801
802 // The Mac code appears to use this method as a hook to implement special
803 // keyboard commands specific to Safari's auto-fill implementation. We
804 // just return false to allow the default action.
805 return false;
806 }
807
808 void EditorClientImpl::textWillBeDeletedInTextField(Element*)
809 {
810 }
811
812 void EditorClientImpl::textDidChangeInTextArea(Element*)
813 {
814 }
815
816 void EditorClientImpl::ignoreWordInSpellDocument(const String&)
817 {
818 notImplemented();
819 }
820
821 void EditorClientImpl::learnWord(const String&)
822 {
823 notImplemented();
824 }
825
826 void EditorClientImpl::checkSpellingOfString(const UChar* text, int length,
827 int* misspellingLocation,
828 int* misspellingLength)
829 {
830 // SpellCheckWord will write (0, 0) into the output vars, which is what our
831 // caller expects if the word is spelled correctly.
832 int spellLocation = -1;
833 int spellLength = 0;
834
835 // Check to see if the provided text is spelled correctly.
836 if (isContinuousSpellCheckingEnabled() && m_webView->client())
837 m_webView->client()->spellCheck(WebString(text, length), spellLocation, spellLength);
838 else {
839 spellLocation = 0;
840 spellLength = 0;
841 }
842
843 // Note: the Mac code checks if the pointers are null before writing to them,
844 // so we do too.
845 if (misspellingLocation)
846 *misspellingLocation = spellLocation;
847 if (misspellingLength)
848 *misspellingLength = spellLength;
849 }
850
851 String EditorClientImpl::getAutoCorrectSuggestionForMisspelledWord(const String& misspelledWord)
852 {
853 if (!(isContinuousSpellCheckingEnabled() && m_webView->client()))
854 return String();
855
856 // Do not autocorrect words with capital letters in it except the
857 // first letter. This will remove cases changing "IMB" to "IBM".
858 for (size_t i = 1; i < misspelledWord.length(); i++) {
859 if (u_isupper(static_cast<UChar32>(misspelledWord[i])))
860 return String();
861 }
862
863 return m_webView->client()->autoCorrectWord(WebString(misspelledWord));
864 }
865
866 void EditorClientImpl::checkGrammarOfString(const UChar*, int length,
867 WTF::Vector<GrammarDetail>&,
868 int* badGrammarLocation,
869 int* badGrammarLength)
870 {
871 notImplemented();
872 if (badGrammarLocation)
873 *badGrammarLocation = 0;
874 if (badGrammarLength)
875 *badGrammarLength = 0;
876 }
877
878 void EditorClientImpl::updateSpellingUIWithGrammarString(const String&,
879 const GrammarDetail& detail)
880 {
881 notImplemented();
882 }
883
884 void EditorClientImpl::updateSpellingUIWithMisspelledWord(const String& misspelledWord)
885 {
886 if (m_webView->client())
887 m_webView->client()->updateSpellingUIWithMisspelledWord(WebString(misspelledWord));
888 }
889
890 void EditorClientImpl::showSpellingUI(bool show)
891 {
892 if (m_webView->client())
893 m_webView->client()->showSpellingUI(show);
894 }
895
896 bool EditorClientImpl::spellingUIIsShowing()
897 {
898 if (m_webView->client())
899 return m_webView->client()->isShowingSpellingUI();
900 return false;
901 }
902
903 void EditorClientImpl::getGuessesForWord(const String&,
904 WTF::Vector<String>& guesses)
905 {
906 notImplemented();
907 }
908
909 void EditorClientImpl::setInputMethodState(bool enabled)
910 {
911 if (m_webView->client())
912 m_webView->client()->setInputMethodEnabled(enabled);
913 }
914
915 } // namesace WebKit
OLDNEW
« no previous file with comments | « webkit/api/src/EditorClientImpl.h ('k') | webkit/glue/editor_client_impl.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698