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