2 * Copyright (C) 2006, 2007, 2008, 2011, 2013 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
30 #include "AXObjectCache.h"
31 #include "AlternativeTextController.h"
32 #include "ApplyStyleCommand.h"
33 #include "CSSComputedStyleDeclaration.h"
34 #include "CSSPropertyNames.h"
35 #include "CSSValueKeywords.h"
36 #include "CachedResourceLoader.h"
37 #include "Clipboard.h"
38 #include "ClipboardEvent.h"
39 #include "CompositionEvent.h"
40 #include "CreateLinkCommand.h"
41 #if ENABLE(DELETION_UI)
42 #include "DeleteButtonController.h"
44 #include "DeleteSelectionCommand.h"
45 #include "DictationAlternative.h"
46 #include "DictationCommand.h"
47 #include "DocumentFragment.h"
48 #include "DocumentMarkerController.h"
49 #include "EditorClient.h"
50 #include "EventHandler.h"
51 #include "EventNames.h"
52 #include "ExceptionCodePlaceholder.h"
53 #include "FocusController.h"
55 #include "FrameTree.h"
56 #include "FrameView.h"
57 #include "GraphicsContext.h"
58 #include "HTMLFormControlElement.h"
59 #include "HTMLFrameOwnerElement.h"
60 #include "HTMLImageElement.h"
61 #include "HTMLNames.h"
62 #include "HTMLTextAreaElement.h"
63 #include "HitTestResult.h"
64 #include "IndentOutdentCommand.h"
65 #include "InsertListCommand.h"
66 #include "KeyboardEvent.h"
68 #include "ModifySelectionListLevel.h"
70 #include "NodeTraversal.h"
72 #include "Pasteboard.h"
73 #include "RemoveFormatCommand.h"
74 #include "RenderBlock.h"
75 #include "RenderPart.h"
76 #include "RenderTextControl.h"
77 #include "RenderedPosition.h"
78 #include "ReplaceSelectionCommand.h"
80 #include "ShadowRoot.h"
81 #include "SimplifyMarkupCommand.h"
83 #include "SpellChecker.h"
84 #include "SpellingCorrectionCommand.h"
85 #include "StylePropertySet.h"
86 #include "StyleResolver.h"
88 #include "TextCheckerClient.h"
89 #include "TextCheckingHelper.h"
90 #include "TextEvent.h"
91 #include "TextIterator.h"
92 #include "TypingCommand.h"
93 #include "UserTypingGestureIndicator.h"
94 #include "VisibleUnits.h"
95 #include "htmlediting.h"
97 #include <wtf/UnusedParam.h>
98 #include <wtf/unicode/CharacterNames.h>
99 #include <wtf/unicode/Unicode.h>
104 using namespace HTMLNames;
106 using namespace Unicode;
108 #if ENABLE(DELETION_UI)
109 PassRefPtr<Range> Editor::avoidIntersectionWithDeleteButtonController(const Range* range) const
111 DeleteButtonController* controller = deleteButtonController();
112 if (!range || !controller)
115 Document* document = range->ownerDocument();
117 Node* startContainer = range->startContainer();
118 int startOffset = range->startOffset();
119 Node* endContainer = range->endContainer();
120 int endOffset = range->endOffset();
125 ASSERT(endContainer);
127 Element* element = controller->containerElement();
128 if (startContainer == element || startContainer->isDescendantOf(element)) {
129 ASSERT(element->parentNode());
130 startContainer = element->parentNode();
131 startOffset = element->nodeIndex();
133 if (endContainer == element || endContainer->isDescendantOf(element)) {
134 ASSERT(element->parentNode());
135 endContainer = element->parentNode();
136 endOffset = element->nodeIndex();
139 return Range::create(document, startContainer, startOffset, endContainer, endOffset);
142 VisibleSelection Editor::avoidIntersectionWithDeleteButtonController(const VisibleSelection& selection) const
144 DeleteButtonController* controller = deleteButtonController();
145 if (selection.isNone() || !controller)
148 Element* element = controller->containerElement();
151 VisibleSelection updatedSelection = selection;
153 Position updatedBase = selection.base();
154 updatePositionForNodeRemoval(updatedBase, element);
155 if (updatedBase != selection.base())
156 updatedSelection.setBase(updatedBase);
158 Position updatedExtent = selection.extent();
159 updatePositionForNodeRemoval(updatedExtent, element);
160 if (updatedExtent != selection.extent())
161 updatedSelection.setExtent(updatedExtent);
163 return updatedSelection;
167 // When an event handler has moved the selection outside of a text control
168 // we should use the target control's selection for this editing operation.
169 VisibleSelection Editor::selectionForCommand(Event* event)
171 VisibleSelection selection = m_frame->selection()->selection();
174 // If the target is a text control, and the current selection is outside of its shadow tree,
175 // then use the saved selection for that text control.
176 HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
177 HTMLTextFormControlElement* textFromControlOfTarget = isHTMLTextFormControlElement(event->target()->toNode()) ? toHTMLTextFormControlElement(event->target()->toNode()) : 0;
178 if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
179 if (RefPtr<Range> range = textFromControlOfTarget->selection())
180 return VisibleSelection(range.get(), DOWNSTREAM, selection.isDirectional());
185 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
186 EditingBehavior Editor::behavior() const
188 if (!m_frame || !m_frame->settings())
189 return EditingBehavior(EditingMacBehavior);
191 return EditingBehavior(m_frame->settings()->editingBehaviorType());
194 EditorClient* Editor::client() const
196 if (Page* page = m_frame->page())
197 return page->editorClient();
202 TextCheckerClient* Editor::textChecker() const
204 if (EditorClient* owner = client())
205 return owner->textChecker();
209 void Editor::handleKeyboardEvent(KeyboardEvent* event)
211 if (EditorClient* c = client())
212 c->handleKeyboardEvent(event);
215 void Editor::handleInputMethodKeydown(KeyboardEvent* event)
217 if (EditorClient* c = client())
218 c->handleInputMethodKeydown(event);
221 bool Editor::handleTextEvent(TextEvent* event)
223 // Default event handling for Drag and Drop will be handled by DragController
224 // so we leave the event for it.
228 if (event->isPaste()) {
229 if (event->pastingFragment())
230 replaceSelectionWithFragment(event->pastingFragment(), false, event->shouldSmartReplace(), event->shouldMatchStyle());
232 replaceSelectionWithText(event->data(), false, event->shouldSmartReplace());
236 String data = event->data();
238 if (event->isLineBreak())
239 return insertLineBreak();
240 return insertParagraphSeparator();
243 return insertTextWithoutSendingTextEvent(data, false, event);
246 bool Editor::canEdit() const
248 return m_frame->selection()->rootEditableElement();
251 bool Editor::canEditRichly() const
253 return m_frame->selection()->isContentRichlyEditable();
256 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items. They
257 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
258 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
259 // normally selectable to implement copy/paste (like divs, or a document body).
261 bool Editor::canDHTMLCut()
263 return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
266 bool Editor::canDHTMLCopy()
268 return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
271 bool Editor::canDHTMLPaste()
273 return !dispatchCPPEvent(eventNames().beforepasteEvent, ClipboardNumb);
276 bool Editor::canCut() const
278 return canCopy() && canDelete();
281 static HTMLImageElement* imageElementFromImageDocument(Document* document)
285 if (!document->isImageDocument())
288 HTMLElement* body = document->body();
292 Node* node = body->firstChild();
295 if (!node->hasTagName(imgTag))
297 return static_cast<HTMLImageElement*>(node);
300 bool Editor::canCopy() const
302 if (imageElementFromImageDocument(m_frame->document()))
304 FrameSelection* selection = m_frame->selection();
305 return selection->isRange() && !selection->isInPasswordField();
308 bool Editor::canPaste() const
313 bool Editor::canDelete() const
315 FrameSelection* selection = m_frame->selection();
316 return selection->isRange() && selection->rootEditableElement();
319 bool Editor::canDeleteRange(Range* range) const
321 Node* startContainer = range->startContainer();
322 Node* endContainer = range->endContainer();
323 if (!startContainer || !endContainer)
326 if (!startContainer->rendererIsEditable() || !endContainer->rendererIsEditable())
329 if (range->collapsed(IGNORE_EXCEPTION)) {
330 VisiblePosition start(range->startPosition(), DOWNSTREAM);
331 VisiblePosition previous = start.previous();
332 // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
333 if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer->rootEditableElement())
339 bool Editor::smartInsertDeleteEnabled()
341 return client() && client()->smartInsertDeleteEnabled();
344 bool Editor::canSmartCopyOrDelete()
346 return client() && client()->smartInsertDeleteEnabled() && m_frame->selection()->granularity() == WordGranularity;
349 bool Editor::isSelectTrailingWhitespaceEnabled()
351 return client() && client()->isSelectTrailingWhitespaceEnabled();
354 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
359 if (m_frame->selection()->isRange()) {
360 if (isTypingAction) {
361 TypingCommand::deleteKeyPressed(m_frame->document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
362 revealSelectionAfterEditingOperation();
365 addToKillRing(selectedRange().get(), false);
366 deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
367 // Implicitly calls revealSelectionAfterEditingOperation().
370 TypingCommand::Options options = 0;
371 if (canSmartCopyOrDelete())
372 options |= TypingCommand::SmartDelete;
374 options |= TypingCommand::KillRing;
376 case DirectionForward:
378 TypingCommand::forwardDeleteKeyPressed(m_frame->document(), options, granularity);
380 case DirectionBackward:
382 TypingCommand::deleteKeyPressed(m_frame->document(), options, granularity);
385 revealSelectionAfterEditingOperation();
388 // FIXME: We should to move this down into deleteKeyPressed.
389 // clear the "start new kill ring sequence" setting, because it was set to true
390 // when the selection was updated by deleting the range
392 setStartNewKillRingSequence(false);
397 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
399 if (m_frame->selection()->isNone())
402 applyCommand(DeleteSelectionCommand::create(m_frame->document(), smartDelete));
405 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
407 Node* target = findEventTargetFromSelection();
410 target->dispatchEvent(TextEvent::createForPlainTextPaste(m_frame->document()->domWindow(), pastingText, smartReplace), IGNORE_EXCEPTION);
413 void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool smartReplace, bool matchStyle)
415 Node* target = findEventTargetFromSelection();
418 target->dispatchEvent(TextEvent::createForFragmentPaste(m_frame->document()->domWindow(), pastingFragment, smartReplace, matchStyle), IGNORE_EXCEPTION);
421 void Editor::pasteAsPlainTextBypassingDHTML()
423 pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
426 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard)
428 String text = pasteboard->plainText(m_frame);
429 if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
430 pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
434 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
436 RefPtr<Range> range = selectedRange();
438 RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, range, allowPlainText, chosePlainText);
439 if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
440 pasteAsFragment(fragment, canSmartReplaceWithPasteboard(pasteboard), chosePlainText);
444 bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
446 return client() && client()->smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
449 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
455 Node* child = fragment->firstChild();
456 if (child && fragment->lastChild() == child && child->isCharacterDataNode())
457 return client()->shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);
460 return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
463 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
465 if (m_frame->selection()->isNone() || !m_frame->selection()->isContentEditable() || !fragment)
468 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
469 if (selectReplacement)
470 options |= ReplaceSelectionCommand::SelectReplacement;
472 options |= ReplaceSelectionCommand::SmartReplace;
474 options |= ReplaceSelectionCommand::MatchStyle;
475 applyCommand(ReplaceSelectionCommand::create(m_frame->document(), fragment, options, EditActionPaste));
476 revealSelectionAfterEditingOperation();
478 if (m_frame->selection()->isInPasswordField() || !isContinuousSpellCheckingEnabled())
480 Node* nodeToCheck = m_frame->selection()->rootEditableElement();
484 RefPtr<Range> rangeToCheck = Range::create(m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
485 m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
488 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
490 replaceSelectionWithFragment(createFragmentFromText(selectedRange().get(), text), selectReplacement, smartReplace, true);
493 PassRefPtr<Range> Editor::selectedRange()
497 return m_frame->selection()->toNormalizedRange();
500 bool Editor::shouldDeleteRange(Range* range) const
502 if (!range || range->collapsed(IGNORE_EXCEPTION))
505 if (!canDeleteRange(range))
508 return client() && client()->shouldDeleteRange(range);
511 bool Editor::tryDHTMLCopy()
513 if (m_frame->selection()->isInPasswordField())
516 return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
519 bool Editor::tryDHTMLCut()
521 if (m_frame->selection()->isInPasswordField())
524 return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
527 bool Editor::tryDHTMLPaste()
529 return !dispatchCPPEvent(eventNames().pasteEvent, ClipboardReadable);
532 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
534 return client() && client()->shouldInsertText(text, range, action);
537 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
540 client()->respondToChangedSelection(m_frame);
541 setStartNewKillRingSequence(true);
542 #if ENABLE(DELETION_UI)
543 m_deleteButtonController->respondToChangedSelection(oldSelection);
545 m_alternativeTextController->respondToChangedSelection(oldSelection, options);
548 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
550 if (AXObjectCache::accessibilityEnabled()) {
551 Node* node = endingSelection.start().deprecatedNode();
552 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
553 cache->postNotification(node, AXObjectCache::AXValueChanged, false);
556 updateMarkersForWordsAffectedByEditing(true);
559 client()->respondToChangedContents();
562 bool Editor::hasBidiSelection() const
564 if (m_frame->selection()->isNone())
568 if (m_frame->selection()->isRange()) {
569 startNode = m_frame->selection()->selection().start().downstream().deprecatedNode();
570 Node* endNode = m_frame->selection()->selection().end().upstream().deprecatedNode();
571 if (enclosingBlock(startNode) != enclosingBlock(endNode))
574 startNode = m_frame->selection()->selection().visibleStart().deepEquivalent().deprecatedNode();
576 RenderObject* renderer = startNode->renderer();
577 while (renderer && !renderer->isRenderBlock())
578 renderer = renderer->parent();
583 RenderStyle* style = renderer->style();
584 if (!style->isLeftToRightDirection())
587 return toRenderBlock(renderer)->containsNonZeroBidiLevel();
590 TriState Editor::selectionUnorderedListState() const
592 if (m_frame->selection()->isCaret()) {
593 if (enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag))
595 } else if (m_frame->selection()->isRange()) {
596 Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag);
597 Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), ulTag);
598 if (startNode && endNode && startNode == endNode)
602 return FalseTriState;
605 TriState Editor::selectionOrderedListState() const
607 if (m_frame->selection()->isCaret()) {
608 if (enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag))
610 } else if (m_frame->selection()->isRange()) {
611 Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag);
612 Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), olTag);
613 if (startNode && endNode && startNode == endNode)
617 return FalseTriState;
620 PassRefPtr<Node> Editor::insertOrderedList()
622 if (!canEditRichly())
625 RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::OrderedList);
626 revealSelectionAfterEditingOperation();
630 PassRefPtr<Node> Editor::insertUnorderedList()
632 if (!canEditRichly())
635 RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::UnorderedList);
636 revealSelectionAfterEditingOperation();
640 bool Editor::canIncreaseSelectionListLevel()
642 return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(m_frame->document());
645 bool Editor::canDecreaseSelectionListLevel()
647 return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(m_frame->document());
650 PassRefPtr<Node> Editor::increaseSelectionListLevel()
652 if (!canEditRichly() || m_frame->selection()->isNone())
655 RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(m_frame->document());
656 revealSelectionAfterEditingOperation();
660 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
662 if (!canEditRichly() || m_frame->selection()->isNone())
665 RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(m_frame->document());
666 revealSelectionAfterEditingOperation();
667 return newList.release();
670 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
672 if (!canEditRichly() || m_frame->selection()->isNone())
675 RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(m_frame->document());
676 revealSelectionAfterEditingOperation();
677 return newList.release();
680 void Editor::decreaseSelectionListLevel()
682 if (!canEditRichly() || m_frame->selection()->isNone())
685 DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(m_frame->document());
686 revealSelectionAfterEditingOperation();
689 void Editor::removeFormattingAndStyle()
691 applyCommand(RemoveFormatCommand::create(m_frame->document()));
694 void Editor::clearLastEditCommand()
696 m_lastEditCommand.clear();
699 // Returns whether caller should continue with "the default processing", which is the same as
700 // the event handler NOT setting the return value to false
701 bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy)
703 Node* target = findEventTargetFromSelection();
707 RefPtr<Clipboard> clipboard = newGeneralClipboard(policy, m_frame);
709 RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
710 target->dispatchEvent(evt, IGNORE_EXCEPTION);
711 bool noDefaultProcessing = evt->defaultPrevented();
712 if (noDefaultProcessing && policy == ClipboardWritable) {
713 Pasteboard* pasteboard = Pasteboard::generalPasteboard();
715 pasteboard->writeClipboard(clipboard.get());
718 // invalidate clipboard here for security
719 clipboard->setAccessPolicy(ClipboardNumb);
721 return !noDefaultProcessing;
724 Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
726 Node* target = selection.start().element();
728 target = m_frame->document()->body();
735 Node* Editor::findEventTargetFromSelection() const
737 return findEventTargetFrom(m_frame->selection()->selection());
740 void Editor::applyStyle(StylePropertySet* style, EditAction editingAction)
742 switch (m_frame->selection()->selectionType()) {
743 case VisibleSelection::NoSelection:
746 case VisibleSelection::CaretSelection:
747 computeAndSetTypingStyle(style, editingAction);
749 case VisibleSelection::RangeSelection:
751 applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction));
756 bool Editor::shouldApplyStyle(StylePropertySet* style, Range* range)
758 return client()->shouldApplyStyle(style, range);
761 void Editor::applyParagraphStyle(StylePropertySet* style, EditAction editingAction)
763 switch (m_frame->selection()->selectionType()) {
764 case VisibleSelection::NoSelection:
767 case VisibleSelection::CaretSelection:
768 case VisibleSelection::RangeSelection:
770 applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties));
775 void Editor::applyStyleToSelection(StylePropertySet* style, EditAction editingAction)
777 if (!style || style->isEmpty() || !canEditRichly())
780 if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
781 applyStyle(style, editingAction);
784 void Editor::applyParagraphStyleToSelection(StylePropertySet* style, EditAction editingAction)
786 if (!style || style->isEmpty() || !canEditRichly())
789 if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
790 applyParagraphStyle(style, editingAction);
793 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
795 return EditingStyle::create(propertyID, value)->triStateOfStyle(
796 EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(), propertyID == CSSPropertyBackgroundColor).get());
799 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
801 return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame->selection()->selection());
804 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
806 RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(),
807 propertyID == CSSPropertyBackgroundColor);
808 if (!selectionStyle || !selectionStyle->style())
811 if (propertyID == CSSPropertyFontSize)
812 return String::number(selectionStyle->legacyFontSize(m_frame->document()));
813 return selectionStyle->style()->getPropertyValue(propertyID);
816 void Editor::indent()
818 applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Indent));
821 void Editor::outdent()
823 applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Outdent));
826 static void dispatchEditableContentChangedEvents(Element* startRoot, Element* endRoot)
829 startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
830 if (endRoot && endRoot != startRoot)
831 endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
834 void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
836 m_frame->document()->updateLayout();
838 EditCommandComposition* composition = cmd->composition();
840 dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
841 VisibleSelection newSelection(cmd->endingSelection());
843 m_alternativeTextController->respondToAppliedEditing(cmd.get());
845 // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
846 FrameSelection::SetSelectionOptions options = cmd->isDictationCommand() ? FrameSelection::DictationTriggered : 0;
847 changeSelectionAfterCommand(newSelection, options);
849 if (!cmd->preservesTypingStyle())
850 m_frame->selection()->clearTypingStyle();
852 // Command will be equal to last edit command only in the case of typing
853 if (m_lastEditCommand.get() == cmd)
854 ASSERT(cmd->isTypingCommand());
856 // Only register a new undo command if the command passed in is
857 // different from the last command
858 m_lastEditCommand = cmd;
860 client()->registerUndoStep(m_lastEditCommand->ensureComposition());
863 respondToChangedContents(newSelection);
866 void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
868 m_frame->document()->updateLayout();
870 dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
872 VisibleSelection newSelection(cmd->startingSelection());
873 changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
874 m_alternativeTextController->respondToUnappliedEditing(cmd.get());
876 m_lastEditCommand = 0;
878 client()->registerRedoStep(cmd);
879 respondToChangedContents(newSelection);
882 void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
884 m_frame->document()->updateLayout();
886 dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
888 VisibleSelection newSelection(cmd->endingSelection());
889 changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
891 m_lastEditCommand = 0;
893 client()->registerUndoStep(cmd);
894 respondToChangedContents(newSelection);
897 Editor::Editor(Frame* frame)
898 : FrameDestructionObserver(frame)
899 , m_ignoreCompositionSelectionChange(false)
900 , m_shouldStartNewKillRingSequence(false)
901 // This is off by default, since most editors want this behavior (this matches IE but not FF).
902 , m_shouldStyleWithCSS(false)
903 , m_killRing(adoptPtr(new KillRing))
904 , m_spellChecker(adoptPtr(new SpellChecker(frame)))
905 , m_alternativeTextController(adoptPtr(new AlternativeTextController(frame)))
906 , m_areMarkedTextMatchesHighlighted(false)
907 , m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv)
908 , m_overwriteModeEnabled(false)
910 #if ENABLE(DELETION_UI)
911 m_deleteButtonController = adoptPtr(new DeleteButtonController(frame));
921 m_compositionNode = 0;
922 m_customCompositionUnderlines.clear();
923 m_shouldStyleWithCSS = false;
924 m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
927 bool Editor::insertText(const String& text, Event* triggeringEvent)
929 return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
932 bool Editor::insertTextForConfirmedComposition(const String& text)
934 return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
937 bool Editor::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent)
939 return m_alternativeTextController->insertDictatedText(text, dictationAlternatives, triggeringEvent);
942 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
947 VisibleSelection selection = selectionForCommand(triggeringEvent);
948 if (!selection.isContentEditable())
950 RefPtr<Range> range = selection.toNormalizedRange();
952 if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
956 updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
958 bool shouldConsiderApplyingAutocorrection = false;
959 if (text == " " || text == "\t")
960 shouldConsiderApplyingAutocorrection = true;
962 if (text.length() == 1 && isPunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
963 shouldConsiderApplyingAutocorrection = true;
965 bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
967 // Get the selection to use for the event that triggered this insertText.
968 // If the event handler changed the selection, we may want to use a different selection
969 // that is contained in the event target.
970 selection = selectionForCommand(triggeringEvent);
971 if (selection.isContentEditable()) {
972 if (Node* selectionStart = selection.start().deprecatedNode()) {
973 RefPtr<Document> document = selectionStart->document();
976 if (triggeringEvent && triggeringEvent->isDictation())
977 DictationCommand::insertText(document.get(), text, triggeringEvent->dictationAlternatives(), selection);
979 TypingCommand::Options options = 0;
980 if (selectInsertedText)
981 options |= TypingCommand::SelectInsertedText;
982 if (autocorrectionWasApplied)
983 options |= TypingCommand::RetainAutocorrectionIndicator;
984 TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
987 // Reveal the current selection
988 if (Frame* editedFrame = document->frame())
989 if (Page* page = editedFrame->page())
990 page->focusController()->focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignCenterIfNeeded);
997 bool Editor::insertLineBreak()
1002 if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1005 VisiblePosition caret = m_frame->selection()->selection().visibleStart();
1006 bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1007 bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1008 TypingCommand::insertLineBreak(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1009 revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1014 bool Editor::insertParagraphSeparator()
1019 if (!canEditRichly())
1020 return insertLineBreak();
1022 if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1025 VisiblePosition caret = m_frame->selection()->selection().visibleStart();
1026 bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1027 bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1028 TypingCommand::insertParagraphSeparator(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1029 revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1037 return; // DHTML did the whole operation
1042 RefPtr<Range> selection = selectedRange();
1043 willWriteSelectionToPasteboard(selection);
1044 if (shouldDeleteRange(selection.get())) {
1045 updateMarkersForWordsAffectedByEditing(true);
1046 if (enclosingTextFormControl(m_frame->selection()->start())) {
1047 Pasteboard::generalPasteboard()->writePlainText(selectedTextForClipboard(),
1048 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1050 Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1051 didWriteSelectionToPasteboard();
1052 deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1059 return; // DHTML did the whole operation
1065 willWriteSelectionToPasteboard(selectedRange());
1066 if (enclosingTextFormControl(m_frame->selection()->start())) {
1067 Pasteboard::generalPasteboard()->writePlainText(selectedTextForClipboard(),
1068 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1070 Document* document = m_frame->document();
1071 if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
1072 Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
1074 Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1077 didWriteSelectionToPasteboard();
1080 void Editor::paste()
1082 ASSERT(m_frame->document());
1083 if (tryDHTMLPaste())
1084 return; // DHTML did the whole operation
1087 updateMarkersForWordsAffectedByEditing(false);
1088 CachedResourceLoader* loader = m_frame->document()->cachedResourceLoader();
1089 ResourceCacheValidationSuppressor validationSuppressor(loader);
1090 if (m_frame->selection()->isContentRichlyEditable())
1091 pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
1093 pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1096 void Editor::pasteAsPlainText()
1098 if (tryDHTMLPaste())
1102 updateMarkersForWordsAffectedByEditing(false);
1103 pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1106 void Editor::performDelete()
1113 addToKillRing(selectedRange().get(), false);
1114 deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1116 // clear the "start new kill ring sequence" setting, because it was set to true
1117 // when the selection was updated by deleting the range
1118 setStartNewKillRingSequence(false);
1121 void Editor::simplifyMarkup(Node* startNode, Node* endNode)
1126 if (startNode->document() != endNode->document())
1128 // check if start node is before endNode
1129 Node* node = startNode;
1130 while (node && node != endNode)
1131 node = NodeTraversal::next(node);
1136 applyCommand(SimplifyMarkupCommand::create(m_frame->document(), startNode, (endNode) ? NodeTraversal::next(endNode) : 0));
1139 void Editor::copyURL(const KURL& url, const String& title)
1141 Pasteboard::generalPasteboard()->writeURL(url, title, m_frame);
1144 void Editor::copyImage(const HitTestResult& result)
1146 KURL url = result.absoluteLinkURL();
1148 url = result.absoluteImageURL();
1150 Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
1153 bool Editor::isContinuousSpellCheckingEnabled() const
1155 return client() && client()->isContinuousSpellCheckingEnabled();
1158 void Editor::toggleContinuousSpellChecking()
1161 client()->toggleContinuousSpellChecking();
1164 bool Editor::isGrammarCheckingEnabled()
1166 return client() && client()->isGrammarCheckingEnabled();
1169 void Editor::toggleGrammarChecking()
1172 client()->toggleGrammarChecking();
1175 int Editor::spellCheckerDocumentTag()
1177 return client() ? client()->spellCheckerDocumentTag() : 0;
1182 void Editor::uppercaseWord()
1185 client()->uppercaseWord();
1188 void Editor::lowercaseWord()
1191 client()->lowercaseWord();
1194 void Editor::capitalizeWord()
1197 client()->capitalizeWord();
1202 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1204 void Editor::showSubstitutionsPanel()
1207 LOG_ERROR("No NSSpellChecker");
1211 if (client()->substitutionsPanelIsShowing()) {
1212 client()->showSubstitutionsPanel(false);
1215 client()->showSubstitutionsPanel(true);
1218 bool Editor::substitutionsPanelIsShowing()
1222 return client()->substitutionsPanelIsShowing();
1225 void Editor::toggleSmartInsertDelete()
1228 client()->toggleSmartInsertDelete();
1231 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1233 return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1236 void Editor::toggleAutomaticQuoteSubstitution()
1239 client()->toggleAutomaticQuoteSubstitution();
1242 bool Editor::isAutomaticLinkDetectionEnabled()
1244 return client() && client()->isAutomaticLinkDetectionEnabled();
1247 void Editor::toggleAutomaticLinkDetection()
1250 client()->toggleAutomaticLinkDetection();
1253 bool Editor::isAutomaticDashSubstitutionEnabled()
1255 return client() && client()->isAutomaticDashSubstitutionEnabled();
1258 void Editor::toggleAutomaticDashSubstitution()
1261 client()->toggleAutomaticDashSubstitution();
1264 bool Editor::isAutomaticTextReplacementEnabled()
1266 return client() && client()->isAutomaticTextReplacementEnabled();
1269 void Editor::toggleAutomaticTextReplacement()
1272 client()->toggleAutomaticTextReplacement();
1275 bool Editor::isAutomaticSpellingCorrectionEnabled()
1277 return m_alternativeTextController->isAutomaticSpellingCorrectionEnabled();
1280 void Editor::toggleAutomaticSpellingCorrection()
1283 client()->toggleAutomaticSpellingCorrection();
1288 bool Editor::shouldEndEditing(Range* range)
1290 return client() && client()->shouldEndEditing(range);
1293 bool Editor::shouldBeginEditing(Range* range)
1295 return client() && client()->shouldBeginEditing(range);
1298 void Editor::clearUndoRedoOperations()
1301 client()->clearUndoRedoOperations();
1304 bool Editor::canUndo()
1306 return client() && client()->canUndo();
1315 bool Editor::canRedo()
1317 return client() && client()->canRedo();
1326 void Editor::didBeginEditing()
1329 client()->didBeginEditing();
1332 void Editor::didEndEditing()
1335 client()->didEndEditing();
1338 void Editor::willWriteSelectionToPasteboard(PassRefPtr<Range> range)
1341 client()->willWriteSelectionToPasteboard(range.get());
1344 void Editor::didWriteSelectionToPasteboard()
1347 client()->didWriteSelectionToPasteboard();
1350 void Editor::toggleBold()
1352 command("ToggleBold").execute();
1355 void Editor::toggleUnderline()
1357 command("ToggleUnderline").execute();
1360 void Editor::setBaseWritingDirection(WritingDirection direction)
1362 Node* focusedNode = frame()->document()->focusedNode();
1363 if (focusedNode && isHTMLTextFormControlElement(focusedNode)) {
1364 if (direction == NaturalWritingDirection)
1366 toHTMLElement(focusedNode)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
1367 focusedNode->dispatchInputEvent();
1368 frame()->document()->updateStyleIfNeeded();
1372 RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
1373 style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1374 applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1377 WritingDirection Editor::baseWritingDirectionForSelectionStart() const
1379 WritingDirection result = LeftToRightWritingDirection;
1381 Position pos = m_frame->selection()->selection().visibleStart().deepEquivalent();
1382 Node* node = pos.deprecatedNode();
1386 RenderObject* renderer = node->renderer();
1390 if (!renderer->isBlockFlow()) {
1391 renderer = renderer->containingBlock();
1396 RenderStyle* style = renderer->style();
1400 switch (style->direction()) {
1402 return LeftToRightWritingDirection;
1404 return RightToLeftWritingDirection;
1410 void Editor::selectComposition()
1412 RefPtr<Range> range = compositionRange();
1416 // The composition can start inside a composed character sequence, so we have to override checks.
1417 // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1418 VisibleSelection selection;
1419 selection.setWithoutValidation(range->startPosition(), range->endPosition());
1420 m_frame->selection()->setSelection(selection, 0);
1423 void Editor::confirmComposition()
1425 if (!m_compositionNode)
1427 setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
1430 void Editor::cancelComposition()
1432 if (!m_compositionNode)
1434 setComposition(emptyString(), CancelComposition);
1437 bool Editor::cancelCompositionIfSelectionIsInvalid()
1441 if (!hasComposition() || ignoreCompositionSelectionChange() || getCompositionSelection(start, end))
1444 cancelComposition();
1448 void Editor::confirmComposition(const String& text)
1450 setComposition(text, ConfirmComposition);
1453 void Editor::setComposition(const String& text, SetCompositionMode mode)
1455 ASSERT(mode == ConfirmComposition || mode == CancelComposition);
1456 UserTypingGestureIndicator typingGestureIndicator(m_frame);
1458 setIgnoreCompositionSelectionChange(true);
1460 if (mode == CancelComposition)
1461 ASSERT(text == emptyString());
1463 selectComposition();
1465 if (m_frame->selection()->isNone()) {
1466 setIgnoreCompositionSelectionChange(false);
1470 // Dispatch a compositionend event to the focused node.
1471 // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
1472 // the DOM Event specification.
1473 Node* target = m_frame->document()->focusedNode();
1475 RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->document()->domWindow(), text);
1476 target->dispatchEvent(event, IGNORE_EXCEPTION);
1479 // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
1480 // will delete the old composition with an optimized replace operation.
1481 if (text.isEmpty() && mode != CancelComposition)
1482 TypingCommand::deleteSelection(m_frame->document(), 0);
1484 m_compositionNode = 0;
1485 m_customCompositionUnderlines.clear();
1487 insertTextForConfirmedComposition(text);
1489 if (mode == CancelComposition) {
1490 // An open typing command that disagrees about current selection would cause issues with typing later on.
1491 TypingCommand::closeTyping(m_frame);
1494 setIgnoreCompositionSelectionChange(false);
1497 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1499 UserTypingGestureIndicator typingGestureIndicator(m_frame);
1501 setIgnoreCompositionSelectionChange(true);
1503 // Updates styles before setting selection for composition to prevent
1504 // inserting the previous composition text into text nodes oddly.
1505 // See https://bugs.webkit.org/show_bug.cgi?id=46868
1506 m_frame->document()->updateStyleIfNeeded();
1508 selectComposition();
1510 if (m_frame->selection()->isNone()) {
1511 setIgnoreCompositionSelectionChange(false);
1515 Node* target = m_frame->document()->focusedNode();
1517 // Dispatch an appropriate composition event to the focused node.
1518 // We check the composition status and choose an appropriate composition event since this
1519 // function is used for three purposes:
1520 // 1. Starting a new composition.
1521 // Send a compositionstart and a compositionupdate event when this function creates
1522 // a new composition node, i.e.
1523 // m_compositionNode == 0 && !text.isEmpty().
1524 // Sending a compositionupdate event at this time ensures that at least one
1525 // compositionupdate event is dispatched.
1526 // 2. Updating the existing composition node.
1527 // Send a compositionupdate event when this function updates the existing composition
1528 // node, i.e. m_compositionNode != 0 && !text.isEmpty().
1529 // 3. Canceling the ongoing composition.
1530 // Send a compositionend event when function deletes the existing composition node, i.e.
1531 // m_compositionNode != 0 && test.isEmpty().
1532 RefPtr<CompositionEvent> event;
1533 if (!m_compositionNode) {
1534 // We should send a compositionstart event only when the given text is not empty because this
1535 // function doesn't create a composition node when the text is empty.
1536 if (!text.isEmpty()) {
1537 target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->document()->domWindow(), text));
1538 event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->document()->domWindow(), text);
1541 if (!text.isEmpty())
1542 event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->document()->domWindow(), text);
1544 event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->document()->domWindow(), text);
1547 target->dispatchEvent(event, IGNORE_EXCEPTION);
1550 // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
1551 // will delete the old composition with an optimized replace operation.
1553 TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
1555 m_compositionNode = 0;
1556 m_customCompositionUnderlines.clear();
1558 if (!text.isEmpty()) {
1559 TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
1561 // Find out what node has the composition now.
1562 Position base = m_frame->selection()->base().downstream();
1563 Position extent = m_frame->selection()->extent();
1564 Node* baseNode = base.deprecatedNode();
1565 unsigned baseOffset = base.deprecatedEditingOffset();
1566 Node* extentNode = extent.deprecatedNode();
1567 unsigned extentOffset = extent.deprecatedEditingOffset();
1569 if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
1570 m_compositionNode = toText(baseNode);
1571 m_compositionStart = baseOffset;
1572 m_compositionEnd = extentOffset;
1573 m_customCompositionUnderlines = underlines;
1574 size_t numUnderlines = m_customCompositionUnderlines.size();
1575 for (size_t i = 0; i < numUnderlines; ++i) {
1576 m_customCompositionUnderlines[i].startOffset += baseOffset;
1577 m_customCompositionUnderlines[i].endOffset += baseOffset;
1579 if (baseNode->renderer())
1580 baseNode->renderer()->repaint();
1582 unsigned start = min(baseOffset + selectionStart, extentOffset);
1583 unsigned end = min(max(start, baseOffset + selectionEnd), extentOffset);
1584 RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
1585 m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1589 setIgnoreCompositionSelectionChange(false);
1592 void Editor::ignoreSpelling()
1597 RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1599 frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1601 String text = selectedText();
1602 ASSERT(text.length());
1603 textChecker()->ignoreWordInSpellDocument(text);
1606 void Editor::learnSpelling()
1611 // FIXME: On Mac OS X, when use "learn" button on "Spelling and Grammar" panel, we don't call this function. It should remove misspelling markers around the learned word, see <rdar://problem/5396072>.
1613 RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1615 frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1617 String text = selectedText();
1618 ASSERT(text.length());
1619 textChecker()->learnWord(text);
1622 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1624 // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1625 // then we wrap and search from the doc start to (approximately) where we started.
1627 // Start at the end of the selection, search to edge of document. Starting at the selection end makes
1628 // repeated "check spelling" commands work.
1629 VisibleSelection selection(frame()->selection()->selection());
1630 RefPtr<Range> spellingSearchRange(rangeOfContents(frame()->document()));
1632 bool startedWithSelection = false;
1633 if (selection.start().deprecatedNode()) {
1634 startedWithSelection = true;
1635 if (startBeforeSelection) {
1636 VisiblePosition start(selection.visibleStart());
1637 // We match AppKit's rule: Start 1 character before the selection.
1638 VisiblePosition oneBeforeStart = start.previous();
1639 setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1641 setStart(spellingSearchRange.get(), selection.visibleEnd());
1644 Position position = spellingSearchRange->startPosition();
1645 if (!isEditablePosition(position)) {
1646 // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1647 // selection is editable.
1648 // This can happen in Mail for a mix of non-editable and editable content (like Stationary),
1649 // when spell checking the whole document before sending the message.
1650 // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1652 position = firstEditablePositionAfterPositionInRoot(position, frame()->document()->documentElement()).deepEquivalent();
1653 if (position.isNull())
1656 Position rangeCompliantPosition = position.parentAnchoredEquivalent();
1657 spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), IGNORE_EXCEPTION);
1658 startedWithSelection = false; // won't need to wrap
1661 // topNode defines the whole range we want to operate on
1662 Node* topNode = highestEditableRoot(position);
1663 // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
1664 spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), IGNORE_EXCEPTION);
1666 // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1667 // at a word boundary. Going back by one char and then forward by a word does the trick.
1668 if (startedWithSelection) {
1669 VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1670 if (oneBeforeStart.isNotNull())
1671 setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1672 // else we were already at the start of the editable node
1675 if (spellingSearchRange->collapsed(IGNORE_EXCEPTION))
1676 return; // nothing to search in
1678 // Get the spell checker if it is available
1682 // We go to the end of our first range instead of the start of it, just to be sure
1683 // we don't get foiled by any word boundary problems at the start. It means we might
1684 // do a tiny bit more searching.
1685 Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer();
1686 int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();
1688 int misspellingOffset = 0;
1689 GrammarDetail grammarDetail;
1690 int grammarPhraseOffset = 0;
1691 RefPtr<Range> grammarSearchRange;
1692 String badGrammarPhrase;
1693 String misspelledWord;
1695 bool isSpelling = true;
1696 int foundOffset = 0;
1698 RefPtr<Range> firstMisspellingRange;
1699 if (unifiedTextCheckerEnabled()) {
1700 grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
1701 foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1703 misspelledWord = foundItem;
1704 misspellingOffset = foundOffset;
1706 badGrammarPhrase = foundItem;
1707 grammarPhraseOffset = foundOffset;
1710 misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1712 #if USE(GRAMMAR_CHECKING)
1713 grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
1714 if (!misspelledWord.isEmpty()) {
1715 // Stop looking at start of next misspelled word
1716 CharacterIterator chars(grammarSearchRange.get());
1717 chars.advance(misspellingOffset);
1718 grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
1721 if (isGrammarCheckingEnabled())
1722 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1726 // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
1727 // block rather than at a selection).
1728 if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
1729 spellingSearchRange->setStart(topNode, 0, IGNORE_EXCEPTION);
1730 // going until the end of the very first chunk we tested is far enough
1731 spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, IGNORE_EXCEPTION);
1733 if (unifiedTextCheckerEnabled()) {
1734 grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
1735 foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1737 misspelledWord = foundItem;
1738 misspellingOffset = foundOffset;
1740 badGrammarPhrase = foundItem;
1741 grammarPhraseOffset = foundOffset;
1744 misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1746 #if USE(GRAMMAR_CHECKING)
1747 grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
1748 if (!misspelledWord.isEmpty()) {
1749 // Stop looking at start of next misspelled word
1750 CharacterIterator chars(grammarSearchRange.get());
1751 chars.advance(misspellingOffset);
1752 grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
1755 if (isGrammarCheckingEnabled())
1756 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1761 if (!badGrammarPhrase.isEmpty()) {
1762 ASSERT(WTF_USE_GRAMMAR_CHECKING);
1763 // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
1764 // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
1765 // panel, and store a marker so we draw the green squiggle later.
1767 ASSERT(badGrammarPhrase.length() > 0);
1768 ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
1770 // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
1771 RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
1772 frame()->selection()->setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
1773 frame()->selection()->revealSelection();
1775 client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
1776 frame()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
1777 } else if (!misspelledWord.isEmpty()) {
1778 // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
1779 // a marker so we draw the red squiggle later.
1781 RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
1782 frame()->selection()->setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
1783 frame()->selection()->revealSelection();
1785 client()->updateSpellingUIWithMisspelledWord(misspelledWord);
1786 frame()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
1790 String Editor::misspelledWordAtCaretOrRange(Node* clickedNode) const
1792 if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
1795 VisibleSelection selection = m_frame->selection()->selection();
1796 if (!selection.isContentEditable() || selection.isNone())
1799 VisibleSelection wordSelection(selection.base());
1800 wordSelection.expandUsingGranularity(WordGranularity);
1801 RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
1803 // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
1804 // selection exactly match the word selection.
1805 if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
1808 String word = wordRange->text();
1809 if (word.isEmpty() || !client())
1812 int wordLength = word.length();
1813 int misspellingLocation = -1;
1814 int misspellingLength = 0;
1815 textChecker()->checkSpellingOfString(word.characters(), wordLength, &misspellingLocation, &misspellingLength);
1817 return misspellingLength == wordLength ? word : String();
1820 String Editor::misspelledSelectionString() const
1822 String selectedString = selectedText();
1823 int length = selectedString.length();
1824 if (!length || !client())
1827 int misspellingLocation = -1;
1828 int misspellingLength = 0;
1829 textChecker()->checkSpellingOfString(selectedString.characters(), length, &misspellingLocation, &misspellingLength);
1831 // The selection only counts as misspelled if the selected text is exactly one misspelled word
1832 if (misspellingLength != length)
1835 // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
1836 // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
1837 // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
1838 // or a grammar error.
1839 client()->updateSpellingUIWithMisspelledWord(selectedString);
1841 return selectedString;
1844 bool Editor::isSelectionUngrammatical()
1846 #if USE(GRAMMAR_CHECKING)
1847 Vector<String> ignoredGuesses;
1848 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1851 return TextCheckingHelper(client(), range).isUngrammatical(ignoredGuesses);
1857 Vector<String> Editor::guessesForUngrammaticalSelection()
1859 #if USE(GRAMMAR_CHECKING)
1860 Vector<String> guesses;
1861 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1864 // Ignore the result of isUngrammatical; we just want the guesses, whether or not there are any
1865 TextCheckingHelper(client(), range).isUngrammatical(guesses);
1868 return Vector<String>();
1872 Vector<String> Editor::guessesForMisspelledWord(const String& word) const
1874 ASSERT(word.length());
1876 Vector<String> guesses;
1878 textChecker()->getGuessesForWord(word, String(), guesses);
1882 Vector<String> Editor::guessesForMisspelledOrUngrammatical(bool& misspelled, bool& ungrammatical)
1884 if (unifiedTextCheckerEnabled()) {
1885 RefPtr<Range> range;
1886 FrameSelection* frameSelection = frame()->selection();
1887 if (frameSelection->isCaret() && behavior().shouldAllowSpellingSuggestionsWithoutSelection()) {
1888 VisibleSelection wordSelection = VisibleSelection(frameSelection->base());
1889 wordSelection.expandUsingGranularity(WordGranularity);
1890 range = wordSelection.toNormalizedRange();
1892 range = frameSelection->toNormalizedRange();
1894 return Vector<String>();
1895 return TextCheckingHelper(client(), range).guessesForMisspelledOrUngrammaticalRange(isGrammarCheckingEnabled(), misspelled, ungrammatical);
1898 String misspelledWord = behavior().shouldAllowSpellingSuggestionsWithoutSelection() ? misspelledWordAtCaretOrRange(m_frame->document()->focusedNode()) : misspelledSelectionString();
1899 misspelled = !misspelledWord.isEmpty();
1902 ungrammatical = false;
1903 return guessesForMisspelledWord(misspelledWord);
1905 if (isGrammarCheckingEnabled() && isSelectionUngrammatical()) {
1906 ungrammatical = true;
1907 return guessesForUngrammaticalSelection();
1909 ungrammatical = false;
1910 return Vector<String>();
1913 void Editor::showSpellingGuessPanel()
1916 LOG_ERROR("No NSSpellChecker");
1920 if (client()->spellingUIIsShowing()) {
1921 client()->showSpellingUI(false);
1925 advanceToNextMisspelling(true);
1926 client()->showSpellingUI(true);
1929 bool Editor::spellingPanelIsShowing()
1933 return client()->spellingUIIsShowing();
1936 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1938 RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
1939 if (selectedRange) {
1940 frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1941 frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Grammar);
1945 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1947 markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
1950 void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
1952 #if !USE(AUTOMATIC_TEXT_REPLACEMENT)
1953 UNUSED_PARAM(doReplacement);
1956 if (unifiedTextCheckerEnabled()) {
1957 m_alternativeTextController->applyPendingCorrection(selectionAfterTyping);
1959 TextCheckingTypeMask textCheckingOptions = 0;
1961 if (isContinuousSpellCheckingEnabled())
1962 textCheckingOptions |= TextCheckingTypeSpelling;
1964 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1966 && (isAutomaticQuoteSubstitutionEnabled()
1967 || isAutomaticLinkDetectionEnabled()
1968 || isAutomaticDashSubstitutionEnabled()
1969 || isAutomaticTextReplacementEnabled()
1970 || ((textCheckingOptions & TextCheckingTypeSpelling) && isAutomaticSpellingCorrectionEnabled())))
1971 textCheckingOptions |= TextCheckingTypeReplacement;
1973 if (!(textCheckingOptions & (TextCheckingTypeSpelling | TextCheckingTypeReplacement)))
1976 if (isGrammarCheckingEnabled())
1977 textCheckingOptions |= TextCheckingTypeGrammar;
1979 VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
1980 if (textCheckingOptions & TextCheckingTypeGrammar) {
1981 VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
1982 markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
1984 markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
1988 if (!isContinuousSpellCheckingEnabled())
1991 // Check spelling of one word
1992 RefPtr<Range> misspellingRange;
1993 markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
1995 // Autocorrect the misspelled word.
1996 if (!misspellingRange)
1999 // Get the misspelled word.
2000 const String misspelledWord = plainText(misspellingRange.get());
2001 String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
2003 // If autocorrected word is non empty, replace the misspelled word by this word.
2004 if (!autocorrectedString.isEmpty()) {
2005 VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
2006 if (newSelection != frame()->selection()->selection()) {
2007 if (!frame()->selection()->shouldChangeSelection(newSelection))
2009 frame()->selection()->setSelection(newSelection);
2012 if (!frame()->editor()->shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
2014 frame()->editor()->replaceSelectionWithText(autocorrectedString, false, false);
2016 // Reset the charet one character further.
2017 frame()->selection()->moveTo(frame()->selection()->end());
2018 frame()->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2021 if (!isGrammarCheckingEnabled())
2024 // Check grammar of entire sentence
2025 markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
2028 void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
2030 // This function is called with a selection already expanded to word boundaries.
2031 // Might be nice to assert that here.
2033 // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
2034 // grammar checking can only be on if spell checking is also on.
2035 if (!isContinuousSpellCheckingEnabled())
2038 RefPtr<Range> searchRange(selection.toNormalizedRange());
2042 // If we're not in an editable node, bail.
2043 Node* editableNode = searchRange->startContainer();
2044 if (!editableNode || !editableNode->rendererIsEditable())
2047 if (!isSpellCheckingEnabledFor(editableNode))
2050 // Get the spell checker if it is available
2054 TextCheckingHelper checker(client(), searchRange);
2056 checker.markAllMisspellings(firstMisspellingRange);
2058 ASSERT(WTF_USE_GRAMMAR_CHECKING);
2059 if (isGrammarCheckingEnabled())
2060 checker.markAllBadGrammar();
2064 bool Editor::isSpellCheckingEnabledFor(Node* node) const
2068 const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
2069 if (!focusedElement)
2071 return focusedElement->isSpellCheckingEnabled();
2074 bool Editor::isSpellCheckingEnabledInFocusedNode() const
2076 return isSpellCheckingEnabledFor(m_frame->selection()->start().deprecatedNode());
2079 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
2081 markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
2084 void Editor::markBadGrammar(const VisibleSelection& selection)
2086 ASSERT(WTF_USE_GRAMMAR_CHECKING);
2087 RefPtr<Range> firstMisspellingRange;
2088 markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
2091 void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
2094 ASSERT(unifiedTextCheckerEnabled());
2096 // There shouldn't be pending autocorrection at this moment.
2097 ASSERT(!m_alternativeTextController->hasPendingCorrection());
2099 bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2100 bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2102 // This function is called with selections already expanded to word boundaries.
2103 if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
2106 // If we're not in an editable node, bail.
2107 Node* editableNode = spellingRange->startContainer();
2108 if (!editableNode || !editableNode->rendererIsEditable())
2111 if (!isSpellCheckingEnabledFor(editableNode))
2114 Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
2115 TextCheckingParagraph paragraphToCheck(rangeToCheck);
2116 if (paragraphToCheck.isRangeEmpty() || paragraphToCheck.isEmpty())
2118 RefPtr<Range> paragraphRange = paragraphToCheck.paragraphRange();
2120 bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
2122 // In asynchronous mode, we intentionally check paragraph-wide sentence.
2123 RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessIncremental, asynchronous ? paragraphRange : rangeToCheck, paragraphRange);
2126 m_spellChecker->requestCheckingFor(request);
2130 Vector<TextCheckingResult> results;
2131 checkTextOfParagraph(textChecker(), paragraphToCheck.textCharacters(), paragraphToCheck.textLength(),
2132 resolveTextCheckingTypeMask(textCheckingOptions), results);
2133 markAndReplaceFor(request, results);
2136 static bool isAutomaticTextReplacementType(TextCheckingType type)
2139 case TextCheckingTypeNone:
2140 case TextCheckingTypeSpelling:
2141 case TextCheckingTypeGrammar:
2143 case TextCheckingTypeLink:
2144 case TextCheckingTypeQuote:
2145 case TextCheckingTypeDash:
2146 case TextCheckingTypeReplacement:
2147 case TextCheckingTypeCorrection:
2148 case TextCheckingTypeShowCorrectionPanel:
2151 ASSERT_NOT_REACHED();
2155 static void correctSpellcheckingPreservingTextCheckingParagraph(TextCheckingParagraph& paragraph, PassRefPtr<Range> rangeToReplace, const String& replacement, int resultLocation, int resultLength)
2157 ContainerNode* scope = toContainerNode(highestAncestor(paragraph.paragraphRange()->startContainer()));
2159 size_t paragraphLocation;
2160 size_t paragraphLength;
2161 TextIterator::getLocationAndLengthFromRange(scope, paragraph.paragraphRange().get(), paragraphLocation, paragraphLength);
2163 applyCommand(SpellingCorrectionCommand::create(rangeToReplace, replacement));
2165 // TextCheckingParagraph may be orphaned after SpellingCorrectionCommand mutated DOM.
2166 // See <rdar://10305315>, http://webkit.org/b/89526.
2168 RefPtr<Range> newParagraphRange = TextIterator::rangeFromLocationAndLength(scope, paragraphLocation, paragraphLength + replacement.length() - resultLength);
2170 paragraph = TextCheckingParagraph(TextIterator::subrange(newParagraphRange.get(), resultLocation, replacement.length()), newParagraphRange);
2173 void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
2177 TextCheckingTypeMask textCheckingOptions = request->data().mask();
2178 TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
2180 const bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
2181 const bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2182 const bool shouldMarkLink = textCheckingOptions & TextCheckingTypeLink;
2183 const bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
2184 const bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2185 const bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
2186 #if !USE(AUTOCORRECTION_PANEL)
2187 ASSERT(!shouldShowCorrectionPanel);
2190 // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2191 int selectionOffset = 0;
2192 bool useAmbiguousBoundaryOffset = false;
2193 bool selectionChanged = false;
2194 bool restoreSelectionAfterChange = false;
2195 bool adjustSelectionForParagraphBoundaries = false;
2197 if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2198 if (m_frame->selection()->selectionType() == VisibleSelection::CaretSelection) {
2199 // Attempt to save the caret position so we can restore it later if needed
2200 Position caretPosition = m_frame->selection()->end();
2201 selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
2202 restoreSelectionAfterChange = true;
2203 if (selectionOffset > 0 && (selectionOffset > paragraph.textLength() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2204 adjustSelectionForParagraphBoundaries = true;
2205 if (selectionOffset > 0 && selectionOffset <= paragraph.textLength() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
2206 useAmbiguousBoundaryOffset = true;
2210 int offsetDueToReplacement = 0;
2212 for (unsigned i = 0; i < results.size(); i++) {
2213 const int spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
2214 const TextCheckingType resultType = results[i].type;
2215 const int resultLocation = results[i].location + offsetDueToReplacement;
2216 const int resultLength = results[i].length;
2217 const int resultEndLocation = resultLocation + resultLength;
2218 const String& replacement = results[i].replacement;
2219 const bool resultEndsAtAmbiguousBoundary = useAmbiguousBoundaryOffset && resultEndLocation == selectionOffset - 1;
2221 // Only mark misspelling if:
2222 // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2223 // 2. Result falls within spellingRange.
2224 // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2225 // "wouldn'" as misspelled right after apostrophe is typed.
2226 if (shouldMarkSpelling && !shouldShowCorrectionPanel && resultType == TextCheckingTypeSpelling
2227 && resultLocation >= paragraph.checkingStart() && resultEndLocation <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2228 ASSERT(resultLength > 0 && resultLocation >= 0);
2229 RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
2230 if (!m_alternativeTextController->isSpellingMarkerAllowed(misspellingRange))
2232 misspellingRange->startContainer()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling, replacement);
2233 } else if (shouldMarkGrammar && resultType == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
2234 ASSERT(resultLength > 0 && resultLocation >= 0);
2235 const Vector<GrammarDetail>& details = results[i].details;
2236 for (unsigned j = 0; j < details.size(); j++) {
2237 const GrammarDetail& detail = details[j];
2238 ASSERT(detail.length > 0 && detail.location >= 0);
2239 if (paragraph.checkingRangeCovers(resultLocation + detail.location, detail.length)) {
2240 RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail.location, detail.length);
2241 badGrammarRange->startContainer()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail.userDescription);
2244 } else if (resultEndLocation <= spellingRangeEndOffset && resultEndLocation >= paragraph.checkingStart()
2245 && isAutomaticTextReplacementType(resultType)) {
2246 // In this case the result range just has to touch the spelling range, so we can handle replacing non-word text such as punctuation.
2247 ASSERT(resultLength > 0 && resultLocation >= 0);
2249 if (shouldShowCorrectionPanel && (resultEndLocation < spellingRangeEndOffset
2250 || !(resultType & (TextCheckingTypeReplacement | TextCheckingTypeCorrection))))
2253 // Apply replacement if:
2254 // 1. The replacement length is non-zero.
2255 // 2. The result doesn't end at an ambiguous boundary.
2256 // (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2257 bool doReplacement = replacement.length() > 0 && !resultEndsAtAmbiguousBoundary;
2258 RefPtr<Range> rangeToReplace = paragraph.subrange(resultLocation, resultLength);
2260 // adding links should be done only immediately after they are typed
2261 if (resultType == TextCheckingTypeLink && selectionOffset != resultEndLocation + 1)
2264 if (!(shouldPerformReplacement || shouldCheckForCorrection || shouldMarkLink) || !doReplacement)
2267 String replacedString = plainText(rangeToReplace.get());
2268 const bool existingMarkersPermitReplacement = m_alternativeTextController->processMarkersOnTextToBeReplacedByResult(&results[i], rangeToReplace.get(), replacedString);
2269 if (!existingMarkersPermitReplacement)
2272 if (shouldShowCorrectionPanel) {
2273 if (resultEndLocation == spellingRangeEndOffset) {
2274 // We only show the correction panel on the last word.
2275 m_alternativeTextController->show(rangeToReplace, replacement);
2278 // If this function is called for showing correction panel, we ignore other correction or replacement.
2282 VisibleSelection selectionToReplace(rangeToReplace.get(), DOWNSTREAM);
2283 if (selectionToReplace != m_frame->selection()->selection()) {
2284 if (!m_frame->selection()->shouldChangeSelection(selectionToReplace))
2288 if (resultType == TextCheckingTypeLink) {
2289 m_frame->selection()->setSelection(selectionToReplace);
2290 selectionChanged = true;
2291 restoreSelectionAfterChange = false;
2292 if (canEditRichly())
2293 applyCommand(CreateLinkCommand::create(m_frame->document(), replacement));
2294 } else if (canEdit() && shouldInsertText(replacement, rangeToReplace.get(), EditorInsertActionTyped)) {
2295 correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, resultLocation, resultLength);
2297 if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
2298 if (Element* root = m_frame->selection()->selection().rootEditableElement())
2299 cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured, true);
2302 // Skip all other results for the replaced text.
2303 while (i + 1 < results.size() && results[i + 1].location + offsetDueToReplacement <= resultLocation)
2306 selectionChanged = true;
2307 offsetDueToReplacement += replacement.length() - resultLength;
2308 if (resultLocation < selectionOffset)
2309 selectionOffset += replacement.length() - resultLength;
2311 // Add a marker so that corrections can easily be undone and won't be re-corrected.
2312 if (resultType == TextCheckingTypeCorrection)
2313 m_alternativeTextController->markCorrection(paragraph.subrange(resultLocation, replacement.length()), replacedString);
2318 if (selectionChanged) {
2319 TextCheckingParagraph extendedParagraph(paragraph);
2320 // Restore the caret position if we have made any replacements
2321 extendedParagraph.expandRangeToNextEnd();
2322 if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2323 RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
2324 m_frame->selection()->moveTo(selectionRange->endPosition(), DOWNSTREAM);
2325 if (adjustSelectionForParagraphBoundaries)
2326 m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2328 // If this fails for any reason, the fallback is to go one position beyond the last replacement
2329 m_frame->selection()->moveTo(m_frame->selection()->end());
2330 m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2335 void Editor::changeBackToReplacedString(const String& replacedString)
2337 ASSERT(unifiedTextCheckerEnabled());
2339 if (replacedString.isEmpty())
2342 RefPtr<Range> selection = selectedRange();
2343 if (!shouldInsertText(replacedString, selection.get(), EditorInsertActionPasted))
2346 m_alternativeTextController->recordAutocorrectionResponseReversed(replacedString, selection);
2347 TextCheckingParagraph paragraph(selection);
2348 replaceSelectionWithText(replacedString, false, false);
2349 RefPtr<Range> changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2350 changedRange->startContainer()->document()->markers()->addMarker(changedRange.get(), DocumentMarker::Replacement, String());
2351 m_alternativeTextController->markReversed(changedRange.get());
2355 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2357 if (unifiedTextCheckerEnabled()) {
2358 if (!isContinuousSpellCheckingEnabled())
2361 // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
2362 TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling;
2363 if (markGrammar && isGrammarCheckingEnabled())
2364 textCheckingOptions |= TextCheckingTypeGrammar;
2365 markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
2369 RefPtr<Range> firstMisspellingRange;
2370 markMisspellings(spellingSelection, firstMisspellingRange);
2372 markBadGrammar(grammarSelection);
2375 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2377 m_alternativeTextController->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2380 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2382 if (!m_alternativeTextController->shouldRemoveMarkersUponEditing() && (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)))
2385 // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2386 // several scenarios:
2387 // 1. Insert in the middle of a word.
2388 // 2. Appending non whitespace at the beginning of word.
2389 // 3. Appending non whitespace at the end of word.
2390 // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2391 // remove the markers on that word.
2392 // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2393 // selection, and remove words between the selection boundaries.
2395 VisiblePosition startOfSelection = frame()->selection()->selection().start();
2396 VisiblePosition endOfSelection = frame()->selection()->selection().end();
2397 if (startOfSelection.isNull())
2399 // First word is the word that ends after or on the start of selection.
2400 VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2401 VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2402 // Last word is the word that begins before or on the end of selection
2403 VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2404 VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2406 if (startOfFirstWord.isNull()) {
2407 startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2408 endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2411 if (endOfLastWord.isNull()) {
2412 startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2413 endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2416 // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2417 // we choose next word as the first word.
2418 if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2419 startOfFirstWord = nextWordPosition(startOfFirstWord);
2420 endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2421 if (startOfFirstWord == endOfSelection)
2425 // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2426 // we choose previous word as the last word.
2427 if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2428 startOfLastWord = previousWordPosition(startOfLastWord);
2429 endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2430 if (endOfLastWord == startOfSelection)
2434 if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2437 // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2438 // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2439 // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2440 // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2441 // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2442 // of marker that contains the word in question, and remove marker on that whole range.
2443 Document* document = m_frame->document();
2444 RefPtr<Range> wordRange = Range::create(document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2446 Vector<DocumentMarker*> markers = document->markers()->markersInRange(wordRange.get(), DocumentMarker::DictationAlternatives);
2447 for (size_t i = 0; i < markers.size(); ++i)
2448 m_alternativeTextController->removeDictationAlternativesForMarker(markers[i]);
2450 document->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption | DocumentMarker::DictationAlternatives, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2451 document->markers()->clearDescriptionOnMarkersIntersectingRange(wordRange.get(), DocumentMarker::Replacement);
2454 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2456 m_alternativeTextController->deletedAutocorrectionAtPosition(position, originalString);
2459 PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
2461 Document* document = m_frame->documentAtPoint(windowPoint);
2465 Frame* frame = document->frame();
2467 FrameView* frameView = frame->view();
2470 IntPoint framePoint = frameView->windowToContents(windowPoint);
2471 VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2473 return avoidIntersectionWithDeleteButtonController(selection.toNormalizedRange().get());
2476 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
2478 if (m_ignoreCompositionSelectionChange)
2481 m_frame->selection()->revealSelection(alignment, revealExtentOption);
2484 void Editor::setIgnoreCompositionSelectionChange(bool ignore)
2486 if (m_ignoreCompositionSelectionChange == ignore)
2489 m_ignoreCompositionSelectionChange = ignore;
2491 revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
2494 PassRefPtr<Range> Editor::compositionRange() const
2496 if (!m_compositionNode)
2498 unsigned length = m_compositionNode->length();
2499 unsigned start = min(m_compositionStart, length);
2500 unsigned end = min(max(start, m_compositionEnd), length);
2503 return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
2506 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
2508 if (!m_compositionNode)
2510 Position start = m_frame->selection()->start();
2511 if (start.deprecatedNode() != m_compositionNode)
2513 Position end = m_frame->selection()->end();
2514 if (end.deprecatedNode() != m_compositionNode)
2517 if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
2519 if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
2522 selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
2523 selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
2527 bool Editor::setSelectionOffsets(int selectionStart, int selectionEnd)
2529 Element* rootEditableElement = m_frame->selection()->rootEditableElement();
2530 if (!rootEditableElement)
2533 RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(rootEditableElement, selectionStart, selectionEnd - selectionStart);
2537 return m_frame->selection()->setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, false);
2540 void Editor::transpose()
2545 VisibleSelection selection = m_frame->selection()->selection();
2546 if (!selection.isCaret())
2549 // Make a selection that goes back one character and forward two characters.
2550 VisiblePosition caret = selection.visibleStart();
2551 VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
2552 VisiblePosition previous = next.previous();
2553 if (next == previous)
2555 previous = previous.previous();
2556 if (!inSameParagraph(next, previous))
2558 RefPtr<Range> range = makeRange(previous, next);
2561 VisibleSelection newSelection(range.get(), DOWNSTREAM);
2563 // Transpose the two characters.
2564 String text = plainText(range.get());
2565 if (text.length() != 2)
2567 String transposed = text.right(1) + text.left(1);
2569 // Select the two characters.
2570 if (newSelection != m_frame->selection()->selection()) {
2571 if (!m_frame->selection()->shouldChangeSelection(newSelection))
2573 m_frame->selection()->setSelection(newSelection);
2576 // Insert the transposed characters.
2577 if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
2579 replaceSelectionWithText(transposed, false, false);
2582 void Editor::addToKillRing(Range* range, bool prepend)
2584 if (m_shouldStartNewKillRingSequence)
2585 killRing()->startNewSequence();
2587 String text = plainText(range);
2589 killRing()->prepend(text);
2591 killRing()->append(text);
2592 m_shouldStartNewKillRingSequence = false;
2595 void Editor::startAlternativeTextUITimer()
2597 m_alternativeTextController->startAlternativeTextUITimer(AlternativeTextTypeCorrection);
2600 void Editor::handleAlternativeTextUIResult(const String& correction)
2602 m_alternativeTextController->handleAlternativeTextUIResult(correction);
2606 void Editor::dismissCorrectionPanelAsIgnored()
2608 m_alternativeTextController->dismiss(ReasonForDismissingAlternativeTextIgnored);
2611 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, FrameSelection::SetSelectionOptions options)
2613 // If the new selection is orphaned, then don't update the selection.
2614 if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
2617 // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
2618 // because there is work that it must do in this situation.
2619 // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
2620 // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
2621 bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection()->selection();
2622 if (selectionDidNotChangeDOMPosition || m_frame->selection()->shouldChangeSelection(newSelection))
2623 m_frame->selection()->setSelection(newSelection, options);
2625 // Some editing operations change the selection visually without affecting its position within the DOM.
2626 // For example when you press return in the following (the caret is marked by ^):
2627 // <div contentEditable="true"><div>^Hello</div></div>
2628 // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
2629 // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
2630 // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
2631 // starts a new kill ring sequence, but we want to do these things (matches AppKit).
2632 if (selectionDidNotChangeDOMPosition && client())
2633 client()->respondToChangedSelection(m_frame);
2636 String Editor::selectedText() const
2638 return selectedText(TextIteratorDefaultBehavior);
2641 String Editor::selectedTextForClipboard() const
2643 if (m_frame->settings() && m_frame->settings()->selectionIncludesAltImageText())
2644 return selectedText(TextIteratorEmitsImageAltText);
2645 return selectedText();
2648 String Editor::selectedText(TextIteratorBehavior behavior) const
2650 // We remove '\0' characters because they are not visibly rendered to the user.
2651 return plainText(m_frame->selection()->toNormalizedRange().get(), behavior).replaceWithLiteral('\0', "");
2654 IntRect Editor::firstRectForRange(Range* range) const
2656 LayoutUnit extraWidthToEndOfLine = 0;
2657 ASSERT(range->startContainer());
2658 ASSERT(range->endContainer());
2660 IntRect startCaretRect = RenderedPosition(VisiblePosition(range->startPosition()).deepEquivalent(), DOWNSTREAM).absoluteRect(&extraWidthToEndOfLine);
2661 if (startCaretRect == LayoutRect())
2664 IntRect endCaretRect = RenderedPosition(VisiblePosition(range->endPosition()).deepEquivalent(), UPSTREAM).absoluteRect();
2665 if (endCaretRect == LayoutRect())
2668 if (startCaretRect.y() == endCaretRect.y()) {
2669 // start and end are on the same line
2670 return IntRect(min(startCaretRect.x(), endCaretRect.x()),
2672 abs(endCaretRect.x() - startCaretRect.x()),
2673 max(startCaretRect.height(), endCaretRect.height()));
2676 // start and end aren't on the same line, so go from start to the end of its line
2677 return IntRect(startCaretRect.x(),
2679 startCaretRect.width() + extraWidthToEndOfLine,
2680 startCaretRect.height());
2683 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
2685 return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
2688 void Editor::computeAndSetTypingStyle(StylePropertySet* style, EditAction editingAction)
2690 if (!style || style->isEmpty()) {
2691 m_frame->selection()->clearTypingStyle();
2695 // Calculate the current typing style.
2696 RefPtr<EditingStyle> typingStyle;
2697 if (m_frame->selection()->typingStyle()) {
2698 typingStyle = m_frame->selection()->typingStyle()->copy();
2699 typingStyle->overrideWithStyle(style);
2701 typingStyle = EditingStyle::create(style);
2703 typingStyle->prepareToApplyAt(m_frame->selection()->selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
2705 // Handle block styles, substracting these from the typing style.
2706 RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
2707 if (!blockStyle->isEmpty())
2708 applyCommand(ApplyStyleCommand::create(m_frame->document(), blockStyle.get(), editingAction));
2710 // Set the remaining style as the typing style.
2711 m_frame->selection()->setTypingStyle(typingStyle);
2714 void Editor::textFieldDidBeginEditing(Element* e)
2717 client()->textFieldDidBeginEditing(e);
2720 void Editor::textFieldDidEndEditing(Element* e)
2722 dismissCorrectionPanelAsIgnored();
2724 client()->textFieldDidEndEditing(e);
2727 void Editor::textDidChangeInTextField(Element* e)
2730 client()->textDidChangeInTextField(e);
2733 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
2736 return client()->doTextFieldCommandFromEvent(e, ke);
2741 void Editor::textWillBeDeletedInTextField(Element* input)
2744 client()->textWillBeDeletedInTextField(input);
2747 void Editor::textDidChangeInTextArea(Element* e)
2750 client()->textDidChangeInTextArea(e);
2753 void Editor::applyEditingStyleToBodyElement() const
2755 RefPtr<NodeList> list = m_frame->document()->getElementsByTagName("body");
2756 unsigned len = list->length();
2757 for (unsigned i = 0; i < len; i++)
2758 applyEditingStyleToElement(toElement(list->item(i)));
2761 void Editor::applyEditingStyleToElement(Element* element) const
2765 ASSERT(element->isStyledElement());
2766 if (!element->isStyledElement())
2769 // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
2770 CSSStyleDeclaration* style = static_cast<StyledElement*>(element)->style();
2771 style->setPropertyInternal(CSSPropertyWordWrap, "break-word", false, IGNORE_EXCEPTION);
2772 style->setPropertyInternal(CSSPropertyWebkitNbspMode, "space", false, IGNORE_EXCEPTION);
2773 style->setPropertyInternal(CSSPropertyWebkitLineBreak, "after-white-space", false, IGNORE_EXCEPTION);
2776 // Searches from the beginning of the document if nothing is selected.
2777 bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
2779 FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0);
2780 return findString(target, options);
2783 bool Editor::findString(const String& target, FindOptions options)
2785 VisibleSelection selection = m_frame->selection()->selection();
2787 RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
2792 m_frame->selection()->setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
2793 m_frame->selection()->revealSelection();
2797 PassRefPtr<Range> Editor::findStringAndScrollToVisible(const String& target, Range* previousMatch, FindOptions options)
2799 RefPtr<Range> nextMatch = rangeOfString(target, previousMatch, options);
2803 nextMatch->firstNode()->renderer()->scrollRectToVisible(nextMatch->boundingBox(),
2804 ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
2806 return nextMatch.release();
2809 PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
2811 if (target.isEmpty())
2814 // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
2815 // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
2816 RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2818 bool forward = !(options & Backwards);
2819 bool startInReferenceRange = referenceRange && (options & StartInSelection);
2820 if (referenceRange) {
2822 searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
2824 searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
2827 RefPtr<Node> shadowTreeRoot = referenceRange && referenceRange->startContainer() ? referenceRange->startContainer()->nonBoundaryShadowTreeRootNode() : 0;
2828 if (shadowTreeRoot) {
2830 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2832 searchRange->setStart(shadowTreeRoot.get(), 0);
2835 RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options));
2836 // If we started in the reference range and the found range exactly matches the reference range, find again.
2837 // Build a selection with the found range to remove collapsed whitespace.
2838 // Compare ranges instead of selection objects to ignore the way that the current selection was made.
2839 if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
2840 searchRange = rangeOfContents(m_frame->document());
2842 searchRange->setStart(referenceRange->endPosition());
2844 searchRange->setEnd(referenceRange->startPosition());
2846 if (shadowTreeRoot) {
2848 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2850 searchRange->setStart(shadowTreeRoot.get(), 0);
2853 resultRange = findPlainText(searchRange.get(), target, options);
2856 // If nothing was found in the shadow tree, search in main content following the shadow tree.
2857 if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && shadowTreeRoot) {
2858 searchRange = rangeOfContents(m_frame->document());
2860 searchRange->setStartAfter(shadowTreeRoot->shadowHost());
2862 searchRange->setEndBefore(shadowTreeRoot->shadowHost());
2864 resultRange = findPlainText(searchRange.get(), target, options);
2867 // If we didn't find anything and we're wrapping, search again in the entire document (this will
2868 // redundantly re-search the area already searched in some cases).
2869 if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && options & WrapAround) {
2870 searchRange = rangeOfContents(m_frame->document());
2871 resultRange = findPlainText(searchRange.get(), target, options);
2872 // We used to return false here if we ended up with the same range that we started with
2873 // (e.g., the reference range was already the only instance of this text). But we decided that
2874 // this should be a success case instead, so we'll just fall through in that case.
2877 return resultRange->collapsed(ASSERT_NO_EXCEPTION) ? 0 : resultRange.release();
2880 static bool isFrameInRange(Frame* frame, Range* range)
2882 bool inRange = false;
2883 for (HTMLFrameOwnerElement* ownerElement = frame->ownerElement(); ownerElement; ownerElement = ownerElement->document()->ownerElement()) {
2884 if (ownerElement->document() == range->ownerDocument()) {
2885 inRange = range->intersectsNode(ownerElement, IGNORE_EXCEPTION);
2892 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches, Vector<RefPtr<Range> >* matches)
2894 if (target.isEmpty())
2897 RefPtr<Range> searchRange;
2899 if (range->ownerDocument() == m_frame->document())
2900 searchRange = range;
2901 else if (!isFrameInRange(m_frame, range))
2905 searchRange = rangeOfContents(m_frame->document());
2907 Node* originalEndContainer = searchRange->endContainer();
2908 int originalEndOffset = searchRange->endOffset();
2910 unsigned matchCount = 0;
2912 RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options & ~Backwards));
2913 if (resultRange->collapsed(IGNORE_EXCEPTION)) {
2914 if (!resultRange->startContainer()->isInShadowTree())
2917 searchRange->setStartAfter(resultRange->startContainer()->shadowHost(), IGNORE_EXCEPTION);
2918 searchRange->setEnd(originalEndContainer, originalEndOffset, IGNORE_EXCEPTION);
2924 matches->append(resultRange);
2927 m_frame->document()->markers()->addMarker(resultRange.get(), DocumentMarker::TextMatch);
2929 // Stop looking if we hit the specified limit. A limit of 0 means no limit.
2930 if (limit > 0 && matchCount >= limit)
2933 // Set the new start for the search range to be the end of the previous
2934 // result range. There is no need to use a VisiblePosition here,
2935 // since findPlainText will use a TextIterator to go over the visible
2937 searchRange->setStart(resultRange->endContainer(IGNORE_EXCEPTION), resultRange->endOffset(IGNORE_EXCEPTION), IGNORE_EXCEPTION);
2939 Node* shadowTreeRoot = searchRange->shadowRoot();
2940 if (searchRange->collapsed(IGNORE_EXCEPTION) && shadowTreeRoot)
2941 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), IGNORE_EXCEPTION);
2944 if (markMatches || matches) {
2945 // Do a "fake" paint in order to execute the code that computes the rendered rect for each text match.
2946 if (m_frame->view() && m_frame->contentRenderer()) {
2947 m_frame->document()->updateLayout(); // Ensure layout is up to date.
2948 LayoutRect visibleRect = m_frame->view()->visibleContentRect();
2949 if (!visibleRect.isEmpty()) {
2950 GraphicsContext context((PlatformGraphicsContext*)0);
2951 context.setPaintingDisabled(true);
2953 PaintBehavior oldBehavior = m_frame->view()->paintBehavior();
2954 m_frame->view()->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
2955 m_frame->view()->paintContents(&context, enclosingIntRect(visibleRect));
2956 m_frame->view()->setPaintBehavior(oldBehavior);
2964 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
2966 if (flag == m_areMarkedTextMatchesHighlighted)
2969 m_areMarkedTextMatchesHighlighted = flag;
2970 m_frame->document()->markers()->repaintMarkers(DocumentMarker::TextMatch);
2973 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
2975 m_alternativeTextController->stopPendingCorrection(oldSelection);
2977 bool closeTyping = options & FrameSelection::CloseTyping;
2978 bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
2979 bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
2980 if (isContinuousSpellCheckingEnabled) {
2981 VisibleSelection newAdjacentWords;
2982 VisibleSelection newSelectedSentence;
2983 bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
2984 if (m_frame->selection()->selection().isContentEditable() || caretBrowsing) {
2985 VisiblePosition newStart(m_frame->selection()->selection().visibleStart());
2986 newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
2987 if (isContinuousGrammarCheckingEnabled)
2988 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
2991 // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
2992 bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
2994 // When typing we check spelling elsewhere, so don't redo it here.
2995 // If this is a change in selection resulting from a delete operation,
2996 // oldSelection may no longer be in the document.
2997 if (shouldCheckSpellingAndGrammar && closeTyping && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
2998 VisiblePosition oldStart(oldSelection.visibleStart());
2999 VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
3000 if (oldAdjacentWords != newAdjacentWords) {
3001 if (isContinuousGrammarCheckingEnabled) {
3002 VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
3003 markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
3005 markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
3009 if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
3010 if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3011 m_frame->document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3013 if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
3014 if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3015 m_frame->document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3019 // When continuous spell checking is off, existing markers disappear after the selection changes.
3020 if (!isContinuousSpellCheckingEnabled)
3021 m_frame->document()->markers()->removeMarkers(DocumentMarker::Spelling);
3022 if (!isContinuousGrammarCheckingEnabled)
3023 m_frame->document()->markers()->removeMarkers(DocumentMarker::Grammar);
3025 notifyComponentsOnChangedSelection(oldSelection, options);
3028 static Node* findFirstMarkable(Node* node)
3031 if (!node->renderer())
3033 if (node->renderer()->isText())
3035 if (node->renderer()->isTextControl())
3036 node = toRenderTextControl(node->renderer())->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3037 else if (node->firstChild())
3038 node = node->firstChild();
3040 node = node->nextSibling();
3046 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3048 Node* node = findFirstMarkable(m_frame->selection()->start().deprecatedNode());
3052 unsigned int startOffset = static_cast<unsigned int>(from);
3053 unsigned int endOffset = static_cast<unsigned int>(from + length);
3054 Vector<DocumentMarker*> markers = m_frame->document()->markers()->markersFor(node);
3055 for (size_t i = 0; i < markers.size(); ++i) {
3056 DocumentMarker* marker = markers[i];
3057 if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3064 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
3066 bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3067 bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3068 bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3069 bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3071 TextCheckingTypeMask checkingTypes = 0;
3072 if (shouldMarkSpelling)
3073 checkingTypes |= TextCheckingTypeSpelling;
3074 if (shouldMarkGrammar)
3075 checkingTypes |= TextCheckingTypeGrammar;
3076 if (shouldCheckForCorrection)
3077 checkingTypes |= TextCheckingTypeCorrection;
3078 if (shouldShowCorrectionPanel)
3079 checkingTypes |= TextCheckingTypeShowCorrectionPanel;
3081 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3082 bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3083 if (shouldPerformReplacement) {
3084 if (isAutomaticLinkDetectionEnabled())
3085 checkingTypes |= TextCheckingTypeLink;
3086 if (isAutomaticQuoteSubstitutionEnabled())
3087 checkingTypes |= TextCheckingTypeQuote;
3088 if (isAutomaticDashSubstitutionEnabled())
3089 checkingTypes |= TextCheckingTypeDash;
3090 if (isAutomaticTextReplacementEnabled())
3091 checkingTypes |= TextCheckingTypeReplacement;
3092 if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3093 checkingTypes |= TextCheckingTypeCorrection;
3097 return checkingTypes;
3100 void Editor::deviceScaleFactorChanged()
3102 #if ENABLE(DELETION_UI)
3103 m_deleteButtonController->deviceScaleFactorChanged();
3107 bool Editor::unifiedTextCheckerEnabled() const
3109 return WebCore::unifiedTextCheckerEnabled(m_frame);
3112 void Editor::willDetachPage()
3114 if (EditorClient* editorClient = client())
3115 editorClient->frameWillDetachPage(frame());
3118 Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker* marker)
3120 return m_alternativeTextController->dictationAlternativesForMarker(marker);
3123 void Editor::applyDictationAlternativelternative(const String& alternativeString)
3125 m_alternativeTextController->applyDictationAlternative(alternativeString);
3128 void Editor::toggleOverwriteModeEnabled()
3130 m_overwriteModeEnabled = !m_overwriteModeEnabled;
3131 frame()->selection()->setShouldShowBlockCursor(m_overwriteModeEnabled);
3134 } // namespace WebCore