#include "config.h"
#include "Editor.h"
#include "AXObjectCache.h"
#include "AlternativeTextController.h"
#include "ApplyStyleCommand.h"
#include "CSSComputedStyleDeclaration.h"
#include "CSSPropertyNames.h"
#include "CSSValueList.h"
#include "CSSValuePool.h"
#include "CachedResourceLoader.h"
#include "ChangeListTypeCommand.h"
#include "ClipboardEvent.h"
#include "CompositionEvent.h"
#include "CompositionHighlight.h"
#include "CreateLinkCommand.h"
#include "CustomUndoStep.h"
#include "DataTransfer.h"
#include "DeleteSelectionCommand.h"
#include "DictationAlternative.h"
#include "DictationCommand.h"
#include "DocumentFragment.h"
#include "DocumentMarkerController.h"
#include "Editing.h"
#include "EditorClient.h"
#include "ElementIterator.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "File.h"
#include "FocusController.h"
#include "FontAttributes.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLAttachmentElement.h"
#include "HTMLBRElement.h"
#include "HTMLBodyElement.h"
#include "HTMLFormControlElement.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLImageElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLOListElement.h"
#include "HTMLQuoteElement.h"
#include "HTMLSpanElement.h"
#include "HTMLUListElement.h"
#include "HitTestResult.h"
#include "IndentOutdentCommand.h"
#include "InputEvent.h"
#include "InsertEditableImageCommand.h"
#include "InsertListCommand.h"
#include "InsertTextCommand.h"
#include "KeyboardEvent.h"
#include "Logging.h"
#include "ModifySelectionListLevel.h"
#include "NodeList.h"
#include "NodeTraversal.h"
#include "Page.h"
#include "Pasteboard.h"
#include "Range.h"
#include "RemoveFormatCommand.h"
#include "RenderBlock.h"
#include "RenderLayer.h"
#include "RenderTextControl.h"
#include "RenderedDocumentMarker.h"
#include "RenderedPosition.h"
#include "ReplaceRangeWithTextCommand.h"
#include "ReplaceSelectionCommand.h"
#include "RuntimeEnabledFeatures.h"
#include "SerializedAttachmentData.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "SharedBuffer.h"
#include "SimplifyMarkupCommand.h"
#include "SpellChecker.h"
#include "SpellingCorrectionCommand.h"
#include "StaticPasteboard.h"
#include "StyleProperties.h"
#include "TelephoneNumberDetector.h"
#include "Text.h"
#include "TextCheckerClient.h"
#include "TextCheckingHelper.h"
#include "TextEvent.h"
#include "TextIterator.h"
#include "TextPlaceholderElement.h"
#include "TypingCommand.h"
#include "UserTypingGestureIndicator.h"
#include "VisibleUnits.h"
#include "markup.h"
#include <pal/FileSizeFormatter.h>
#include <pal/system/Sound.h>
#include <pal/text/KillRing.h>
#include <wtf/SetForScope.h>
#include <wtf/unicode/CharacterNames.h>
#if PLATFORM(MAC)
#include "ServicesOverlayController.h"
#endif
#if ENABLE(ATTACHMENT_ELEMENT)
#include "PromisedAttachmentInfo.h"
#endif
namespace WebCore {
static bool dispatchBeforeInputEvent(Element& element, const AtomString& inputType, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { }, Event::IsCancelable cancelable = Event::IsCancelable::Yes)
{
if (!element.document().settings().inputEventsEnabled())
return true;
auto event = InputEvent::create(eventNames().beforeinputEvent, inputType, cancelable, element.document().windowProxy(), data, WTFMove(dataTransfer), targetRanges, 0);
element.dispatchEvent(event);
return !event->defaultPrevented();
}
static void dispatchInputEvent(Element& element, const AtomString& inputType, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { })
{
if (element.document().settings().inputEventsEnabled()) {
element.dispatchScopedEvent(InputEvent::create(eventNames().inputEvent, inputType, Event::IsCancelable::No,
element.document().windowProxy(), data, WTFMove(dataTransfer), targetRanges, 0));
} else
element.dispatchInputEvent();
}
static String inputEventDataForEditingStyleAndAction(const StyleProperties* style, EditAction action)
{
if (!style)
return { };
switch (action) {
case EditAction::SetColor:
return style->getPropertyValue(CSSPropertyColor);
case EditAction::SetInlineWritingDirection:
case EditAction::SetBlockWritingDirection:
return style->getPropertyValue(CSSPropertyDirection);
default:
return { };
}
}
static String inputEventDataForEditingStyleAndAction(EditingStyle& style, EditAction action)
{
return inputEventDataForEditingStyleAndAction(style.style(), action);
}
class ClearTextCommand : public DeleteSelectionCommand {
public:
ClearTextCommand(Document& document);
static void CreateAndApply(Document&);
private:
EditAction editingAction() const override;
};
ClearTextCommand::ClearTextCommand(Document& document)
: DeleteSelectionCommand(document, false, true, false, false, true)
{
}
EditAction ClearTextCommand::editingAction() const
{
return EditAction::Delete;
}
void ClearTextCommand::CreateAndApply(Document& document)
{
if (document.selection().isNone())
return;
document.editor().clear();
const VisibleSelection oldSelection = document.selection().selection();
document.selection().selectAll();
auto clearCommand = adoptRef(*new ClearTextCommand(document));
clearCommand->setStartingSelection(oldSelection);
clearCommand->apply();
}
using namespace HTMLNames;
using namespace WTF::Unicode;
TemporarySelectionChange::TemporarySelectionChange(Document& document, Optional<VisibleSelection> temporarySelection, OptionSet<TemporarySelectionOption> options)
: m_document(RefPtr(&document))
, m_options(options)
, m_wasIgnoringSelectionChanges(document.editor().ignoreSelectionChanges())
#if PLATFORM(IOS_FAMILY)
, m_appearanceUpdatesWereEnabled(document.selection().isUpdateAppearanceEnabled())
#endif
{
#if PLATFORM(IOS_FAMILY)
if (options & TemporarySelectionOption::EnableAppearanceUpdates)
document.selection().setUpdateAppearanceEnabled(true);
#endif
if (options & TemporarySelectionOption::IgnoreSelectionChanges)
document.editor().setIgnoreSelectionChanges(true);
if (temporarySelection) {
m_selectionToRestore = document.selection().selection();
setSelection(temporarySelection.value());
}
}
TemporarySelectionChange::~TemporarySelectionChange()
{
if (m_selectionToRestore)
setSelection(m_selectionToRestore.value());
if (m_options & TemporarySelectionOption::IgnoreSelectionChanges) {
auto revealSelection = m_options & TemporarySelectionOption::RevealSelection ? Editor::RevealSelection::Yes : Editor::RevealSelection::No;
m_document->editor().setIgnoreSelectionChanges(m_wasIgnoringSelectionChanges, revealSelection);
}
#if PLATFORM(IOS_FAMILY)
if (m_options & TemporarySelectionOption::EnableAppearanceUpdates)
m_document->selection().setUpdateAppearanceEnabled(m_appearanceUpdatesWereEnabled);
#endif
}
void TemporarySelectionChange::setSelection(const VisibleSelection& selection)
{
auto options = FrameSelection::defaultSetSelectionOptions();
if (m_options & TemporarySelectionOption::DoNotSetFocus)
options.add(FrameSelection::DoNotSetFocus);
m_document->selection().setSelection(selection, options);
}
VisibleSelection Editor::selectionForCommand(Event* event)
{
auto selection = m_document.selection().selection();
if (!event)
return selection;
if (is<Element>(event->target()) && downcast<Element>(*event->target()).isTextField()) {
auto& target = downcast<HTMLTextFormControlElement>(*event->target());
auto start = selection.start();
if (start.isNull() || &target != enclosingTextFormControl(start)) {
if (auto range = target.selection())
return { *range, DOWNSTREAM, selection.isDirectional() };
}
}
return selection;
}
EditingBehavior Editor::behavior() const
{
return EditingBehavior(m_document.settings().editingBehaviorType());
}
EditorClient* Editor::client() const
{
if (Page* page = m_document.page())
return &page->editorClient();
return nullptr;
}
TextCheckerClient* Editor::textChecker() const
{
if (EditorClient* owner = client())
return owner->textChecker();
return 0;
}
void Editor::handleKeyboardEvent(KeyboardEvent& event)
{
if (auto* client = this->client())
client->handleKeyboardEvent(event);
}
void Editor::handleInputMethodKeydown(KeyboardEvent& event)
{
if (auto* client = this->client())
client->handleInputMethodKeydown(event);
}
void Editor::didDispatchInputMethodKeydown(KeyboardEvent& event)
{
if (auto* client = this->client())
client->didDispatchInputMethodKeydown(event);
}
bool Editor::handleTextEvent(TextEvent& event)
{
LOG(Editing, "Editor %p handleTextEvent (data %s)", this, event.data().utf8().data());
if (event.isDrop())
return false;
if (event.isPaste()) {
if (event.pastingFragment()) {
#if PLATFORM(IOS_FAMILY)
if (client()->performsTwoStepPaste(event.pastingFragment()))
return true;
#endif
replaceSelectionWithFragment(*event.pastingFragment(), SelectReplacement::No, event.shouldSmartReplace() ? SmartReplace::Yes : SmartReplace::No, event.shouldMatchStyle() ? MatchStyle::Yes : MatchStyle::No, EditAction::Paste, event.mailBlockquoteHandling());
} else
replaceSelectionWithText(event.data(), SelectReplacement::No, event.shouldSmartReplace() ? SmartReplace::Yes : SmartReplace::No, EditAction::Paste);
return true;
}
String data = event.data();
if (data == "\n") {
if (event.isLineBreak())
return insertLineBreak();
return insertParagraphSeparator();
}
return insertTextWithoutSendingTextEvent(data, false, &event);
}
bool Editor::canEdit() const
{
return m_document.selection().selection().rootEditableElement();
}
bool Editor::canEditRichly() const
{
return m_document.selection().selection().isContentRichlyEditable();
}
enum class ClipboardEventKind {
Copy,
Cut,
Paste,
PasteAsPlainText,
PasteAsQuotation,
BeforeCopy,
BeforeCut,
BeforePaste,
};
static AtomString eventNameForClipboardEvent(ClipboardEventKind kind)
{
switch (kind) {
case ClipboardEventKind::Copy:
return eventNames().copyEvent;
case ClipboardEventKind::Cut:
return eventNames().cutEvent;
case ClipboardEventKind::Paste:
case ClipboardEventKind::PasteAsPlainText:
case ClipboardEventKind::PasteAsQuotation:
return eventNames().pasteEvent;
case ClipboardEventKind::BeforeCopy:
return eventNames().beforecopyEvent;
case ClipboardEventKind::BeforeCut:
return eventNames().beforecutEvent;
case ClipboardEventKind::BeforePaste:
return eventNames().beforepasteEvent;
}
ASSERT_NOT_REACHED();
return { };
}
static Ref<DataTransfer> createDataTransferForClipboardEvent(Document& document, ClipboardEventKind kind)
{
switch (kind) {
case ClipboardEventKind::Copy:
case ClipboardEventKind::Cut:
return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::ReadWrite, makeUnique<StaticPasteboard>());
case ClipboardEventKind::PasteAsPlainText:
if (RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled()) {
auto plainTextType = "text/plain"_s;
auto plainText = Pasteboard::createForCopyAndPaste()->readString(plainTextType);
auto pasteboard = makeUnique<StaticPasteboard>();
pasteboard->writeString(plainTextType, plainText);
return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Readonly, WTFMove(pasteboard));
}
FALLTHROUGH;
case ClipboardEventKind::Paste:
case ClipboardEventKind::PasteAsQuotation:
return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Readonly, Pasteboard::createForCopyAndPaste());
case ClipboardEventKind::BeforeCopy:
case ClipboardEventKind::BeforeCut:
case ClipboardEventKind::BeforePaste:
return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Invalid, makeUnique<StaticPasteboard>());
}
ASSERT_NOT_REACHED();
return DataTransfer::createForCopyAndPaste(document, DataTransfer::StoreMode::Invalid, makeUnique<StaticPasteboard>());
}
static bool dispatchClipboardEvent(RefPtr<Element>&& target, ClipboardEventKind kind)
{
if (!target)
return true;
auto dataTransfer = createDataTransferForClipboardEvent(target->document(), kind);
auto event = ClipboardEvent::create(eventNameForClipboardEvent(kind), dataTransfer.copyRef());
target->dispatchEvent(event);
bool noDefaultProcessing = event->defaultPrevented();
if (noDefaultProcessing && (kind == ClipboardEventKind::Copy || kind == ClipboardEventKind::Cut) && dataTransfer->pasteboard().hasData())
dataTransfer->commitToPasteboard(*Pasteboard::createForCopyAndPaste());
dataTransfer->makeInvalidForSecurity();
return !noDefaultProcessing;
}
bool Editor::canDHTMLCut()
{
if (m_document.selection().selection().isInPasswordField())
return false;
return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforeCut);
}
bool Editor::canDHTMLCopy()
{
if (m_document.selection().selection().isInPasswordField())
return false;
return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforeCopy);
}
bool Editor::canDHTMLPaste()
{
return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::BeforePaste);
}
bool Editor::canCut() const
{
return canCopy() && canDelete();
}
static HTMLImageElement* imageElementFromImageDocument(Document& document)
{
if (!document.isImageDocument())
return nullptr;
HTMLElement* body = document.bodyOrFrameset();
if (!body)
return nullptr;
Node* node = body->firstChild();
if (!is<HTMLImageElement>(node))
return nullptr;
return downcast<HTMLImageElement>(node);
}
bool Editor::canCopy() const
{
if (imageElementFromImageDocument(document()))
return true;
const VisibleSelection& selection = m_document.selection().selection();
return selection.isRange() && !selection.isInPasswordField();
}
bool Editor::canPaste() const
{
if (m_document.frame()->mainFrame().loader().shouldSuppressTextInputFromEditing())
return false;
return canEdit();
}
bool Editor::canDelete() const
{
const VisibleSelection& selection = m_document.selection().selection();
return selection.isRange() && selection.rootEditableElement();
}
bool Editor::canDeleteRange(const SimpleRange& range) const
{
if (!range.start.container->hasEditableStyle() || !range.end.container->hasEditableStyle())
return false;
if (range.collapsed()) {
auto previous = VisiblePosition { createLegacyEditingPosition(range.start), DOWNSTREAM }.previous();
if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != range.start.container->rootEditableElement())
return false;
}
return true;
}
bool Editor::shouldSmartDelete()
{
if (behavior().shouldAlwaysSmartDelete())
return true;
return m_document.selection().granularity() == TextGranularity::WordGranularity;
}
bool Editor::smartInsertDeleteEnabled()
{
return client() && client()->smartInsertDeleteEnabled();
}
bool Editor::canSmartCopyOrDelete()
{
return client() && client()->smartInsertDeleteEnabled() && shouldSmartDelete();
}
bool Editor::isSelectTrailingWhitespaceEnabled() const
{
return client() && client()->isSelectTrailingWhitespaceEnabled();
}
bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool shouldAddToKillRing, bool isTypingAction)
{
if (!canEdit())
return false;
if (m_document.selection().isRange()) {
if (isTypingAction) {
TypingCommand::deleteKeyPressed(document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
revealSelectionAfterEditingOperation();
} else {
if (shouldAddToKillRing)
addRangeToKillRing(*selectedRange(), KillRingInsertionMode::AppendText);
deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
}
} else {
TypingCommand::Options options = 0;
if (canSmartCopyOrDelete())
options |= TypingCommand::SmartDelete;
if (shouldAddToKillRing)
options |= TypingCommand::AddsToKillRing;
switch (direction) {
case SelectionDirection::Forward:
case SelectionDirection::Right:
TypingCommand::forwardDeleteKeyPressed(document(), options, granularity);
break;
case SelectionDirection::Backward:
case SelectionDirection::Left:
TypingCommand::deleteKeyPressed(document(), options, granularity);
break;
}
revealSelectionAfterEditingOperation();
}
if (shouldAddToKillRing)
setStartNewKillRingSequence(false);
return true;
}
void Editor::deleteSelectionWithSmartDelete(bool smartDelete, EditAction editingAction)
{
if (m_document.selection().isNone())
return;
DeleteSelectionCommand::create(document(), smartDelete, true, false, false, true, editingAction)->apply();
}
void Editor::clearText()
{
ClearTextCommand::CreateAndApply(m_document);
}
void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
{
Element* target = findEventTargetFromSelection();
if (!target)
return;
target->dispatchEvent(TextEvent::createForPlainTextPaste(document().windowProxy(), pastingText, smartReplace));
}
void Editor::pasteAsFragment(Ref<DocumentFragment>&& pastingFragment, bool smartReplace, bool matchStyle, MailBlockquoteHandling respectsMailBlockquote)
{
Element* target = findEventTargetFromSelection();
if (!target)
return;
target->dispatchEvent(TextEvent::createForFragmentPaste(document().windowProxy(), WTFMove(pastingFragment), smartReplace, matchStyle, respectsMailBlockquote));
}
void Editor::pasteAsPlainTextBypassingDHTML()
{
pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
}
void Editor::pasteAsPlainTextWithPasteboard(Pasteboard& pasteboard)
{
String text = readPlainTextFromPasteboard(pasteboard);
if (client() && client()->shouldInsertText(text, selectedRange(), EditorInsertAction::Pasted))
pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
}
String Editor::readPlainTextFromPasteboard(Pasteboard& pasteboard)
{
PasteboardPlainText text;
pasteboard.read(text);
return plainTextFromPasteboard(text);
}
#if !PLATFORM(MAC)
String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
{
return text.text;
}
#endif
bool Editor::canSmartReplaceWithPasteboard(Pasteboard& pasteboard)
{
return client() && client()->smartInsertDeleteEnabled() && pasteboard.canSmartReplace();
}
bool Editor::shouldInsertFragment(DocumentFragment& fragment, const Optional<SimpleRange>& replacingDOMRange, EditorInsertAction givenAction)
{
if (!client())
return false;
auto* child = fragment.firstChild();
if (is<CharacterData>(child) && fragment.lastChild() == child)
return client()->shouldInsertText(downcast<CharacterData>(*child).data(), replacingDOMRange, givenAction);
return client()->shouldInsertNode(fragment, replacingDOMRange, givenAction);
}
void Editor::replaceSelectionWithFragment(DocumentFragment& fragment, SelectReplacement selectReplacement, SmartReplace smartReplace, MatchStyle matchStyle, EditAction editingAction, MailBlockquoteHandling mailBlockquoteHandling)
{
VisibleSelection selection = m_document.selection().selection();
if (selection.isNone() || !selection.isContentEditable())
return;
AccessibilityReplacedText replacedText;
if (AXObjectCache::accessibilityEnabled() && (editingAction == EditAction::Paste || editingAction == EditAction::Insert))
replacedText = AccessibilityReplacedText(selection);
OptionSet<ReplaceSelectionCommand::CommandOption> options { ReplaceSelectionCommand::PreventNesting, ReplaceSelectionCommand::SanitizeFragment };
if (selectReplacement == SelectReplacement::Yes)
options.add(ReplaceSelectionCommand::SelectReplacement);
if (smartReplace == SmartReplace::Yes)
options.add(ReplaceSelectionCommand::SmartReplace);
if (matchStyle == MatchStyle::Yes)
options.add(ReplaceSelectionCommand::MatchStyle);
if (mailBlockquoteHandling == MailBlockquoteHandling::IgnoreBlockquote)
options.add(ReplaceSelectionCommand::IgnoreMailBlockquote);
auto command = ReplaceSelectionCommand::create(document(), &fragment, options, editingAction);
command->apply();
m_imageElementsToLoadBeforeRevealingSelection.clear();
if (auto insertionRange = command->insertedContentRange())
m_imageElementsToLoadBeforeRevealingSelection = visibleImageElementsInRangeWithNonLoadedImages(*insertionRange);
if (m_imageElementsToLoadBeforeRevealingSelection.isEmpty())
revealSelectionAfterEditingOperation();
selection = m_document.selection().selection();
if (selection.isInPasswordField())
return;
if (AXObjectCache::accessibilityEnabled() && editingAction == EditAction::Paste) {
String text = AccessibilityObject::stringForVisiblePositionRange(command->visibleSelectionForInsertedText());
replacedText.postTextStateChangeNotification(document().existingAXObjectCache(), AXTextEditTypePaste, text, m_document.selection().selection());
command->composition()->setRangeDeletedByUnapply(replacedText.replacedRange());
}
if (AXObjectCache::accessibilityEnabled() && editingAction == EditAction::Insert) {
String text = command->documentFragmentPlainText();
replacedText.postTextStateChangeNotification(document().existingAXObjectCache(), AXTextEditTypeInsert, text, m_document.selection().selection());
command->composition()->setRangeDeletedByUnapply(replacedText.replacedRange());
}
if (!isContinuousSpellCheckingEnabled())
return;
Node* nodeToCheck = selection.rootEditableElement();
if (!nodeToCheck)
return;
auto rangeToCheck = makeRangeSelectingNodeContents(*nodeToCheck);
if (auto request = SpellCheckRequest::create(resolveTextCheckingTypeMask(*nodeToCheck, { TextCheckingType::Spelling, TextCheckingType::Grammar }), TextCheckingProcessBatch, rangeToCheck, rangeToCheck, rangeToCheck))
m_spellChecker->requestCheckingFor(request.releaseNonNull());
}
void Editor::replaceSelectionWithText(const String& text, SelectReplacement selectReplacement, SmartReplace smartReplace, EditAction editingAction)
{
auto range = selectedRange();
if (!range)
return;
replaceSelectionWithFragment(createFragmentFromText(*range, text), selectReplacement, smartReplace, MatchStyle::Yes, editingAction);
}
Optional<SimpleRange> Editor::selectedRange()
{
return m_document.selection().selection().toNormalizedRange();
}
bool Editor::shouldDeleteRange(const Optional<SimpleRange>& range) const
{
return range && !range->collapsed() && canDeleteRange(*range) && client() && client()->shouldDeleteRange(*range);
}
bool Editor::tryDHTMLCopy()
{
if (m_document.selection().selection().isInPasswordField())
return false;
return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::Copy);
}
bool Editor::tryDHTMLCut()
{
if (m_document.selection().selection().isInPasswordField())
return false;
return !dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::Cut);
}
bool Editor::shouldInsertText(const String& text, const Optional<SimpleRange>& range, EditorInsertAction action) const
{
if (m_document.frame()->mainFrame().loader().shouldSuppressTextInputFromEditing() && action == EditorInsertAction::Typed)
return false;
return client() && client()->shouldInsertText(text, range, action);
}
void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
{
if (AXObjectCache::accessibilityEnabled()) {
Node* node = endingSelection.start().deprecatedNode();
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->postNotification(node, AXObjectCache::AXValueChanged, TargetObservableParent);
}
updateMarkersForWordsAffectedByEditing(true);
if (client())
client()->respondToChangedContents();
}
bool Editor::hasBidiSelection() const
{
if (m_document.selection().isNone())
return false;
Node* startNode;
if (m_document.selection().isRange()) {
startNode = m_document.selection().selection().start().downstream().deprecatedNode();
Node* endNode = m_document.selection().selection().end().upstream().deprecatedNode();
if (enclosingBlock(startNode) != enclosingBlock(endNode))
return false;
} else
startNode = m_document.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
if (!startNode)
return false;
auto renderer = startNode->renderer();
while (renderer && !is<RenderBlockFlow>(*renderer))
renderer = renderer->parent();
if (!renderer)
return false;
if (!renderer->style().isLeftToRightDirection())
return true;
return downcast<RenderBlockFlow>(*renderer).containsNonZeroBidiLevel();
}
TriState Editor::selectionUnorderedListState() const
{
if (m_document.selection().isCaret()) {
if (enclosingElementWithTag(m_document.selection().selection().start(), ulTag))
return TriState::True;
} else if (m_document.selection().isRange()) {
auto* startNode = enclosingElementWithTag(m_document.selection().selection().start(), ulTag);
auto* endNode = enclosingElementWithTag(m_document.selection().selection().end(), ulTag);
if (startNode && endNode && startNode == endNode)
return TriState::True;
}
return TriState::False;
}
TriState Editor::selectionOrderedListState() const
{
if (m_document.selection().isCaret()) {
if (enclosingElementWithTag(m_document.selection().selection().start(), olTag))
return TriState::True;
} else if (m_document.selection().isRange()) {
auto* startNode = enclosingElementWithTag(m_document.selection().selection().start(), olTag);
auto* endNode = enclosingElementWithTag(m_document.selection().selection().end(), olTag);
if (startNode && endNode && startNode == endNode)
return TriState::True;
}
return TriState::False;
}
RefPtr<Node> Editor::insertOrderedList()
{
if (!canEditRichly())
return nullptr;
auto newList = InsertListCommand::insertList(document(), InsertListCommand::Type::OrderedList);
revealSelectionAfterEditingOperation();
return newList;
}
RefPtr<Node> Editor::insertUnorderedList()
{
if (!canEditRichly())
return nullptr;
auto newList = InsertListCommand::insertList(document(), InsertListCommand::Type::UnorderedList);
revealSelectionAfterEditingOperation();
return newList;
}
bool Editor::canIncreaseSelectionListLevel()
{
return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(&document());
}
bool Editor::canDecreaseSelectionListLevel()
{
return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(&document());
}
RefPtr<Node> Editor::increaseSelectionListLevel()
{
if (!canEditRichly() || m_document.selection().isNone())
return nullptr;
RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(&document());
revealSelectionAfterEditingOperation();
return newList;
}
RefPtr<Node> Editor::increaseSelectionListLevelOrdered()
{
if (!canEditRichly() || m_document.selection().isNone())
return nullptr;
RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(&document());
revealSelectionAfterEditingOperation();
return newList;
}
RefPtr<Node> Editor::increaseSelectionListLevelUnordered()
{
if (!canEditRichly() || m_document.selection().isNone())
return nullptr;
RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(&document());
revealSelectionAfterEditingOperation();
return newList;
}
void Editor::decreaseSelectionListLevel()
{
if (!canEditRichly() || m_document.selection().isNone())
return;
DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(&document());
revealSelectionAfterEditingOperation();
}
void Editor::removeFormattingAndStyle()
{
RemoveFormatCommand::create(document())->apply();
}
void Editor::clearLastEditCommand()
{
m_lastEditCommand = nullptr;
}
Element* Editor::findEventTargetFrom(const VisibleSelection& selection) const
{
Element* target = selection.start().element();
if (!target)
target = document().bodyOrFrameset();
if (!target)
return nullptr;
return target;
}
Element* Editor::findEventTargetFromSelection() const
{
return findEventTargetFrom(m_document.selection().selection());
}
void Editor::applyStyle(StyleProperties* style, EditAction editingAction)
{
if (style)
applyStyle(EditingStyle::create(style), editingAction, ColorFilterMode::UseOriginalColor);
}
void Editor::applyStyle(RefPtr<EditingStyle>&& style, EditAction editingAction, ColorFilterMode colorFilterMode)
{
if (!style)
return;
auto selectionType = m_document.selection().selection().selectionType();
if (selectionType == VisibleSelection::NoSelection)
return;
String inputTypeName = inputTypeNameForEditingAction(editingAction);
String inputEventData = inputEventDataForEditingStyleAndAction(*style, editingAction);
RefPtr<Element> element = m_document.selection().selection().rootEditableElement();
if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
return;
Ref<EditingStyle> styleToApply = colorFilterMode == ColorFilterMode::InvertColor ? style->inverseTransformColorIfNeeded(*element) : style.releaseNonNull();
switch (selectionType) {
case VisibleSelection::CaretSelection:
computeAndSetTypingStyle(styleToApply.get(), editingAction);
break;
case VisibleSelection::RangeSelection:
ApplyStyleCommand::create(document(), styleToApply.ptr(), editingAction)->apply();
break;
default:
break;
}
if (client())
client()->didApplyStyle();
if (element)
dispatchInputEvent(*element, inputTypeName, inputEventData);
}
bool Editor::shouldApplyStyle(const StyleProperties& style, const SimpleRange& range)
{
return client()->shouldApplyStyle(style, range);
}
void Editor::applyParagraphStyle(StyleProperties* style, EditAction editingAction)
{
if (!style)
return;
auto selectionType = m_document.selection().selection().selectionType();
if (selectionType == VisibleSelection::NoSelection)
return;
String inputTypeName = inputTypeNameForEditingAction(editingAction);
String inputEventData = inputEventDataForEditingStyleAndAction(style, editingAction);
RefPtr<Element> element = m_document.selection().selection().rootEditableElement();
if (element && !dispatchBeforeInputEvent(*element, inputTypeName, inputEventData))
return;
ApplyStyleCommand::create(document(), EditingStyle::create(style).ptr(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
client()->didApplyStyle();
if (element)
dispatchInputEvent(*element, inputTypeName, inputEventData);
}
void Editor::applyStyleToSelection(StyleProperties* style, EditAction editingAction)
{
if (!style || style->isEmpty() || !canEditRichly())
return;
if (!client() || !client()->shouldApplyStyle(*style, m_document.selection().selection().toNormalizedRange()))
return;
applyStyle(style, editingAction);
}
void Editor::applyStyleToSelection(Ref<EditingStyle>&& style, EditAction editingAction, ColorFilterMode colorFilterMode)
{
if (style->isEmpty() || !canEditRichly())
return;
if (!client() || !client()->shouldApplyStyle(style->styleWithResolvedTextDecorations(), m_document.selection().selection().toNormalizedRange()))
return;
applyStyle(WTFMove(style), editingAction, colorFilterMode);
}
void Editor::applyParagraphStyleToSelection(StyleProperties* style, EditAction editingAction)
{
if (!style || style->isEmpty() || !canEditRichly())
return;
if (client() && client()->shouldApplyStyle(*style, m_document.selection().selection().toNormalizedRange()))
applyParagraphStyle(style, editingAction);
}
bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
{
if (auto editingStyle = EditingStyle::styleAtSelectionStart(m_document.selection().selection(), propertyID == CSSPropertyBackgroundColor))
return editingStyle->hasStyle(propertyID, value);
return false;
}
TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
{
return EditingStyle::create(propertyID, value)->triStateOfStyle(m_document.selection().selection());
}
String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
{
RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_document.selection().selection(),
propertyID == CSSPropertyBackgroundColor);
if (!selectionStyle || !selectionStyle->style())
return String();
if (propertyID == CSSPropertyFontSize)
return String::number(selectionStyle->legacyFontSize(document()));
return selectionStyle->style()->getPropertyValue(propertyID);
}
void Editor::indent()
{
IndentOutdentCommand::create(document(), IndentOutdentCommand::Indent)->apply();
}
void Editor::outdent()
{
IndentOutdentCommand::create(document(), IndentOutdentCommand::Outdent)->apply();
}
static void notifyTextFromControls(Element* startRoot, Element* endRoot)
{
HTMLTextFormControlElement* startingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(startRoot));
HTMLTextFormControlElement* endingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(endRoot));
if (startingTextControl)
startingTextControl->didEditInnerTextValue();
if (endingTextControl && startingTextControl != endingTextControl)
endingTextControl->didEditInnerTextValue();
}
static bool dispatchBeforeInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { }, Event::IsCancelable cancelable = Event::IsCancelable::Yes)
{
bool continueWithDefaultBehavior = true;
if (startRoot)
continueWithDefaultBehavior &= dispatchBeforeInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
if (endRoot && endRoot != startRoot)
continueWithDefaultBehavior &= dispatchBeforeInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges, cancelable);
return continueWithDefaultBehavior;
}
static void dispatchInputEvents(RefPtr<Element> startRoot, RefPtr<Element> endRoot, const AtomString& inputTypeName, const String& data = { }, RefPtr<DataTransfer>&& dataTransfer = nullptr, const Vector<RefPtr<StaticRange>>& targetRanges = { })
{
if (startRoot)
dispatchInputEvent(*startRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
if (endRoot && endRoot != startRoot)
dispatchInputEvent(*endRoot, inputTypeName, data, WTFMove(dataTransfer), targetRanges);
}
bool Editor::willApplyEditing(CompositeEditCommand& command, Vector<RefPtr<StaticRange>>&& targetRanges) const
{
if (!command.shouldDispatchInputEvents())
return true;
auto* composition = command.composition();
if (!composition)
return true;
if (command.isTopLevelCommand() && command.isTypingCommand() && document().view())
m_prohibitScrollingDueToContentSizeChangesWhileTyping = document().view()->prohibitScrollingWhenChangingContentSizeForScope();
return dispatchBeforeInputEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement(), command.inputEventTypeName(),
command.inputEventData(), command.inputEventDataTransfer(), targetRanges, command.isBeforeInputEventCancelable() ? Event::IsCancelable::Yes : Event::IsCancelable::No);
}
void Editor::appliedEditing(CompositeEditCommand& command)
{
LOG(Editing, "Editor %p appliedEditing", this);
document().updateLayout();
ASSERT(command.composition());
auto& composition = *command.composition();
VisibleSelection newSelection(command.endingSelection());
notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
if (command.isTopLevelCommand()) {
OptionSet<FrameSelection::SetSelectionOption> options;
if (command.isDictationCommand())
options.add(FrameSelection::DictationTriggered);
changeSelectionAfterCommand(newSelection, options);
}
if (command.shouldDispatchInputEvents())
dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), command.inputEventTypeName(), command.inputEventData(), command.inputEventDataTransfer());
if (command.isTopLevelCommand()) {
updateEditorUINowIfScheduled();
m_alternativeTextController->respondToAppliedEditing(&command);
if (!command.preservesTypingStyle())
m_document.selection().clearTypingStyle();
if (m_lastEditCommand.get() == &command)
ASSERT(command.isTypingCommand());
else {
m_lastEditCommand = &command;
if (client())
client()->registerUndoStep(m_lastEditCommand->ensureComposition());
}
respondToChangedContents(newSelection);
if (command.isTypingCommand())
m_prohibitScrollingDueToContentSizeChangesWhileTyping = nullptr;
}
}
bool Editor::willUnapplyEditing(const EditCommandComposition& composition) const
{
return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyUndo");
}
void Editor::unappliedEditing(EditCommandComposition& composition)
{
document().updateLayout();
notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
VisibleSelection newSelection(composition.startingSelection());
changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyUndo");
updateEditorUINowIfScheduled();
m_alternativeTextController->respondToUnappliedEditing(&composition);
m_lastEditCommand = nullptr;
if (auto* client = this->client())
client->registerRedoStep(composition);
respondToChangedContents(newSelection);
}
bool Editor::willReapplyEditing(const EditCommandComposition& composition) const
{
return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyRedo");
}
void Editor::reappliedEditing(EditCommandComposition& composition)
{
document().updateLayout();
notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
VisibleSelection newSelection(composition.endingSelection());
changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyRedo");
updateEditorUINowIfScheduled();
m_lastEditCommand = nullptr;
if (auto* client = this->client())
client->registerUndoStep(composition);
respondToChangedContents(newSelection);
}
Editor::Editor(Document& document)
: m_document(document)
, m_killRing(makeUnique<PAL::KillRing>())
, m_spellChecker(makeUnique<SpellChecker>(document))
, m_alternativeTextController(makeUnique<AlternativeTextController>(document))
, m_editorUIUpdateTimer(*this, &Editor::editorUIUpdateTimerFired)
#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS_FAMILY)
, m_telephoneNumberDetectionUpdateTimer(*this, &Editor::scanSelectionForTelephoneNumbers)
#endif
{
}
Editor::~Editor() = default;
void Editor::clear()
{
m_lastEditCommand = nullptr;
if (m_compositionNode) {
m_compositionNode = nullptr;
if (EditorClient* client = this->client())
client->discardedComposition(m_document.frame());
}
m_customCompositionUnderlines.clear();
m_customCompositionHighlights.clear();
m_shouldStyleWithCSS = false;
m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
m_mark = { };
m_oldSelectionForEditorUIUpdate = { };
m_editorUIUpdateTimer.stop();
m_alternativeTextController->stopAlternativeTextUITimer();
#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS_FAMILY)
m_telephoneNumberDetectionUpdateTimer.stop();
m_detectedTelephoneNumberRanges.clear();
#endif
}
bool Editor::insertText(const String& text, Event* triggeringEvent, TextEventInputType inputType)
{
return m_document.frame()->eventHandler().handleTextInputEvent(text, triggeringEvent, inputType);
}
bool Editor::insertTextForConfirmedComposition(const String& text)
{
return m_document.frame()->eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
}
bool Editor::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent)
{
return m_alternativeTextController->insertDictatedText(text, dictationAlternatives, triggeringEvent);
}
bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
{
if (text.isEmpty())
return false;
VisibleSelection selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
if (!shouldInsertText(text, selection.toNormalizedRange(), EditorInsertAction::Typed))
return true;
bool isStartOfNewWord = isSpaceOrNewline(selection.visibleStart().characterBefore());
updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]) || isStartOfNewWord);
bool shouldConsiderApplyingAutocorrection = false;
if (text == " " || text == "\t")
shouldConsiderApplyingAutocorrection = true;
if (text.length() == 1 && u_ispunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
shouldConsiderApplyingAutocorrection = true;
bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
selection = selectionForCommand(triggeringEvent);
if (selection.isContentEditable()) {
if (Node* selectionStart = selection.start().deprecatedNode()) {
Ref<Document> document(selectionStart->document());
if (triggeringEvent && triggeringEvent->isDictation())
DictationCommand::insertText(document, text, triggeringEvent->dictationAlternatives(), selection);
else {
TypingCommand::Options options = 0;
if (selectInsertedText)
options |= TypingCommand::SelectInsertedText;
if (autocorrectionWasApplied)
options |= TypingCommand::RetainAutocorrectionIndicator;
if (triggeringEvent && triggeringEvent->isAutocompletion())
options |= TypingCommand::IsAutocompletion;
TypingCommand::insertText(document, text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionFinal : TypingCommand::TextCompositionNone);
}
if (client() && client()->shouldRevealCurrentSelectionAfterInsertion()) {
if (auto* page = document->page())
page->revealCurrentSelection();
}
}
}
return true;
}
bool Editor::insertLineBreak()
{
if (!canEdit())
return false;
if (!shouldInsertText("\n"_s, m_document.selection().selection().toNormalizedRange(), EditorInsertAction::Typed))
return true;
VisiblePosition caret = m_document.selection().selection().visibleStart();
bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
TypingCommand::insertLineBreak(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
return true;
}
bool Editor::insertParagraphSeparator()
{
if (!canEdit())
return false;
if (!canEditRichly())
return insertLineBreak();
if (!shouldInsertText("\n"_s, m_document.selection().selection().toNormalizedRange(), EditorInsertAction::Typed))
return true;
VisiblePosition caret = m_document.selection().selection().visibleStart();
bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
TypingCommand::insertParagraphSeparator(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
return true;
}
bool Editor::insertParagraphSeparatorInQuotedContent()
{
TypingCommand::insertParagraphSeparatorInQuotedContent(document());
revealSelectionAfterEditingOperation();
return true;
}
void Editor::cut(FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
SetForScope<bool> copyScope { m_copyingFromMenuOrKeyBinding, fromMenuOrKeyBinding == FromMenuOrKeyBinding::Yes };
if (tryDHTMLCut())
return; if (!canCut()) {
PAL::systemBeep();
return;
}
performCutOrCopy(CutAction);
}
void Editor::copy(FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
SetForScope<bool> copyScope { m_copyingFromMenuOrKeyBinding, fromMenuOrKeyBinding == FromMenuOrKeyBinding::Yes };
if (tryDHTMLCopy())
return; if (!canCopy()) {
PAL::systemBeep();
return;
}
performCutOrCopy(CopyAction);
}
void Editor::postTextStateChangeNotificationForCut(const String& text, const VisibleSelection& selection)
{
if (!AXObjectCache::accessibilityEnabled())
return;
if (!text.length())
return;
AXObjectCache* cache = document().existingAXObjectCache();
if (!cache)
return;
cache->postTextStateChangeNotification(selection.start().anchorNode(), AXTextEditTypeCut, text, selection.start());
}
void Editor::performCutOrCopy(EditorActionSpecifier action)
{
auto selection = selectedRange();
willWriteSelectionToPasteboard(selection);
if (action == CutAction) {
if (!shouldDeleteRange(selection))
return;
updateMarkersForWordsAffectedByEditing(true);
}
if (enclosingTextFormControl(m_document.selection().selection().start()))
Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForDataTransfer(), canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
else {
HTMLImageElement* imageElement = nullptr;
if (action == CopyAction)
imageElement = imageElementFromImageDocument(document());
if (imageElement) {
#if !PLATFORM(WIN)
writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *imageElement, document().url(), document().title());
#else
Pasteboard::createForCopyAndPaste()->writeImage(*imageElement, document().url(), document().title());
#endif
} else {
#if !PLATFORM(WIN)
writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
#else
Pasteboard::createForCopyAndPaste()->writeSelection(*selection, canSmartCopyOrDelete(), *m_document.frame(), IncludeImageAltTextForDataTransfer);
#endif
}
}
didWriteSelectionToPasteboard();
if (action == CutAction) {
String text;
if (AXObjectCache::accessibilityEnabled())
text = AccessibilityObject::stringForVisiblePositionRange(m_document.selection().selection());
deleteSelectionWithSmartDelete(canSmartCopyOrDelete(), EditAction::Cut);
if (AXObjectCache::accessibilityEnabled())
postTextStateChangeNotificationForCut(text, m_document.selection().selection());
}
}
void Editor::paste(FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
paste(*Pasteboard::createForCopyAndPaste(), fromMenuOrKeyBinding);
}
void Editor::paste(Pasteboard& pasteboard, FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
SetForScope<bool> pasteScope { m_pastingFromMenuOrKeyBinding, fromMenuOrKeyBinding == FromMenuOrKeyBinding::Yes };
if (!dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::Paste))
return; if (!canPaste())
return;
updateMarkersForWordsAffectedByEditing(false);
ResourceCacheValidationSuppressor validationSuppressor(document().cachedResourceLoader());
if (m_document.selection().selection().isContentRichlyEditable())
pasteWithPasteboard(&pasteboard, { PasteOption::AllowPlainText });
else
pasteAsPlainTextWithPasteboard(pasteboard);
}
void Editor::pasteAsPlainText(FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
SetForScope<bool> pasteScope { m_pastingFromMenuOrKeyBinding, fromMenuOrKeyBinding == FromMenuOrKeyBinding::Yes };
if (!dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::PasteAsPlainText))
return;
if (!canPaste())
return;
updateMarkersForWordsAffectedByEditing(false);
pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
}
void Editor::pasteAsQuotation(FromMenuOrKeyBinding fromMenuOrKeyBinding)
{
SetForScope<bool> pasteScope { m_pastingFromMenuOrKeyBinding, fromMenuOrKeyBinding == FromMenuOrKeyBinding::Yes };
if (!dispatchClipboardEvent(findEventTargetFromSelection(), ClipboardEventKind::PasteAsQuotation))
return;
if (!canPaste())
return;
updateMarkersForWordsAffectedByEditing(false);
ResourceCacheValidationSuppressor validationSuppressor(document().cachedResourceLoader());
auto pasteboard = Pasteboard::createForCopyAndPaste();
if (m_document.selection().selection().isContentRichlyEditable())
pasteWithPasteboard(pasteboard.get(), { PasteOption::AllowPlainText, PasteOption::AsQuotation });
else
pasteAsPlainTextWithPasteboard(*pasteboard);
}
void Editor::quoteFragmentForPasting(DocumentFragment& fragment)
{
auto blockQuote = HTMLQuoteElement::create(blockquoteTag, document());
blockQuote->setAttributeWithoutSynchronization(typeAttr, AtomString("cite"));
blockQuote->setAttributeWithoutSynchronization(classAttr, AtomString(ApplePasteAsQuotation));
auto childNode = fragment.firstChild();
if (childNode) {
while (childNode) {
blockQuote->appendChild(*childNode);
childNode = fragment.firstChild();
}
} else
blockQuote->appendChild(HTMLBRElement::create(document()));
fragment.appendChild(blockQuote);
}
void Editor::performDelete()
{
if (!canDelete()) {
PAL::systemBeep();
return;
}
addRangeToKillRing(*selectedRange(), KillRingInsertionMode::AppendText);
deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
setStartNewKillRingSequence(false);
}
void Editor::changeSelectionListType()
{
if (auto type = ChangeListTypeCommand::listConversionType(document()))
ChangeListTypeCommand::create(document(), *type)->apply();
}
void Editor::simplifyMarkup(Node* startNode, Node* endNode)
{
if (!startNode)
return;
if (endNode) {
if (&startNode->document() != &endNode->document())
return;
Node* node = startNode;
while (node && node != endNode)
node = NodeTraversal::next(*node);
if (!node)
return;
}
SimplifyMarkupCommand::create(document(), startNode, endNode ? NodeTraversal::next(*endNode) : nullptr)->apply();
}
void Editor::copyURL(const URL& url, const String& title)
{
copyURL(url, title, *Pasteboard::createForCopyAndPaste());
}
void Editor::copyURL(const URL& url, const String& title, Pasteboard& pasteboard)
{
PasteboardURL pasteboardURL;
pasteboardURL.url = url;
pasteboardURL.title = title;
#if PLATFORM(MAC)
pasteboardURL.userVisibleForm = userVisibleString(url);
#endif
pasteboard.write(pasteboardURL);
}
PasteboardWriterData::URLData Editor::pasteboardWriterURL(const URL& url, const String& title)
{
PasteboardWriterData::URLData result;
result.url = url;
result.title = title;
#if PLATFORM(MAC)
result.userVisibleForm = userVisibleString(url);
#endif
return result;
}
#if !PLATFORM(IOS_FAMILY)
void Editor::copyImage(const HitTestResult& result)
{
Element* element = result.innerNonSharedElement();
if (!element)
return;
URL url = result.absoluteLinkURL();
if (url.isEmpty())
url = result.absoluteImageURL();
#if !PLATFORM(WIN)
writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *element, url, result.altDisplayString());
#else
Pasteboard::createForCopyAndPaste()->writeImage(*element, url, result.altDisplayString());
#endif
}
#endif
void Editor::revealSelectionIfNeededAfterLoadingImageForElement(HTMLImageElement& element)
{
if (m_imageElementsToLoadBeforeRevealingSelection.isEmpty())
return;
if (!m_imageElementsToLoadBeforeRevealingSelection.remove(&element))
return;
if (!m_imageElementsToLoadBeforeRevealingSelection.isEmpty())
return;
document().updateLayout();
revealSelectionAfterEditingOperation();
}
void Editor::renderLayerDidScroll(const RenderLayer& layer)
{
if (m_imageElementsToLoadBeforeRevealingSelection.isEmpty())
return;
auto startContainer = makeRefPtr(m_document.selection().selection().start().containerNode());
if (!startContainer)
return;
auto* startContainerRenderer = startContainer->renderer();
if (!startContainerRenderer)
return;
for (auto* enclosingLayer = startContainerRenderer->enclosingLayer(); enclosingLayer; enclosingLayer = enclosingLayer->parent()) {
if (enclosingLayer == &layer) {
m_imageElementsToLoadBeforeRevealingSelection.clear();
break;
}
}
}
bool Editor::isContinuousSpellCheckingEnabled() const
{
return client() && client()->isContinuousSpellCheckingEnabled();
}
void Editor::toggleContinuousSpellChecking()
{
if (client())
client()->toggleContinuousSpellChecking();
}
bool Editor::isGrammarCheckingEnabled()
{
return client() && client()->isGrammarCheckingEnabled();
}
void Editor::toggleGrammarChecking()
{
if (client())
client()->toggleGrammarChecking();
}
int Editor::spellCheckerDocumentTag()
{
return client() ? client()->spellCheckerDocumentTag() : 0;
}
#if USE(APPKIT)
void Editor::uppercaseWord()
{
if (client())
client()->uppercaseWord();
}
void Editor::lowercaseWord()
{
if (client())
client()->lowercaseWord();
}
void Editor::capitalizeWord()
{
if (client())
client()->capitalizeWord();
}
#endif
#if USE(AUTOMATIC_TEXT_REPLACEMENT)
void Editor::showSubstitutionsPanel()
{
if (!client()) {
LOG_ERROR("No NSSpellChecker");
return;
}
if (client()->substitutionsPanelIsShowing()) {
client()->showSubstitutionsPanel(false);
return;
}
client()->showSubstitutionsPanel(true);
}
bool Editor::substitutionsPanelIsShowing()
{
if (!client())
return false;
return client()->substitutionsPanelIsShowing();
}
void Editor::toggleSmartInsertDelete()
{
if (client())
client()->toggleSmartInsertDelete();
}
bool Editor::isAutomaticQuoteSubstitutionEnabled()
{
return client() && client()->isAutomaticQuoteSubstitutionEnabled();
}
void Editor::toggleAutomaticQuoteSubstitution()
{
if (client())
client()->toggleAutomaticQuoteSubstitution();
}
bool Editor::isAutomaticLinkDetectionEnabled()
{
return client() && client()->isAutomaticLinkDetectionEnabled();
}
void Editor::toggleAutomaticLinkDetection()
{
if (client())
client()->toggleAutomaticLinkDetection();
}
bool Editor::isAutomaticDashSubstitutionEnabled()
{
return client() && client()->isAutomaticDashSubstitutionEnabled();
}
void Editor::toggleAutomaticDashSubstitution()
{
if (client())
client()->toggleAutomaticDashSubstitution();
}
bool Editor::isAutomaticTextReplacementEnabled()
{
return client() && client()->isAutomaticTextReplacementEnabled();
}
void Editor::toggleAutomaticTextReplacement()
{
if (client())
client()->toggleAutomaticTextReplacement();
}
bool Editor::isAutomaticSpellingCorrectionEnabled()
{
return m_alternativeTextController->isAutomaticSpellingCorrectionEnabled();
}
void Editor::toggleAutomaticSpellingCorrection()
{
if (client())
client()->toggleAutomaticSpellingCorrection();
}
#endif
bool Editor::shouldEndEditing(const SimpleRange& range)
{
return client() && client()->shouldEndEditing(range);
}
bool Editor::shouldBeginEditing(const SimpleRange& range)
{
return client() && client()->shouldBeginEditing(range);
}
void Editor::clearUndoRedoOperations()
{
if (client())
client()->clearUndoRedoOperations();
}
bool Editor::canUndo() const
{
return client() && client()->canUndo();
}
void Editor::undo()
{
if (client())
client()->undo();
}
bool Editor::canRedo() const
{
return client() && client()->canRedo();
}
void Editor::redo()
{
if (client())
client()->redo();
}
void Editor::registerCustomUndoStep(Ref<CustomUndoStep>&& undoStep)
{
ASSERT(RuntimeEnabledFeatures::sharedFeatures().undoManagerAPIEnabled());
if (auto* client = this->client())
client->registerUndoStep(WTFMove(undoStep));
}
void Editor::didBeginEditing()
{
if (client())
client()->didBeginEditing();
}
void Editor::didEndEditing()
{
if (client())
client()->didEndEditing();
}
void Editor::willWriteSelectionToPasteboard(const Optional<SimpleRange>& range)
{
if (client())
client()->willWriteSelectionToPasteboard(range);
}
void Editor::didWriteSelectionToPasteboard()
{
if (client())
client()->didWriteSelectionToPasteboard();
}
void Editor::toggleBold()
{
command("ToggleBold").execute();
}
void Editor::toggleUnderline()
{
command("ToggleUnderline").execute();
}
void Editor::setBaseWritingDirection(WritingDirection direction)
{
#if PLATFORM(IOS_FAMILY)
if (inSameParagraph(m_document.selection().selection().visibleStart(), m_document.selection().selection().visibleEnd())
&& baseWritingDirectionForSelectionStart() == direction)
return;
#endif
Element* focusedElement = document().focusedElement();
if (focusedElement && focusedElement->isTextField()) {
if (direction == WritingDirection::Natural)
return;
auto& focusedFormElement = downcast<HTMLTextFormControlElement>(*focusedElement);
auto directionValue = direction == WritingDirection::LeftToRight ? "ltr" : "rtl";
auto writingDirectionInputTypeName = inputTypeNameForEditingAction(EditAction::SetBlockWritingDirection);
if (!dispatchBeforeInputEvent(focusedFormElement, writingDirectionInputTypeName, directionValue))
return;
focusedFormElement.setAttributeWithoutSynchronization(dirAttr, directionValue);
dispatchInputEvent(focusedFormElement, writingDirectionInputTypeName, directionValue);
document().updateStyleIfNeeded();
return;
}
auto style = MutableStyleProperties::create();
style->setProperty(CSSPropertyDirection, direction == WritingDirection::LeftToRight ? "ltr" : direction == WritingDirection::RightToLeft ? "rtl" : "inherit", false);
applyParagraphStyleToSelection(style.ptr(), EditAction::SetBlockWritingDirection);
}
WritingDirection Editor::baseWritingDirectionForSelectionStart() const
{
auto result = WritingDirection::LeftToRight;
Position pos = m_document.selection().selection().visibleStart().deepEquivalent();
Node* node = pos.deprecatedNode();
if (!node)
return result;
auto renderer = node->renderer();
if (!renderer)
return result;
if (!renderer->isRenderBlockFlow()) {
renderer = renderer->containingBlock();
if (!renderer)
return result;
}
switch (renderer->style().direction()) {
case TextDirection::LTR:
return WritingDirection::LeftToRight;
case TextDirection::RTL:
return WritingDirection::RightToLeft;
}
return result;
}
void Editor::selectComposition()
{
auto range = compositionRange();
if (!range)
return;
VisibleSelection selection;
selection.setWithoutValidation(createLegacyEditingPosition(range->start), createLegacyEditingPosition(range->end));
m_document.selection().setSelection(selection, { });
}
void Editor::confirmComposition()
{
if (!m_compositionNode)
return;
setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
}
void Editor::confirmCompositionAndNotifyClient()
{
if (!hasComposition())
return;
auto frame = makeRefPtr(m_document.frame());
if (!frame)
return;
confirmComposition();
if (auto editorClient = client()) {
editorClient->respondToChangedSelection(frame.get());
editorClient->discardedComposition(frame.get());
}
}
void Editor::cancelComposition()
{
if (!m_compositionNode)
return;
setComposition(emptyString(), CancelComposition);
}
bool Editor::cancelCompositionIfSelectionIsInvalid()
{
unsigned start;
unsigned end;
if (!hasComposition() || ignoreSelectionChanges() || getCompositionSelection(start, end))
return false;
cancelComposition();
return true;
}
void Editor::confirmComposition(const String& text)
{
setComposition(text, ConfirmComposition);
}
class SetCompositionScope {
public:
SetCompositionScope(Document& document)
: m_document(RefPtr(&document))
, m_typingGestureIndicator(*document.frame())
{
m_document->editor().setIgnoreSelectionChanges(true);
}
~SetCompositionScope()
{
m_document->editor().setIgnoreSelectionChanges(false);
if (auto* editorClient = m_document->editor().client())
editorClient->didUpdateComposition();
}
RefPtr<Document> m_document;
UserTypingGestureIndicator m_typingGestureIndicator;
};
void Editor::setComposition(const String& text, SetCompositionMode mode)
{
ASSERT(mode == ConfirmComposition || mode == CancelComposition);
SetCompositionScope setCompositionScope(m_document);
if (mode == CancelComposition)
ASSERT(text == emptyString());
else
selectComposition();
m_compositionNode = nullptr;
m_customCompositionUnderlines.clear();
m_customCompositionHighlights.clear();
if (m_document.selection().isNone())
return;
if (mode != CancelComposition)
TypingCommand::deleteSelection(document(), 0, TypingCommand::TextCompositionPending);
insertTextForConfirmedComposition(text);
if (auto* target = document().focusedElement())
target->dispatchEvent(CompositionEvent::create(eventNames().compositionendEvent, document().windowProxy(), text));
if (mode == CancelComposition) {
TypingCommand::closeTyping(m_document);
}
}
void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, const Vector<CompositionHighlight>& highlights, unsigned selectionStart, unsigned selectionEnd)
{
SetCompositionScope setCompositionScope(m_document);
document().updateStyleIfNeeded();
selectComposition();
if (m_document.selection().isNone())
return;
String originalText = selectedText();
bool isStartingToRecomposeExistingRange = !text.isEmpty() && selectionStart < selectionEnd && !hasComposition();
if (isStartingToRecomposeExistingRange) {
TypingCommand::deleteSelection(document(), 0, TypingCommand::TextCompositionFinal);
const VisibleSelection& currentSelection = m_document.selection().selection();
if (currentSelection.isRange()) {
m_document.selection().setSelection({ currentSelection.end(), currentSelection.end() });
}
}
#if PLATFORM(IOS_FAMILY)
client()->startDelayingAndCoalescingContentChangeNotifications();
#endif
Element* target = document().focusedElement();
if (target) {
RefPtr<CompositionEvent> event;
if (!m_compositionNode) {
if (!text.isEmpty()) {
target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, document().windowProxy(), originalText));
event = CompositionEvent::create(eventNames().compositionupdateEvent, document().windowProxy(), text);
}
} else if (!text.isEmpty())
event = CompositionEvent::create(eventNames().compositionupdateEvent, document().windowProxy(), text);
if (event)
target->dispatchEvent(*event);
}
if (text.isEmpty()) {
TypingCommand::deleteSelection(document(), TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionPending);
if (target)
target->dispatchEvent(CompositionEvent::create(eventNames().compositionendEvent, document().windowProxy(), text));
}
m_compositionNode = nullptr;
m_customCompositionUnderlines.clear();
m_customCompositionHighlights.clear();
if (!text.isEmpty()) {
TypingCommand::insertText(document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionPending);
Position base = m_document.selection().selection().base().downstream();
Position extent = m_document.selection().selection().extent();
Node* baseNode = base.deprecatedNode();
unsigned baseOffset = base.deprecatedEditingOffset();
Node* extentNode = extent.deprecatedNode();
unsigned extentOffset = extent.deprecatedEditingOffset();
if (is<Text>(baseNode) && baseNode == extentNode && baseOffset + text.length() == extentOffset) {
m_compositionNode = downcast<Text>(baseNode);
m_compositionStart = baseOffset;
m_compositionEnd = extentOffset;
m_customCompositionUnderlines = underlines;
for (auto& underline : m_customCompositionUnderlines) {
underline.startOffset += baseOffset;
underline.endOffset += baseOffset;
}
m_customCompositionHighlights = highlights;
for (auto& highlight : m_customCompositionHighlights) {
highlight.startOffset += baseOffset;
highlight.endOffset += baseOffset;
}
if (baseNode->renderer())
baseNode->renderer()->repaint();
unsigned start = std::min(baseOffset + selectionStart, extentOffset);
unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
auto range = SimpleRange { { *baseNode, start }, { *baseNode, end } };
m_document.selection().setSelectedRange(range, DOWNSTREAM, FrameSelection::ShouldCloseTyping::No);
}
}
#if PLATFORM(IOS_FAMILY)
client()->stopDelayingAndCoalescingContentChangeNotifications();
#endif
}
void Editor::ignoreSpelling()
{
if (!client())
return;
if (auto selectedRange = m_document.selection().selection().toNormalizedRange())
removeMarkers(*selectedRange, DocumentMarker::Spelling);
String text = selectedText();
ASSERT(text.length());
textChecker()->ignoreWordInSpellDocument(text);
}
void Editor::learnSpelling()
{
if (!client())
return;
if (auto selectedRange = m_document.selection().selection().toNormalizedRange())
removeMarkers(*selectedRange, DocumentMarker::Spelling);
String text = selectedText();
ASSERT(text.length());
textChecker()->learnWord(text);
}
#if !PLATFORM(IOS_FAMILY)
void Editor::advanceToNextMisspelling(bool startBeforeSelection)
{
Ref<Document> protectedDocument(m_document);
VisibleSelection selection(m_document.selection().selection());
auto spellingSearchRange = makeRangeSelectingNodeContents(document());
bool startedWithSelection = false;
if (selection.start().deprecatedNode()) {
startedWithSelection = true;
if (startBeforeSelection) {
auto start = selection.visibleStart();
auto beforeStart = start.previous();
if (beforeStart.isNotNull())
start = beforeStart;
spellingSearchRange.start = *makeBoundaryPoint(start);
} else
spellingSearchRange.start = *makeBoundaryPoint(selection.visibleEnd());
}
auto position = createLegacyEditingPosition(spellingSearchRange.start);
if (!isEditablePosition(position)) {
position = VisiblePosition(firstEditablePositionAfterPositionInRoot(position, document().documentElement())).deepEquivalent();
if (position.isNull())
return;
if (auto point = makeBoundaryPoint(position.parentAnchoredEquivalent()))
spellingSearchRange.start = *point;
startedWithSelection = false; }
auto* topNode = highestEditableRoot(position);
if (topNode)
spellingSearchRange.end = makeBoundaryPointAfterNodeContents(*topNode);
if (startedWithSelection) {
auto oneBeforeStart = VisiblePosition(createLegacyEditingPosition(spellingSearchRange.start), DOWNSTREAM).previous();
if (oneBeforeStart.isNotNull())
spellingSearchRange.start = *makeBoundaryPoint(endOfWord(oneBeforeStart));
}
if (spellingSearchRange.collapsed())
return;
if (!client())
return;
auto searchEndAfterWrap = spellingSearchRange.end;
TextCheckingHelper::MisspelledWord misspelledWord;
TextCheckingHelper::UngrammaticalPhrase ungrammaticalPhrase;
auto grammarSearchRange = spellingSearchRange;
if (unifiedTextCheckerEnabled()) {
auto foundItem = TextCheckingHelper(*client(), spellingSearchRange).findFirstMisspelledWordOrUngrammaticalPhrase(isGrammarCheckingEnabled());
if (auto word = WTF::get_if<TextCheckingHelper::MisspelledWord>(foundItem))
misspelledWord = WTFMove(*word);
else
ungrammaticalPhrase = WTF::get<TextCheckingHelper::UngrammaticalPhrase>(WTFMove(foundItem));
} else {
misspelledWord = TextCheckingHelper(*client(), spellingSearchRange).findFirstMisspelledWord();
if (!misspelledWord.word.isEmpty()) {
CharacterIterator characterIterator(grammarSearchRange);
characterIterator.advance(misspelledWord.offset);
grammarSearchRange.end = characterIterator.range().start;
}
if (isGrammarCheckingEnabled())
ungrammaticalPhrase = TextCheckingHelper(*client(), grammarSearchRange).findFirstUngrammaticalPhrase();
}
if (startedWithSelection && misspelledWord.word.isEmpty() && ungrammaticalPhrase.phrase.isEmpty()) {
if (topNode)
spellingSearchRange.start = makeBoundaryPointBeforeNodeContents(*topNode);
spellingSearchRange.end = searchEndAfterWrap;
if (unifiedTextCheckerEnabled()) {
auto foundItem = TextCheckingHelper(*client(), spellingSearchRange).findFirstMisspelledWordOrUngrammaticalPhrase(isGrammarCheckingEnabled());
if (auto word = WTF::get_if<TextCheckingHelper::MisspelledWord>(foundItem))
misspelledWord = WTFMove(*word);
else
ungrammaticalPhrase = WTF::get<TextCheckingHelper::UngrammaticalPhrase>(WTFMove(foundItem));
} else {
misspelledWord = TextCheckingHelper(*client(), spellingSearchRange).findFirstMisspelledWord();
grammarSearchRange = spellingSearchRange;
if (!misspelledWord.word.isEmpty()) {
CharacterIterator characterIterator(grammarSearchRange);
characterIterator.advance(misspelledWord.offset);
grammarSearchRange.end = characterIterator.range().start;
}
if (isGrammarCheckingEnabled())
ungrammaticalPhrase = TextCheckingHelper(*client(), grammarSearchRange).findFirstUngrammaticalPhrase();
}
}
if (!ungrammaticalPhrase.phrase.isEmpty()) {
ASSERT(ungrammaticalPhrase.phrase.length() > 0);
ASSERT(ungrammaticalPhrase.detail.range.length > 0);
auto badGrammarRange = resolveCharacterRange(grammarSearchRange, { ungrammaticalPhrase.offset + ungrammaticalPhrase.detail.range.location, ungrammaticalPhrase.detail.range.length });
m_document.selection().setSelection(VisibleSelection(badGrammarRange, SEL_DEFAULT_AFFINITY));
m_document.selection().revealSelection();
client()->updateSpellingUIWithGrammarString(ungrammaticalPhrase.phrase, ungrammaticalPhrase.detail);
addMarker(badGrammarRange, DocumentMarker::Grammar, ungrammaticalPhrase.detail.userDescription);
} else if (!misspelledWord.word.isEmpty()) {
auto misspellingRange = resolveCharacterRange(spellingSearchRange, { misspelledWord.offset, misspelledWord.word.length() });
m_document.selection().setSelection(VisibleSelection(misspellingRange, DOWNSTREAM));
m_document.selection().revealSelection();
client()->updateSpellingUIWithMisspelledWord(misspelledWord.word);
addMarker(misspellingRange, DocumentMarker::Spelling);
}
}
#endif // !PLATFORM(IOS_FAMILY)
String Editor::misspelledWordAtCaretOrRange(Node* clickedNode) const
{
if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
return String();
VisibleSelection selection = m_document.selection().selection();
if (!selection.isContentEditable() || selection.isNone())
return String();
VisibleSelection wordSelection(selection.base());
wordSelection.expandUsingGranularity(TextGranularity::WordGranularity);
auto wordRange = wordSelection.toNormalizedRange();
if (!wordRange)
return String();
if (selection.isRange() && *wordRange != selection.toNormalizedRange())
return String();
String word = plainText(*wordRange);
if (word.isEmpty() || !client())
return String();
int wordLength = word.length();
int misspellingLocation = -1;
int misspellingLength = 0;
textChecker()->checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
return misspellingLength == wordLength ? word : String();
}
String Editor::misspelledSelectionString() const
{
String selectedString = selectedText();
int length = selectedString.length();
if (!length || !client())
return String();
int misspellingLocation = -1;
int misspellingLength = 0;
textChecker()->checkSpellingOfString(selectedString, &misspellingLocation, &misspellingLength);
if (misspellingLength != length)
return String();
client()->updateSpellingUIWithMisspelledWord(selectedString);
return selectedString;
}
Vector<String> Editor::guessesForMisspelledWord(const String& word) const
{
ASSERT(word.length());
Vector<String> guesses;
if (client())
textChecker()->getGuessesForWord(word, String(), m_document.selection().selection(), guesses);
return guesses;
}
TextCheckingGuesses Editor::guessesForMisspelledOrUngrammatical()
{
if (unifiedTextCheckerEnabled()) {
Optional<SimpleRange> range;
auto selection = m_document.selection().selection();
if (selection.isCaret() && behavior().shouldAllowSpellingSuggestionsWithoutSelection()) {
auto wordSelection = VisibleSelection(selection.base());
wordSelection.expandUsingGranularity(TextGranularity::WordGranularity);
range = wordSelection.toNormalizedRange();
} else
range = selection.toNormalizedRange();
if (!range || !client())
return { };
return TextCheckingHelper(*client(), *range).guessesForMisspelledWordOrUngrammaticalPhrase(isGrammarCheckingEnabled());
}
auto misspelledWord = behavior().shouldAllowSpellingSuggestionsWithoutSelection() ? misspelledWordAtCaretOrRange(document().focusedElement()) : misspelledSelectionString();
if (misspelledWord.isEmpty())
return { };
return { guessesForMisspelledWord(misspelledWord), true, false };
}
void Editor::showSpellingGuessPanel()
{
if (!client()) {
LOG_ERROR("No NSSpellChecker");
return;
}
if (client()->spellingUIIsShowing()) {
client()->showSpellingUI(false);
return;
}
#if !PLATFORM(IOS_FAMILY)
advanceToNextMisspelling(true);
#endif
client()->showSpellingUI(true);
}
bool Editor::spellingPanelIsShowing()
{
if (!client())
return false;
return client()->spellingUIIsShowing();
}
void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection& movingSelection)
{
if (auto selectedRange = movingSelection.toNormalizedRange())
removeMarkers(*selectedRange, { DocumentMarker::Spelling, DocumentMarker::Grammar });
}
void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
{
markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
}
void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
{
Ref<Document> protectedDocument(m_document);
if (platformDrivenTextCheckerEnabled())
return;
#if PLATFORM(IOS_FAMILY)
UNUSED_PARAM(selectionAfterTyping);
UNUSED_PARAM(doReplacement);
OptionSet<TextCheckingType> textCheckingOptions;
if (isContinuousSpellCheckingEnabled())
textCheckingOptions.add(TextCheckingType::Spelling);
if (!textCheckingOptions.contains(TextCheckingType::Spelling))
return;
auto adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
auto adjacentWordRange = adjacentWords.toNormalizedRange();
markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWordRange, adjacentWordRange, adjacentWordRange);
#else
#if !USE(AUTOMATIC_TEXT_REPLACEMENT)
UNUSED_PARAM(doReplacement);
#endif
if (unifiedTextCheckerEnabled()) {
m_alternativeTextController->applyPendingCorrection(selectionAfterTyping);
OptionSet<TextCheckingType> textCheckingOptions;
if (isContinuousSpellCheckingEnabled())
textCheckingOptions.add(TextCheckingType::Spelling);
#if USE(AUTOMATIC_TEXT_REPLACEMENT)
if (doReplacement
&& (isAutomaticQuoteSubstitutionEnabled()
|| isAutomaticLinkDetectionEnabled()
|| isAutomaticDashSubstitutionEnabled()
|| isAutomaticTextReplacementEnabled()
|| (textCheckingOptions.contains(TextCheckingType::Spelling) && isAutomaticSpellingCorrectionEnabled())))
textCheckingOptions.add(TextCheckingType::Replacement);
#endif
if (!textCheckingOptions.contains(TextCheckingType::Spelling) && !textCheckingOptions.contains(TextCheckingType::Replacement))
return;
if (isGrammarCheckingEnabled())
textCheckingOptions.add(TextCheckingType::Grammar);
auto sentenceStart = startOfSentence(wordStart);
auto sentenceEnd = endOfSentence(wordStart);
VisibleSelection fullSentence(sentenceStart, sentenceEnd);
auto fullSentenceRange = fullSentence.toNormalizedRange();
if (!fullSentenceRange)
return;
auto spellCheckingStart = wordStart;
auto spellCheckingEnd = wordStart;
while (sentenceStart < spellCheckingStart) {
auto previousPosition = spellCheckingStart.previous(CannotCrossEditingBoundary);
if (previousPosition.isNull() || previousPosition == spellCheckingStart)
break;
auto* container = previousPosition.deepEquivalent().downstream().containerNode();
if (auto* containerElement = is<Element>(container) ? downcast<Element>(container) : container->parentElement()) {
if (!containerElement->isSpellCheckingEnabled())
break;
}
spellCheckingStart = previousPosition;
}
while (spellCheckingEnd < sentenceEnd) {
auto nextPosition = spellCheckingEnd.next(CannotCrossEditingBoundary);
if (nextPosition.isNull() || nextPosition == spellCheckingEnd)
break;
auto* container = nextPosition.deepEquivalent().upstream().containerNode();
if (auto* containerElement = is<Element>(container) ? downcast<Element>(container) : container->parentElement()) {
if (!containerElement->isSpellCheckingEnabled())
break;
}
spellCheckingEnd = nextPosition;
}
auto spellCheckingRange = VisibleSelection(spellCheckingStart, spellCheckingEnd).toNormalizedRange();
if (!spellCheckingRange)
return;
auto adjacentWordRange = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)).toNormalizedRange();
if (!adjacentWordRange)
return;
removeMarkers(*fullSentenceRange, DocumentMarker::Grammar);
removeMarkers(*spellCheckingRange, DocumentMarker::Spelling);
markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellCheckingRange, adjacentWordRange, fullSentenceRange);
return;
}
if (!isContinuousSpellCheckingEnabled())
return;
auto misspellingRange = markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)));
if (!misspellingRange)
return;
String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(plainText(*misspellingRange));
if (!autocorrectedString.isEmpty()) {
VisibleSelection newSelection(*misspellingRange, DOWNSTREAM);
if (newSelection != m_document.selection().selection()) {
if (!m_document.selection().shouldChangeSelection(newSelection))
return;
m_document.selection().setSelection(newSelection);
}
if (!m_document.editor().shouldInsertText(autocorrectedString, misspellingRange, EditorInsertAction::Typed))
return;
m_document.editor().replaceSelectionWithText(autocorrectedString, SelectReplacement::No, SmartReplace::No, EditAction::Insert);
m_document.selection().moveTo(m_document.selection().selection().end());
m_document.selection().modify(FrameSelection::AlterationMove, SelectionDirection::Forward, TextGranularity::CharacterGranularity);
}
if (!isGrammarCheckingEnabled())
return;
markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
#endif
}
Optional<SimpleRange> Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling)
{
#if !PLATFORM(IOS_FAMILY)
if (!isContinuousSpellCheckingEnabled())
return WTF::nullopt;
auto searchRange = selection.toNormalizedRange();
if (!searchRange)
return WTF::nullopt;
Node& editableNode = searchRange->startContainer();
if (!editableNode.hasEditableStyle())
return WTF::nullopt;
if (!isSpellCheckingEnabledFor(&editableNode))
return WTF::nullopt;
if (!client())
return WTF::nullopt;
TextCheckingHelper checker(*client(), *searchRange);
if (checkSpelling)
return checker.markAllMisspelledWords();
if (isGrammarCheckingEnabled())
checker.markAllUngrammaticalPhrases();
return WTF::nullopt;
#else
UNUSED_PARAM(selection);
UNUSED_PARAM(checkSpelling);
return WTF::nullopt;
#endif
}
bool Editor::isSpellCheckingEnabledFor(Node* node) const
{
if (!node)
return false;
Element* element = is<Element>(*node) ? downcast<Element>(node) : node->parentElement();
if (!element)
return false;
if (element->isInUserAgentShadowTree()) {
if (HTMLTextFormControlElement* textControl = enclosingTextFormControl(firstPositionInOrBeforeNode(element)))
return textControl->isSpellCheckingEnabled();
}
return element->isSpellCheckingEnabled();
}
bool Editor::isSpellCheckingEnabledInFocusedNode() const
{
return isSpellCheckingEnabledFor(m_document.selection().selection().start().deprecatedNode());
}
Optional<SimpleRange> Editor::markMisspellings(const VisibleSelection& selection)
{
return markMisspellingsOrBadGrammar(selection, true);
}
void Editor::markBadGrammar(const VisibleSelection& selection)
{
markMisspellingsOrBadGrammar(selection, false);
}
void Editor::markAllMisspellingsAndBadGrammarInRanges(OptionSet<TextCheckingType> textCheckingOptions, const Optional<SimpleRange>& spellingRange, const Optional<SimpleRange>& automaticReplacementRange, const Optional<SimpleRange>& grammarRange)
{
if (platformDrivenTextCheckerEnabled())
return;
ASSERT(unifiedTextCheckerEnabled());
ASSERT(!m_alternativeTextController->hasPendingCorrection());
bool shouldMarkGrammar = textCheckingOptions.contains(TextCheckingType::Grammar);
bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
return;
Node& editableNode = spellingRange->startContainer();
if (!editableNode.hasEditableStyle())
return;
if (!isSpellCheckingEnabledFor(&editableNode))
return;
auto& rangeToCheck = shouldMarkGrammar ? *grammarRange : *spellingRange;
TextCheckingParagraph paragraphToCheck(rangeToCheck);
if (paragraphToCheck.isEmpty())
return;
bool asynchronous = m_document.settings().asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
auto resolvedOptions = resolveTextCheckingTypeMask(editableNode, textCheckingOptions);
auto& paragraphRange = paragraphToCheck.paragraphRange();
auto& checkingRange = asynchronous ? paragraphRange : rangeToCheck;
auto& textReplacementRange = automaticReplacementRange ? *automaticReplacementRange : rangeToCheck;
auto request = SpellCheckRequest::create(resolvedOptions, TextCheckingProcessIncremental, checkingRange, textReplacementRange, paragraphRange);
if (!request)
return;
if (asynchronous) {
m_spellChecker->requestCheckingFor(request.releaseNonNull());
return;
}
Vector<TextCheckingResult> results;
checkTextOfParagraph(*textChecker(), paragraphToCheck.text(), resolvedOptions, results, m_document.selection().selection());
markAndReplaceFor(request.releaseNonNull(), results);
}
static bool isAutomaticTextReplacementType(TextCheckingType type)
{
switch (type) {
case TextCheckingType::None:
case TextCheckingType::Spelling:
case TextCheckingType::Grammar:
return false;
case TextCheckingType::Link:
case TextCheckingType::Quote:
case TextCheckingType::Dash:
case TextCheckingType::Replacement:
case TextCheckingType::Correction:
case TextCheckingType::ShowCorrectionPanel:
return true;
}
ASSERT_NOT_REACHED();
return false;
}
void Editor::replaceRangeForSpellChecking(const SimpleRange& rangeToReplace, const String& replacement)
{
SpellingCorrectionCommand::create(rangeToReplace, replacement)->apply();
}
static void correctSpellcheckingPreservingTextCheckingParagraph(TextCheckingParagraph& paragraph, const SimpleRange& rangeToReplace, const String& replacement, CharacterRange resultCharacterRange)
{
auto scopeNode = makeRef(downcast<ContainerNode>(paragraph.paragraphRange().startContainer().rootNode()));
auto paragraphCharacterRange = characterRange(makeBoundaryPointBeforeNodeContents(scopeNode), paragraph.paragraphRange());
SpellingCorrectionCommand::create(rangeToReplace, replacement)->apply();
paragraphCharacterRange.length += replacement.length() - resultCharacterRange.length;
auto newParagraphRange = resolveCharacterRange(makeRangeSelectingNodeContents(scopeNode), paragraphCharacterRange);
auto spellCheckingRange = resolveCharacterRange(newParagraphRange, { resultCharacterRange.location, replacement.length() });
paragraph = TextCheckingParagraph(spellCheckingRange, spellCheckingRange, newParagraphRange);
}
void Editor::markAndReplaceFor(const SpellCheckRequest& request, const Vector<TextCheckingResult>& results)
{
Ref<Document> protectedDocument(m_document);
auto textCheckingOptions = request.data().checkingTypes();
TextCheckingParagraph paragraph(request.checkingRange(), request.automaticReplacementRange(), request.paragraphRange());
bool shouldPerformReplacement = textCheckingOptions.containsAny({ TextCheckingType::Quote, TextCheckingType::Dash, TextCheckingType::Replacement });
bool shouldMarkSpelling = textCheckingOptions.contains(TextCheckingType::Spelling);
bool shouldMarkGrammar = textCheckingOptions.contains(TextCheckingType::Grammar);
bool shouldMarkLink = textCheckingOptions.contains(TextCheckingType::Link);
bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
bool shouldCheckForCorrection = shouldShowCorrectionPanel || textCheckingOptions.contains(TextCheckingType::Correction);
#if !USE(AUTOCORRECTION_PANEL)
ASSERT(!shouldShowCorrectionPanel);
#endif
uint64_t selectionOffset = 0;
bool useAmbiguousBoundaryOffset = false;
bool selectionChanged = false;
bool restoreSelectionAfterChange = false;
if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
if (m_document.selection().selection().selectionType() == VisibleSelection::CaretSelection) {
Position caretPosition = m_document.selection().selection().end();
selectionOffset = paragraph.offsetTo(caretPosition).releaseReturnValue();
restoreSelectionAfterChange = true;
if (selectionOffset > 0 && selectionOffset <= paragraph.text().length() && isAmbiguousBoundaryCharacter(paragraph.text()[selectionOffset - 1]))
useAmbiguousBoundaryOffset = true;
}
}
int offsetDueToReplacement = 0;
for (unsigned i = 0; i < results.size(); i++) {
auto spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
TextCheckingType resultType = results[i].type;
auto resultLocation = results[i].range.location + offsetDueToReplacement;
auto resultLength = results[i].range.length;
auto resultEndLocation = resultLocation + resultLength;
auto automaticReplacementStartLocation = paragraph.automaticReplacementStart(true);
auto automaticReplacementEndLocation = automaticReplacementStartLocation + paragraph.automaticReplacementLength(true) + offsetDueToReplacement;
const String& replacement = results[i].replacement;
bool resultEndsAtAmbiguousBoundary = useAmbiguousBoundaryOffset && selectionOffset - 1 <= resultEndLocation;
if (shouldMarkSpelling && !shouldShowCorrectionPanel && resultType == TextCheckingType::Spelling
&& resultLocation >= paragraph.checkingStart() && resultEndLocation <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
ASSERT(resultLength > 0);
auto misspellingRange = paragraph.subrange({ resultLocation, resultLength });
if (!m_alternativeTextController->isSpellingMarkerAllowed(misspellingRange))
continue;
addMarker(misspellingRange, DocumentMarker::Spelling, replacement);
} else if (shouldMarkGrammar && resultType == TextCheckingType::Grammar && paragraph.checkingRangeCovers({ resultLocation, resultLength })) {
ASSERT(resultLength > 0);
for (auto& detail : results[i].details) {
ASSERT(detail.range.length > 0);
if (paragraph.checkingRangeCovers({ resultLocation + detail.range.location, detail.range.length })) {
auto badGrammarRange = paragraph.subrange({ resultLocation + detail.range.location, detail.range.length });
addMarker(badGrammarRange, DocumentMarker::Grammar, detail.userDescription);
}
}
} else if (automaticReplacementStartLocation <= resultEndLocation && resultEndLocation <= automaticReplacementEndLocation
&& isAutomaticTextReplacementType(resultType)) {
ASSERT(resultLength > 0);
if (shouldShowCorrectionPanel && (resultEndLocation < automaticReplacementEndLocation
|| (resultType != TextCheckingType::Replacement && resultType != TextCheckingType::Correction)))
continue;
bool doReplacement = replacement.length() > 0 && !resultEndsAtAmbiguousBoundary;
auto rangeToReplace = paragraph.subrange({ resultLocation, resultLength });
if (resultType == TextCheckingType::Link && selectionOffset != resultEndLocation + 1)
continue;
if (!(shouldPerformReplacement || shouldCheckForCorrection || shouldMarkLink) || !doReplacement)
continue;
String replacedString = plainText(rangeToReplace);
bool existingMarkersPermitReplacement = m_alternativeTextController->processMarkersOnTextToBeReplacedByResult(results[i], rangeToReplace, replacedString);
if (!existingMarkersPermitReplacement)
continue;
if (shouldShowCorrectionPanel) {
if (resultEndLocation == automaticReplacementEndLocation) {
m_alternativeTextController->show(rangeToReplace, replacement);
break;
}
continue;
}
VisibleSelection selectionToReplace(rangeToReplace, DOWNSTREAM);
if (selectionToReplace != m_document.selection().selection()) {
if (!m_document.selection().shouldChangeSelection(selectionToReplace))
continue;
}
if (resultType == TextCheckingType::Link) {
m_document.selection().setSelection(selectionToReplace);
selectionChanged = true;
restoreSelectionAfterChange = false;
if (canEditRichly())
CreateLinkCommand::create(document(), replacement)->apply();
} else if (canEdit() && shouldInsertText(replacement, rangeToReplace, EditorInsertAction::Typed)) {
correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, { resultLocation, resultLength });
if (AXObjectCache* cache = document().existingAXObjectCache()) {
if (Element* root = m_document.selection().selection().rootEditableElement())
cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured);
}
while (i + 1 < results.size() && results[i + 1].range.location + offsetDueToReplacement <= resultLocation)
i++;
selectionChanged = true;
offsetDueToReplacement += replacement.length() - resultLength;
if (resultLocation < selectionOffset)
selectionOffset += replacement.length() - resultLength;
if (resultType == TextCheckingType::Correction) {
auto replacementRange = paragraph.subrange({ resultLocation, replacement.length() });
m_alternativeTextController->recordAutocorrectionResponse(AutocorrectionResponse::Accepted, replacedString, replacementRange);
m_alternativeTextController->markCorrection(replacementRange, replacedString);
}
}
}
}
if (selectionChanged) {
TextCheckingParagraph extendedParagraph(WTFMove(paragraph));
extendedParagraph.expandRangeToNextEnd();
if (restoreSelectionAfterChange && selectionOffset <= extendedParagraph.rangeLength()) {
auto selectionRange = extendedParagraph.subrange({ 0, selectionOffset });
m_document.selection().moveTo(createLegacyEditingPosition(selectionRange.end), DOWNSTREAM);
} else {
m_document.selection().moveTo(m_document.selection().selection().end());
m_document.selection().modify(FrameSelection::AlterationMove, SelectionDirection::Forward, TextGranularity::CharacterGranularity);
}
}
}
void Editor::changeBackToReplacedString(const String& replacedString)
{
#if !PLATFORM(IOS_FAMILY)
ASSERT(unifiedTextCheckerEnabled());
if (replacedString.isEmpty())
return;
auto selection = selectedRange();
if (!selection || !shouldInsertText(replacedString, selection, EditorInsertAction::Pasted))
return;
m_alternativeTextController->recordAutocorrectionResponse(AutocorrectionResponse::Reverted, replacedString, *selection);
TextCheckingParagraph paragraph(*selection);
replaceSelectionWithText(replacedString, SelectReplacement::No, SmartReplace::No, EditAction::Insert);
auto changedRange = paragraph.subrange(CharacterRange(paragraph.checkingStart(), replacedString.length()));
addMarker(changedRange, DocumentMarker::Replacement, String());
m_alternativeTextController->markReversed(changedRange);
#else
ASSERT_NOT_REACHED();
UNUSED_PARAM(replacedString);
#endif // !PLATFORM(IOS_FAMILY)
}
void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
{
if (platformDrivenTextCheckerEnabled())
return;
if (unifiedTextCheckerEnabled()) {
if (!isContinuousSpellCheckingEnabled())
return;
OptionSet<TextCheckingType> textCheckingOptions { TextCheckingType::Spelling };
if (markGrammar && isGrammarCheckingEnabled())
textCheckingOptions.add(TextCheckingType::Grammar);
auto spellCheckingRange = spellingSelection.toNormalizedRange();
markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellCheckingRange, spellCheckingRange, grammarSelection.toNormalizedRange());
return;
}
markMisspellings(spellingSelection);
if (markGrammar)
markBadGrammar(grammarSelection);
}
void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
{
m_alternativeTextController->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
}
void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
{
if (!document().markers().hasMarkers())
return;
if (!m_alternativeTextController->shouldRemoveMarkersUponEditing() && (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Spelling)))
return;
VisiblePosition startOfSelection = m_document.selection().selection().start();
VisiblePosition endOfSelection = m_document.selection().selection().end();
if (startOfSelection.isNull())
return;
VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
if (startOfFirstWord.isNull()) {
startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
}
if (endOfLastWord.isNull()) {
startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
}
auto originalEndOfFirstWord = endOfFirstWord;
auto originalStartOfLastWord = startOfLastWord;
if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
startOfFirstWord = nextWordPosition(startOfFirstWord);
endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
if (startOfFirstWord == originalStartOfLastWord)
return;
}
if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
startOfLastWord = previousWordPosition(startOfLastWord);
endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
if (endOfLastWord == originalEndOfFirstWord)
return;
}
if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
return;
auto wordRange = *makeSimpleRange(startOfFirstWord, endOfLastWord);
for (auto* marker : document().markers().markersInRange(wordRange, DocumentMarker::DictationAlternatives))
m_alternativeTextController->removeDictationAlternativesForMarker(*marker);
OptionSet<DocumentMarker::MarkerType> markerTypesToRemove {
DocumentMarker::CorrectionIndicator,
DocumentMarker::DictationAlternatives,
DocumentMarker::SpellCheckingExemption,
DocumentMarker::Spelling,
#if !PLATFORM(IOS_FAMILY)
DocumentMarker::Grammar,
#endif
};
removeMarkers(wordRange, markerTypesToRemove, RemovePartiallyOverlappingMarker::Yes);
document().markers().clearDescriptionOnMarkersIntersectingRange(wordRange, DocumentMarker::Replacement);
}
void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
{
m_alternativeTextController->deletedAutocorrectionAtPosition(position, originalString);
}
Optional<SimpleRange> Editor::rangeForPoint(const IntPoint& windowPoint)
{
auto document = m_document.frame()->documentAtPoint(windowPoint);
if (!document)
return WTF::nullopt;
auto frame = document->frame();
if (!frame)
return WTF::nullopt;
auto frameView = frame->view();
if (!frameView)
return WTF::nullopt;
return VisibleSelection { frame->visiblePositionForPoint(frameView->windowToContents(windowPoint)) }.toNormalizedRange();
}
void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
{
if (m_ignoreSelectionChanges)
return;
SelectionRevealMode revealMode = SelectionRevealMode::Reveal;
m_document.selection().revealSelection(revealMode, alignment, revealExtentOption);
}
void Editor::setIgnoreSelectionChanges(bool ignore, RevealSelection shouldRevealExistingSelection)
{
if (m_ignoreSelectionChanges == ignore)
return;
m_ignoreSelectionChanges = ignore;
#if PLATFORM(IOS_FAMILY)
if (!ignore)
respondToChangedSelection(m_document.selection().selection(), { });
#endif
if (!ignore && shouldRevealExistingSelection == RevealSelection::Yes)
revealSelectionAfterEditingOperation(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
}
Optional<SimpleRange> Editor::compositionRange() const
{
if (!m_compositionNode)
return WTF::nullopt;
unsigned length = m_compositionNode->length();
unsigned start = std::min(m_compositionStart, length);
unsigned end = std::clamp(m_compositionEnd, start, length);
if (start >= end)
return WTF::nullopt;
return { { { *m_compositionNode, start }, { *m_compositionNode, end } } };
}
bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
{
if (!m_compositionNode)
return false;
const VisibleSelection& selection = m_document.selection().selection();
Position start = selection.start();
if (start.deprecatedNode() != m_compositionNode)
return false;
Position end = selection.end();
if (end.deprecatedNode() != m_compositionNode)
return false;
if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
return false;
if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
return false;
selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
return true;
}
void Editor::transpose()
{
if (!canEdit())
return;
VisibleSelection selection = m_document.selection().selection();
if (!selection.isCaret())
return;
VisiblePosition caret = selection.visibleStart();
VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
VisiblePosition previous = next.previous();
if (next == previous)
return;
previous = previous.previous();
if (!inSameParagraph(next, previous))
return;
auto range = makeSimpleRange(previous, next);
if (!range)
return;
VisibleSelection newSelection(*range, DOWNSTREAM);
String text = plainText(*range);
if (text.length() != 2)
return;
String transposed = text.right(1) + text.left(1);
if (newSelection != m_document.selection().selection()) {
if (!m_document.selection().shouldChangeSelection(newSelection))
return;
m_document.selection().setSelection(newSelection);
}
if (!shouldInsertText(transposed, newSelection.firstRange(), EditorInsertAction::Typed))
return;
replaceSelectionWithText(transposed, SelectReplacement::No, SmartReplace::No, EditAction::Insert);
}
void Editor::addRangeToKillRing(const SimpleRange& range, KillRingInsertionMode mode)
{
addTextToKillRing(plainText(range), mode);
}
void Editor::addTextToKillRing(const String& text, KillRingInsertionMode mode)
{
if (m_shouldStartNewKillRingSequence)
killRing().startNewSequence();
m_shouldStartNewKillRingSequence = false;
switch (mode) {
case KillRingInsertionMode::PrependText:
killRing().prepend(text);
break;
case KillRingInsertionMode::AppendText:
killRing().append(text);
break;
}
}
void Editor::startAlternativeTextUITimer()
{
m_alternativeTextController->startAlternativeTextUITimer(AlternativeTextTypeCorrection);
}
void Editor::handleAlternativeTextUIResult(const String& correction)
{
m_alternativeTextController->handleAlternativeTextUIResult(correction);
}
void Editor::dismissCorrectionPanelAsIgnored()
{
m_alternativeTextController->dismiss(ReasonForDismissingAlternativeTextIgnored);
}
void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, OptionSet<FrameSelection::SetSelectionOption> options)
{
Ref<Document> protectedDocument(m_document);
if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
return;
bool selectionDidNotChangeDOMPosition = newSelection == m_document.selection().selection();
if (selectionDidNotChangeDOMPosition || m_document.selection().shouldChangeSelection(newSelection))
m_document.selection().setSelection(newSelection, options);
#if PLATFORM(IOS_FAMILY)
if (m_ignoreSelectionChanges)
return;
#endif
if (selectionDidNotChangeDOMPosition && client())
client()->respondToChangedSelection(m_document.frame());
}
String Editor::selectedText() const
{
TextIteratorBehavior behavior = TextIteratorDefaultBehavior;
if (m_document.settings().selectionAcrossShadowBoundariesEnabled())
behavior |= TextIteratorTraversesFlatTree;
return selectedText(behavior);
}
String Editor::selectedTextForDataTransfer() const
{
TextIteratorBehavior behavior = TextIteratorEmitsImageAltText;
if (m_document.settings().selectionAcrossShadowBoundariesEnabled())
behavior |= TextIteratorTraversesFlatTree;
return selectedText(behavior);
}
String Editor::selectedText(TextIteratorBehavior behavior) const
{
auto range = m_document.selection().selection().firstRange();
return range ? plainText(*range, behavior).replaceWithLiteral('\0', "") : emptyString();
}
RefPtr<TextPlaceholderElement> Editor::insertTextPlaceholder(const IntSize& size)
{
if (m_document.selection().isNone() || !m_document.selection().selection().isContentEditable())
return nullptr;
Ref<Document> document { this->document() };
deleteSelectionWithSmartDelete(false);
auto range = m_document.selection().selection().toNormalizedRange();
if (!range)
return nullptr;
auto placeholder = TextPlaceholderElement::create(document, size);
createLiveRange(*range)->insertNode(placeholder.copyRef());
if (!placeholder->parentNode())
return nullptr;
m_document.selection().setSelection(VisibleSelection { positionInParentBeforeNode(placeholder.ptr()), SEL_DEFAULT_AFFINITY }, FrameSelection::defaultSetSelectionOptions(UserTriggered));
return placeholder;
}
void Editor::removeTextPlaceholder(TextPlaceholderElement& placeholder)
{
ASSERT(placeholder.isConnected());
Ref<Document> document { this->document() };
auto savedRootEditableElement = makeRefPtr(placeholder.rootEditableElement());
auto savedPositionBeforePlaceholder = positionBeforeNode(&placeholder).parentAnchoredEquivalent();
placeholder.remove();
if (m_document.selection().isFocusedAndActive() && document->focusedElement() == savedRootEditableElement)
m_document.selection().setSelection(VisibleSelection { savedPositionBeforePlaceholder, SEL_DEFAULT_AFFINITY }, FrameSelection::defaultSetSelectionOptions(UserTriggered));
}
static inline void collapseCaretWidth(IntRect& rect)
{
if (rect.width() == caretWidth)
rect.setWidth(0);
else if (rect.height() == caretWidth)
rect.setHeight(0);
}
IntRect Editor::firstRectForRange(const SimpleRange& range) const
{
range.start.document().updateLayout();
VisiblePosition startVisiblePosition(createLegacyEditingPosition(range.start), DOWNSTREAM);
if (range.collapsed()) {
IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect();
collapseCaretWidth(startCaretRect);
return startCaretRect;
}
VisiblePosition endVisiblePosition(createLegacyEditingPosition(range.end), UPSTREAM);
if (inSameLine(startVisiblePosition, endVisiblePosition))
return enclosingIntRect(unitedBoundingBoxes(RenderObject::absoluteTextQuads(range)));
LayoutUnit extraWidthToEndOfLine;
IntRect startCaretRect = RenderedPosition(startVisiblePosition).absoluteRect(&extraWidthToEndOfLine);
if (startCaretRect == IntRect())
return IntRect();
bool textIsHorizontal = startCaretRect.width() == caretWidth;
return textIsHorizontal ?
IntRect(startCaretRect.x(),
startCaretRect.y(),
startCaretRect.width() + extraWidthToEndOfLine,
startCaretRect.height()) :
IntRect(startCaretRect.x(),
startCaretRect.y(),
startCaretRect.width(),
startCaretRect.height() + extraWidthToEndOfLine);
}
bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
{
#if PLATFORM(IOS_FAMILY)
if (m_document.frame() && m_document.frame()->selectionChangeCallbacksDisabled())
return true;
#endif
return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange(), newSelection.toNormalizedRange(), affinity, stillSelecting);
}
void Editor::computeAndSetTypingStyle(EditingStyle& style, EditAction editingAction)
{
if (style.isEmpty()) {
m_document.selection().clearTypingStyle();
return;
}
RefPtr<EditingStyle> typingStyle;
if (auto existingTypingStyle = m_document.selection().typingStyle())
typingStyle = existingTypingStyle->copy();
else
typingStyle = EditingStyle::create();
typingStyle->overrideTypingStyleAt(style, m_document.selection().selection().visibleStart().deepEquivalent());
RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
if (!blockStyle->isEmpty())
ApplyStyleCommand::create(document(), blockStyle.get(), editingAction)->apply();
m_document.selection().setTypingStyle(WTFMove(typingStyle));
}
void Editor::computeAndSetTypingStyle(StyleProperties& properties, EditAction editingAction)
{
return computeAndSetTypingStyle(EditingStyle::create(&properties), editingAction);
}
void Editor::textFieldDidBeginEditing(Element* e)
{
if (client())
client()->textFieldDidBeginEditing(e);
}
void Editor::textFieldDidEndEditing(Element* e)
{
dismissCorrectionPanelAsIgnored();
if (client())
client()->textFieldDidEndEditing(e);
}
void Editor::textDidChangeInTextField(Element* e)
{
if (client())
client()->textDidChangeInTextField(e);
}
bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
{
if (client())
return client()->doTextFieldCommandFromEvent(e, ke);
return false;
}
void Editor::textWillBeDeletedInTextField(Element* input)
{
if (client())
client()->textWillBeDeletedInTextField(input);
}
void Editor::textDidChangeInTextArea(Element* e)
{
if (client())
client()->textDidChangeInTextArea(e);
}
void Editor::applyEditingStyleToBodyElement() const
{
auto body = makeRefPtr(document().body());
if (!body)
return;
body->setInlineStyleProperty(CSSPropertyWordWrap, CSSValueBreakWord);
body->setInlineStyleProperty(CSSPropertyWebkitNbspMode, CSSValueSpace);
body->setInlineStyleProperty(CSSPropertyLineBreak, CSSValueAfterWhiteSpace);
}
bool Editor::findString(const String& target, FindOptions options)
{
Ref<Document> protectedDocument(m_document);
VisibleSelection selection = m_document.selection().selection();
auto resultRange = rangeOfString(target, selection.firstRange(), options);
if (!resultRange)
return false;
m_document.selection().setSelection(VisibleSelection(*resultRange, DOWNSTREAM));
if (!(options.contains(DoNotRevealSelection)))
m_document.selection().revealSelection();
return true;
}
template<typename T> static auto& start(T& range, FindOptions options)
{
return options.contains(Backwards) ? range.end : range.start;
}
template<typename T> static auto& end(T& range, FindOptions options)
{
return options.contains(Backwards) ? range.start : range.end;
}
static BoundaryPoint makeBoundaryPointAfterNodeContents(Node& node, FindOptions options)
{
return options.contains(Backwards) ? makeBoundaryPointBeforeNodeContents(node) : makeBoundaryPointAfterNodeContents(node);
}
static Optional<BoundaryPoint> makeBoundaryPointAfterNode(Node& node, FindOptions options)
{
return options.contains(Backwards) ? makeBoundaryPointBeforeNode(node) : makeBoundaryPointAfterNode(node);
}
static SimpleRange collapseIfRootsDiffer(SimpleRange&& range)
{
return &range.start.container->rootNode() == &range.end.container->rootNode()
? WTFMove(range) : SimpleRange { range.start, range.start };
}
Optional<SimpleRange> Editor::rangeOfString(const String& target, const Optional<SimpleRange>& referenceRange, FindOptions options)
{
if (target.isEmpty())
return WTF::nullopt;
bool startInReferenceRange = referenceRange && options.contains(StartInSelection);
auto shadowTreeRoot = referenceRange ? referenceRange->startContainer().containingShadowRoot() : nullptr;
auto searchRange = makeRangeSelectingNodeContents(document());
if (referenceRange)
start(searchRange, options) = startInReferenceRange ? start(*referenceRange, options) : end(*referenceRange, options);
if (shadowTreeRoot)
end(searchRange, options) = makeBoundaryPointAfterNodeContents(*shadowTreeRoot, options);
auto resultRange = collapseIfRootsDiffer(findPlainText(searchRange, target, options));
if (startInReferenceRange && VisibleSelection(resultRange).toNormalizedRange() == referenceRange) {
searchRange = makeRangeSelectingNodeContents(document());
start(searchRange, options) = end(*referenceRange, options);
if (shadowTreeRoot)
end(searchRange, options) = makeBoundaryPointAfterNodeContents(*shadowTreeRoot, options);
resultRange = collapseIfRootsDiffer(findPlainText(searchRange, target, options));
}
if (resultRange.collapsed() && shadowTreeRoot) {
searchRange = makeRangeSelectingNodeContents(document());
if (auto host = shadowTreeRoot->shadowHost())
start(searchRange, options) = *makeBoundaryPointAfterNode(*host, options);
resultRange = collapseIfRootsDiffer(findPlainText(searchRange, target, options));
}
if (resultRange.collapsed() && options.contains(WrapAround)) {
resultRange = collapseIfRootsDiffer(findPlainText(makeRangeSelectingNodeContents(document()), target, options));
}
return resultRange.collapsed() ? WTF::nullopt : makeOptional(resultRange);
}
static bool isFrameInRange(Frame& frame, const SimpleRange& range)
{
for (auto* ownerElement = frame.ownerElement(); ownerElement; ownerElement = ownerElement->document().ownerElement()) {
if (&ownerElement->document() == &range.start.document()) {
auto result = createLiveRange(range)->intersectsNode(*ownerElement);
return !result.hasException() && result.releaseReturnValue();
}
}
return false;
}
unsigned Editor::countMatchesForText(const String& target, const Optional<SimpleRange>& range, FindOptions options, unsigned limit, bool markMatches, Vector<SimpleRange>* matches)
{
if (target.isEmpty())
return 0;
Optional<SimpleRange> searchRange;
if (range) {
if (&range->start.document() == &document())
searchRange = *range;
else if (!isFrameInRange(*m_document.frame(), *range))
return 0;
}
if (!searchRange)
searchRange = makeRangeSelectingNodeContents(document());
auto originalEnd = searchRange->end;
unsigned matchCount = 0;
do {
auto resultRange = findPlainText(*searchRange, target, options - Backwards);
if (resultRange.collapsed()) {
if (!resultRange.start.container->isInShadowTree())
break;
searchRange->start = makeBoundaryPointAfterNodeContents(*resultRange.start.container->shadowHost());
searchRange->end = originalEnd;
continue;
}
++matchCount;
if (matches)
matches->append(resultRange);
if (markMatches)
addMarker(resultRange, DocumentMarker::TextMatch);
if (limit > 0 && matchCount >= limit)
break;
searchRange->start = WTFMove(resultRange.end);
if (searchRange->collapsed()) {
if (auto shadowTreeRoot = searchRange->start.container->containingShadowRoot())
searchRange->end = makeBoundaryPointAfterNodeContents(*shadowTreeRoot);
}
} while (true);
return matchCount;
}
void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
{
if (flag == m_areMarkedTextMatchesHighlighted)
return;
m_areMarkedTextMatchesHighlighted = flag;
document().markers().repaintMarkers(DocumentMarker::TextMatch);
}
#if !PLATFORM(MAC)
void Editor::selectionWillChange()
{
}
#endif
void Editor::respondToChangedSelection(const VisibleSelection&, OptionSet<FrameSelection::SetSelectionOption> options)
{
#if PLATFORM(IOS_FAMILY)
if (m_ignoreSelectionChanges)
return;
#endif
if (client())
client()->respondToChangedSelection(m_document.frame());
#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS_FAMILY)
if (shouldDetectTelephoneNumbers())
m_telephoneNumberDetectionUpdateTimer.startOneShot(0_s);
#endif
setStartNewKillRingSequence(true);
m_imageElementsToLoadBeforeRevealingSelection.clear();
if (m_editorUIUpdateTimer.isActive())
return;
m_editorUIUpdateTimerShouldCheckSpellingAndGrammar = options.contains(FrameSelection::CloseTyping) && !options.contains(FrameSelection::SpellCorrectionTriggered);
m_editorUIUpdateTimerWasTriggeredByDictation = options.contains(FrameSelection::DictationTriggered);
scheduleEditorUIUpdate();
}
#if ENABLE(TELEPHONE_NUMBER_DETECTION) && PLATFORM(MAC)
bool Editor::shouldDetectTelephoneNumbers() const
{
return m_document.isTelephoneNumberParsingEnabled() && TelephoneNumberDetector::isSupported();
}
static Vector<SimpleRange> scanForTelephoneNumbers(const SimpleRange& range)
{
auto& startNode = range.startContainer();
if (startNode.hasEditableStyle())
return { };
auto text = plainText(range);
Vector<SimpleRange> result;
unsigned length = text.length();
unsigned scannerPosition = 0;
int relativeStartPosition = 0;
int relativeEndPosition = 0;
auto characters = StringView { text }.upconvertedCharacters();
while (scannerPosition < length && TelephoneNumberDetector::find(&characters[scannerPosition], length - scannerPosition, &relativeStartPosition, &relativeEndPosition)) {
ASSERT(scannerPosition + relativeEndPosition <= length);
result.append(resolveCharacterRange(range, CharacterRange(scannerPosition + relativeStartPosition, relativeEndPosition - relativeStartPosition)));
scannerPosition += relativeEndPosition;
}
return result;
}
static SimpleRange extendSelection(const SimpleRange& range, unsigned charactersToExtend)
{
auto start = createLegacyEditingPosition(range.start);
auto end = createLegacyEditingPosition(range.end);
for (unsigned i = 0; i < charactersToExtend; ++i) {
start = start.previous(Character);
end = end.next(Character);
}
return *makeSimpleRange(start, end);
}
void Editor::scanSelectionForTelephoneNumbers()
{
if (!shouldDetectTelephoneNumbers() || !client())
return;
m_detectedTelephoneNumberRanges.clear();
auto& selection = m_document.selection();
if (selection.isRange()) {
if (auto selectedRange = selection.selection().firstRange()) {
constexpr unsigned charactersToExtend = 15;
auto selectedLiveRange = createLiveRange(*selectedRange);
for (auto& range : scanForTelephoneNumbers(extendSelection(*selectedRange, charactersToExtend))) {
addMarker(range, DocumentMarker::TelephoneNumber);
if (rangesOverlap(createLiveRange(range).ptr(), selectedLiveRange.ptr()))
m_detectedTelephoneNumberRanges.append(range);
}
}
}
if (auto* page = m_document.page())
page->servicesOverlayController().selectedTelephoneNumberRangesChanged();
}
#endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS_FAMILY)
void Editor::updateEditorUINowIfScheduled()
{
if (!m_editorUIUpdateTimer.isActive())
return;
m_editorUIUpdateTimer.stop();
editorUIUpdateTimerFired();
}
void Editor::editorUIUpdateTimerFired()
{
VisibleSelection oldSelection = m_oldSelectionForEditorUIUpdate;
m_alternativeTextController->stopPendingCorrection(oldSelection);
bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
if (isContinuousSpellCheckingEnabled) {
VisibleSelection newAdjacentWords;
VisibleSelection newSelectedSentence;
bool caretBrowsing = m_document.settings().caretBrowsingEnabled();
if (m_document.selection().selection().isContentEditable() || caretBrowsing) {
VisiblePosition newStart(m_document.selection().selection().visibleStart());
#if !PLATFORM(IOS_FAMILY)
newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
#else
EWordSide startWordSide = LeftWordIfOnBoundary;
UChar32 c = newStart.characterBefore();
if (isSpaceOrNewline(c) || c == noBreakSpace || isStartOfParagraph(newStart)) {
startWordSide = RightWordIfOnBoundary;
}
newAdjacentWords = VisibleSelection(startOfWord(newStart, startWordSide), endOfWord(newStart, RightWordIfOnBoundary));
#endif // !PLATFORM(IOS_FAMILY)
if (isContinuousGrammarCheckingEnabled)
newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
}
if (m_editorUIUpdateTimerShouldCheckSpellingAndGrammar && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->isConnected()) {
VisiblePosition oldStart(oldSelection.visibleStart());
VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
if (oldAdjacentWords != newAdjacentWords) {
if (isContinuousGrammarCheckingEnabled) {
VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
} else
markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
}
}
if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Spelling)) {
if (auto wordRange = newAdjacentWords.toNormalizedRange())
removeMarkers(*wordRange, DocumentMarker::Spelling);
}
if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingType::Grammar)) {
if (auto sentenceRange = newSelectedSentence.toNormalizedRange())
removeMarkers(*sentenceRange, DocumentMarker::Grammar);
}
}
if (!isContinuousSpellCheckingEnabled)
document().markers().removeMarkers(DocumentMarker::Spelling);
if (!isContinuousGrammarCheckingEnabled)
document().markers().removeMarkers(DocumentMarker::Grammar);
if (!m_editorUIUpdateTimerWasTriggeredByDictation)
m_alternativeTextController->respondToChangedSelection(oldSelection);
m_oldSelectionForEditorUIUpdate = m_document.selection().selection();
#if ENABLE(ATTACHMENT_ELEMENT)
notifyClientOfAttachmentUpdates();
#endif
}
static Node* findFirstMarkable(Node* node)
{
while (node) {
if (!node->renderer())
return nullptr;
if (node->renderer()->isTextOrLineBreak())
return node;
if (is<Element>(*node) && downcast<Element>(*node).isTextField())
node = downcast<HTMLTextFormControlElement>(*node).visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
else if (node->firstChild())
node = node->firstChild();
else
node = node->nextSibling();
}
return nullptr;
}
bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
{
Node* node = findFirstMarkable(m_document.selection().selection().start().deprecatedNode());
if (!node)
return false;
unsigned int startOffset = static_cast<unsigned int>(from);
unsigned int endOffset = static_cast<unsigned int>(from + length);
Vector<RenderedDocumentMarker*> markers = document().markers().markersFor(*node);
for (auto* marker : markers) {
if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
return true;
}
return false;
}
OptionSet<TextCheckingType> Editor::resolveTextCheckingTypeMask(const Node& rootEditableElement, OptionSet<TextCheckingType> textCheckingOptions)
{
#if USE(AUTOMATIC_TEXT_REPLACEMENT) && !PLATFORM(IOS_FAMILY)
bool onlyAllowsTextReplacement = false;
if (auto* host = rootEditableElement.shadowHost())
onlyAllowsTextReplacement = is<HTMLInputElement>(host) && downcast<HTMLInputElement>(*host).isSpellcheckDisabledExceptTextReplacement();
if (onlyAllowsTextReplacement)
textCheckingOptions = textCheckingOptions & TextCheckingType::Replacement;
#else
UNUSED_PARAM(rootEditableElement);
#endif
bool shouldMarkSpelling = textCheckingOptions.contains(TextCheckingType::Spelling);
bool shouldMarkGrammar = textCheckingOptions.contains(TextCheckingType::Grammar);
#if !PLATFORM(IOS_FAMILY)
bool shouldShowCorrectionPanel = textCheckingOptions.contains(TextCheckingType::ShowCorrectionPanel);
bool shouldCheckForCorrection = shouldShowCorrectionPanel || textCheckingOptions.contains(TextCheckingType::Correction);
#endif
OptionSet<TextCheckingType> checkingTypes;
if (shouldMarkSpelling)
checkingTypes.add(TextCheckingType::Spelling);
if (shouldMarkGrammar)
checkingTypes.add(TextCheckingType::Grammar);
#if !PLATFORM(IOS_FAMILY)
if (shouldCheckForCorrection)
checkingTypes.add(TextCheckingType::Correction);
if (shouldShowCorrectionPanel)
checkingTypes.add(TextCheckingType::ShowCorrectionPanel);
#if USE(AUTOMATIC_TEXT_REPLACEMENT)
bool shouldPerformReplacement = textCheckingOptions.contains(TextCheckingType::Replacement);
if (shouldPerformReplacement) {
if (!onlyAllowsTextReplacement) {
if (isAutomaticLinkDetectionEnabled())
checkingTypes.add(TextCheckingType::Link);
if (isAutomaticQuoteSubstitutionEnabled())
checkingTypes.add(TextCheckingType::Quote);
if (isAutomaticDashSubstitutionEnabled())
checkingTypes.add(TextCheckingType::Dash);
if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
checkingTypes.add(TextCheckingType::Correction);
}
if (isAutomaticTextReplacementEnabled())
checkingTypes.add(TextCheckingType::Replacement);
}
#endif
#endif // !PLATFORM(IOS_FAMILY)
return checkingTypes;
}
static bool candidateWouldReplaceText(const VisibleSelection& selection)
{
UChar32 characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection = 0;
charactersAroundPosition(selection.visibleStart(), characterAfterSelection, characterBeforeSelection, twoCharacterBeforeSelection);
return !(characterBeforeSelection == '\0' || characterBeforeSelection == '\n' || characterBeforeSelection == ' ');
}
String Editor::stringForCandidateRequest() const
{
auto& selection = m_document.selection().selection();
auto range = selection.isCaret()
? wordRangeFromPosition(selection.start())
: selection.toNormalizedRange();
if (!range)
return { };
if (!candidateWouldReplaceText(selection))
return { };
return plainText(*range);
}
Optional<SimpleRange> Editor::contextRangeForCandidateRequest() const
{
auto& selection = m_document.selection().selection();
return makeSimpleRange(startOfParagraph(selection.visibleStart()), endOfParagraph(selection.visibleEnd()));
}
Optional<SimpleRange> Editor::rangeForTextCheckingResult(const TextCheckingResult& result) const
{
if (!result.range.length)
return WTF::nullopt;
auto contextRange = contextRangeForCandidateRequest();
if (!contextRange)
return WTF::nullopt;
return resolveCharacterRange(*contextRange, result.range);
}
void Editor::scheduleEditorUIUpdate()
{
m_editorUIUpdateTimer.startOneShot(0_s);
}
#if !PLATFORM(COCOA)
void Editor::platformFontAttributesAtSelectionStart(FontAttributes&, const RenderStyle&) const
{
}
String Editor::platformContentTypeForBlobType(const String& type) const
{
return type;
}
#endif
static Vector<TextList> editableTextListsAtPositionInDescendingOrder(const Position& position)
{
auto startContainer = makeRefPtr(position.containerNode());
if (!startContainer)
return { };
auto* editableRoot = highestEditableRoot(firstPositionInOrBeforeNode(startContainer.get()));
if (!editableRoot)
return { };
Vector<Ref<HTMLElement>> enclosingLists;
for (auto& ancestor : ancestorsOfType<HTMLElement>(*startContainer)) {
if (&ancestor == editableRoot)
break;
auto* renderer = ancestor.renderer();
if (!renderer)
continue;
if (is<HTMLUListElement>(ancestor) || is<HTMLOListElement>(ancestor))
enclosingLists.append(ancestor);
}
Vector<TextList> textLists;
textLists.reserveCapacity(enclosingLists.size());
for (auto iterator = enclosingLists.rbegin(); iterator != enclosingLists.rend(); ++iterator) {
auto& list = iterator->get();
bool ordered = is<HTMLOListElement>(list);
textLists.uncheckedAppend({ list.renderer()->style().listStyleType(), ordered ? downcast<HTMLOListElement>(list).start() : 1, ordered });
}
return textLists;
}
FontAttributes Editor::fontAttributesAtSelectionStart() const
{
FontAttributes attributes;
Node* nodeToRemove = nullptr;
auto* style = styleForSelectionStart(m_document.frame(), nodeToRemove);
if (!style) {
if (nodeToRemove)
nodeToRemove->remove();
return attributes;
}
platformFontAttributesAtSelectionStart(attributes, *style);
auto backgroundColor = style->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
if (backgroundColor.isVisible())
attributes.backgroundColor = backgroundColor;
auto foregroundColor = style->visitedDependentColorWithColorFilter(CSSPropertyColor);
if (foregroundColor.isValid() && !Color::isBlackColor(foregroundColor))
attributes.foregroundColor = foregroundColor;
if (auto* shadowData = style->textShadow())
attributes.fontShadow = { shadowData->color(), { static_cast<float>(shadowData->x()), static_cast<float>(shadowData->y()) }, static_cast<double>(shadowData->radius()) };
switch (style->verticalAlign()) {
case VerticalAlign::Baseline:
case VerticalAlign::Bottom:
case VerticalAlign::BaselineMiddle:
case VerticalAlign::Length:
case VerticalAlign::Middle:
case VerticalAlign::TextBottom:
case VerticalAlign::TextTop:
case VerticalAlign::Top:
break;
case VerticalAlign::Sub:
attributes.subscriptOrSuperscript = FontAttributes::SubscriptOrSuperscript::Subscript;
break;
case VerticalAlign::Super:
attributes.subscriptOrSuperscript = FontAttributes::SubscriptOrSuperscript::Superscript;
break;
}
attributes.textLists = editableTextListsAtPositionInDescendingOrder(m_document.selection().selection().start());
switch (style->textAlign()) {
case TextAlignMode::Right:
case TextAlignMode::WebKitRight:
attributes.horizontalAlignment = FontAttributes::HorizontalAlignment::Right;
break;
case TextAlignMode::Left:
case TextAlignMode::WebKitLeft:
attributes.horizontalAlignment = FontAttributes::HorizontalAlignment::Left;
break;
case TextAlignMode::Center:
case TextAlignMode::WebKitCenter:
attributes.horizontalAlignment = FontAttributes::HorizontalAlignment::Center;
break;
case TextAlignMode::Justify:
attributes.horizontalAlignment = FontAttributes::HorizontalAlignment::Justify;
break;
case TextAlignMode::Start:
if (style->hasExplicitlySetDirection())
attributes.horizontalAlignment = style->isLeftToRightDirection() ? FontAttributes::HorizontalAlignment::Left : FontAttributes::HorizontalAlignment::Right;
else
attributes.horizontalAlignment = FontAttributes::HorizontalAlignment::Natural;
break;
case TextAlignMode::End:
attributes.horizontalAlignment = style->isLeftToRightDirection() ? FontAttributes::HorizontalAlignment::Right : FontAttributes::HorizontalAlignment::Left;
break;
}
auto typingStyle = makeRefPtr(m_document.selection().typingStyle());
if (typingStyle && typingStyle->style()) {
auto value = typingStyle->style()->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
if (value && value->isValueList()) {
CSSValueList& valueList = downcast<CSSValueList>(*value);
if (valueList.hasValue(CSSValuePool::singleton().createIdentifierValue(CSSValueLineThrough).ptr()))
attributes.hasStrikeThrough = true;
if (valueList.hasValue(CSSValuePool::singleton().createIdentifierValue(CSSValueUnderline).ptr()))
attributes.hasUnderline = true;
}
} else {
auto decoration = style->textDecorationsInEffect();
if (decoration & TextDecoration::LineThrough)
attributes.hasStrikeThrough = true;
if (decoration & TextDecoration::Underline)
attributes.hasUnderline = true;
}
if (nodeToRemove)
nodeToRemove->remove();
return attributes;
}
#if ENABLE(ATTACHMENT_ELEMENT)
PromisedAttachmentInfo Editor::promisedAttachmentInfo(Element& element)
{
auto* client = this->client();
if (!client || !client->supportsClientSideAttachmentData())
return { };
RefPtr<HTMLAttachmentElement> attachment;
if (is<HTMLAttachmentElement>(element))
attachment = &downcast<HTMLAttachmentElement>(element);
else if (is<HTMLImageElement>(element))
attachment = downcast<HTMLImageElement>(element).attachmentElement();
if (!attachment)
return { };
Vector<String> additionalTypes;
Vector<RefPtr<SharedBuffer>> additionalData;
#if PLATFORM(COCOA)
getPasteboardTypesAndDataForAttachment(element, additionalTypes, additionalData);
#endif
if (auto* file = attachment->file())
return { file->url(), platformContentTypeForBlobType(file->type()), file->name(), { }, WTFMove(additionalTypes), WTFMove(additionalData) };
return { { }, { }, { }, attachment->uniqueIdentifier(), WTFMove(additionalTypes), WTFMove(additionalData) };
}
void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<SharedBuffer>&& data)
{
if (auto* client = this->client())
client->registerAttachmentIdentifier(identifier, contentType, preferredFileName, WTFMove(data));
}
void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& filePath)
{
if (auto* client = this->client())
client->registerAttachmentIdentifier(identifier, contentType, filePath);
}
void Editor::registerAttachments(Vector<SerializedAttachmentData>&& data)
{
if (auto* client = this->client())
client->registerAttachments(WTFMove(data));
}
void Editor::registerAttachmentIdentifier(const String& identifier)
{
if (auto* client = this->client())
client->registerAttachmentIdentifier(identifier);
}
void Editor::cloneAttachmentData(const String& fromIdentifier, const String& toIdentifier)
{
if (auto* client = this->client())
client->cloneAttachmentData(fromIdentifier, toIdentifier);
}
void Editor::didInsertAttachmentElement(HTMLAttachmentElement& attachment)
{
auto identifier = attachment.uniqueIdentifier();
if (identifier.isEmpty())
return;
if (!m_removedAttachmentIdentifiers.take(identifier))
m_insertedAttachmentIdentifiers.add(identifier);
scheduleEditorUIUpdate();
}
void Editor::didRemoveAttachmentElement(HTMLAttachmentElement& attachment)
{
auto identifier = attachment.uniqueIdentifier();
if (identifier.isEmpty())
return;
if (!m_insertedAttachmentIdentifiers.take(identifier))
m_removedAttachmentIdentifiers.add(identifier);
scheduleEditorUIUpdate();
}
void Editor::notifyClientOfAttachmentUpdates()
{
auto removedAttachmentIdentifiers = WTFMove(m_removedAttachmentIdentifiers);
auto insertedAttachmentIdentifiers = WTFMove(m_insertedAttachmentIdentifiers);
if (!client())
return;
for (auto& identifier : removedAttachmentIdentifiers)
client()->didRemoveAttachmentWithIdentifier(identifier);
for (auto& identifier : insertedAttachmentIdentifiers) {
if (auto attachment = m_document.attachmentForIdentifier(identifier))
client()->didInsertAttachmentWithIdentifier(identifier, attachment->attributeWithoutSynchronization(HTMLNames::srcAttr), attachment->hasEnclosingImage());
else
ASSERT_NOT_REACHED();
}
}
void Editor::insertAttachment(const String& identifier, Optional<uint64_t>&& fileSize, const String& fileName, const String& contentType)
{
auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document());
attachment->setUniqueIdentifier(identifier);
attachment->updateAttributes(WTFMove(fileSize), contentType, fileName);
auto fragmentToInsert = document().createDocumentFragment();
fragmentToInsert->appendChild(attachment.get());
replaceSelectionWithFragment(fragmentToInsert.get(), SelectReplacement::No, SmartReplace::No, MatchStyle::Yes);
}
#endif // ENABLE(ATTACHMENT_ELEMENT)
void Editor::handleAcceptedCandidate(TextCheckingResult acceptedCandidate)
{
const VisibleSelection& selection = m_document.selection().selection();
m_isHandlingAcceptedCandidate = true;
if (auto range = rangeForTextCheckingResult(acceptedCandidate)) {
if (shouldInsertText(acceptedCandidate.replacement, *range, EditorInsertAction::Typed))
ReplaceRangeWithTextCommand::create(*range, acceptedCandidate.replacement)->apply();
} else
insertText(acceptedCandidate.replacement, nullptr);
if (auto insertedCandidateRange = rangeExpandedByCharactersInDirectionAtWordBoundary(selection.visibleStart(), acceptedCandidate.replacement.length(), SelectionDirection::Backward))
addMarker(*insertedCandidateRange, DocumentMarker::AcceptedCandidate, acceptedCandidate.replacement);
m_isHandlingAcceptedCandidate = false;
}
bool Editor::unifiedTextCheckerEnabled() const
{
return WebCore::unifiedTextCheckerEnabled(m_document.frame());
}
Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker& marker)
{
return m_alternativeTextController->dictationAlternativesForMarker(marker);
}
void Editor::applyDictationAlternative(const String& alternativeString)
{
m_alternativeTextController->applyDictationAlternative(alternativeString);
}
void Editor::toggleOverwriteModeEnabled()
{
m_overwriteModeEnabled = !m_overwriteModeEnabled;
m_document.selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
}
Optional<SimpleRange> Editor::adjustedSelectionRange()
{
auto range = selectedRange();
if (range) {
if (auto enclosingAnchor = enclosingElementWithTag(firstPositionInNode(commonInclusiveAncestor(*range).get()), HTMLNames::aTag)) {
if (comparePositions(firstPositionInOrBeforeNode(range->start.container.ptr()), createLegacyEditingPosition(range->start)) >= 0)
range->start = makeBoundaryPointBeforeNodeContents(*enclosingAnchor);
}
}
return range;
}
const RenderStyle* Editor::styleForSelectionStart(Frame* frame, Node*& nodeToRemove)
{
nodeToRemove = nullptr;
if (frame->selection().isNone())
return nullptr;
Position position = adjustedSelectionStartForStyleComputation(frame->selection().selection());
if (!position.isCandidate() || position.isNull())
return nullptr;
RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
if (!typingStyle || !typingStyle->style())
return &position.deprecatedNode()->renderer()->style();
auto styleElement = HTMLSpanElement::create(*frame->document());
String styleText = typingStyle->style()->asText() + " display: inline";
styleElement->setAttribute(HTMLNames::styleAttr, styleText);
styleElement->appendChild(frame->document()->createEditingTextNode(emptyString()));
auto positionNode = position.deprecatedNode();
if (!positionNode || !positionNode->parentNode() || positionNode->parentNode()->appendChild(styleElement).hasException())
return nullptr;
nodeToRemove = styleElement.ptr();
frame->document()->updateStyleIfNeeded();
return styleElement->renderer() ? &styleElement->renderer()->style() : nullptr;
}
const Font* Editor::fontForSelection(bool& hasMultipleFonts) const
{
hasMultipleFonts = false;
if (!m_document.selection().isRange()) {
Node* nodeToRemove;
auto* style = styleForSelectionStart(m_document.frame(), nodeToRemove);
const Font* font = nullptr;
if (style) {
font = &style->fontCascade().primaryFont();
if (nodeToRemove)
nodeToRemove->remove();
}
return font;
}
auto range = m_document.selection().selection().toNormalizedRange();
if (!range)
return nullptr;
auto adjustedStart = makeBoundaryPoint(adjustedSelectionStartForStyleComputation(m_document.selection().selection()));
if (!adjustedStart)
return nullptr;
range->start = *adjustedStart;
const Font* font = nullptr;
for (auto& node : intersectingNodes(*range)) {
auto renderer = node.renderer();
if (!renderer)
continue;
auto& primaryFont = renderer->style().fontCascade().primaryFont();
if (!font)
font = &primaryFont;
else if (font != &primaryFont) {
hasMultipleFonts = true;
break;
}
}
return font;
}
RefPtr<HTMLImageElement> Editor::insertEditableImage()
{
return InsertEditableImageCommand::insertEditableImage(document());
}
bool Editor::canCopyExcludingStandaloneImages() const
{
auto& selection = m_document.selection().selection();
return selection.isRange() && !selection.isInPasswordField();
}
}