1 /*
2 * Copyright (C) 2005, 2006, 2008 Apple 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 "ReplaceSelectionCommand.h"
28
29 #include "ApplyStyleCommand.h"
30 #include "BeforeTextInsertedEvent.h"
31 #include "BreakBlockquoteCommand.h"
32 #include "CSSComputedStyleDeclaration.h"
33 #include "CSSProperty.h"
34 #include "CSSPropertyNames.h"
35 #include "CSSValueKeywords.h"
36 #include "Document.h"
37 #include "DocumentFragment.h"
38 #include "EditingText.h"
39 #include "EventNames.h"
40 #include "Element.h"
41 #include "Frame.h"
42 #include "HTMLElement.h"
43 #include "HTMLInterchange.h"
44 #include "HTMLInputElement.h"
45 #include "HTMLNames.h"
46 #include "SelectionController.h"
47 #include "SmartReplace.h"
48 #include "TextIterator.h"
49 #include "htmlediting.h"
50 #include "markup.h"
51 #include "visible_units.h"
52 #include <wtf/StdLibExtras.h>
53
54 namespace WebCore {
55
56 using namespace HTMLNames;
57
58 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
59
60 // --- ReplacementFragment helper class
61
62 class ReplacementFragment : Noncopyable {
63 public:
64 ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const Selection&);
65
66 Node* firstChild() const;
67 Node* lastChild() const;
68
69 bool isEmpty() const;
70
hasInterchangeNewlineAtStart() const71 bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
hasInterchangeNewlineAtEnd() const72 bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
73
74 void removeNode(PassRefPtr<Node>);
75 void removeNodePreservingChildren(Node*);
76
77 private:
78 PassRefPtr<Node> insertFragmentForTestRendering(Node* context);
79 void removeUnrenderedNodes(Node*);
80 void restoreTestRenderingNodesToFragment(Node*);
81 void removeInterchangeNodes(Node*);
82
83 void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
84
85 RefPtr<Document> m_document;
86 RefPtr<DocumentFragment> m_fragment;
87 bool m_matchStyle;
88 bool m_hasInterchangeNewlineAtStart;
89 bool m_hasInterchangeNewlineAtEnd;
90 };
91
isInterchangeNewlineNode(const Node * node)92 static bool isInterchangeNewlineNode(const Node *node)
93 {
94 DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
95 return node && node->hasTagName(brTag) &&
96 static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
97 }
98
isInterchangeConvertedSpaceSpan(const Node * node)99 static bool isInterchangeConvertedSpaceSpan(const Node *node)
100 {
101 DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
102 return node->isHTMLElement() &&
103 static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
104 }
105
ReplacementFragment(Document * document,DocumentFragment * fragment,bool matchStyle,const Selection & selection)106 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const Selection& selection)
107 : m_document(document),
108 m_fragment(fragment),
109 m_matchStyle(matchStyle),
110 m_hasInterchangeNewlineAtStart(false),
111 m_hasInterchangeNewlineAtEnd(false)
112 {
113 if (!m_document)
114 return;
115 if (!m_fragment)
116 return;
117 if (!m_fragment->firstChild())
118 return;
119
120 Element* editableRoot = selection.rootEditableElement();
121 ASSERT(editableRoot);
122 if (!editableRoot)
123 return;
124
125 Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
126
127 if (!editableRoot->inlineEventListenerForType(eventNames().webkitBeforeTextInsertedEvent) &&
128 // FIXME: Remove these checks once textareas and textfields actually register an event handler.
129 !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextField()) &&
130 !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextArea()) &&
131 editableRoot->isContentRichlyEditable()) {
132 removeInterchangeNodes(m_fragment.get());
133 return;
134 }
135
136 Node* styleNode = selection.base().node();
137 RefPtr<Node> holder = insertFragmentForTestRendering(styleNode);
138
139 RefPtr<Range> range = Selection::selectionFromContentsOfNode(holder.get()).toRange();
140 String text = plainText(range.get());
141 // Give the root a chance to change the text.
142 RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
143 ExceptionCode ec = 0;
144 editableRoot->dispatchEvent(evt, ec);
145 ASSERT(ec == 0);
146 if (text != evt->text() || !editableRoot->isContentRichlyEditable()) {
147 restoreTestRenderingNodesToFragment(holder.get());
148 removeNode(holder);
149
150 m_fragment = createFragmentFromText(selection.toRange().get(), evt->text());
151 if (!m_fragment->firstChild())
152 return;
153 holder = insertFragmentForTestRendering(styleNode);
154 }
155
156 removeInterchangeNodes(holder.get());
157
158 removeUnrenderedNodes(holder.get());
159 restoreTestRenderingNodesToFragment(holder.get());
160 removeNode(holder);
161 }
162
isEmpty() const163 bool ReplacementFragment::isEmpty() const
164 {
165 return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
166 }
167
firstChild() const168 Node *ReplacementFragment::firstChild() const
169 {
170 return m_fragment ? m_fragment->firstChild() : 0;
171 }
172
lastChild() const173 Node *ReplacementFragment::lastChild() const
174 {
175 return m_fragment ? m_fragment->lastChild() : 0;
176 }
177
removeNodePreservingChildren(Node * node)178 void ReplacementFragment::removeNodePreservingChildren(Node *node)
179 {
180 if (!node)
181 return;
182
183 while (RefPtr<Node> n = node->firstChild()) {
184 removeNode(n);
185 insertNodeBefore(n.release(), node);
186 }
187 removeNode(node);
188 }
189
removeNode(PassRefPtr<Node> node)190 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
191 {
192 if (!node)
193 return;
194
195 Node *parent = node->parentNode();
196 if (!parent)
197 return;
198
199 ExceptionCode ec = 0;
200 parent->removeChild(node.get(), ec);
201 ASSERT(ec == 0);
202 }
203
insertNodeBefore(PassRefPtr<Node> node,Node * refNode)204 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
205 {
206 if (!node || !refNode)
207 return;
208
209 Node* parent = refNode->parentNode();
210 if (!parent)
211 return;
212
213 ExceptionCode ec = 0;
214 parent->insertBefore(node, refNode, ec);
215 ASSERT(ec == 0);
216 }
217
insertFragmentForTestRendering(Node * context)218 PassRefPtr<Node> ReplacementFragment::insertFragmentForTestRendering(Node* context)
219 {
220 Node* body = m_document->body();
221 if (!body)
222 return 0;
223
224 RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
225
226 ExceptionCode ec = 0;
227
228 // Copy the whitespace and user-select style from the context onto this element.
229 // FIXME: We should examine other style properties to see if they would be appropriate to consider during the test rendering.
230 Node* n = context;
231 while (n && !n->isElementNode())
232 n = n->parentNode();
233 if (n) {
234 RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n);
235 CSSStyleDeclaration* style = holder->style();
236 style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec);
237 ASSERT(ec == 0);
238 style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec);
239 ASSERT(ec == 0);
240 }
241
242 holder->appendChild(m_fragment, ec);
243 ASSERT(ec == 0);
244
245 body->appendChild(holder.get(), ec);
246 ASSERT(ec == 0);
247
248 m_document->updateLayoutIgnorePendingStylesheets();
249
250 return holder.release();
251 }
252
restoreTestRenderingNodesToFragment(Node * holder)253 void ReplacementFragment::restoreTestRenderingNodesToFragment(Node *holder)
254 {
255 if (!holder)
256 return;
257
258 ExceptionCode ec = 0;
259 while (RefPtr<Node> node = holder->firstChild()) {
260 holder->removeChild(node.get(), ec);
261 ASSERT(ec == 0);
262 m_fragment->appendChild(node.get(), ec);
263 ASSERT(ec == 0);
264 }
265 }
266
removeUnrenderedNodes(Node * holder)267 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
268 {
269 Vector<Node*> unrendered;
270
271 for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
272 if (!isNodeRendered(node) && !isTableStructureNode(node))
273 unrendered.append(node);
274
275 size_t n = unrendered.size();
276 for (size_t i = 0; i < n; ++i)
277 removeNode(unrendered[i]);
278 }
279
removeInterchangeNodes(Node * container)280 void ReplacementFragment::removeInterchangeNodes(Node* container)
281 {
282 // Interchange newlines at the "start" of the incoming fragment must be
283 // either the first node in the fragment or the first leaf in the fragment.
284 Node* node = container->firstChild();
285 while (node) {
286 if (isInterchangeNewlineNode(node)) {
287 m_hasInterchangeNewlineAtStart = true;
288 removeNode(node);
289 break;
290 }
291 node = node->firstChild();
292 }
293 if (!container->hasChildNodes())
294 return;
295 // Interchange newlines at the "end" of the incoming fragment must be
296 // either the last node in the fragment or the last leaf in the fragment.
297 node = container->lastChild();
298 while (node) {
299 if (isInterchangeNewlineNode(node)) {
300 m_hasInterchangeNewlineAtEnd = true;
301 removeNode(node);
302 break;
303 }
304 node = node->lastChild();
305 }
306
307 node = container->firstChild();
308 while (node) {
309 Node *next = node->traverseNextNode();
310 if (isInterchangeConvertedSpaceSpan(node)) {
311 RefPtr<Node> n = 0;
312 while ((n = node->firstChild())) {
313 removeNode(n);
314 insertNodeBefore(n, node);
315 }
316 removeNode(node);
317 if (n)
318 next = n->traverseNextNode();
319 }
320 node = next;
321 }
322 }
323
ReplaceSelectionCommand(Document * document,PassRefPtr<DocumentFragment> fragment,bool selectReplacement,bool smartReplace,bool matchStyle,bool preventNesting,bool movingParagraph,EditAction editAction)324 ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment,
325 bool selectReplacement, bool smartReplace, bool matchStyle, bool preventNesting, bool movingParagraph,
326 EditAction editAction)
327 : CompositeEditCommand(document),
328 m_selectReplacement(selectReplacement),
329 m_smartReplace(smartReplace),
330 m_matchStyle(matchStyle),
331 m_documentFragment(fragment),
332 m_preventNesting(preventNesting),
333 m_movingParagraph(movingParagraph),
334 m_editAction(editAction),
335 m_shouldMergeEnd(false)
336 {
337 }
338
hasMatchingQuoteLevel(VisiblePosition endOfExistingContent,VisiblePosition endOfInsertedContent)339 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
340 {
341 Position existing = endOfExistingContent.deepEquivalent();
342 Position inserted = endOfInsertedContent.deepEquivalent();
343 bool isInsideMailBlockquote = nearestMailBlockquote(inserted.node());
344 return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
345 }
346
shouldMergeStart(bool selectionStartWasStartOfParagraph,bool fragmentHasInterchangeNewlineAtStart)347 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart)
348 {
349 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
350 VisiblePosition prev = startOfInsertedContent.previous(true);
351 if (prev.isNull())
352 return false;
353
354 if (!m_movingParagraph && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
355 return true;
356
357 return !selectionStartWasStartOfParagraph &&
358 !fragmentHasInterchangeNewlineAtStart &&
359 isStartOfParagraph(startOfInsertedContent) &&
360 !startOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
361 shouldMerge(startOfInsertedContent, prev);
362 }
363
shouldMergeEnd(bool selectionEndWasEndOfParagraph)364 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
365 {
366 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
367 VisiblePosition next = endOfInsertedContent.next(true);
368 if (next.isNull())
369 return false;
370
371 return !selectionEndWasEndOfParagraph &&
372 isEndOfParagraph(endOfInsertedContent) &&
373 !endOfInsertedContent.deepEquivalent().node()->hasTagName(brTag) &&
374 shouldMerge(endOfInsertedContent, next);
375 }
376
isMailPasteAsQuotationNode(const Node * node)377 static bool isMailPasteAsQuotationNode(const Node* node)
378 {
379 return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
380 }
381
382 // Wrap CompositeEditCommand::removeNodePreservingChildren() so we can update the nodes we track
removeNodePreservingChildren(Node * node)383 void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node)
384 {
385 if (m_firstNodeInserted == node)
386 m_firstNodeInserted = node->traverseNextNode();
387 if (m_lastLeafInserted == node)
388 m_lastLeafInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling();
389 CompositeEditCommand::removeNodePreservingChildren(node);
390 }
391
392 // Wrap CompositeEditCommand::removeNodeAndPruneAncestors() so we can update the nodes we track
removeNodeAndPruneAncestors(Node * node)393 void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node)
394 {
395 // prepare in case m_firstNodeInserted and/or m_lastLeafInserted get removed
396 // FIXME: shouldn't m_lastLeafInserted be adjusted using traversePreviousNode()?
397 Node* afterFirst = m_firstNodeInserted ? m_firstNodeInserted->traverseNextSibling() : 0;
398 Node* afterLast = m_lastLeafInserted ? m_lastLeafInserted->traverseNextSibling() : 0;
399
400 CompositeEditCommand::removeNodeAndPruneAncestors(node);
401
402 // adjust m_firstNodeInserted and m_lastLeafInserted since either or both may have been removed
403 if (m_lastLeafInserted && !m_lastLeafInserted->inDocument())
404 m_lastLeafInserted = afterLast;
405 if (m_firstNodeInserted && !m_firstNodeInserted->inDocument())
406 m_firstNodeInserted = m_lastLeafInserted && m_lastLeafInserted->inDocument() ? afterFirst : 0;
407 }
408
shouldMerge(const VisiblePosition & source,const VisiblePosition & destination)409 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
410 {
411 if (source.isNull() || destination.isNull())
412 return false;
413
414 Node* sourceNode = source.deepEquivalent().node();
415 Node* destinationNode = destination.deepEquivalent().node();
416 Node* sourceBlock = enclosingBlock(sourceNode);
417 return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
418 sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock)) &&
419 enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
420 enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
421 // Don't merge to or from a position before or after a block because it would
422 // be a no-op and cause infinite recursion.
423 !isBlock(sourceNode) && !isBlock(destinationNode);
424 }
425
426 // Style rules that match just inserted elements could change their appearance, like
427 // a div inserted into a document with div { display:inline; }.
negateStyleRulesThatAffectAppearance()428 void ReplaceSelectionCommand::negateStyleRulesThatAffectAppearance()
429 {
430 for (RefPtr<Node> node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
431 // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
432 if (isStyleSpan(node.get())) {
433 HTMLElement* e = static_cast<HTMLElement*>(node.get());
434 // There are other styles that style rules can give to style spans,
435 // but these are the two important ones because they'll prevent
436 // inserted content from appearing in the right paragraph.
437 // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
438 // results. We already know one issue because td elements ignore their display property
439 // in quirks mode (which Mail.app is always in). We should look for an alternative.
440 if (isBlock(e))
441 e->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline);
442 if (e->renderer() && e->renderer()->style()->floating() != FNONE)
443 e->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone);
444 }
445 if (node == m_lastLeafInserted)
446 break;
447 }
448 }
449
removeUnrenderedTextNodesAtEnds()450 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds()
451 {
452 document()->updateLayoutIgnorePendingStylesheets();
453 if (!m_lastLeafInserted->renderer() &&
454 m_lastLeafInserted->isTextNode() &&
455 !enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), selectTag) &&
456 !enclosingNodeWithTag(Position(m_lastLeafInserted.get(), 0), scriptTag)) {
457 if (m_firstNodeInserted == m_lastLeafInserted) {
458 removeNode(m_lastLeafInserted.get());
459 m_lastLeafInserted = 0;
460 m_firstNodeInserted = 0;
461 return;
462 }
463 RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode();
464 removeNode(m_lastLeafInserted.get());
465 m_lastLeafInserted = previous;
466 }
467
468 // We don't have to make sure that m_firstNodeInserted isn't inside a select or script element, because
469 // it is a top level node in the fragment and the user can't insert into those elements.
470 if (!m_firstNodeInserted->renderer() &&
471 m_firstNodeInserted->isTextNode()) {
472 if (m_firstNodeInserted == m_lastLeafInserted) {
473 removeNode(m_firstNodeInserted.get());
474 m_firstNodeInserted = 0;
475 m_lastLeafInserted = 0;
476 return;
477 }
478 RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling();
479 removeNode(m_firstNodeInserted.get());
480 m_firstNodeInserted = next;
481 }
482 }
483
handlePasteAsQuotationNode()484 void ReplaceSelectionCommand::handlePasteAsQuotationNode()
485 {
486 Node* node = m_firstNodeInserted.get();
487 if (isMailPasteAsQuotationNode(node))
488 removeNodeAttribute(static_cast<Element*>(node), classAttr);
489 }
490
positionAtEndOfInsertedContent()491 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent()
492 {
493 Node* lastNode = m_lastLeafInserted.get();
494 Node* enclosingSelect = enclosingNodeWithTag(Position(lastNode, 0), selectTag);
495 if (enclosingSelect)
496 lastNode = enclosingSelect;
497 return VisiblePosition(Position(lastNode, maxDeepOffset(lastNode)));
498 }
499
positionAtStartOfInsertedContent()500 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent()
501 {
502 // Return the inserted content's first VisiblePosition.
503 return VisiblePosition(nextCandidate(positionBeforeNode(m_firstNodeInserted.get())));
504 }
505
506 // Remove style spans before insertion if they are unnecessary. It's faster because we'll
507 // avoid doing a layout.
handleStyleSpansBeforeInsertion(ReplacementFragment & fragment,const Position & insertionPos)508 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
509 {
510 Node* topNode = fragment.firstChild();
511
512 // Handling this case is more complicated (see handleStyleSpans) and doesn't receive the optimization.
513 if (isMailPasteAsQuotationNode(topNode))
514 return false;
515
516 // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
517 // before inserting it. Look for and handle style spans after insertion.
518 if (!isStyleSpan(topNode))
519 return false;
520
521 Node* sourceDocumentStyleSpan = topNode;
522 RefPtr<Node> copiedRangeStyleSpan = sourceDocumentStyleSpan->firstChild();
523
524 RefPtr<CSSMutableStyleDeclaration> styleAtInsertionPos = rangeCompliantEquivalent(insertionPos).computedStyle()->copyInheritableProperties();
525 String styleText = styleAtInsertionPos->cssText();
526
527 if (styleText == static_cast<Element*>(sourceDocumentStyleSpan)->getAttribute(styleAttr)) {
528 fragment.removeNodePreservingChildren(sourceDocumentStyleSpan);
529 if (!isStyleSpan(copiedRangeStyleSpan.get()))
530 return true;
531 }
532
533 if (isStyleSpan(copiedRangeStyleSpan.get()) && styleText == static_cast<Element*>(copiedRangeStyleSpan.get())->getAttribute(styleAttr)) {
534 fragment.removeNodePreservingChildren(copiedRangeStyleSpan.get());
535 return true;
536 }
537
538 return false;
539 }
540
541 // At copy time, WebKit wraps copied content in a span that contains the source document's
542 // default styles. If the copied Range inherits any other styles from its ancestors, we put
543 // those styles on a second span.
544 // This function removes redundant styles from those spans, and removes the spans if all their
545 // styles are redundant.
546 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
547 // We should remove styles from spans that are overridden by all of their children, either here
548 // or at copy time.
handleStyleSpans()549 void ReplaceSelectionCommand::handleStyleSpans()
550 {
551 Node* sourceDocumentStyleSpan = 0;
552 Node* copiedRangeStyleSpan = 0;
553 // The style span that contains the source document's default style should be at
554 // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
555 // so search for the top level style span instead of assuming it's at the top.
556 for (Node* node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
557 if (isStyleSpan(node)) {
558 sourceDocumentStyleSpan = node;
559 // If the copied Range's common ancestor had user applied inheritable styles
560 // on it, they'll be on a second style span, just below the one that holds the
561 // document defaults.
562 if (isStyleSpan(node->firstChild()))
563 copiedRangeStyleSpan = node->firstChild();
564 break;
565 }
566 }
567
568 // There might not be any style spans if we're pasting from another application or if
569 // we are here because of a document.execCommand("InsertHTML", ...) call.
570 if (!sourceDocumentStyleSpan)
571 return;
572
573 RefPtr<CSSMutableStyleDeclaration> sourceDocumentStyle = static_cast<HTMLElement*>(sourceDocumentStyleSpan)->getInlineStyleDecl()->copy();
574 Node* context = sourceDocumentStyleSpan->parentNode();
575
576 // If Mail wraps the fragment with a Paste as Quotation blockquote, styles from that element are
577 // allowed to override those from the source document, see <rdar://problem/4930986>.
578 if (isMailPasteAsQuotationNode(context)) {
579 RefPtr<CSSMutableStyleDeclaration> blockquoteStyle = computedStyle(context)->copyInheritableProperties();
580 RefPtr<CSSMutableStyleDeclaration> parentStyle = computedStyle(context->parentNode())->copyInheritableProperties();
581 parentStyle->diff(blockquoteStyle.get());
582
583 CSSMutableStyleDeclaration::const_iterator end = blockquoteStyle->end();
584 for (CSSMutableStyleDeclaration::const_iterator it = blockquoteStyle->begin(); it != end; ++it) {
585 const CSSProperty& property = *it;
586 sourceDocumentStyle->removeProperty(property.id());
587 }
588
589 context = context->parentNode();
590 }
591
592 RefPtr<CSSMutableStyleDeclaration> contextStyle = computedStyle(context)->copyInheritableProperties();
593 contextStyle->diff(sourceDocumentStyle.get());
594
595 // Remove block properties in the span's style. This prevents properties that probably have no effect
596 // currently from affecting blocks later if the style is cloned for a new block element during a future
597 // editing operation.
598 // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
599 // with block styles by the editing engine used to style them. WebKit doesn't do this, but others might.
600 sourceDocumentStyle->removeBlockProperties();
601
602 // The styles on sourceDocumentStyleSpan are all redundant, and there is no copiedRangeStyleSpan
603 // to consider. We're finished.
604 if (sourceDocumentStyle->length() == 0 && !copiedRangeStyleSpan) {
605 removeNodePreservingChildren(sourceDocumentStyleSpan);
606 return;
607 }
608
609 // There are non-redundant styles on sourceDocumentStyleSpan, but there is no
610 // copiedRangeStyleSpan. Clear the redundant styles from sourceDocumentStyleSpan
611 // and return.
612 if (sourceDocumentStyle->length() > 0 && !copiedRangeStyleSpan) {
613 setNodeAttribute(static_cast<Element*>(sourceDocumentStyleSpan), styleAttr, sourceDocumentStyle->cssText());
614 return;
615 }
616
617 RefPtr<CSSMutableStyleDeclaration> copiedRangeStyle = static_cast<HTMLElement*>(copiedRangeStyleSpan)->getInlineStyleDecl()->copy();
618
619 // We're going to put sourceDocumentStyleSpan's non-redundant styles onto copiedRangeStyleSpan,
620 // as long as they aren't overridden by ones on copiedRangeStyleSpan.
621 sourceDocumentStyle->merge(copiedRangeStyle.get(), true);
622 copiedRangeStyle = sourceDocumentStyle;
623
624 removeNodePreservingChildren(sourceDocumentStyleSpan);
625
626 // Remove redundant styles.
627 context = copiedRangeStyleSpan->parentNode();
628 contextStyle = computedStyle(context)->copyInheritableProperties();
629 contextStyle->diff(copiedRangeStyle.get());
630
631 // See the comments above about removing block properties.
632 copiedRangeStyle->removeBlockProperties();
633
634 // All the styles on copiedRangeStyleSpan are redundant, remove it.
635 if (copiedRangeStyle->length() == 0) {
636 removeNodePreservingChildren(copiedRangeStyleSpan);
637 return;
638 }
639
640 // Clear the redundant styles from the span's style attribute.
641 // FIXME: If font-family:-webkit-monospace is non-redundant, then the font-size should stay, even if it
642 // appears redundant.
643 setNodeAttribute(static_cast<Element*>(copiedRangeStyleSpan), styleAttr, copiedRangeStyle->cssText());
644 }
645
mergeEndIfNeeded()646 void ReplaceSelectionCommand::mergeEndIfNeeded()
647 {
648 if (!m_shouldMergeEnd)
649 return;
650
651 VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
652 VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
653
654 // Bail to avoid infinite recursion.
655 if (m_movingParagraph) {
656 ASSERT_NOT_REACHED();
657 return;
658 }
659
660 // Merging two paragraphs will destroy the moved one's block styles. Always move the end of inserted forward
661 // to preserve the block style of the paragraph already in the document, unless the paragraph to move would
662 // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
663 // block styles.
664 bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
665
666 VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
667 VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
668
669 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
670 // Merging forward will remove m_lastLeafInserted from the document.
671 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
672 // only ever used to create positions where inserted content starts/ends.
673 if (mergeForward) {
674 m_lastLeafInserted = destination.previous().deepEquivalent().node();
675 if (!m_firstNodeInserted->inDocument())
676 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().node();
677 }
678 }
679
doApply()680 void ReplaceSelectionCommand::doApply()
681 {
682 Selection selection = endingSelection();
683 ASSERT(selection.isCaretOrRange());
684 ASSERT(selection.start().node());
685 if (selection.isNone() || !selection.start().node())
686 return;
687
688 bool selectionIsPlainText = !selection.isContentRichlyEditable();
689
690 Element* currentRoot = selection.rootEditableElement();
691 ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
692
693 if (m_matchStyle)
694 m_insertionStyle = styleAtPosition(selection.start());
695
696 VisiblePosition visibleStart = selection.visibleStart();
697 VisiblePosition visibleEnd = selection.visibleEnd();
698
699 bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
700 bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
701
702 Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().node());
703
704 Position insertionPos = selection.start();
705 bool startIsInsideMailBlockquote = nearestMailBlockquote(insertionPos.node());
706
707 if (selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote ||
708 startBlock == currentRoot ||
709 startBlock && startBlock->renderer() && startBlock->renderer()->isListItem() ||
710 selectionIsPlainText)
711 m_preventNesting = false;
712
713 if (selection.isRange()) {
714 // When the end of the selection being pasted into is at the end of a paragraph, and that selection
715 // spans multiple blocks, not merging may leave an empty line.
716 // When the start of the selection being pasted into is at the start of a block, not merging
717 // will leave hanging block(s).
718 // Merge blocks if the start of the selection was in a Mail blockquote, since we handle
719 // that case specially to prevent nesting.
720 bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
721 // FIXME: We should only expand to include fully selected special elements if we are copying a
722 // selection and pasting it on top of itself.
723 deleteSelection(false, mergeBlocksAfterDelete, true, false);
724 visibleStart = endingSelection().visibleStart();
725 if (fragment.hasInterchangeNewlineAtStart()) {
726 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
727 if (!isEndOfDocument(visibleStart))
728 setEndingSelection(visibleStart.next());
729 } else
730 insertParagraphSeparator();
731 }
732 insertionPos = endingSelection().start();
733 } else {
734 ASSERT(selection.isCaret());
735 if (fragment.hasInterchangeNewlineAtStart()) {
736 VisiblePosition next = visibleStart.next(true);
737 if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
738 setEndingSelection(next);
739 else
740 insertParagraphSeparator();
741 }
742 // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
743 // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
744 // As long as the div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
745 // not <div>xbar<div>bar</div><div>bazx</div></div>.
746 // Don't do this if the selection started in a Mail blockquote.
747 if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
748 insertParagraphSeparator();
749 setEndingSelection(endingSelection().visibleStart().previous());
750 }
751 insertionPos = endingSelection().start();
752 }
753
754 if (startIsInsideMailBlockquote && m_preventNesting) {
755 // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
756 // out of any surrounding Mail blockquotes.
757 applyCommandToComposite(BreakBlockquoteCommand::create(document()));
758 // This will leave a br between the split.
759 Node* br = endingSelection().start().node();
760 ASSERT(br->hasTagName(brTag));
761 // Insert content between the two blockquotes, but remove the br (since it was just a placeholder).
762 insertionPos = positionBeforeNode(br);
763 removeNode(br);
764 }
765
766 // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
767 prepareWhitespaceAtPositionForSplit(insertionPos);
768
769 // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
770 // p that maps to the same visible position as p (since in the case where a br is at the end of a block and collapsed
771 // away, there are positions after the br which map to the same visible position as [br, 0]).
772 Node* endBR = insertionPos.downstream().node()->hasTagName(brTag) ? insertionPos.downstream().node() : 0;
773 VisiblePosition originalVisPosBeforeEndBR;
774 if (endBR)
775 originalVisPosBeforeEndBR = VisiblePosition(endBR, 0, DOWNSTREAM).previous();
776
777 startBlock = enclosingBlock(insertionPos.node());
778
779 // Adjust insertionPos to prevent nesting.
780 // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
781 if (m_preventNesting && startBlock && !startIsInsideMailBlockquote) {
782 ASSERT(startBlock != currentRoot);
783 VisiblePosition visibleInsertionPos(insertionPos);
784 if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
785 insertionPos = positionAfterNode(startBlock);
786 else if (isStartOfBlock(visibleInsertionPos))
787 insertionPos = positionBeforeNode(startBlock);
788 }
789
790 // Paste into run of tabs splits the tab span.
791 insertionPos = positionOutsideTabSpan(insertionPos);
792
793 // Paste at start or end of link goes outside of link.
794 insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
795
796 // FIXME: Can this wait until after the operation has been performed? There doesn't seem to be
797 // any work performed after this that queries or uses the typing style.
798 if (Frame* frame = document()->frame())
799 frame->clearTypingStyle();
800
801 bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
802
803 // We're finished if there is nothing to add.
804 if (fragment.isEmpty() || !fragment.firstChild())
805 return;
806
807 // 1) Insert the content.
808 // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>.
809 // 3) Merge the start of the added content with the content before the position being pasted into.
810 // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
811 // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
812 // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
813 // incoming fragment.
814 // 5) Add spaces for smart replace.
815 // 6) Select the replacement if requested, and match style if requested.
816
817 VisiblePosition startOfInsertedContent, endOfInsertedContent;
818
819 RefPtr<Node> refNode = fragment.firstChild();
820 RefPtr<Node> node = refNode->nextSibling();
821
822 fragment.removeNode(refNode);
823 insertNodeAtAndUpdateNodesInserted(refNode, insertionPos);
824
825 while (node) {
826 Node* next = node->nextSibling();
827 fragment.removeNode(node);
828 insertNodeAfterAndUpdateNodesInserted(node, refNode.get());
829 refNode = node;
830 node = next;
831 }
832
833 removeUnrenderedTextNodesAtEnds();
834
835 negateStyleRulesThatAffectAppearance();
836
837 if (!handledStyleSpans)
838 handleStyleSpans();
839
840 // Mutation events (bug 20161) may have already removed the inserted content
841 if (!m_firstNodeInserted || !m_firstNodeInserted->inDocument())
842 return;
843
844 endOfInsertedContent = positionAtEndOfInsertedContent();
845 startOfInsertedContent = positionAtStartOfInsertedContent();
846
847 // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and
848 // didn't have a br after it, so the inserted content ended up in the same paragraph.
849 if (startBlock && insertionPos.node() == startBlock->parentNode() && (unsigned)insertionPos.offset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
850 insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
851
852 Position lastPositionToSelect;
853
854 bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd();
855
856 if (shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))
857 removeNodeAndPruneAncestors(endBR);
858
859 // Determine whether or not we should merge the end of inserted content with what's after it before we do
860 // the start merge so that the start merge doesn't effect our decision.
861 m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
862
863 if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart())) {
864 // Bail to avoid infinite recursion.
865 if (m_movingParagraph) {
866 // setting display:inline does not work for td elements in quirks mode
867 ASSERT(m_firstNodeInserted->hasTagName(tdTag));
868 return;
869 }
870 VisiblePosition destination = startOfInsertedContent.previous();
871 VisiblePosition startOfParagraphToMove = startOfInsertedContent;
872
873 // Merging the the first paragraph of inserted content with the content that came
874 // before the selection that was pasted into would also move content after
875 // the selection that was pasted into if: only one paragraph was being pasted,
876 // and it was not wrapped in a block, the selection that was pasted into ended
877 // at the end of a block and the next paragraph didn't start at the start of a block.
878 // Insert a line break just after the inserted content to separate it from what
879 // comes after and prevent that from happening.
880 VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
881 if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove)
882 insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
883
884 // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes. The nodes are
885 // only ever used to create positions where inserted content starts/ends.
886 moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
887 m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().downstream().node();
888 if (!m_lastLeafInserted->inDocument())
889 m_lastLeafInserted = endingSelection().visibleEnd().deepEquivalent().upstream().node();
890 }
891
892 endOfInsertedContent = positionAtEndOfInsertedContent();
893 startOfInsertedContent = positionAtStartOfInsertedContent();
894
895 if (interchangeNewlineAtEnd) {
896 VisiblePosition next = endOfInsertedContent.next(true);
897
898 if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
899 if (!isStartOfParagraph(endOfInsertedContent)) {
900 setEndingSelection(endOfInsertedContent);
901 // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph
902 // block's style seems to annoy users.
903 insertParagraphSeparator(true);
904
905 // Select up to the paragraph separator that was added.
906 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
907 updateNodesInserted(lastPositionToSelect.node());
908 }
909 } else {
910 // Select up to the beginning of the next paragraph.
911 lastPositionToSelect = next.deepEquivalent().downstream();
912 }
913
914 } else
915 mergeEndIfNeeded();
916
917 handlePasteAsQuotationNode();
918
919 endOfInsertedContent = positionAtEndOfInsertedContent();
920 startOfInsertedContent = positionAtStartOfInsertedContent();
921
922 // Add spaces for smart replace.
923 if (m_smartReplace && currentRoot) {
924 // Disable smart replace for password fields.
925 Node* start = currentRoot->shadowAncestorNode();
926 if (start->hasTagName(inputTag) && static_cast<HTMLInputElement*>(start)->inputType() == HTMLInputElement::PASSWORD)
927 m_smartReplace = false;
928 }
929 if (m_smartReplace) {
930 bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) &&
931 !isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false);
932 if (needsTrailingSpace) {
933 RenderObject* renderer = m_lastLeafInserted->renderer();
934 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
935 Node* endNode = positionAtEndOfInsertedContent().deepEquivalent().upstream().node();
936 if (endNode->isTextNode()) {
937 Text* text = static_cast<Text*>(endNode);
938 insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " ");
939 } else {
940 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
941 insertNodeAfterAndUpdateNodesInserted(node, endNode);
942 }
943 }
944
945 bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) &&
946 !isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true);
947 if (needsLeadingSpace) {
948 RenderObject* renderer = m_lastLeafInserted->renderer();
949 bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
950 Node* startNode = positionAtStartOfInsertedContent().deepEquivalent().downstream().node();
951 if (startNode->isTextNode()) {
952 Text* text = static_cast<Text*>(startNode);
953 insertTextIntoNode(text, 0, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
954 } else {
955 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
956 // Don't updateNodesInserted. Doing so would set m_lastLeafInserted to be the node containing the
957 // leading space, but m_lastLeafInserted is supposed to mark the end of pasted content.
958 insertNodeBefore(node, startNode);
959 // FIXME: Use positions to track the start/end of inserted content.
960 m_firstNodeInserted = node;
961 }
962 }
963 }
964
965 completeHTMLReplacement(lastPositionToSelect);
966 }
967
shouldRemoveEndBR(Node * endBR,const VisiblePosition & originalVisPosBeforeEndBR)968 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
969 {
970 if (!endBR || !endBR->inDocument())
971 return false;
972
973 VisiblePosition visiblePos(Position(endBR, 0));
974
975 // Don't remove the br if nothing was inserted.
976 if (visiblePos.previous() == originalVisPosBeforeEndBR)
977 return false;
978
979 // Remove the br if it is collapsed away and so is unnecessary.
980 if (!document()->inStrictMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
981 return true;
982
983 // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
984 // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
985 return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
986 }
987
completeHTMLReplacement(const Position & lastPositionToSelect)988 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
989 {
990 Position start;
991 Position end;
992
993 // FIXME: This should never not be the case.
994 if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastLeafInserted && m_lastLeafInserted->inDocument()) {
995
996 start = positionAtStartOfInsertedContent().deepEquivalent();
997 end = positionAtEndOfInsertedContent().deepEquivalent();
998
999 // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
1000 rebalanceWhitespaceAt(start);
1001 rebalanceWhitespaceAt(end);
1002
1003 if (m_matchStyle) {
1004 ASSERT(m_insertionStyle);
1005 applyStyle(m_insertionStyle.get(), start, end);
1006 }
1007
1008 if (lastPositionToSelect.isNotNull())
1009 end = lastPositionToSelect;
1010 } else if (lastPositionToSelect.isNotNull())
1011 start = end = lastPositionToSelect;
1012 else
1013 return;
1014
1015 if (m_selectReplacement)
1016 setEndingSelection(Selection(start, end, SEL_DEFAULT_AFFINITY));
1017 else
1018 setEndingSelection(Selection(end, SEL_DEFAULT_AFFINITY));
1019 }
1020
editingAction() const1021 EditAction ReplaceSelectionCommand::editingAction() const
1022 {
1023 return m_editAction;
1024 }
1025
insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild,Node * refChild)1026 void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1027 {
1028 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1029 insertNodeAfter(insertChild, refChild);
1030 updateNodesInserted(nodeToUpdate);
1031 }
1032
insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild,const Position & p)1033 void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild, const Position& p)
1034 {
1035 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1036 insertNodeAt(insertChild, p);
1037 updateNodesInserted(nodeToUpdate);
1038 }
1039
insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild,Node * refChild)1040 void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1041 {
1042 Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1043 insertNodeBefore(insertChild, refChild);
1044 updateNodesInserted(nodeToUpdate);
1045 }
1046
updateNodesInserted(Node * node)1047 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
1048 {
1049 if (!node)
1050 return;
1051
1052 if (!m_firstNodeInserted)
1053 m_firstNodeInserted = node;
1054
1055 if (node == m_lastLeafInserted)
1056 return;
1057
1058 m_lastLeafInserted = node->lastDescendant();
1059 }
1060
1061 } // namespace WebCore
1062