Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(22)

Side by Side Diff: Source/core/editing/DeleteSelectionCommand.cpp

Issue 1294543005: Move execCommand related files in core/editing/ related files into core/editing/commands/ (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@master
Patch Set: 2015-08-18T14:20:58 Rebase for merging code style fixes Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 "core/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/EditingUtilities.h"
36 #include "core/editing/Editor.h"
37 #include "core/editing/VisibleUnits.h"
38 #include "core/frame/LocalFrame.h"
39 #include "core/html/HTMLBRElement.h"
40 #include "core/html/HTMLInputElement.h"
41 #include "core/html/HTMLStyleElement.h"
42 #include "core/html/HTMLTableRowElement.h"
43 #include "core/layout/LayoutTableCell.h"
44 #include "core/layout/LayoutText.h"
45
46 namespace blink {
47
48 using namespace HTMLNames;
49
50 static bool isTableCellEmpty(Node* cell)
51 {
52 ASSERT(isTableCell(cell));
53 return VisiblePosition(firstPositionInNode(cell)).deepEquivalent() == Visibl ePosition(lastPositionInNode(cell)).deepEquivalent();
54 }
55
56 static bool isTableRowEmpty(Node* row)
57 {
58 if (!isHTMLTableRowElement(row))
59 return false;
60
61 for (Node* child = row->firstChild(); child; child = child->nextSibling()) {
62 if (isTableCell(child) && !isTableCellEmpty(child))
63 return false;
64 }
65 return true;
66 }
67
68 DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDel ete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMa rkup)
69 : CompositeEditCommand(document)
70 , m_hasSelectionToDelete(false)
71 , m_smartDelete(smartDelete)
72 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
73 , m_needPlaceholder(false)
74 , m_expandForSpecialElements(expandForSpecialElements)
75 , m_pruneStartBlockIfNecessary(false)
76 , m_startsAtEmptyLine(false)
77 , m_sanitizeMarkup(sanitizeMarkup)
78 , m_startBlock(nullptr)
79 , m_endBlock(nullptr)
80 , m_typingStyle(nullptr)
81 , m_deleteIntoBlockquoteStyle(nullptr)
82 {
83 }
84
85 DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection , bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup)
86 : CompositeEditCommand(*selection.start().document())
87 , m_hasSelectionToDelete(true)
88 , m_smartDelete(smartDelete)
89 , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
90 , m_needPlaceholder(false)
91 , m_expandForSpecialElements(expandForSpecialElements)
92 , m_pruneStartBlockIfNecessary(false)
93 , m_startsAtEmptyLine(false)
94 , m_sanitizeMarkup(sanitizeMarkup)
95 , m_selectionToDelete(selection)
96 , m_startBlock(nullptr)
97 , m_endBlock(nullptr)
98 , m_typingStyle(nullptr)
99 , m_deleteIntoBlockquoteStyle(nullptr)
100 {
101 }
102
103 void DeleteSelectionCommand::initializeStartEnd(Position& start, Position& end)
104 {
105 HTMLElement* startSpecialContainer = nullptr;
106 HTMLElement* endSpecialContainer = nullptr;
107
108 start = m_selectionToDelete.start();
109 end = m_selectionToDelete.end();
110
111 // For HRs, we'll get a position at (HR,1) when hitting delete from the begi nning of the previous line, or (HR,0) when forward deleting,
112 // but in these cases, we want to delete it, so manually expand the selectio n
113 if (isHTMLHRElement(*start.anchorNode()))
114 start = positionBeforeNode(start.anchorNode());
115 else if (isHTMLHRElement(*end.anchorNode()))
116 end = positionAfterNode(end.anchorNode());
117
118 // FIXME: This is only used so that moveParagraphs can avoid the bugs in spe cial element expansion.
119 if (!m_expandForSpecialElements)
120 return;
121
122 while (1) {
123 startSpecialContainer = 0;
124 endSpecialContainer = 0;
125
126 Position s = positionBeforeContainingSpecialElement(start, &startSpecial Container);
127 Position e = positionAfterContainingSpecialElement(end, &endSpecialConta iner);
128
129 if (!startSpecialContainer && !endSpecialContainer)
130 break;
131
132 if (VisiblePosition(start).deepEquivalent() != m_selectionToDelete.visib leStart().deepEquivalent() || VisiblePosition(end).deepEquivalent() != m_selecti onToDelete.visibleEnd().deepEquivalent())
133 break;
134
135 // If we're going to expand to include the startSpecialContainer, it mus t be fully selected.
136 if (startSpecialContainer && !endSpecialContainer && comparePositions(po sitionInParentAfterNode(*startSpecialContainer), end) > -1)
137 break;
138
139 // If we're going to expand to include the endSpecialContainer, it must be fully selected.
140 if (endSpecialContainer && !startSpecialContainer && comparePositions(st art, positionInParentBeforeNode(*endSpecialContainer)) > -1)
141 break;
142
143 if (startSpecialContainer && startSpecialContainer->isDescendantOf(endSp ecialContainer)) {
144 // Don't adjust the end yet, it is the end of a special element that contains the start
145 // special element (which may or may not be fully selected).
146 start = s;
147 } else if (endSpecialContainer && endSpecialContainer->isDescendantOf(st artSpecialContainer)) {
148 // Don't adjust the start yet, it is the start of a special element that contains the end
149 // special element (which may or may not be fully selected).
150 end = e;
151 } else {
152 start = s;
153 end = e;
154 }
155 }
156 }
157
158 void DeleteSelectionCommand::setStartingSelectionOnSmartDelete(const Position& s tart, const Position& end)
159 {
160 bool isBaseFirst = startingSelection().isBaseFirst();
161 VisiblePosition newBase(isBaseFirst ? start : end);
162 VisiblePosition newExtent(isBaseFirst ? end : start);
163 setStartingSelection(VisibleSelection(newBase, newExtent, startingSelection( ).isDirectional()));
164 }
165
166 void DeleteSelectionCommand::initializePositionData()
167 {
168 Position start, end;
169 initializeStartEnd(start, end);
170
171 ASSERT(isEditablePosition(start, ContentIsEditable, DoNotUpdateStyle));
172 if (!isEditablePosition(end, ContentIsEditable, DoNotUpdateStyle))
173 end = lastEditablePositionBeforePositionInRoot(end, highestEditableRoot( start));
174
175 m_upstreamStart = start.upstream();
176 m_downstreamStart = start.downstream();
177 m_upstreamEnd = end.upstream();
178 m_downstreamEnd = end.downstream();
179
180 m_startRoot = editableRootForPosition(start);
181 m_endRoot = editableRootForPosition(end);
182
183 m_startTableRow = toHTMLTableRowElement(enclosingNodeOfType(start, &isHTMLTa bleRowElement));
184 m_endTableRow = toHTMLTableRowElement(enclosingNodeOfType(end, &isHTMLTableR owElement));
185
186 // Don't move content out of a table cell.
187 // If the cell is non-editable, enclosingNodeOfType won't return it by defau lt, so
188 // tell that function that we don't care if it returns non-editable nodes.
189 Node* startCell = enclosingNodeOfType(m_upstreamStart, &isTableCell, CanCros sEditingBoundary);
190 Node* endCell = enclosingNodeOfType(m_downstreamEnd, &isTableCell, CanCrossE ditingBoundary);
191 // FIXME: This isn't right. A borderless table with two rows and a single c olumn would appear as two paragraphs.
192 if (endCell && endCell != startCell)
193 m_mergeBlocksAfterDelete = false;
194
195 // Usually the start and the end of the selection to delete are pulled toget her as a result of the deletion.
196 // Sometimes they aren't (like when no merge is requested), so we must choos e one position to hold the caret
197 // and receive the placeholder after deletion.
198 VisiblePosition visibleEnd(m_downstreamEnd);
199 if (m_mergeBlocksAfterDelete && !isEndOfParagraph(visibleEnd))
200 m_endingPosition = m_downstreamEnd;
201 else
202 m_endingPosition = m_downstreamStart;
203
204 // We don't want to merge into a block if it will mean changing the quote le vel of content after deleting
205 // selections that contain a whole number paragraphs plus a line break, sinc e it is unclear to most users
206 // that such a selection actually ends at the start of the next paragraph. T his matches TextEdit behavior
207 // for indented paragraphs.
208 // Only apply this rule if the endingSelection is a range selection. If it is a caret, then other operations have created
209 // 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 .
210 if (numEnclosingMailBlockquotes(start) != numEnclosingMailBlockquotes(end)
211 && isStartOfParagraph(visibleEnd) && isStartOfParagraph(VisiblePosition( start))
212 && endingSelection().isRange()) {
213 m_mergeBlocksAfterDelete = false;
214 m_pruneStartBlockIfNecessary = true;
215 }
216
217 // Handle leading and trailing whitespace, as well as smart delete adjustmen ts to the selection
218 m_leadingWhitespace = leadingWhitespacePosition(m_upstreamStart, m_selection ToDelete.affinity());
219 m_trailingWhitespace = trailingWhitespacePosition(m_downstreamEnd, VP_DEFAUL T_AFFINITY);
220
221 if (m_smartDelete) {
222
223 // skip smart delete if the selection to delete already starts or ends w ith whitespace
224 Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.affi nity()).deepEquivalent();
225 bool skipSmartDelete = trailingWhitespacePosition(pos, VP_DEFAULT_AFFINI TY, ConsiderNonCollapsibleWhitespace).isNotNull();
226 if (!skipSmartDelete)
227 skipSmartDelete = leadingWhitespacePosition(m_downstreamEnd, VP_DEFA ULT_AFFINITY, ConsiderNonCollapsibleWhitespace).isNotNull();
228
229 // extend selection upstream if there is whitespace there
230 bool hasLeadingWhitespaceBeforeAdjustment = leadingWhitespacePosition(m_ upstreamStart, m_selectionToDelete.affinity(), ConsiderNonCollapsibleWhitespace) .isNotNull();
231 if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
232 VisiblePosition visiblePos = VisiblePosition(m_upstreamStart, VP_DEF AULT_AFFINITY).previous();
233 pos = visiblePos.deepEquivalent();
234 // Expand out one character upstream for smart delete and recalculat e
235 // positions based on this change.
236 m_upstreamStart = pos.upstream();
237 m_downstreamStart = pos.downstream();
238 m_leadingWhitespace = leadingWhitespacePosition(m_upstreamStart, vis iblePos.affinity());
239
240 setStartingSelectionOnSmartDelete(m_upstreamStart, m_upstreamEnd);
241 }
242
243 // trailing whitespace is only considered for smart delete if there is n o leading
244 // whitespace, as in the case where you double-click the first word of a paragraph.
245 if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && trailin gWhitespacePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY, ConsiderNonCollapsible Whitespace).isNotNull()) {
246 // Expand out one character downstream for smart delete and recalcul ate
247 // positions based on this change.
248 pos = VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY).next().d eepEquivalent();
249 m_upstreamEnd = pos.upstream();
250 m_downstreamEnd = pos.downstream();
251 m_trailingWhitespace = trailingWhitespacePosition(m_downstreamEnd, V P_DEFAULT_AFFINITY);
252
253 setStartingSelectionOnSmartDelete(m_downstreamStart, m_downstreamEnd );
254 }
255 }
256
257 // We must pass call parentAnchoredEquivalent on the positions since some ed iting positions
258 // that appear inside their nodes aren't really inside them. [hr, 0] is one example.
259 // FIXME: parentAnchoredEquivalent should eventually be moved into enclosing element getters
260 // like the one below, since editing functions should obviously accept editi ng positions.
261 // FIXME: Passing false to enclosingNodeOfType tells it that it's OK to retu rn a non-editable
262 // node. This was done to match existing behavior, but it seems wrong.
263 m_startBlock = enclosingNodeOfType(m_downstreamStart.parentAnchoredEquivalen t(), &isBlock, CanCrossEditingBoundary);
264 m_endBlock = enclosingNodeOfType(m_upstreamEnd.parentAnchoredEquivalent(), & isBlock, CanCrossEditingBoundary);
265 }
266
267 // We don't want to inherit style from an element which can't have contents.
268 static bool shouldNotInheritStyleFrom(const Node& node)
269 {
270 return !node.canContainRangeEndPoint();
271 }
272
273 void DeleteSelectionCommand::saveTypingStyleState()
274 {
275 // A common case is deleting characters that are all from the same text node . In
276 // that case, the style at the start of the selection before deletion will b e the
277 // same as the style at the start of the selection after deletion (since tho se
278 // two positions will be identical). Therefore there is no need to save the
279 // typing style at the start of the selection, nor is there a reason to
280 // compute the style at the start of the selection after deletion (see the
281 // early return in calculateTypingStyleAfterDelete).
282 if (m_upstreamStart.anchorNode() == m_downstreamEnd.anchorNode() && m_upstre amStart.anchorNode()->isTextNode())
283 return;
284
285 if (shouldNotInheritStyleFrom(*m_selectionToDelete.start().anchorNode()))
286 return;
287
288 // Figure out the typing style in effect before the delete is done.
289 m_typingStyle = EditingStyle::create(m_selectionToDelete.start(), EditingSty le::EditingPropertiesInEffect);
290 m_typingStyle->removeStyleAddedByElement(enclosingAnchorElement(m_selectionT oDelete.start()));
291
292 // If we're deleting into a Mail blockquote, save the style at end() instead of start()
293 // We'll use this later in computeTypingStyleAfterDelete if we end up outsid e of a Mail blockquote
294 if (enclosingNodeOfType(m_selectionToDelete.start(), isMailHTMLBlockquoteEle ment))
295 m_deleteIntoBlockquoteStyle = EditingStyle::create(m_selectionToDelete.e nd());
296 else
297 m_deleteIntoBlockquoteStyle = nullptr;
298 }
299
300 bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
301 {
302 Node* nodeAfterUpstreamStart = m_upstreamStart.computeNodeAfterPosition();
303 Node* nodeAfterDownstreamStart = m_downstreamStart.computeNodeAfterPosition( );
304 // Upstream end will appear before BR due to canonicalization
305 Node* nodeAfterUpstreamEnd = m_upstreamEnd.computeNodeAfterPosition();
306
307 if (!nodeAfterUpstreamStart || !nodeAfterDownstreamStart)
308 return false;
309
310 // Check for special-case where the selection contains only a BR on a line b y itself after another BR.
311 bool upstreamStartIsBR = isHTMLBRElement(*nodeAfterUpstreamStart);
312 bool downstreamStartIsBR = isHTMLBRElement(*nodeAfterDownstreamStart);
313 bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && nodeAf terDownstreamStart == nodeAfterUpstreamEnd;
314 if (isBROnLineByItself) {
315 removeNode(nodeAfterDownstreamStart);
316 return true;
317 }
318
319 // FIXME: This code doesn't belong in here.
320 // We detect the case where the start is an empty line consisting of BR not wrapped in a block element.
321 if (upstreamStartIsBR && downstreamStartIsBR && !(isStartOfBlock(VisiblePosi tion(positionBeforeNode(nodeAfterUpstreamStart))) && isEndOfBlock(VisiblePositio n(positionAfterNode(nodeAfterUpstreamStart))))) {
322 m_startsAtEmptyLine = true;
323 m_endingPosition = m_downstreamEnd;
324 }
325
326 return false;
327 }
328
329 static Position firstEditablePositionInNode(Node* node)
330 {
331 ASSERT(node);
332 Node* next = node;
333 while (next && !next->hasEditableStyle())
334 next = NodeTraversal::next(*next, node);
335 return next ? firstPositionInOrBeforeNode(next) : Position();
336 }
337
338 void DeleteSelectionCommand::removeNode(PassRefPtrWillBeRawPtr<Node> node, Shoul dAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
339 {
340 if (!node)
341 return;
342
343 if (m_startRoot != m_endRoot && !(node->isDescendantOf(m_startRoot.get()) && node->isDescendantOf(m_endRoot.get()))) {
344 // If a node is not in both the start and end editable roots, remove it only if its inside an editable region.
345 if (!node->parentNode()->hasEditableStyle()) {
346 // Don't remove non-editable atomic nodes.
347 if (!node->hasChildren())
348 return;
349 // Search this non-editable region for editable regions to empty.
350 RefPtrWillBeRawPtr<Node> child = node->firstChild();
351 while (child) {
352 RefPtrWillBeRawPtr<Node> nextChild = child->nextSibling();
353 removeNode(child.get(), shouldAssumeContentIsAlwaysEditable);
354 // Bail if nextChild is no longer node's child.
355 if (nextChild && nextChild->parentNode() != node)
356 return;
357 child = nextChild;
358 }
359
360 // Don't remove editable regions that are inside non-editable ones, just clear them.
361 return;
362 }
363 }
364
365 if (isTableStructureNode(node.get()) || node->isRootEditableElement()) {
366 // Do not remove an element of table structure; remove its contents.
367 // Likewise for the root editable element.
368 Node* child = node->firstChild();
369 while (child) {
370 Node* remove = child;
371 child = child->nextSibling();
372 removeNode(remove, shouldAssumeContentIsAlwaysEditable);
373 }
374
375 // Make sure empty cell has some height, if a placeholder can be inserte d.
376 document().updateLayoutIgnorePendingStylesheets();
377 LayoutObject* r = node->layoutObject();
378 if (r && r->isTableCell() && toLayoutTableCell(r)->contentHeight() <= 0) {
379 Position firstEditablePosition = firstEditablePositionInNode(node.ge t());
380 if (firstEditablePosition.isNotNull())
381 insertBlockPlaceholder(firstEditablePosition);
382 }
383 return;
384 }
385
386 if (node == m_startBlock) {
387 VisiblePosition previous = VisiblePosition(firstPositionInNode(m_startBl ock.get())).previous();
388 if (previous.isNotNull() && !isEndOfBlock(previous))
389 m_needPlaceholder = true;
390 }
391 if (node == m_endBlock) {
392 VisiblePosition next = VisiblePosition(lastPositionInNode(m_endBlock.get ())).next();
393 if (next.isNotNull() && !isStartOfBlock(next))
394 m_needPlaceholder = true;
395 }
396
397 // FIXME: Update the endpoints of the range being deleted.
398 updatePositionForNodeRemoval(m_endingPosition, *node);
399 updatePositionForNodeRemoval(m_leadingWhitespace, *node);
400 updatePositionForNodeRemoval(m_trailingWhitespace, *node);
401
402 CompositeEditCommand::removeNode(node, shouldAssumeContentIsAlwaysEditable);
403 }
404
405 static void updatePositionForTextRemoval(Text* node, int offset, int count, Posi tion& position)
406 {
407 if (!position.isOffsetInAnchor() || position.computeContainerNode() != node)
408 return;
409
410 if (position.offsetInContainerNode() > offset + count)
411 position = Position(position.computeContainerNode(), position.offsetInCo ntainerNode() - count);
412 else if (position.offsetInContainerNode() > offset)
413 position = Position(position.computeContainerNode(), offset);
414 }
415
416 void DeleteSelectionCommand::deleteTextFromNode(PassRefPtrWillBeRawPtr<Text> nod e, 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
427 void DeleteSelectionCommand::makeStylingElementsDirectChildrenOfEditableRootToPr eventStyleLoss()
428 {
429 RefPtrWillBeRawPtr<Range> range = m_selectionToDelete.toNormalizedRange();
430 RefPtrWillBeRawPtr<Node> node = range->firstNode();
431 while (node && node != range->pastLastNode()) {
432 RefPtrWillBeRawPtr<Node> nextNode = NodeTraversal::next(*node);
433 if (isHTMLStyleElement(*node) || isHTMLLinkElement(*node)) {
434 nextNode = NodeTraversal::nextSkippingChildren(*node);
435 RefPtrWillBeRawPtr<Element> rootEditableElement = node->rootEditable Element();
436 if (rootEditableElement.get()) {
437 removeNode(node);
438 appendNode(node, rootEditableElement);
439 }
440 }
441 node = nextNode;
442 }
443 }
444
445 void DeleteSelectionCommand::handleGeneralDelete()
446 {
447 if (m_upstreamStart.isNull())
448 return;
449
450 int startOffset = m_upstreamStart.computeEditingOffset();
451 Node* startNode = m_upstreamStart.anchorNode();
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 && canHaveChil drenForEditing(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 >= EditingStrategy::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.anchorNode()) {
480 if (m_downstreamEnd.computeEditingOffset() - 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.computeOff setInContainerNode() - startOffset);
485 } else {
486 removeChildrenInRange(startNode, startOffset, m_downstreamEnd.co mputeEditingOffset());
487 m_endingPosition = m_upstreamStart;
488 }
489 }
490
491 // The selection to delete is all in one node.
492 if (!startNode->layoutObject() || (!startOffset && m_downstreamEnd.atLas tEditingPositionForNode()))
493 removeNode(startNode);
494 } else {
495 bool startNodeWasDescendantOfEndNode = m_upstreamStart.anchorNode()->isD escendantOf(m_downstreamEnd.anchorNode());
496 // The selection to delete spans more than one node.
497 RefPtrWillBeRawPtr<Node> node(startNode);
498
499 if (startOffset > 0) {
500 if (startNode->isTextNode()) {
501 // in a text node that needs to be trimmed
502 Text* text = toText(node);
503 deleteTextFromNode(text, startOffset, text->length() - startOffs et);
504 node = NodeTraversal::next(*node);
505 } else {
506 node = NodeTraversal::childAt(*startNode, startOffset);
507 }
508 } else if (startNode == m_upstreamEnd.anchorNode() && startNode->isTextN ode()) {
509 Text* text = toText(m_upstreamEnd.anchorNode());
510 deleteTextFromNode(text, 0, m_upstreamEnd.computeOffsetInContainerNo de());
511 }
512
513 // handle deleting all nodes that are completely selected
514 while (node && node != m_downstreamEnd.anchorNode()) {
515 if (comparePositions(firstPositionInOrBeforeNode(node.get()), m_down streamEnd) >= 0) {
516 // NodeTraversal::nextSkippingChildren just blew past the end po sition, so stop deleting
517 node = nullptr;
518 } else if (!m_downstreamEnd.anchorNode()->isDescendantOf(node.get()) ) {
519 RefPtrWillBeRawPtr<Node> nextNode = NodeTraversal::nextSkippingC hildren(*node);
520 // if we just removed a node from the end container, update end position so the
521 // check above will work
522 updatePositionForNodeRemoval(m_downstreamEnd, *node);
523 removeNode(node.get());
524 node = nextNode.get();
525 } else {
526 Node& n = NodeTraversal::lastWithinOrSelf(*node);
527 if (m_downstreamEnd.anchorNode() == n && m_downstreamEnd.compute EditingOffset() >= caretMaxOffset(&n)) {
528 removeNode(node.get());
529 node = nullptr;
530 } else {
531 node = NodeTraversal::next(*node);
532 }
533 }
534 }
535
536 if (m_downstreamEnd.anchorNode() != startNode && !m_upstreamStart.anchor Node()->isDescendantOf(m_downstreamEnd.anchorNode()) && m_downstreamEnd.inDocume nt() && m_downstreamEnd.computeEditingOffset() >= caretMinOffset(m_downstreamEnd .anchorNode())) {
537 if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildr enForEditing(m_downstreamEnd.anchorNode())) {
538 // The node itself is fully selected, not just its contents. De lete it.
539 removeNode(m_downstreamEnd.anchorNode());
540 } else {
541 if (m_downstreamEnd.anchorNode()->isTextNode()) {
542 // in a text node that needs to be trimmed
543 Text* text = toText(m_downstreamEnd.anchorNode());
544 if (m_downstreamEnd.computeEditingOffset() > 0) {
545 deleteTextFromNode(text, 0, m_downstreamEnd.computeEditi ngOffset());
546 }
547 // Remove children of m_downstreamEnd.anchorNode() that come aft er m_upstreamStart.
548 // Don't try to remove children if m_upstreamStart was inside m_ downstreamEnd.anchorNode()
549 // and m_upstreamStart has been removed from the document, becau se then we don't
550 // know how many children to remove.
551 // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
552 // always know which children to remove.
553 } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart .inDocument())) {
554 int offset = 0;
555 if (m_upstreamStart.anchorNode()->isDescendantOf(m_downstrea mEnd.anchorNode())) {
556 Node* n = m_upstreamStart.anchorNode();
557 while (n && n->parentNode() != m_downstreamEnd.anchorNod e())
558 n = n->parentNode();
559 if (n)
560 offset = n->nodeIndex() + 1;
561 }
562 removeChildrenInRange(m_downstreamEnd.anchorNode(), offset, m_downstreamEnd.computeEditingOffset());
563 m_downstreamEnd = createLegacyEditingPosition(m_downstreamEn d.anchorNode(), offset);
564 }
565 }
566 }
567 }
568 }
569
570 void DeleteSelectionCommand::fixupWhitespace()
571 {
572 document().updateLayoutIgnorePendingStylesheets();
573 // FIXME: isRenderedCharacter should be removed, and we should use VisiblePo sition::characterAfter and VisiblePosition::characterBefore
574 if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharac ter() && m_leadingWhitespace.anchorNode()->isTextNode()) {
575 Text* textNode = toText(m_leadingWhitespace.anchorNode());
576 ASSERT(!textNode->layoutObject() || textNode->layoutObject()->style()->c ollapseWhiteSpace());
577 replaceTextInNodePreservingMarkers(textNode, m_leadingWhitespace.compute OffsetInContainerNode(), 1, nonBreakingSpaceString());
578 }
579 if (m_trailingWhitespace.isNotNull() && !m_trailingWhitespace.isRenderedChar acter() && m_trailingWhitespace.anchorNode()->isTextNode()) {
580 Text* textNode = toText(m_trailingWhitespace.anchorNode());
581 ASSERT(!textNode->layoutObject() || textNode->layoutObject()->style()->c ollapseWhiteSpace());
582 replaceTextInNodePreservingMarkers(textNode, m_trailingWhitespace.comput eOffsetInContainerNode(), 1, nonBreakingSpaceString());
583 }
584 }
585
586 // If a selection starts in one block and ends in another, we have to merge to b ring content before the
587 // start together with content after the end.
588 void DeleteSelectionCommand::mergeParagraphs()
589 {
590 if (!m_mergeBlocksAfterDelete) {
591 if (m_pruneStartBlockIfNecessary) {
592 // We aren't going to merge into the start block, so remove it if it 's empty.
593 prune(m_startBlock);
594 // Removing the start block during a deletion is usually an indicati on that we need
595 // a placeholder, but not in this case.
596 m_needPlaceholder = false;
597 }
598 return;
599 }
600
601 // It shouldn't have been asked to both try and merge content into the start block and prune it.
602 ASSERT(!m_pruneStartBlockIfNecessary);
603
604 // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
605 if (!m_downstreamEnd.inDocument() || !m_upstreamStart.inDocument())
606 return;
607
608 // FIXME: The deletion algorithm shouldn't let this happen.
609 if (comparePositions(m_upstreamStart, m_downstreamEnd) > 0)
610 return;
611
612 // There's nothing to merge.
613 if (m_upstreamStart == m_downstreamEnd)
614 return;
615
616 VisiblePosition startOfParagraphToMove(m_downstreamEnd);
617 VisiblePosition mergeDestination(m_upstreamStart);
618
619 // m_downstreamEnd's block has been emptied out by deletion. There is no co ntent inside of it to
620 // move, so just remove it.
621 Element* endBlock = enclosingBlock(m_downstreamEnd.anchorNode());
622 if (!endBlock || !endBlock->contains(startOfParagraphToMove.deepEquivalent() .anchorNode()) || !startOfParagraphToMove.deepEquivalent().anchorNode()) {
623 removeNode(enclosingBlock(m_downstreamEnd.anchorNode()));
624 return;
625 }
626
627 // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
628 if (!mergeDestination.deepEquivalent().anchorNode() || (!mergeDestination.de epEquivalent().anchorNode()->isDescendantOf(enclosingBlock(m_upstreamStart.compu teContainerNode())) && (!mergeDestination.deepEquivalent().anchorNode()->hasChil dren() || !m_upstreamStart.computeContainerNode()->hasChildren())) || (m_startsA tEmptyLine && mergeDestination.deepEquivalent() != startOfParagraphToMove.deepEq uivalent())) {
629 insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
630 mergeDestination = VisiblePosition(m_upstreamStart);
631 }
632
633 if (mergeDestination.deepEquivalent() == startOfParagraphToMove.deepEquivale nt())
634 return;
635
636 VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove , CanSkipOverEditingBoundary);
637
638 if (mergeDestination.deepEquivalent() == endOfParagraphToMove.deepEquivalent ())
639 return;
640
641 // If the merge destination and source to be moved are both list items of di fferent lists, merge them into single list.
642 Node* listItemInFirstParagraph = enclosingNodeOfType(m_upstreamStart, isList Item);
643 Node* listItemInSecondParagraph = enclosingNodeOfType(m_downstreamEnd, isLis tItem);
644 if (listItemInFirstParagraph && listItemInSecondParagraph
645 && listItemInFirstParagraph->parentElement() != listItemInSecondParagrap h->parentElement()
646 && canMergeLists(listItemInFirstParagraph->parentElement(), listItemInSe condParagraph->parentElement())) {
647 mergeIdenticalElements(listItemInFirstParagraph->parentElement(), listIt emInSecondParagraph->parentElement());
648 m_endingPosition = mergeDestination.deepEquivalent();
649 return;
650 }
651
652 // The rule for merging into an empty block is: only do so if its farther to the right.
653 // FIXME: Consider RTL.
654 if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfP aragraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds( ).x()) {
655 if (isHTMLBRElement(*mergeDestination.deepEquivalent().downstream().anch orNode())) {
656 removeNodeAndPruneAncestors(mergeDestination.deepEquivalent().downst ream().anchorNode());
657 m_endingPosition = startOfParagraphToMove.deepEquivalent();
658 return;
659 }
660 }
661
662 // Block images, tables and horizontal rules cannot be made inline with cont ent at mergeDestination. If there is
663 // any (!isStartOfParagraph(mergeDestination)), don't merge, just move the c aret to just before the selection we deleted.
664 // See https://bugs.webkit.org/show_bug.cgi?id=25439
665 if (isRenderedAsNonInlineTableImageOrHR(startOfParagraphToMove.deepEquivalen t().anchorNode()) && !isStartOfParagraph(mergeDestination)) {
666 m_endingPosition = m_upstreamStart;
667 return;
668 }
669
670 // moveParagraphs will insert placeholders if it removes blocks that would r equire their use, don't let block
671 // removals that it does cause the insertion of *another* placeholder.
672 bool needPlaceholder = m_needPlaceholder;
673 bool paragraphToMergeIsEmpty = startOfParagraphToMove.deepEquivalent() == en dOfParagraphToMove.deepEquivalent();
674 moveParagraph(startOfParagraphToMove, endOfParagraphToMove, mergeDestination , false, !paragraphToMergeIsEmpty);
675 m_needPlaceholder = needPlaceholder;
676 // The endingPosition was likely clobbered by the move, so recompute it (mov eParagraph selects the moved paragraph).
677 m_endingPosition = endingSelection().start();
678 }
679
680 void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows()
681 {
682 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_start TableRow) {
683 Node* row = m_endTableRow->previousSibling();
684 while (row && row != m_startTableRow) {
685 RefPtrWillBeRawPtr<Node> previousRow = row->previousSibling();
686 if (isTableRowEmpty(row)) {
687 // Use a raw removeNode, instead of DeleteSelectionCommand's,
688 // because that won't remove rows, it only empties them in
689 // preparation for this function.
690 CompositeEditCommand::removeNode(row);
691 }
692 row = previousRow.get();
693 }
694 }
695
696 // Remove empty rows after the start row.
697 if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m _endTableRow) {
698 Node* row = m_startTableRow->nextSibling();
699 while (row && row != m_endTableRow) {
700 RefPtrWillBeRawPtr<Node> nextRow = row->nextSibling();
701 if (isTableRowEmpty(row))
702 CompositeEditCommand::removeNode(row);
703 row = nextRow.get();
704 }
705 }
706
707 if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_start TableRow) {
708 if (isTableRowEmpty(m_endTableRow.get())) {
709 // Don't remove m_endTableRow if it's where we're putting the ending
710 // selection.
711 if (!m_endingPosition.anchorNode()->isDescendantOf(m_endTableRow.get ())) {
712 // FIXME: We probably shouldn't remove m_endTableRow unless it's
713 // fully selected, even if it is empty. We'll need to start
714 // adjusting the selection endpoints during deletion to know
715 // whether or not m_endTableRow was fully selected here.
716 CompositeEditCommand::removeNode(m_endTableRow.get());
717 }
718 }
719 }
720 }
721
722 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
723 {
724 // Clearing any previously set typing style and doing an early return.
725 if (!m_typingStyle) {
726 document().frame()->selection().clearTypingStyle();
727 return;
728 }
729
730 // Compute the difference between the style before the delete and the style now
731 // after the delete has been done. Set this style on the frame, so other edi ting
732 // commands being composed with this one will work, and also cache it on the command,
733 // so the LocalFrame::appliedEditing can set it after the whole composite co mmand
734 // has completed.
735
736 // If we deleted into a blockquote, but are now no longer in a blockquote, u se the alternate typing style
737 if (m_deleteIntoBlockquoteStyle && !enclosingNodeOfType(m_endingPosition, is MailHTMLBlockquoteElement, CanCrossEditingBoundary))
738 m_typingStyle = m_deleteIntoBlockquoteStyle;
739 m_deleteIntoBlockquoteStyle = nullptr;
740
741 m_typingStyle->prepareToApplyAt(m_endingPosition);
742 if (m_typingStyle->isEmpty())
743 m_typingStyle = nullptr;
744 // This is where we've deleted all traces of a style but not a whole paragra ph (that's handled above).
745 // In this case if we start typing, the new characters should have the same style as the just deleted ones,
746 // but, if we change the selection, come back and start typing that style sh ould be lost. Also see
747 // preserveTypingStyle() below.
748 document().frame()->selection().setTypingStyle(m_typingStyle);
749 }
750
751 void DeleteSelectionCommand::clearTransientState()
752 {
753 m_selectionToDelete = VisibleSelection();
754 m_upstreamStart = Position();
755 m_downstreamStart = Position();
756 m_upstreamEnd = Position();
757 m_downstreamEnd = Position();
758 m_endingPosition = Position();
759 m_leadingWhitespace = Position();
760 m_trailingWhitespace = Position();
761 }
762
763 // This method removes div elements with no attributes that have only one child or no children at all.
764 void DeleteSelectionCommand::removeRedundantBlocks()
765 {
766 Node* node = m_endingPosition.computeContainerNode();
767 Element* rootElement = node->rootEditableElement();
768
769 while (node != rootElement) {
770 if (isRemovableBlock(node)) {
771 if (node == m_endingPosition.anchorNode())
772 updatePositionForNodeRemovalPreservingChildren(m_endingPosition, *node);
773
774 CompositeEditCommand::removeNodePreservingChildren(node);
775 node = m_endingPosition.anchorNode();
776 } else {
777 node = node->parentNode();
778 }
779 }
780 }
781
782 void DeleteSelectionCommand::doApply()
783 {
784 // If selection has not been set to a custom selection when the command was created,
785 // use the current ending selection.
786 if (!m_hasSelectionToDelete)
787 m_selectionToDelete = endingSelection();
788
789 if (!m_selectionToDelete.isNonOrphanedRange() || !m_selectionToDelete.isCont entEditable())
790 return;
791
792 // save this to later make the selection with
793 EAffinity affinity = m_selectionToDelete.affinity();
794
795 Position downstreamEnd = m_selectionToDelete.end().downstream();
796 bool rootWillStayOpenWithoutPlaceholder = downstreamEnd.computeContainerNode () == downstreamEnd.computeContainerNode()->rootEditableElement()
797 || (downstreamEnd.computeContainerNode()->isTextNode() && downstreamEnd. computeContainerNode()->parentNode() == downstreamEnd.computeContainerNode()->ro otEditableElement());
798 bool lineBreakAtEndOfSelectionToDelete = lineBreakExistsAtVisiblePosition(m_ selectionToDelete.visibleEnd());
799 m_needPlaceholder = !rootWillStayOpenWithoutPlaceholder
800 && isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditin gBoundary)
801 && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBou ndary)
802 && !lineBreakAtEndOfSelectionToDelete;
803 if (m_needPlaceholder) {
804 // Don't need a placeholder when deleting a selection that starts just
805 // before a table and ends inside it (we do need placeholders to hold
806 // open empty cells, but that's handled elsewhere).
807 if (Element* table = isLastPositionBeforeTable(m_selectionToDelete.visib leStart())) {
808 if (m_selectionToDelete.end().anchorNode()->isDescendantOf(table))
809 m_needPlaceholder = false;
810 }
811 }
812
813
814 // set up our state
815 initializePositionData();
816
817 bool lineBreakBeforeStart = lineBreakExistsAtVisiblePosition(VisiblePosition (m_upstreamStart).previous());
818
819 // Delete any text that may hinder our ability to fixup whitespace after the delete
820 deleteInsignificantTextDownstream(m_trailingWhitespace);
821
822 saveTypingStyleState();
823
824 // deleting just a BR is handled specially, at least because we do not
825 // want to replace it with a placeholder BR!
826 if (handleSpecialCaseBRDelete()) {
827 calculateTypingStyleAfterDelete();
828 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSe lection().isDirectional()));
829 clearTransientState();
830 rebalanceWhitespace();
831 return;
832 }
833
834 handleGeneralDelete();
835
836 fixupWhitespace();
837
838 mergeParagraphs();
839
840 removePreviouslySelectedEmptyTableRows();
841
842 if (!m_needPlaceholder && rootWillStayOpenWithoutPlaceholder) {
843 VisiblePosition visualEnding(m_endingPosition);
844 bool hasPlaceholder = lineBreakExistsAtVisiblePosition(visualEnding)
845 && visualEnding.next(CannotCrossEditingBoundary).isNull();
846 m_needPlaceholder = hasPlaceholder && lineBreakBeforeStart && !lineBreak AtEndOfSelectionToDelete;
847 }
848
849 RefPtrWillBeRawPtr<HTMLBRElement> placeholder = m_needPlaceholder ? createBr eakElement(document()) : nullptr;
850
851 if (placeholder) {
852 if (m_sanitizeMarkup)
853 removeRedundantBlocks();
854 // handleGeneralDelete cause DOM mutation events so |m_endingPosition|
855 // can be out of document.
856 if (m_endingPosition.inDocument())
857 insertNodeAt(placeholder.get(), m_endingPosition);
858 }
859
860 rebalanceWhitespaceAt(m_endingPosition);
861
862 calculateTypingStyleAfterDelete();
863
864 setEndingSelection(VisibleSelection(m_endingPosition, affinity, endingSelect ion().isDirectional()));
865 clearTransientState();
866 }
867
868 EditAction DeleteSelectionCommand::editingAction() const
869 {
870 // Note that DeleteSelectionCommand is also used when the user presses the D elete key,
871 // but in that case there's a TypingCommand that supplies the editingAction( ), so
872 // the Undo menu correctly shows "Undo Typing"
873 return EditActionCut;
874 }
875
876 // Normally deletion doesn't preserve the typing style that was present before i t. For example,
877 // type a character, Bold, then delete the character and start typing. The Bold typing style shouldn't
878 // stick around. Deletion should preserve a typing style that *it* sets, howeve r.
879 bool DeleteSelectionCommand::preservesTypingStyle() const
880 {
881 return m_typingStyle;
882 }
883
884 DEFINE_TRACE(DeleteSelectionCommand)
885 {
886 visitor->trace(m_selectionToDelete);
887 visitor->trace(m_upstreamStart);
888 visitor->trace(m_downstreamStart);
889 visitor->trace(m_upstreamEnd);
890 visitor->trace(m_downstreamEnd);
891 visitor->trace(m_endingPosition);
892 visitor->trace(m_leadingWhitespace);
893 visitor->trace(m_trailingWhitespace);
894 visitor->trace(m_startBlock);
895 visitor->trace(m_endBlock);
896 visitor->trace(m_typingStyle);
897 visitor->trace(m_deleteIntoBlockquoteStyle);
898 visitor->trace(m_startRoot);
899 visitor->trace(m_endRoot);
900 visitor->trace(m_startTableRow);
901 visitor->trace(m_endTableRow);
902 visitor->trace(m_temporaryPlaceholder);
903 CompositeEditCommand::trace(visitor);
904 }
905
906 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698