1/*
2 * Copyright (C) 2005 Apple Computer, Inc.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "core/editing/DeleteSelectionCommand.h"
28
29#include "HTMLNames.h"
30#include "core/dom/Document.h"
31#include "core/dom/Element.h"
32#include "core/dom/NodeTraversal.h"
33#include "core/dom/Text.h"
34#include "core/editing/EditingBoundary.h"
35#include "core/editing/Editor.h"
36#include "core/editing/VisibleUnits.h"
37#include "core/editing/htmlediting.h"
38#include "core/html/HTMLInputElement.h"
39#include "core/html/HTMLTableElement.h"
40#include "core/frame/Frame.h"
41#include "core/rendering/RenderTableCell.h"
42
43namespace WebCore {
44
45using namespace HTMLNames;
46
47static bool isTableRow(const Node* node)
48{
49    return node && node->hasTagName(trTag);
50}
51
52static bool isTableCellEmpty(Node* cell)
53{
54    ASSERT(isTableCell(cell));
55    return VisiblePosition(firstPositionInNode(cell)) == VisiblePosition(lastPositionInNode(cell));
56}
57
58static bool isTableRowEmpty(Node* row)
59{
60    if (!isTableRow(row))
61        return false;
62
63    for (Node* child = row->firstChild(); child; child = child->nextSibling())
64        if (isTableCell(child) && !isTableCellEmpty(child))
65            return false;
66
67    return true;
68}
69
70DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
71    : CompositeEditCommand(document)
72    , m_hasSelectionToDelete(false)
73    , m_smartDelete(smartDelete)
74    , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
75    , m_needPlaceholder(false)
76    , m_replace(replace)
77    , m_expandForSpecialElements(expandForSpecialElements)
78    , m_pruneStartBlockIfNecessary(false)
79    , m_startsAtEmptyLine(false)
80    , m_sanitizeMarkup(sanitizeMarkup)
81    , m_startBlock(0)
82    , m_endBlock(0)
83    , m_typingStyle(0)
84    , m_deleteIntoBlockquoteStyle(0)
85{
86}
87
88DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
89    : CompositeEditCommand(*selection.start().document())
90    , m_hasSelectionToDelete(true)
91    , m_smartDelete(smartDelete)
92    , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
93    , m_needPlaceholder(false)
94    , m_replace(replace)
95    , m_expandForSpecialElements(expandForSpecialElements)
96    , m_pruneStartBlockIfNecessary(false)
97    , m_startsAtEmptyLine(false)
98    , m_sanitizeMarkup(sanitizeMarkup)
99    , m_selectionToDelete(selection)
100    , m_startBlock(0)
101    , m_endBlock(0)
102    , m_typingStyle(0)
103    , m_deleteIntoBlockquoteStyle(0)
104{
105}
106
107void DeleteSelectionCommand::initializeStartEnd(Position& start, Position& end)
108{
109    Node* startSpecialContainer = 0;
110    Node* endSpecialContainer = 0;
111
112    start = m_selectionToDelete.start();
113    end = m_selectionToDelete.end();
114
115    // For HRs, we'll get a position at (HR,1) when hitting delete from the beginning of the previous line, or (HR,0) when forward deleting,
116    // but in these cases, we want to delete it, so manually expand the selection
117    if (start.deprecatedNode()->hasTagName(hrTag))
118        start = positionBeforeNode(start.deprecatedNode());
119    else if (end.deprecatedNode()->hasTagName(hrTag))
120        end = positionAfterNode(end.deprecatedNode());
121
122    // FIXME: This is only used so that moveParagraphs can avoid the bugs in special element expansion.
123    if (!m_expandForSpecialElements)
124        return;
125
126    while (1) {
127        startSpecialContainer = 0;
128        endSpecialContainer = 0;
129
130        Position s = positionBeforeContainingSpecialElement(start, &startSpecialContainer);
131        Position e = positionAfterContainingSpecialElement(end, &endSpecialContainer);
132
133        if (!startSpecialContainer && !endSpecialContainer)
134            break;
135
136        if (VisiblePosition(start) != m_selectionToDelete.visibleStart() || VisiblePosition(end) != m_selectionToDelete.visibleEnd())
137            break;
138
139        // If we're going to expand to include the startSpecialContainer, it must be fully selected.
140        if (startSpecialContainer && !endSpecialContainer && comparePositions(positionInParentAfterNode(startSpecialContainer), end) > -1)
141            break;
142
143        // If we're going to expand to include the endSpecialContainer, it must be fully selected.
144        if (endSpecialContainer && !startSpecialContainer && comparePositions(start, positionInParentBeforeNode(endSpecialContainer)) > -1)
145            break;
146
147        if (startSpecialContainer && startSpecialContainer->isDescendantOf(endSpecialContainer))
148            // Don't adjust the end yet, it is the end of a special element that contains the start
149            // special element (which may or may not be fully selected).
150            start = s;
151        else if (endSpecialContainer && endSpecialContainer->isDescendantOf(startSpecialContainer))
152            // Don't adjust the start yet, it is the start of a special element that contains the end
153            // special element (which may or may not be fully selected).
154            end = e;
155        else {
156            start = s;
157            end = e;
158        }
159    }
160}
161
162void DeleteSelectionCommand::setStartingSelectionOnSmartDelete(const Position& start, const Position& end)
163{
164    VisiblePosition newBase;
165    VisiblePosition newExtent;
166    if (startingSelection().isBaseFirst()) {
167        newBase = start;
168        newExtent = end;
169    } else {
170        newBase = end;
171        newExtent = start;
172    }
173    setStartingSelection(VisibleSelection(newBase, newExtent, startingSelection().isDirectional()));
174}
175
176void DeleteSelectionCommand::initializePositionData()
177{
178    Position start, end;
179    initializeStartEnd(start, end);
180
181    m_upstreamStart = start.upstream();
182    m_downstreamStart = start.downstream();
183    m_upstreamEnd = end.upstream();
184    m_downstreamEnd = end.downstream();
185
186    m_startRoot = editableRootForPosition(start);
187    m_endRoot = editableRootForPosition(end);
188
189    m_startTableRow = enclosingNodeOfType(start, &isTableRow);
190    m_endTableRow = enclosingNodeOfType(end, &isTableRow);
191
192    // Don't move content out of a table cell.
193    // If the cell is non-editable, enclosingNodeOfType won't return it by default, so
194    // tell that function that we don't care if it returns non-editable nodes.
195    Node* startCell = enclosingNodeOfType(m_upstreamStart, &isTableCell, CanCrossEditingBoundary);
196    Node* endCell = enclosingNodeOfType(m_downstreamEnd, &isTableCell, CanCrossEditingBoundary);
197    // FIXME: This isn't right.  A borderless table with two rows and a single column would appear as two paragraphs.
198    if (endCell && endCell != startCell)
199        m_mergeBlocksAfterDelete = false;
200
201    // Usually the start and the end of the selection to delete are pulled together as a result of the deletion.
202    // Sometimes they aren't (like when no merge is requested), so we must choose one position to hold the caret
203    // and receive the placeholder after deletion.
204    VisiblePosition visibleEnd(m_downstreamEnd);
205    if (m_mergeBlocksAfterDelete && !isEndOfParagraph(visibleEnd))
206        m_endingPosition = m_downstreamEnd;
207    else
208        m_endingPosition = m_downstreamStart;
209
210    // We don't want to merge into a block if it will mean changing the quote level of content after deleting
211    // selections that contain a whole number paragraphs plus a line break, since it is unclear to most users
212    // that such a selection actually ends at the start of the next paragraph. This matches TextEdit behavior
213    // for indented paragraphs.
214    // Only apply this rule if the endingSelection is a range selection.  If it is a caret, then other operations have created
215    // the selection we're deleting (like the process of creating a selection to delete during a backspace), and the user isn't in the situation described above.
216    if (numEnclosingMailBlockquotes(start) != numEnclosingMailBlockquotes(end)
217            && isStartOfParagraph(visibleEnd) && isStartOfParagraph(VisiblePosition(start))
218            && endingSelection().isRange()) {
219        m_mergeBlocksAfterDelete = false;
220        m_pruneStartBlockIfNecessary = true;
221    }
222
223    // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
224    m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity());
225    m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
226
227    if (m_smartDelete) {
228
229        // skip smart delete if the selection to delete already starts or ends with whitespace
230        Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.affinity()).deepEquivalent();
231        bool skipSmartDelete = pos.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
232        if (!skipSmartDelete)
233            skipSmartDelete = m_downstreamEnd.leadingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
234
235        // extend selection upstream if there is whitespace there
236        bool hasLeadingWhitespaceBeforeAdjustment = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.affinity(), true).isNotNull();
237        if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
238            VisiblePosition visiblePos = VisiblePosition(m_upstreamStart, VP_DEFAULT_AFFINITY).previous();
239            pos = visiblePos.deepEquivalent();
240            // Expand out one character upstream for smart delete and recalculate
241            // positions based on this change.
242            m_upstreamStart = pos.upstream();
243            m_downstreamStart = pos.downstream();
244            m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(visiblePos.affinity());
245
246            setStartingSelectionOnSmartDelete(m_upstreamStart, m_upstreamEnd);
247        }
248
249        // trailing whitespace is only considered for smart delete if there is no leading
250        // whitespace, as in the case where you double-click the first word of a paragraph.
251        if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull()) {
252            // Expand out one character downstream for smart delete and recalculate
253            // positions based on this change.
254            pos = VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY).next().deepEquivalent();
255            m_upstreamEnd = pos.upstream();
256            m_downstreamEnd = pos.downstream();
257            m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
258
259            setStartingSelectionOnSmartDelete(m_downstreamStart, m_downstreamEnd);
260        }
261    }
262
263    // We must pass call parentAnchoredEquivalent on the positions since some editing positions
264    // that appear inside their nodes aren't really inside them.  [hr, 0] is one example.
265    // FIXME: parentAnchoredEquivalent should eventually be moved into enclosing element getters
266    // like the one below, since editing functions should obviously accept editing positions.
267    // FIXME: Passing false to enclosingNodeOfType tells it that it's OK to return a non-editable
268    // node.  This was done to match existing behavior, but it seems wrong.
269    m_startBlock = enclosingNodeOfType(m_downstreamStart.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
270    m_endBlock = enclosingNodeOfType(m_upstreamEnd.parentAnchoredEquivalent(), &isBlock, CanCrossEditingBoundary);
271}
272
273// We don't want to inherit style from an element which can't have contents.
274static bool shouldNotInheritStyleFrom(const Node& node)
275{
276    return !node.canContainRangeEndPoint();
277}
278
279void DeleteSelectionCommand::saveTypingStyleState()
280{
281    // A common case is deleting characters that are all from the same text node. In
282    // that case, the style at the start of the selection before deletion will be the
283    // same as the style at the start of the selection after deletion (since those
284    // two positions will be identical). Therefore there is no need to save the
285    // typing style at the start of the selection, nor is there a reason to
286    // compute the style at the start of the selection after deletion (see the
287    // early return in calculateTypingStyleAfterDelete).
288    if (m_upstreamStart.deprecatedNode() == m_downstreamEnd.deprecatedNode() && m_upstreamStart.deprecatedNode()->isTextNode())
289        return;
290
291    if (shouldNotInheritStyleFrom(*m_selectionToDelete.start().anchorNode()))
292        return;
293
294    // Figure out the typing style in effect before the delete is done.
295    m_typingStyle = EditingStyle::create(m_selectionToDelete.start(), EditingStyle::EditingPropertiesInEffect);
296    m_typingStyle->removeStyleAddedByNode(enclosingAnchorElement(m_selectionToDelete.start()));
297
298    // If we're deleting into a Mail blockquote, save the style at end() instead of start()
299    // We'll use this later in computeTypingStyleAfterDelete if we end up outside of a Mail blockquote
300    if (enclosingNodeOfType(m_selectionToDelete.start(), isMailBlockquote))
301        m_deleteIntoBlockquoteStyle = EditingStyle::create(m_selectionToDelete.end());
302    else
303        m_deleteIntoBlockquoteStyle = 0;
304}
305
306bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
307{
308    Node* nodeAfterUpstreamStart = m_upstreamStart.computeNodeAfterPosition();
309    Node* nodeAfterDownstreamStart = m_downstreamStart.computeNodeAfterPosition();
310    // Upstream end will appear before BR due to canonicalization
311    Node* nodeAfterUpstreamEnd = m_upstreamEnd.computeNodeAfterPosition();
312
313    if (!nodeAfterUpstreamStart || !nodeAfterDownstreamStart)
314        return false;
315
316    // Check for special-case where the selection contains only a BR on a line by itself after another BR.
317    bool upstreamStartIsBR = nodeAfterUpstreamStart->hasTagName(brTag);
318    bool downstreamStartIsBR = nodeAfterDownstreamStart->hasTagName(brTag);
319    bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && nodeAfterDownstreamStart == nodeAfterUpstreamEnd;
320    if (isBROnLineByItself) {
321        removeNode(nodeAfterDownstreamStart);
322        return true;
323    }
324
325    // FIXME: This code doesn't belong in here.
326    // We detect the case where the start is an empty line consisting of BR not wrapped in a block element.
327    if (upstreamStartIsBR && downstreamStartIsBR && !(isStartOfBlock(positionBeforeNode(nodeAfterUpstreamStart)) && isEndOfBlock(positionAfterNode(nodeAfterUpstreamStart)))) {
328        m_startsAtEmptyLine = true;
329        m_endingPosition = m_downstreamEnd;
330    }
331
332    return false;
333}
334
335static Position firstEditablePositionInNode(Node* node)
336{
337    ASSERT(node);
338    Node* next = node;
339    while (next && !next->rendererIsEditable())
340        next = NodeTraversal::next(*next, node);
341    return next ? firstPositionInOrBeforeNode(next) : Position();
342}
343
344void DeleteSelectionCommand::removeNode(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
345{
346    if (!node)
347        return;
348
349    if (m_startRoot != m_endRoot && !(node->isDescendantOf(m_startRoot.get()) && node->isDescendantOf(m_endRoot.get()))) {
350        // If a node is not in both the start and end editable roots, remove it only if its inside an editable region.
351        if (!node->parentNode()->rendererIsEditable()) {
352            // Don't remove non-editable atomic nodes.
353            if (!node->firstChild())
354                return;
355            // Search this non-editable region for editable regions to empty.
356            RefPtr<Node> child = node->firstChild();
357            while (child) {
358                RefPtr<Node> nextChild = child->nextSibling();
359                removeNode(child.get(), shouldAssumeContentIsAlwaysEditable);
360                // Bail if nextChild is no longer node's child.
361                if (nextChild && nextChild->parentNode() != node)
362                    return;
363                child = nextChild;
364            }
365
366            // Don't remove editable regions that are inside non-editable ones, just clear them.
367            return;
368        }
369    }
370
371    if (isTableStructureNode(node.get()) || node->isRootEditableElement()) {
372        // Do not remove an element of table structure; remove its contents.
373        // Likewise for the root editable element.
374        Node* child = node->firstChild();
375        while (child) {
376            Node* remove = child;
377            child = child->nextSibling();
378            removeNode(remove, shouldAssumeContentIsAlwaysEditable);
379        }
380
381        // Make sure empty cell has some height, if a placeholder can be inserted.
382        document().updateLayoutIgnorePendingStylesheets();
383        RenderObject *r = node->renderer();
384        if (r && r->isTableCell() && toRenderTableCell(r)->contentHeight() <= 0) {
385            Position firstEditablePosition = firstEditablePositionInNode(node.get());
386            if (firstEditablePosition.isNotNull())
387                insertBlockPlaceholder(firstEditablePosition);
388        }
389        return;
390    }
391
392    if (node == m_startBlock && !isEndOfBlock(VisiblePosition(firstPositionInNode(m_startBlock.get())).previous()))
393        m_needPlaceholder = true;
394    else if (node == m_endBlock && !isStartOfBlock(VisiblePosition(lastPositionInNode(m_startBlock.get())).next()))
395        m_needPlaceholder = true;
396
397    // FIXME: Update the endpoints of the range being deleted.
398    updatePositionForNodeRemoval(m_endingPosition, node.get());
399    updatePositionForNodeRemoval(m_leadingWhitespace, node.get());
400    updatePositionForNodeRemoval(m_trailingWhitespace, node.get());
401
402    CompositeEditCommand::removeNode(node, shouldAssumeContentIsAlwaysEditable);
403}
404
405static void updatePositionForTextRemoval(Node* node, int offset, int count, Position& position)
406{
407    if (position.anchorType() != Position::PositionIsOffsetInAnchor || position.containerNode() != node)
408        return;
409
410    if (position.offsetInContainerNode() > offset + count)
411        position.moveToOffset(position.offsetInContainerNode() - count);
412    else if (position.offsetInContainerNode() > offset)
413        position.moveToOffset(offset);
414}
415
416void DeleteSelectionCommand::deleteTextFromNode(PassRefPtr<Text> node, unsigned offset, unsigned count)
417{
418    // FIXME: Update the endpoints of the range being deleted.
419    updatePositionForTextRemoval(node.get(), offset, count, m_endingPosition);
420    updatePositionForTextRemoval(node.get(), offset, count, m_leadingWhitespace);
421    updatePositionForTextRemoval(node.get(), offset, count, m_trailingWhitespace);
422    updatePositionForTextRemoval(node.get(), offset, count, m_downstreamEnd);
423
424    CompositeEditCommand::deleteTextFromNode(node, offset, count);
425}
426
427void DeleteSelectionCommand::makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss()
428{
429    RefPtr<Range> range = m_selectionToDelete.toNormalizedRange();
430    RefPtr<Node> node = range->firstNode();
431    while (node && node != range->pastLastNode()) {
432        RefPtr<Node> nextNode = NodeTraversal::next(*node);
433        if ((node->hasTagName(styleTag) && !(toElement(node)->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
434            nextNode = NodeTraversal::nextSkippingChildren(*node);
435            RefPtr<ContainerNode> rootEditableElement = node->rootEditableElement();
436            if (rootEditableElement.get()) {
437                removeNode(node);
438                appendNode(node, rootEditableElement);
439            }
440        }
441        node = nextNode;
442    }
443}
444
445void DeleteSelectionCommand::handleGeneralDelete()
446{
447    if (m_upstreamStart.isNull())
448        return;
449
450    int startOffset = m_upstreamStart.deprecatedEditingOffset();
451    Node* startNode = m_upstreamStart.deprecatedNode();
452    ASSERT(startNode);
453
454    makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
455
456    // Never remove the start block unless it's a table, in which case we won't merge content in.
457    if (startNode->isSameNode(m_startBlock.get()) && !startOffset && canHaveChildrenForEditing(startNode) && !isHTMLTableElement(startNode)) {
458        startOffset = 0;
459        startNode = NodeTraversal::next(*startNode);
460        if (!startNode)
461            return;
462    }
463
464    if (startOffset >= caretMaxOffset(startNode) && startNode->isTextNode()) {
465        Text* text = toText(startNode);
466        if (text->length() > (unsigned)caretMaxOffset(startNode))
467            deleteTextFromNode(text, caretMaxOffset(startNode), text->length() - caretMaxOffset(startNode));
468    }
469
470    if (startOffset >= lastOffsetForEditing(startNode)) {
471        startNode = NodeTraversal::nextSkippingChildren(*startNode);
472        startOffset = 0;
473    }
474
475    // Done adjusting the start.  See if we're all done.
476    if (!startNode)
477        return;
478
479    if (startNode == m_downstreamEnd.deprecatedNode()) {
480        if (m_downstreamEnd.deprecatedEditingOffset() - startOffset > 0) {
481            if (startNode->isTextNode()) {
482                // in a text node that needs to be trimmed
483                Text* text = toText(startNode);
484                deleteTextFromNode(text, startOffset, m_downstreamEnd.deprecatedEditingOffset() - startOffset);
485            } else {
486                removeChildrenInRange(startNode, startOffset, m_downstreamEnd.deprecatedEditingOffset());
487                m_endingPosition = m_upstreamStart;
488            }
489        }
490
491        // The selection to delete is all in one node.
492        if (!startNode->renderer() || (!startOffset && m_downstreamEnd.atLastEditingPositionForNode()))
493            removeNode(startNode);
494    }
495    else {
496        bool startNodeWasDescendantOfEndNode = m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode());
497        // The selection to delete spans more than one node.
498        RefPtr<Node> node(startNode);
499
500        if (startOffset > 0) {
501            if (startNode->isTextNode()) {
502                // in a text node that needs to be trimmed
503                Text* text = toText(node);
504                deleteTextFromNode(text, startOffset, text->length() - startOffset);
505                node = NodeTraversal::next(*node);
506            } else {
507                node = startNode->childNode(startOffset);
508            }
509        } else if (startNode == m_upstreamEnd.deprecatedNode() && startNode->isTextNode()) {
510            Text* text = toText(m_upstreamEnd.deprecatedNode());
511            deleteTextFromNode(text, 0, m_upstreamEnd.deprecatedEditingOffset());
512        }
513
514        // handle deleting all nodes that are completely selected
515        while (node && node != m_downstreamEnd.deprecatedNode()) {
516            if (comparePositions(firstPositionInOrBeforeNode(node.get()), m_downstreamEnd) >= 0) {
517                // NodeTraversal::nextSkippingChildren just blew past the end position, so stop deleting
518                node = 0;
519            } else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
520                RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(*node);
521                // if we just removed a node from the end container, update end position so the
522                // check above will work
523                updatePositionForNodeRemoval(m_downstreamEnd, node.get());
524                removeNode(node.get());
525                node = nextNode.get();
526            } else {
527                Node& n = node->lastDescendant();
528                if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(&n)) {
529                    removeNode(node.get());
530                    node = 0;
531                } else {
532                    node = NodeTraversal::next(*node);
533                }
534            }
535        }
536
537        if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
538            if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.deprecatedNode())) {
539                // The node itself is fully selected, not just its contents.  Delete it.
540                removeNode(m_downstreamEnd.deprecatedNode());
541            } else {
542                if (m_downstreamEnd.deprecatedNode()->isTextNode()) {
543                    // in a text node that needs to be trimmed
544                    Text* text = toText(m_downstreamEnd.deprecatedNode());
545                    if (m_downstreamEnd.deprecatedEditingOffset() > 0) {
546                        deleteTextFromNode(text, 0, m_downstreamEnd.deprecatedEditingOffset());
547                    }
548                // Remove children of m_downstreamEnd.deprecatedNode() that come after m_upstreamStart.
549                // Don't try to remove children if m_upstreamStart was inside m_downstreamEnd.deprecatedNode()
550                // and m_upstreamStart has been removed from the document, because then we don't
551                // know how many children to remove.
552                // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
553                // always know which children to remove.
554                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.inDocument())) {
555                    int offset = 0;
556                    if (m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode())) {
557                        Node* n = m_upstreamStart.deprecatedNode();
558                        while (n && n->parentNode() != m_downstreamEnd.deprecatedNode())
559                            n = n->parentNode();
560                        if (n)
561                            offset = n->nodeIndex() + 1;
562                    }
563                    removeChildrenInRange(m_downstreamEnd.deprecatedNode(), offset, m_downstreamEnd.deprecatedEditingOffset());
564                    m_downstreamEnd = createLegacyEditingPosition(m_downstreamEnd.deprecatedNode(), offset);
565                }
566            }
567        }
568    }
569}
570
571void DeleteSelectionCommand::fixupWhitespace()
572{
573    document().updateLayoutIgnorePendingStylesheets();
574    // FIXME: isRenderedCharacter should be removed, and we should use VisiblePosition::characterAfter and VisiblePosition::characterBefore
575    if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharacter() && m_leadingWhitespace.deprecatedNode()->isTextNode()) {
576        Text* textNode = toText(m_leadingWhitespace.deprecatedNode());
577        ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
578        replaceTextInNodePreservingMarkers(textNode, m_leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
579    }
580    if (m_trailingWhitespace.isNotNull() && !m_trailingWhitespace.isRenderedCharacter() && m_trailingWhitespace.deprecatedNode()->isTextNode()) {
581        Text* textNode = toText(m_trailingWhitespace.deprecatedNode());
582        ASSERT(!textNode->renderer() ||textNode->renderer()->style()->collapseWhiteSpace());
583        replaceTextInNodePreservingMarkers(textNode, m_trailingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
584    }
585}
586
587// If a selection starts in one block and ends in another, we have to merge to bring content before the
588// start together with content after the end.
589void DeleteSelectionCommand::mergeParagraphs()
590{
591    if (!m_mergeBlocksAfterDelete) {
592        if (m_pruneStartBlockIfNecessary) {
593            // We aren't going to merge into the start block, so remove it if it's empty.
594            prune(m_startBlock);
595            // Removing the start block during a deletion is usually an indication that we need
596            // a placeholder, but not in this case.
597            m_needPlaceholder = false;
598        }
599        return;
600    }
601
602    // It shouldn't have been asked to both try and merge content into the start block and prune it.
603    ASSERT(!m_pruneStartBlockIfNecessary);
604
605    // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
606    if (!m_downstreamEnd.inDocument() || !m_upstreamStart.inDocument())
607         return;
608
609    // FIXME: The deletion algorithm shouldn't let this happen.
610    if (comparePositions(m_upstreamStart, m_downstreamEnd) > 0)
611        return;
612
613    // There's nothing to merge.
614    if (m_upstreamStart == m_downstreamEnd)
615        return;
616
617    VisiblePosition startOfParagraphToMove(m_downstreamEnd);
618    VisiblePosition mergeDestination(m_upstreamStart);
619
620    // m_downstreamEnd's block has been emptied out by deletion.  There is no content inside of it to
621    // move, so just remove it.
622    Element* endBlock = enclosingBlock(m_downstreamEnd.deprecatedNode());
623    if (!endBlock || !endBlock->contains(startOfParagraphToMove.deepEquivalent().deprecatedNode()) || !startOfParagraphToMove.deepEquivalent().deprecatedNode()) {
624        removeNode(enclosingBlock(m_downstreamEnd.deprecatedNode()));
625        return;
626    }
627
628    // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
629    if (!mergeDestination.deepEquivalent().deprecatedNode() || (!mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) && (!mergeDestination.deepEquivalent().anchorNode()->firstChild() || !m_upstreamStart.containerNode()->firstChild())) || (m_startsAtEmptyLine && mergeDestination != startOfParagraphToMove)) {
630        insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
631        mergeDestination = VisiblePosition(m_upstreamStart);
632    }
633
634    if (mergeDestination == startOfParagraphToMove)
635        return;
636
637    VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove);
638
639    if (mergeDestination == endOfParagraphToMove)
640        return;
641
642    // The rule for merging into an empty block is: only do so if its farther to the right.
643    // FIXME: Consider RTL.
644    if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfParagraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds().x()) {
645        if (mergeDestination.deepEquivalent().downstream().deprecatedNode()->hasTagName(brTag)) {
646            removeNodeAndPruneAncestors(mergeDestination.deepEquivalent().downstream().deprecatedNode());
647            m_endingPosition = startOfParagraphToMove.deepEquivalent();
648            return;
649        }
650    }
651
652    // Block images, tables and horizontal rules cannot be made inline with content at mergeDestination.  If there is
653    // any (!isStartOfParagraph(mergeDestination)), don't merge, just move the caret to just before the selection we deleted.
654    // See https://bugs.webkit.org/show_bug.cgi?id=25439
655    if (isRenderedAsNonInlineTableImageOrHR(startOfParagraphToMove.deepEquivalent().deprecatedNode()) && !isStartOfParagraph(mergeDestination)) {
656        m_endingPosition = m_upstreamStart;
657        return;
658    }
659
660    // moveParagraphs will insert placeholders if it removes blocks that would require their use, don't let block
661    // removals that it does cause the insertion of *another* placeholder.
662    bool needPlaceholder = m_needPlaceholder;
663    bool paragraphToMergeIsEmpty = (startOfParagraphToMove == endOfParagraphToMove);
664    moveParagraph(startOfParagraphToMove, endOfParagraphToMove, mergeDestination, false, !paragraphToMergeIsEmpty);
665    m_needPlaceholder = needPlaceholder;
666    // The endingPosition was likely clobbered by the move, so recompute it (moveParagraph selects the moved paragraph).
667    m_endingPosition = endingSelection().start();
668}
669
670void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows()
671{
672    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
673        Node* row = m_endTableRow->previousSibling();
674        while (row && row != m_startTableRow) {
675            RefPtr<Node> previousRow = row->previousSibling();
676            if (isTableRowEmpty(row))
677                // Use a raw removeNode, instead of DeleteSelectionCommand's, because
678                // that won't remove rows, it only empties them in preparation for this function.
679                CompositeEditCommand::removeNode(row);
680            row = previousRow.get();
681        }
682    }
683
684    // Remove empty rows after the start row.
685    if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m_endTableRow) {
686        Node* row = m_startTableRow->nextSibling();
687        while (row && row != m_endTableRow) {
688            RefPtr<Node> nextRow = row->nextSibling();
689            if (isTableRowEmpty(row))
690                CompositeEditCommand::removeNode(row);
691            row = nextRow.get();
692        }
693    }
694
695    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow)
696        if (isTableRowEmpty(m_endTableRow.get())) {
697            // Don't remove m_endTableRow if it's where we're putting the ending selection.
698            if (!m_endingPosition.deprecatedNode()->isDescendantOf(m_endTableRow.get())) {
699                // FIXME: We probably shouldn't remove m_endTableRow unless it's fully selected, even if it is empty.
700                // We'll need to start adjusting the selection endpoints during deletion to know whether or not m_endTableRow
701                // was fully selected here.
702                CompositeEditCommand::removeNode(m_endTableRow.get());
703            }
704        }
705}
706
707void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
708{
709    // Clearing any previously set typing style and doing an early return.
710    if (!m_typingStyle) {
711        document().frame()->selection().clearTypingStyle();
712        return;
713    }
714
715    // Compute the difference between the style before the delete and the style now
716    // after the delete has been done. Set this style on the frame, so other editing
717    // commands being composed with this one will work, and also cache it on the command,
718    // so the Frame::appliedEditing can set it after the whole composite command
719    // has completed.
720
721    // If we deleted into a blockquote, but are now no longer in a blockquote, use the alternate typing style
722    if (m_deleteIntoBlockquoteStyle && !enclosingNodeOfType(m_endingPosition, isMailBlockquote, CanCrossEditingBoundary))
723        m_typingStyle = m_deleteIntoBlockquoteStyle;
724    m_deleteIntoBlockquoteStyle = 0;
725
726    m_typingStyle->prepareToApplyAt(m_endingPosition);
727    if (m_typingStyle->isEmpty())
728        m_typingStyle = 0;
729    // This is where we've deleted all traces of a style but not a whole paragraph (that's handled above).
730    // In this case if we start typing, the new characters should have the same style as the just deleted ones,
731    // but, if we change the selection, come back and start typing that style should be lost.  Also see
732    // preserveTypingStyle() below.
733    document().frame()->selection().setTypingStyle(m_typingStyle);
734}
735
736void DeleteSelectionCommand::clearTransientState()
737{
738    m_selectionToDelete = VisibleSelection();
739    m_upstreamStart.clear();
740    m_downstreamStart.clear();
741    m_upstreamEnd.clear();
742    m_downstreamEnd.clear();
743    m_endingPosition.clear();
744    m_leadingWhitespace.clear();
745    m_trailingWhitespace.clear();
746}
747
748// This method removes div elements with no attributes that have only one child or no children at all.
749void DeleteSelectionCommand::removeRedundantBlocks()
750{
751    Node* node = m_endingPosition.containerNode();
752    Node* rootNode = node->rootEditableElement();
753
754    while (node != rootNode) {
755        if (isRemovableBlock(node)) {
756            if (node == m_endingPosition.anchorNode())
757                updatePositionForNodeRemovalPreservingChildren(m_endingPosition, node);
758
759            CompositeEditCommand::removeNodePreservingChildren(node);
760            node = m_endingPosition.anchorNode();
761        } else
762            node = node->parentNode();
763    }
764}
765
766void DeleteSelectionCommand::doApply()
767{
768    // If selection has not been set to a custom selection when the command was created,
769    // use the current ending selection.
770    if (!m_hasSelectionToDelete)
771        m_selectionToDelete = endingSelection();
772
773    if (!m_selectionToDelete.isNonOrphanedRange())
774        return;
775
776    // save this to later make the selection with
777    EAffinity affinity = m_selectionToDelete.affinity();
778
779    Position downstreamEnd = m_selectionToDelete.end().downstream();
780    bool rootWillStayOpenWithoutPlaceholder = downstreamEnd.containerNode() == downstreamEnd.containerNode()->rootEditableElement()
781        || (downstreamEnd.containerNode()->isTextNode() && downstreamEnd.containerNode()->parentNode() == downstreamEnd.containerNode()->rootEditableElement());
782    bool lineBreakAtEndOfSelectionToDelete = lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
783    m_needPlaceholder = !rootWillStayOpenWithoutPlaceholder
784        && isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditingBoundary)
785        && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBoundary)
786        && !lineBreakAtEndOfSelectionToDelete;
787    if (m_needPlaceholder) {
788        // Don't need a placeholder when deleting a selection that starts just before a table
789        // and ends inside it (we do need placeholders to hold open empty cells, but that's
790        // handled elsewhere).
791        if (Node* table = isLastPositionBeforeTable(m_selectionToDelete.visibleStart()))
792            if (m_selectionToDelete.end().deprecatedNode()->isDescendantOf(table))
793                m_needPlaceholder = false;
794    }
795
796
797    // set up our state
798    initializePositionData();
799
800    bool lineBreakBeforeStart = lineBreakExistsAtVisiblePosition(VisiblePosition(m_upstreamStart).previous());
801
802    // Delete any text that may hinder our ability to fixup whitespace after the delete
803    deleteInsignificantTextDownstream(m_trailingWhitespace);
804
805    saveTypingStyleState();
806
807    // deleting just a BR is handled specially, at least because we do not
808    // want to replace it with a placeholder BR!
809    if (handleSpecialCaseBRDelete()) {
810        calculateTypingStyleAfterDelete();
811        setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
812        clearTransientState();
813        rebalanceWhitespace();
814        return;
815    }
816
817    handleGeneralDelete();
818
819    fixupWhitespace();
820
821    mergeParagraphs();
822
823    removePreviouslySelectedEmptyTableRows();
824
825    if (!m_needPlaceholder && rootWillStayOpenWithoutPlaceholder) {
826        VisiblePosition visualEnding(m_endingPosition);
827        bool hasPlaceholder = lineBreakExistsAtVisiblePosition(visualEnding)
828            && visualEnding.next(CannotCrossEditingBoundary).isNull();
829        m_needPlaceholder = hasPlaceholder && lineBreakBeforeStart && !lineBreakAtEndOfSelectionToDelete;
830    }
831
832    RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
833
834    if (placeholder) {
835        if (m_sanitizeMarkup)
836            removeRedundantBlocks();
837        insertNodeAt(placeholder.get(), m_endingPosition);
838    }
839
840    rebalanceWhitespaceAt(m_endingPosition);
841
842    calculateTypingStyleAfterDelete();
843
844    setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelection().isDirectional()));
845    clearTransientState();
846}
847
848EditAction DeleteSelectionCommand::editingAction() const
849{
850    // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
851    // but in that case there's a TypingCommand that supplies the editingAction(), so
852    // the Undo menu correctly shows "Undo Typing"
853    return EditActionCut;
854}
855
856// Normally deletion doesn't preserve the typing style that was present before it.  For example,
857// type a character, Bold, then delete the character and start typing.  The Bold typing style shouldn't
858// stick around.  Deletion should preserve a typing style that *it* sets, however.
859bool DeleteSelectionCommand::preservesTypingStyle() const
860{
861    return m_typingStyle;
862}
863
864} // namespace WebCore
865