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