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