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 "Editor.h"
#include "EditorInsertAction.h"
#include "ElementTraversal.h"
#include "ExceptionCodePlaceholder.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 "MergeIdenticalElementsCommand.h"
#include "NodeTraversal.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 "ScopedEventQueue.h"
#include "SetNodeAttributeCommand.h"
#include "SplitElementCommand.h"
#include "SplitTextNodeCommand.h"
#include "SplitTextNodeContainingElementCommand.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisibleUnits.h"
#include "WrapContentsInDummySpanCommand.h"
#include "htmlediting.h"
#include "markup.h"
#if ENABLE(DELETION_UI)
#include "DeleteButtonController.h"
#endif
#if PLATFORM(IOS)
#include "BreakBlockquoteCommand.h"
#endif
namespace WebCore {
using namespace HTMLNames;
PassRefPtr<EditCommandComposition> EditCommandComposition::create(Document& document,
const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction editAction)
{
return adoptRef(new EditCommandComposition(document, startingSelection, endingSelection, editAction));
}
EditCommandComposition::EditCommandComposition(Document& document, const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction editAction)
: m_document(&document)
, m_startingSelection(startingSelection)
, m_endingSelection(endingSelection)
, m_startingRootEditableElement(startingSelection.rootEditableElement())
, m_endingRootEditableElement(endingSelection.rootEditableElement())
, m_editAction(editAction)
{
}
void EditCommandComposition::unapply()
{
ASSERT(m_document);
RefPtr<Frame> frame = m_document->frame();
ASSERT(frame);
m_document->updateLayoutIgnorePendingStylesheets();
#if PLATFORM(IOS)
frame->editor().cancelComposition();
#endif
{
#if ENABLE(DELETION_UI)
DeleteButtonControllerDisableScope deleteButtonControllerDisableScope(frame.get());
#endif
size_t size = m_commands.size();
for (size_t i = size; i; --i)
m_commands[i - 1]->doUnapply();
}
frame->editor().unappliedEditing(this);
}
void EditCommandComposition::reapply()
{
ASSERT(m_document);
RefPtr<Frame> frame = m_document->frame();
ASSERT(frame);
m_document->updateLayoutIgnorePendingStylesheets();
{
#if ENABLE(DELETION_UI)
DeleteButtonControllerDisableScope deleteButtonControllerDisableScope(frame.get());
#endif
size_t size = m_commands.size();
for (size_t i = 0; i != size; ++i)
m_commands[i]->doReapply();
}
frame->editor().reappliedEditing(this);
}
void EditCommandComposition::append(SimpleEditCommand* command)
{
m_commands.append(command);
}
void EditCommandComposition::setStartingSelection(const VisibleSelection& selection)
{
m_startingSelection = selection;
m_startingRootEditableElement = selection.rootEditableElement();
}
void EditCommandComposition::setEndingSelection(const VisibleSelection& selection)
{
m_endingSelection = selection;
m_endingRootEditableElement = selection.rootEditableElement();
}
#ifndef NDEBUG
void EditCommandComposition::getNodesInCommand(HashSet<Node*>& nodes)
{
size_t size = m_commands.size();
for (size_t i = 0; i < size; ++i)
m_commands[i]->getNodesInCommand(nodes);
}
#endif
void applyCommand(PassRefPtr<CompositeEditCommand> command)
{
command->apply();
}
CompositeEditCommand::CompositeEditCommand(Document& document)
: EditCommand(document)
{
}
CompositeEditCommand::~CompositeEditCommand()
{
ASSERT(isTopLevelCommand() || !m_composition);
}
void CompositeEditCommand::apply()
{
if (!endingSelection().isContentRichlyEditable()) {
switch (editingAction()) {
case EditActionTyping:
case EditActionPaste:
case EditActionDrag:
case EditActionSetWritingDirection:
case EditActionCut:
case EditActionUnspecified:
#if PLATFORM(IOS)
case EditActionDelete:
case EditActionDictation:
#endif
break;
default:
ASSERT_NOT_REACHED();
return;
}
}
ensureComposition();
document().updateLayoutIgnorePendingStylesheets();
{
EventQueueScope eventQueueScope;
#if ENABLE(DELETION_UI)
DeleteButtonControllerDisableScope deleteButtonControllerDisableScope(&frame());
#endif
doApply();
}
if (!isTypingCommand())
frame().editor().appliedEditing(this);
setShouldRetainAutocorrectionIndicator(false);
}
EditCommandComposition* CompositeEditCommand::ensureComposition()
{
CompositeEditCommand* command = this;
while (command && command->parent())
command = command->parent();
if (!command->m_composition)
command->m_composition = EditCommandComposition::create(document(), startingSelection(), endingSelection(), editingAction());
return command->m_composition.get();
}
bool CompositeEditCommand::isCreateLinkCommand() const
{
return false;
}
bool CompositeEditCommand::preservesTypingStyle() const
{
return false;
}
bool CompositeEditCommand::isTypingCommand() const
{
return false;
}
bool CompositeEditCommand::shouldRetainAutocorrectionIndicator() const
{
return false;
}
void CompositeEditCommand::setShouldRetainAutocorrectionIndicator(bool)
{
}
void CompositeEditCommand::applyCommandToComposite(PassRefPtr<EditCommand> prpCommand)
{
RefPtr<EditCommand> command = prpCommand;
command->setParent(this);
command->doApply();
if (command->isSimpleEditCommand()) {
command->setParent(0);
ensureComposition()->append(toSimpleEditCommand(command.get()));
}
m_commands.append(command.release());
}
void CompositeEditCommand::applyCommandToComposite(PassRefPtr<CompositeEditCommand> command, const VisibleSelection& selection)
{
command->setParent(this);
if (selection != command->endingSelection()) {
command->setStartingSelection(selection);
command->setEndingSelection(selection);
}
command->doApply();
m_commands.append(command);
}
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, bool pasteBlockqutoeIntoUnquotedArea)
{
applyCommandToComposite(InsertParagraphSeparatorCommand::create(document(), useDefaultParagraphElement, pasteBlockqutoeIntoUnquotedArea));
}
void CompositeEditCommand::insertLineBreak()
{
applyCommandToComposite(InsertLineBreakCommand::create(document()));
}
bool CompositeEditCommand::isRemovableBlock(const Node* node)
{
if (!node->hasTagName(divTag))
return false;
Node* parentNode = node->parentNode();
if (parentNode && parentNode->firstChild() != parentNode->lastChild())
return false;
if (!toElement(node)->hasAttributes())
return true;
return false;
}
void CompositeEditCommand::insertNodeBefore(PassRefPtr<Node> insertChild, PassRefPtr<Node> refChild, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
{
ASSERT(!refChild->hasTagName(bodyTag));
applyCommandToComposite(InsertNodeBeforeCommand::create(insertChild, refChild, shouldAssumeContentIsAlwaysEditable));
}
void CompositeEditCommand::insertNodeAfter(PassRefPtr<Node> insertChild, PassRefPtr<Node> refChild)
{
ASSERT(insertChild);
ASSERT(refChild);
ASSERT(!refChild->hasTagName(bodyTag));
ContainerNode* parent = refChild->parentNode();
ASSERT(parent);
ASSERT(!parent->isShadowRoot());
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, toContainerNode(refChild));
} else if (caretMinOffset(refChild) >= offset)
insertNodeBefore(insertChild, refChild);
else if (refChild->isTextNode() && caretMaxOffset(refChild) > offset) {
splitTextNode(toText(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, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
{
if (!node || !node->nonShadowBoundaryParentNode())
return;
applyCommandToComposite(RemoveNodeCommand::create(node, shouldAssumeContentIsAlwaysEditable));
}
void CompositeEditCommand::removeNodePreservingChildren(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
{
applyCommandToComposite(RemoveNodePreservingChildrenCommand::create(node, shouldAssumeContentIsAlwaysEditable));
}
void CompositeEditCommand::removeNodeAndPruneAncestors(PassRefPtr<Node> node)
{
RefPtr<ContainerNode> parent = node->parentNode();
removeNode(node);
prune(parent.release());
}
void CompositeEditCommand::moveRemainingSiblingsToNewParent(Node* node, Node* pastLastNodeToMove, PassRefPtr<Element> prpNewParent)
{
NodeVector nodesToRemove;
RefPtr<Element> newParent = prpNewParent;
for (; node && node != pastLastNodeToMove; node = node->nextSibling())
nodesToRemove.append(*node);
for (unsigned i = 0; i < nodesToRemove.size(); i++) {
removeNode(&nodesToRemove[i].get());
appendNode(&nodesToRemove[i].get(), newParent);
}
}
void CompositeEditCommand::updatePositionForNodeRemovalPreservingChildren(Position& position, Node* node)
{
int offset = (position.anchorType() == Position::PositionIsOffsetInAnchor) ? position.offsetInContainerNode() : 0;
updatePositionForNodeRemoval(position, node);
if (offset)
position.moveToOffset(offset);
}
HTMLElement* CompositeEditCommand::replaceElementWithSpanPreservingChildrenAndAttributes(PassRefPtr<HTMLElement> node)
{
RefPtr<ReplaceNodeWithSpanCommand> command = ReplaceNodeWithSpanCommand::create(node);
applyCommandToComposite(command);
ASSERT(command->spanElement()->inDocument());
return command->spanElement();
}
void CompositeEditCommand::prune(PassRefPtr<Node> node)
{
if (RefPtr<Node> highestNodeToRemove = highestNodeToRemoveInPruning(node.get()))
removeNode(highestNodeToRemove.release());
}
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));
}
#if PLATFORM(IOS)
void CompositeEditCommand::inputText(const String& text, bool selectInsertedText)
{
unsigned offset = 0;
unsigned length = text.length();
RefPtr<ContainerNode> scope;
unsigned startIndex = indexForVisiblePosition(endingSelection().visibleStart(), scope);
size_t newline;
do {
newline = text.find('\n', offset);
if (newline != offset) {
int substringLength = newline == notFound ? length - offset : newline - offset;
RefPtr<InsertTextCommand> command = InsertTextCommand::create(document(), text.substring(offset, substringLength), false);
applyCommandToComposite(command);
}
if (newline != notFound) {
VisiblePosition caret(endingSelection().visibleStart());
if (enclosingNodeOfType(caret.deepEquivalent(), &isMailBlockquote)) {
if (caret.previous().characterAfter() == ' ') {
if (!offset && !startIndex)
startIndex--;
else if (!length)
length--;
}
applyCommandToComposite(BreakBlockquoteCommand::create(document()));
} else
insertLineBreak();
}
offset = newline + 1;
} while (newline != notFound && offset != length);
if (selectInsertedText)
setEndingSelection(VisibleSelection(visiblePositionForIndex(startIndex, scope.get()), visiblePositionForIndex(startIndex + length, scope.get())));
}
#endif
void CompositeEditCommand::insertTextIntoNode(PassRefPtr<Text> node, unsigned offset, const String& text)
{
if (!text.isEmpty())
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> prpNode, unsigned offset, unsigned count, const String& replacementText)
{
RefPtr<Text> node(prpNode);
applyCommandToComposite(DeleteFromTextNodeCommand::create(node, offset, count));
if (!replacementText.isEmpty())
applyCommandToComposite(InsertIntoTextNodeCommand::create(node, offset, replacementText));
}
Position CompositeEditCommand::replaceSelectedTextInNode(const String& text)
{
Position start = endingSelection().start();
Position end = endingSelection().end();
if (start.containerNode() != end.containerNode() || !start.containerNode()->isTextNode() || isTabSpanTextNode(start.containerNode()))
return Position();
RefPtr<Text> textNode = start.containerText();
replaceTextInNode(textNode, start.offsetInContainerNode(), end.offsetInContainerNode() - start.offsetInContainerNode(), text);
return Position(textNode.release(), start.offsetInContainerNode() + text.length());
}
static void copyMarkers(const Vector<DocumentMarker*>& markerPointers, Vector<DocumentMarker>& markers)
{
size_t arraySize = markerPointers.size();
markers.reserveCapacity(arraySize);
for (size_t i = 0; i < arraySize; ++i)
markers.append(*markerPointers[i]);
}
void CompositeEditCommand::replaceTextInNodePreservingMarkers(PassRefPtr<Text> prpNode, unsigned offset, unsigned count, const String& replacementText)
{
RefPtr<Text> node(prpNode);
DocumentMarkerController& markerController = document().markers();
Vector<DocumentMarker> markers;
copyMarkers(markerController.markersInRange(Range::create(document(), node, offset, node, offset + count).get(), DocumentMarker::AllMarkers()), markers);
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)
#if PLATFORM(IOS)
markerController.addMarker(newRange.get(), markers[i].type(), markers[i].description(), markers[i].alternatives(), markers[i].metadata());
#else
markerController.addMarker(newRange.get(), markers[i].type(), markers[i].description());
#endif // PLATFORM(IOS)
}
Position CompositeEditCommand::positionOutsideTabSpan(const Position& pos)
{
if (!isTabSpanTextNode(pos.anchorNode()))
return pos;
switch (pos.anchorType()) {
case Position::PositionIsBeforeChildren:
case Position::PositionIsAfterChildren:
ASSERT_NOT_REACHED();
return pos;
case Position::PositionIsOffsetInAnchor:
break;
case Position::PositionIsBeforeAnchor:
return positionInParentBeforeNode(pos.anchorNode());
case Position::PositionIsAfterAnchor:
return positionInParentAfterNode(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(toText(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, bool sanitizeMarkup)
{
if (endingSelection().isRange())
applyCommandToComposite(DeleteSelectionCommand::create(document(), smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
}
void CompositeEditCommand::deleteSelection(const VisibleSelection &selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
{
if (selection.isRange())
applyCommandToComposite(DeleteSelectionCommand::create(selection, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
}
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[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 = toText(node);
if (textNode->length() == 0)
return false;
node->document().updateStyleIfNeeded();
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 = toText(node)->data();
if (!isWhitespace(text[offset])) {
offset--;
if (offset < 0 || !isWhitespace(text[offset]))
return;
}
rebalanceWhitespaceOnTextSubstring(toText(node), position.offsetInContainerNode(), position.offsetInContainerNode());
}
void CompositeEditCommand::rebalanceWhitespaceOnTextSubstring(PassRefPtr<Text> prpTextNode, int startOffset, int endOffset)
{
RefPtr<Text> textNode = prpTextNode;
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));
VisiblePosition visibleDownstreamPos(Position(textNode, downstream));
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.release(), upstream, length, rebalancedString);
}
void CompositeEditCommand::prepareWhitespaceAtPositionForSplit(Position& position)
{
Node* node = position.deprecatedNode();
if (!node || !node->isTextNode())
return;
Text* textNode = toText(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 (deprecatedIsCollapsibleWhitespace(previousVisiblePos.characterAfter()) && previous.deprecatedNode()->isTextNode() && !previous.deprecatedNode()->hasTagName(brTag))
replaceTextInNodePreservingMarkers(toText(previous.deprecatedNode()), previous.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
if (deprecatedIsCollapsibleWhitespace(visiblePos.characterAfter()) && position.deprecatedNode()->isTextNode() && !position.deprecatedNode()->hasTagName(brTag))
replaceTextInNodePreservingMarkers(toText(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;
document().updateLayout();
RenderText* textRenderer = 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 = std::max(gapStart, start);
gapEnd = std::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;
Vector<RefPtr<Text>> nodes;
for (Node* node = start.deprecatedNode(); node; node = NodeTraversal::next(node)) {
if (node->isTextNode())
nodes.append(toText(node));
if (node == end.deprecatedNode())
break;
}
for (size_t i = 0; i < nodes.size(); ++i) {
Text* textNode = nodes[i].get();
int startOffset = textNode == start.deprecatedNode() ? start.deprecatedEditingOffset() : 0;
int endOffset = textNode == end.deprecatedNode() ? end.deprecatedEditingOffset() : static_cast<int>(textNode->length());
deleteInsignificantText(textNode, startOffset, endOffset);
}
}
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;
document().updateLayoutIgnorePendingStylesheets();
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;
document().updateLayoutIgnorePendingStylesheets();
RenderObject* renderer = container->renderer();
if (!renderer || !renderer->isRenderBlockFlow())
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(toText(p.anchorNode()), p.offsetInContainerNode(), 1);
}
PassRefPtr<Node> CompositeEditCommand::insertNewDefaultParagraphElementAt(const Position& position)
{
RefPtr<Element> paragraphElement = createDefaultParagraphElement(document());
paragraphElement->appendChild(createBreakElement(document()), IGNORE_EXCEPTION);
insertNodeAt(paragraphElement, position);
return paragraphElement.release();
}
PassRefPtr<Node> CompositeEditCommand::moveParagraphContentsToNewBlockIfNecessary(const Position& pos)
{
if (pos.isNull())
return 0;
document().updateLayoutIgnorePendingStylesheets();
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(toRenderElement(*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 (isEndOfEditableOrNonEditableContent(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(Element& anchorElement)
{
ASSERT(anchorElement.isLink());
setEndingSelection(VisibleSelection::selectionFromContentsOfNode(&anchorElement));
applyStyledElement(&anchorElement);
if (anchorElement.inDocument())
removeNodePreservingChildren(&anchorElement);
}
void CompositeEditCommand::cloneParagraphUnderNewElement(const Position& start, const Position& end, Node* passedOuterNode, Element* blockElement)
{
ASSERT(comparePositions(start, end) <= 0);
RefPtr<Node> lastNode;
RefPtr<Node> outerNode = passedOuterNode;
if (outerNode->isRootEditableElement()) {
lastNode = blockElement;
} else {
lastNode = outerNode->cloneNode(isRenderedTable(outerNode.get()));
appendNode(lastNode, blockElement);
}
if (start.deprecatedNode() != outerNode && lastNode->isElementNode() && start.anchorNode()->isDescendantOf(outerNode.get())) {
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(isRenderedTable(item));
appendNode(child, toElement(lastNode.get()));
lastNode = child.release();
}
}
if (start.deprecatedNode() != end.deprecatedNode() && !start.deprecatedNode()->isDescendantOf(end.deprecatedNode())) {
while (!end.deprecatedNode()->isDescendantOf(outerNode.get())) {
outerNode = outerNode->parentNode();
}
RefPtr<Node> startNode = start.deprecatedNode();
for (RefPtr<Node> node = NodeTraversal::nextSkippingChildren(startNode.get(), outerNode.get()); node; node = NodeTraversal::nextSkippingChildren(node.get(), outerNode.get())) {
while (startNode->parentNode() != node->parentNode()) {
startNode = startNode->parentNode();
lastNode = lastNode->parentNode();
}
RefPtr<Node> clonedNode = node->cloneNode(true);
insertNodeAfter(clonedNode, lastNode);
lastNode = clonedNode.release();
if (node == end.deprecatedNode() || end.deprecatedNode()->isDescendantOf(node.get()))
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)) {
if (!position.rendersInDifferentPosition(destination.deepEquivalent())) {
prune(node);
return;
}
removeNodeAndPruneAncestors(node);
}
else if (lineBreakExistsAtPosition(position)) {
Text* textNode = toText(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 = startOfParagraphToMove == endOfParagraphToMove ? start : 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() && !isRenderedTable(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;
bool originalIsDirectional = endingSelection().isDirectional();
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, 0, DoNotAnnotateForInterchange, true), "");
RefPtr<EditingStyle> styleInEmptyParagraph;
#if !PLATFORM(IOS)
if (startOfParagraphToMove == endOfParagraphToMove && preserveStyle) {
#else
if (startOfParagraphToMove == endOfParagraphToMove && preserveStyle && isRichlyEditablePosition(destination.deepEquivalent())) {
#endif
styleInEmptyParagraph = EditingStyle::create(startOfParagraphToMove.deepEquivalent());
styleInEmptyParagraph->mergeTypingStyle(document());
styleInEmptyParagraph->removeBlockProperties();
}
setEndingSelection(VisibleSelection(start, end, DOWNSTREAM));
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());
document().updateLayoutIgnorePendingStylesheets();
}
RefPtr<Range> startToDestinationRange(Range::create(document(), firstPositionInNode(document().documentElement()), destination.deepEquivalent().parentAnchoredEquivalent()));
destinationIndex = TextIterator::rangeLength(startToDestinationRange.get(), true);
setEndingSelection(VisibleSelection(destination, originalIsDirectional));
ASSERT(endingSelection().isCaretOrRange());
ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MovingParagraph;
if (!preserveStyle)
options |= ReplaceSelectionCommand::MatchStyle;
applyCommandToComposite(ReplaceSelectionCommand::create(document(), fragment, options));
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, originalIsDirectional));
}
}
bool CompositeEditCommand::breakOutOfEmptyListItem()
{
RefPtr<Node> emptyListItem = enclosingEmptyListItem(endingSelection().visibleStart());
if (!emptyListItem)
return false;
RefPtr<EditingStyle> style = EditingStyle::create(endingSelection().start());
style->mergeTypingStyle(document());
RefPtr<ContainerNode> listNode = emptyListItem->parentNode();
if (!listNode
|| (!listNode->hasTagName(ulTag) && !listNode->hasTagName(olTag))
|| !listNode->hasEditableStyle()
|| listNode == emptyListItem->rootEditableElement())
return false;
RefPtr<Element> newBlock = 0;
if (ContainerNode* blockEnclosingList = listNode->parentNode()) {
if (blockEnclosingList->hasTagName(liTag)) { if (visiblePositionAfterNode(blockEnclosingList) == visiblePositionAfterNode(listNode.get())) {
splitElement(toElement(blockEnclosingList), listNode);
removeNodePreservingChildren(listNode->parentNode());
newBlock = createListItemElement(document());
}
} else if (blockEnclosingList->hasTagName(olTag) || blockEnclosingList->hasTagName(ulTag))
newBlock = createListItemElement(document());
}
if (!newBlock)
newBlock = createDefaultParagraphElement(document());
RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? ElementTraversal::previousSibling(emptyListItem.get()): emptyListItem->previousSibling();
RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? ElementTraversal::nextSibling(emptyListItem.get()): emptyListItem->nextSibling();
if (isListItem(nextListNode.get()) || isListElement(nextListNode.get())) {
if (isListItem(previousListNode.get()) || isListElement(previousListNode.get()))
splitElement(toElement(listNode.get()), emptyListItem);
insertNodeBefore(newBlock, listNode);
removeNode(emptyListItem);
} else {
insertNodeAfter(newBlock, listNode);
removeNode(isListItem(previousListNode.get()) || isListElement(previousListNode.get()) ? emptyListItem.get() : listNode.get());
}
appendBlockPlaceholder(newBlock);
setEndingSelection(VisibleSelection(firstPositionInNode(newBlock.get()), DOWNSTREAM, endingSelection().isDirectional()));
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, endingSelection().isDirectional()));
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))
removeNodeAndPruneAncestors(caretPos.deprecatedNode());
else if (caretPos.deprecatedNode()->isTextNode()) {
ASSERT(caretPos.deprecatedEditingOffset() == 0);
Text* textNode = toText(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);
Element* 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(toElement(node->parentNode()), node);
}
return node.release();
}
PassRefPtr<Element> createBlockPlaceholderElement(Document& document)
{
return document.createElement(brTag, false);
}
}