fcfb5ad3ac08d577fc55edc0a3b8158b81cebd03
[WebKit-https.git] / Source / WebCore / editing / Editor.cpp
1 /*
2  * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE 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 INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "Editor.h"
29
30 #include "AXObjectCache.h"
31 #include "AlternativeTextController.h"
32 #include "ApplyStyleCommand.h"
33 #include "CSSComputedStyleDeclaration.h"
34 #include "CSSPropertyNames.h"
35 #include "CachedResourceLoader.h"
36 #include "ClipboardEvent.h"
37 #include "CompositionEvent.h"
38 #include "CreateLinkCommand.h"
39 #include "DataTransfer.h"
40 #include "DeleteSelectionCommand.h"
41 #include "DictationAlternative.h"
42 #include "DictationCommand.h"
43 #include "DocumentFragment.h"
44 #include "DocumentMarkerController.h"
45 #include "EditorClient.h"
46 #include "EventHandler.h"
47 #include "EventNames.h"
48 #include "FocusController.h"
49 #include "Frame.h"
50 #include "FrameTree.h"
51 #include "FrameView.h"
52 #include "GraphicsContext.h"
53 #include "HTMLCollection.h"
54 #include "HTMLFormControlElement.h"
55 #include "HTMLFrameOwnerElement.h"
56 #include "HTMLImageElement.h"
57 #include "HTMLInputElement.h"
58 #include "HTMLNames.h"
59 #include "HitTestResult.h"
60 #include "IndentOutdentCommand.h"
61 #include "InputEvent.h"
62 #include "InsertListCommand.h"
63 #include "InsertTextCommand.h"
64 #include "KeyboardEvent.h"
65 #include "KillRing.h"
66 #include "Logging.h"
67 #include "MainFrame.h"
68 #include "ModifySelectionListLevel.h"
69 #include "NodeList.h"
70 #include "NodeTraversal.h"
71 #include "Page.h"
72 #include "Pasteboard.h"
73 #include "Range.h"
74 #include "RemoveFormatCommand.h"
75 #include "RenderBlock.h"
76 #include "RenderTextControl.h"
77 #include "RenderedDocumentMarker.h"
78 #include "RenderedPosition.h"
79 #include "ReplaceRangeWithTextCommand.h"
80 #include "ReplaceSelectionCommand.h"
81 #include "Settings.h"
82 #include "ShadowRoot.h"
83 #include "SimplifyMarkupCommand.h"
84 #include "Sound.h"
85 #include "SpellChecker.h"
86 #include "SpellingCorrectionCommand.h"
87 #include "StyleProperties.h"
88 #include "TelephoneNumberDetector.h"
89 #include "Text.h"
90 #include "TextCheckerClient.h"
91 #include "TextCheckingHelper.h"
92 #include "TextEvent.h"
93 #include "TextIterator.h"
94 #include "TypingCommand.h"
95 #include "UserTypingGestureIndicator.h"
96 #include "VisibleUnits.h"
97 #include "htmlediting.h"
98 #include "markup.h"
99 #include <wtf/unicode/CharacterNames.h>
100
101 #if PLATFORM(MAC)
102 #include "ServicesOverlayController.h"
103 #endif
104
105 namespace WebCore {
106
107 static bool dispatchBeforeInputEvent(Element& element, const AtomicString& inputType, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { }, bool cancelable = true)
108 {
109     auto* settings = element.document().settings();
110     if (!settings || !settings->inputEventsEnabled())
111         return true;
112
113     return element.dispatchEvent(InputEvent::create(eventNames().beforeinputEvent, inputType, true, cancelable, element.document().defaultView(), data, WTFMove(dataTransfer), targetRanges, 0));
114 }
115
116 static void dispatchInputEvent(Element& element, const AtomicString& inputType, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { })
117 {
118     auto* settings = element.document().settings();
119     if (settings && settings->inputEventsEnabled())
120         element.dispatchEvent(InputEvent::create(eventNames().inputEvent, inputType, true, false, element.document().defaultView(), data, WTFMove(dataTransfer), targetRanges, 0));
121     else
122         element.dispatchInputEvent();
123 }
124
125 static String inputEventDataForEditingStyleAndAction(const StyleProperties* style, EditAction action)
126 {
127     if (!style)
128         return { };
129
130     switch (action) {
131     case EditActionSetColor:
132         return style->getPropertyValue(CSSPropertyColor);
133     case EditActionSetWritingDirection:
134         return style->getPropertyValue(CSSPropertyDirection);
135     default:
136         return { };
137     }
138 }
139
140 static String inputEventDataForEditingStyleAndAction(EditingStyle& style, EditAction action)
141 {
142     return inputEventDataForEditingStyleAndAction(style.style(), action);
143 }
144
145 class ClearTextCommand : public DeleteSelectionCommand {
146 public:
147     ClearTextCommand(Document& document);
148     static void CreateAndApply(const RefPtr<Frame> frame);
149     
150 private:
151     EditAction editingAction() const override;
152 };
153
154 ClearTextCommand::ClearTextCommand(Document& document)
155     : DeleteSelectionCommand(document, false, true, false, false, true)
156 {
157 }
158
159 EditAction ClearTextCommand::editingAction() const
160 {
161     return EditActionDelete;
162 }
163
164 void ClearTextCommand::CreateAndApply(const RefPtr<Frame> frame)
165 {
166     if (frame->selection().isNone())
167         return;
168
169     // Don't leave around stale composition state.
170     frame->editor().clear();
171     
172     const VisibleSelection oldSelection = frame->selection().selection();
173     frame->selection().selectAll();
174     auto clearCommand = adoptRef(*new ClearTextCommand(*frame->document()));
175     clearCommand->setStartingSelection(oldSelection);
176     applyCommand(WTFMove(clearCommand));
177 }
178
179 using namespace HTMLNames;
180 using namespace WTF;
181 using namespace Unicode;
182
183 // When an event handler has moved the selection outside of a text control
184 // we should use the target control's selection for this editing operation.
185 VisibleSelection Editor::selectionForCommand(Event* event)
186 {
187     VisibleSelection selection = m_frame.selection().selection();
188     if (!event)
189         return selection;
190     // If the target is a text control, and the current selection is outside of its shadow tree,
191     // then use the saved selection for that text control.
192     HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
193     HTMLTextFormControlElement* textFromControlOfTarget = is<HTMLTextFormControlElement>(*event->target()->toNode()) ? downcast<HTMLTextFormControlElement>(event->target()->toNode()) : nullptr;
194     if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
195         if (RefPtr<Range> range = textFromControlOfTarget->selection())
196             return VisibleSelection(*range, DOWNSTREAM, selection.isDirectional());
197     }
198     return selection;
199 }
200
201 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
202 EditingBehavior Editor::behavior() const
203 {
204     return EditingBehavior(m_frame.settings().editingBehaviorType());
205 }
206
207 EditorClient* Editor::client() const
208 {
209     if (Page* page = m_frame.page())
210         return &page->editorClient();
211     return nullptr;
212 }
213
214 TextCheckerClient* Editor::textChecker() const
215 {
216     if (EditorClient* owner = client())
217         return owner->textChecker();
218     return 0;
219 }
220
221 void Editor::handleKeyboardEvent(KeyboardEvent& event)
222 {
223     if (EditorClient* c = client())
224         c->handleKeyboardEvent(&event);
225 }
226
227 void Editor::handleInputMethodKeydown(KeyboardEvent& event)
228 {
229     if (EditorClient* c = client())
230         c->handleInputMethodKeydown(&event);
231 }
232
233 bool Editor::handleTextEvent(TextEvent& event)
234 {
235     LOG(Editing, "Editor %p handleTextEvent (data %s)", this, event.data().utf8().data());
236
237     // Default event handling for Drag and Drop will be handled by DragController
238     // so we leave the event for it.
239     if (event.isDrop())
240         return false;
241
242     if (event.isPaste()) {
243         if (event.pastingFragment()) {
244 #if PLATFORM(IOS)
245             if (client()->performsTwoStepPaste(event.pastingFragment()))
246                 return true;
247 #endif
248             replaceSelectionWithFragment(event.pastingFragment(), false, event.shouldSmartReplace(), event.shouldMatchStyle(), EditActionPaste, event.mailBlockquoteHandling());
249         } else
250             replaceSelectionWithText(event.data(), false, event.shouldSmartReplace(), EditActionPaste);
251         return true;
252     }
253
254     String data = event.data();
255     if (data == "\n") {
256         if (event.isLineBreak())
257             return insertLineBreak();
258         return insertParagraphSeparator();
259     }
260
261     return insertTextWithoutSendingTextEvent(data, false, &event);
262 }
263
264 bool Editor::canEdit() const
265 {
266     return m_frame.selection().selection().rootEditableElement();
267 }
268
269 bool Editor::canEditRichly() const
270 {
271     return m_frame.selection().selection().isContentRichlyEditable();
272 }
273
274 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
275 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
276 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
277 // normally selectable to implement copy/paste (like divs, or a document body).
278
279 bool Editor::canDHTMLCut()
280 {
281     return !m_frame.selection().selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, DataTransferAccessPolicy::Numb);
282 }
283
284 bool Editor::canDHTMLCopy()
285 {
286     return !m_frame.selection().selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, DataTransferAccessPolicy::Numb);
287 }
288
289 bool Editor::canDHTMLPaste()
290 {
291     return !dispatchCPPEvent(eventNames().beforepasteEvent, DataTransferAccessPolicy::Numb);
292 }
293
294 bool Editor::canCut() const
295 {
296     return canCopy() && canDelete();
297 }
298
299 static HTMLImageElement* imageElementFromImageDocument(Document& document)
300 {
301     if (!document.isImageDocument())
302         return nullptr;
303     
304     HTMLElement* body = document.bodyOrFrameset();
305     if (!body)
306         return nullptr;
307     
308     Node* node = body->firstChild();
309     if (!is<HTMLImageElement>(node))
310         return nullptr;
311     return downcast<HTMLImageElement>(node);
312 }
313
314 bool Editor::canCopy() const
315 {
316     if (imageElementFromImageDocument(document()))
317         return true;
318     const VisibleSelection& selection = m_frame.selection().selection();
319     return selection.isRange() && !selection.isInPasswordField();
320 }
321
322 bool Editor::canPaste() const
323 {
324     return canEdit();
325 }
326
327 bool Editor::canDelete() const
328 {
329     const VisibleSelection& selection = m_frame.selection().selection();
330     return selection.isRange() && selection.rootEditableElement();
331 }
332
333 bool Editor::canDeleteRange(Range* range) const
334 {
335     Node& startContainer = range->startContainer();
336     Node& endContainer = range->endContainer();
337     
338     if (!startContainer.hasEditableStyle() || !endContainer.hasEditableStyle())
339         return false;
340
341     if (range->collapsed()) {
342         VisiblePosition start(range->startPosition(), DOWNSTREAM);
343         VisiblePosition previous = start.previous();
344         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
345         if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer.rootEditableElement())
346             return false;
347     }
348     return true;
349 }
350
351 bool Editor::smartInsertDeleteEnabled()
352 {   
353     return client() && client()->smartInsertDeleteEnabled();
354 }
355     
356 bool Editor::canSmartCopyOrDelete()
357 {
358     return client() && client()->smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
359 }
360
361 bool Editor::isSelectTrailingWhitespaceEnabled()
362 {
363     return client() && client()->isSelectTrailingWhitespaceEnabled();
364 }
365
366 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool shouldAddToKillRing, bool isTypingAction)
367 {
368     if (!canEdit())
369         return false;
370
371     if (m_frame.selection().isRange()) {
372         if (isTypingAction) {
373             TypingCommand::deleteKeyPressed(document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
374             revealSelectionAfterEditingOperation();
375         } else {
376             if (shouldAddToKillRing)
377                 addRangeToKillRing(*selectedRange().get(), KillRingInsertionMode::AppendText);
378             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
379             // Implicitly calls revealSelectionAfterEditingOperation().
380         }
381     } else {
382         TypingCommand::Options options = 0;
383         if (canSmartCopyOrDelete())
384             options |= TypingCommand::SmartDelete;
385         if (shouldAddToKillRing)
386             options |= TypingCommand::AddsToKillRing;
387         switch (direction) {
388         case DirectionForward:
389         case DirectionRight:
390             TypingCommand::forwardDeleteKeyPressed(document(), options, granularity);
391             break;
392         case DirectionBackward:
393         case DirectionLeft:
394             TypingCommand::deleteKeyPressed(document(), options, granularity);
395             break;
396         }
397         revealSelectionAfterEditingOperation();
398     }
399
400     // FIXME: We should to move this down into deleteKeyPressed.
401     // clear the "start new kill ring sequence" setting, because it was set to true
402     // when the selection was updated by deleting the range
403     if (shouldAddToKillRing)
404         setStartNewKillRingSequence(false);
405
406     return true;
407 }
408
409 void Editor::deleteSelectionWithSmartDelete(bool smartDelete, EditAction editingAction)
410 {
411     if (m_frame.selection().isNone())
412         return;
413
414     applyCommand(DeleteSelectionCommand::create(document(), smartDelete, true, false, false, true, editingAction));
415 }
416
417 void Editor::clearText()
418 {
419     ClearTextCommand::CreateAndApply(&m_frame);
420 }
421
422 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
423 {
424     Node* target = findEventTargetFromSelection();
425     if (!target)
426         return;
427     target->dispatchEvent(TextEvent::createForPlainTextPaste(document().domWindow(), pastingText, smartReplace));
428 }
429
430 void Editor::pasteAsFragment(Ref<DocumentFragment>&& pastingFragment, bool smartReplace, bool matchStyle, MailBlockquoteHandling respectsMailBlockquote)
431 {
432     Node* target = findEventTargetFromSelection();
433     if (!target)
434         return;
435     target->dispatchEvent(TextEvent::createForFragmentPaste(document().domWindow(), WTFMove(pastingFragment), smartReplace, matchStyle, respectsMailBlockquote));
436 }
437
438 void Editor::pasteAsPlainTextBypassingDHTML()
439 {
440     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
441 }
442
443 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard& pasteboard)
444 {
445     String text = readPlainTextFromPasteboard(pasteboard);
446     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
447         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
448 }
449
450 String Editor::readPlainTextFromPasteboard(Pasteboard& pasteboard)
451 {
452     PasteboardPlainText text;
453     pasteboard.read(text);
454     return plainTextFromPasteboard(text);
455 }
456
457 #if !PLATFORM(MAC)
458
459 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
460 {
461     return text.text;
462 }
463
464 #endif
465
466 bool Editor::canSmartReplaceWithPasteboard(Pasteboard& pasteboard)
467 {
468     return client() && client()->smartInsertDeleteEnabled() && pasteboard.canSmartReplace();
469 }
470
471 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
472 {
473     if (!client())
474         return false;
475     
476     if (fragment) {
477         Node* child = fragment->firstChild();
478         if (is<CharacterData>(child) && fragment->lastChild() == child)
479             return client()->shouldInsertText(downcast<CharacterData>(*child).data(), replacingDOMRange.get(), givenAction);
480     }
481
482     return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
483 }
484
485 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle, EditAction editingAction, MailBlockquoteHandling mailBlockquoteHandling)
486 {
487     VisibleSelection selection = m_frame.selection().selection();
488     if (selection.isNone() || !selection.isContentEditable() || !fragment)
489         return;
490
491     AccessibilityReplacedText replacedText;
492     if (AXObjectCache::accessibilityEnabled() && editingAction == EditActionPaste)
493         replacedText = AccessibilityReplacedText(selection);
494
495     ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
496     if (selectReplacement)
497         options |= ReplaceSelectionCommand::SelectReplacement;
498     if (smartReplace)
499         options |= ReplaceSelectionCommand::SmartReplace;
500     if (matchStyle)
501         options |= ReplaceSelectionCommand::MatchStyle;
502     if (mailBlockquoteHandling == MailBlockquoteHandling::IgnoreBlockquote)
503         options |= ReplaceSelectionCommand::IgnoreMailBlockquote;
504
505     RefPtr<ReplaceSelectionCommand> command = ReplaceSelectionCommand::create(document(), fragment, options, editingAction);
506     applyCommand(command);
507     revealSelectionAfterEditingOperation();
508
509     selection = m_frame.selection().selection();
510     if (selection.isInPasswordField())
511         return;
512
513     if (AXObjectCache::accessibilityEnabled() && editingAction == EditActionPaste) {
514         String text = AccessibilityObject::stringForVisiblePositionRange(command->visibleSelectionForInsertedText());
515         replacedText.postTextStateChangeNotification(document().existingAXObjectCache(), AXTextEditTypePaste, text, m_frame.selection().selection());
516         command->composition()->setRangeDeletedByUnapply(replacedText.replacedRange());
517     }
518
519     if (!isContinuousSpellCheckingEnabled())
520         return;
521
522     Node* nodeToCheck = selection.rootEditableElement();
523     if (!nodeToCheck)
524         return;
525
526     RefPtr<Range> rangeToCheck = Range::create(document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
527     m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(*nodeToCheck, TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
528 }
529
530 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace, EditAction editingAction)
531 {
532     RefPtr<Range> range = selectedRange();
533     if (!range)
534         return;
535
536     replaceSelectionWithFragment(createFragmentFromText(*range, text), selectReplacement, smartReplace, true, editingAction);
537 }
538
539 RefPtr<Range> Editor::selectedRange()
540 {
541     return m_frame.selection().toNormalizedRange();
542 }
543
544 bool Editor::shouldDeleteRange(Range* range) const
545 {
546     if (!range || range->collapsed())
547         return false;
548     
549     if (!canDeleteRange(range))
550         return false;
551
552     return client() && client()->shouldDeleteRange(range);
553 }
554
555 bool Editor::tryDHTMLCopy()
556 {   
557     if (m_frame.selection().selection().isInPasswordField())
558         return false;
559
560     return !dispatchCPPEvent(eventNames().copyEvent, DataTransferAccessPolicy::Writable);
561 }
562
563 bool Editor::tryDHTMLCut()
564 {
565     if (m_frame.selection().selection().isInPasswordField())
566         return false;
567     
568     return !dispatchCPPEvent(eventNames().cutEvent, DataTransferAccessPolicy::Writable);
569 }
570
571 bool Editor::tryDHTMLPaste()
572 {
573     return !dispatchCPPEvent(eventNames().pasteEvent, DataTransferAccessPolicy::Readable);
574 }
575
576 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
577 {
578     if (m_frame.loader().shouldSuppressKeyboardInput() && action == EditorInsertActionTyped)
579         return false;
580
581     return client() && client()->shouldInsertText(text, range, action);
582 }
583
584 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
585 {
586     if (AXObjectCache::accessibilityEnabled()) {
587         Node* node = endingSelection.start().deprecatedNode();
588         if (AXObjectCache* cache = document().existingAXObjectCache())
589             cache->postNotification(node, AXObjectCache::AXValueChanged, TargetObservableParent);
590     }
591
592     updateMarkersForWordsAffectedByEditing(true);
593
594     if (client())
595         client()->respondToChangedContents();
596 }
597
598 bool Editor::hasBidiSelection() const
599 {
600     if (m_frame.selection().isNone())
601         return false;
602
603     Node* startNode;
604     if (m_frame.selection().isRange()) {
605         startNode = m_frame.selection().selection().start().downstream().deprecatedNode();
606         Node* endNode = m_frame.selection().selection().end().upstream().deprecatedNode();
607         if (enclosingBlock(startNode) != enclosingBlock(endNode))
608             return false;
609     } else
610         startNode = m_frame.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
611
612     if (!startNode)
613         return false;
614
615     auto renderer = startNode->renderer();
616     while (renderer && !is<RenderBlockFlow>(*renderer))
617         renderer = renderer->parent();
618
619     if (!renderer)
620         return false;
621
622     if (!renderer->style().isLeftToRightDirection())
623         return true;
624
625     return downcast<RenderBlockFlow>(*renderer).containsNonZeroBidiLevel();
626 }
627
628 TriState Editor::selectionUnorderedListState() const
629 {
630     if (m_frame.selection().isCaret()) {
631         if (enclosingElementWithTag(m_frame.selection().selection().start(), ulTag))
632             return TrueTriState;
633     } else if (m_frame.selection().isRange()) {
634         auto* startNode = enclosingElementWithTag(m_frame.selection().selection().start(), ulTag);
635         auto* endNode = enclosingElementWithTag(m_frame.selection().selection().end(), ulTag);
636         if (startNode && endNode && startNode == endNode)
637             return TrueTriState;
638     }
639
640     return FalseTriState;
641 }
642
643 TriState Editor::selectionOrderedListState() const
644 {
645     if (m_frame.selection().isCaret()) {
646         if (enclosingElementWithTag(m_frame.selection().selection().start(), olTag))
647             return TrueTriState;
648     } else if (m_frame.selection().isRange()) {
649         auto* startNode = enclosingElementWithTag(m_frame.selection().selection().start(), olTag);
650         auto* endNode = enclosingElementWithTag(m_frame.selection().selection().end(), olTag);
651         if (startNode && endNode && startNode == endNode)
652             return TrueTriState;
653     }
654
655     return FalseTriState;
656 }
657
658 PassRefPtr<Node> Editor::insertOrderedList()
659 {
660     if (!canEditRichly())
661         return 0;
662         
663     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::OrderedList);
664     revealSelectionAfterEditingOperation();
665     return newList;
666 }
667
668 PassRefPtr<Node> Editor::insertUnorderedList()
669 {
670     if (!canEditRichly())
671         return 0;
672         
673     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::UnorderedList);
674     revealSelectionAfterEditingOperation();
675     return newList;
676 }
677
678 bool Editor::canIncreaseSelectionListLevel()
679 {
680     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(&document());
681 }
682
683 bool Editor::canDecreaseSelectionListLevel()
684 {
685     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(&document());
686 }
687
688 RefPtr<Node> Editor::increaseSelectionListLevel()
689 {
690     if (!canEditRichly() || m_frame.selection().isNone())
691         return nullptr;
692     
693     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(&document());
694     revealSelectionAfterEditingOperation();
695     return newList;
696 }
697
698 RefPtr<Node> Editor::increaseSelectionListLevelOrdered()
699 {
700     if (!canEditRichly() || m_frame.selection().isNone())
701         return nullptr;
702     
703     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(&document());
704     revealSelectionAfterEditingOperation();
705     return newList;
706 }
707
708 RefPtr<Node> Editor::increaseSelectionListLevelUnordered()
709 {
710     if (!canEditRichly() || m_frame.selection().isNone())
711         return nullptr;
712     
713     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(&document());
714     revealSelectionAfterEditingOperation();
715     return newList;
716 }
717
718 void Editor::decreaseSelectionListLevel()
719 {
720     if (!canEditRichly() || m_frame.selection().isNone())
721         return;
722     
723     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(&document());
724     revealSelectionAfterEditingOperation();
725 }
726
727 void Editor::removeFormattingAndStyle()
728 {
729     applyCommand(RemoveFormatCommand::create(document()));
730 }
731
732 void Editor::clearLastEditCommand() 
733 {
734     m_lastEditCommand = nullptr;
735 }
736
737 // Returns whether caller should continue with "the default processing", which is the same as 
738 // the event handler NOT setting the return value to false
739 bool Editor::dispatchCPPEvent(const AtomicString& eventType, DataTransferAccessPolicy policy)
740 {
741     Node* target = findEventTargetFromSelection();
742     if (!target)
743         return true;
744
745     auto dataTransfer = DataTransfer::createForCopyAndPaste(policy);
746
747     ClipboardEvent::Init init;
748     init.bubbles = true;
749     init.cancelable = true;
750     init.clipboardData = dataTransfer.ptr();
751     auto event = ClipboardEvent::create(eventType, init, Event::IsTrusted::Yes);
752     target->dispatchEvent(event);
753     bool noDefaultProcessing = event->defaultPrevented();
754     if (noDefaultProcessing && policy == DataTransferAccessPolicy::Writable) {
755         auto pasteboard = Pasteboard::createForCopyAndPaste();
756         pasteboard->clear();
757         pasteboard->writePasteboard(dataTransfer->pasteboard());
758     }
759
760     // invalidate dataTransfer here for security
761     dataTransfer->setAccessPolicy(DataTransferAccessPolicy::Numb);
762     
763     return !noDefaultProcessing;
764 }
765
766 Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
767 {
768     Node* target = selection.start().element();
769     if (!target)
770         target = document().bodyOrFrameset();
771     if (!target)
772         return nullptr;
773
774     return target;
775 }
776
777 Node* Editor::findEventTargetFromSelection() const
778 {
779     return findEventTargetFrom(m_frame.selection().selection());
780 }
781
782 void Editor::applyStyle(StyleProperties* style, EditAction editingAction)
783 {
784     if (style)
785         applyStyle(EditingStyle::create(style), editingAction);
786 }
787
788 void Editor::applyStyle(RefPtr<EditingStyle>&& style, EditAction editingAction)
789 {
790     if (!style)
791         return;
792
793     auto selectionType = m_frame.selection().selection().selectionType();
794     if (selectionType == VisibleSelection::NoSelection)
795         return;
796
797     String inputTypeName = inputTypeNameForEditingAction(editingAction);
798     String inputEventData = inputEventDataForEditingStyleAndAction(*style, editingAction);
799     RefPtr<Element> element = m_frame.selection().selection().rootEditableElement();
800     if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
801         return;
802
803     switch (selectionType) {
804     case VisibleSelection::CaretSelection:
805         computeAndSetTypingStyle(*style, editingAction);
806         break;
807     case VisibleSelection::RangeSelection:
808         applyCommand(ApplyStyleCommand::create(document(), style.get(), editingAction));
809         break;
810     default:
811         break;
812     }
813
814     client()->didApplyStyle();
815     if (element)
816         dispatchInputEvent(*element, inputTypeName, inputEventData);
817 }
818     
819 bool Editor::shouldApplyStyle(StyleProperties* style, Range* range)
820 {   
821     return client()->shouldApplyStyle(style, range);
822 }
823     
824 void Editor::applyParagraphStyle(StyleProperties* style, EditAction editingAction)
825 {
826     if (!style)
827         return;
828
829     auto selectionType = m_frame.selection().selection().selectionType();
830     if (selectionType == VisibleSelection::NoSelection)
831         return;
832
833     String inputTypeName = inputTypeNameForEditingAction(editingAction);
834     String inputEventData = inputEventDataForEditingStyleAndAction(style, editingAction);
835     RefPtr<Element> element = m_frame.selection().selection().rootEditableElement();
836     if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
837         return;
838
839     applyCommand(ApplyStyleCommand::create(document(), EditingStyle::create(style).ptr(), editingAction, ApplyStyleCommand::ForceBlockProperties));
840     client()->didApplyStyle();
841     if (element)
842         dispatchInputEvent(*element, inputTypeName, inputEventData);
843 }
844
845 void Editor::applyStyleToSelection(StyleProperties* style, EditAction editingAction)
846 {
847     if (!style || style->isEmpty() || !canEditRichly())
848         return;
849
850     if (!client() || !client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
851         return;
852     applyStyle(style, editingAction);
853 }
854
855 void Editor::applyStyleToSelection(Ref<EditingStyle>&& style, EditAction editingAction)
856 {
857     if (style->isEmpty() || !canEditRichly())
858         return;
859
860     // FIXME: This is wrong for text decorations since m_mutableStyle is empty.
861     if (!client() || !client()->shouldApplyStyle(style->styleWithResolvedTextDecorations().ptr(), m_frame.selection().toNormalizedRange().get()))
862         return;
863
864     applyStyle(WTFMove(style), editingAction);
865 }
866
867 void Editor::applyParagraphStyleToSelection(StyleProperties* style, EditAction editingAction)
868 {
869     if (!style || style->isEmpty() || !canEditRichly())
870         return;
871     
872     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
873         applyParagraphStyle(style, editingAction);
874 }
875
876 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
877 {
878     return EditingStyle::create(propertyID, value)->triStateOfStyle(
879         EditingStyle::styleAtSelectionStart(m_frame.selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
880 }
881
882 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
883 {
884     return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame.selection().selection());
885 }
886
887 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
888 {
889     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(),
890         propertyID == CSSPropertyBackgroundColor);
891     if (!selectionStyle || !selectionStyle->style())
892         return String();
893
894     if (propertyID == CSSPropertyFontSize)
895         return String::number(selectionStyle->legacyFontSize(&document()));
896     return selectionStyle->style()->getPropertyValue(propertyID);
897 }
898
899 void Editor::indent()
900 {
901     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Indent));
902 }
903
904 void Editor::outdent()
905 {
906     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Outdent));
907 }
908
909 static void notifyTextFromControls(Element* startRoot, Element* endRoot)
910 {
911     HTMLTextFormControlElement* startingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(startRoot));
912     HTMLTextFormControlElement* endingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(endRoot));
913     if (startingTextControl)
914         startingTextControl->didEditInnerTextValue();
915     if (endingTextControl && startingTextControl != endingTextControl)
916         endingTextControl->didEditInnerTextValue();
917 }
918
919 static bool dispatchBeforeInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomicString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { }, bool cancelable = true)
920 {
921     bool continueWithDefaultBehavior = true;
922     if (startRoot)
923         continueWithDefaultBehavior &= dispatchBeforeInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
924     if (endRoot && endRoot != startRoot)
925         continueWithDefaultBehavior &= dispatchBeforeInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
926     return continueWithDefaultBehavior;
927 }
928
929 static void dispatchInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomicString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { })
930 {
931     if (startRoot)
932         dispatchInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
933     if (endRoot && endRoot != startRoot)
934         dispatchInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
935 }
936
937 bool Editor::willApplyEditing(CompositeEditCommand& command, Vector<RefPtr<StaticRange>>&& targetRanges) const
938 {
939     if (!command.shouldDispatchInputEvents())
940         return true;
941
942     auto* composition = command.composition();
943     if (!composition)
944         return true;
945
946     return dispatchBeforeInputEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement(), command.inputEventTypeName(), command.inputEventData(), command.inputEventDataTransfer(), targetRanges, command.isBeforeInputEventCancelable());
947 }
948
949 void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
950 {
951     LOG(Editing, "Editor %p appliedEditing", this);
952
953     document().updateLayout();
954
955     EditCommandComposition* composition = cmd->composition();
956     ASSERT(composition);
957     VisibleSelection newSelection(cmd->endingSelection());
958
959     notifyTextFromControls(composition->startingRootEditableElement(), composition->endingRootEditableElement());
960
961     if (cmd->isTopLevelCommand()) {
962         // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
963         FrameSelection::SetSelectionOptions options = cmd->isDictationCommand() ? FrameSelection::DictationTriggered : 0;
964
965         changeSelectionAfterCommand(newSelection, options);
966     }
967
968     if (cmd->shouldDispatchInputEvents())
969         dispatchInputEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement(), cmd->inputEventTypeName(), cmd->inputEventData(), cmd->inputEventDataTransfer());
970
971     if (cmd->isTopLevelCommand()) {
972         updateEditorUINowIfScheduled();
973
974         m_alternativeTextController->respondToAppliedEditing(cmd.get());
975
976         if (!cmd->preservesTypingStyle())
977             m_frame.selection().clearTypingStyle();
978
979         // Command will be equal to last edit command only in the case of typing
980         if (m_lastEditCommand.get() == cmd)
981             ASSERT(cmd->isTypingCommand());
982         else {
983             // Only register a new undo command if the command passed in is
984             // different from the last command
985             m_lastEditCommand = cmd;
986             if (client())
987                 client()->registerUndoStep(m_lastEditCommand->ensureComposition());
988         }
989         respondToChangedContents(newSelection);
990     }
991 }
992
993 bool Editor::willUnapplyEditing(const EditCommandComposition& composition) const
994 {
995     return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyUndo");
996 }
997
998 void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
999 {
1000     document().updateLayout();
1001
1002     notifyTextFromControls(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
1003
1004     VisibleSelection newSelection(cmd->startingSelection());
1005     changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
1006     dispatchInputEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement(), "historyUndo");
1007
1008     updateEditorUINowIfScheduled();
1009
1010     m_alternativeTextController->respondToUnappliedEditing(cmd.get());
1011
1012     m_lastEditCommand = nullptr;
1013     if (client())
1014         client()->registerRedoStep(cmd);
1015     respondToChangedContents(newSelection);
1016 }
1017
1018 bool Editor::willReapplyEditing(const EditCommandComposition& composition) const
1019 {
1020     return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyRedo");
1021 }
1022
1023 void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
1024 {
1025     document().updateLayout();
1026
1027     notifyTextFromControls(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
1028
1029     VisibleSelection newSelection(cmd->endingSelection());
1030     changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
1031     dispatchInputEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement(), "historyRedo");
1032     
1033     updateEditorUINowIfScheduled();
1034
1035     m_lastEditCommand = nullptr;
1036     if (client())
1037         client()->registerUndoStep(cmd);
1038     respondToChangedContents(newSelection);
1039 }
1040
1041 Editor::Editor(Frame& frame)
1042     : m_frame(frame)
1043     , m_killRing(std::make_unique<KillRing>())
1044     , m_spellChecker(std::make_unique<SpellChecker>(frame))
1045     , m_alternativeTextController(std::make_unique<AlternativeTextController>(frame))
1046     , m_editorUIUpdateTimer(*this, &Editor::editorUIUpdateTimerFired)
1047 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
1048     , m_telephoneNumberDetectionUpdateTimer(*this, &Editor::scanSelectionForTelephoneNumbers)
1049 #endif
1050 {
1051 }
1052
1053 Editor::~Editor()
1054 {
1055 }
1056
1057 void Editor::clear()
1058 {
1059     if (m_compositionNode) {
1060         m_compositionNode = nullptr;
1061         if (EditorClient* client = this->client())
1062             client->discardedComposition(&m_frame);
1063     }
1064     m_customCompositionUnderlines.clear();
1065     m_shouldStyleWithCSS = false;
1066     m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
1067 }
1068
1069 bool Editor::insertText(const String& text, Event* triggeringEvent, TextEventInputType inputType)
1070 {
1071     return m_frame.eventHandler().handleTextInputEvent(text, triggeringEvent, inputType);
1072 }
1073
1074 bool Editor::insertTextForConfirmedComposition(const String& text)
1075 {
1076     return m_frame.eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
1077 }
1078
1079 bool Editor::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent)
1080 {
1081     return m_alternativeTextController->insertDictatedText(text, dictationAlternatives, triggeringEvent);
1082 }
1083
1084 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
1085 {
1086     if (text.isEmpty())
1087         return false;
1088
1089     VisibleSelection selection = selectionForCommand(triggeringEvent);
1090     if (!selection.isContentEditable())
1091         return false;
1092     RefPtr<Range> range = selection.toNormalizedRange();
1093
1094     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
1095         return true;
1096
1097     updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
1098
1099     bool shouldConsiderApplyingAutocorrection = false;
1100     if (text == " " || text == "\t")
1101         shouldConsiderApplyingAutocorrection = true;
1102
1103     if (text.length() == 1 && u_ispunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
1104         shouldConsiderApplyingAutocorrection = true;
1105
1106     bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1107
1108     // Get the selection to use for the event that triggered this insertText.
1109     // If the event handler changed the selection, we may want to use a different selection
1110     // that is contained in the event target.
1111     selection = selectionForCommand(triggeringEvent);
1112     if (selection.isContentEditable()) {
1113         if (Node* selectionStart = selection.start().deprecatedNode()) {
1114             Ref<Document> document(selectionStart->document());
1115
1116             // Insert the text
1117             if (triggeringEvent && triggeringEvent->isDictation())
1118                 DictationCommand::insertText(document, text, triggeringEvent->dictationAlternatives(), selection);
1119             else {
1120                 TypingCommand::Options options = 0;
1121                 if (selectInsertedText)
1122                     options |= TypingCommand::SelectInsertedText;
1123                 if (autocorrectionWasApplied)
1124                     options |= TypingCommand::RetainAutocorrectionIndicator;
1125                 if (triggeringEvent && triggeringEvent->isAutocompletion())
1126                     options |= TypingCommand::IsAutocompletion;
1127                 TypingCommand::insertText(document, text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionFinal : TypingCommand::TextCompositionNone);
1128             }
1129
1130             // Reveal the current selection
1131             if (Frame* editedFrame = document->frame())
1132                 if (Page* page = editedFrame->page()) {
1133 #if PLATFORM(IOS)
1134                     SelectionRevealMode revealMode = SelectionRevealMode::RevealUpToMainFrame;
1135 #else
1136                     SelectionRevealMode revealMode = SelectionRevealMode::Reveal;
1137 #endif
1138                     page->focusController().focusedOrMainFrame().selection().revealSelection(revealMode, ScrollAlignment::alignCenterIfNeeded);
1139                 }
1140         }
1141     }
1142
1143     return true;
1144 }
1145
1146 bool Editor::insertLineBreak()
1147 {
1148     if (!canEdit())
1149         return false;
1150
1151     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1152         return true;
1153
1154     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1155     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1156     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1157     TypingCommand::insertLineBreak(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1158     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1159
1160     return true;
1161 }
1162
1163 bool Editor::insertParagraphSeparator()
1164 {
1165     if (!canEdit())
1166         return false;
1167
1168     if (!canEditRichly())
1169         return insertLineBreak();
1170
1171     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1172         return true;
1173
1174     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1175     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1176     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1177     TypingCommand::insertParagraphSeparator(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1178     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1179
1180     return true;
1181 }
1182
1183 bool Editor::insertParagraphSeparatorInQuotedContent()
1184 {
1185     // FIXME: Why is this missing calls to canEdit, canEditRichly, etc.?
1186     TypingCommand::insertParagraphSeparatorInQuotedContent(document());
1187     revealSelectionAfterEditingOperation();
1188     return true;
1189 }
1190
1191 void Editor::cut()
1192 {
1193     if (tryDHTMLCut())
1194         return; // DHTML did the whole operation
1195     if (!canCut()) {
1196         systemBeep();
1197         return;
1198     }
1199
1200     performCutOrCopy(CutAction);
1201 }
1202
1203 void Editor::copy()
1204 {
1205     if (tryDHTMLCopy())
1206         return; // DHTML did the whole operation
1207     if (!canCopy()) {
1208         systemBeep();
1209         return;
1210     }
1211
1212     performCutOrCopy(CopyAction);
1213 }
1214
1215 void Editor::postTextStateChangeNotificationForCut(const String& text, const VisibleSelection& selection)
1216 {
1217     if (!AXObjectCache::accessibilityEnabled())
1218         return;
1219     if (!text.length())
1220         return;
1221     AXObjectCache* cache = document().existingAXObjectCache();
1222     if (!cache)
1223         return;
1224     cache->postTextStateChangeNotification(selection.start().anchorNode(), AXTextEditTypeCut, text, selection.start());
1225 }
1226
1227 void Editor::performCutOrCopy(EditorActionSpecifier action)
1228 {
1229     RefPtr<Range> selection = selectedRange();
1230     willWriteSelectionToPasteboard(selection);
1231     if (action == CutAction) {
1232         if (!shouldDeleteRange(selection.get()))
1233             return;
1234
1235         updateMarkersForWordsAffectedByEditing(true);
1236     }
1237
1238     if (enclosingTextFormControl(m_frame.selection().selection().start()))
1239         Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForDataTransfer(), canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1240     else {
1241         HTMLImageElement* imageElement = nullptr;
1242         if (action == CopyAction)
1243             imageElement = imageElementFromImageDocument(document());
1244
1245         if (imageElement) {
1246 #if PLATFORM(COCOA) || PLATFORM(EFL) || PLATFORM(GTK)
1247             writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *imageElement, document().url(), document().title());
1248 #else
1249             Pasteboard::createForCopyAndPaste()->writeImage(*imageElement, document().url(), document().title());
1250 #endif
1251         } else {
1252 #if PLATFORM(COCOA) || PLATFORM(EFL) || PLATFORM(GTK)
1253             writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
1254 #else
1255             // FIXME: Convert all other platforms to match Mac and delete this.
1256             Pasteboard::createForCopyAndPaste()->writeSelection(*selection, canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForDataTransfer);
1257 #endif
1258         }
1259     }
1260
1261     didWriteSelectionToPasteboard();
1262     if (action == CutAction) {
1263         String text;
1264         if (AXObjectCache::accessibilityEnabled())
1265             text = AccessibilityObject::stringForVisiblePositionRange(m_frame.selection().selection());
1266         deleteSelectionWithSmartDelete(canSmartCopyOrDelete(), EditActionCut);
1267         if (AXObjectCache::accessibilityEnabled())
1268             postTextStateChangeNotificationForCut(text, m_frame.selection().selection());
1269     }
1270 }
1271
1272 void Editor::paste()
1273 {
1274     paste(*Pasteboard::createForCopyAndPaste());
1275 }
1276
1277 void Editor::paste(Pasteboard& pasteboard)
1278 {
1279     if (tryDHTMLPaste())
1280         return; // DHTML did the whole operation
1281     if (!canPaste())
1282         return;
1283     updateMarkersForWordsAffectedByEditing(false);
1284     ResourceCacheValidationSuppressor validationSuppressor(document().cachedResourceLoader());
1285     if (m_frame.selection().selection().isContentRichlyEditable())
1286         pasteWithPasteboard(&pasteboard, true);
1287     else
1288         pasteAsPlainTextWithPasteboard(pasteboard);
1289 }
1290
1291 void Editor::pasteAsPlainText()
1292 {
1293     if (tryDHTMLPaste())
1294         return;
1295     if (!canPaste())
1296         return;
1297     updateMarkersForWordsAffectedByEditing(false);
1298     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
1299 }
1300
1301 void Editor::performDelete()
1302 {
1303     if (!canDelete()) {
1304         systemBeep();
1305         return;
1306     }
1307
1308     addRangeToKillRing(*selectedRange().get(), KillRingInsertionMode::AppendText);
1309     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1310
1311     // clear the "start new kill ring sequence" setting, because it was set to true
1312     // when the selection was updated by deleting the range
1313     setStartNewKillRingSequence(false);
1314 }
1315
1316 void Editor::simplifyMarkup(Node* startNode, Node* endNode)
1317 {
1318     if (!startNode)
1319         return;
1320     if (endNode) {
1321         if (&startNode->document() != &endNode->document())
1322             return;
1323         // check if start node is before endNode
1324         Node* node = startNode;
1325         while (node && node != endNode)
1326             node = NodeTraversal::next(*node);
1327         if (!node)
1328             return;
1329     }
1330     
1331     applyCommand(SimplifyMarkupCommand::create(document(), startNode, endNode ? NodeTraversal::next(*endNode) : nullptr));
1332 }
1333
1334 void Editor::copyURL(const URL& url, const String& title)
1335 {
1336     copyURL(url, title, *Pasteboard::createForCopyAndPaste());
1337 }
1338
1339 void Editor::copyURL(const URL& url, const String& title, Pasteboard& pasteboard)
1340 {
1341     PasteboardURL pasteboardURL;
1342     pasteboardURL.url = url;
1343     pasteboardURL.title = title;
1344
1345 #if PLATFORM(MAC)
1346     fillInUserVisibleForm(pasteboardURL);
1347 #endif
1348
1349     pasteboard.write(pasteboardURL);
1350 }
1351
1352 #if !PLATFORM(IOS)
1353
1354 void Editor::copyImage(const HitTestResult& result)
1355 {
1356     Element* element = result.innerNonSharedElement();
1357     if (!element)
1358         return;
1359
1360     URL url = result.absoluteLinkURL();
1361     if (url.isEmpty())
1362         url = result.absoluteImageURL();
1363
1364 #if PLATFORM(COCOA) || PLATFORM(EFL) || PLATFORM(GTK)
1365     writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *element, url, result.altDisplayString());
1366 #else
1367     Pasteboard::createForCopyAndPaste()->writeImage(*element, url, result.altDisplayString());
1368 #endif
1369 }
1370
1371 #endif
1372
1373 bool Editor::isContinuousSpellCheckingEnabled() const
1374 {
1375     return client() && client()->isContinuousSpellCheckingEnabled();
1376 }
1377
1378 void Editor::toggleContinuousSpellChecking()
1379 {
1380     if (client())
1381         client()->toggleContinuousSpellChecking();
1382 }
1383
1384 bool Editor::isGrammarCheckingEnabled()
1385 {
1386     return client() && client()->isGrammarCheckingEnabled();
1387 }
1388
1389 void Editor::toggleGrammarChecking()
1390 {
1391     if (client())
1392         client()->toggleGrammarChecking();
1393 }
1394
1395 int Editor::spellCheckerDocumentTag()
1396 {
1397     return client() ? client()->spellCheckerDocumentTag() : 0;
1398 }
1399
1400 #if USE(APPKIT)
1401
1402 void Editor::uppercaseWord()
1403 {
1404     if (client())
1405         client()->uppercaseWord();
1406 }
1407
1408 void Editor::lowercaseWord()
1409 {
1410     if (client())
1411         client()->lowercaseWord();
1412 }
1413
1414 void Editor::capitalizeWord()
1415 {
1416     if (client())
1417         client()->capitalizeWord();
1418 }
1419     
1420 #endif
1421
1422 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1423
1424 void Editor::showSubstitutionsPanel()
1425 {
1426     if (!client()) {
1427         LOG_ERROR("No NSSpellChecker");
1428         return;
1429     }
1430
1431     if (client()->substitutionsPanelIsShowing()) {
1432         client()->showSubstitutionsPanel(false);
1433         return;
1434     }
1435     client()->showSubstitutionsPanel(true);
1436 }
1437
1438 bool Editor::substitutionsPanelIsShowing()
1439 {
1440     if (!client())
1441         return false;
1442     return client()->substitutionsPanelIsShowing();
1443 }
1444
1445 void Editor::toggleSmartInsertDelete()
1446 {
1447     if (client())
1448         client()->toggleSmartInsertDelete();
1449 }
1450
1451 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1452 {
1453     return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1454 }
1455
1456 void Editor::toggleAutomaticQuoteSubstitution()
1457 {
1458     if (client())
1459         client()->toggleAutomaticQuoteSubstitution();
1460 }
1461
1462 bool Editor::isAutomaticLinkDetectionEnabled()
1463 {
1464     return client() && client()->isAutomaticLinkDetectionEnabled();
1465 }
1466
1467 void Editor::toggleAutomaticLinkDetection()
1468 {
1469     if (client())
1470         client()->toggleAutomaticLinkDetection();
1471 }
1472
1473 bool Editor::isAutomaticDashSubstitutionEnabled()
1474 {
1475     return client() && client()->isAutomaticDashSubstitutionEnabled();
1476 }
1477
1478 void Editor::toggleAutomaticDashSubstitution()
1479 {
1480     if (client())
1481         client()->toggleAutomaticDashSubstitution();
1482 }
1483
1484 bool Editor::isAutomaticTextReplacementEnabled()
1485 {
1486     return client() && client()->isAutomaticTextReplacementEnabled();
1487 }
1488
1489 void Editor::toggleAutomaticTextReplacement()
1490 {
1491     if (client())
1492         client()->toggleAutomaticTextReplacement();
1493 }
1494
1495 bool Editor::isAutomaticSpellingCorrectionEnabled()
1496 {
1497     return m_alternativeTextController->isAutomaticSpellingCorrectionEnabled();
1498 }
1499
1500 void Editor::toggleAutomaticSpellingCorrection()
1501 {
1502     if (client())
1503         client()->toggleAutomaticSpellingCorrection();
1504 }
1505
1506 #endif
1507
1508 bool Editor::shouldEndEditing(Range* range)
1509 {
1510     return client() && client()->shouldEndEditing(range);
1511 }
1512
1513 bool Editor::shouldBeginEditing(Range* range)
1514 {
1515     return client() && client()->shouldBeginEditing(range);
1516 }
1517
1518 void Editor::clearUndoRedoOperations()
1519 {
1520     if (client())
1521         client()->clearUndoRedoOperations();
1522 }
1523
1524 bool Editor::canUndo()
1525 {
1526     return client() && client()->canUndo();
1527 }
1528
1529 void Editor::undo()
1530 {
1531     if (client())
1532         client()->undo();
1533 }
1534
1535 bool Editor::canRedo()
1536 {
1537     return client() && client()->canRedo();
1538 }
1539
1540 void Editor::redo()
1541 {
1542     if (client())
1543         client()->redo();
1544 }
1545
1546 void Editor::didBeginEditing()
1547 {
1548     if (client())
1549         client()->didBeginEditing();
1550 }
1551
1552 void Editor::didEndEditing()
1553 {
1554     if (client())
1555         client()->didEndEditing();
1556 }
1557
1558 void Editor::willWriteSelectionToPasteboard(PassRefPtr<Range> range)
1559 {
1560     if (client())
1561         client()->willWriteSelectionToPasteboard(range.get());
1562 }
1563
1564 void Editor::didWriteSelectionToPasteboard()
1565 {
1566     if (client())
1567         client()->didWriteSelectionToPasteboard();
1568 }
1569
1570 void Editor::toggleBold()
1571 {
1572     command("ToggleBold").execute();
1573 }
1574
1575 void Editor::toggleUnderline()
1576 {
1577     command("ToggleUnderline").execute();
1578 }
1579
1580 void Editor::setBaseWritingDirection(WritingDirection direction)
1581 {
1582 #if PLATFORM(IOS)
1583     if (inSameParagraph(m_frame.selection().selection().visibleStart(), m_frame.selection().selection().visibleEnd()) && 
1584         baseWritingDirectionForSelectionStart() == direction)
1585         return;
1586 #endif
1587         
1588     Element* focusedElement = document().focusedElement();
1589     if (is<HTMLTextFormControlElement>(focusedElement)) {
1590         if (direction == NaturalWritingDirection)
1591             return;
1592
1593         auto& focusedFormElement = downcast<HTMLTextFormControlElement>(*focusedElement);
1594         auto directionValue = direction == LeftToRightWritingDirection ? "ltr" : "rtl";
1595         auto writingDirectionInputTypeName = inputTypeNameForEditingAction(EditActionSetWritingDirection);
1596         if (!dispatchBeforeInputEvent(focusedFormElement, writingDirectionInputTypeName, directionValue))
1597             return;
1598
1599         focusedFormElement.setAttributeWithoutSynchronization(dirAttr, directionValue);
1600         dispatchInputEvent(focusedFormElement, writingDirectionInputTypeName, directionValue);
1601         document().updateStyleIfNeeded();
1602         return;
1603     }
1604
1605     RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
1606     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1607     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1608 }
1609
1610 WritingDirection Editor::baseWritingDirectionForSelectionStart() const
1611 {
1612     WritingDirection result = LeftToRightWritingDirection;
1613
1614     Position pos = m_frame.selection().selection().visibleStart().deepEquivalent();
1615     Node* node = pos.deprecatedNode();
1616     if (!node)
1617         return result;
1618
1619     auto renderer = node->renderer();
1620     if (!renderer)
1621         return result;
1622
1623     if (!renderer->isRenderBlockFlow()) {
1624         renderer = renderer->containingBlock();
1625         if (!renderer)
1626             return result;
1627     }
1628
1629     switch (renderer->style().direction()) {
1630     case LTR:
1631         return LeftToRightWritingDirection;
1632     case RTL:
1633         return RightToLeftWritingDirection;
1634     }
1635     
1636     return result;
1637 }
1638
1639 void Editor::selectComposition()
1640 {
1641     RefPtr<Range> range = compositionRange();
1642     if (!range)
1643         return;
1644     
1645     // The composition can start inside a composed character sequence, so we have to override checks.
1646     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1647     VisibleSelection selection;
1648     selection.setWithoutValidation(range->startPosition(), range->endPosition());
1649     m_frame.selection().setSelection(selection, 0);
1650 }
1651
1652 void Editor::confirmComposition()
1653 {
1654     if (!m_compositionNode)
1655         return;
1656     setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
1657 }
1658
1659 void Editor::cancelComposition()
1660 {
1661     if (!m_compositionNode)
1662         return;
1663     setComposition(emptyString(), CancelComposition);
1664 }
1665
1666 bool Editor::cancelCompositionIfSelectionIsInvalid()
1667 {
1668     unsigned start;
1669     unsigned end;
1670     if (!hasComposition() || ignoreCompositionSelectionChange() || getCompositionSelection(start, end))
1671         return false;
1672
1673     cancelComposition();
1674     return true;
1675 }
1676
1677 void Editor::confirmComposition(const String& text)
1678 {
1679     setComposition(text, ConfirmComposition);
1680 }
1681
1682 void Editor::setComposition(const String& text, SetCompositionMode mode)
1683 {
1684     ASSERT(mode == ConfirmComposition || mode == CancelComposition);
1685     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1686
1687     setIgnoreCompositionSelectionChange(true);
1688
1689     if (mode == CancelComposition)
1690         ASSERT(text == emptyString());
1691     else
1692         selectComposition();
1693
1694     m_compositionNode = nullptr;
1695     m_customCompositionUnderlines.clear();
1696
1697     if (m_frame.selection().isNone()) {
1698         setIgnoreCompositionSelectionChange(false);
1699         return;
1700     }
1701
1702     // Always delete the current composition before inserting the finalized composition text if we're confirming our composition.
1703     // Our default behavior (if the beforeinput event is not prevented) is to insert the finalized composition text back in.
1704     // We pass TypingCommand::TextCompositionPending here to indicate that we are deleting the pending composition.
1705     if (mode != CancelComposition)
1706         TypingCommand::deleteSelection(document(), 0, TypingCommand::TextCompositionPending);
1707
1708     insertTextForConfirmedComposition(text);
1709
1710     if (auto* target = document().focusedElement())
1711         target->dispatchEvent(CompositionEvent::create(eventNames().compositionendEvent, document().domWindow(), text));
1712
1713     if (mode == CancelComposition) {
1714         // An open typing command that disagrees about current selection would cause issues with typing later on.
1715         TypingCommand::closeTyping(&m_frame);
1716     }
1717
1718     setIgnoreCompositionSelectionChange(false);
1719 }
1720
1721 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1722 {
1723     Ref<Frame> protection(m_frame);
1724
1725     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1726
1727     setIgnoreCompositionSelectionChange(true);
1728
1729     // Updates styles before setting selection for composition to prevent
1730     // inserting the previous composition text into text nodes oddly.
1731     // See https://bugs.webkit.org/show_bug.cgi?id=46868
1732     document().updateStyleIfNeeded();
1733
1734     selectComposition();
1735
1736     if (m_frame.selection().isNone()) {
1737         setIgnoreCompositionSelectionChange(false);
1738         return;
1739     }
1740
1741     String originalText = selectedText();
1742     bool isStartingToRecomposeExistingRange = !text.isEmpty() && selectionStart < selectionEnd && !hasComposition();
1743     if (isStartingToRecomposeExistingRange) {
1744         // We pass TypingCommand::TextCompositionFinal here to indicate that we are removing composition text that has been finalized.
1745         TypingCommand::deleteSelection(document(), 0, TypingCommand::TextCompositionFinal);
1746         const VisibleSelection& currentSelection = m_frame.selection().selection();
1747         if (currentSelection.isRange()) {
1748             // If deletion was prevented, then we need to collapse the selection to the end so that the original text will not be recomposed.
1749             m_frame.selection().setSelection({ currentSelection.end(), currentSelection.end() });
1750         }
1751     }
1752
1753 #if PLATFORM(IOS)
1754     client()->startDelayingAndCoalescingContentChangeNotifications();
1755 #endif
1756
1757     Element* target = document().focusedElement();
1758     if (target) {
1759         // Dispatch an appropriate composition event to the focused node.
1760         // We check the composition status and choose an appropriate composition event since this
1761         // function is used for three purposes:
1762         // 1. Starting a new composition.
1763         //    Send a compositionstart and a compositionupdate event when this function creates
1764         //    a new composition node, i.e.
1765         //    m_compositionNode == 0 && !text.isEmpty().
1766         //    Sending a compositionupdate event at this time ensures that at least one
1767         //    compositionupdate event is dispatched.
1768         // 2. Updating the existing composition node.
1769         //    Send a compositionupdate event when this function updates the existing composition
1770         //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
1771         // 3. Canceling the ongoing composition.
1772         //    Send a compositionend event when function deletes the existing composition node, i.e.
1773         //    m_compositionNode != 0 && test.isEmpty().
1774         RefPtr<CompositionEvent> event;
1775         if (!m_compositionNode) {
1776             // We should send a compositionstart event only when the given text is not empty because this
1777             // function doesn't create a composition node when the text is empty.
1778             if (!text.isEmpty()) {
1779                 target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, document().domWindow(), originalText));
1780                 event = CompositionEvent::create(eventNames().compositionupdateEvent, document().domWindow(), text);
1781             }
1782         } else if (!text.isEmpty())
1783             event = CompositionEvent::create(eventNames().compositionupdateEvent, document().domWindow(), text);
1784
1785         if (event)
1786             target->dispatchEvent(*event);
1787     }
1788
1789     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1790     // will delete the old composition with an optimized replace operation.
1791     if (text.isEmpty()) {
1792         TypingCommand::deleteSelection(document(), TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionPending);
1793         if (target)
1794             target->dispatchEvent(CompositionEvent::create(eventNames().compositionendEvent, document().domWindow(), text));
1795     }
1796
1797     m_compositionNode = nullptr;
1798     m_customCompositionUnderlines.clear();
1799
1800     if (!text.isEmpty()) {
1801         TypingCommand::insertText(document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionPending);
1802
1803         // Find out what node has the composition now.
1804         Position base = m_frame.selection().selection().base().downstream();
1805         Position extent = m_frame.selection().selection().extent();
1806         Node* baseNode = base.deprecatedNode();
1807         unsigned baseOffset = base.deprecatedEditingOffset();
1808         Node* extentNode = extent.deprecatedNode();
1809         unsigned extentOffset = extent.deprecatedEditingOffset();
1810
1811         if (is<Text>(baseNode) && baseNode == extentNode && baseOffset + text.length() == extentOffset) {
1812             m_compositionNode = downcast<Text>(baseNode);
1813             m_compositionStart = baseOffset;
1814             m_compositionEnd = extentOffset;
1815             m_customCompositionUnderlines = underlines;
1816             for (auto& underline : m_customCompositionUnderlines) {
1817                 underline.startOffset += baseOffset;
1818                 underline.endOffset += baseOffset;
1819             }
1820             if (baseNode->renderer())
1821                 baseNode->renderer()->repaint();
1822
1823             unsigned start = std::min(baseOffset + selectionStart, extentOffset);
1824             unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
1825             RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
1826             m_frame.selection().setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1827         }
1828     }
1829
1830     setIgnoreCompositionSelectionChange(false);
1831
1832 #if PLATFORM(IOS)        
1833     client()->stopDelayingAndCoalescingContentChangeNotifications();
1834 #endif
1835 }
1836
1837 void Editor::ignoreSpelling()
1838 {
1839     if (!client())
1840         return;
1841         
1842     RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange();
1843     if (selectedRange)
1844         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1845
1846     String text = selectedText();
1847     ASSERT(text.length());
1848     textChecker()->ignoreWordInSpellDocument(text);
1849 }
1850
1851 void Editor::learnSpelling()
1852 {
1853     if (!client())
1854         return;
1855         
1856     // 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>.
1857
1858     RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange();
1859     if (selectedRange)
1860         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1861
1862     String text = selectedText();
1863     ASSERT(text.length());
1864     textChecker()->learnWord(text);
1865 }
1866
1867 #if !PLATFORM(IOS)
1868
1869 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1870 {
1871     Ref<Frame> protection(m_frame);
1872
1873     // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1874     // then we wrap and search from the doc start to (approximately) where we started.
1875     
1876     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
1877     // repeated "check spelling" commands work.
1878     VisibleSelection selection(m_frame.selection().selection());
1879     RefPtr<Range> spellingSearchRange(rangeOfContents(document()));
1880
1881     bool startedWithSelection = false;
1882     if (selection.start().deprecatedNode()) {
1883         startedWithSelection = true;
1884         if (startBeforeSelection) {
1885             VisiblePosition start(selection.visibleStart());
1886             // We match AppKit's rule: Start 1 character before the selection.
1887             VisiblePosition oneBeforeStart = start.previous();
1888             setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1889         } else
1890             setStart(spellingSearchRange.get(), selection.visibleEnd());
1891     }
1892
1893     Position position = spellingSearchRange->startPosition();
1894     if (!isEditablePosition(position)) {
1895         // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1896         // selection is editable.
1897         // This can happen in Mail for a mix of non-editable and editable content (like Stationary), 
1898         // when spell checking the whole document before sending the message.
1899         // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1900
1901         position = VisiblePosition(firstEditablePositionAfterPositionInRoot(position, document().documentElement())).deepEquivalent();
1902         if (position.isNull())
1903             return;
1904         
1905         Position rangeCompliantPosition = position.parentAnchoredEquivalent();
1906         if (rangeCompliantPosition.deprecatedNode())
1907             spellingSearchRange->setStart(*rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset());
1908         startedWithSelection = false; // won't need to wrap
1909     }
1910     
1911     // topNode defines the whole range we want to operate on 
1912     auto* topNode = highestEditableRoot(position);
1913     // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
1914     if (topNode)
1915         spellingSearchRange->setEnd(*topNode, lastOffsetForEditing(*topNode));
1916
1917     // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1918     // at a word boundary. Going back by one char and then forward by a word does the trick.
1919     if (startedWithSelection) {
1920         VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1921         if (oneBeforeStart.isNotNull())
1922             setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1923         // else we were already at the start of the editable node
1924     }
1925
1926     if (spellingSearchRange->collapsed())
1927         return; // nothing to search in
1928     
1929     // Get the spell checker if it is available
1930     if (!client())
1931         return;
1932         
1933     // We go to the end of our first range instead of the start of it, just to be sure
1934     // we don't get foiled by any word boundary problems at the start.  It means we might
1935     // do a tiny bit more searching.
1936     Node& searchEndNodeAfterWrap = spellingSearchRange->endContainer();
1937     int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();
1938     
1939     int misspellingOffset = 0;
1940     GrammarDetail grammarDetail;
1941     int grammarPhraseOffset = 0;
1942     RefPtr<Range> grammarSearchRange;
1943     String badGrammarPhrase;
1944     String misspelledWord;
1945
1946     bool isSpelling = true;
1947     int foundOffset = 0;
1948     String foundItem;
1949     RefPtr<Range> firstMisspellingRange;
1950     if (unifiedTextCheckerEnabled()) {
1951         grammarSearchRange = spellingSearchRange->cloneRange();
1952         foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1953         if (isSpelling) {
1954             misspelledWord = foundItem;
1955             misspellingOffset = foundOffset;
1956         } else {
1957             badGrammarPhrase = foundItem;
1958             grammarPhraseOffset = foundOffset;
1959         }
1960     } else {
1961         misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1962
1963 #if USE(GRAMMAR_CHECKING)
1964         grammarSearchRange = spellingSearchRange->cloneRange();
1965         if (!misspelledWord.isEmpty()) {
1966             // Stop looking at start of next misspelled word
1967             CharacterIterator chars(*grammarSearchRange);
1968             chars.advance(misspellingOffset);
1969             grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset());
1970         }
1971     
1972         if (isGrammarCheckingEnabled())
1973             badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1974 #endif
1975     }
1976     
1977     // 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
1978     // block rather than at a selection).
1979     if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
1980         if (topNode)
1981             spellingSearchRange->setStart(*topNode, 0);
1982         // going until the end of the very first chunk we tested is far enough
1983         spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap);
1984         
1985         if (unifiedTextCheckerEnabled()) {
1986             grammarSearchRange = spellingSearchRange->cloneRange();
1987             foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1988             if (isSpelling) {
1989                 misspelledWord = foundItem;
1990                 misspellingOffset = foundOffset;
1991             } else {
1992                 badGrammarPhrase = foundItem;
1993                 grammarPhraseOffset = foundOffset;
1994             }
1995         } else {
1996             misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1997
1998 #if USE(GRAMMAR_CHECKING)
1999             grammarSearchRange = spellingSearchRange->cloneRange();
2000             if (!misspelledWord.isEmpty()) {
2001                 // Stop looking at start of next misspelled word
2002                 CharacterIterator chars(*grammarSearchRange);
2003                 chars.advance(misspellingOffset);
2004                 grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset());
2005             }
2006
2007             if (isGrammarCheckingEnabled())
2008                 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
2009 #endif
2010         }
2011     }
2012     
2013 #if !USE(GRAMMAR_CHECKING)
2014     ASSERT(badGrammarPhrase.isEmpty());
2015     UNUSED_PARAM(grammarPhraseOffset);
2016 #else
2017     if (!badGrammarPhrase.isEmpty()) {
2018         // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
2019         // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
2020         // panel, and store a marker so we draw the green squiggle later.
2021         
2022         ASSERT(badGrammarPhrase.length() > 0);
2023         ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
2024         
2025         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
2026         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
2027         m_frame.selection().setSelection(VisibleSelection(*badGrammarRange, SEL_DEFAULT_AFFINITY));
2028         m_frame.selection().revealSelection();
2029         
2030         client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
2031         document().markers().addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
2032     } else
2033 #endif
2034     if (!misspelledWord.isEmpty()) {
2035         // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
2036         // a marker so we draw the red squiggle later.
2037         
2038         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
2039         m_frame.selection().setSelection(VisibleSelection(*misspellingRange, DOWNSTREAM));
2040         m_frame.selection().revealSelection();
2041         
2042         client()->updateSpellingUIWithMisspelledWord(misspelledWord);
2043         document().markers().addMarker(misspellingRange.get(), DocumentMarker::Spelling);
2044     }
2045 }
2046
2047 #endif // !PLATFORM(IOS)
2048
2049 String Editor::misspelledWordAtCaretOrRange(Node* clickedNode) const
2050 {
2051     if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
2052         return String();
2053
2054     VisibleSelection selection = m_frame.selection().selection();
2055     if (!selection.isContentEditable() || selection.isNone())
2056         return String();
2057
2058     VisibleSelection wordSelection(selection.base());
2059     wordSelection.expandUsingGranularity(WordGranularity);
2060     RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
2061
2062     // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
2063     // selection exactly match the word selection.
2064     if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
2065         return String();
2066
2067     String word = wordRange->text();
2068     if (word.isEmpty() || !client())
2069         return String();
2070
2071     int wordLength = word.length();
2072     int misspellingLocation = -1;
2073     int misspellingLength = 0;
2074     textChecker()->checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
2075
2076     return misspellingLength == wordLength ? word : String();
2077 }
2078
2079 String Editor::misspelledSelectionString() const
2080 {
2081     String selectedString = selectedText();
2082     int length = selectedString.length();
2083     if (!length || !client())
2084         return String();
2085
2086     int misspellingLocation = -1;
2087     int misspellingLength = 0;
2088     textChecker()->checkSpellingOfString(selectedString, &misspellingLocation, &misspellingLength);
2089     
2090     // The selection only counts as misspelled if the selected text is exactly one misspelled word
2091     if (misspellingLength != length)
2092         return String();
2093     
2094     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
2095     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
2096     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
2097     // or a grammar error.
2098     client()->updateSpellingUIWithMisspelledWord(selectedString);
2099     
2100     return selectedString;
2101 }
2102
2103 bool Editor::isSelectionUngrammatical()
2104 {
2105 #if USE(GRAMMAR_CHECKING)
2106     RefPtr<Range> range = m_frame.selection().toNormalizedRange();
2107     if (!range)
2108         return false;
2109     return TextCheckingHelper(client(), range).isUngrammatical();
2110 #else
2111     return false;
2112 #endif
2113 }
2114
2115 Vector<String> Editor::guessesForMisspelledWord(const String& word) const
2116 {
2117     ASSERT(word.length());
2118
2119     Vector<String> guesses;
2120     if (client())
2121         textChecker()->getGuessesForWord(word, String(), m_frame.selection().selection(), guesses);
2122     return guesses;
2123 }
2124
2125 Vector<String> Editor::guessesForMisspelledOrUngrammatical(bool& misspelled, bool& ungrammatical)
2126 {
2127     if (unifiedTextCheckerEnabled()) {
2128         RefPtr<Range> range;
2129         VisibleSelection selection = m_frame.selection().selection();
2130         if (selection.isCaret() && behavior().shouldAllowSpellingSuggestionsWithoutSelection()) {
2131             VisibleSelection wordSelection = VisibleSelection(selection.base());
2132             wordSelection.expandUsingGranularity(WordGranularity);
2133             range = wordSelection.toNormalizedRange();
2134         } else
2135             range = selection.toNormalizedRange();
2136         if (!range)
2137             return Vector<String>();
2138         return TextCheckingHelper(client(), range).guessesForMisspelledOrUngrammaticalRange(isGrammarCheckingEnabled(), misspelled, ungrammatical);
2139     }
2140
2141     String misspelledWord = behavior().shouldAllowSpellingSuggestionsWithoutSelection() ? misspelledWordAtCaretOrRange(document().focusedElement()) : misspelledSelectionString();
2142     misspelled = !misspelledWord.isEmpty();
2143     // Only unified text checker supports guesses for ungrammatical phrases.
2144     ungrammatical = false;
2145
2146     if (misspelled)
2147         return guessesForMisspelledWord(misspelledWord);
2148     return Vector<String>();
2149 }
2150
2151 void Editor::showSpellingGuessPanel()
2152 {
2153     if (!client()) {
2154         LOG_ERROR("No NSSpellChecker");
2155         return;
2156     }
2157
2158     if (client()->spellingUIIsShowing()) {
2159         client()->showSpellingUI(false);
2160         return;
2161     }
2162
2163 #if !PLATFORM(IOS)
2164     advanceToNextMisspelling(true);
2165 #endif
2166     client()->showSpellingUI(true);
2167 }
2168
2169 bool Editor::spellingPanelIsShowing()
2170 {
2171     if (!client())
2172         return false;
2173     return client()->spellingUIIsShowing();
2174 }
2175
2176 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
2177 {
2178     RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
2179     if (selectedRange) {
2180         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
2181         document().markers().removeMarkers(selectedRange.get(), DocumentMarker::Grammar);
2182     }
2183 }
2184
2185 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
2186 {
2187     markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
2188 }
2189
2190 void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
2191 {
2192     Ref<Frame> protection(m_frame);
2193
2194 #if PLATFORM(IOS)
2195     UNUSED_PARAM(selectionAfterTyping);
2196     UNUSED_PARAM(doReplacement);
2197     TextCheckingTypeMask textCheckingOptions = 0;
2198     if (isContinuousSpellCheckingEnabled())
2199         textCheckingOptions |= TextCheckingTypeSpelling;
2200     if (!(textCheckingOptions & TextCheckingTypeSpelling))
2201         return;
2202
2203     VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
2204     markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
2205 #else
2206 #if !USE(AUTOMATIC_TEXT_REPLACEMENT)
2207     UNUSED_PARAM(doReplacement);
2208 #endif
2209
2210     if (unifiedTextCheckerEnabled()) {
2211         m_alternativeTextController->applyPendingCorrection(selectionAfterTyping);
2212
2213         TextCheckingTypeMask textCheckingOptions = 0;
2214
2215         if (isContinuousSpellCheckingEnabled())
2216             textCheckingOptions |= TextCheckingTypeSpelling;
2217
2218 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2219         if (doReplacement
2220             && (isAutomaticQuoteSubstitutionEnabled()
2221                 || isAutomaticLinkDetectionEnabled()
2222                 || isAutomaticDashSubstitutionEnabled()
2223                 || isAutomaticTextReplacementEnabled()
2224                 || ((textCheckingOptions & TextCheckingTypeSpelling) && isAutomaticSpellingCorrectionEnabled())))
2225             textCheckingOptions |= TextCheckingTypeReplacement;
2226 #endif
2227         if (!(textCheckingOptions & (TextCheckingTypeSpelling | TextCheckingTypeReplacement)))
2228             return;
2229
2230         if (isGrammarCheckingEnabled())
2231             textCheckingOptions |= TextCheckingTypeGrammar;
2232
2233         VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
2234         if (textCheckingOptions & TextCheckingTypeGrammar) {
2235             VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
2236             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
2237         } else
2238             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
2239         return;
2240     }
2241
2242     if (!isContinuousSpellCheckingEnabled())
2243         return;
2244
2245     // Check spelling of one word
2246     RefPtr<Range> misspellingRange;
2247     markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
2248
2249     // Autocorrect the misspelled word.
2250     if (!misspellingRange)
2251         return;
2252     
2253     // Get the misspelled word.
2254     const String misspelledWord = plainText(misspellingRange.get());
2255     String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
2256
2257     // If autocorrected word is non empty, replace the misspelled word by this word.
2258     if (!autocorrectedString.isEmpty()) {
2259         VisibleSelection newSelection(*misspellingRange, DOWNSTREAM);
2260         if (newSelection != m_frame.selection().selection()) {
2261             if (!m_frame.selection().shouldChangeSelection(newSelection))
2262                 return;
2263             m_frame.selection().setSelection(newSelection);
2264         }
2265
2266         if (!m_frame.editor().shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
2267             return;
2268         m_frame.editor().replaceSelectionWithText(autocorrectedString, false, false, EditActionInsert);
2269
2270         // Reset the charet one character further.
2271         m_frame.selection().moveTo(m_frame.selection().selection().end());
2272         m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2273     }
2274
2275     if (!isGrammarCheckingEnabled())
2276         return;
2277     
2278     // Check grammar of entire sentence
2279     markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
2280 #endif
2281 }
2282     
2283 void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
2284 {
2285 #if !PLATFORM(IOS)
2286     // This function is called with a selection already expanded to word boundaries.
2287     // Might be nice to assert that here.
2288     
2289     // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
2290     // grammar checking can only be on if spell checking is also on.
2291     if (!isContinuousSpellCheckingEnabled())
2292         return;
2293     
2294     RefPtr<Range> searchRange(selection.toNormalizedRange());
2295     if (!searchRange)
2296         return;
2297     
2298     // If we're not in an editable node, bail.
2299     Node& editableNode = searchRange->startContainer();
2300     if (!editableNode.hasEditableStyle())
2301         return;
2302
2303     if (!isSpellCheckingEnabledFor(&editableNode))
2304         return;
2305
2306     // Get the spell checker if it is available
2307     if (!client())
2308         return;
2309     
2310     TextCheckingHelper checker(client(), searchRange);
2311     if (checkSpelling)
2312         checker.markAllMisspellings(firstMisspellingRange);
2313     else {
2314 #if USE(GRAMMAR_CHECKING)
2315         if (isGrammarCheckingEnabled())
2316             checker.markAllBadGrammar();
2317 #else
2318         ASSERT_NOT_REACHED();
2319 #endif
2320     }    
2321 #else
2322         UNUSED_PARAM(selection);
2323         UNUSED_PARAM(checkSpelling);
2324         UNUSED_PARAM(firstMisspellingRange);
2325 #endif // !PLATFORM(IOS)
2326 }
2327
2328 bool Editor::isSpellCheckingEnabledFor(Node* node) const
2329 {
2330     if (!node)
2331         return false;
2332     Element* element = is<Element>(*node) ? downcast<Element>(node) : node->parentElement();
2333     if (!element)
2334         return false;
2335     if (element->isInUserAgentShadowTree()) {
2336         if (HTMLTextFormControlElement* textControl = enclosingTextFormControl(firstPositionInOrBeforeNode(element)))
2337             return textControl->isSpellCheckingEnabled();
2338     }
2339     return element->isSpellCheckingEnabled();
2340 }
2341
2342 bool Editor::isSpellCheckingEnabledInFocusedNode() const
2343 {
2344     return isSpellCheckingEnabledFor(m_frame.selection().selection().start().deprecatedNode());
2345 }
2346
2347 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
2348 {
2349     markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
2350 }
2351     
2352 void Editor::markBadGrammar(const VisibleSelection& selection)
2353 {
2354 #if USE(GRAMMAR_CHECKING)
2355     RefPtr<Range> firstMisspellingRange;
2356     markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
2357 #else
2358     ASSERT_NOT_REACHED();
2359 #endif
2360 }
2361
2362 void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
2363 {
2364     ASSERT(unifiedTextCheckerEnabled());
2365
2366     // There shouldn't be pending autocorrection at this moment.
2367     ASSERT(!m_alternativeTextController->hasPendingCorrection());
2368
2369     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2370     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2371
2372     // This function is called with selections already expanded to word boundaries.
2373     if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
2374         return;
2375
2376     // If we're not in an editable node, bail.
2377     Node& editableNode = spellingRange->startContainer();
2378     if (!editableNode.hasEditableStyle())
2379         return;
2380
2381     if (!isSpellCheckingEnabledFor(&editableNode))
2382         return;
2383
2384     Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
2385     TextCheckingParagraph paragraphToCheck(rangeToCheck);
2386     if (paragraphToCheck.isEmpty())
2387         return;
2388     RefPtr<Range> paragraphRange = paragraphToCheck.paragraphRange();
2389
2390     bool asynchronous = m_frame.settings().asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
2391
2392     // In asynchronous mode, we intentionally check paragraph-wide sentence.
2393     const auto resolvedOptions = resolveTextCheckingTypeMask(editableNode, textCheckingOptions);
2394     auto request = SpellCheckRequest::create(resolvedOptions, TextCheckingProcessIncremental, asynchronous ? paragraphRange : rangeToCheck, paragraphRange);
2395
2396     if (asynchronous) {
2397         m_spellChecker->requestCheckingFor(WTFMove(request));
2398         return;
2399     }
2400
2401     Vector<TextCheckingResult> results;
2402     checkTextOfParagraph(*textChecker(), paragraphToCheck.text(), resolvedOptions, results, m_frame.selection().selection());
2403     markAndReplaceFor(WTFMove(request), results);
2404 }
2405
2406 static bool isAutomaticTextReplacementType(TextCheckingType type)
2407 {
2408     switch (type) {
2409     case TextCheckingTypeNone:
2410     case TextCheckingTypeSpelling:
2411     case TextCheckingTypeGrammar:
2412         return false;
2413     case TextCheckingTypeLink:
2414     case TextCheckingTypeQuote:
2415     case TextCheckingTypeDash:
2416     case TextCheckingTypeReplacement:
2417     case TextCheckingTypeCorrection:
2418     case TextCheckingTypeShowCorrectionPanel:
2419         return true;
2420     }
2421     ASSERT_NOT_REACHED();
2422     return false;
2423 }
2424
2425 static void correctSpellcheckingPreservingTextCheckingParagraph(TextCheckingParagraph& paragraph, PassRefPtr<Range> rangeToReplace, const String& replacement, int resultLocation, int resultLength)
2426 {
2427     auto& scope = downcast<ContainerNode>(paragraph.paragraphRange()->startContainer().rootNode());
2428
2429     size_t paragraphLocation;
2430     size_t paragraphLength;
2431     TextIterator::getLocationAndLengthFromRange(&scope, paragraph.paragraphRange().get(), paragraphLocation, paragraphLength);
2432
2433     applyCommand(SpellingCorrectionCommand::create(rangeToReplace, replacement));
2434
2435     // TextCheckingParagraph may be orphaned after SpellingCorrectionCommand mutated DOM.
2436     // See <rdar://10305315>, http://webkit.org/b/89526.
2437
2438     RefPtr<Range> newParagraphRange = TextIterator::rangeFromLocationAndLength(&scope, paragraphLocation, paragraphLength + replacement.length() - resultLength);
2439
2440     paragraph = TextCheckingParagraph(TextIterator::subrange(newParagraphRange.get(), resultLocation, replacement.length()), newParagraphRange);
2441 }
2442
2443 void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
2444 {
2445     Ref<Frame> protection(m_frame);
2446     ASSERT(request);
2447
2448     TextCheckingTypeMask textCheckingOptions = request->data().mask();
2449     TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
2450
2451     const bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
2452     const bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2453     const bool shouldMarkLink = textCheckingOptions & TextCheckingTypeLink;
2454     const bool shouldPerformReplacement = textCheckingOptions & (TextCheckingTypeQuote | TextCheckingTypeDash | TextCheckingTypeReplacement);
2455     const bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2456     const bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
2457 #if !USE(AUTOCORRECTION_PANEL)
2458     ASSERT(!shouldShowCorrectionPanel);
2459 #endif
2460
2461     // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2462     int selectionOffset = 0;
2463     bool useAmbiguousBoundaryOffset = false;
2464     bool selectionChanged = false;
2465     bool restoreSelectionAfterChange = false;
2466     bool adjustSelectionForParagraphBoundaries = false;
2467
2468     if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2469         if (m_frame.selection().selection().selectionType() == VisibleSelection::CaretSelection) {
2470             // Attempt to save the caret position so we can restore it later if needed
2471             Position caretPosition = m_frame.selection().selection().end();
2472             selectionOffset = paragraph.offsetTo(caretPosition).releaseReturnValue();
2473             restoreSelectionAfterChange = true;
2474             if (selectionOffset > 0 && (selectionOffset > paragraph.textLength() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2475                 adjustSelectionForParagraphBoundaries = true;
2476             if (selectionOffset > 0 && selectionOffset <= paragraph.textLength() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
2477                 useAmbiguousBoundaryOffset = true;
2478         }
2479     }
2480
2481     int offsetDueToReplacement = 0;
2482
2483     for (unsigned i = 0; i < results.size(); i++) {
2484         const int spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
2485         const TextCheckingType resultType = results[i].type;
2486         const int resultLocation = results[i].location + offsetDueToReplacement;
2487         const int resultLength = results[i].length;
2488         const int resultEndLocation = resultLocation + resultLength;
2489         const String& replacement = results[i].replacement;
2490         const bool resultEndsAtAmbiguousBoundary = useAmbiguousBoundaryOffset && selectionOffset - 1 <= resultEndLocation;
2491
2492         // Only mark misspelling if:
2493         // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2494         // 2. Result falls within spellingRange.
2495         // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2496         //    "wouldn'" as misspelled right after apostrophe is typed.
2497         if (shouldMarkSpelling && !shouldShowCorrectionPanel && resultType == TextCheckingTypeSpelling
2498             && resultLocation >= paragraph.checkingStart() && resultEndLocation <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2499             ASSERT(resultLength > 0 && resultLocation >= 0);
2500             RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
2501             if (!m_alternativeTextController->isSpellingMarkerAllowed(misspellingRange))
2502                 continue;
2503             misspellingRange->startContainer().document().markers().addMarker(misspellingRange.get(), DocumentMarker::Spelling, replacement);
2504         } else if (shouldMarkGrammar && resultType == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
2505             ASSERT(resultLength > 0 && resultLocation >= 0);
2506             for (auto& detail : results[i].details) {
2507                 ASSERT(detail.length > 0 && detail.location >= 0);
2508                 if (paragraph.checkingRangeCovers(resultLocation + detail.location, detail.length)) {
2509                     RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail.location, detail.length);
2510                     badGrammarRange->startContainer().document().markers().addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail.userDescription);
2511                 }
2512             }
2513         } else if (resultEndLocation <= spellingRangeEndOffset && resultEndLocation >= paragraph.checkingStart()
2514             && isAutomaticTextReplacementType(resultType)) {
2515             // In this case the result range just has to touch the spelling range, so we can handle replacing non-word text such as punctuation.
2516             ASSERT(resultLength > 0 && resultLocation >= 0);
2517
2518             if (shouldShowCorrectionPanel && (resultEndLocation < spellingRangeEndOffset
2519                 || !(resultType & (TextCheckingTypeReplacement | TextCheckingTypeCorrection))))
2520                 continue;
2521
2522             // Apply replacement if:
2523             // 1. The replacement length is non-zero.
2524             // 2. The result doesn't end at an ambiguous boundary.
2525             //    (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2526             bool doReplacement = replacement.length() > 0 && !resultEndsAtAmbiguousBoundary;
2527             RefPtr<Range> rangeToReplace = paragraph.subrange(resultLocation, resultLength);
2528
2529             // adding links should be done only immediately after they are typed
2530             if (resultType == TextCheckingTypeLink && selectionOffset != resultEndLocation + 1)
2531                 continue;
2532
2533             if (!(shouldPerformReplacement || shouldCheckForCorrection || shouldMarkLink) || !doReplacement)
2534                 continue;
2535
2536             String replacedString = plainText(rangeToReplace.get());
2537             const bool existingMarkersPermitReplacement = m_alternativeTextController->processMarkersOnTextToBeReplacedByResult(&results[i], rangeToReplace.get(), replacedString);
2538             if (!existingMarkersPermitReplacement)
2539                 continue;
2540
2541             if (shouldShowCorrectionPanel) {
2542                 if (resultEndLocation == spellingRangeEndOffset) {
2543                     // We only show the correction panel on the last word.
2544                     m_alternativeTextController->show(rangeToReplace, replacement);
2545                     break;
2546                 }
2547                 // If this function is called for showing correction panel, we ignore other correction or replacement.
2548                 continue;
2549             }
2550
2551             VisibleSelection selectionToReplace(*rangeToReplace, DOWNSTREAM);
2552             if (selectionToReplace != m_frame.selection().selection()) {
2553                 if (!m_frame.selection().shouldChangeSelection(selectionToReplace))
2554                     continue;
2555             }
2556
2557             if (resultType == TextCheckingTypeLink) {
2558                 m_frame.selection().setSelection(selectionToReplace);
2559                 selectionChanged = true;
2560                 restoreSelectionAfterChange = false;
2561                 if (canEditRichly())
2562                     applyCommand(CreateLinkCommand::create(document(), replacement));
2563             } else if (canEdit() && shouldInsertText(replacement, rangeToReplace.get(), EditorInsertActionTyped)) {
2564                 correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, resultLocation, resultLength);
2565
2566                 if (AXObjectCache* cache = document().existingAXObjectCache()) {
2567                     if (Element* root = m_frame.selection().selection().rootEditableElement())
2568                         cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured);
2569                 }
2570
2571                 // Skip all other results for the replaced text.
2572                 while (i + 1 < results.size() && results[i + 1].location + offsetDueToReplacement <= resultLocation)
2573                     i++;
2574
2575                 selectionChanged = true;
2576                 offsetDueToReplacement += replacement.length() - resultLength;
2577                 if (resultLocation < selectionOffset)
2578                     selectionOffset += replacement.length() - resultLength;
2579
2580                 // Add a marker so that corrections can easily be undone and won't be re-corrected.
2581                 if (resultType == TextCheckingTypeCorrection)
2582                     m_alternativeTextController->markCorrection(paragraph.subrange(resultLocation, replacement.length()), replacedString);
2583             }
2584         }
2585     }
2586
2587     if (selectionChanged) {
2588         TextCheckingParagraph extendedParagraph(paragraph);
2589         // Restore the caret position if we have made any replacements
2590         extendedParagraph.expandRangeToNextEnd();
2591         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2592             RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
2593             m_frame.selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
2594             if (adjustSelectionForParagraphBoundaries)
2595                 m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2596         } else {
2597             // If this fails for any reason, the fallback is to go one position beyond the last replacement
2598             m_frame.selection().moveTo(m_frame.selection().selection().end());
2599             m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2600         }
2601     }
2602 }
2603
2604 void Editor::changeBackToReplacedString(const String& replacedString)
2605 {
2606 #if !PLATFORM(IOS)
2607     ASSERT(unifiedTextCheckerEnabled());
2608
2609     if (replacedString.isEmpty())
2610         return;
2611
2612     RefPtr<Range> selection = selectedRange();
2613     if (!shouldInsertText(replacedString, selection.get(), EditorInsertActionPasted))
2614         return;
2615     
2616     m_alternativeTextController->recordAutocorrectionResponseReversed(replacedString, selection);
2617     TextCheckingParagraph paragraph(selection);
2618     replaceSelectionWithText(replacedString, false, false, EditActionInsert);
2619     RefPtr<Range> changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2620     changedRange->startContainer().document().markers().addMarker(changedRange.get(), DocumentMarker::Replacement, String());
2621     m_alternativeTextController->markReversed(changedRange.get());
2622 #else
2623     ASSERT_NOT_REACHED();
2624     UNUSED_PARAM(replacedString);
2625 #endif // !PLATFORM(IOS)
2626 }
2627
2628
2629 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2630 {
2631     if (unifiedTextCheckerEnabled()) {
2632         if (!isContinuousSpellCheckingEnabled())
2633             return;
2634
2635         // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
2636         TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling;
2637         if (markGrammar && isGrammarCheckingEnabled())
2638             textCheckingOptions |= TextCheckingTypeGrammar;
2639         markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
2640         return;
2641     }
2642
2643     RefPtr<Range> firstMisspellingRange;
2644     markMisspellings(spellingSelection, firstMisspellingRange);
2645     if (markGrammar)
2646         markBadGrammar(grammarSelection);
2647 }
2648
2649 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2650 {
2651     m_alternativeTextController->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2652 }
2653
2654 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2655 {
2656     if (!document().markers().hasMarkers())
2657         return;
2658
2659     if (!m_alternativeTextController->shouldRemoveMarkersUponEditing() && (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)))
2660         return;
2661
2662     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2663     // several scenarios:
2664     // 1. Insert in the middle of a word.
2665     // 2. Appending non whitespace at the beginning of word.
2666     // 3. Appending non whitespace at the end of word.
2667     // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2668     // remove the markers on that word.
2669     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2670     // selection, and remove words between the selection boundaries.
2671     //
2672     VisiblePosition startOfSelection = m_frame.selection().selection().start();
2673     VisiblePosition endOfSelection = m_frame.selection().selection().end();
2674     if (startOfSelection.isNull())
2675         return;
2676     // First word is the word that ends after or on the start of selection.
2677     VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2678     VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2679     // Last word is the word that begins before or on the end of selection
2680     VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2681     VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2682
2683     if (startOfFirstWord.isNull()) {
2684         startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2685         endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2686     }
2687     
2688     if (endOfLastWord.isNull()) {
2689         startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2690         endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2691     }
2692
2693     // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2694     // we choose next word as the first word.
2695     if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2696         startOfFirstWord = nextWordPosition(startOfFirstWord);
2697         endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2698         if (startOfFirstWord == endOfSelection)
2699             return;
2700     }
2701
2702     // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2703     // we choose previous word as the last word.
2704     if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2705         startOfLastWord = previousWordPosition(startOfLastWord);
2706         endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2707         if (endOfLastWord == startOfSelection)
2708             return;
2709     }
2710
2711     if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2712         return;
2713
2714     // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2715     // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2716     // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2717     // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2718     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2719     // of marker that contains the word in question, and remove marker on that whole range.
2720     RefPtr<Range> wordRange = Range::create(document(), startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2721
2722     Vector<RenderedDocumentMarker*> markers = document().markers().markersInRange(wordRange.get(), DocumentMarker::DictationAlternatives);
2723     for (auto* marker : markers)
2724         m_alternativeTextController->removeDictationAlternativesForMarker(marker);
2725
2726 #if PLATFORM(IOS)
2727     document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption | DocumentMarker::DictationAlternatives | DocumentMarker::DictationPhraseWithAlternatives, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2728 #else
2729     document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption | DocumentMarker::DictationAlternatives, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2730 #endif
2731     document().markers().clearDescriptionOnMarkersIntersectingRange(wordRange.get(), DocumentMarker::Replacement);
2732 }
2733
2734 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2735 {
2736     m_alternativeTextController->deletedAutocorrectionAtPosition(position, originalString);
2737 }
2738
2739 PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
2740 {
2741     Document* document = m_frame.documentAtPoint(windowPoint);
2742     if (!document)
2743         return 0;
2744     
2745     Frame* frame = document->frame();
2746     ASSERT(frame);
2747     FrameView* frameView = frame->view();
2748     if (!frameView)
2749         return 0;
2750     IntPoint framePoint = frameView->windowToContents(windowPoint);
2751     VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2752
2753     return selection.toNormalizedRange();
2754 }
2755
2756 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
2757 {
2758     if (m_ignoreCompositionSelectionChange)
2759         return;
2760
2761 #if PLATFORM(IOS)
2762     SelectionRevealMode revealMode = SelectionRevealMode::RevealUpToMainFrame;
2763 #else
2764     SelectionRevealMode revealMode = SelectionRevealMode::Reveal;
2765 #endif
2766
2767     m_frame.selection().revealSelection(revealMode, alignment, revealExtentOption);
2768 }
2769
2770 void Editor::setIgnoreCompositionSelectionChange(bool ignore, RevealSelection shouldRevealExistingSelection)
2771 {
2772     if (m_ignoreCompositionSelectionChange == ignore)
2773         return;
2774
2775     m_ignoreCompositionSelectionChange = ignore;
2776 #if PLATFORM(IOS)
2777     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830> 
2778     if (!ignore)
2779         respondToChangedSelection(m_frame.selection().selection(), 0);
2780 #endif
2781     if (!ignore && shouldRevealExistingSelection == RevealSelection::Yes)
2782         revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
2783 }
2784
2785 RefPtr<Range> Editor::compositionRange() const
2786 {
2787     if (!m_compositionNode)
2788         return nullptr;
2789     unsigned length = m_compositionNode->length();
2790     unsigned start = std::min(m_compositionStart, length);
2791     unsigned end = std::min(std::max(start, m_compositionEnd), length);
2792     if (start >= end)
2793         return nullptr;
2794     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
2795 }
2796
2797 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
2798 {
2799     if (!m_compositionNode)
2800         return false;
2801     const VisibleSelection& selection = m_frame.selection().selection();
2802     Position start = selection.start();
2803     if (start.deprecatedNode() != m_compositionNode)
2804         return false;
2805     Position end = selection.end();
2806     if (end.deprecatedNode() != m_compositionNode)
2807         return false;
2808
2809     if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
2810         return false;
2811     if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
2812         return false;
2813
2814     selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
2815     selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
2816     return true;
2817 }
2818
2819 void Editor::transpose()
2820 {
2821     if (!canEdit())
2822         return;
2823
2824     VisibleSelection selection = m_frame.selection().selection();
2825     if (!selection.isCaret())
2826         return;
2827
2828     // Make a selection that goes back one character and forward two characters.
2829     VisiblePosition caret = selection.visibleStart();
2830     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
2831     VisiblePosition previous = next.previous();
2832     if (next == previous)
2833         return;
2834     previous = previous.previous();
2835     if (!inSameParagraph(next, previous))
2836         return;
2837     RefPtr<Range> range = makeRange(previous, next);
2838     if (!range)
2839         return;
2840     VisibleSelection newSelection(*range, DOWNSTREAM);
2841
2842     // Transpose the two characters.
2843     String text = plainText(range.get());
2844     if (text.length() != 2)
2845         return;
2846     String transposed = text.right(1) + text.left(1);
2847
2848     // Select the two characters.
2849     if (newSelection != m_frame.selection().selection()) {
2850         if (!m_frame.selection().shouldChangeSelection(newSelection))
2851             return;
2852         m_frame.selection().setSelection(newSelection);
2853     }
2854
2855     // Insert the transposed characters.
2856     if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
2857         return;
2858     replaceSelectionWithText(transposed, false, false, EditActionInsert);
2859 }
2860
2861 void Editor::addRangeToKillRing(const Range& range, KillRingInsertionMode mode)
2862 {
2863     addTextToKillRing(plainText(&range), mode);
2864 }
2865
2866 void Editor::addTextToKillRing(const String& text, KillRingInsertionMode mode)
2867 {
2868     if (m_shouldStartNewKillRingSequence)
2869         killRing().startNewSequence();
2870
2871     m_shouldStartNewKillRingSequence = false;
2872
2873     // If the kill was from a backwards motion, prepend to the kill ring.
2874     // This will ensure that alternating forward and backward kills will
2875     // build up the original string in the kill ring without permuting it.
2876     switch (mode) {
2877     case KillRingInsertionMode::PrependText:
2878         killRing().prepend(text);
2879         break;
2880     case KillRingInsertionMode::AppendText:
2881         killRing().append(text);
2882         break;
2883     }
2884 }
2885
2886 void Editor::startAlternativeTextUITimer()
2887 {
2888     m_alternativeTextController->startAlternativeTextUITimer(AlternativeTextTypeCorrection);
2889 }
2890
2891 void Editor::handleAlternativeTextUIResult(const String& correction)
2892 {
2893     m_alternativeTextController->handleAlternativeTextUIResult(correction);
2894 }
2895
2896
2897 void Editor::dismissCorrectionPanelAsIgnored()
2898 {
2899     m_alternativeTextController->dismiss(ReasonForDismissingAlternativeTextIgnored);
2900 }
2901
2902 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, FrameSelection::SetSelectionOptions options)
2903 {
2904     Ref<Frame> protection(m_frame);
2905
2906     // If the new selection is orphaned, then don't update the selection.
2907     if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
2908         return;
2909
2910     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
2911     // because there is work that it must do in this situation.
2912     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
2913     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
2914     bool selectionDidNotChangeDOMPosition = newSelection == m_frame.selection().selection();
2915     if (selectionDidNotChangeDOMPosition || m_frame.selection().shouldChangeSelection(newSelection))
2916         m_frame.selection().setSelection(newSelection, options);
2917
2918     // Some editing operations change the selection visually without affecting its position within the DOM.
2919     // For example when you press return in the following (the caret is marked by ^):
2920     // <div contentEditable="true"><div>^Hello</div></div>
2921     // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
2922     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
2923     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
2924     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
2925 #if PLATFORM(IOS)
2926     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830>
2927     if (m_ignoreCompositionSelectionChange)
2928         return;
2929 #endif
2930     if (selectionDidNotChangeDOMPosition && client())
2931         client()->respondToChangedSelection(&m_frame);
2932 }
2933
2934 String Editor::selectedText() const
2935 {
2936     return selectedText(TextIteratorDefaultBehavior);
2937 }
2938
2939 String Editor::selectedTextForDataTransfer() const
2940 {
2941     if (m_frame.settings().selectionIncludesAltImageText())
2942         return selectedText(TextIteratorEmitsImageAltText);
2943     return selectedText();
2944 }
2945
2946 String Editor::selectedText(TextIteratorBehavior behavior) const
2947 {
2948     // We remove '\0' characters because they are not visibly rendered to the user.
2949     return plainText(m_frame.selection().toNormalizedRange().get(), behavior).replaceWithLiteral('\0', "");
2950 }
2951
2952 static inline void collapseCaretWidth(IntRect& rect)
2953 {
2954     // FIXME: Width adjustment doesn't work for rotated text.
2955     if (rect.width() == caretWidth)
2956         rect.setWidth(0);
2957     else if (rect.height() == caretWidth)
2958         rect.setHeight(0);
2959 }
2960
2961 IntRect Editor::firstRectForRange(Range* range) const
2962 {
2963     VisiblePosition startVisiblePosition(range->startPosition(), DOWNSTREAM);
2964
2965     if (range->collapsed()) {
2966         // FIXME: Getting caret rect and removing caret width is a very roundabout way to get collapsed range location.
2967         // In particular, width adjustment doesn't work for rotated text.
2968         IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect();
2969         collapseCaretWidth(startCaretRect);
2970         return startCaretRect;
2971     }
2972
2973     VisiblePosition endVisiblePosition(range->endPosition(), UPSTREAM);
2974
2975     if (inSameLine(startVisiblePosition, endVisiblePosition))
2976         return enclosingIntRect(RenderObject::absoluteBoundingBoxRectForRange(range));
2977
2978     LayoutUnit extraWidthToEndOfLine = 0;
2979     IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect(&extraWidthToEndOfLine);
2980     if (startCaretRect == IntRect())
2981         return IntRect();
2982
2983     // When start and end aren't on the same line, we want to go from start to the end of its line.
2984     bool textIsHorizontal = startCaretRect.width() == caretWidth;
2985     return textIsHorizontal ?
2986         IntRect(startCaretRect.x(),
2987             startCaretRect.y(),
2988             startCaretRect.width() + extraWidthToEndOfLine,
2989             startCaretRect.height()) :
2990         IntRect(startCaretRect.x(),
2991             startCaretRect.y(),
2992             startCaretRect.width(),
2993             startCaretRect.height() + extraWidthToEndOfLine);
2994 }
2995
2996 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
2997 {
2998 #if PLATFORM(IOS)
2999     if (m_frame.selectionChangeCallbacksDisabled())
3000         return true;
3001 #endif
3002     return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
3003 }
3004
3005 void Editor::computeAndSetTypingStyle(EditingStyle& style, EditAction editingAction)
3006 {
3007     if (style.isEmpty()) {
3008         m_frame.selection().clearTypingStyle();
3009         return;
3010     }
3011
3012     // Calculate the current typing style.
3013     RefPtr<EditingStyle> typingStyle;
3014     if (auto existingTypingStyle = m_frame.selection().typingStyle())
3015         typingStyle = existingTypingStyle->copy();
3016     else
3017         typingStyle = EditingStyle::create();
3018     typingStyle->overrideTypingStyleAt(style, m_frame.selection().selection().visibleStart().deepEquivalent());
3019
3020     // Handle block styles, substracting these from the typing style.
3021     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
3022     if (!blockStyle->isEmpty())
3023         applyCommand(ApplyStyleCommand::create(document(), blockStyle.get(), editingAction));
3024
3025     // Set the remaining style as the typing style.
3026     m_frame.selection().setTypingStyle(typingStyle);
3027 }
3028
3029 void Editor::computeAndSetTypingStyle(StyleProperties& properties, EditAction editingAction)
3030 {
3031     return computeAndSetTypingStyle(EditingStyle::create(&properties), editingAction);
3032 }
3033
3034 void Editor::textFieldDidBeginEditing(Element* e)
3035 {
3036     if (client())
3037         client()->textFieldDidBeginEditing(e);
3038 }
3039
3040 void Editor::textFieldDidEndEditing(Element* e)
3041 {
3042     dismissCorrectionPanelAsIgnored();
3043     if (client())
3044         client()->textFieldDidEndEditing(e);
3045 }
3046
3047 void Editor::textDidChangeInTextField(Element* e)
3048 {
3049     if (client())
3050         client()->textDidChangeInTextField(e);
3051 }
3052
3053 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
3054 {
3055     if (client())
3056         return client()->doTextFieldCommandFromEvent(e, ke);
3057
3058     return false;
3059 }
3060
3061 void Editor::textWillBeDeletedInTextField(Element* input)
3062 {
3063     if (client())
3064         client()->textWillBeDeletedInTextField(input);
3065 }
3066
3067 void Editor::textDidChangeInTextArea(Element* e)
3068 {
3069     if (client())
3070         client()->textDidChangeInTextArea(e);
3071 }
3072
3073 void Editor::applyEditingStyleToBodyElement() const
3074 {
3075     auto collection = document().getElementsByTagName(HTMLNames::bodyTag.localName());
3076     unsigned length = collection->length();
3077     for (unsigned i = 0; i < length; ++i)
3078         applyEditingStyleToElement(collection->item(i));
3079 }
3080
3081 void Editor::applyEditingStyleToElement(Element* element) const
3082 {
3083     ASSERT(!element || is<StyledElement>(*element));
3084     if (!is<StyledElement>(element))
3085         return;
3086
3087     // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
3088     CSSStyleDeclaration* style = downcast<StyledElement>(*element).cssomStyle();
3089     style->setPropertyInternal(CSSPropertyWordWrap, "break-word", false);
3090     style->setPropertyInternal(CSSPropertyWebkitNbspMode, "space", false);
3091     style->setPropertyInternal(CSSPropertyWebkitLineBreak, "after-white-space", false);
3092 }
3093
3094 bool Editor::findString(const String& target, FindOptions options)
3095 {
3096     Ref<Frame> protection(m_frame);
3097
3098     VisibleSelection selection = m_frame.selection().selection();
3099
3100     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
3101
3102     if (!resultRange)
3103         return false;
3104
3105     m_frame.selection().setSelection(VisibleSelection(*resultRange, DOWNSTREAM));
3106
3107     if (!(options & DoNotRevealSelection))
3108         m_frame.selection().revealSelection();
3109
3110     return true;
3111 }
3112
3113 RefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
3114 {
3115     if (target.isEmpty())
3116         return nullptr;
3117
3118     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
3119     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
3120     RefPtr<Range> searchRange(rangeOfContents(document()));
3121
3122     bool forward = !(options & Backwards);
3123     bool startInReferenceRange = referenceRange && (options & StartInSelection);
3124     if (referenceRange) {
3125         if (forward)
3126             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
3127         else
3128             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
3129     }
3130
3131     RefPtr<Node> shadowTreeRoot = referenceRange ? referenceRange->startContainer().nonBoundaryShadowTreeRootNode() : nullptr;
3132     if (shadowTreeRoot) {
3133         if (forward)
3134             searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3135         else
3136             searchRange->setStart(*shadowTreeRoot, 0);
3137     }
3138
3139     RefPtr<Range> resultRange = findPlainText(*searchRange, target, options);
3140     // If we started in the reference range and the found range exactly matches the reference range, find again.
3141     // Build a selection with the found range to remove collapsed whitespace.
3142     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
3143     if (startInReferenceRange && areRangesEqual(VisibleSelection(*resultRange).toNormalizedRange().get(), referenceRange)) {
3144         searchRange = rangeOfContents(document());
3145         if (forward)
3146             searchRange->setStart(referenceRange->endPosition());
3147         else
3148             searchRange->setEnd(referenceRange->startPosition());
3149
3150         if (shadowTreeRoot) {
3151             if (forward)
3152                 searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3153             else
3154                 searchRange->setStart(*shadowTreeRoot, 0);
3155         }
3156
3157         resultRange = findPlainText(*searchRange, target, options);
3158     }
3159
3160     // If nothing was found in the shadow tree, search in main content following the shadow tree.
3161     if (resultRange->collapsed() && shadowTreeRoot) {
3162         searchRange = rangeOfContents(document());
3163         if (shadowTreeRoot->shadowHost()) {
3164             if (forward)
3165                 searchRange->setStartAfter(*shadowTreeRoot->shadowHost());
3166             else
3167                 searchRange->setEndBefore(*shadowTreeRoot->shadowHost());
3168         }
3169
3170         resultRange = findPlainText(*searchRange, target, options);
3171     }
3172
3173     // If we didn't find anything and we're wrapping, search again in the entire document (this will
3174     // redundantly re-search the area already searched in some cases).
3175     if (resultRange->collapsed() && options & WrapAround) {
3176         searchRange = rangeOfContents(document());
3177         resultRange = findPlainText(*searchRange, target, options);
3178         // We used to return false here if we ended up with the same range that we started with
3179         // (e.g., the reference range was already the only instance of this text). But we decided that
3180         // this should be a success case instead, so we'll just fall through in that case.
3181     }
3182
3183     return resultRange->collapsed() ? nullptr : resultRange;
3184 }
3185
3186 static bool isFrameInRange(Frame& frame, Range& range)
3187 {
3188     for (auto* ownerElement = frame.ownerElement(); ownerElement; ownerElement = ownerElement->document().ownerElement()) {
3189         if (&ownerElement->document() == &range.ownerDocument()) {
3190             auto result = range.intersectsNode(*ownerElement);
3191             return !result.hasException() && result.releaseReturnValue();
3192         }
3193     }
3194     return false;
3195 }
3196
3197 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches, Vector<RefPtr<Range>>* matches)
3198 {
3199     if (target.isEmpty())
3200         return 0;
3201
3202     RefPtr<Range> searchRange;
3203     if (range) {
3204         if (&range->ownerDocument() == &document())
3205             searchRange = range;
3206         else if (!isFrameInRange(m_frame, *range))
3207             return 0;
3208     }
3209     if (!searchRange)
3210         searchRange = rangeOfContents(document());
3211
3212     Node& originalEndContainer = searchRange->endContainer();
3213     int originalEndOffset = searchRange->endOffset();
3214
3215     unsigned matchCount = 0;
3216     do {
3217         RefPtr<Range> resultRange(findPlainText(*searchRange, target, options & ~Backwards));
3218         if (resultRange->collapsed()) {
3219             if (!resultRange->startContainer().isInShadowTree())
3220                 break;
3221
3222             searchRange->setStartAfter(*resultRange->startContainer().shadowHost());
3223             searchRange->setEnd(originalEndContainer, originalEndOffset);
3224             continue;
3225         }
3226
3227         ++matchCount;
3228         if (matches)
3229             matches->append(resultRange);
3230         
3231         if (markMatches)
3232             document().markers().addMarker(resultRange.get(), DocumentMarker::TextMatch);
3233
3234         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
3235         if (limit > 0 && matchCount >= limit)
3236             break;
3237
3238         // Set the new start for the search range to be the end of the previous
3239         // result range. There is no need to use a VisiblePosition here,
3240         // since findPlainText will use a TextIterator to go over the visible
3241         // text nodes. 
3242         searchRange->setStart(resultRange->endContainer(), resultRange->endOffset());
3243
3244         Node* shadowTreeRoot = searchRange->shadowRoot();
3245         if (searchRange->collapsed() && shadowTreeRoot)
3246             searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3247     } while (true);
3248
3249     return matchCount;
3250 }
3251
3252 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
3253 {
3254     if (flag == m_areMarkedTextMatchesHighlighted)
3255         return;
3256
3257     m_areMarkedTextMatchesHighlighted = flag;
3258     document().markers().repaintMarkers(DocumentMarker::TextMatch);
3259 }
3260
3261 #if !PLATFORM(MAC)
3262 void Editor::selectionWillChange()
3263 {
3264 }
3265 #endif
3266
3267 void Editor::respondToChangedSelection(const VisibleSelection&, FrameSelection::SetSelectionOptions options)
3268 {
3269 #if PLATFORM(IOS)
3270     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830> 
3271     if (m_ignoreCompositionSelectionChange)
3272         return;
3273 #endif
3274
3275     if (client())
3276         client()->respondToChangedSelection(&m_frame);
3277
3278 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
3279     if (shouldDetectTelephoneNumbers())
3280         m_telephoneNumberDetectionUpdateTimer.startOneShot(0);
3281 #endif
3282
3283     setStartNewKillRingSequence(true);
3284
3285     if (m_editorUIUpdateTimer.isActive())
3286         return;
3287
3288     // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
3289     m_editorUIUpdateTimerShouldCheckSpellingAndGrammar = options & FrameSelection::CloseTyping
3290         && !(options & FrameSelection::SpellCorrectionTriggered);
3291     m_editorUIUpdateTimerWasTriggeredByDictation = options & FrameSelection::DictationTriggered;
3292     m_editorUIUpdateTimer.startOneShot(0);
3293 }
3294
3295 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
3296
3297 bool Editor::shouldDetectTelephoneNumbers()
3298 {
3299     if (!m_frame.document())
3300         return false;
3301     return document().isTelephoneNumberParsingEnabled() && TelephoneNumberDetector::isSupported();
3302 }
3303
3304 void Editor::scanSelectionForTelephoneNumbers()
3305 {
3306     if (!shouldDetectTelephoneNumbers() || !client())
3307         return;
3308
3309     m_detectedTelephoneNumberRanges.clear();
3310
3311     Vector<RefPtr<Range>> markedRanges;
3312
3313     FrameSelection& frameSelection = m_frame.selection();
3314     if (!frameSelection.isRange()) {
3315         m_frame.mainFrame().servicesOverlayController().selectedTelephoneNumberRangesChanged();
3316         return;
3317     }
3318     RefPtr<Range> selectedRange = frameSelection.toNormalizedRange();
3319
3320     // Extend the range a few characters in each direction to detect incompletely selected phone numbers.
3321     static const int charactersToExtend = 15;
3322     const VisibleSelection& visibleSelection = frameSelection.selection();
3323     Position start = visibleSelection.start();
3324     Position end = visibleSelection.end();
3325     for (int i = 0; i < charactersToExtend; ++i) {
3326         start = start.previous(Character);
3327         end = end.next(Character);
3328     }
3329
3330     FrameSelection extendedSelection;
3331     extendedSelection.setStart(start);
3332     extendedSelection.setEnd(end);
3333     RefPtr<Range> extendedRange = extendedSelection.toNormalizedRange();
3334
3335     if (!extendedRange) {
3336         m_frame.mainFrame().servicesOverlayController().selectedTelephoneNumberRangesChanged();
3337         return;
3338     }
3339
3340     scanRangeForTelephoneNumbers(*extendedRange, extendedRange->text(), markedRanges);
3341
3342     // Only consider ranges with a detected telephone number if they overlap with the actual selection range.
3343     for (auto& range : markedRanges) {
3344         if (rangesOverlap(range.get(), selectedRange.get()))
3345             m_detectedTelephoneNumberRanges.append(range);
3346     }
3347
3348     m_frame.mainFrame().servicesOverlayController().selectedTelephoneNumberRangesChanged();
3349 }
3350
3351 void Editor::scanRangeForTelephoneNumbers(Range& range, const StringView& stringView, Vector<RefPtr<Range>>& markedRanges)
3352 {
3353     // Don't scan for phone numbers inside editable regions.
3354     Node& startNode = range.startContainer();
3355     if (startNode.hasEditableStyle())
3356         return;
3357
3358     // relativeStartPosition and relativeEndPosition are the endpoints of the phone number range,
3359     // relative to the scannerPosition
3360     unsigned length = stringView.length();
3361     unsigned scannerPosition = 0;
3362     int relativeStartPosition = 0;
3363     int relativeEndPosition = 0;
3364
3365     auto characters = stringView.upconvertedCharacters();
3366
3367     while (scannerPosition < length && TelephoneNumberDetector::find(&characters[scannerPosition], length - scannerPosition, &relativeStartPosition, &relativeEndPosition)) {
3368         // The convention in the Data Detectors framework is that the end position is the first character NOT in the phone number
3369         // (that is, the length of the range is relativeEndPosition - relativeStartPosition). So subtract 1 to get the same
3370         // convention as the old WebCore phone number parser (so that the rest of the code is still valid if we want to go back
3371         // to the old parser).
3372         --relativeEndPosition;
3373
3374         ASSERT(scannerPosition + relativeEndPosition < length);
3375
3376         unsigned subrangeOffset = scannerPosition + relativeStartPosition;
3377         unsigned subrangeLength = relativeEndPosition - relativeStartPosition + 1;
3378
3379         RefPtr<Range> subrange = TextIterator::subrange(&range, subrangeOffset, subrangeLength);
3380
3381         markedRanges.append(subrange);
3382         range.ownerDocument().markers().addMarker(subrange.get(), DocumentMarker::TelephoneNumber);
3383
3384         scannerPosition += relativeEndPosition + 1;
3385     }
3386 }
3387
3388 #endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
3389
3390 void Editor::updateEditorUINowIfScheduled()
3391 {
3392     if (!m_editorUIUpdateTimer.isActive())
3393         return;
3394     m_editorUIUpdateTimer.stop();
3395     editorUIUpdateTimerFired();
3396 }
3397
3398 void Editor::editorUIUpdateTimerFired()
3399 {
3400     VisibleSelection oldSelection = m_oldSelectionForEditorUIUpdate;
3401
3402     m_alternativeTextController->stopPendingCorrection(oldSelection);
3403     
3404     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
3405     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
3406     if (isContinuousSpellCheckingEnabled) {
3407         VisibleSelection newAdjacentWords;
3408         VisibleSelection newSelectedSentence;
3409         bool caretBrowsing = m_frame.settings().caretBrowsingEnabled();
3410         if (m_frame.selection().selection().isContentEditable() || caretBrowsing) {
3411             VisiblePosition newStart(m_frame.selection().selection().visibleStart());
3412 #if !PLATFORM(IOS)
3413             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
3414 #else
3415             // If this bug gets fixed, this PLATFORM(IOS) code could be removed:
3416             // <rdar://problem/7259611> Word boundary code on iPhone gives different results than desktop
3417             EWordSide startWordSide = LeftWordIfOnBoundary;
3418             UChar32 c = newStart.characterBefore();
3419             // FIXME: VisiblePosition::characterAfter() and characterBefore() do not emit newlines the same
3420             // way as TextIterator, so we do an isStartOfParagraph check here.
3421             if (isSpaceOrNewline(c) || c == 0xA0 || isStartOfParagraph(newStart)) {
3422                 startWordSide = RightWordIfOnBoundary;
3423             }
3424             newAdjacentWords = VisibleSelection(startOfWord(newStart, startWordSide), endOfWord(newStart, RightWordIfOnBoundary));
3425 #endif // !PLATFORM(IOS)
3426             if (isContinuousGrammarCheckingEnabled)
3427                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
3428         }
3429
3430         // When typing we check spelling elsewhere, so don't redo it here.
3431         // If this is a change in selection resulting from a delete operation,
3432         // oldSelection may no longer be in the document.
3433         if (m_editorUIUpdateTimerShouldCheckSpellingAndGrammar && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
3434             VisiblePosition oldStart(oldSelection.visibleStart());
3435             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
3436             if (oldAdjacentWords != newAdjacentWords) {
3437                 if (isContinuousGrammarCheckingEnabled) {
3438                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
3439                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
3440                 } else
3441                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
3442             }
3443         }
3444
3445         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
3446             if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3447                 document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3448         }
3449         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
3450             if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3451                 document().markers().removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3452         }
3453     }
3454
3455     // When continuous spell checking is off, existing markers disappear after the selection changes.
3456     if (!isContinuousSpellCheckingEnabled)
3457         document().markers().removeMarkers(DocumentMarker::Spelling);
3458     if (!isContinuousGrammarCheckingEnabled)
3459         document().markers().removeMarkers(DocumentMarker::Grammar);
3460
3461     if (!m_editorUIUpdateTimerWasTriggeredByDictation)
3462         m_alternativeTextController->respondToChangedSelection(oldSelection);
3463
3464     m_oldSelectionForEditorUIUpdate = m_frame.selection().selection();
3465 }
3466
3467 static Node* findFirstMarkable(Node* node)
3468 {
3469     while (node) {
3470         if (!node->renderer())
3471             return nullptr;
3472         if (node->renderer()->isTextOrLineBreak())
3473             return node;
3474         if (is<HTMLTextFormControlElement>(*node))
3475             node = downcast<HTMLTextFormControlElement>(*node).visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3476         else if (node->firstChild())
3477             node = node->firstChild();
3478         else
3479             node = node->nextSibling();
3480     }
3481
3482     return nullptr;
3483 }
3484
3485 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3486 {
3487     Node* node = findFirstMarkable(m_frame.selection().selection().start().deprecatedNode());
3488     if (!node)
3489         return false;
3490
3491     unsigned int startOffset = static_cast<unsigned int>(from);
3492     unsigned int endOffset = static_cast<unsigned int>(from + length);
3493     Vector<RenderedDocumentMarker*> markers = document().markers().markersFor(node);
3494     for (auto* marker : markers) {
3495         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3496             return true;
3497     }
3498
3499     return false;
3500 }       
3501
3502 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(const Node& rootEditableElement, TextCheckingTypeMask textCheckingOptions)
3503 {
3504 #if USE(AUTOMATIC_TEXT_REPLACEMENT) && !PLATFORM(IOS)
3505     bool onlyAllowsTextReplacement = false;
3506     if (auto* host = rootEditableElement.shadowHost())
3507         onlyAllowsTextReplacement = is<HTMLInputElement>(host) && downcast<HTMLInputElement>(*host).isSpellcheckDisabledExceptTextReplacement();
3508     if (onlyAllowsTextReplacement)
3509         textCheckingOptions &= TextCheckingTypeReplacement;
3510 #else
3511     UNUSED_PARAM(rootEditableElement);
3512 #endif
3513
3514     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3515     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3516 #if !PLATFORM(IOS)
3517     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3518     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3519 #endif
3520
3521     TextCheckingTypeMask checkingTypes = 0;
3522     if (shouldMarkSpelling)
3523         checkingTypes |= TextCheckingTypeSpelling;
3524     if (shouldMarkGrammar)
3525         checkingTypes |= TextCheckingTypeGrammar;
3526 #if !PLATFORM(IOS)
3527     if (shouldCheckForCorrection)
3528         checkingTypes |= TextCheckingTypeCorrection;
3529     if (shouldShowCorrectionPanel)
3530         checkingTypes |= TextCheckingTypeShowCorrectionPanel;
3531
3532 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3533     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3534     if (shouldPerformReplacement) {
3535         if (!onlyAllowsTextReplacement) {
3536             if (isAutomaticLinkDetectionEnabled())
3537                 checkingTypes |= TextCheckingTypeLink;
3538             if (isAutomaticQuoteSubstitutionEnabled())
3539                 checkingTypes |= TextCheckingTypeQuote;
3540             if (isAutomaticDashSubstitutionEnabled())
3541                 checkingTypes |= TextCheckingTypeDash;
3542             if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3543                 checkingTypes |= TextCheckingTypeCorrection;
3544         }
3545         if (isAutomaticTextReplacementEnabled())
3546             checkingTypes |= TextCheckingTypeReplacement;
3547     }
3548 #endif
3549 #endif // !PLATFORM(IOS)
3550
3551     return checkingTypes;
3552 }
3553
3554 static RefPtr<Range> candidateRangeForSelection(Frame& frame)
3555 {
3556     const VisibleSelection& selection = frame.selection().selection();
3557     return selection.isCaret() ? wordRangeFromPosition(selection.start()) : frame.selection().toNormalizedRange();
3558 }
3559
3560 static bool candidateWouldReplaceText(const VisibleSelection& selection)
3561 {
3562     // If the character behind the caret in the current selection is anything but a space or a newline then we should
3563     // replace the whole current word with the candidate.
3564     UChar32 characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection = 0;
3565     charactersAroundPosition(selection.visibleStart(), characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection);
3566     return !(characterBeforeSelection == '\0' || characterBeforeSelection == '\n' || characterBeforeSelection == ' ');
3567 }
3568
3569 String Editor::stringForCandidateRequest() const
3570 {
3571     const VisibleSelection& selection = m_frame.selection().selection();
3572     RefPtr<Range> rangeForCurrentlyTypedString = candidateRangeForSelection(m_frame);
3573     if (rangeForCurrentlyTypedString && candidateWouldReplaceText(selection))
3574         return plainText(rangeForCurrentlyTypedString.get());
3575
3576     return String();
3577 }
3578     
3579 RefPtr<Range> Editor::contextRangeForCandidateRequest() const
3580 {
3581     const VisibleSelection& selection = m_frame.selection().selection();
3582     return makeRange(startOfParagraph(selection.visibleStart()), endOfParagraph(selection.visibleEnd()));
3583 }
3584
3585 RefPtr<Range> Editor::rangeForTextCheckingResult(const TextCheckingResult& result) const
3586 {
3587     if (!result.length)
3588         return nullptr;
3589
3590     RefPtr<Range> contextRange = contextRangeForCandidateRequest();
3591     if (!contextRange)
3592         return nullptr;
3593
3594     return TextIterator::subrange(contextRange.get(), result.location, result.length);
3595 }
3596
3597 void Editor::handleAcceptedCandidate(TextCheckingResult acceptedCandidate)
3598 {
3599     const VisibleSelection& selection = m_frame.selection().selection();
3600
3601     m_isHandlingAcceptedCandidate = true;
3602
3603     if (auto range = rangeForTextCheckingResult(acceptedCandidate)) {
3604         if (shouldInsertText(acceptedCandidate.replacement, range.get(), EditorInsertActionTyped)) {
3605             Ref<ReplaceRangeWithTextCommand> replaceCommand = ReplaceRangeWithTextCommand::create(range.get(), acceptedCandidate.replacement);
3606             applyCommand(replaceCommand.ptr());
3607         }
3608     } else
3609         insertText(acceptedCandidate.replacement, nullptr);
3610
3611     RefPtr<Range> insertedCandidateRange = rangeExpandedByCharactersInDirectionAtWordBoundary(selection.visibleStart(), acceptedCandidate.replacement.length(), DirectionBackward);
3612     if (insertedCandidateRange)
3613         insertedCandidateRange->startContainer().document().markers().addMarker(insertedCandidateRange.get(), DocumentMarker::AcceptedCandidate, acceptedCandidate.replacement);
3614
3615     m_isHandlingAcceptedCandidate = false;
3616 }
3617
3618 bool Editor::unifiedTextCheckerEnabled() const
3619 {
3620     return WebCore::unifiedTextCheckerEnabled(&m_frame);
3621 }
3622
3623 Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker* marker)
3624 {
3625     return m_alternativeTextController->dictationAlternativesForMarker(marker);
3626 }
3627
3628 void Editor::applyDictationAlternativelternative(const String& alternativeString)
3629 {
3630     m_alternativeTextController->applyDictationAlternative(alternativeString);
3631 }
3632
3633 void Editor::toggleOverwriteModeEnabled()
3634 {
3635     m_overwriteModeEnabled = !m_overwriteModeEnabled;
3636     m_frame.selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
3637 }
3638
3639 Document& Editor::document() const
3640 {
3641     ASSERT(m_frame.document());
3642     return *m_frame.document();
3643 }
3644
3645 } // namespace WebCore