CompositeEditCommand.cpp [plain text]
#include "config.h"
#include "CompositeEditCommand.h"
#include "AppendNodeCommand.h"
#include "ApplyStyleCommand.h"
#include "DeleteFromTextNodeCommand.h"
#include "DeleteSelectionCommand.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "DocumentMarkerController.h"
#include "EditorInsertAction.h"
#include "Frame.h"
#include "HTMLElement.h"
#include "HTMLNames.h"
#include "InlineTextBox.h"
#include "InsertIntoTextNodeCommand.h"
#include "InsertLineBreakCommand.h"
#include "InsertNodeBeforeCommand.h"
#include "InsertParagraphSeparatorCommand.h"
#include "InsertTextCommand.h"
#include "JoinTextNodesCommand.h"
#include "MergeIdenticalElementsCommand.h"
#include "Range.h"
#include "RemoveCSSPropertyCommand.h"
#include "RemoveNodeCommand.h"
#include "RemoveNodePreservingChildrenCommand.h"
#include "ReplaceNodeWithSpanCommand.h"
#include "ReplaceSelectionCommand.h"
#include "RenderBlock.h"
#include "RenderText.h"
#include "SetNodeAttributeCommand.h"
#include "SplitElementCommand.h"
#include "SplitTextNodeCommand.h"
#include "SplitTextNodeContainingElementCommand.h"
#include "Text.h"
#include "TextIterator.h"
#include "WrapContentsInDummySpanCommand.h"
#include "htmlediting.h"
#include "markup.h"
#include "visible_units.h"
#include <wtf/unicode/CharacterNames.h>
using namespace std;
namespace WebCore {
using namespace HTMLNames;
CompositeEditCommand::CompositeEditCommand(Document *document)
: EditCommand(document)
{
}
CompositeEditCommand::~CompositeEditCommand()
{
}
void CompositeEditCommand::doUnapply()
{
size_t size = m_commands.size();
for (size_t i = size; i != 0; --i)
m_commands[i - 1]->unapply();
}
void CompositeEditCommand::doReapply()
{
size_t size = m_commands.size();
for (size_t i = 0; i != size; ++i)
m_commands[i]->reapply();
}
void CompositeEditCommand::applyCommandToComposite(PassRefPtr<EditCommand> cmd)
{
cmd->setParent(this);
cmd->apply();
m_commands.append(cmd);
}
void CompositeEditCommand::applyStyle(const EditingStyle* style, EditAction editingAction)
{
applyCommandToComposite(ApplyStyleCommand::create(document(), style, editingAction));
}
void CompositeEditCommand::applyStyle(const EditingStyle* style, const Position& start, const Position& end, EditAction editingAction)
{
applyCommandToComposite(ApplyStyleCommand::create(document(), style, start, end, editingAction));
}
void CompositeEditCommand::applyStyledElement(PassRefPtr<Element> element)
{
applyCommandToComposite(ApplyStyleCommand::create(element, false));
}
void CompositeEditCommand::removeStyledElement(PassRefPtr<Element> element)
{
applyCommandToComposite(ApplyStyleCommand::create(element, true));
}
void CompositeEditCommand::insertParagraphSeparator(bool useDefaultParagraphElement)
{
applyCommandToComposite(InsertParagraphSeparatorCommand::create(document(), useDefaultParagraphElement));
}
void CompositeEditCommand::insertLineBreak()
{
applyCommandToComposite(InsertLineBreakCommand::create(document()));
}
void CompositeEditCommand::insertNodeBefore(PassRefPtr<Node> insertChild, PassRefPtr<Node> refChild)
{
ASSERT(!refChild->hasTagName(bodyTag));
applyCommandToComposite(InsertNodeBeforeCommand::create(insertChild, refChild));
}
void CompositeEditCommand::insertNodeAfter(PassRefPtr<Node> insertChild, PassRefPtr<Node> refChild)
{
ASSERT(insertChild);
ASSERT(refChild);
ASSERT(!refChild->hasTagName(bodyTag));
ContainerNode* parent = refChild->parentNode();
ASSERT(parent);
if (parent->lastChild() == refChild)
appendNode(insertChild, parent);
else {
ASSERT(refChild->nextSibling());
insertNodeBefore(insertChild, refChild->nextSibling());
}
}
void CompositeEditCommand::insertNodeAt(PassRefPtr<Node> insertChild, const Position& editingPosition)
{
ASSERT(isEditablePosition(editingPosition));
Position p = editingPosition.parentAnchoredEquivalent();
Node* refChild = p.deprecatedNode();
int offset = p.deprecatedEditingOffset();
if (canHaveChildrenForEditing(refChild)) {
Node* child = refChild->firstChild();
for (int i = 0; child && i < offset; i++)
child = child->nextSibling();
if (child)
insertNodeBefore(insertChild, child);
else
appendNode(insertChild, static_cast<Element*>(refChild));
} else if (caretMinOffset(refChild) >= offset)
insertNodeBefore(insertChild, refChild);
else if (refChild->isTextNode() && caretMaxOffset(refChild) > offset) {
splitTextNode(static_cast<Text *>(refChild), offset);
if (!refChild->inDocument())
return;
insertNodeBefore(insertChild, refChild);
} else
insertNodeAfter(insertChild, refChild);
}
void CompositeEditCommand::appendNode(PassRefPtr<Node> node, PassRefPtr<ContainerNode> parent)
{
ASSERT(canHaveChildrenForEditing(parent.get()));
applyCommandToComposite(AppendNodeCommand::create(parent, node));
}
void CompositeEditCommand::removeChildrenInRange(PassRefPtr<Node> node, unsigned from, unsigned to)
{
Vector<RefPtr<Node> > children;
Node* child = node->childNode(from);
for (unsigned i = from; child && i < to; i++, child = child->nextSibling())
children.append(child);
size_t size = children.size();
for (size_t i = 0; i < size; ++i)
removeNode(children[i].release());
}
void CompositeEditCommand::removeNode(PassRefPtr<Node> node)
{
if (!node || !node->parentNode())
return;
applyCommandToComposite(RemoveNodeCommand::create(node));
}
void CompositeEditCommand::removeNodePreservingChildren(PassRefPtr<Node> node)
{
applyCommandToComposite(RemoveNodePreservingChildrenCommand::create(node));
}
void CompositeEditCommand::removeNodeAndPruneAncestors(PassRefPtr<Node> node)
{
RefPtr<ContainerNode> parent = node->parentNode();
removeNode(node);
prune(parent.release());
}
HTMLElement* CompositeEditCommand::replaceElementWithSpanPreservingChildrenAndAttributes(PassRefPtr<HTMLElement> node)
{
RefPtr<ReplaceNodeWithSpanCommand> command = ReplaceNodeWithSpanCommand::create(node);
applyCommandToComposite(command);
ASSERT(command->spanElement()->inDocument());
return command->spanElement();
}
static bool hasARenderedDescendant(Node* node)
{
Node* n = node->firstChild();
while (n) {
if (n->renderer())
return true;
n = n->traverseNextNode(node);
}
return false;
}
void CompositeEditCommand::prune(PassRefPtr<Node> node)
{
while (node) {
RenderObject* renderer = node->renderer();
if (renderer && (!renderer->canHaveChildren() || hasARenderedDescendant(node.get()) || node->rootEditableElement() == node))
return;
RefPtr<ContainerNode> next = node->parentNode();
removeNode(node);
node = next;
}
}
void CompositeEditCommand::splitTextNode(PassRefPtr<Text> node, unsigned offset)
{
applyCommandToComposite(SplitTextNodeCommand::create(node, offset));
}
void CompositeEditCommand::splitElement(PassRefPtr<Element> element, PassRefPtr<Node> atChild)
{
applyCommandToComposite(SplitElementCommand::create(element, atChild));
}
void CompositeEditCommand::mergeIdenticalElements(PassRefPtr<Element> prpFirst, PassRefPtr<Element> prpSecond)
{
RefPtr<Element> first = prpFirst;
RefPtr<Element> second = prpSecond;
ASSERT(!first->isDescendantOf(second.get()) && second != first);
if (first->nextSibling() != second) {
removeNode(second);
insertNodeAfter(second, first);
}
applyCommandToComposite(MergeIdenticalElementsCommand::create(first, second));
}
void CompositeEditCommand::wrapContentsInDummySpan(PassRefPtr<Element> element)
{
applyCommandToComposite(WrapContentsInDummySpanCommand::create(element));
}
void CompositeEditCommand::splitTextNodeContainingElement(PassRefPtr<Text> text, unsigned offset)
{
applyCommandToComposite(SplitTextNodeContainingElementCommand::create(text, offset));
}
void CompositeEditCommand::joinTextNodes(PassRefPtr<Text> text1, PassRefPtr<Text> text2)
{
applyCommandToComposite(JoinTextNodesCommand::create(text1, text2));
}
void CompositeEditCommand::inputText(const String& text, bool selectInsertedText)
{
unsigned offset = 0;
unsigned length = text.length();
RefPtr<Range> startRange = Range::create(document(), firstPositionInNode(document()->documentElement()), endingSelection().start());
unsigned startIndex = TextIterator::rangeLength(startRange.get());
size_t newline;
do {
newline = text.find('\n', offset);
if (newline != offset) {
RefPtr<InsertTextCommand> command = InsertTextCommand::create(document());
applyCommandToComposite(command);
int substringLength = newline == notFound ? length - offset : newline - offset;
command->input(text.substring(offset, substringLength), false);
}
if (newline != notFound)
insertLineBreak();
offset = newline + 1;
} while (newline != notFound && offset != length);
if (selectInsertedText) {
RefPtr<Range> selectedRange = TextIterator::rangeFromLocationAndLength(document()->documentElement(), startIndex, length);
setEndingSelection(VisibleSelection(selectedRange.get()));
}
}
void CompositeEditCommand::insertTextIntoNode(PassRefPtr<Text> node, unsigned offset, const String& text)
{
applyCommandToComposite(InsertIntoTextNodeCommand::create(node, offset, text));
}
void CompositeEditCommand::deleteTextFromNode(PassRefPtr<Text> node, unsigned offset, unsigned count)
{
applyCommandToComposite(DeleteFromTextNodeCommand::create(node, offset, count));
}
void CompositeEditCommand::replaceTextInNode(PassRefPtr<Text> node, unsigned offset, unsigned count, const String& replacementText)
{
applyCommandToComposite(DeleteFromTextNodeCommand::create(node.get(), offset, count));
applyCommandToComposite(InsertIntoTextNodeCommand::create(node, offset, replacementText));
}
void CompositeEditCommand::replaceTextInNodePreservingMarkers(PassRefPtr<Text> prpNode, unsigned offset, unsigned count, const String& replacementText)
{
RefPtr<Text> node(prpNode);
DocumentMarkerController* markerController = document()->markers();
Vector<DocumentMarker> markers = markerController->markersInRange(Range::create(document(), node, offset, node, offset + count).get(), DocumentMarker::AllMarkers());
replaceTextInNode(node, offset, count, replacementText);
RefPtr<Range> newRange = Range::create(document(), node, offset, node, offset + replacementText.length());
for (size_t i = 0; i < markers.size(); ++i)
markerController->addMarker(newRange.get(), markers[i].type, markers[i].description);
}
Position CompositeEditCommand::positionOutsideTabSpan(const Position& pos)
{
if (!isTabSpanTextNode(pos.anchorNode()))
return pos;
if (pos.anchorType() == Position::PositionIsAfterAnchor)
return positionInParentAfterNode(pos.anchorNode());
if (pos.anchorType() == Position::PositionIsBeforeAnchor)
return positionInParentBeforeNode(pos.anchorNode());
Node* tabSpan = tabSpanNode(pos.containerNode());
if (pos.offsetInContainerNode() <= caretMinOffset(pos.containerNode()))
return positionInParentBeforeNode(tabSpan);
if (pos.offsetInContainerNode() >= caretMaxOffset(pos.containerNode()))
return positionInParentAfterNode(tabSpan);
splitTextNodeContainingElement(static_cast<Text *>(pos.containerNode()), pos.offsetInContainerNode());
return positionInParentBeforeNode(tabSpan);
}
void CompositeEditCommand::insertNodeAtTabSpanPosition(PassRefPtr<Node> node, const Position& pos)
{
insertNodeAt(node, positionOutsideTabSpan(pos));
}
void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
{
if (endingSelection().isRange())
applyCommandToComposite(DeleteSelectionCommand::create(document(), smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements));
}
void CompositeEditCommand::deleteSelection(const VisibleSelection &selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements)
{
if (selection.isRange())
applyCommandToComposite(DeleteSelectionCommand::create(selection, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements));
}
void CompositeEditCommand::removeCSSProperty(PassRefPtr<StyledElement> element, CSSPropertyID property)
{
applyCommandToComposite(RemoveCSSPropertyCommand::create(document(), element, property));
}
void CompositeEditCommand::removeNodeAttribute(PassRefPtr<Element> element, const QualifiedName& attribute)
{
setNodeAttribute(element, attribute, AtomicString());
}
void CompositeEditCommand::setNodeAttribute(PassRefPtr<Element> element, const QualifiedName& attribute, const AtomicString& value)
{
applyCommandToComposite(SetNodeAttributeCommand::create(element, attribute, value));
}
static inline bool containsOnlyWhitespace(const String& text)
{
for (unsigned i = 0; i < text.length(); ++i) {
if (!isWhitespace(text.characters()[i]))
return false;
}
return true;
}
bool CompositeEditCommand::shouldRebalanceLeadingWhitespaceFor(const String& text) const
{
return containsOnlyWhitespace(text);
}
bool CompositeEditCommand::canRebalance(const Position& position) const
{
Node* node = position.containerNode();
if (position.anchorType() != Position::PositionIsOffsetInAnchor || !node || !node->isTextNode())
return false;
Text* textNode = static_cast<Text*>(node);
if (textNode->length() == 0)
return false;
RenderObject* renderer = textNode->renderer();
if (renderer && !renderer->style()->collapseWhiteSpace())
return false;
return true;
}
void CompositeEditCommand::rebalanceWhitespaceAt(const Position& position)
{
Node* node = position.containerNode();
if (!canRebalance(position))
return;
int offset = position.deprecatedEditingOffset();
String text = static_cast<Text*>(node)->data();
if (!isWhitespace(text[offset])) {
offset--;
if (offset < 0 || !isWhitespace(text[offset]))
return;
}
rebalanceWhitespaceOnTextSubstring(static_cast<Text*>(node), position.offsetInContainerNode(), position.offsetInContainerNode());
}
void CompositeEditCommand::rebalanceWhitespaceOnTextSubstring(RefPtr<Text> textNode, int startOffset, int endOffset)
{
String text = textNode->data();
ASSERT(!text.isEmpty());
int upstream = startOffset;
while (upstream > 0 && isWhitespace(text[upstream - 1]))
upstream--;
int downstream = endOffset;
while ((unsigned)downstream < text.length() && isWhitespace(text[downstream]))
downstream++;
int length = downstream - upstream;
if (!length)
return;
VisiblePosition visibleUpstreamPos(Position(textNode, upstream, Position::PositionIsOffsetInAnchor));
VisiblePosition visibleDownstreamPos(Position(textNode, downstream, Position::PositionIsOffsetInAnchor));
String string = text.substring(upstream, length);
String rebalancedString = stringWithRebalancedWhitespace(string,
isStartOfParagraph(visibleUpstreamPos) || upstream == 0,
isEndOfParagraph(visibleDownstreamPos) || (unsigned)downstream == text.length());
if (string != rebalancedString)
replaceTextInNodePreservingMarkers(textNode, upstream, length, rebalancedString);
}
void CompositeEditCommand::prepareWhitespaceAtPositionForSplit(Position& position)
{
Node* node = position.deprecatedNode();
if (!node || !node->isTextNode())
return;
Text* textNode = static_cast<Text*>(node);
if (textNode->length() == 0)
return;
RenderObject* renderer = textNode->renderer();
if (renderer && !renderer->style()->collapseWhiteSpace())
return;
Position upstreamPos = position.upstream();
deleteInsignificantText(position.upstream(), position.downstream());
position = upstreamPos.downstream();
VisiblePosition visiblePos(position);
VisiblePosition previousVisiblePos(visiblePos.previous());
Position previous(previousVisiblePos.deepEquivalent());
if (isCollapsibleWhitespace(previousVisiblePos.characterAfter()) && previous.deprecatedNode()->isTextNode() && !previous.deprecatedNode()->hasTagName(brTag))
replaceTextInNodePreservingMarkers(static_cast<Text*>(previous.deprecatedNode()), previous.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
if (isCollapsibleWhitespace(visiblePos.characterAfter()) && position.deprecatedNode()->isTextNode() && !position.deprecatedNode()->hasTagName(brTag))
replaceTextInNodePreservingMarkers(static_cast<Text*>(position.deprecatedNode()), position.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
}
void CompositeEditCommand::rebalanceWhitespace()
{
VisibleSelection selection = endingSelection();
if (selection.isNone())
return;
rebalanceWhitespaceAt(selection.start());
if (selection.isRange())
rebalanceWhitespaceAt(selection.end());
}
void CompositeEditCommand::deleteInsignificantText(PassRefPtr<Text> textNode, unsigned start, unsigned end)
{
if (!textNode || start >= end)
return;
RenderText* textRenderer = toRenderText(textNode->renderer());
if (!textRenderer)
return;
Vector<InlineTextBox*> sortedTextBoxes;
size_t sortedTextBoxesPosition = 0;
for (InlineTextBox* textBox = textRenderer->firstTextBox(); textBox; textBox = textBox->nextTextBox())
sortedTextBoxes.append(textBox);
if (textRenderer->containsReversedText())
std::sort(sortedTextBoxes.begin(), sortedTextBoxes.end(), InlineTextBox::compareByStart);
InlineTextBox* box = sortedTextBoxes.isEmpty() ? 0 : sortedTextBoxes[sortedTextBoxesPosition];
if (!box) {
removeNode(textNode);
return;
}
unsigned length = textNode->length();
if (start >= length || end > length)
return;
unsigned removed = 0;
InlineTextBox* prevBox = 0;
String str;
while (prevBox || box) {
unsigned gapStart = prevBox ? prevBox->start() + prevBox->len() : 0;
if (end < gapStart)
break;
unsigned gapEnd = box ? box->start() : length;
bool indicesIntersect = start <= gapEnd && end >= gapStart;
int gapLen = gapEnd - gapStart;
if (indicesIntersect && gapLen > 0) {
gapStart = max(gapStart, start);
gapEnd = min(gapEnd, end);
if (str.isNull())
str = textNode->data().substring(start, end - start);
str.remove(gapStart - start - removed, gapLen);
removed += gapLen;
}
prevBox = box;
if (box) {
if (++sortedTextBoxesPosition < sortedTextBoxes.size())
box = sortedTextBoxes[sortedTextBoxesPosition];
else
box = 0;
}
}
if (!str.isNull()) {
if (!str.isEmpty())
replaceTextInNode(textNode, start, end - start, str);
else {
ASSERT(start > 0 || end - start < textNode->length());
deleteTextFromNode(textNode, start, end - start);
}
}
}
void CompositeEditCommand::deleteInsignificantText(const Position& start, const Position& end)
{
if (start.isNull() || end.isNull())
return;
if (comparePositions(start, end) >= 0)
return;
Node* next;
for (Node* node = start.deprecatedNode(); node; node = next) {
next = node->traverseNextNode();
if (node->isTextNode()) {
Text* textNode = static_cast<Text*>(node);
int startOffset = node == start.deprecatedNode() ? start.deprecatedEditingOffset() : 0;
int endOffset = node == end.deprecatedNode() ? end.deprecatedEditingOffset() : static_cast<int>(textNode->length());
deleteInsignificantText(textNode, startOffset, endOffset);
}
if (node == end.deprecatedNode())
break;
}
}
void CompositeEditCommand::deleteInsignificantTextDownstream(const Position& pos)
{
Position end = VisiblePosition(pos, VP_DEFAULT_AFFINITY).next().deepEquivalent().downstream();
deleteInsignificantText(pos, end);
}
PassRefPtr<Node> CompositeEditCommand::appendBlockPlaceholder(PassRefPtr<Element> container)
{
if (!container)
return 0;
ASSERT(container->renderer());
RefPtr<Node> placeholder = createBlockPlaceholderElement(document());
appendNode(placeholder, container);
return placeholder.release();
}
PassRefPtr<Node> CompositeEditCommand::insertBlockPlaceholder(const Position& pos)
{
if (pos.isNull())
return 0;
ASSERT(pos.deprecatedNode()->renderer());
RefPtr<Node> placeholder = createBlockPlaceholderElement(document());
insertNodeAt(placeholder, pos);
return placeholder.release();
}
PassRefPtr<Node> CompositeEditCommand::addBlockPlaceholderIfNeeded(Element* container)
{
if (!container)
return 0;
updateLayout();
RenderObject* renderer = container->renderer();
if (!renderer || !renderer->isBlockFlow())
return 0;
RenderBlock* block = toRenderBlock(renderer);
if (block->height() == 0 || (block->isListItem() && block->isEmpty()))
return appendBlockPlaceholder(container);
return 0;
}
void CompositeEditCommand::removePlaceholderAt(const Position& p)
{
ASSERT(lineBreakExistsAtPosition(p));
if (p.anchorNode()->hasTagName(brTag)) {
removeNode(p.anchorNode());
return;
}
deleteTextFromNode(static_cast<Text*>(p.anchorNode()), p.offsetInContainerNode(), 1);
}
PassRefPtr<Node> CompositeEditCommand::insertNewDefaultParagraphElementAt(const Position& position)
{
RefPtr<Element> paragraphElement = createDefaultParagraphElement(document());
ExceptionCode ec;
paragraphElement->appendChild(createBreakElement(document()), ec);
insertNodeAt(paragraphElement, position);
return paragraphElement.release();
}
PassRefPtr<Node> CompositeEditCommand::moveParagraphContentsToNewBlockIfNecessary(const Position& pos)
{
if (pos.isNull())
return 0;
updateLayout();
VisiblePosition visiblePos(pos, VP_DEFAULT_AFFINITY);
VisiblePosition visibleParagraphStart(startOfParagraph(visiblePos));
VisiblePosition visibleParagraphEnd = endOfParagraph(visiblePos);
VisiblePosition next = visibleParagraphEnd.next();
VisiblePosition visibleEnd = next.isNotNull() ? next : visibleParagraphEnd;
Position upstreamStart = visibleParagraphStart.deepEquivalent().upstream();
Position upstreamEnd = visibleEnd.deepEquivalent().upstream();
if (comparePositions(pos, upstreamStart) < 0)
return 0;
if (isBlock(upstreamStart.deprecatedNode())) {
if (upstreamStart.deprecatedNode() == editableRootForPosition(upstreamStart)) {
if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(upstreamStart.deprecatedNode()->renderer()))
return insertNewDefaultParagraphElementAt(upstreamStart);
} else if (isBlock(upstreamEnd.deprecatedNode())) {
if (!upstreamEnd.deprecatedNode()->isDescendantOf(upstreamStart.deprecatedNode())) {
return 0;
}
} else if (enclosingBlock(upstreamEnd.deprecatedNode()) != upstreamStart.deprecatedNode()) {
ASSERT(upstreamStart.deprecatedNode()->isDescendantOf(enclosingBlock(upstreamEnd.deprecatedNode())));
return 0;
} else if (isEndOfDocument(visibleEnd)) {
return 0;
}
}
RefPtr<Node> newBlock = insertNewDefaultParagraphElementAt(upstreamStart);
bool endWasBr = visibleParagraphEnd.deepEquivalent().deprecatedNode()->hasTagName(brTag);
moveParagraphs(visibleParagraphStart, visibleParagraphEnd, VisiblePosition(firstPositionInNode(newBlock.get())));
if (newBlock->lastChild() && newBlock->lastChild()->hasTagName(brTag) && !endWasBr)
removeNode(newBlock->lastChild());
return newBlock.release();
}
void CompositeEditCommand::pushAnchorElementDown(Node* anchorNode)
{
if (!anchorNode)
return;
ASSERT(anchorNode->isLink());
setEndingSelection(VisibleSelection::selectionFromContentsOfNode(anchorNode));
applyStyledElement(static_cast<Element*>(anchorNode));
if (anchorNode->inDocument())
removeNodePreservingChildren(anchorNode);
}
void CompositeEditCommand::cloneParagraphUnderNewElement(Position& start, Position& end, Node* outerNode, Element* blockElement)
{
RefPtr<Node> topNode = outerNode->cloneNode(isTableElement(outerNode));
appendNode(topNode, blockElement);
RefPtr<Node> lastNode = topNode;
if (start.deprecatedNode() != outerNode) {
Vector<RefPtr<Node> > ancestors;
for (Node* n = start.deprecatedNode(); n && n != outerNode; n = n->parentNode())
ancestors.append(n);
for (size_t i = ancestors.size(); i != 0; --i) {
Node* item = ancestors[i - 1].get();
RefPtr<Node> child = item->cloneNode(isTableElement(item));
appendNode(child, static_cast<Element *>(lastNode.get()));
lastNode = child.release();
}
}
if (start.deprecatedNode() != end.deprecatedNode() && !start.deprecatedNode()->isDescendantOf(end.deprecatedNode())) {
while (!end.deprecatedNode()->isDescendantOf(outerNode)) {
outerNode = outerNode->parentNode();
topNode = topNode->parentNode();
}
for (Node* n = start.deprecatedNode()->traverseNextSibling(outerNode); n; n = n->traverseNextSibling(outerNode)) {
if (n->parentNode() != start.deprecatedNode()->parentNode())
lastNode = topNode->lastChild();
RefPtr<Node> clonedNode = n->cloneNode(true);
insertNodeAfter(clonedNode, lastNode);
lastNode = clonedNode.release();
if (n == end.deprecatedNode() || end.deprecatedNode()->isDescendantOf(n))
break;
}
}
}
void CompositeEditCommand::cleanupAfterDeletion(VisiblePosition destination)
{
VisiblePosition caretAfterDelete = endingSelection().visibleStart();
if (caretAfterDelete != destination && isStartOfParagraph(caretAfterDelete) && isEndOfParagraph(caretAfterDelete)) {
Position position = caretAfterDelete.deepEquivalent().downstream();
Node* node = position.deprecatedNode();
if (node->hasTagName(brTag))
removeNodeAndPruneAncestors(node);
else if (isBlock(node))
removeNodeAndPruneAncestors(node);
else if (lineBreakExistsAtPosition(position)) {
Text* textNode = static_cast<Text*>(node);
if (textNode->length() == 1)
removeNodeAndPruneAncestors(node);
else
deleteTextFromNode(textNode, position.deprecatedEditingOffset(), 1);
}
}
}
void CompositeEditCommand::moveParagraphWithClones(const VisiblePosition& startOfParagraphToMove, const VisiblePosition& endOfParagraphToMove, Element* blockElement, Node* outerNode)
{
ASSERT(outerNode);
ASSERT(blockElement);
VisiblePosition beforeParagraph = startOfParagraphToMove.previous();
VisiblePosition afterParagraph(endOfParagraphToMove.next());
Position start = startOfParagraphToMove.deepEquivalent().downstream();
Position end = endOfParagraphToMove.deepEquivalent().upstream();
cloneParagraphUnderNewElement(start, end, outerNode, blockElement);
setEndingSelection(VisibleSelection(start, end, DOWNSTREAM));
deleteSelection(false, false, false, false);
cleanupAfterDeletion();
beforeParagraph = VisiblePosition(beforeParagraph.deepEquivalent());
afterParagraph = VisiblePosition(afterParagraph.deepEquivalent());
if (beforeParagraph.isNotNull() && !isTableElement(beforeParagraph.deepEquivalent().deprecatedNode())
&& ((!isEndOfParagraph(beforeParagraph) && !isStartOfParagraph(beforeParagraph)) || beforeParagraph == afterParagraph)) {
insertNodeAt(createBreakElement(document()), beforeParagraph.deepEquivalent());
}
}
void CompositeEditCommand::moveParagraph(const VisiblePosition& startOfParagraphToMove, const VisiblePosition& endOfParagraphToMove, const VisiblePosition& destination, bool preserveSelection, bool preserveStyle)
{
ASSERT(isStartOfParagraph(startOfParagraphToMove));
ASSERT(isEndOfParagraph(endOfParagraphToMove));
moveParagraphs(startOfParagraphToMove, endOfParagraphToMove, destination, preserveSelection, preserveStyle);
}
void CompositeEditCommand::moveParagraphs(const VisiblePosition& startOfParagraphToMove, const VisiblePosition& endOfParagraphToMove, const VisiblePosition& destination, bool preserveSelection, bool preserveStyle)
{
if (startOfParagraphToMove == destination)
return;
int startIndex = -1;
int endIndex = -1;
int destinationIndex = -1;
if (preserveSelection && !endingSelection().isNone()) {
VisiblePosition visibleStart = endingSelection().visibleStart();
VisiblePosition visibleEnd = endingSelection().visibleEnd();
bool startAfterParagraph = comparePositions(visibleStart, endOfParagraphToMove) > 0;
bool endBeforeParagraph = comparePositions(visibleEnd, startOfParagraphToMove) < 0;
if (!startAfterParagraph && !endBeforeParagraph) {
bool startInParagraph = comparePositions(visibleStart, startOfParagraphToMove) >= 0;
bool endInParagraph = comparePositions(visibleEnd, endOfParagraphToMove) <= 0;
startIndex = 0;
if (startInParagraph) {
RefPtr<Range> startRange = Range::create(document(), startOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent(), visibleStart.deepEquivalent().parentAnchoredEquivalent());
startIndex = TextIterator::rangeLength(startRange.get(), true);
}
endIndex = 0;
if (endInParagraph) {
RefPtr<Range> endRange = Range::create(document(), startOfParagraphToMove.deepEquivalent().parentAnchoredEquivalent(), visibleEnd.deepEquivalent().parentAnchoredEquivalent());
endIndex = TextIterator::rangeLength(endRange.get(), true);
}
}
}
VisiblePosition beforeParagraph = startOfParagraphToMove.previous(CannotCrossEditingBoundary);
VisiblePosition afterParagraph(endOfParagraphToMove.next(CannotCrossEditingBoundary));
Position start = startOfParagraphToMove.deepEquivalent().downstream();
Position end = endOfParagraphToMove.deepEquivalent().upstream();
Position startRangeCompliant = start.parentAnchoredEquivalent();
Position endRangeCompliant = end.parentAnchoredEquivalent();
RefPtr<Range> range = Range::create(document(), startRangeCompliant.deprecatedNode(), startRangeCompliant.deprecatedEditingOffset(), endRangeCompliant.deprecatedNode(), endRangeCompliant.deprecatedEditingOffset());
RefPtr<DocumentFragment> fragment;
if (startOfParagraphToMove != endOfParagraphToMove)
fragment = createFragmentFromMarkup(document(), createMarkup(range.get(), 0, DoNotAnnotateForInterchange, true), "");
RefPtr<EditingStyle> styleInEmptyParagraph;
if (startOfParagraphToMove == endOfParagraphToMove && preserveStyle) {
styleInEmptyParagraph = EditingStyle::create(startOfParagraphToMove.deepEquivalent());
styleInEmptyParagraph->mergeTypingStyle(document());
styleInEmptyParagraph->removeBlockProperties();
}
setEndingSelection(VisibleSelection(start, end, DOWNSTREAM));
document()->frame()->editor()->clearMisspellingsAndBadGrammar(endingSelection());
deleteSelection(false, false, false, false);
ASSERT(destination.deepEquivalent().anchorNode()->inDocument());
cleanupAfterDeletion(destination);
ASSERT(destination.deepEquivalent().anchorNode()->inDocument());
beforeParagraph = VisiblePosition(beforeParagraph.deepEquivalent());
afterParagraph = VisiblePosition(afterParagraph.deepEquivalent());
if (beforeParagraph.isNotNull() && (!isEndOfParagraph(beforeParagraph) || beforeParagraph == afterParagraph)) {
insertNodeAt(createBreakElement(document()), beforeParagraph.deepEquivalent());
updateLayout();
}
RefPtr<Range> startToDestinationRange(Range::create(document(), firstPositionInNode(document()->documentElement()), destination.deepEquivalent().parentAnchoredEquivalent()));
destinationIndex = TextIterator::rangeLength(startToDestinationRange.get(), true);
setEndingSelection(destination);
ASSERT(endingSelection().isCaretOrRange());
ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MovingParagraph;
if (!preserveStyle)
options |= ReplaceSelectionCommand::MatchStyle;
applyCommandToComposite(ReplaceSelectionCommand::create(document(), fragment, options));
document()->frame()->editor()->markMisspellingsAndBadGrammar(endingSelection());
bool selectionIsEmptyParagraph = endingSelection().isCaret() && isStartOfParagraph(endingSelection().visibleStart()) && isEndOfParagraph(endingSelection().visibleStart());
if (styleInEmptyParagraph && selectionIsEmptyParagraph)
applyStyle(styleInEmptyParagraph.get());
if (preserveSelection && startIndex != -1) {
RefPtr<Range> start = TextIterator::rangeFromLocationAndLength(document()->documentElement(), destinationIndex + startIndex, 0, true);
RefPtr<Range> end = TextIterator::rangeFromLocationAndLength(document()->documentElement(), destinationIndex + endIndex, 0, true);
if (start && end)
setEndingSelection(VisibleSelection(start->startPosition(), end->startPosition(), DOWNSTREAM));
}
}
bool CompositeEditCommand::breakOutOfEmptyListItem()
{
Node* emptyListItem = enclosingEmptyListItem(endingSelection().visibleStart());
if (!emptyListItem)
return false;
RefPtr<EditingStyle> style = EditingStyle::create(endingSelection().start());
style->mergeTypingStyle(document());
ContainerNode* listNode = emptyListItem->parentNode();
if (!listNode
|| (!listNode->hasTagName(ulTag) && !listNode->hasTagName(olTag))
|| !listNode->rendererIsEditable()
|| listNode == emptyListItem->rootEditableElement())
return false;
RefPtr<Element> newBlock = 0;
if (ContainerNode* blockEnclosingList = listNode->parentNode()) {
if (blockEnclosingList->hasTagName(liTag)) { if (visiblePositionAfterNode(blockEnclosingList) == visiblePositionAfterNode(listNode)) {
splitElement(static_cast<Element*>(blockEnclosingList), listNode);
removeNodePreservingChildren(listNode->parentNode());
newBlock = createListItemElement(document());
}
} else if (blockEnclosingList->hasTagName(olTag) || blockEnclosingList->hasTagName(ulTag))
newBlock = createListItemElement(document());
}
if (!newBlock)
newBlock = createDefaultParagraphElement(document());
if (emptyListItem->renderer()->nextSibling()) {
if (emptyListItem->renderer()->previousSibling())
splitElement(static_cast<Element*>(listNode), emptyListItem);
insertNodeBefore(newBlock, listNode);
removeNode(emptyListItem);
} else {
insertNodeAfter(newBlock, listNode);
removeNode(emptyListItem->renderer()->previousSibling() ? emptyListItem : listNode);
}
appendBlockPlaceholder(newBlock);
setEndingSelection(VisibleSelection(firstPositionInNode(newBlock.get()), DOWNSTREAM));
style->prepareToApplyAt(endingSelection().start());
if (!style->isEmpty())
applyStyle(style.get());
return true;
}
bool CompositeEditCommand::breakOutOfEmptyMailBlockquotedParagraph()
{
if (!endingSelection().isCaret())
return false;
VisiblePosition caret(endingSelection().visibleStart());
Node* highestBlockquote = highestEnclosingNodeOfType(caret.deepEquivalent(), &isMailBlockquote);
if (!highestBlockquote)
return false;
if (!isStartOfParagraph(caret) || !isEndOfParagraph(caret))
return false;
VisiblePosition previous(caret.previous(CannotCrossEditingBoundary));
if (enclosingNodeOfType(previous.deepEquivalent(), &isMailBlockquote))
return false;
RefPtr<Node> br = createBreakElement(document());
insertNodeBefore(br, highestBlockquote);
VisiblePosition atBR(positionBeforeNode(br.get()));
if (!isStartOfParagraph(atBR))
insertNodeBefore(createBreakElement(document()), br);
setEndingSelection(VisibleSelection(atBR));
if (!lineBreakExistsAtVisiblePosition(caret))
return false;
Position caretPos(caret.deepEquivalent().downstream());
ASSERT(caretPos.deprecatedNode()->hasTagName(brTag) || (caretPos.deprecatedNode()->isTextNode() && caretPos.deprecatedNode()->renderer()->style()->preserveNewline()));
if (caretPos.deprecatedNode()->hasTagName(brTag)) {
Position beforeBR(positionInParentBeforeNode(caretPos.deprecatedNode()));
removeNode(caretPos.deprecatedNode());
prune(beforeBR.deprecatedNode());
} else if (caretPos.deprecatedNode()->isTextNode()) {
ASSERT(caretPos.deprecatedEditingOffset() == 0);
Text* textNode = static_cast<Text*>(caretPos.deprecatedNode());
ContainerNode* parentNode = textNode->parentNode();
deleteTextFromNode(textNode, 0, 1);
prune(parentNode);
}
return true;
}
Position CompositeEditCommand::positionAvoidingSpecialElementBoundary(const Position& original)
{
if (original.isNull())
return original;
VisiblePosition visiblePos(original);
Node* enclosingAnchor = enclosingAnchorElement(original);
Position result = original;
if (!enclosingAnchor)
return result;
if (enclosingAnchor && !isBlock(enclosingAnchor)) {
VisiblePosition firstInAnchor(firstPositionInNode(enclosingAnchor));
VisiblePosition lastInAnchor(lastPositionInNode(enclosingAnchor));
if (visiblePos == lastInAnchor) {
if (original.deprecatedNode() != enclosingAnchor && original.deprecatedNode()->parentNode() != enclosingAnchor) {
pushAnchorElementDown(enclosingAnchor);
enclosingAnchor = enclosingAnchorElement(original);
if (!enclosingAnchor)
return original;
}
Position downstream(visiblePos.deepEquivalent().downstream());
if (lineBreakExistsAtVisiblePosition(visiblePos) && downstream.deprecatedNode()->isDescendantOf(enclosingAnchor))
return original;
result = positionInParentAfterNode(enclosingAnchor);
}
if (visiblePos == firstInAnchor) {
if (original.deprecatedNode() != enclosingAnchor && original.deprecatedNode()->parentNode() != enclosingAnchor) {
pushAnchorElementDown(enclosingAnchor);
enclosingAnchor = enclosingAnchorElement(original);
}
if (!enclosingAnchor)
return original;
result = positionInParentBeforeNode(enclosingAnchor);
}
}
if (result.isNull() || !editableRootForPosition(result))
result = original;
return result;
}
PassRefPtr<Node> CompositeEditCommand::splitTreeToNode(Node* start, Node* end, bool shouldSplitAncestor)
{
ASSERT(start);
ASSERT(end);
ASSERT(start != end);
RefPtr<Node> node;
if (shouldSplitAncestor && end->parentNode())
end = end->parentNode();
RefPtr<Node> endNode = end;
for (node = start; node && node->parentNode() != endNode; node = node->parentNode()) {
if (!node->parentNode()->isElementNode())
break;
VisiblePosition positionInParent = firstPositionInNode(node->parentNode());
VisiblePosition positionInNode = firstPositionInOrBeforeNode(node.get());
if (positionInParent != positionInNode)
splitElement(static_cast<Element*>(node->parentNode()), node);
}
return node.release();
}
PassRefPtr<Element> createBlockPlaceholderElement(Document* document)
{
RefPtr<Element> breakNode = document->createElement(brTag, false);
return breakNode.release();
}
}