ReplaceSelectionCommand.cpp [plain text]
#include "config.h"
#include "ReplaceSelectionCommand.h"
#include "ApplyStyleCommand.h"
#include "BeforeTextInsertedEvent.h"
#include "BreakBlockquoteCommand.h"
#include "CSSComputedStyleDeclaration.h"
#include "CSSMutableStyleDeclaration.h"
#include "CSSProperty.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "EditingText.h"
#include "Element.h"
#include "EventNames.h"
#include "Frame.h"
#include "HTMLElement.h"
#include "HTMLInputElement.h"
#include "HTMLInterchange.h"
#include "HTMLNames.h"
#include "SelectionController.h"
#include "SmartReplace.h"
#include "TextIterator.h"
#include "htmlediting.h"
#include "markup.h"
#include "visible_units.h"
#include <wtf/StdLibExtras.h>
namespace WebCore {
using namespace HTMLNames;
enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
class ReplacementFragment : Noncopyable {
public:
ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&);
Node* firstChild() const;
Node* lastChild() const;
bool isEmpty() const;
bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
void removeNode(PassRefPtr<Node>);
void removeNodePreservingChildren(Node*);
private:
PassRefPtr<Node> insertFragmentForTestRendering(Node* context);
void removeUnrenderedNodes(Node*);
void restoreTestRenderingNodesToFragment(Node*);
void removeInterchangeNodes(Node*);
void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
RefPtr<Document> m_document;
RefPtr<DocumentFragment> m_fragment;
bool m_matchStyle;
bool m_hasInterchangeNewlineAtStart;
bool m_hasInterchangeNewlineAtEnd;
};
static bool isInterchangeNewlineNode(const Node *node)
{
DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
return node && node->hasTagName(brTag) &&
static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
}
static bool isInterchangeConvertedSpaceSpan(const Node *node)
{
DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
return node->isHTMLElement() &&
static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
}
ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const VisibleSelection& selection)
: m_document(document),
m_fragment(fragment),
m_matchStyle(matchStyle),
m_hasInterchangeNewlineAtStart(false),
m_hasInterchangeNewlineAtEnd(false)
{
if (!m_document)
return;
if (!m_fragment)
return;
if (!m_fragment->firstChild())
return;
Element* editableRoot = selection.rootEditableElement();
ASSERT(editableRoot);
if (!editableRoot)
return;
Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
!(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
editableRoot->isContentRichlyEditable()) {
removeInterchangeNodes(m_fragment.get());
return;
}
Node* styleNode = selection.base().node();
RefPtr<Node> holder = insertFragmentForTestRendering(styleNode);
RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
String text = plainText(range.get());
RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
ExceptionCode ec = 0;
editableRoot->dispatchEvent(evt, ec);
ASSERT(ec == 0);
if (text != evt->text() || !editableRoot->isContentRichlyEditable()) {
restoreTestRenderingNodesToFragment(holder.get());
removeNode(holder);
m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
if (!m_fragment->firstChild())
return;
holder = insertFragmentForTestRendering(styleNode);
}
removeInterchangeNodes(holder.get());
removeUnrenderedNodes(holder.get());
restoreTestRenderingNodesToFragment(holder.get());
removeNode(holder);
}
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)
{
if (!node)
return;
while (RefPtr<Node> n = node->firstChild()) {
removeNode(n);
insertNodeBefore(n.release(), node);
}
removeNode(node);
}
void ReplacementFragment::removeNode(PassRefPtr<Node> node)
{
if (!node)
return;
Node *parent = node->parentNode();
if (!parent)
return;
ExceptionCode ec = 0;
parent->removeChild(node.get(), ec);
ASSERT(ec == 0);
}
void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
{
if (!node || !refNode)
return;
Node* parent = refNode->parentNode();
if (!parent)
return;
ExceptionCode ec = 0;
parent->insertBefore(node, refNode, ec);
ASSERT(ec == 0);
}
PassRefPtr<Node> ReplacementFragment::insertFragmentForTestRendering(Node* context)
{
Node* body = m_document->body();
if (!body)
return 0;
RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
ExceptionCode ec = 0;
Node* n = context;
while (n && !n->isElementNode())
n = n->parentNode();
if (n) {
RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n);
CSSStyleDeclaration* style = holder->style();
style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec);
ASSERT(ec == 0);
style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec);
ASSERT(ec == 0);
}
holder->appendChild(m_fragment, ec);
ASSERT(ec == 0);
body->appendChild(holder.get(), ec);
ASSERT(ec == 0);
m_document->updateLayoutIgnorePendingStylesheets();
return holder.release();
}
void ReplacementFragment::restoreTestRenderingNodesToFragment(Node *holder)
{
if (!holder)
return;
ExceptionCode ec = 0;
while (RefPtr<Node> node = holder->firstChild()) {
holder->removeChild(node.get(), ec);
ASSERT(ec == 0);
m_fragment->appendChild(node.get(), ec);
ASSERT(ec == 0);
}
}
void ReplacementFragment::removeUnrenderedNodes(Node* holder)
{
Vector<Node*> unrendered;
for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
if (!isNodeRendered(node) && !isTableStructureNode(node))
unrendered.append(node);
size_t n = unrendered.size();
for (size_t i = 0; i < n; ++i)
removeNode(unrendered[i]);
}
void ReplacementFragment::removeInterchangeNodes(Node* container)
{
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) {
Node *next = node->traverseNextNode();
if (isInterchangeConvertedSpaceSpan(node)) {
RefPtr<Node> n = 0;
while ((n = node->firstChild())) {
removeNode(n);
insertNodeBefore(n, node);
}
removeNode(node);
if (n)
next = n->traverseNextNode();
}
node = next;
}
}
ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment,
bool selectReplacement, bool smartReplace, bool matchStyle, bool preventNesting, bool movingParagraph,
EditAction editAction)
: CompositeEditCommand(document),
m_selectReplacement(selectReplacement),
m_smartReplace(smartReplace),
m_matchStyle(matchStyle),
m_documentFragment(fragment),
m_preventNesting(preventNesting),
m_movingParagraph(movingParagraph),
m_editAction(editAction),
m_shouldMergeEnd(false)
{
}
static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
{
Position existing = endOfExistingContent.deepEquivalent();
Position inserted = endOfInsertedContent.deepEquivalent();
bool isInsideMailBlockquote = nearestMailBlockquote(inserted.node());
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(true);
if (prev.isNull())
return false;
if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
return true;
return !selectionStartWasStartOfParagraph &&
!fragmentHasInterchangeNewlineAtStart &&
isStartOfParagraph(startOfInsertedContent) &&
!startOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
shouldMerge(startOfInsertedContent, prev);
}
bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
{
VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
VisiblePosition next = endOfInsertedContent.next(true);
if (next.isNull())
return false;
return !selectionEndWasEndOfParagraph &&
isEndOfParagraph(endOfInsertedContent) &&
!endOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
shouldMerge(endOfInsertedContent, next);
}
static bool isMailPasteAsQuotationNode(const Node* node)
{
return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
}
void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = node->traverseNextNode();
if (m_lastLeafInserted == node)
m_lastLeafInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling();
CompositeEditCommand::removeNodePreservingChildren(node);
}
void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node)
{
Node* afterFirst = m_firstNodeInserted ? m_firstNodeInserted->traverseNextSibling() : 0;
Node* afterLast = m_lastLeafInserted ? m_lastLeafInserted->traverseNextSibling() : 0;
CompositeEditCommand::removeNodeAndPruneAncestors(node);
if (m_lastLeafInserted && !m_lastLeafInserted->inDocument())
m_lastLeafInserted = afterLast;
if (m_firstNodeInserted && !m_firstNodeInserted->inDocument())
m_firstNodeInserted = m_lastLeafInserted && m_lastLeafInserted->inDocument() ? afterFirst : 0;
}
static bool isHeaderElement(Node* a)
{
if (!a)
return false;
return a->hasTagName(h1Tag) ||
a->hasTagName(h2Tag) ||
a->hasTagName(h3Tag) ||
a->hasTagName(h4Tag) ||
a->hasTagName(h5Tag);
}
static bool haveSameTagName(Node* a, Node* b)
{
return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName();
}
bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
{
if (source.isNull() || destination.isNull())
return false;
Node* sourceNode = source.deepEquivalent().node();
Node* destinationNode = destination.deepEquivalent().node();
Node* sourceBlock = enclosingBlock(sourceNode);
Node* 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);
}
void ReplaceSelectionCommand::negateStyleRulesThatAffectAppearance()
{
for (RefPtr<Node> node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
if (isStyleSpan(node.get())) {
HTMLElement* e = static_cast<HTMLElement*>(node.get());
if (isBlock(e))
e->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline);
if (e->renderer() && e->renderer()->style()->floating() != FNONE)
e->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone);
}
if (node == m_lastLeafInserted)
break;
}
}
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds()
{
document()->updateLayoutIgnorePendingStylesheets();
if (!m_lastLeafInserted->renderer() &&
m_lastLeafInserted->isTextNode() &&
!enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), selectTag) &&
!enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), scriptTag)) {
if (m_firstNodeInserted == m_lastLeafInserted) {
removeNode(m_lastLeafInserted.get());
m_lastLeafInserted = 0;
m_firstNodeInserted = 0;
return;
}
RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode();
removeNode(m_lastLeafInserted.get());
m_lastLeafInserted = previous;
}
if (!m_firstNodeInserted->renderer() &&
m_firstNodeInserted->isTextNode()) {
if (m_firstNodeInserted == m_lastLeafInserted) {
removeNode(m_firstNodeInserted.get());
m_firstNodeInserted = 0;
m_lastLeafInserted = 0;
return;
}
RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling();
removeNode(m_firstNodeInserted.get());
m_firstNodeInserted = next;
}
}
void ReplaceSelectionCommand::handlePasteAsQuotationNode()
{
Node* node = m_firstNodeInserted.get();
if (isMailPasteAsQuotationNode(node))
removeNodeAttribute(static_cast<Element*>(node), classAttr);
}
VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent()
{
Node* lastNode = m_lastLeafInserted.get();
Node* enclosingSelect = enclosingNodeWithTag(firstDeepEditingPositionForNode(lastNode), selectTag);
if (enclosingSelect)
lastNode = enclosingSelect;
return lastDeepEditingPositionForNode(lastNode);
}
VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent()
{
return VisiblePosition(nextCandidate(positionBeforeNode(m_firstNodeInserted.get())));
}
static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
{
Node* topNode = fragment.firstChild();
if (isMailPasteAsQuotationNode(topNode) || nearestMailBlockquote(topNode))
return false;
if (!isStyleSpan(topNode))
return false;
Node* sourceDocumentStyleSpan = topNode;
RefPtr<Node> copiedRangeStyleSpan = sourceDocumentStyleSpan->firstChild();
RefPtr<CSSMutableStyleDeclaration> styleAtInsertionPos = rangeCompliantEquivalent(insertionPos).computedStyle()->copyInheritableProperties();
String styleText = styleAtInsertionPos->cssText();
if (styleText == static_cast<Element*>(sourceDocumentStyleSpan)->getAttribute(styleAttr)) {
fragment.removeNodePreservingChildren(sourceDocumentStyleSpan);
if (!isStyleSpan(copiedRangeStyleSpan.get()))
return true;
}
if (isStyleSpan(copiedRangeStyleSpan.get()) && styleText == static_cast<Element*>(copiedRangeStyleSpan.get())->getAttribute(styleAttr)) {
fragment.removeNodePreservingChildren(copiedRangeStyleSpan.get());
return true;
}
return false;
}
void ReplaceSelectionCommand::handleStyleSpans()
{
Node* sourceDocumentStyleSpan = 0;
Node* copiedRangeStyleSpan = 0;
for (Node* node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
if (isStyleSpan(node)) {
sourceDocumentStyleSpan = node;
if (isStyleSpan(node->firstChild()))
copiedRangeStyleSpan = node->firstChild();
break;
}
}
if (!sourceDocumentStyleSpan)
return;
RefPtr<CSSMutableStyleDeclaration> sourceDocumentStyle = static_cast<HTMLElement*>(sourceDocumentStyleSpan)->getInlineStyleDecl()->copy();
Node* context = sourceDocumentStyleSpan->parentNode();
Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : nearestMailBlockquote(context);
if (blockquoteNode) {
RefPtr<CSSMutableStyleDeclaration> blockquoteStyle = computedStyle(blockquoteNode)->copyInheritableProperties();
RefPtr<CSSMutableStyleDeclaration> parentStyle = computedStyle(blockquoteNode->parentNode())->copyInheritableProperties();
parentStyle->diff(blockquoteStyle.get());
CSSMutableStyleDeclaration::const_iterator end = blockquoteStyle->end();
for (CSSMutableStyleDeclaration::const_iterator it = blockquoteStyle->begin(); it != end; ++it) {
const CSSProperty& property = *it;
sourceDocumentStyle->removeProperty(property.id());
}
context = blockquoteNode->parentNode();
}
RefPtr<CSSMutableStyleDeclaration> contextStyle = computedStyle(context)->copyInheritableProperties();
contextStyle->diff(sourceDocumentStyle.get());
sourceDocumentStyle->removeBlockProperties();
if (sourceDocumentStyle->length() == 0 && !copiedRangeStyleSpan) {
removeNodePreservingChildren(sourceDocumentStyleSpan);
return;
}
if (sourceDocumentStyle->length() > 0 && !copiedRangeStyleSpan) {
setNodeAttribute(static_cast<Element*>(sourceDocumentStyleSpan), styleAttr, sourceDocumentStyle->cssText());
return;
}
RefPtr<CSSMutableStyleDeclaration> copiedRangeStyle = static_cast<HTMLElement*>(copiedRangeStyleSpan)->getInlineStyleDecl()->copy();
sourceDocumentStyle->merge(copiedRangeStyle.get(), true);
copiedRangeStyle = sourceDocumentStyle;
removeNodePreservingChildren(sourceDocumentStyleSpan);
context = copiedRangeStyleSpan->parentNode();
contextStyle = computedStyle(context)->copyInheritableProperties();
contextStyle->diff(copiedRangeStyle.get());
copiedRangeStyle->removeBlockProperties();
if (copiedRangeStyle->length() == 0) {
removeNodePreservingChildren(copiedRangeStyleSpan);
return;
}
setNodeAttribute(static_cast<Element*>(copiedRangeStyleSpan), styleAttr, copiedRangeStyle->cssText());
}
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();
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
if (mergeForward) {
m_lastLeafInserted = destination.previous().deepEquivalent().node();
if (!m_firstNodeInserted->inDocument())
m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().node();
}
}
void ReplaceSelectionCommand::doApply()
{
VisibleSelection selection = endingSelection();
ASSERT(selection.isCaretOrRange());
ASSERT(selection.start().node());
if (selection.isNone() || !selection.start().node())
return;
bool selectionIsPlainText = !selection.isContentRichlyEditable();
Element* currentRoot = selection.rootEditableElement();
ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
if (performTrivialReplace(fragment))
return;
if (m_matchStyle)
m_insertionStyle = styleAtPosition(selection.start());
VisiblePosition visibleStart = selection.visibleStart();
VisiblePosition visibleEnd = selection.visibleEnd();
bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().node());
Position insertionPos = selection.start();
bool startIsInsideMailBlockquote = nearestMailBlockquote(insertionPos.node());
if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
startBlock == currentRoot ||
(startBlock && startBlock->renderer() && startBlock->renderer()->isListItem()) ||
selectionIsPlainText)
m_preventNesting = false;
if (selection.isRange()) {
bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
deleteSelection(false, mergeBlocksAfterDelete, true, false);
visibleStart = endingSelection().visibleStart();
if (fragment.hasInterchangeNewlineAtStart()) {
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
if (!isEndOfDocument(visibleStart))
setEndingSelection(visibleStart.next());
} else
insertParagraphSeparator();
}
insertionPos = endingSelection().start();
} else {
ASSERT(selection.isCaret());
if (fragment.hasInterchangeNewlineAtStart()) {
VisiblePosition next = visibleStart.next(true);
if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
setEndingSelection(next);
else
insertParagraphSeparator();
}
if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
insertParagraphSeparator();
setEndingSelection(endingSelection().visibleStart().previous());
}
insertionPos = endingSelection().start();
}
if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
applyCommandToComposite(BreakBlockquoteCommand::create(document()));
Node* br = endingSelection().start().node();
ASSERT(br->hasTagName(brTag));
insertionPos = positionBeforeNode(br);
removeNode(br);
}
prepareWhitespaceAtPositionForSplit(insertionPos);
Node* endBR = insertionPos.downstream().node()->hasTagName(brTag) ? insertionPos.downstream().node() : 0;
VisiblePosition originalVisPosBeforeEndBR;
if (endBR)
originalVisPosBeforeEndBR = VisiblePosition(endBR, 0, DOWNSTREAM).previous();
startBlock = enclosingBlock(insertionPos.node());
if (m_preventNesting && startBlock && !startIsInsideMailBlockquote) {
ASSERT(startBlock != currentRoot);
VisiblePosition visibleInsertionPos(insertionPos);
if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
insertionPos = positionAfterNode(startBlock);
else if (isStartOfBlock(visibleInsertionPos))
insertionPos = positionBeforeNode(startBlock);
}
insertionPos = positionOutsideTabSpan(insertionPos);
insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
if (Frame* frame = document()->frame())
frame->clearTypingStyle();
bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
if (fragment.isEmpty() || !fragment.firstChild())
return;
VisiblePosition startOfInsertedContent, endOfInsertedContent;
RefPtr<Node> refNode = fragment.firstChild();
RefPtr<Node> node = refNode->nextSibling();
fragment.removeNode(refNode);
insertNodeAtAndUpdateNodesInserted(refNode, insertionPos);
if (!refNode->inDocument())
return;
while (node) {
Node* next = node->nextSibling();
fragment.removeNode(node);
insertNodeAfterAndUpdateNodesInserted(node, refNode.get());
if (!node->inDocument())
return;
refNode = node;
node = next;
}
removeUnrenderedTextNodesAtEnds();
negateStyleRulesThatAffectAppearance();
if (!handledStyleSpans)
handleStyleSpans();
if (!m_firstNodeInserted || !m_firstNodeInserted->inDocument())
return;
endOfInsertedContent = positionAtEndOfInsertedContent();
startOfInsertedContent = positionAtStartOfInsertedContent();
if (startBlock && insertionPos.node() == startBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
Position lastPositionToSelect;
bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd();
if (shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))
removeNodeAndPruneAncestors(endBR);
m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
VisiblePosition destination = startOfInsertedContent.previous();
VisiblePosition startOfParagraphToMove = startOfInsertedContent;
VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
if (!startOfParagraphToMove.deepEquivalent().node()->inDocument())
return;
}
moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().downstream().node();
if (!m_lastLeafInserted->inDocument())
m_lastLeafInserted = endingSelection().visibleEnd().deepEquivalent().upstream().node();
}
endOfInsertedContent = positionAtEndOfInsertedContent();
startOfInsertedContent = positionAtStartOfInsertedContent();
if (interchangeNewlineAtEnd) {
VisiblePosition next = endOfInsertedContent.next(true);
if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
if (!isStartOfParagraph(endOfInsertedContent)) {
setEndingSelection(endOfInsertedContent);
insertParagraphSeparator(true);
lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
updateNodesInserted(lastPositionToSelect.node());
}
} else {
lastPositionToSelect = next.deepEquivalent().downstream();
}
} else
mergeEndIfNeeded();
handlePasteAsQuotationNode();
endOfInsertedContent = positionAtEndOfInsertedContent();
startOfInsertedContent = positionAtStartOfInsertedContent();
if (m_smartReplace && currentRoot) {
Node* start = currentRoot->shadowAncestorNode();
if (start->hasTagName(inputTag) && static_cast<HTMLInputElement*>(start)->inputType() == HTMLInputElement::PASSWORD)
m_smartReplace = false;
}
if (m_smartReplace) {
bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) &&
!isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false);
if (needsTrailingSpace) {
RenderObject* renderer = m_lastLeafInserted->renderer();
bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
Node* endNode = positionAtEndOfInsertedContent().deepEquivalent().upstream().node();
if (endNode->isTextNode()) {
Text* text = static_cast<Text*>(endNode);
insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " ");
} else {
RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
insertNodeAfterAndUpdateNodesInserted(node, endNode);
}
}
bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) &&
!isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true);
if (needsLeadingSpace) {
RenderObject* renderer = m_lastLeafInserted->renderer();
bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
Node* startNode = positionAtStartOfInsertedContent().deepEquivalent().downstream().node();
if (startNode->isTextNode()) {
Text* text = static_cast<Text*>(startNode);
insertTextIntoNode(text, 0, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
} else {
RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
insertNodeBefore(node, startNode);
m_firstNodeInserted = node;
}
}
}
completeHTMLReplacement(lastPositionToSelect);
}
bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
{
if (!endBR || !endBR->inDocument())
return false;
VisiblePosition visiblePos(Position(endBR, 0));
if (visiblePos.previous() == originalVisPosBeforeEndBR)
return false;
if (!document()->inStrictMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
return true;
return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
}
void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
{
Position start;
Position end;
if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastLeafInserted && m_lastLeafInserted->inDocument()) {
start = positionAtStartOfInsertedContent().deepEquivalent();
end = positionAtEndOfInsertedContent().deepEquivalent();
rebalanceWhitespaceAt(start);
rebalanceWhitespaceAt(end);
if (m_matchStyle) {
ASSERT(m_insertionStyle);
applyStyle(m_insertionStyle.get(), start, end);
}
if (lastPositionToSelect.isNotNull())
end = lastPositionToSelect;
} else if (lastPositionToSelect.isNotNull())
start = end = lastPositionToSelect;
else
return;
if (m_selectReplacement)
setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY));
else
setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY));
}
EditAction ReplaceSelectionCommand::editingAction() const
{
return m_editAction;
}
void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
{
Node* nodeToUpdate = insertChild.get(); insertNodeAfter(insertChild, refChild);
updateNodesInserted(nodeToUpdate);
}
void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild, const Position& p)
{
Node* nodeToUpdate = insertChild.get(); insertNodeAt(insertChild, p);
updateNodesInserted(nodeToUpdate);
}
void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
{
Node* nodeToUpdate = insertChild.get(); insertNodeBefore(insertChild, refChild);
updateNodesInserted(nodeToUpdate);
}
void ReplaceSelectionCommand::updateNodesInserted(Node *node)
{
if (!node)
return;
if (!m_firstNodeInserted)
m_firstNodeInserted = node;
if (node == m_lastLeafInserted)
return;
m_lastLeafInserted = node->lastDescendant();
}
bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
{
if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
return false;
if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
return false;
Text* textNode = static_cast<Text*>(fragment.firstChild());
String text(textNode->data());
Position start = endingSelection().start();
Position end = endingSelection().end();
if (start.anchorNode() != end.anchorNode() || !start.anchorNode()->isTextNode())
return false;
replaceTextInNode(static_cast<Text*>(start.anchorNode()), start.offsetInContainerNode(), end.offsetInContainerNode() - start.offsetInContainerNode(), text);
end = Position(start.anchorNode(), start.offsetInContainerNode() + text.length());
VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
setEndingSelection(selectionAfterReplace);
return true;
}
}