ReplaceSelectionCommand.cpp [plain text]
#include "config.h"
#include "ReplaceSelectionCommand.h"
#include "AXObjectCache.h"
#include "ApplyStyleCommand.h"
#include "BeforeTextInsertedEvent.h"
#include "BreakBlockquoteCommand.h"
#include "CSSComputedStyleDeclaration.h"
#include "CSSStyleDeclaration.h"
#include "DOMWrapperWorld.h"
#include "DataTransfer.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "Editing.h"
#include "EditingBehavior.h"
#include "ElementIterator.h"
#include "EventNames.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "HTMLBRElement.h"
#include "HTMLBaseElement.h"
#include "HTMLBodyElement.h"
#include "HTMLInputElement.h"
#include "HTMLLIElement.h"
#include "HTMLLinkElement.h"
#include "HTMLMetaElement.h"
#include "HTMLNames.h"
#include "HTMLStyleElement.h"
#include "HTMLTitleElement.h"
#include "NodeList.h"
#include "NodeRenderStyle.h"
#include "Position.h"
#include "RenderInline.h"
#include "RenderText.h"
#include "ScriptElement.h"
#include "SimplifyMarkupCommand.h"
#include "SmartReplace.h"
#include "StyleProperties.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisibleUnits.h"
#include "markup.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
namespace WebCore {
using namespace HTMLNames;
enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
class ReplacementFragment {
WTF_MAKE_FAST_ALLOCATED;
WTF_MAKE_NONCOPYABLE(ReplacementFragment);
public:
ReplacementFragment(DocumentFragment*, const VisibleSelection&);
DocumentFragment* fragment() { return m_fragment.get(); }
Node* firstChild() const;
Node* lastChild() const;
bool isEmpty() const;
bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
void removeNode(Node&);
void removeNodePreservingChildren(Node&);
private:
void removeContentsWithSideEffects();
Ref<HTMLElement> insertFragmentForTestRendering(Node* rootEditableNode);
void removeUnrenderedNodes(Node*);
void restoreAndRemoveTestRenderingNodesToFragment(StyledElement*);
void removeInterchangeNodes(Node*);
void insertNodeBefore(Node&, Node& refNode);
RefPtr<DocumentFragment> m_fragment;
bool m_hasInterchangeNewlineAtStart;
bool m_hasInterchangeNewlineAtEnd;
};
static bool isInterchangeNewlineNode(const Node* node)
{
static NeverDestroyed<String> interchangeNewlineClassString(AppleInterchangeNewline);
return is<HTMLBRElement>(node) && downcast<HTMLBRElement>(*node).attributeWithoutSynchronization(classAttr) == interchangeNewlineClassString;
}
static bool isInterchangeConvertedSpaceSpan(const Node* node)
{
static NeverDestroyed<String> convertedSpaceSpanClassString(AppleConvertedSpace);
return is<HTMLElement>(node) && downcast<HTMLElement>(*node).attributeWithoutSynchronization(classAttr) == convertedSpaceSpanClassString;
}
static Position positionAvoidingPrecedingNodes(Position position)
{
ASSERT(position.isNotNull());
if (editingIgnoresContent(*position.deprecatedNode()))
return position;
auto* enclosingBlockNode = enclosingBlock(position.containerNode());
for (Position nextPosition = position; nextPosition.containerNode() != enclosingBlockNode; position = nextPosition) {
if (lineBreakExistsAtPosition(position))
break;
if (position.containerNode()->nonShadowBoundaryParentNode())
nextPosition = positionInParentAfterNode(position.containerNode());
if (nextPosition == position)
break;
if (enclosingBlock(nextPosition.containerNode()) != enclosingBlockNode)
break;
if (VisiblePosition(position) != VisiblePosition(nextPosition))
break;
}
return position;
}
ReplacementFragment::ReplacementFragment(DocumentFragment* fragment, const VisibleSelection& selection)
: m_fragment(fragment)
, m_hasInterchangeNewlineAtStart(false)
, m_hasInterchangeNewlineAtEnd(false)
{
if (!m_fragment)
return;
if (!m_fragment->firstChild())
return;
removeContentsWithSideEffects();
RefPtr<Element> editableRoot = selection.rootEditableElement();
ASSERT(editableRoot);
if (!editableRoot)
return;
auto* shadowHost = editableRoot->shadowHost();
if (!editableRoot->attributeEventListener(eventNames().webkitBeforeTextInsertedEvent, mainThreadNormalWorld())
&& !(shadowHost && shadowHost->renderer() && shadowHost->renderer()->isTextControl())
&& editableRoot->hasRichlyEditableStyle()) {
removeInterchangeNodes(m_fragment.get());
return;
}
auto page = createPageForSanitizingWebContent();
Document* stagingDocument = page->mainFrame().document();
ASSERT(stagingDocument->body());
ComputedStyleExtractor computedStyleOfEditableRoot(editableRoot.get());
stagingDocument->body()->setAttributeWithoutSynchronization(styleAttr, computedStyleOfEditableRoot.copyProperties()->asText());
RefPtr<StyledElement> holder = insertFragmentForTestRendering(stagingDocument->body());
if (!holder) {
removeInterchangeNodes(m_fragment.get());
return;
}
auto range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
String text = range ? plainText(*range, static_cast<TextIteratorBehavior>(TextIteratorEmitsOriginalText | TextIteratorIgnoresStyleVisibility)) : emptyString();
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
auto event = BeforeTextInsertedEvent::create(text);
editableRoot->dispatchEvent(event);
if (text != event->text() || !editableRoot->hasRichlyEditableStyle()) {
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
auto range = selection.toNormalizedRange();
if (!range)
return;
m_fragment = createFragmentFromText(*range, event->text());
if (!m_fragment->firstChild())
return;
holder = insertFragmentForTestRendering(stagingDocument->body());
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreAndRemoveTestRenderingNodesToFragment(holder.get());
}
}
void ReplacementFragment::removeContentsWithSideEffects()
{
Vector<Ref<Element>> elementsToRemove;
Vector<std::pair<Ref<Element>, QualifiedName>> attributesToRemove;
auto it = descendantsOfType<Element>(*m_fragment).begin();
auto end = descendantsOfType<Element>(*m_fragment).end();
while (it != end) {
auto element = makeRef(*it);
if (isScriptElement(element) || (is<HTMLStyleElement>(element) && element->getAttribute(classAttr) != WebKitMSOListQuirksStyle)
|| is<HTMLBaseElement>(element) || is<HTMLLinkElement>(element) || is<HTMLMetaElement>(element) || is<HTMLTitleElement>(element)) {
elementsToRemove.append(WTFMove(element));
it.traverseNextSkippingChildren();
continue;
}
if (element->hasAttributes()) {
for (auto& attribute : element->attributesIterator()) {
if (element->isEventHandlerAttribute(attribute) || element->isJavaScriptURLAttribute(attribute))
attributesToRemove.append({ element.copyRef(), attribute.name() });
}
}
++it;
}
for (auto& element : elementsToRemove)
removeNode(WTFMove(element));
for (auto& item : attributesToRemove)
item.first->removeAttribute(item.second);
}
bool ReplacementFragment::isEmpty() const
{
return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
}
Node *ReplacementFragment::firstChild() const
{
return m_fragment ? m_fragment->firstChild() : 0;
}
Node *ReplacementFragment::lastChild() const
{
return m_fragment ? m_fragment->lastChild() : 0;
}
void ReplacementFragment::removeNodePreservingChildren(Node& node)
{
Ref<Node> protectedNode = node;
while (RefPtr<Node> n = node.firstChild()) {
removeNode(*n);
insertNodeBefore(*n, node);
}
removeNode(node);
}
void ReplacementFragment::removeNode(Node& node)
{
ContainerNode* parent = node.nonShadowBoundaryParentNode();
if (!parent)
return;
parent->removeChild(node);
}
void ReplacementFragment::insertNodeBefore(Node& node, Node& refNode)
{
ContainerNode* parent = refNode.nonShadowBoundaryParentNode();
if (!parent)
return;
parent->insertBefore(node, &refNode);
}
Ref<HTMLElement> ReplacementFragment::insertFragmentForTestRendering(Node* rootNode)
{
auto document = makeRef(rootNode->document());
auto holder = createDefaultParagraphElement(document.get());
holder->appendChild(*m_fragment);
rootNode->appendChild(holder);
document->updateLayoutIgnorePendingStylesheets();
return holder;
}
void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(StyledElement* holder)
{
if (!holder)
return;
while (RefPtr<Node> node = holder->firstChild()) {
holder->removeChild(*node);
m_fragment->appendChild(*node);
}
removeNode(*holder);
}
void ReplacementFragment::removeUnrenderedNodes(Node* holder)
{
Vector<Ref<Node>> unrendered;
for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder)) {
if (!isNodeRendered(*node) && !isTableStructureNode(node))
unrendered.append(*node);
}
for (auto& node : unrendered)
removeNode(node);
}
void ReplacementFragment::removeInterchangeNodes(Node* container)
{
m_hasInterchangeNewlineAtStart = false;
m_hasInterchangeNewlineAtEnd = false;
Node* node = container->firstChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtStart = true;
removeNode(*node);
break;
}
node = node->firstChild();
}
if (!container->hasChildNodes())
return;
node = container->lastChild();
while (node) {
if (isInterchangeNewlineNode(node)) {
m_hasInterchangeNewlineAtEnd = true;
removeNode(*node);
break;
}
node = node->lastChild();
}
node = container->firstChild();
while (node) {
RefPtr<Node> next = NodeTraversal::next(*node);
if (isInterchangeConvertedSpaceSpan(node)) {
next = NodeTraversal::nextSkippingChildren(*node);
removeNodePreservingChildren(*node);
}
node = next.get();
}
}
inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node* node)
{
if (!node)
return;
if (!m_firstNodeInserted)
m_firstNodeInserted = node;
m_lastNodeInserted = node;
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node* node)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::next(*node);
if (m_lastNodeInserted == node) {
m_lastNodeInserted = node->lastChild() ? node->lastChild() : NodeTraversal::nextSkippingChildren(*node);
if (!m_lastNodeInserted && m_firstNodeInserted) {
auto* previousNode = NodeTraversal::previousSkippingChildren(*node);
ASSERT(previousNode);
m_lastNodeInserted = m_firstNodeInserted->compareDocumentPosition(*previousNode) & Node::DOCUMENT_POSITION_FOLLOWING ? previousNode : m_firstNodeInserted;
}
}
}
inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node* node)
{
if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
m_firstNodeInserted = nullptr;
m_lastNodeInserted = nullptr;
} else if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
else if (m_lastNodeInserted == node)
m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
}
inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node* node, Node* newNode)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = newNode;
if (m_lastNodeInserted == node)
m_lastNodeInserted = newNode;
}
ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, RefPtr<DocumentFragment>&& fragment, OptionSet<CommandOption> options, EditAction editAction)
: CompositeEditCommand(document, editAction)
, m_selectReplacement(options & SelectReplacement)
, m_smartReplace(options & SmartReplace)
, m_matchStyle(options & MatchStyle)
, m_documentFragment(fragment)
, m_preventNesting(options & PreventNesting)
, m_movingParagraph(options & MovingParagraph)
, m_sanitizeFragment(options & SanitizeFragment)
, m_shouldMergeEnd(false)
, m_ignoreMailBlockquote(options & IgnoreMailBlockquote)
{
}
static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
{
Position existing = endOfExistingContent.deepEquivalent();
Position inserted = endOfInsertedContent.deepEquivalent();
bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
}
bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
{
if (m_movingParagraph)
return false;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
if (prev.isNull())
return false;
if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
return true;
return !selectionStartWasStartOfParagraph
&& !fragmentHasInterchangeNewlineAtStart
&& isStartOfParagraph(startOfInsertedContent)
&& !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
&& shouldMerge(startOfInsertedContent, prev);
}
bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
{
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
if (next.isNull())
return false;
return !selectionEndWasEndOfParagraph
&& isEndOfParagraph(endOfInsertedContent)
&& !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
&& shouldMerge(endOfInsertedContent, next);
}
static bool isMailPasteAsQuotationNode(const Node* node)
{
return node && node->hasTagName(blockquoteTag) && downcast<Element>(node)->attributeWithoutSynchronization(classAttr) == ApplePasteAsQuotation;
}
static bool isHeaderElement(const Node* a)
{
if (!a)
return false;
return a->hasTagName(h1Tag)
|| a->hasTagName(h2Tag)
|| a->hasTagName(h3Tag)
|| a->hasTagName(h4Tag)
|| a->hasTagName(h5Tag)
|| a->hasTagName(h6Tag);
}
static bool haveSameTagName(Node* a, Node* b)
{
return is<Element>(a) && is<Element>(b) && downcast<Element>(*a).tagName() == downcast<Element>(*b).tagName();
}
bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
{
if (source.isNull() || destination.isNull())
return false;
auto* sourceNode = source.deepEquivalent().deprecatedNode();
auto* destinationNode = destination.deepEquivalent().deprecatedNode();
auto* sourceBlock = enclosingBlock(sourceNode);
auto* destinationBlock = enclosingBlock(destinationNode);
return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode)
&& sourceBlock
&& (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock))
&& enclosingListChild(sourceBlock) == enclosingListChild(destinationNode)
&& enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent())
&& (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock))
&& !isBlock(sourceNode) && !isBlock(destinationNode);
}
static bool fragmentNeedsColorTransformed(ReplacementFragment& fragment, const Position& insertionPos)
{
RefPtr<Element> editableRoot = insertionPos.rootEditableElement();
ASSERT(editableRoot);
if (!editableRoot)
return false;
auto* editableRootRenderer = editableRoot->renderer();
if (!editableRootRenderer || !editableRootRenderer->style().hasAppleColorFilter())
return false;
const auto& colorFilter = editableRootRenderer->style().appleColorFilter();
for (const auto& colorFilterOperation : colorFilter.operations()) {
if (colorFilterOperation->type() != FilterOperation::APPLE_INVERT_LIGHTNESS)
return false;
}
auto propertyLightness = [&](const StyleProperties& inlineStyle, CSSPropertyID propertyID) -> Optional<double> {
auto color = inlineStyle.propertyAsColor(propertyID);
if (!color || !color.value().isVisible() || color.value().isSemantic())
return { };
return color.value().lightness();
};
const double lightnessDarkEnoughForText = 0.4;
const double lightnessLightEnoughForBackground = 0.6;
for (RefPtr<Node> node = fragment.firstChild(); node; node = NodeTraversal::next(*node)) {
if (!is<StyledElement>(*node))
continue;
auto& element = downcast<StyledElement>(*node);
auto* inlineStyle = element.inlineStyle();
if (!inlineStyle)
continue;
auto textLightness = propertyLightness(*inlineStyle, CSSPropertyColor);
if (textLightness && *textLightness < lightnessDarkEnoughForText)
return false;
auto backgroundLightness = propertyLightness(*inlineStyle, CSSPropertyBackgroundColor);
if (backgroundLightness && *backgroundLightness > lightnessLightEnoughForBackground)
return false;
}
return true;
}
void ReplaceSelectionCommand::inverseTransformColor(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = NodeTraversal::next(*node)) {
if (!is<StyledElement>(*node))
continue;
auto& element = downcast<StyledElement>(*node);
auto* inlineStyle = element.inlineStyle();
if (!inlineStyle)
continue;
auto editingStyle = EditingStyle::create(inlineStyle);
auto transformedStyle = editingStyle->inverseTransformColorIfNeeded(element);
if (editingStyle.ptr() == transformedStyle.ptr())
continue;
setNodeAttribute(element, styleAttr, transformedStyle->style()->asText());
}
}
void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
next = NodeTraversal::next(*node);
if (!is<StyledElement>(*node))
continue;
StyledElement* element = downcast<StyledElement>(node.get());
const StyleProperties* inlineStyle = element->inlineStyle();
auto newInlineStyle = EditingStyle::create(inlineStyle);
if (inlineStyle) {
if (is<HTMLElement>(*element)) {
Vector<QualifiedName> attributes;
HTMLElement& htmlElement = downcast<HTMLElement>(*element);
if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
element = downcast<StyledElement>(node.get());
insertedNodes.didReplaceNode(&htmlElement, node.get());
} else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, nullptr, attributes, EditingStyle::DoNotExtractMatchingStyle)) {
for (auto& attribute : attributes)
removeNodeAttribute(*element, attribute);
}
}
ContainerNode* context = element->parentNode();
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
newInlineStyle->removeStyleFromRulesAndContext(*element, document().documentElement());
newInlineStyle->removeStyleFromRulesAndContext(*element, context);
}
if (!inlineStyle || newInlineStyle->isEmpty()) {
if (isStyleSpanOrSpanWithOnlyStyleAttribute(*element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(*element);
continue;
}
removeNodeAttribute(*element, styleAttr);
} else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount())
setNodeAttribute(*element, styleAttr, newInlineStyle->style()->asText());
if (element->parentNode() && isNonTableCellHTMLBlockElement(element) && areIdenticalElements(*element, *element->parentNode())
&& VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
&& VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(*element);
continue;
}
if (element->parentNode() && element->parentNode()->hasRichlyEditableStyle())
removeNodeAttribute(*element, contenteditableAttr);
if (isLegacyAppleStyleSpan(element)) {
if (!element->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(element);
removeNodePreservingChildren(*element);
continue;
}
if (isBlock(element))
element->cssomStyle().setPropertyInternal(CSSPropertyDisplay, "inline", false);
if (element->renderer() && element->renderer()->style().isFloating())
element->cssomStyle().setPropertyInternal(CSSPropertyFloat, "none", false);
}
}
}
static bool isProhibitedParagraphChild(const AtomString& name)
{
static const auto localNames = makeNeverDestroyed([] {
static const HTMLQualifiedName* const tags[] = {
&addressTag.get(),
&articleTag.get(),
&asideTag.get(),
&blockquoteTag.get(),
&captionTag.get(),
¢erTag.get(),
&colTag.get(),
&colgroupTag.get(),
&ddTag.get(),
&detailsTag.get(),
&dirTag.get(),
&divTag.get(),
&dlTag.get(),
&dtTag.get(),
&fieldsetTag.get(),
&figcaptionTag.get(),
&figureTag.get(),
&footerTag.get(),
&formTag.get(),
&h1Tag.get(),
&h2Tag.get(),
&h3Tag.get(),
&h4Tag.get(),
&h5Tag.get(),
&h6Tag.get(),
&headerTag.get(),
&hgroupTag.get(),
&hrTag.get(),
&liTag.get(),
&listingTag.get(),
&mainTag.get(), &menuTag.get(),
&navTag.get(),
&olTag.get(),
&pTag.get(),
&plaintextTag.get(),
&preTag.get(),
§ionTag.get(),
&summaryTag.get(),
&tableTag.get(),
&tbodyTag.get(),
&tdTag.get(),
&tfootTag.get(),
&thTag.get(),
&theadTag.get(),
&trTag.get(),
&ulTag.get(),
&xmpTag.get(),
};
HashSet<AtomString> set;
for (auto& tag : tags)
set.add(tag->localName());
return set;
}());
return localNames.get().contains(name);
}
void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
{
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
next = NodeTraversal::next(*node);
if (!is<HTMLElement>(*node))
continue;
if (isProhibitedParagraphChild(downcast<HTMLElement>(*node).localName())) {
if (auto* paragraphElement = enclosingElementWithTag(positionInParentBeforeNode(node.get()), pTag)) {
auto* parent = paragraphElement->parentNode();
if (parent && parent->hasEditableStyle())
moveNodeOutOfAncestor(*node, *paragraphElement, insertedNodes);
}
}
if (isHeaderElement(node.get())) {
if (auto* headerElement = highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement)) {
if (headerElement->parentNode() && headerElement->parentNode()->isContentRichlyEditable())
moveNodeOutOfAncestor(*node, *headerElement, insertedNodes);
else {
HTMLElement* newSpanElement = replaceElementWithSpanPreservingChildrenAndAttributes(downcast<HTMLElement>(*node));
insertedNodes.didReplaceNode(node.get(), newSpanElement);
}
}
}
}
}
static inline bool hasRenderedText(const Text& text)
{
return text.renderer() && text.renderer()->hasRenderedText();
}
void ReplaceSelectionCommand::moveNodeOutOfAncestor(Node& node, Node& ancestor, InsertedNodes& insertedNodes)
{
Ref<Node> protectedNode = node;
Ref<Node> protectedAncestor = ancestor;
VisiblePosition positionAtEndOfNode = lastPositionInOrAfterNode(&node);
VisiblePosition lastPositionInParagraph = lastPositionInNode(&ancestor);
if (positionAtEndOfNode == lastPositionInParagraph) {
removeNode(node);
if (ancestor.nextSibling())
insertNodeBefore(WTFMove(protectedNode), *ancestor.nextSibling());
else
appendNode(WTFMove(protectedNode), *ancestor.parentNode());
} else {
RefPtr<Node> nodeToSplitTo = splitTreeToNode(node, ancestor, true);
removeNode(node);
if (nodeToSplitTo)
insertNodeBefore(WTFMove(protectedNode), *nodeToSplitTo);
}
document().updateLayoutIgnorePendingStylesheets();
bool safeToRemoveAncestor = true;
for (auto* child = ancestor.firstChild(); child; child = child->nextSibling()) {
if (is<Text>(child) && hasRenderedText(downcast<Text>(*child))) {
safeToRemoveAncestor = false;
break;
}
if (is<Element>(child)) {
safeToRemoveAncestor = false;
break;
}
}
if (safeToRemoveAncestor) {
insertedNodes.willRemoveNode(&ancestor);
removeNode(ancestor);
}
}
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
{
document().updateLayoutIgnorePendingStylesheets();
Node* lastLeafInserted = insertedNodes.lastLeafInserted();
if (is<Text>(lastLeafInserted) && !hasRenderedText(downcast<Text>(*lastLeafInserted))
&& !enclosingElementWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
&& !enclosingElementWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
insertedNodes.willRemoveNode(lastLeafInserted);
removeNode(*lastLeafInserted);
}
Node* firstNodeInserted = insertedNodes.firstNodeInserted();
if (is<Text>(firstNodeInserted) && !hasRenderedText(downcast<Text>(*firstNodeInserted))) {
insertedNodes.willRemoveNode(firstNodeInserted);
removeNode(*firstNodeInserted);
}
}
VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent() const
{
auto* enclosingSelect = enclosingElementWithTag(m_endOfInsertedContent, selectTag);
return enclosingSelect ? lastPositionInOrAfterNode(enclosingSelect) : m_endOfInsertedContent;
}
VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent() const
{
return m_startOfInsertedContent;
}
static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
{
Node* topNode = fragment.firstChild();
if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
return false;
if (!isLegacyAppleStyleSpan(topNode))
return false;
Node* wrappingStyleSpan = topNode;
auto styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
String styleText = styleAtInsertionPos->style()->asText();
if (styleText != downcast<Element>(*wrappingStyleSpan).getAttribute(styleAttr))
return false;
fragment.removeNodePreservingChildren(*wrappingStyleSpan);
return true;
}
void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
{
HTMLElement* wrappingStyleSpan = nullptr;
for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
if (isLegacyAppleStyleSpan(node)) {
wrappingStyleSpan = downcast<HTMLElement>(node);
break;
}
}
if (!wrappingStyleSpan)
return;
auto style = EditingStyle::create(wrappingStyleSpan->inlineStyle());
ContainerNode* context = wrappingStyleSpan->parentNode();
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
if (blockquoteNode)
context = document().documentElement();
style->prepareToApplyAt(firstPositionInNode(context));
style->removeBlockProperties();
if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
insertedNodes.willRemoveNodePreservingChildren(wrappingStyleSpan);
removeNodePreservingChildren(*wrappingStyleSpan);
} else
setNodeAttribute(*wrappingStyleSpan, styleAttr, style->style()->asText());
}
void ReplaceSelectionCommand::mergeEndIfNeeded()
{
if (!m_shouldMergeEnd)
return;
VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
if (m_movingParagraph) {
ASSERT_NOT_REACHED();
return;
}
bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
if (endOfParagraph(startOfParagraphToMove) == destination) {
auto placeholder = HTMLBRElement::create(document());
auto* placeholderPtr = placeholder.ptr();
insertNodeBefore(WTFMove(placeholder), *startOfParagraphToMove.deepEquivalent().deprecatedNode());
destination = VisiblePosition(positionBeforeNode(placeholderPtr));
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
if (mergeForward) {
if (m_startOfInsertedContent.isOrphan())
m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent();
m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent();
if (m_endOfInsertedContent.isNull())
m_endOfInsertedContent = m_startOfInsertedContent;
}
}
static Node* enclosingInline(Node* node)
{
while (ContainerNode* parent = node->parentNode()) {
if (isBlockFlowElement(*parent) || parent->hasTagName(bodyTag))
return node;
for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
if (isBlockFlowElement(*sibling))
return node;
}
node = parent;
}
return node;
}
static bool isInlineNodeWithStyle(const Node* node)
{
if (isBlock(node))
return false;
if (!node->isHTMLElement())
return false;
const HTMLElement* element = static_cast<const HTMLElement*>(node);
const AtomString& classAttributeValue = element->attributeWithoutSynchronization(classAttr);
if (classAttributeValue == AppleTabSpanClass
|| classAttributeValue == AppleConvertedSpace
|| classAttributeValue == ApplePasteAsQuotation)
return true;
return EditingStyle::elementIsStyledSpanOrHTMLEquivalent(*element);
}
inline Node* nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(const Position& insertionPos)
{
Node* containgBlock = enclosingBlock(insertionPos.containerNode());
return highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle, CannotCrossEditingBoundary, containgBlock);
}
bool ReplaceSelectionCommand::willApplyCommand()
{
m_documentFragmentPlainText = m_documentFragment->textContent();
m_documentFragmentHTMLMarkup = serializeFragment(*m_documentFragment, SerializedNodes::SubtreeIncludingNode);
ensureReplacementFragment();
return CompositeEditCommand::willApplyCommand();
}
static bool hasBlankLineBetweenParagraphs(Position& position)
{
bool reachedBoundaryStart = false;
bool reachedBoundaryEnd = false;
VisiblePosition visiblePosition(position);
VisiblePosition previousPosition = visiblePosition.previous(CannotCrossEditingBoundary, &reachedBoundaryStart);
VisiblePosition nextPosition = visiblePosition.next(CannotCrossEditingBoundary, &reachedBoundaryStart);
bool hasLineBeforePosition = isEndOfLine(previousPosition);
return !reachedBoundaryStart && !reachedBoundaryEnd && isBlankParagraph(visiblePosition) && hasLineBeforePosition && isStartOfLine(nextPosition);
}
void ReplaceSelectionCommand::doApply()
{
VisibleSelection selection = endingSelection();
ASSERT(selection.isCaretOrRange());
ASSERT(selection.start().deprecatedNode());
if (selection.isNoneOrOrphaned() || !selection.start().deprecatedNode() || !selection.isContentEditable())
return;
if (!selection.isContentRichlyEditable())
m_matchStyle = false;
ReplacementFragment& fragment = *ensureReplacementFragment();
if (performTrivialReplace(fragment))
return;
if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style().userModify() == UserModify::ReadWritePlaintextOnly)
&& (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style().userModify() == UserModify::ReadWritePlaintextOnly))
m_matchStyle = false;
if (m_matchStyle) {
m_insertionStyle = EditingStyle::create(selection.start());
m_insertionStyle->mergeTypingStyle(document());
}
VisiblePosition visibleStart = selection.visibleStart();
VisiblePosition visibleEnd = selection.visibleEnd();
bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
Position insertionPos = selection.start();
bool shouldHandleMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary) && !m_ignoreMailBlockquote;
bool selectionIsPlainText = !selection.isContentRichlyEditable();
Element* currentRoot = selection.rootEditableElement();
if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !shouldHandleMailBlockquote)
|| startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
m_preventNesting = false;
if (selection.isRange()) {
bool mergeBlocksAfterDelete = shouldHandleMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
deleteSelection(false, mergeBlocksAfterDelete, true, false, true);
visibleStart = endingSelection().visibleStart();
if (fragment.hasInterchangeNewlineAtStart()) {
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
if (!isEndOfEditableOrNonEditableContent(visibleStart))
setEndingSelection(visibleStart.next());
} else
insertParagraphSeparator();
}
insertionPos = endingSelection().start();
} else {
ASSERT(selection.isCaret());
if (fragment.hasInterchangeNewlineAtStart()) {
VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
setEndingSelection(next);
else {
insertParagraphSeparator();
visibleStart = endingSelection().visibleStart();
}
}
if (m_preventNesting && !shouldHandleMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
insertParagraphSeparator();
setEndingSelection(endingSelection().visibleStart().previous());
}
insertionPos = endingSelection().start();
}
if (shouldHandleMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
applyCommandToComposite(BreakBlockquoteCommand::create(document()));
Node* br = endingSelection().start().deprecatedNode();
ASSERT(br->hasTagName(brTag));
insertionPos = positionInParentBeforeNode(br);
removeNode(*br);
}
prepareWhitespaceAtPositionForSplit(insertionPos);
if (!insertionPos.downstream().deprecatedNode())
return;
RefPtr<Node> endBR = insertionPos.downstream().deprecatedNode()->hasTagName(brTag) ? insertionPos.downstream().deprecatedNode() : nullptr;
VisiblePosition originalVisPosBeforeEndBR;
if (endBR)
originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR.get())).previous();
RefPtr<Node> insertionBlock = enclosingBlock(insertionPos.deprecatedNode());
if (m_preventNesting && insertionBlock && !isTableCell(insertionBlock.get()) && !shouldHandleMailBlockquote) {
ASSERT(insertionBlock != currentRoot);
VisiblePosition visibleInsertionPos(insertionPos);
if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
insertionPos = positionInParentAfterNode(insertionBlock.get());
else if (isStartOfBlock(visibleInsertionPos))
insertionPos = positionInParentBeforeNode(insertionBlock.get());
}
insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
document().selection().clearTypingStyle();
insertionPos = positionAvoidingPrecedingNodes(insertionPos);
insertionPos = positionOutsideTabSpan(insertionPos);
bool hasBlankLinesBetweenParagraphs = hasBlankLineBetweenParagraphs(insertionPos);
bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
bool needsColorTransformed = fragmentNeedsColorTransformed(fragment, insertionPos);
if (fragment.isEmpty() || !fragment.firstChild())
return;
if (!m_matchStyle && !enclosingList(insertionPos.containerNode())) {
if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
splitTextNode(*insertionPos.containerText(), insertionPos.offsetInContainerNode());
insertionPos = firstPositionInNode(insertionPos.containerNode());
}
if (RefPtr<Node> nodeToSplitTo = nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(insertionPos)) {
if (insertionPos.containerNode() != nodeToSplitTo->parentNode()) {
Node* splitStart = insertionPos.computeNodeAfterPosition();
if (!splitStart)
splitStart = insertionPos.containerNode();
ASSERT(splitStart);
nodeToSplitTo = splitTreeToNode(*splitStart, *nodeToSplitTo->parentNode()).get();
insertionPos = positionInParentBeforeNode(nodeToSplitTo.get());
}
}
}
InsertedNodes insertedNodes;
RefPtr<Node> refNode = fragment.firstChild();
RefPtr<Node> node = refNode->nextSibling();
if (refNode)
fragment.removeNode(*refNode);
Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
bool isInsertingIntoList = (isListHTMLElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListHTMLElement(refNode->firstChild())))
&& blockStart && blockStart->renderer()->isListItem();
if (isInsertingIntoList)
refNode = insertAsListItems(downcast<HTMLElement>(*refNode), blockStart, insertionPos, insertedNodes);
else {
insertNodeAt(*refNode, insertionPos);
insertedNodes.respondToNodeInsertion(refNode.get());
}
if (!refNode->isConnected())
return;
bool plainTextFragment = isPlainTextMarkup(refNode.get());
while (node) {
RefPtr<Node> next = node->nextSibling();
fragment.removeNode(*node);
insertNodeAfter(*node, *refNode);
insertedNodes.respondToNodeInsertion(node.get());
if (!node->isConnected())
return;
refNode = node;
if (node && plainTextFragment)
plainTextFragment = isPlainTextMarkup(node.get());
node = next;
}
if (insertedNodes.isEmpty())
return;
removeUnrenderedTextNodesAtEnds(insertedNodes);
if (!handledStyleSpans)
handleStyleSpans(insertedNodes);
if (insertedNodes.isEmpty())
return;
if (!insertedNodes.firstNodeInserted()->isConnected())
return;
VisiblePosition startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
if (!startOfInsertedContent.isNull() && insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->computeNodeIndex() && !isStartOfParagraph(startOfInsertedContent))
insertNodeAt(HTMLBRElement::create(document()), startOfInsertedContent.deepEquivalent());
if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR.get(), originalVisPosBeforeEndBR))) {
auto parent = makeRefPtr(endBR->parentNode());
insertedNodes.willRemoveNode(endBR.get());
removeNode(*endBR);
document().updateLayoutIgnorePendingStylesheets();
if (auto nodeToRemove = makeRefPtr(highestNodeToRemoveInPruning(parent.get()))) {
insertedNodes.willRemoveNode(nodeToRemove.get());
removeNode(*nodeToRemove);
}
}
makeInsertedContentRoundTrippableWithHTMLTreeBuilder(insertedNodes);
if (insertedNodes.isEmpty())
return;
if (needsColorTransformed)
inverseTransformColor(insertedNodes);
removeRedundantStylesAndKeepStyleSpanInline(insertedNodes);
if (insertedNodes.isEmpty())
return;
if (m_sanitizeFragment)
applyCommandToComposite(SimplifyMarkupCommand::create(document(), insertedNodes.firstNodeInserted(), insertedNodes.pastLastLeaf()));
m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), shouldHandleMailBlockquote)) {
VisiblePosition startOfParagraphToMove = positionAtStartOfInsertedContent();
VisiblePosition destination = startOfParagraphToMove.previous();
Node* destinationNode = destination.deepEquivalent().deprecatedNode();
if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
insertNodeBefore(HTMLBRElement::create(document()), *refNode);
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
insertNodeAt(HTMLBRElement::create(document()), endOfInsertedContent.deepEquivalent());
if (!startOfParagraphToMove.deepEquivalent().anchorNode()->isConnected())
return;
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
m_startOfInsertedContent = endingSelection().visibleStart().deepEquivalent().downstream();
if (m_endOfInsertedContent.isOrphan())
m_endOfInsertedContent = endingSelection().visibleEnd().deepEquivalent().upstream();
}
Position lastPositionToSelect;
if (fragment.hasInterchangeNewlineAtEnd()) {
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
if (!isStartOfParagraph(endOfInsertedContent)) {
setEndingSelection(endOfInsertedContent);
Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
if (isListItem(enclosingNode)) {
auto newListItem = HTMLLIElement::create(document());
insertNodeAfter(newListItem.copyRef(), *enclosingNode);
setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.ptr())));
} else {
insertParagraphSeparator(true, !shouldHandleMailBlockquote && highestEnclosingNodeOfType(endOfInsertedContent.deepEquivalent(),
isMailBlockquote, CannotCrossEditingBoundary, insertedNodes.firstNodeInserted()->parentNode()));
}
lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
updateNodesInserted(lastPositionToSelect.deprecatedNode());
}
} else {
lastPositionToSelect = next.deepEquivalent().downstream();
}
} else
mergeEndIfNeeded();
if (Node* mailBlockquote = enclosingNodeOfType(positionAtStartOfInsertedContent().deepEquivalent(), isMailPasteAsQuotationNode))
removeNodeAttribute(downcast<Element>(*mailBlockquote), classAttr);
if (shouldPerformSmartReplace())
addSpacesForSmartReplace();
if (!isInsertingIntoList && hasBlankLinesBetweenParagraphs && shouldPerformSmartParagraphReplace())
addNewLinesForSmartReplace();
if (plainTextFragment)
m_matchStyle = false;
completeHTMLReplacement(lastPositionToSelect);
}
String ReplaceSelectionCommand::inputEventData() const
{
if (isEditingTextAreaOrTextInput())
return m_documentFragment->textContent();
return CompositeEditCommand::inputEventData();
}
RefPtr<DataTransfer> ReplaceSelectionCommand::inputEventDataTransfer() const
{
if (isEditingTextAreaOrTextInput())
return CompositeEditCommand::inputEventDataTransfer();
return DataTransfer::createForInputEvent(m_documentFragmentPlainText, m_documentFragmentHTMLMarkup);
}
bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
{
if (!endBR || !endBR->isConnected())
return false;
VisiblePosition visiblePos(positionBeforeNode(endBR));
if (visiblePos.previous() == originalVisPosBeforeEndBR)
return false;
if (!document().inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
return true;
return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
}
bool ReplaceSelectionCommand::shouldPerformSmartReplace() const
{
if (!m_smartReplace)
return false;
Element* textControl = enclosingTextFormControl(positionAtStartOfInsertedContent().deepEquivalent());
if (is<HTMLInputElement>(textControl) && downcast<HTMLInputElement>(*textControl).isPasswordField())
return false;
return true;
}
bool ReplaceSelectionCommand::shouldPerformSmartParagraphReplace() const
{
if (!m_smartReplace)
return false;
if (!document().editingBehavior().shouldSmartInsertDeleteParagraphs())
return false;
return true;
}
static bool isCharacterSmartReplaceExemptConsideringNonBreakingSpace(UChar32 character, bool previousCharacter)
{
return isCharacterSmartReplaceExempt(character == noBreakSpace ? ' ' : character, previousCharacter);
}
void ReplaceSelectionCommand::addNewLinesForSmartReplace()
{
VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
bool isPastedContentEntireParagraphs = isStartOfParagraph(startOfInsertedContent) && isEndOfParagraph(endOfInsertedContent);
if (!isPastedContentEntireParagraphs)
return;
bool reachedBoundaryStart = false;
bool reachedBoundaryEnd = false;
VisiblePosition positionBeforeStart = startOfInsertedContent.previous(CannotCrossEditingBoundary, &reachedBoundaryStart);
VisiblePosition positionAfterEnd = endOfInsertedContent.next(CannotCrossEditingBoundary, &reachedBoundaryEnd);
if (!reachedBoundaryStart && !reachedBoundaryEnd) {
if (!isBlankParagraph(positionBeforeStart) && !isBlankParagraph(startOfInsertedContent) && isEndOfLine(positionBeforeStart) && !isEndOfEditableOrNonEditableContent(positionAfterEnd) && !isEndOfEditableOrNonEditableContent(endOfInsertedContent)) {
setEndingSelection(startOfInsertedContent);
insertParagraphSeparator();
auto newStart = endingSelection().visibleStart().previous(CannotCrossEditingBoundary, &reachedBoundaryStart);
if (!reachedBoundaryStart)
m_startOfInsertedContent = newStart.deepEquivalent();
}
}
reachedBoundaryStart = false;
reachedBoundaryEnd = false;
positionAfterEnd = endOfInsertedContent.next(CannotCrossEditingBoundary, &reachedBoundaryEnd);
positionBeforeStart = startOfInsertedContent.previous(CannotCrossEditingBoundary, &reachedBoundaryStart);
if (!reachedBoundaryEnd && !reachedBoundaryStart) {
if (!isBlankParagraph(positionAfterEnd) && !isBlankParagraph(endOfInsertedContent) && isStartOfLine(positionAfterEnd) && !isEndOfLine(positionAfterEnd) && !isEndOfEditableOrNonEditableContent(positionAfterEnd)) {
setEndingSelection(endOfInsertedContent);
insertParagraphSeparator();
m_endOfInsertedContent = endingSelection().start();
}
}
}
void ReplaceSelectionCommand::addSpacesForSmartReplace()
{
VisiblePosition startOfInsertedContent = positionAtStartOfInsertedContent();
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
Position endUpstream = endOfInsertedContent.deepEquivalent().upstream();
Node* endNode = endUpstream.computeNodeBeforePosition();
int endOffset = is<Text>(endNode) ? downcast<Text>(*endNode).length() : 0;
if (endUpstream.anchorType() == Position::PositionIsOffsetInAnchor) {
endNode = endUpstream.containerNode();
endOffset = endUpstream.offsetInContainerNode();
}
bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) && !isStartOfParagraph(endOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(endOfInsertedContent.characterAfter(), false);
if (needsTrailingSpace && endNode) {
bool collapseWhiteSpace = !endNode->renderer() || endNode->renderer()->style().collapseWhiteSpace();
if (is<Text>(*endNode)) {
insertTextIntoNode(downcast<Text>(*endNode), endOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
if (m_endOfInsertedContent.containerNode() == endNode)
m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
} else {
auto node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
insertNodeAfter(node.copyRef(), *endNode);
updateNodesInserted(node.ptr());
}
}
document().updateLayout();
Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
Node* startNode = startDownstream.computeNodeAfterPosition();
unsigned startOffset = 0;
if (startDownstream.anchorType() == Position::PositionIsOffsetInAnchor) {
startNode = startDownstream.containerNode();
startOffset = startDownstream.offsetInContainerNode();
}
bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) && !isEndOfParagraph(startOfInsertedContent) && !isCharacterSmartReplaceExemptConsideringNonBreakingSpace(startOfInsertedContent.previous().characterAfter(), true);
if (needsLeadingSpace && startNode) {
bool collapseWhiteSpace = !startNode->renderer() || startNode->renderer()->style().collapseWhiteSpace();
if (is<Text>(*startNode)) {
insertTextIntoNode(downcast<Text>(*startNode), startOffset, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
} else {
auto node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
auto* nodePtr = node.ptr();
insertNodeBefore(WTFMove(node), *startNode);
m_startOfInsertedContent = firstPositionInNode(nodePtr);
}
}
}
void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
{
Position start = positionAtStartOfInsertedContent().deepEquivalent();
Position end = positionAtEndOfInsertedContent().deepEquivalent();
if (start.isNotNull() && !start.isOrphan() && end.isNotNull() && !end.isOrphan()) {
rebalanceWhitespaceAt(start);
rebalanceWhitespaceAt(end);
if (m_matchStyle) {
ASSERT(m_insertionStyle);
applyStyle(m_insertionStyle.get(), start, end);
}
if (lastPositionToSelect.isNotNull())
end = lastPositionToSelect;
mergeTextNodesAroundPosition(start, end);
mergeTextNodesAroundPosition(end, start);
} else if (lastPositionToSelect.isNotNull())
start = end = lastPositionToSelect;
else
return;
if (AXObjectCache::accessibilityEnabled() && editingAction() == EditAction::Paste)
m_visibleSelectionForInsertedText = VisibleSelection(start, end);
if (m_selectReplacement)
setEndingSelection(VisibleSelection(start, end, VisibleSelection::defaultAffinity, endingSelection().isDirectional()));
else
setEndingSelection(VisibleSelection(end, VisibleSelection::defaultAffinity, endingSelection().isDirectional()));
}
void ReplaceSelectionCommand::mergeTextNodesAroundPosition(Position& position, Position& positionOnlyToBeUpdated)
{
bool positionIsOffsetInAnchor = position.anchorType() == Position::PositionIsOffsetInAnchor;
bool positionOnlyToBeUpdatedIsOffsetInAnchor = positionOnlyToBeUpdated.anchorType() == Position::PositionIsOffsetInAnchor;
RefPtr<Text> text;
if (positionIsOffsetInAnchor && is<Text>(position.containerNode()))
text = downcast<Text>(position.containerNode());
else {
Node* before = position.computeNodeBeforePosition();
if (is<Text>(before))
text = downcast<Text>(before);
else {
Node* after = position.computeNodeAfterPosition();
if (is<Text>(after))
text = downcast<Text>(after);
}
}
if (!text)
return;
if (is<Text>(text->previousSibling())) {
Ref<Text> previous(downcast<Text>(*text->previousSibling()));
insertTextIntoNode(*text, 0, previous->data());
if (positionIsOffsetInAnchor)
position.moveToOffset(previous->length() + position.offsetInContainerNode());
else
updatePositionForNodeRemoval(position, previous.get());
if (positionOnlyToBeUpdatedIsOffsetInAnchor) {
if (positionOnlyToBeUpdated.containerNode() == text)
positionOnlyToBeUpdated.moveToOffset(previous->length() + positionOnlyToBeUpdated.offsetInContainerNode());
else if (positionOnlyToBeUpdated.containerNode() == previous.ptr())
positionOnlyToBeUpdated.moveToPosition(text.get(), positionOnlyToBeUpdated.offsetInContainerNode());
} else
updatePositionForNodeRemoval(positionOnlyToBeUpdated, previous.get());
removeNode(previous);
}
if (is<Text>(text->nextSibling())) {
Ref<Text> next(downcast<Text>(*text->nextSibling()));
unsigned originalLength = text->length();
insertTextIntoNode(*text, originalLength, next->data());
if (!positionIsOffsetInAnchor)
updatePositionForNodeRemoval(position, next.get());
if (positionOnlyToBeUpdatedIsOffsetInAnchor && positionOnlyToBeUpdated.containerNode() == next.ptr())
positionOnlyToBeUpdated.moveToPosition(text.get(), originalLength + positionOnlyToBeUpdated.offsetInContainerNode());
else
updatePositionForNodeRemoval(positionOnlyToBeUpdated, next.get());
removeNode(next);
}
}
static HTMLElement* singleChildList(HTMLElement& element)
{
if (!element.hasOneChild())
return nullptr;
auto& child = *element.firstChild();
return isListHTMLElement(&child) ? &downcast<HTMLElement>(child) : nullptr;
}
static HTMLElement& deepestSingleChildList(HTMLElement& topLevelList)
{
auto* list = &topLevelList;
while (auto* childList = singleChildList(*list))
list = childList;
return *list;
}
Node* ReplaceSelectionCommand::insertAsListItems(HTMLElement& passedListElement, Node* insertionBlock, const Position& insertPos, InsertedNodes& insertedNodes)
{
Ref<HTMLElement> listElement = deepestSingleChildList(passedListElement);
bool isStart = isStartOfParagraph(insertPos);
bool isEnd = isEndOfParagraph(insertPos);
bool isMiddle = !isStart && !isEnd;
Node* lastNode = insertionBlock;
if (isMiddle) {
int textNodeOffset = insertPos.offsetInContainerNode();
if (is<Text>(*insertPos.deprecatedNode()) && textNodeOffset > 0)
splitTextNode(downcast<Text>(*insertPos.deprecatedNode()), textNodeOffset);
splitTreeToNode(*insertPos.deprecatedNode(), *lastNode, true);
}
while (RefPtr<Node> listItem = listElement->firstChild()) {
listElement->removeChild(*listItem);
if (isStart || isMiddle) {
insertNodeBefore(*listItem, *lastNode);
insertedNodes.respondToNodeInsertion(listItem.get());
} else if (isEnd) {
insertNodeAfter(*listItem, *lastNode);
insertedNodes.respondToNodeInsertion(listItem.get());
lastNode = listItem.get();
} else
ASSERT_NOT_REACHED();
}
if ((isStart || isMiddle) && lastNode->previousSibling())
lastNode = lastNode->previousSibling();
return lastNode;
}
void ReplaceSelectionCommand::updateNodesInserted(Node *node)
{
if (!node)
return;
if (m_startOfInsertedContent.isNull())
m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
m_endOfInsertedContent = lastPositionInOrAfterNode(node->lastDescendant());
}
ReplacementFragment* ReplaceSelectionCommand::ensureReplacementFragment()
{
if (!m_replacementFragment)
m_replacementFragment = makeUnique<ReplacementFragment>(m_documentFragment.get(), endingSelection());
return m_replacementFragment.get();
}
bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
{
if (!is<Text>(fragment.firstChild()) || fragment.firstChild() != fragment.lastChild())
return false;
if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
return false;
if (nodeToSplitToAvoidPastingIntoInlineNodesWithStyle(endingSelection().start()))
return false;
RefPtr<Node> nodeAfterInsertionPos = endingSelection().end().downstream().anchorNode();
Text& textNode = downcast<Text>(*fragment.firstChild());
Position start = endingSelection().start();
Position end = replaceSelectedTextInNode(textNode.data());
if (end.isNull())
return false;
if (nodeAfterInsertionPos && nodeAfterInsertionPos->parentNode() && nodeAfterInsertionPos->hasTagName(brTag)
&& shouldRemoveEndBR(nodeAfterInsertionPos.get(), positionBeforeNode(nodeAfterInsertionPos.get())))
removeNodeAndPruneAncestors(*nodeAfterInsertionPos);
VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
if (AXObjectCache::accessibilityEnabled() && editingAction() == EditAction::Paste)
m_visibleSelectionForInsertedText = VisibleSelection(start, end);
setEndingSelection(selectionAfterReplace);
return true;
}
Optional<SimpleRange> ReplaceSelectionCommand::insertedContentRange() const
{
return makeSimpleRange(m_startOfInsertedContent, m_endOfInsertedContent);
}
}