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