438737a5273c889af802c2f33eda20ea6890cf39
[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 = { }, Event::IsCancelable cancelable = Event::IsCancelable::Yes)
114 {
115     if (!element.document().settings().inputEventsEnabled())
116         return true;
117
118     auto event = InputEvent::create(eventNames().beforeinputEvent, inputType, 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, Event::IsCancelable::No,
131             element.document().windowProxy(), data, WTFMove(dataTransfer), targetRanges, 0));
132     } else
133         element.dispatchInputEvent();
134 }
135
136 static String inputEventDataForEditingStyleAndAction(const StyleProperties* style, EditAction action)
137 {
138     if (!style)
139         return { };
140
141     switch (action) {
142     case EditActionSetColor:
143         return style->getPropertyValue(CSSPropertyColor);
144     case EditActionSetWritingDirection:
145         return style->getPropertyValue(CSSPropertyDirection);
146     default:
147         return { };
148     }
149 }
150
151 static String inputEventDataForEditingStyleAndAction(EditingStyle& style, EditAction action)
152 {
153     return inputEventDataForEditingStyleAndAction(style.style(), action);
154 }
155
156 class ClearTextCommand : public DeleteSelectionCommand {
157 public:
158     ClearTextCommand(Document& document);
159     static void CreateAndApply(const RefPtr<Frame> frame);
160     
161 private:
162     EditAction editingAction() const override;
163 };
164
165 ClearTextCommand::ClearTextCommand(Document& document)
166     : DeleteSelectionCommand(document, false, true, false, false, true)
167 {
168 }
169
170 EditAction ClearTextCommand::editingAction() const
171 {
172     return EditActionDelete;
173 }
174
175 void ClearTextCommand::CreateAndApply(const RefPtr<Frame> frame)
176 {
177     if (frame->selection().isNone())
178         return;
179
180     // Don't leave around stale composition state.
181     frame->editor().clear();
182     
183     const VisibleSelection oldSelection = frame->selection().selection();
184     frame->selection().selectAll();
185     auto clearCommand = adoptRef(*new ClearTextCommand(*frame->document()));
186     clearCommand->setStartingSelection(oldSelection);
187     clearCommand->apply();
188 }
189
190 using namespace HTMLNames;
191 using namespace WTF;
192 using namespace Unicode;
193
194 TemporarySelectionChange::TemporarySelectionChange(Frame& frame, std::optional<VisibleSelection> temporarySelection, OptionSet<TemporarySelectionOption> options)
195     : m_frame(frame)
196     , m_options(options)
197     , m_wasIgnoringSelectionChanges(frame.editor().ignoreSelectionChanges())
198 #if PLATFORM(IOS)
199     , m_appearanceUpdatesWereEnabled(frame.selection().isUpdateAppearanceEnabled())
200 #endif
201 {
202 #if PLATFORM(IOS)
203     if (options & TemporarySelectionOptionEnableAppearanceUpdates)
204         frame.selection().setUpdateAppearanceEnabled(true);
205 #endif
206
207     if (options & TemporarySelectionOptionIgnoreSelectionChanges)
208         frame.editor().setIgnoreSelectionChanges(true);
209
210     if (temporarySelection) {
211         m_selectionToRestore = frame.selection().selection();
212         frame.selection().setSelection(temporarySelection.value());
213     }
214 }
215
216 TemporarySelectionChange::~TemporarySelectionChange()
217 {
218     if (m_selectionToRestore)
219         m_frame->selection().setSelection(m_selectionToRestore.value());
220
221     if (m_options & TemporarySelectionOptionIgnoreSelectionChanges) {
222         auto revealSelection = m_options & TemporarySelectionOptionRevealSelection ? Editor::RevealSelection::Yes : Editor::RevealSelection::No;
223         m_frame->editor().setIgnoreSelectionChanges(m_wasIgnoringSelectionChanges, revealSelection);
224     }
225
226 #if PLATFORM(IOS)
227     if (m_options & TemporarySelectionOptionEnableAppearanceUpdates)
228         m_frame->selection().setUpdateAppearanceEnabled(m_appearanceUpdatesWereEnabled);
229 #endif
230 }
231
232 // When an event handler has moved the selection outside of a text control
233 // we should use the target control's selection for this editing operation.
234 VisibleSelection Editor::selectionForCommand(Event* event)
235 {
236     auto selection = m_frame.selection().selection();
237     if (!event)
238         return selection;
239     // If the target is a text control, and the current selection is outside of its shadow tree,
240     // then use the saved selection for that text control.
241     if (is<Element>(event->target()) && downcast<Element>(*event->target()).isTextField()) {
242         auto& target = downcast<HTMLTextFormControlElement>(*event->target());
243         auto start = selection.start();
244         if (start.isNull() || &target != enclosingTextFormControl(start)) {
245             if (auto range = target.selection())
246                 return { *range, DOWNSTREAM, selection.isDirectional() };
247         }
248     }
249     return selection;
250 }
251
252 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
253 EditingBehavior Editor::behavior() const
254 {
255     return EditingBehavior(m_frame.settings().editingBehaviorType());
256 }
257
258 EditorClient* Editor::client() const
259 {
260     if (Page* page = m_frame.page())
261         return &page->editorClient();
262     return nullptr;
263 }
264
265 TextCheckerClient* Editor::textChecker() const
266 {
267     if (EditorClient* owner = client())
268         return owner->textChecker();
269     return 0;
270 }
271
272 void Editor::handleKeyboardEvent(KeyboardEvent& event)
273 {
274     if (EditorClient* c = client())
275         c->handleKeyboardEvent(&event);
276 }
277
278 void Editor::handleInputMethodKeydown(KeyboardEvent& event)
279 {
280     if (EditorClient* c = client())
281         c->handleInputMethodKeydown(&event);
282 }
283
284 bool Editor::handleTextEvent(TextEvent& event)
285 {
286     LOG(Editing, "Editor %p handleTextEvent (data %s)", this, event.data().utf8().data());
287
288     // Default event handling for Drag and Drop will be handled by DragController
289     // so we leave the event for it.
290     if (event.isDrop())
291         return false;
292
293     if (event.isPaste()) {
294         if (event.pastingFragment()) {
295 #if PLATFORM(IOS)
296             if (client()->performsTwoStepPaste(event.pastingFragment()))
297                 return true;
298 #endif
299             replaceSelectionWithFragment(*event.pastingFragment(), false, event.shouldSmartReplace(), event.shouldMatchStyle(), EditActionPaste, event.mailBlockquoteHandling());
300         } else
301             replaceSelectionWithText(event.data(), false, event.shouldSmartReplace(), EditActionPaste);
302         return true;
303     }
304
305     String data = event.data();
306     if (data == "\n") {
307         if (event.isLineBreak())
308             return insertLineBreak();
309         return insertParagraphSeparator();
310     }
311
312     return insertTextWithoutSendingTextEvent(data, false, &event);
313 }
314
315 bool Editor::canEdit() const
316 {
317     return m_frame.selection().selection().rootEditableElement();
318 }
319
320 bool Editor::canEditRichly() const
321 {
322     return m_frame.selection().selection().isContentRichlyEditable();
323 }
324
325 enum class ClipboardEventKind {
326     Copy,
327     Cut,
328     Paste,
329     PasteAsPlainText,
330     BeforeCopy,
331     BeforeCut,
332     BeforePaste,
333 };
334
335 static AtomicString eventNameForClipboardEvent(ClipboardEventKind kind)
336 {
337     switch (kind) {
338     case ClipboardEventKind::Copy:
339         return eventNames().copyEvent;
340     case ClipboardEventKind::Cut:
341         return eventNames().cutEvent;
342     case ClipboardEventKind::Paste:
343     case ClipboardEventKind::PasteAsPlainText:
344         return eventNames().pasteEvent;
345     case ClipboardEventKind::BeforeCopy:
346         return eventNames().beforecopyEvent;
347     case ClipboardEventKind::BeforeCut:
348         return eventNames().beforecutEvent;
349     case ClipboardEventKind::BeforePaste:
350         return eventNames().beforepasteEvent;
351     }
352     ASSERT_NOT_REACHED();
353     return { };
354 }
355
356 static Ref<DataTransfer> createDataTransferForClipboardEvent(Document& document, ClipboardEventKind kind)
357 {
358     switch (kind) {
359     case ClipboardEventKind::Copy:
360     case ClipboardEventKind::Cut:
361         return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::ReadWrite, std::make_unique<StaticPasteboard>());
362     case ClipboardEventKind::PasteAsPlainText:
363         if (RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled()) {
364             auto plainTextType = "text/plain"_s;
365             auto plainText = Pasteboard::createForCopyAndPaste()->readString(plainTextType);
366             auto pasteboard = std::make_unique<StaticPasteboard>();
367             pasteboard->writeString(plainTextType, plainText);
368             return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Readonly, WTFMove(pasteboard));
369         }
370         FALLTHROUGH;
371     case ClipboardEventKind::Paste:
372         return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Readonly, Pasteboard::createForCopyAndPaste());
373     case ClipboardEventKind::BeforeCopy:
374     case ClipboardEventKind::BeforeCut:
375     case ClipboardEventKind::BeforePaste:
376         return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Invalid, std::make_unique<StaticPasteboard>());
377     }
378     ASSERT_NOT_REACHED();
379     return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Invalid, std::make_unique<StaticPasteboard>());
380 }
381
382 // Returns whether caller should continue with "the default processing", which is the same as
383 // the event handler NOT setting the return value to false
384 // https://w3c.github.io/clipboard-apis/#fire-a-clipboard-event
385 static bool dispatchClipboardEvent(RefPtr<Element>&& target, ClipboardEventKind kind)
386 {
387     // FIXME: Move the target selection code here.
388     if (!target)
389         return true;
390
391     auto dataTransfer = createDataTransferForClipboardEvent(target->document(), kind);
392
393     auto event = ClipboardEvent::create(eventNameForClipboardEvent(kind), dataTransfer.copyRef());
394
395     target->dispatchEvent(event);
396     bool noDefaultProcessing = event->defaultPrevented();
397     if (noDefaultProcessing && (kind == ClipboardEventKind::Copy || kind == ClipboardEventKind::Cut)) {
398         auto pasteboard = Pasteboard::createForCopyAndPaste();
399         pasteboard->clear();
400         dataTransfer->commitToPasteboard(*pasteboard);
401     }
402
403     dataTransfer->makeInvalidForSecurity();
404
405     return !noDefaultProcessing;
406 }
407
408 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
409 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
410 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
411 // normally selectable to implement copy/paste (like divs, or a document body).
412
413 bool Editor::canDHTMLCut()
414 {
415     if (m_frame.selection().selection().isInPasswordField())
416         return false;
417
418     return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforeCut);
419 }
420
421 bool Editor::canDHTMLCopy()
422 {
423     if (m_frame.selection().selection().isInPasswordField())
424         return false;
425     return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforeCopy);
426 }
427
428 bool Editor::canDHTMLPaste()
429 {
430     return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforePaste);
431 }
432
433 bool Editor::canCut() const
434 {
435     return canCopy() && canDelete();
436 }
437
438 static HTMLImageElement* imageElementFromImageDocument(Document& document)
439 {
440     if (!document.isImageDocument())
441         return nullptr;
442     
443     HTMLElement* body = document.bodyOrFrameset();
444     if (!body)
445         return nullptr;
446     
447     Node* node = body->firstChild();
448     if (!is<HTMLImageElement>(node))
449         return nullptr;
450     return downcast<HTMLImageElement>(node);
451 }
452
453 bool Editor::canCopy() const
454 {
455     if (imageElementFromImageDocument(document()))
456         return true;
457     const VisibleSelection& selection = m_frame.selection().selection();
458     return selection.isRange() && !selection.isInPasswordField();
459 }
460
461 bool Editor::canPaste() const
462 {
463     if (m_frame.mainFrame().loader().shouldSuppressTextInputFromEditing())
464         return false;
465
466     return canEdit();
467 }
468
469 bool Editor::canDelete() const
470 {
471     const VisibleSelection& selection = m_frame.selection().selection();
472     return selection.isRange() && selection.rootEditableElement();
473 }
474
475 bool Editor::canDeleteRange(Range* range) const
476 {
477     Node& startContainer = range->startContainer();
478     Node& endContainer = range->endContainer();
479     
480     if (!startContainer.hasEditableStyle() || !endContainer.hasEditableStyle())
481         return false;
482
483     if (range->collapsed()) {
484         VisiblePosition start(range->startPosition(), DOWNSTREAM);
485         VisiblePosition previous = start.previous();
486         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
487         if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer.rootEditableElement())
488             return false;
489     }
490     return true;
491 }
492
493 bool Editor::smartInsertDeleteEnabled()
494 {   
495     return client() && client()->smartInsertDeleteEnabled();
496 }
497     
498 bool Editor::canSmartCopyOrDelete()
499 {
500     return client() && client()->smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
501 }
502
503 bool Editor::isSelectTrailingWhitespaceEnabled() const
504 {
505     return client() && client()->isSelectTrailingWhitespaceEnabled();
506 }
507
508 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool shouldAddToKillRing, bool isTypingAction)
509 {
510     if (!canEdit())
511         return false;
512
513     if (m_frame.selection().isRange()) {
514         if (isTypingAction) {
515             TypingCommand::deleteKeyPressed(document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
516             revealSelectionAfterEditingOperation();
517         } else {
518             if (shouldAddToKillRing)
519                 addRangeToKillRing(*selectedRange().get(), KillRingInsertionMode::AppendText);
520             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
521             // Implicitly calls revealSelectionAfterEditingOperation().
522         }
523     } else {
524         TypingCommand::Options options = 0;
525         if (canSmartCopyOrDelete())
526             options |= TypingCommand::SmartDelete;
527         if (shouldAddToKillRing)
528             options |= TypingCommand::AddsToKillRing;
529         switch (direction) {
530         case DirectionForward:
531         case DirectionRight:
532             TypingCommand::forwardDeleteKeyPressed(document(), options, granularity);
533             break;
534         case DirectionBackward:
535         case DirectionLeft:
536             TypingCommand::deleteKeyPressed(document(), options, granularity);
537             break;
538         }
539         revealSelectionAfterEditingOperation();
540     }
541
542     // FIXME: We should to move this down into deleteKeyPressed.
543     // clear the "start new kill ring sequence" setting, because it was set to true
544     // when the selection was updated by deleting the range
545     if (shouldAddToKillRing)
546         setStartNewKillRingSequence(false);
547
548     return true;
549 }
550
551 void Editor::deleteSelectionWithSmartDelete(bool smartDelete, EditAction editingAction)
552 {
553     if (m_frame.selection().isNone())
554         return;
555
556     DeleteSelectionCommand::create(document(), smartDelete, true, false, false, true, editingAction)->apply();
557 }
558
559 void Editor::clearText()
560 {
561     ClearTextCommand::CreateAndApply(&m_frame);
562 }
563
564 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
565 {
566     Element* target = findEventTargetFromSelection();
567     if (!target)
568         return;
569     target->dispatchEvent(TextEvent::createForPlainTextPaste(document().windowProxy(), pastingText, smartReplace));
570 }
571
572 void Editor::pasteAsFragment(Ref<DocumentFragment>&& pastingFragment, bool smartReplace, bool matchStyle, MailBlockquoteHandling respectsMailBlockquote)
573 {
574     Element* target = findEventTargetFromSelection();
575     if (!target)
576         return;
577     target->dispatchEvent(TextEvent::createForFragmentPaste(document().windowProxy(), WTFMove(pastingFragment), smartReplace, matchStyle, respectsMailBlockquote));
578 }
579
580 void Editor::pasteAsPlainTextBypassingDHTML()
581 {
582     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
583 }
584
585 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard& pasteboard)
586 {
587     String text = readPlainTextFromPasteboard(pasteboard);
588     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertAction::Pasted))
589         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
590 }
591
592 String Editor::readPlainTextFromPasteboard(Pasteboard& pasteboard)
593 {
594     PasteboardPlainText text;
595     pasteboard.read(text);
596     return plainTextFromPasteboard(text);
597 }
598
599 #if !PLATFORM(MAC)
600
601 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
602 {
603     return text.text;
604 }
605
606 #endif
607
608 bool Editor::canSmartReplaceWithPasteboard(Pasteboard& pasteboard)
609 {
610     return client() && client()->smartInsertDeleteEnabled() && pasteboard.canSmartReplace();
611 }
612
613 bool Editor::shouldInsertFragment(DocumentFragment& fragment, Range* replacingDOMRange, EditorInsertAction givenAction)
614 {
615     if (!client())
616         return false;
617     
618     auto* child = fragment.firstChild();
619     if (is<CharacterData>(child) && fragment.lastChild() == child)
620         return client()->shouldInsertText(downcast<CharacterData>(*child).data(), replacingDOMRange, givenAction);
621
622     return client()->shouldInsertNode(&fragment, replacingDOMRange, givenAction);
623 }
624
625 void Editor::replaceSelectionWithFragment(DocumentFragment& fragment, bool selectReplacement, bool smartReplace, bool matchStyle, EditAction editingAction, MailBlockquoteHandling mailBlockquoteHandling)
626 {
627     VisibleSelection selection = m_frame.selection().selection();
628     if (selection.isNone() || !selection.isContentEditable())
629         return;
630
631     AccessibilityReplacedText replacedText;
632     if (AXObjectCache::accessibilityEnabled() && editingAction == EditActionPaste)
633         replacedText = AccessibilityReplacedText(selection);
634
635     OptionSet<ReplaceSelectionCommand::CommandOption> options { ReplaceSelectionCommand::PreventNesting, ReplaceSelectionCommand::SanitizeFragment };
636     if (selectReplacement)
637         options |= ReplaceSelectionCommand::SelectReplacement;
638     if (smartReplace)
639         options |= ReplaceSelectionCommand::SmartReplace;
640     if (matchStyle)
641         options |= ReplaceSelectionCommand::MatchStyle;
642     if (mailBlockquoteHandling == MailBlockquoteHandling::IgnoreBlockquote)
643         options |= ReplaceSelectionCommand::IgnoreMailBlockquote;
644
645     auto command = ReplaceSelectionCommand::create(document(), &fragment, options, editingAction);
646     command->apply();
647     revealSelectionAfterEditingOperation();
648
649     selection = m_frame.selection().selection();
650     if (selection.isInPasswordField())
651         return;
652
653     if (AXObjectCache::accessibilityEnabled() && editingAction == EditActionPaste) {
654         String text = AccessibilityObject::stringForVisiblePositionRange(command->visibleSelectionForInsertedText());
655         replacedText.postTextStateChangeNotification(document().existingAXObjectCache(), AXTextEditTypePaste, text, m_frame.selection().selection());
656         command->composition()->setRangeDeletedByUnapply(replacedText.replacedRange());
657     }
658
659     if (!isContinuousSpellCheckingEnabled())
660         return;
661
662     Node* nodeToCheck = selection.rootEditableElement();
663     if (!nodeToCheck)
664         return;
665
666     auto rangeToCheck = Range::create(document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
667     if (auto request = SpellCheckRequest::create(resolveTextCheckingTypeMask(*nodeToCheck, { TextCheckingType::Spelling, TextCheckingType::Grammar }), TextCheckingProcessBatch, rangeToCheck.copyRef(), rangeToCheck.copyRef(), rangeToCheck.copyRef()))
668         m_spellChecker->requestCheckingFor(request.releaseNonNull());
669 }
670
671 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace, EditAction editingAction)
672 {
673     RefPtr<Range> range = selectedRange();
674     if (!range)
675         return;
676
677     replaceSelectionWithFragment(createFragmentFromText(*range, text), selectReplacement, smartReplace, true, editingAction);
678 }
679
680 RefPtr<Range> Editor::selectedRange()
681 {
682     return m_frame.selection().toNormalizedRange();
683 }
684
685 bool Editor::shouldDeleteRange(Range* range) const
686 {
687     if (!range || range->collapsed())
688         return false;
689     
690     if (!canDeleteRange(range))
691         return false;
692
693     return client() && client()->shouldDeleteRange(range);
694 }
695
696 bool Editor::tryDHTMLCopy()
697 {   
698     if (m_frame.selection().selection().isInPasswordField())
699         return false;
700
701     return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::Copy);
702 }
703
704 bool Editor::tryDHTMLCut()
705 {
706     if (m_frame.selection().selection().isInPasswordField())
707         return false;
708     
709     return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::Cut);
710 }
711
712 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
713 {
714     if (m_frame.mainFrame().loader().shouldSuppressTextInputFromEditing() && action == EditorInsertAction::Typed)
715         return false;
716
717     return client() && client()->shouldInsertText(text, range, action);
718 }
719
720 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
721 {
722     if (AXObjectCache::accessibilityEnabled()) {
723         Node* node = endingSelection.start().deprecatedNode();
724         if (AXObjectCache* cache = document().existingAXObjectCache())
725             cache->postNotification(node, AXObjectCache::AXValueChanged, TargetObservableParent);
726     }
727
728     updateMarkersForWordsAffectedByEditing(true);
729
730     if (client())
731         client()->respondToChangedContents();
732 }
733
734 bool Editor::hasBidiSelection() const
735 {
736     if (m_frame.selection().isNone())
737         return false;
738
739     Node* startNode;
740     if (m_frame.selection().isRange()) {
741         startNode = m_frame.selection().selection().start().downstream().deprecatedNode();
742         Node* endNode = m_frame.selection().selection().end().upstream().deprecatedNode();
743         if (enclosingBlock(startNode) != enclosingBlock(endNode))
744             return false;
745     } else
746         startNode = m_frame.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
747
748     if (!startNode)
749         return false;
750
751     auto renderer = startNode->renderer();
752     while (renderer && !is<RenderBlockFlow>(*renderer))
753         renderer = renderer->parent();
754
755     if (!renderer)
756         return false;
757
758     if (!renderer->style().isLeftToRightDirection())
759         return true;
760
761     return downcast<RenderBlockFlow>(*renderer).containsNonZeroBidiLevel();
762 }
763
764 TriState Editor::selectionUnorderedListState() const
765 {
766     if (m_frame.selection().isCaret()) {
767         if (enclosingElementWithTag(m_frame.selection().selection().start(), ulTag))
768             return TrueTriState;
769     } else if (m_frame.selection().isRange()) {
770         auto* startNode = enclosingElementWithTag(m_frame.selection().selection().start(), ulTag);
771         auto* endNode = enclosingElementWithTag(m_frame.selection().selection().end(), ulTag);
772         if (startNode && endNode && startNode == endNode)
773             return TrueTriState;
774     }
775
776     return FalseTriState;
777 }
778
779 TriState Editor::selectionOrderedListState() const
780 {
781     if (m_frame.selection().isCaret()) {
782         if (enclosingElementWithTag(m_frame.selection().selection().start(), olTag))
783             return TrueTriState;
784     } else if (m_frame.selection().isRange()) {
785         auto* startNode = enclosingElementWithTag(m_frame.selection().selection().start(), olTag);
786         auto* endNode = enclosingElementWithTag(m_frame.selection().selection().end(), olTag);
787         if (startNode && endNode && startNode == endNode)
788             return TrueTriState;
789     }
790
791     return FalseTriState;
792 }
793
794 RefPtr<Node> Editor::insertOrderedList()
795 {
796     if (!canEditRichly())
797         return nullptr;
798         
799     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::OrderedList);
800     revealSelectionAfterEditingOperation();
801     return newList;
802 }
803
804 RefPtr<Node> Editor::insertUnorderedList()
805 {
806     if (!canEditRichly())
807         return nullptr;
808         
809     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::UnorderedList);
810     revealSelectionAfterEditingOperation();
811     return newList;
812 }
813
814 bool Editor::canIncreaseSelectionListLevel()
815 {
816     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(&document());
817 }
818
819 bool Editor::canDecreaseSelectionListLevel()
820 {
821     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(&document());
822 }
823
824 RefPtr<Node> Editor::increaseSelectionListLevel()
825 {
826     if (!canEditRichly() || m_frame.selection().isNone())
827         return nullptr;
828     
829     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(&document());
830     revealSelectionAfterEditingOperation();
831     return newList;
832 }
833
834 RefPtr<Node> Editor::increaseSelectionListLevelOrdered()
835 {
836     if (!canEditRichly() || m_frame.selection().isNone())
837         return nullptr;
838     
839     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(&document());
840     revealSelectionAfterEditingOperation();
841     return newList;
842 }
843
844 RefPtr<Node> Editor::increaseSelectionListLevelUnordered()
845 {
846     if (!canEditRichly() || m_frame.selection().isNone())
847         return nullptr;
848     
849     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(&document());
850     revealSelectionAfterEditingOperation();
851     return newList;
852 }
853
854 void Editor::decreaseSelectionListLevel()
855 {
856     if (!canEditRichly() || m_frame.selection().isNone())
857         return;
858     
859     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(&document());
860     revealSelectionAfterEditingOperation();
861 }
862
863 void Editor::removeFormattingAndStyle()
864 {
865     RemoveFormatCommand::create(document())->apply();
866 }
867
868 void Editor::clearLastEditCommand() 
869 {
870     m_lastEditCommand = nullptr;
871 }
872
873 Element* Editor::findEventTargetFrom(const VisibleSelection& selection) const
874 {
875     Element* target = selection.start().element();
876     if (!target)
877         target = document().bodyOrFrameset();
878     if (!target)
879         return nullptr;
880
881     return target;
882 }
883
884 Element* Editor::findEventTargetFromSelection() const
885 {
886     return findEventTargetFrom(m_frame.selection().selection());
887 }
888
889 void Editor::applyStyle(StyleProperties* style, EditAction editingAction)
890 {
891     if (style)
892         applyStyle(EditingStyle::create(style), editingAction, ColorFilterMode::UseOriginalColor);
893 }
894
895 void Editor::applyStyle(RefPtr<EditingStyle>&& style, EditAction editingAction, ColorFilterMode colorFilterMode)
896 {
897     if (!style)
898         return;
899
900     auto selectionType = m_frame.selection().selection().selectionType();
901     if (selectionType == VisibleSelection::NoSelection)
902         return;
903
904     String inputTypeName = inputTypeNameForEditingAction(editingAction);
905     String inputEventData = inputEventDataForEditingStyleAndAction(*style, editingAction);
906     RefPtr<Element> element = m_frame.selection().selection().rootEditableElement();
907     if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
908         return;
909
910     Ref<EditingStyle> styleToApply = colorFilterMode == ColorFilterMode::InvertColor ? style->inverseTransformColorIfNeeded(*element) : style.releaseNonNull();
911
912     switch (selectionType) {
913     case VisibleSelection::CaretSelection:
914         computeAndSetTypingStyle(styleToApply.get(), editingAction);
915         break;
916     case VisibleSelection::RangeSelection:
917         ApplyStyleCommand::create(document(), styleToApply.ptr(), editingAction)->apply();
918         break;
919     default:
920         break;
921     }
922
923     client()->didApplyStyle();
924     if (element)
925         dispatchInputEvent(*element, inputTypeName, inputEventData);
926 }
927     
928 bool Editor::shouldApplyStyle(StyleProperties* style, Range* range)
929 {   
930     return client()->shouldApplyStyle(style, range);
931 }
932     
933 void Editor::applyParagraphStyle(StyleProperties* style, EditAction editingAction)
934 {
935     if (!style)
936         return;
937
938     auto selectionType = m_frame.selection().selection().selectionType();
939     if (selectionType == VisibleSelection::NoSelection)
940         return;
941
942     String inputTypeName = inputTypeNameForEditingAction(editingAction);
943     String inputEventData = inputEventDataForEditingStyleAndAction(style, editingAction);
944     RefPtr<Element> element = m_frame.selection().selection().rootEditableElement();
945     if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
946         return;
947
948     ApplyStyleCommand::create(document(), EditingStyle::create(style).ptr(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
949     client()->didApplyStyle();
950     if (element)
951         dispatchInputEvent(*element, inputTypeName, inputEventData);
952 }
953
954 void Editor::applyStyleToSelection(StyleProperties* style, EditAction editingAction)
955 {
956     if (!style || style->isEmpty() || !canEditRichly())
957         return;
958
959     if (!client() || !client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
960         return;
961     applyStyle(style, editingAction);
962 }
963
964 void Editor::applyStyleToSelection(Ref<EditingStyle>&& style, EditAction editingAction, ColorFilterMode colorFilterMode)
965 {
966     if (style->isEmpty() || !canEditRichly())
967         return;
968
969     // FIXME: This is wrong for text decorations since m_mutableStyle is empty.
970     if (!client() || !client()->shouldApplyStyle(style->styleWithResolvedTextDecorations().ptr(), m_frame.selection().toNormalizedRange().get()))
971         return;
972
973     applyStyle(WTFMove(style), editingAction, colorFilterMode);
974 }
975
976 void Editor::applyParagraphStyleToSelection(StyleProperties* style, EditAction editingAction)
977 {
978     if (!style || style->isEmpty() || !canEditRichly())
979         return;
980     
981     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
982         applyParagraphStyle(style, editingAction);
983 }
984
985 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
986 {
987     if (auto editingStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(), propertyID == CSSPropertyBackgroundColor))
988         return editingStyle->hasStyle(propertyID, value);
989     return false;
990 }
991
992 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
993 {
994     return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame.selection().selection());
995 }
996
997 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
998 {
999     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(),
1000         propertyID == CSSPropertyBackgroundColor);
1001     if (!selectionStyle || !selectionStyle->style())
1002         return String();
1003
1004     if (propertyID == CSSPropertyFontSize)
1005         return String::number(selectionStyle->legacyFontSize(document()));
1006     return selectionStyle->style()->getPropertyValue(propertyID);
1007 }
1008
1009 void Editor::indent()
1010 {
1011     IndentOutdentCommand::create(document(), IndentOutdentCommand::Indent)->apply();
1012 }
1013
1014 void Editor::outdent()
1015 {
1016     IndentOutdentCommand::create(document(), IndentOutdentCommand::Outdent)->apply();
1017 }
1018
1019 static void notifyTextFromControls(Element* startRoot, Element* endRoot)
1020 {
1021     HTMLTextFormControlElement* startingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(startRoot));
1022     HTMLTextFormControlElement* endingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(endRoot));
1023     if (startingTextControl)
1024         startingTextControl->didEditInnerTextValue();
1025     if (endingTextControl && startingTextControl != endingTextControl)
1026         endingTextControl->didEditInnerTextValue();
1027 }
1028
1029 static bool dispatchBeforeInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomicString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { }, Event::IsCancelable cancelable = Event::IsCancelable::Yes)
1030 {
1031     bool continueWithDefaultBehavior = true;
1032     if (startRoot)
1033         continueWithDefaultBehavior &= dispatchBeforeInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
1034     if (endRoot && endRoot != startRoot)
1035         continueWithDefaultBehavior &= dispatchBeforeInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
1036     return continueWithDefaultBehavior;
1037 }
1038
1039 static void dispatchInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomicString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { })
1040 {
1041     if (startRoot)
1042         dispatchInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
1043     if (endRoot && endRoot != startRoot)
1044         dispatchInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
1045 }
1046
1047 bool Editor::willApplyEditing(CompositeEditCommand& command, Vector<RefPtr<StaticRange>>&& targetRanges) const
1048 {
1049     if (!command.shouldDispatchInputEvents())
1050         return true;
1051
1052     auto* composition = command.composition();
1053     if (!composition)
1054         return true;
1055
1056     return dispatchBeforeInputEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement(), command.inputEventTypeName(),
1057         command.inputEventData(), command.inputEventDataTransfer(), targetRanges, command.isBeforeInputEventCancelable() ? Event::IsCancelable::Yes : Event::IsCancelable::No);
1058 }
1059
1060 void Editor::appliedEditing(CompositeEditCommand& command)
1061 {
1062     LOG(Editing, "Editor %p appliedEditing", this);
1063
1064     document().updateLayout();
1065
1066     ASSERT(command.composition());
1067     auto& composition = *command.composition();
1068     VisibleSelection newSelection(command.endingSelection());
1069
1070     notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
1071
1072     if (command.isTopLevelCommand()) {
1073         // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
1074         OptionSet<FrameSelection::SetSelectionOption> options;
1075         if (command.isDictationCommand())
1076             options |= FrameSelection::DictationTriggered;
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 TextDirection::LTR:
1766         return LeftToRightWritingDirection;
1767     case TextDirection::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, { });
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     OptionSet<TextCheckingType> textCheckingOptions;
2341     if (isContinuousSpellCheckingEnabled())
2342         textCheckingOptions |= TextCheckingType::Spelling;
2343     if (!textCheckingOptions.contains(TextCheckingType::Spelling))
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         OptionSet<TextCheckingType> textCheckingOptions;
2358
2359         if (isContinuousSpellCheckingEnabled())
2360             textCheckingOptions |= TextCheckingType::Spelling;
2361
2362 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2363         if (doReplacement
2364             && (isAutomaticQuoteSubstitutionEnabled()
2365                 || isAutomaticLinkDetectionEnabled()
2366                 || isAutomaticDashSubstitutionEnabled()
2367                 || isAutomaticTextReplacementEnabled()
2368                 || (textCheckingOptions.contains(TextCheckingType::Spelling) && isAutomaticSpellingCorrectionEnabled())))
2369             textCheckingOptions |= TextCheckingType::Replacement;
2370 #endif
2371         if (!textCheckingOptions.contains(TextCheckingType::Spelling) && !textCheckingOptions.contains(TextCheckingType::Replacement))
2372             return;
2373
2374         if (isGrammarCheckingEnabled())
2375             textCheckingOptions |= TextCheckingType::Grammar;
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(OptionSet<TextCheckingType> 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.contains(TextCheckingType::Grammar);
2565     bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
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 TextCheckingType::None:
2607     case TextCheckingType::Spelling:
2608     case TextCheckingType::Grammar:
2609         return false;
2610     case TextCheckingType::Link:
2611     case TextCheckingType::Quote:
2612     case TextCheckingType::Dash:
2613     case TextCheckingType::Replacement:
2614     case TextCheckingType::Correction:
2615     case TextCheckingType::ShowCorrectionPanel:
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     auto textCheckingOptions = request.data().checkingTypes();
2646     TextCheckingParagraph paragraph(request.checkingRange(), request.automaticReplacementRange(), &request.paragraphRange());
2647
2648     // FIXME: Mark this const once MSVC bug is fixed: <https://developercommunity.visualstudio.com/content/problem/316713/msvc-cant-compile-webkits-optionsetcontainsany.html>.
2649     bool shouldPerformReplacement = textCheckingOptions.containsAny({ TextCheckingType::Quote, TextCheckingType::Dash, TextCheckingType::Replacement });
2650     const bool shouldMarkSpelling = textCheckingOptions.contains(TextCheckingType::Spelling);
2651     const bool shouldMarkGrammar = textCheckingOptions.contains(TextCheckingType::Grammar);
2652     const bool shouldMarkLink = textCheckingOptions.contains(TextCheckingType::Link);
2653     const bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
2654     const bool shouldCheckForCorrection = shouldShowCorrectionPanel || textCheckingOptions.contains(TextCheckingType::Correction);
2655 #if !USE(AUTOCORRECTION_PANEL)
2656     ASSERT(!shouldShowCorrectionPanel);
2657 #endif
2658
2659     // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2660     int selectionOffset = 0;
2661     bool useAmbiguousBoundaryOffset = false;
2662     bool selectionChanged = false;
2663     bool restoreSelectionAfterChange = false;
2664     bool adjustSelectionForParagraphBoundaries = false;
2665
2666     if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2667         if (m_frame.selection().selection().selectionType() == VisibleSelection::CaretSelection) {
2668             // Attempt to save the caret position so we can restore it later if needed
2669             Position caretPosition = m_frame.selection().selection().end();
2670             selectionOffset = paragraph.offsetTo(caretPosition).releaseReturnValue();
2671             restoreSelectionAfterChange = true;
2672             if (selectionOffset > 0 && (selectionOffset > paragraph.textLength() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2673                 adjustSelectionForParagraphBoundaries = true;
2674             if (selectionOffset > 0 && selectionOffset <= paragraph.textLength() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
2675                 useAmbiguousBoundaryOffset = true;
2676         }
2677     }
2678
2679     int offsetDueToReplacement = 0;
2680
2681     for (unsigned i = 0; i < results.size(); i++) {
2682         const int spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
2683         const TextCheckingType resultType = results[i].type;
2684         const int resultLocation = results[i].location + offsetDueToReplacement;
2685         const int resultLength = results[i].length;
2686         const int resultEndLocation = resultLocation + resultLength;
2687         const int automaticReplacementEndLocation = paragraph.automaticReplacementStart() + paragraph.automaticReplacementLength() + offsetDueToReplacement;
2688         const String& replacement = results[i].replacement;
2689         const bool resultEndsAtAmbiguousBoundary = useAmbiguousBoundaryOffset && selectionOffset - 1 <= resultEndLocation;
2690
2691         // Only mark misspelling if:
2692         // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2693         // 2. Result falls within spellingRange.
2694         // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2695         //    "wouldn'" as misspelled right after apostrophe is typed.
2696         if (shouldMarkSpelling && !shouldShowCorrectionPanel && resultType == TextCheckingType::Spelling
2697             && resultLocation >= paragraph.checkingStart() && resultEndLocation <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2698             ASSERT(resultLength > 0 && resultLocation >= 0);
2699             auto misspellingRange = paragraph.subrange(resultLocation, resultLength);
2700             if (!m_alternativeTextController->isSpellingMarkerAllowed(misspellingRange))
2701                 continue;
2702             misspellingRange->startContainer().document().markers().addMarker(misspellingRange.ptr(), DocumentMarker::Spelling, replacement);
2703         } else if (shouldMarkGrammar && resultType == TextCheckingType::Grammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
2704             ASSERT(resultLength > 0 && resultLocation >= 0);
2705             for (auto& detail : results[i].details) {
2706                 ASSERT(detail.length > 0 && detail.location >= 0);
2707                 if (paragraph.checkingRangeCovers(resultLocation + detail.location, detail.length)) {
2708                     auto badGrammarRange = paragraph.subrange(resultLocation + detail.location, detail.length);
2709                     badGrammarRange->startContainer().document().markers().addMarker(badGrammarRange.ptr(), DocumentMarker::Grammar, detail.userDescription);
2710                 }
2711             }
2712         } else if (resultEndLocation <= automaticReplacementEndLocation && resultEndLocation >= paragraph.automaticReplacementStart()
2713             && isAutomaticTextReplacementType(resultType)) {
2714             // 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.
2715             ASSERT(resultLength > 0 && resultLocation >= 0);
2716
2717             if (shouldShowCorrectionPanel && (resultEndLocation < automaticReplacementEndLocation
2718                 || (resultType != TextCheckingType::Replacement && resultType != TextCheckingType::Correction)))
2719                 continue;
2720
2721             // Apply replacement if:
2722             // 1. The replacement length is non-zero.
2723             // 2. The result doesn't end at an ambiguous boundary.
2724             //    (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2725             bool doReplacement = replacement.length() > 0 && !resultEndsAtAmbiguousBoundary;
2726             auto rangeToReplace = paragraph.subrange(resultLocation, resultLength);
2727
2728             // Adding links should be done only immediately after they are typed.
2729             if (resultType == TextCheckingType::Link && selectionOffset != resultEndLocation + 1)
2730                 continue;
2731
2732             if (!(shouldPerformReplacement || shouldCheckForCorrection || shouldMarkLink) || !doReplacement)
2733                 continue;
2734
2735             String replacedString = plainText(rangeToReplace.ptr());
2736             const bool existingMarkersPermitReplacement = m_alternativeTextController->processMarkersOnTextToBeReplacedByResult(results[i], rangeToReplace, replacedString);
2737             if (!existingMarkersPermitReplacement)
2738                 continue;
2739
2740             if (shouldShowCorrectionPanel) {
2741                 if (resultEndLocation == automaticReplacementEndLocation) {
2742                     // We only show the correction panel on the last word.
2743                     m_alternativeTextController->show(rangeToReplace, replacement);
2744                     break;
2745                 }
2746                 // If this function is called for showing correction panel, we ignore other correction or replacement.
2747                 continue;
2748             }
2749
2750             VisibleSelection selectionToReplace(rangeToReplace, DOWNSTREAM);
2751             if (selectionToReplace != m_frame.selection().selection()) {
2752                 if (!m_frame.selection().shouldChangeSelection(selectionToReplace))
2753                     continue;
2754             }
2755
2756             if (resultType == TextCheckingType::Link) {
2757                 m_frame.selection().setSelection(selectionToReplace);
2758                 selectionChanged = true;
2759                 restoreSelectionAfterChange = false;
2760                 if (canEditRichly())
2761                     CreateLinkCommand::create(document(), replacement)->apply();
2762             } else if (canEdit() && shouldInsertText(replacement, rangeToReplace.ptr(), EditorInsertAction::Typed)) {
2763                 correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, resultLocation, resultLength);
2764
2765                 if (AXObjectCache* cache = document().existingAXObjectCache()) {
2766                     if (Element* root = m_frame.selection().selection().rootEditableElement())
2767                         cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured);
2768                 }
2769
2770                 // Skip all other results for the replaced text.
2771                 while (i + 1 < results.size() && results[i + 1].location + offsetDueToReplacement <= resultLocation)
2772                     i++;
2773
2774                 selectionChanged = true;
2775                 offsetDueToReplacement += replacement.length() - resultLength;
2776                 if (resultLocation < selectionOffset)
2777                     selectionOffset += replacement.length() - resultLength;
2778
2779                 if (resultType == TextCheckingType::Correction) {
2780                     auto replacementRange = paragraph.subrange(resultLocation, replacement.length());
2781                     m_alternativeTextController->recordAutocorrectionResponse(AutocorrectionResponse::Accepted, replacedString, replacementRange.ptr());
2782
2783                     // Add a marker so that corrections can easily be undone and won't be re-corrected.
2784                     m_alternativeTextController->markCorrection(replacementRange, replacedString);
2785                 }
2786             }
2787         }
2788     }
2789
2790     if (selectionChanged) {
2791         TextCheckingParagraph extendedParagraph(WTFMove(paragraph));
2792         // Restore the caret position if we have made any replacements
2793         extendedParagraph.expandRangeToNextEnd();
2794         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2795             auto selectionRange = extendedParagraph.subrange(0, selectionOffset);
2796             m_frame.selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
2797             if (adjustSelectionForParagraphBoundaries)
2798                 m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2799         } else {
2800             // If this fails for any reason, the fallback is to go one position beyond the last replacement
2801             m_frame.selection().moveTo(m_frame.selection().selection().end());
2802             m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2803         }
2804     }
2805 }
2806
2807 void Editor::changeBackToReplacedString(const String& replacedString)
2808 {
2809 #if !PLATFORM(IOS)
2810     ASSERT(unifiedTextCheckerEnabled());
2811
2812     if (replacedString.isEmpty())
2813         return;
2814
2815     RefPtr<Range> selection = selectedRange();
2816     if (!shouldInsertText(replacedString, selection.get(), EditorInsertAction::Pasted))
2817         return;
2818     
2819     m_alternativeTextController->recordAutocorrectionResponse(AutocorrectionResponse::Reverted, replacedString, selection.get());
2820     TextCheckingParagraph paragraph(*selection);
2821     replaceSelectionWithText(replacedString, false, false, EditActionInsert);
2822     auto changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2823     changedRange->startContainer().document().markers().addMarker(changedRange.ptr(), DocumentMarker::Replacement, String());
2824     m_alternativeTextController->markReversed(changedRange);
2825 #else
2826     ASSERT_NOT_REACHED();
2827     UNUSED_PARAM(replacedString);
2828 #endif // !PLATFORM(IOS)
2829 }
2830
2831
2832 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2833 {
2834     if (unifiedTextCheckerEnabled()) {
2835         if (!isContinuousSpellCheckingEnabled())
2836             return;
2837
2838         // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
2839         OptionSet<TextCheckingType> textCheckingOptions { TextCheckingType::Spelling };
2840         if (markGrammar && isGrammarCheckingEnabled())
2841             textCheckingOptions |= TextCheckingType::Grammar;
2842         auto spellCheckingRange = spellingSelection.toNormalizedRange();
2843         markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellCheckingRange.copyRef(), spellCheckingRange.copyRef(), grammarSelection.toNormalizedRange());
2844         return;
2845     }
2846
2847     RefPtr<Range> firstMisspellingRange;
2848     markMisspellings(spellingSelection, firstMisspellingRange);
2849     if (markGrammar)
2850         markBadGrammar(grammarSelection);
2851 }
2852
2853 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2854 {
2855     m_alternativeTextController->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2856 }
2857
2858 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2859 {
2860     if (!document().markers().hasMarkers())
2861         return;
2862
2863     if (!m_alternativeTextController->shouldRemoveMarkersUponEditing() && (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Spelling)))
2864         return;
2865
2866     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2867     // several scenarios:
2868     // 1. Insert in the middle of a word.
2869     // 2. Appending non whitespace at the beginning of word.
2870     // 3. Appending non whitespace at the end of word.
2871     // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2872     // remove the markers on that word.
2873     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2874     // selection, and remove words between the selection boundaries.
2875     //
2876     VisiblePosition startOfSelection = m_frame.selection().selection().start();
2877     VisiblePosition endOfSelection = m_frame.selection().selection().end();
2878     if (startOfSelection.isNull())
2879         return;
2880     // First word is the word that ends after or on the start of selection.
2881     VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2882     VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2883     // Last word is the word that begins before or on the end of selection
2884     VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2885     VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2886
2887     if (startOfFirstWord.isNull()) {
2888         startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2889         endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2890     }
2891     
2892     if (endOfLastWord.isNull()) {
2893         startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2894         endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2895     }
2896
2897     // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2898     // we choose next word as the first word.
2899     if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2900         startOfFirstWord = nextWordPosition(startOfFirstWord);
2901         endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2902         if (startOfFirstWord == endOfSelection)
2903             return;
2904     }
2905
2906     // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2907     // we choose previous word as the last word.
2908     if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2909         startOfLastWord = previousWordPosition(startOfLastWord);
2910         endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2911         if (endOfLastWord == startOfSelection)
2912             return;
2913     }
2914
2915     if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2916         return;
2917
2918     // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2919     // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2920     // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2921     // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2922     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2923     // of marker that contains the word in question, and remove marker on that whole range.
2924     auto wordRange = Range::create(document(), startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2925
2926     Vector<RenderedDocumentMarker*> markers = document().markers().markersInRange(wordRange, DocumentMarker::DictationAlternatives);
2927     for (auto* marker : markers)
2928         m_alternativeTextController->removeDictationAlternativesForMarker(*marker);
2929
2930     OptionSet<DocumentMarker::MarkerType> markerTypesToRemove {
2931         DocumentMarker::CorrectionIndicator,
2932         DocumentMarker::DictationAlternatives,
2933         DocumentMarker::SpellCheckingExemption,
2934         DocumentMarker::Spelling,
2935 #if !PLATFORM(IOS)
2936         DocumentMarker::Grammar,
2937 #endif
2938     };
2939     document().markers().removeMarkers(wordRange.ptr(), markerTypesToRemove, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2940     document().markers().clearDescriptionOnMarkersIntersectingRange(wordRange, DocumentMarker::Replacement);
2941 }
2942
2943 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2944 {
2945     m_alternativeTextController->deletedAutocorrectionAtPosition(position, originalString);
2946 }
2947
2948 RefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
2949 {
2950     Document* document = m_frame.documentAtPoint(windowPoint);
2951     if (!document)
2952         return nullptr;
2953     
2954     Frame* frame = document->frame();
2955     ASSERT(frame);
2956     FrameView* frameView = frame->view();
2957     if (!frameView)
2958         return nullptr;
2959     IntPoint framePoint = frameView->windowToContents(windowPoint);
2960     VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2961
2962     return selection.toNormalizedRange();
2963 }
2964
2965 void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
2966 {
2967     if (m_ignoreSelectionChanges)
2968         return;
2969
2970 #if PLATFORM(IOS)
2971     SelectionRevealMode revealMode = SelectionRevealMode::RevealUpToMainFrame;
2972 #else
2973     SelectionRevealMode revealMode = SelectionRevealMode::Reveal;
2974 #endif
2975
2976     m_frame.selection().revealSelection(revealMode, alignment, revealExtentOption);
2977 }
2978
2979 void Editor::setIgnoreSelectionChanges(bool ignore, RevealSelection shouldRevealExistingSelection)
2980 {
2981     if (m_ignoreSelectionChanges == ignore)
2982         return;
2983
2984     m_ignoreSelectionChanges = ignore;
2985 #if PLATFORM(IOS)
2986     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830> 
2987     if (!ignore)
2988         respondToChangedSelection(m_frame.selection().selection(), { });
2989 #endif
2990     if (!ignore && shouldRevealExistingSelection == RevealSelection::Yes)
2991         revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
2992 }
2993
2994 RefPtr<Range> Editor::compositionRange() const
2995 {
2996     if (!m_compositionNode)
2997         return nullptr;
2998     unsigned length = m_compositionNode->length();
2999     unsigned start = std::min(m_compositionStart, length);
3000     unsigned end = std::min(std::max(start, m_compositionEnd), length);
3001     if (start >= end)
3002         return nullptr;
3003     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
3004 }
3005
3006 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
3007 {
3008     if (!m_compositionNode)
3009         return false;
3010     const VisibleSelection& selection = m_frame.selection().selection();
3011     Position start = selection.start();
3012     if (start.deprecatedNode() != m_compositionNode)
3013         return false;
3014     Position end = selection.end();
3015     if (end.deprecatedNode() != m_compositionNode)
3016         return false;
3017
3018     if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
3019         return false;
3020     if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
3021         return false;
3022
3023     selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
3024     selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
3025     return true;
3026 }
3027
3028 void Editor::transpose()
3029 {
3030     if (!canEdit())
3031         return;
3032
3033     VisibleSelection selection = m_frame.selection().selection();
3034     if (!selection.isCaret())
3035         return;
3036
3037     // Make a selection that goes back one character and forward two characters.
3038     VisiblePosition caret = selection.visibleStart();
3039     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
3040     VisiblePosition previous = next.previous();
3041     if (next == previous)
3042         return;
3043     previous = previous.previous();
3044     if (!inSameParagraph(next, previous))
3045         return;
3046     RefPtr<Range> range = makeRange(previous, next);
3047     if (!range)
3048         return;
3049     VisibleSelection newSelection(*range, DOWNSTREAM);
3050
3051     // Transpose the two characters.
3052     String text = plainText(range.get());
3053     if (text.length() != 2)
3054         return;
3055     String transposed = text.right(1) + text.left(1);
3056
3057     // Select the two characters.
3058     if (newSelection != m_frame.selection().selection()) {
3059         if (!m_frame.selection().shouldChangeSelection(newSelection))
3060             return;
3061         m_frame.selection().setSelection(newSelection);
3062     }
3063
3064     // Insert the transposed characters.
3065     if (!shouldInsertText(transposed, range.get(), EditorInsertAction::Typed))
3066         return;
3067     replaceSelectionWithText(transposed, false, false, EditActionInsert);
3068 }
3069
3070 void Editor::addRangeToKillRing(const Range& range, KillRingInsertionMode mode)
3071 {
3072     addTextToKillRing(plainText(&range), mode);
3073 }
3074
3075 void Editor::addTextToKillRing(const String& text, KillRingInsertionMode mode)
3076 {
3077     if (m_shouldStartNewKillRingSequence)
3078         killRing().startNewSequence();
3079
3080     m_shouldStartNewKillRingSequence = false;
3081
3082     // If the kill was from a backwards motion, prepend to the kill ring.
3083     // This will ensure that alternating forward and backward kills will
3084     // build up the original string in the kill ring without permuting it.
3085     switch (mode) {
3086     case KillRingInsertionMode::PrependText:
3087         killRing().prepend(text);
3088         break;
3089     case KillRingInsertionMode::AppendText:
3090         killRing().append(text);
3091         break;
3092     }
3093 }
3094
3095 void Editor::startAlternativeTextUITimer()
3096 {
3097     m_alternativeTextController->startAlternativeTextUITimer(AlternativeTextTypeCorrection);
3098 }
3099
3100 void Editor::handleAlternativeTextUIResult(const String& correction)
3101 {
3102     m_alternativeTextController->handleAlternativeTextUIResult(correction);
3103 }
3104
3105
3106 void Editor::dismissCorrectionPanelAsIgnored()
3107 {
3108     m_alternativeTextController->dismiss(ReasonForDismissingAlternativeTextIgnored);
3109 }
3110
3111 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, OptionSet<FrameSelection::SetSelectionOption> options)
3112 {
3113     Ref<Frame> protection(m_frame);
3114
3115     // If the new selection is orphaned, then don't update the selection.
3116     if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
3117         return;
3118
3119     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
3120     // because there is work that it must do in this situation.
3121     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
3122     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
3123     bool selectionDidNotChangeDOMPosition = newSelection == m_frame.selection().selection();
3124     if (selectionDidNotChangeDOMPosition || m_frame.selection().shouldChangeSelection(newSelection))
3125         m_frame.selection().setSelection(newSelection, options);
3126
3127     // Some editing operations change the selection visually without affecting its position within the DOM.
3128     // For example when you press return in the following (the caret is marked by ^):
3129     // <div contentEditable="true"><div>^Hello</div></div>
3130     // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
3131     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
3132     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
3133     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
3134 #if PLATFORM(IOS)
3135     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830>
3136     if (m_ignoreSelectionChanges)
3137         return;
3138 #endif
3139     if (selectionDidNotChangeDOMPosition && client())
3140         client()->respondToChangedSelection(&m_frame);
3141 }
3142
3143 String Editor::selectedText() const
3144 {
3145     return selectedText(TextIteratorDefaultBehavior);
3146 }
3147
3148 String Editor::selectedTextForDataTransfer() const
3149 {
3150     return selectedText(TextIteratorEmitsImageAltText);
3151 }
3152
3153 String Editor::selectedText(TextIteratorBehavior behavior) const
3154 {
3155     // We remove '\0' characters because they are not visibly rendered to the user.
3156     return plainText(m_frame.selection().toNormalizedRange().get(), behavior).replaceWithLiteral('\0', "");
3157 }
3158
3159 static inline void collapseCaretWidth(IntRect& rect)
3160 {
3161     // FIXME: Width adjustment doesn't work for rotated text.
3162     if (rect.width() == caretWidth)
3163         rect.setWidth(0);
3164     else if (rect.height() == caretWidth)
3165         rect.setHeight(0);
3166 }
3167
3168 IntRect Editor::firstRectForRange(Range* range) const
3169 {
3170     VisiblePosition startVisiblePosition(range->startPosition(), DOWNSTREAM);
3171
3172     if (range->collapsed()) {
3173         // FIXME: Getting caret rect and removing caret width is a very roundabout way to get collapsed range location.
3174         // In particular, width adjustment doesn't work for rotated text.
3175         IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect();
3176         collapseCaretWidth(startCaretRect);
3177         return startCaretRect;
3178     }
3179
3180     VisiblePosition endVisiblePosition(range->endPosition(), UPSTREAM);
3181
3182     if (inSameLine(startVisiblePosition, endVisiblePosition))
3183         return enclosingIntRect(RenderObject::absoluteBoundingBoxRectForRange(range));
3184
3185     LayoutUnit extraWidthToEndOfLine = 0;
3186     IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect(&extraWidthToEndOfLine);
3187     if (startCaretRect == IntRect())
3188         return IntRect();
3189
3190     // When start and end aren't on the same line, we want to go from start to the end of its line.
3191     bool textIsHorizontal = startCaretRect.width() == caretWidth;
3192     return textIsHorizontal ?
3193         IntRect(startCaretRect.x(),
3194             startCaretRect.y(),
3195             startCaretRect.width() + extraWidthToEndOfLine,
3196             startCaretRect.height()) :
3197         IntRect(startCaretRect.x(),
3198             startCaretRect.y(),
3199             startCaretRect.width(),
3200             startCaretRect.height() + extraWidthToEndOfLine);
3201 }
3202
3203 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
3204 {
3205 #if PLATFORM(IOS)
3206     if (m_frame.selectionChangeCallbacksDisabled())
3207         return true;
3208 #endif
3209     return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
3210 }
3211
3212 void Editor::computeAndSetTypingStyle(EditingStyle& style, EditAction editingAction)
3213 {
3214     if (style.isEmpty()) {
3215         m_frame.selection().clearTypingStyle();
3216         return;
3217     }
3218
3219     // Calculate the current typing style.
3220     RefPtr<EditingStyle> typingStyle;
3221     if (auto existingTypingStyle = m_frame.selection().typingStyle())
3222         typingStyle = existingTypingStyle->copy();
3223     else
3224         typingStyle = EditingStyle::create();
3225     typingStyle->overrideTypingStyleAt(style, m_frame.selection().selection().visibleStart().deepEquivalent());
3226
3227     // Handle block styles, substracting these from the typing style.
3228     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
3229     if (!blockStyle->isEmpty())
3230         ApplyStyleCommand::create(document(), blockStyle.get(), editingAction)->apply();
3231
3232     // Set the remaining style as the typing style.
3233     m_frame.selection().setTypingStyle(WTFMove(typingStyle));
3234 }
3235
3236 void Editor::computeAndSetTypingStyle(StyleProperties& properties, EditAction editingAction)
3237 {
3238     return computeAndSetTypingStyle(EditingStyle::create(&properties), editingAction);
3239 }
3240
3241 void Editor::textFieldDidBeginEditing(Element* e)
3242 {
3243     if (client())
3244         client()->textFieldDidBeginEditing(e);
3245 }
3246
3247 void Editor::textFieldDidEndEditing(Element* e)
3248 {
3249     dismissCorrectionPanelAsIgnored();
3250     if (client())
3251         client()->textFieldDidEndEditing(e);
3252 }
3253
3254 void Editor::textDidChangeInTextField(Element* e)
3255 {
3256     if (client())
3257         client()->textDidChangeInTextField(e);
3258 }
3259
3260 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
3261 {
3262     if (client())
3263         return client()->doTextFieldCommandFromEvent(e, ke);
3264
3265     return false;
3266 }
3267
3268 void Editor::textWillBeDeletedInTextField(Element* input)
3269 {
3270     if (client())
3271         client()->textWillBeDeletedInTextField(input);
3272 }
3273
3274 void Editor::textDidChangeInTextArea(Element* e)
3275 {
3276     if (client())
3277         client()->textDidChangeInTextArea(e);
3278 }
3279
3280 void Editor::applyEditingStyleToBodyElement() const
3281 {
3282     auto collection = document().getElementsByTagName(HTMLNames::bodyTag->localName());
3283     unsigned length = collection->length();
3284     for (unsigned i = 0; i < length; ++i)
3285         applyEditingStyleToElement(collection->item(i));
3286 }
3287
3288 void Editor::applyEditingStyleToElement(Element* element) const
3289 {
3290     ASSERT(!element || is<StyledElement>(*element));
3291     if (!is<StyledElement>(element))
3292         return;
3293
3294     // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
3295     auto& style = downcast<StyledElement>(*element).cssomStyle();
3296     style.setPropertyInternal(CSSPropertyWordWrap, "break-word", false);
3297     style.setPropertyInternal(CSSPropertyWebkitNbspMode, "space", false);
3298     style.setPropertyInternal(CSSPropertyLineBreak, "after-white-space", false);
3299 }
3300
3301 bool Editor::findString(const String& target, FindOptions options)
3302 {
3303     Ref<Frame> protection(m_frame);
3304
3305     VisibleSelection selection = m_frame.selection().selection();
3306
3307     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
3308
3309     if (!resultRange)
3310         return false;
3311
3312     m_frame.selection().setSelection(VisibleSelection(*resultRange, DOWNSTREAM));
3313
3314     if (!(options.contains(DoNotRevealSelection)))
3315         m_frame.selection().revealSelection();
3316
3317     return true;
3318 }
3319
3320 RefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
3321 {
3322     if (target.isEmpty())
3323         return nullptr;
3324
3325     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
3326     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
3327     RefPtr<Range> searchRange(rangeOfContents(document()));
3328
3329     bool forward = !options.contains(Backwards);
3330     bool startInReferenceRange = referenceRange && options.contains(StartInSelection);
3331     if (referenceRange) {
3332         if (forward)
3333             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
3334         else
3335             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
3336     }
3337
3338     RefPtr<ShadowRoot> shadowTreeRoot = referenceRange ? referenceRange->startContainer().containingShadowRoot() : nullptr;
3339     if (shadowTreeRoot) {
3340         if (forward)
3341             searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3342         else
3343             searchRange->setStart(*shadowTreeRoot, 0);
3344     }
3345
3346     RefPtr<Range> resultRange = findPlainText(*searchRange, target, options);
3347     // If we started in the reference range and the found range exactly matches the reference range, find again.
3348     // Build a selection with the found range to remove collapsed whitespace.
3349     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
3350     if (startInReferenceRange && areRangesEqual(VisibleSelection(*resultRange).toNormalizedRange().get(), referenceRange)) {
3351         searchRange = rangeOfContents(document());
3352         if (forward)
3353             searchRange->setStart(referenceRange->endPosition());
3354         else
3355             searchRange->setEnd(referenceRange->startPosition());
3356
3357         if (shadowTreeRoot) {
3358             if (forward)
3359                 searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3360             else
3361                 searchRange->setStart(*shadowTreeRoot, 0);
3362         }
3363
3364         resultRange = findPlainText(*searchRange, target, options);
3365     }
3366
3367     // If nothing was found in the shadow tree, search in main content following the shadow tree.
3368     if (resultRange->collapsed() && shadowTreeRoot) {
3369         searchRange = rangeOfContents(document());
3370         if (shadowTreeRoot->shadowHost()) {
3371             if (forward)
3372                 searchRange->setStartAfter(*shadowTreeRoot->shadowHost());
3373             else
3374                 searchRange->setEndBefore(*shadowTreeRoot->shadowHost());
3375         }
3376
3377         resultRange = findPlainText(*searchRange, target, options);
3378     }
3379
3380     // If we didn't find anything and we're wrapping, search again in the entire document (this will
3381     // redundantly re-search the area already searched in some cases).
3382     if (resultRange->collapsed() && options.contains(WrapAround)) {
3383         searchRange = rangeOfContents(document());
3384         resultRange = findPlainText(*searchRange, target, options);
3385         // We used to return false here if we ended up with the same range that we started with
3386         // (e.g., the reference range was already the only instance of this text). But we decided that
3387         // this should be a success case instead, so we'll just fall through in that case.
3388     }
3389
3390     return resultRange->collapsed() ? nullptr : resultRange;
3391 }
3392
3393 static bool isFrameInRange(Frame& frame, Range& range)
3394 {
3395     for (auto* ownerElement = frame.ownerElement(); ownerElement; ownerElement = ownerElement->document().ownerElement()) {
3396         if (&ownerElement->document() == &range.ownerDocument()) {
3397             auto result = range.intersectsNode(*ownerElement);
3398             return !result.hasException() && result.releaseReturnValue();
3399         }
3400     }
3401     return false;
3402 }
3403
3404 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches, Vector<RefPtr<Range>>* matches)
3405 {
3406     if (target.isEmpty())
3407         return 0;
3408
3409     RefPtr<Range> searchRange;
3410     if (range) {
3411         if (&range->ownerDocument() == &document())
3412             searchRange = range;
3413         else if (!isFrameInRange(m_frame, *range))
3414             return 0;
3415     }
3416     if (!searchRange)
3417         searchRange = rangeOfContents(document());
3418
3419     Node& originalEndContainer = searchRange->endContainer();
3420     int originalEndOffset = searchRange->endOffset();
3421
3422     unsigned matchCount = 0;
3423     do {
3424         RefPtr<Range> resultRange(findPlainText(*searchRange, target, options - Backwards));
3425         if (resultRange->collapsed()) {
3426             if (!resultRange->startContainer().isInShadowTree())
3427                 break;
3428
3429             searchRange->setStartAfter(*resultRange->startContainer().shadowHost());
3430             searchRange->setEnd(originalEndContainer, originalEndOffset);
3431             continue;
3432         }
3433
3434         ++matchCount;
3435         if (matches)
3436             matches->append(resultRange);
3437         
3438         if (markMatches)
3439             document().markers().addMarker(resultRange.get(), DocumentMarker::TextMatch);
3440
3441         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
3442         if (limit > 0 && matchCount >= limit)
3443             break;
3444
3445         // Set the new start for the search range to be the end of the previous
3446         // result range. There is no need to use a VisiblePosition here,
3447         // since findPlainText will use a TextIterator to go over the visible
3448         // text nodes. 
3449         searchRange->setStart(resultRange->endContainer(), resultRange->endOffset());
3450
3451         Node* shadowTreeRoot = searchRange->shadowRoot();
3452         if (searchRange->collapsed() && shadowTreeRoot)
3453             searchRange->setEnd(*shadowTreeRoot, shadowTreeRoot->countChildNodes());
3454     } while (true);
3455
3456     return matchCount;
3457 }
3458
3459 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
3460 {
3461     if (flag == m_areMarkedTextMatchesHighlighted)
3462         return;
3463
3464     m_areMarkedTextMatchesHighlighted = flag;
3465     document().markers().repaintMarkers(DocumentMarker::TextMatch);
3466 }
3467
3468 #if !PLATFORM(MAC)
3469 void Editor::selectionWillChange()
3470 {
3471 }
3472 #endif
3473
3474 void Editor::respondToChangedSelection(const VisibleSelection&, OptionSet<FrameSelection::SetSelectionOption> options)
3475 {
3476 #if PLATFORM(IOS)
3477     // FIXME: Should suppress selection change notifications during a composition change <https://webkit.org/b/38830> 
3478     if (m_ignoreSelectionChanges)
3479         return;
3480 #endif
3481
3482     if (client())
3483         client()->respondToChangedSelection(&m_frame);
3484
3485 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
3486     if (shouldDetectTelephoneNumbers())
3487         m_telephoneNumberDetectionUpdateTimer.startOneShot(0_s);
3488 #endif
3489
3490     setStartNewKillRingSequence(true);
3491
3492     if (m_editorUIUpdateTimer.isActive())
3493         return;
3494
3495     // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
3496     m_editorUIUpdateTimerShouldCheckSpellingAndGrammar = options.contains(FrameSelection::CloseTyping) && !options.contains(FrameSelection::SpellCorrectionTriggered);
3497     m_editorUIUpdateTimerWasTriggeredByDictation = options.contains(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())
3544             page->servicesOverlayController().selectedTelephoneNumberRangesChanged();
3545         return;
3546     }
3547
3548     scanRangeForTelephoneNumbers(*extendedRange, extendedRange->text(), markedRanges);
3549
3550     // Only consider ranges with a detected telephone number if they overlap with the actual selection range.
3551     for (auto& range : markedRanges) {
3552         if (rangesOverlap(range.get(), selectedRange.get()))
3553             m_detectedTelephoneNumberRanges.append(range);
3554     }
3555
3556     if (auto* page = m_frame.page())
3557         page->servicesOverlayController().selectedTelephoneNumberRangesChanged();
3558 }
3559
3560 void Editor::scanRangeForTelephoneNumbers(Range& range, const StringView& stringView, Vector<RefPtr<Range>>& markedRanges)
3561 {
3562     // Don't scan for phone numbers inside editable regions.
3563     Node& startNode = range.startContainer();
3564     if (startNode.hasEditableStyle())
3565         return;
3566
3567     // relativeStartPosition and relativeEndPosition are the endpoints of the phone number range,
3568     // relative to the scannerPosition
3569     unsigned length = stringView.length();
3570     unsigned scannerPosition = 0;
3571     int relativeStartPosition = 0;
3572     int relativeEndPosition = 0;
3573
3574     auto characters = stringView.upconvertedCharacters();
3575
3576     while (scannerPosition < length && TelephoneNumberDetector::find(&characters[scannerPosition], length - scannerPosition, &relativeStartPosition, &relativeEndPosition)) {
3577         // The convention in the Data Detectors framework is that the end position is the first character NOT in the phone number
3578         // (that is, the length of the range is relativeEndPosition - relativeStartPosition). So subtract 1 to get the same
3579         // convention as the old WebCore phone number parser (so that the rest of the code is still valid if we want to go back
3580         // to the old parser).
3581         --relativeEndPosition;
3582
3583         ASSERT(scannerPosition + relativeEndPosition < length);
3584
3585         unsigned subrangeOffset = scannerPosition + relativeStartPosition;
3586         unsigned subrangeLength = relativeEndPosition - relativeStartPosition + 1;
3587
3588         RefPtr<Range> subrange = TextIterator::subrange(range, subrangeOffset, subrangeLength);
3589
3590         markedRanges.append(subrange);
3591         range.ownerDocument().markers().addMarker(subrange.get(), DocumentMarker::TelephoneNumber);
3592
3593         scannerPosition += relativeEndPosition + 1;
3594     }
3595 }
3596
3597 #endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
3598
3599 void Editor::updateEditorUINowIfScheduled()
3600 {
3601     if (!m_editorUIUpdateTimer.isActive())
3602         return;
3603     m_editorUIUpdateTimer.stop();
3604     editorUIUpdateTimerFired();
3605 }
3606
3607 void Editor::editorUIUpdateTimerFired()
3608 {
3609     VisibleSelection oldSelection = m_oldSelectionForEditorUIUpdate;
3610
3611     m_alternativeTextController->stopPendingCorrection(oldSelection);
3612     
3613     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
3614     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
3615     if (isContinuousSpellCheckingEnabled) {
3616         VisibleSelection newAdjacentWords;
3617         VisibleSelection newSelectedSentence;
3618         bool caretBrowsing = m_frame.settings().caretBrowsingEnabled();
3619         if (m_frame.selection().selection().isContentEditable() || caretBrowsing) {
3620             VisiblePosition newStart(m_frame.selection().selection().visibleStart());
3621 #if !PLATFORM(IOS)
3622             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
3623 #else
3624             // If this bug gets fixed, this PLATFORM(IOS) code could be removed:
3625             // <rdar://problem/7259611> Word boundary code on iPhone gives different results than desktop
3626             EWordSide startWordSide = LeftWordIfOnBoundary;
3627             UChar32 c = newStart.characterBefore();
3628             // FIXME: VisiblePosition::characterAfter() and characterBefore() do not emit newlines the same
3629             // way as TextIterator, so we do an isStartOfParagraph check here.
3630             if (isSpaceOrNewline(c) || c == noBreakSpace || isStartOfParagraph(newStart)) {
3631                 startWordSide = RightWordIfOnBoundary;
3632             }
3633             newAdjacentWords = VisibleSelection(startOfWord(newStart, startWordSide), endOfWord(newStart, RightWordIfOnBoundary));
3634 #endif // !PLATFORM(IOS)
3635             if (isContinuousGrammarCheckingEnabled)
3636                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
3637         }
3638
3639         // When typing we check spelling elsewhere, so don't redo it here.
3640         // If this is a change in selection resulting from a delete operation,
3641         // oldSelection may no longer be in the document.
3642         if (m_editorUIUpdateTimerShouldCheckSpellingAndGrammar && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->isConnected()) {
3643             VisiblePosition oldStart(oldSelection.visibleStart());
3644             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
3645             if (oldAdjacentWords != newAdjacentWords) {
3646                 if (isContinuousGrammarCheckingEnabled) {
3647                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
3648                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
3649                 } else
3650                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
3651             }
3652         }
3653
3654         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Spelling)) {
3655             if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3656                 document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3657         }
3658         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Grammar)) {
3659             if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3660                 document().markers().removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3661         }
3662     }
3663
3664     // When continuous spell checking is off, existing markers disappear after the selection changes.
3665     if (!isContinuousSpellCheckingEnabled)
3666         document().markers().removeMarkers(DocumentMarker::Spelling);
3667     if (!isContinuousGrammarCheckingEnabled)
3668         document().markers().removeMarkers(DocumentMarker::Grammar);
3669
3670     if (!m_editorUIUpdateTimerWasTriggeredByDictation)
3671         m_alternativeTextController->respondToChangedSelection(oldSelection);
3672
3673     m_oldSelectionForEditorUIUpdate = m_frame.selection().selection();
3674
3675 #if ENABLE(ATTACHMENT_ELEMENT)
3676     notifyClientOfAttachmentUpdates();
3677 #endif
3678 }
3679
3680 static Node* findFirstMarkable(Node* node)
3681 {
3682     while (node) {
3683         if (!node->renderer())
3684             return nullptr;
3685         if (node->renderer()->isTextOrLineBreak())
3686             return node;
3687         if (is<Element>(*node) && downcast<Element>(*node).isTextField())
3688             node = downcast<HTMLTextFormControlElement>(*node).visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3689         else if (node->firstChild())
3690             node = node->firstChild();
3691         else
3692             node = node->nextSibling();
3693     }
3694
3695     return nullptr;
3696 }
3697
3698 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3699 {
3700     Node* node = findFirstMarkable(m_frame.selection().selection().start().deprecatedNode());
3701     if (!node)
3702         return false;
3703
3704     unsigned int startOffset = static_cast<unsigned int>(from);
3705     unsigned int endOffset = static_cast<unsigned int>(from + length);
3706     Vector<RenderedDocumentMarker*> markers = document().markers().markersFor(node);
3707     for (auto* marker : markers) {
3708         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3709             return true;
3710     }
3711
3712     return false;
3713 }       
3714
3715 OptionSet<TextCheckingType> Editor::resolveTextCheckingTypeMask(const Node& rootEditableElement, OptionSet<TextCheckingType> textCheckingOptions)
3716 {
3717 #if USE(AUTOMATIC_TEXT_REPLACEMENT) && !PLATFORM(IOS)
3718     bool onlyAllowsTextReplacement = false;
3719     if (auto* host = rootEditableElement.shadowHost())
3720         onlyAllowsTextReplacement = is<HTMLInputElement>(host) && downcast<HTMLInputElement>(*host).isSpellcheckDisabledExceptTextReplacement();
3721     if (onlyAllowsTextReplacement)
3722         textCheckingOptions = textCheckingOptions & TextCheckingType::Replacement;
3723 #else
3724     UNUSED_PARAM(rootEditableElement);
3725 #endif
3726
3727     bool shouldMarkSpelling = textCheckingOptions.contains(TextCheckingType::Spelling);
3728     bool shouldMarkGrammar = textCheckingOptions.contains(TextCheckingType::Grammar);
3729 #if !PLATFORM(IOS)
3730     bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
3731     bool shouldCheckForCorrection = shouldShowCorrectionPanel || textCheckingOptions.contains(TextCheckingType::Correction);
3732 #endif
3733
3734     OptionSet<TextCheckingType> checkingTypes;
3735     if (shouldMarkSpelling)
3736         checkingTypes |= TextCheckingType::Spelling;
3737     if (shouldMarkGrammar)
3738         checkingTypes |= TextCheckingType::Grammar;
3739 #if !PLATFORM(IOS)
3740     if (shouldCheckForCorrection)
3741         checkingTypes |= TextCheckingType::Correction;
3742     if (shouldShowCorrectionPanel)
3743         checkingTypes |= TextCheckingType::ShowCorrectionPanel;
3744
3745 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3746     bool shouldPerformReplacement = textCheckingOptions.contains(TextCheckingType::Replacement);
3747     if (shouldPerformReplacement) {
3748         if (!onlyAllowsTextReplacement) {
3749             if (isAutomaticLinkDetectionEnabled())
3750                 checkingTypes |= TextCheckingType::Link;
3751             if (isAutomaticQuoteSubstitutionEnabled())
3752                 checkingTypes |= TextCheckingType::Quote;
3753             if (isAutomaticDashSubstitutionEnabled())
3754                 checkingTypes |= TextCheckingType::Dash;
3755             if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3756                 checkingTypes |= TextCheckingType::Correction;
3757         }
3758         if (isAutomaticTextReplacementEnabled())
3759             checkingTypes |= TextCheckingType::Replacement;
3760     }
3761 #endif
3762 #endif // !PLATFORM(IOS)
3763
3764     return checkingTypes;
3765 }
3766
3767 static RefPtr<Range> candidateRangeForSelection(Frame& frame)
3768 {
3769     const VisibleSelection& selection = frame.selection().selection();
3770     return selection.isCaret() ? wordRangeFromPosition(selection.start()) : frame.selection().toNormalizedRange();
3771 }
3772
3773 static bool candidateWouldReplaceText(const VisibleSelection& selection)
3774 {
3775     // If the character behind the caret in the current selection is anything but a space or a newline then we should
3776     // replace the whole current word with the candidate.
3777     UChar32 characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection = 0;
3778     charactersAroundPosition(selection.visibleStart(), characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection);
3779     return !(characterBeforeSelection == '\0' || characterBeforeSelection == '\n' || characterBeforeSelection == ' ');
3780 }
3781
3782 String Editor::stringForCandidateRequest() const
3783 {
3784     const VisibleSelection& selection = m_frame.selection().selection();
3785     RefPtr<Range> rangeForCurrentlyTypedString = candidateRangeForSelection(m_frame);
3786     if (rangeForCurrentlyTypedString && candidateWouldReplaceText(selection))
3787         return plainText(rangeForCurrentlyTypedString.get());
3788
3789     return String();
3790 }
3791     
3792 RefPtr<Range> Editor::contextRangeForCandidateRequest() const
3793 {
3794     const VisibleSelection& selection = m_frame.selection().selection();
3795     return makeRange(startOfParagraph(selection.visibleStart()), endOfParagraph(selection.visibleEnd()));
3796 }
3797
3798 RefPtr<Range> Editor::rangeForTextCheckingResult(const TextCheckingResult& result) const
3799 {
3800     if (!result.length)
3801         return nullptr;
3802
3803     RefPtr<Range> contextRange = contextRangeForCandidateRequest();
3804     if (!contextRange)
3805         return nullptr;
3806
3807     return TextIterator::subrange(*contextRange, result.location, result.length);
3808 }
3809
3810 void Editor::scheduleEditorUIUpdate()
3811 {
3812     m_editorUIUpdateTimer.startOneShot(0_s);
3813 }
3814
3815 #if ENABLE(ATTACHMENT_ELEMENT)
3816
3817 void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<SharedBuffer>&& data)
3818 {
3819     if (auto* client = this->client())
3820         client->registerAttachmentIdentifier(identifier, contentType, preferredFileName, WTFMove(data));
3821 }
3822
3823 void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& filePath)
3824 {
3825     if (auto* client = this->client())
3826         client->registerAttachmentIdentifier(identifier, contentType, filePath);
3827 }
3828
3829 void Editor::cloneAttachmentData(const String& fromIdentifier, const String& toIdentifier)
3830 {
3831     if (auto* client = this->client())
3832         client->cloneAttachmentData(fromIdentifier, toIdentifier);
3833 }
3834
3835 void Editor::didInsertAttachmentElement(HTMLAttachmentElement& attachment)
3836 {
3837     auto identifier = attachment.uniqueIdentifier();
3838     if (identifier.isEmpty())
3839         return;
3840
3841     if (!m_removedAttachmentIdentifiers.take(identifier))
3842         m_insertedAttachmentIdentifiers.add(identifier);
3843     scheduleEditorUIUpdate();
3844 }
3845
3846 void Editor::didRemoveAttachmentElement(HTMLAttachmentElement& attachment)
3847 {
3848     auto identifier = attachment.uniqueIdentifier();
3849     if (identifier.isEmpty())
3850         return;
3851
3852     if (!m_insertedAttachmentIdentifiers.take(identifier))
3853         m_removedAttachmentIdentifiers.add(identifier);
3854     scheduleEditorUIUpdate();
3855 }
3856
3857 void Editor::notifyClientOfAttachmentUpdates()
3858 {
3859     auto removedAttachmentIdentifiers = WTFMove(m_removedAttachmentIdentifiers);
3860     auto insertedAttachmentIdentifiers = WTFMove(m_insertedAttachmentIdentifiers);
3861     if (!client())
3862         return;
3863
3864     for (auto& identifier : removedAttachmentIdentifiers)
3865         client()->didRemoveAttachmentWithIdentifier(identifier);
3866
3867     auto* document = m_frame.document();
3868     if (!document)
3869         return;
3870
3871     for (auto& identifier : insertedAttachmentIdentifiers) {
3872         if (auto attachment = document->attachmentForIdentifier(identifier))
3873             client()->didInsertAttachmentWithIdentifier(identifier, attachment->attributeWithoutSynchronization(HTMLNames::srcAttr));
3874         else
3875             ASSERT_NOT_REACHED();
3876     }
3877 }
3878
3879 void Editor::insertAttachment(const String& identifier, std::optional<uint64_t>&& fileSize, const String& fileName, const String& contentType)
3880 {
3881     auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document());
3882     attachment->setUniqueIdentifier(identifier);
3883     attachment->updateAttributes(WTFMove(fileSize), contentType, fileName);
3884
3885     auto fragmentToInsert = document().createDocumentFragment();
3886     fragmentToInsert->appendChild(attachment.get());
3887
3888     replaceSelectionWithFragment(fragmentToInsert.get(), false, false, true);
3889 }
3890
3891 #endif // ENABLE(ATTACHMENT_ELEMENT)
3892
3893 void Editor::handleAcceptedCandidate(TextCheckingResult acceptedCandidate)
3894 {
3895     const VisibleSelection& selection = m_frame.selection().selection();
3896
3897     m_isHandlingAcceptedCandidate = true;
3898
3899     if (auto range = rangeForTextCheckingResult(acceptedCandidate)) {
3900         if (shouldInsertText(acceptedCandidate.replacement, range.get(), EditorInsertAction::Typed))
3901             ReplaceRangeWithTextCommand::create(range.get(), acceptedCandidate.replacement)->apply();
3902     } else
3903         insertText(acceptedCandidate.replacement, nullptr);
3904
3905     RefPtr<Range> insertedCandidateRange = rangeExpandedByCharactersInDirectionAtWordBoundary(selection.visibleStart(), acceptedCandidate.replacement.length(), DirectionBackward);
3906     if (insertedCandidateRange)
3907         insertedCandidateRange->startContainer().document().markers().addMarker(insertedCandidateRange.get(), DocumentMarker::AcceptedCandidate, acceptedCandidate.replacement);
3908
3909     m_isHandlingAcceptedCandidate = false;
3910 }
3911
3912 bool Editor::unifiedTextCheckerEnabled() const
3913 {
3914     return WebCore::unifiedTextCheckerEnabled(&m_frame);
3915 }
3916
3917 Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker& marker)
3918 {
3919     return m_alternativeTextController->dictationAlternativesForMarker(marker);
3920 }
3921
3922 void Editor::applyDictationAlternativelternative(const String& alternativeString)
3923 {
3924     m_alternativeTextController->applyDictationAlternative(alternativeString);
3925 }
3926
3927 void Editor::toggleOverwriteModeEnabled()
3928 {
3929     m_overwriteModeEnabled = !m_overwriteModeEnabled;
3930     m_frame.selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
3931 }
3932
3933 Document& Editor::document() const
3934 {
3935     ASSERT(m_frame.document());
3936     return *m_frame.document();
3937 }
3938
3939 RefPtr<Range> Editor::adjustedSelectionRange()
3940 {
3941     // FIXME: Why do we need to adjust the selection to include the anchor tag it's in?
3942     // Whoever wrote this code originally forgot to leave us a comment explaining the rationale.
3943     RefPtr<Range> range = selectedRange();
3944     Node* commonAncestor = range->commonAncestorContainer();
3945     ASSERT(commonAncestor);
3946     auto* enclosingAnchor = enclosingElementWithTag(firstPositionInNode(commonAncestor), HTMLNames::aTag);
3947     if (enclosingAnchor && comparePositions(firstPositionInOrBeforeNode(range->startPosition().anchorNode()), range->startPosition()) >= 0)
3948         range->setStart(*enclosingAnchor, 0);
3949     return range;
3950 }
3951
3952 // FIXME: This figures out the current style by inserting a <span>!
3953 const RenderStyle* Editor::styleForSelectionStart(Frame* frame, Node*& nodeToRemove)
3954 {
3955     nodeToRemove = nullptr;
3956
3957     if (frame->selection().isNone())
3958         return nullptr;
3959
3960     Position position = adjustedSelectionStartForStyleComputation(frame->selection().selection());
3961     if (!position.isCandidate() || position.isNull())
3962         return nullptr;
3963
3964     RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
3965     if (!typingStyle || !typingStyle->style())
3966         return &position.deprecatedNode()->renderer()->style();
3967
3968     auto styleElement = HTMLSpanElement::create(*frame->document());
3969
3970     String styleText = typingStyle->style()->asText() + " display: inline";
3971     styleElement->setAttribute(HTMLNames::styleAttr, styleText);
3972
3973     styleElement->appendChild(frame->document()->createEditingTextNode(emptyString()));
3974
3975     auto positionNode = position.deprecatedNode();
3976     if (!positionNode || !positionNode->parentNode() || positionNode->parentNode()->appendChild(styleElement).hasException())
3977         return nullptr;
3978
3979     nodeToRemove = styleElement.ptr();
3980     
3981     frame->document()->updateStyleIfNeeded();
3982     return styleElement->renderer() ? &styleElement->renderer()->style() : nullptr;
3983 }
3984
3985 const Font* Editor::fontForSelection(bool& hasMultipleFonts) const
3986 {
3987     hasMultipleFonts = false;
3988
3989     if (!m_frame.selection().isRange()) {
3990         Node* nodeToRemove;
3991         auto* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
3992
3993         const Font* font = nullptr;
3994         if (style) {
3995             font = &style->fontCascade().primaryFont();
3996             if (nodeToRemove)
3997                 nodeToRemove->remove();
3998         }
3999
4000         return font;
4001     }
4002
4003     RefPtr<Range> range = m_frame.selection().toNormalizedRange();
4004     if (!range)
4005         return nullptr;
4006
4007     Node* startNode = adjustedSelectionStartForStyleComputation(m_frame.selection().selection()).deprecatedNode();
4008     if (!startNode)
4009         return nullptr;
4010
4011     const Font* font = nullptr;
4012     Node* pastEnd = range->pastLastNode();
4013     // In the loop below, node should eventually match pastEnd and not become null, but we've seen at least one
4014     // unreproducible case where this didn't happen, so check for null also.
4015     for (Node* node = startNode; node && node != pastEnd; node = NodeTraversal::next(*node)) {
4016         auto renderer = node->renderer();
4017         if (!renderer)
4018             continue;
4019         // FIXME: Are there any node types that have renderers, but that we should be skipping?
4020         const Font& primaryFont = renderer->style().fontCascade().primaryFont();
4021         if (!font)
4022             font = &primaryFont;
4023         else if (font != &primaryFont) {
4024             hasMultipleFonts = true;
4025             break;
4026         }
4027     }
4028
4029     return font;
4030 }
4031
4032 String Editor::clientReplacementURLForResource(Ref<SharedBuffer>&& resourceData, const String& mimeType)
4033 {
4034     if (auto* editorClient = client())
4035         return editorClient->replacementURLForResource(WTFMove(resourceData), mimeType);
4036
4037     return { };
4038 }
4039
4040 } // namespace WebCore