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 "CSSMutableStyleDeclaration.h"
34 #include "CSSPropertyNames.h"
35 #include "CSSValueKeywords.h"
36 #include "Document.h"
37 #include "DocumentFragment.h"
38 #include "EditingText.h"
39 #include "Element.h"
40 #include "EventNames.h"
41 #include "Frame.h"
42 #include "HTMLElement.h"
43 #include "HTMLInputElement.h"
44 #include "HTMLInterchange.h"
45 #include "HTMLNames.h"
46 #include "NodeList.h"
47 #include "SelectionController.h"
48 #include "SmartReplace.h"
49 #include "TextIterator.h"
50 #include "htmlediting.h"
51 #include "markup.h"
52 #include "visible_units.h"
53 #include <wtf/StdLibExtras.h>
54 #include <wtf/Vector.h>
55 
56 namespace WebCore {
57 
58 typedef Vector<RefPtr<Node> > NodeVector;
59 
60 using namespace HTMLNames;
61 
62 enum EFragmentType { EmptyFragment, SingleTextNodeFragment, TreeFragment };
63 
64 // --- ReplacementFragment helper class
65 
66 class ReplacementFragment {
67     WTF_MAKE_NONCOPYABLE(ReplacementFragment);
68 public:
69     ReplacementFragment(Document*, DocumentFragment*, bool matchStyle, const VisibleSelection&);
70 
71     Node* firstChild() const;
72     Node* lastChild() const;
73 
74     bool isEmpty() const;
75 
hasInterchangeNewlineAtStart() const76     bool hasInterchangeNewlineAtStart() const { return m_hasInterchangeNewlineAtStart; }
hasInterchangeNewlineAtEnd() const77     bool hasInterchangeNewlineAtEnd() const { return m_hasInterchangeNewlineAtEnd; }
78 
79     void removeNode(PassRefPtr<Node>);
80     void removeNodePreservingChildren(Node*);
81 
82 private:
83     PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* context);
84     void removeUnrenderedNodes(Node*);
85     void restoreTestRenderingNodesToFragment(StyledElement*);
86     void removeInterchangeNodes(Node*);
87 
88     void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
89 
90     RefPtr<Document> m_document;
91     RefPtr<DocumentFragment> m_fragment;
92     bool m_matchStyle;
93     bool m_hasInterchangeNewlineAtStart;
94     bool m_hasInterchangeNewlineAtEnd;
95 };
96 
isInterchangeNewlineNode(const Node * node)97 static bool isInterchangeNewlineNode(const Node *node)
98 {
99     DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
100     return node && node->hasTagName(brTag) &&
101            static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
102 }
103 
isInterchangeConvertedSpaceSpan(const Node * node)104 static bool isInterchangeConvertedSpaceSpan(const Node *node)
105 {
106     DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
107     return node->isHTMLElement() &&
108            static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
109 }
110 
positionAvoidingPrecedingNodes(Position pos)111 static Position positionAvoidingPrecedingNodes(Position pos)
112 {
113     // If we're already on a break, it's probably a placeholder and we shouldn't change our position.
114     if (editingIgnoresContent(pos.deprecatedNode()))
115         return pos;
116 
117     // We also stop when changing block flow elements because even though the visual position is the
118     // same.  E.g.,
119     //   <div>foo^</div>^
120     // The two positions above are the same visual position, but we want to stay in the same block.
121     Node* stopNode = pos.deprecatedNode()->enclosingBlockFlowElement();
122     while (stopNode != pos.deprecatedNode() && VisiblePosition(pos) == VisiblePosition(pos.next()))
123         pos = pos.next();
124     return pos;
125 }
126 
ReplacementFragment(Document * document,DocumentFragment * fragment,bool matchStyle,const VisibleSelection & selection)127 ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* fragment, bool matchStyle, const VisibleSelection& selection)
128     : m_document(document),
129       m_fragment(fragment),
130       m_matchStyle(matchStyle),
131       m_hasInterchangeNewlineAtStart(false),
132       m_hasInterchangeNewlineAtEnd(false)
133 {
134     if (!m_document)
135         return;
136     if (!m_fragment)
137         return;
138     if (!m_fragment->firstChild())
139         return;
140 
141     RefPtr<Element> editableRoot = selection.rootEditableElement();
142     ASSERT(editableRoot);
143     if (!editableRoot)
144         return;
145 
146     Node* shadowAncestorNode = editableRoot->shadowAncestorNode();
147 
148     if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
149         // FIXME: Remove these checks once textareas and textfields actually register an event handler.
150         !(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
151         editableRoot->rendererIsRichlyEditable()) {
152         removeInterchangeNodes(m_fragment.get());
153         return;
154     }
155 
156     RefPtr<Node> styleNode = selection.base().deprecatedNode();
157     RefPtr<StyledElement> holder = insertFragmentForTestRendering(styleNode.get());
158     if (!holder) {
159         removeInterchangeNodes(m_fragment.get());
160         return;
161     }
162 
163     RefPtr<Range> range = VisibleSelection::selectionFromContentsOfNode(holder.get()).toNormalizedRange();
164     String text = plainText(range.get());
165     // Give the root a chance to change the text.
166     RefPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text);
167     ExceptionCode ec = 0;
168     editableRoot->dispatchEvent(evt, ec);
169     ASSERT(ec == 0);
170     if (text != evt->text() || !editableRoot->rendererIsRichlyEditable()) {
171         restoreTestRenderingNodesToFragment(holder.get());
172         removeNode(holder);
173 
174         m_fragment = createFragmentFromText(selection.toNormalizedRange().get(), evt->text());
175         if (!m_fragment->firstChild())
176             return;
177         holder = insertFragmentForTestRendering(styleNode.get());
178     }
179 
180     removeInterchangeNodes(holder.get());
181 
182     removeUnrenderedNodes(holder.get());
183     restoreTestRenderingNodesToFragment(holder.get());
184     removeNode(holder);
185 }
186 
isEmpty() const187 bool ReplacementFragment::isEmpty() const
188 {
189     return (!m_fragment || !m_fragment->firstChild()) && !m_hasInterchangeNewlineAtStart && !m_hasInterchangeNewlineAtEnd;
190 }
191 
firstChild() const192 Node *ReplacementFragment::firstChild() const
193 {
194     return m_fragment ? m_fragment->firstChild() : 0;
195 }
196 
lastChild() const197 Node *ReplacementFragment::lastChild() const
198 {
199     return m_fragment ? m_fragment->lastChild() : 0;
200 }
201 
removeNodePreservingChildren(Node * node)202 void ReplacementFragment::removeNodePreservingChildren(Node *node)
203 {
204     if (!node)
205         return;
206 
207     while (RefPtr<Node> n = node->firstChild()) {
208         removeNode(n);
209         insertNodeBefore(n.release(), node);
210     }
211     removeNode(node);
212 }
213 
removeNode(PassRefPtr<Node> node)214 void ReplacementFragment::removeNode(PassRefPtr<Node> node)
215 {
216     if (!node)
217         return;
218 
219     ContainerNode* parent = node->parentNode();
220     if (!parent)
221         return;
222 
223     ExceptionCode ec = 0;
224     parent->removeChild(node.get(), ec);
225     ASSERT(ec == 0);
226 }
227 
insertNodeBefore(PassRefPtr<Node> node,Node * refNode)228 void ReplacementFragment::insertNodeBefore(PassRefPtr<Node> node, Node* refNode)
229 {
230     if (!node || !refNode)
231         return;
232 
233     ContainerNode* parent = refNode->parentNode();
234     if (!parent)
235         return;
236 
237     ExceptionCode ec = 0;
238     parent->insertBefore(node, refNode, ec);
239     ASSERT(ec == 0);
240 }
241 
insertFragmentForTestRendering(Node * context)242 PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* context)
243 {
244     HTMLElement* body = m_document->body();
245     if (!body)
246         return 0;
247 
248     RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
249 
250     ExceptionCode ec = 0;
251 
252     // Copy the whitespace and user-select style from the context onto this element.
253     // Walk up past <br> elements which may be placeholders and might have their own specified styles.
254     // FIXME: We should examine other style properties to see if they would be appropriate to consider during the test rendering.
255     Node* n = context;
256     while (n && (!n->isElementNode() || n->hasTagName(brTag)))
257         n = n->parentNode();
258     if (n) {
259         RefPtr<CSSComputedStyleDeclaration> conFontStyle = computedStyle(n);
260         CSSStyleDeclaration* style = holder->style();
261         style->setProperty(CSSPropertyWhiteSpace, conFontStyle->getPropertyValue(CSSPropertyWhiteSpace), false, ec);
262         ASSERT(ec == 0);
263         style->setProperty(CSSPropertyWebkitUserSelect, conFontStyle->getPropertyValue(CSSPropertyWebkitUserSelect), false, ec);
264         ASSERT(ec == 0);
265     }
266 
267     holder->appendChild(m_fragment, ec);
268     ASSERT(ec == 0);
269 
270     body->appendChild(holder.get(), ec);
271     ASSERT(ec == 0);
272 
273     m_document->updateLayoutIgnorePendingStylesheets();
274 
275     return holder.release();
276 }
277 
restoreTestRenderingNodesToFragment(StyledElement * holder)278 void ReplacementFragment::restoreTestRenderingNodesToFragment(StyledElement* holder)
279 {
280     if (!holder)
281         return;
282 
283     ExceptionCode ec = 0;
284     while (RefPtr<Node> node = holder->firstChild()) {
285         holder->removeChild(node.get(), ec);
286         ASSERT(ec == 0);
287         m_fragment->appendChild(node.get(), ec);
288         ASSERT(ec == 0);
289     }
290 }
291 
removeUnrenderedNodes(Node * holder)292 void ReplacementFragment::removeUnrenderedNodes(Node* holder)
293 {
294     Vector<RefPtr<Node> > unrendered;
295 
296     for (Node* node = holder->firstChild(); node; node = node->traverseNextNode(holder))
297         if (!isNodeRendered(node) && !isTableStructureNode(node))
298             unrendered.append(node);
299 
300     size_t n = unrendered.size();
301     for (size_t i = 0; i < n; ++i)
302         removeNode(unrendered[i]);
303 }
304 
removeInterchangeNodes(Node * container)305 void ReplacementFragment::removeInterchangeNodes(Node* container)
306 {
307     // Interchange newlines at the "start" of the incoming fragment must be
308     // either the first node in the fragment or the first leaf in the fragment.
309     Node* node = container->firstChild();
310     while (node) {
311         if (isInterchangeNewlineNode(node)) {
312             m_hasInterchangeNewlineAtStart = true;
313             removeNode(node);
314             break;
315         }
316         node = node->firstChild();
317     }
318     if (!container->hasChildNodes())
319         return;
320     // Interchange newlines at the "end" of the incoming fragment must be
321     // either the last node in the fragment or the last leaf in the fragment.
322     node = container->lastChild();
323     while (node) {
324         if (isInterchangeNewlineNode(node)) {
325             m_hasInterchangeNewlineAtEnd = true;
326             removeNode(node);
327             break;
328         }
329         node = node->lastChild();
330     }
331 
332     node = container->firstChild();
333     while (node) {
334         Node *next = node->traverseNextNode();
335         if (isInterchangeConvertedSpaceSpan(node)) {
336             RefPtr<Node> n = 0;
337             while ((n = node->firstChild())) {
338                 removeNode(n);
339                 insertNodeBefore(n, node);
340             }
341             removeNode(node);
342             if (n)
343                 next = n->traverseNextNode();
344         }
345         node = next;
346     }
347 }
348 
ReplaceSelectionCommand(Document * document,PassRefPtr<DocumentFragment> fragment,CommandOptions options,EditAction editAction)349 ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
350     : CompositeEditCommand(document)
351     , m_selectReplacement(options & SelectReplacement)
352     , m_smartReplace(options & SmartReplace)
353     , m_matchStyle(options & MatchStyle)
354     , m_documentFragment(fragment)
355     , m_preventNesting(options & PreventNesting)
356     , m_movingParagraph(options & MovingParagraph)
357     , m_editAction(editAction)
358     , m_shouldMergeEnd(false)
359 {
360 }
361 
hasMatchingQuoteLevel(VisiblePosition endOfExistingContent,VisiblePosition endOfInsertedContent)362 static bool hasMatchingQuoteLevel(VisiblePosition endOfExistingContent, VisiblePosition endOfInsertedContent)
363 {
364     Position existing = endOfExistingContent.deepEquivalent();
365     Position inserted = endOfInsertedContent.deepEquivalent();
366     bool isInsideMailBlockquote = enclosingNodeOfType(inserted, isMailBlockquote, CanCrossEditingBoundary);
367     return isInsideMailBlockquote && (numEnclosingMailBlockquotes(existing) == numEnclosingMailBlockquotes(inserted));
368 }
369 
shouldMergeStart(bool selectionStartWasStartOfParagraph,bool fragmentHasInterchangeNewlineAtStart,bool selectionStartWasInsideMailBlockquote)370 bool ReplaceSelectionCommand::shouldMergeStart(bool selectionStartWasStartOfParagraph, bool fragmentHasInterchangeNewlineAtStart, bool selectionStartWasInsideMailBlockquote)
371 {
372     if (m_movingParagraph)
373         return false;
374 
375     VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
376     VisiblePosition prev = startOfInsertedContent.previous(CannotCrossEditingBoundary);
377     if (prev.isNull())
378         return false;
379 
380     // When we have matching quote levels, its ok to merge more frequently.
381     // For a successful merge, we still need to make sure that the inserted content starts with the beginning of a paragraph.
382     // And we should only merge here if the selection start was inside a mail blockquote.  This prevents against removing a
383     // blockquote from newly pasted quoted content that was pasted into an unquoted position.  If that unquoted position happens
384     // to be right after another blockquote, we don't want to merge and risk stripping a valid block (and newline) from the pasted content.
385     if (isStartOfParagraph(startOfInsertedContent) && selectionStartWasInsideMailBlockquote && hasMatchingQuoteLevel(prev, positionAtEndOfInsertedContent()))
386         return true;
387 
388     return !selectionStartWasStartOfParagraph
389         && !fragmentHasInterchangeNewlineAtStart
390         && isStartOfParagraph(startOfInsertedContent)
391         && !startOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
392         && shouldMerge(startOfInsertedContent, prev);
393 }
394 
shouldMergeEnd(bool selectionEndWasEndOfParagraph)395 bool ReplaceSelectionCommand::shouldMergeEnd(bool selectionEndWasEndOfParagraph)
396 {
397     VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
398     VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
399     if (next.isNull())
400         return false;
401 
402     return !selectionEndWasEndOfParagraph
403         && isEndOfParagraph(endOfInsertedContent)
404         && !endOfInsertedContent.deepEquivalent().deprecatedNode()->hasTagName(brTag)
405         && shouldMerge(endOfInsertedContent, next);
406 }
407 
isMailPasteAsQuotationNode(const Node * node)408 static bool isMailPasteAsQuotationNode(const Node* node)
409 {
410     return node && node->hasTagName(blockquoteTag) && node->isElementNode() && static_cast<const Element*>(node)->getAttribute(classAttr) == ApplePasteAsQuotation;
411 }
412 
413 // Wrap CompositeEditCommand::removeNodePreservingChildren() so we can update the nodes we track
removeNodePreservingChildren(Node * node)414 void ReplaceSelectionCommand::removeNodePreservingChildren(Node* node)
415 {
416     if (m_firstNodeInserted == node)
417         m_firstNodeInserted = node->traverseNextNode();
418     if (m_lastLeafInserted == node)
419         m_lastLeafInserted = node->lastChild() ? node->lastChild() : node->traverseNextSibling();
420     CompositeEditCommand::removeNodePreservingChildren(node);
421 }
422 
423 // Wrap CompositeEditCommand::removeNodeAndPruneAncestors() so we can update the nodes we track
removeNodeAndPruneAncestors(Node * node)424 void ReplaceSelectionCommand::removeNodeAndPruneAncestors(Node* node)
425 {
426     // prepare in case m_firstNodeInserted and/or m_lastLeafInserted get removed
427     // FIXME: shouldn't m_lastLeafInserted be adjusted using traversePreviousNode()?
428     Node* afterFirst = m_firstNodeInserted ? m_firstNodeInserted->traverseNextSibling() : 0;
429     Node* afterLast = m_lastLeafInserted ? m_lastLeafInserted->traverseNextSibling() : 0;
430 
431     CompositeEditCommand::removeNodeAndPruneAncestors(node);
432 
433     // adjust m_firstNodeInserted and m_lastLeafInserted since either or both may have been removed
434     if (m_lastLeafInserted && !m_lastLeafInserted->inDocument())
435         m_lastLeafInserted = afterLast;
436     if (m_firstNodeInserted && !m_firstNodeInserted->inDocument())
437         m_firstNodeInserted = m_lastLeafInserted && m_lastLeafInserted->inDocument() ? afterFirst : 0;
438 }
439 
isHeaderElement(Node * a)440 static bool isHeaderElement(Node* a)
441 {
442     if (!a)
443         return false;
444 
445     return a->hasTagName(h1Tag) ||
446            a->hasTagName(h2Tag) ||
447            a->hasTagName(h3Tag) ||
448            a->hasTagName(h4Tag) ||
449            a->hasTagName(h5Tag);
450 }
451 
haveSameTagName(Node * a,Node * b)452 static bool haveSameTagName(Node* a, Node* b)
453 {
454     return a && b && a->isElementNode() && b->isElementNode() && static_cast<Element*>(a)->tagName() == static_cast<Element*>(b)->tagName();
455 }
456 
shouldMerge(const VisiblePosition & source,const VisiblePosition & destination)457 bool ReplaceSelectionCommand::shouldMerge(const VisiblePosition& source, const VisiblePosition& destination)
458 {
459     if (source.isNull() || destination.isNull())
460         return false;
461 
462     Node* sourceNode = source.deepEquivalent().deprecatedNode();
463     Node* destinationNode = destination.deepEquivalent().deprecatedNode();
464     Node* sourceBlock = enclosingBlock(sourceNode);
465     Node* destinationBlock = enclosingBlock(destinationNode);
466     return !enclosingNodeOfType(source.deepEquivalent(), &isMailPasteAsQuotationNode) &&
467            sourceBlock && (!sourceBlock->hasTagName(blockquoteTag) || isMailBlockquote(sourceBlock))  &&
468            enclosingListChild(sourceBlock) == enclosingListChild(destinationNode) &&
469            enclosingTableCell(source.deepEquivalent()) == enclosingTableCell(destination.deepEquivalent()) &&
470            (!isHeaderElement(sourceBlock) || haveSameTagName(sourceBlock, destinationBlock)) &&
471            // Don't merge to or from a position before or after a block because it would
472            // be a no-op and cause infinite recursion.
473            !isBlock(sourceNode) && !isBlock(destinationNode);
474 }
475 
476 // Style rules that match just inserted elements could change their appearance, like
477 // a div inserted into a document with div { display:inline; }.
negateStyleRulesThatAffectAppearance()478 void ReplaceSelectionCommand::negateStyleRulesThatAffectAppearance()
479 {
480     for (RefPtr<Node> node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
481         // FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
482         if (isStyleSpan(node.get())) {
483             HTMLElement* e = toHTMLElement(node.get());
484             // There are other styles that style rules can give to style spans,
485             // but these are the two important ones because they'll prevent
486             // inserted content from appearing in the right paragraph.
487             // FIXME: Hyatt is concerned that selectively using display:inline will give inconsistent
488             // results. We already know one issue because td elements ignore their display property
489             // in quirks mode (which Mail.app is always in). We should look for an alternative.
490             if (isBlock(e))
491                 e->getInlineStyleDecl()->setProperty(CSSPropertyDisplay, CSSValueInline);
492             if (e->renderer() && e->renderer()->style()->floating() != FNONE)
493                 e->getInlineStyleDecl()->setProperty(CSSPropertyFloat, CSSValueNone);
494         }
495         if (node == m_lastLeafInserted)
496             break;
497     }
498 }
499 
removeUnrenderedTextNodesAtEnds()500 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds()
501 {
502     document()->updateLayoutIgnorePendingStylesheets();
503     if (!m_lastLeafInserted->renderer()
504         && m_lastLeafInserted->isTextNode()
505         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(m_lastLeafInserted.get()), selectTag)
506         && !enclosingNodeWithTag(firstPositionInOrBeforeNode(m_lastLeafInserted.get()), scriptTag)) {
507         if (m_firstNodeInserted == m_lastLeafInserted) {
508             removeNode(m_lastLeafInserted.get());
509             m_lastLeafInserted = 0;
510             m_firstNodeInserted = 0;
511             return;
512         }
513         RefPtr<Node> previous = m_lastLeafInserted->traversePreviousNode();
514         removeNode(m_lastLeafInserted.get());
515         m_lastLeafInserted = previous;
516     }
517 
518     // We don't have to make sure that m_firstNodeInserted isn't inside a select or script element, because
519     // it is a top level node in the fragment and the user can't insert into those elements.
520     if (!m_firstNodeInserted->renderer() &&
521         m_firstNodeInserted->isTextNode()) {
522         if (m_firstNodeInserted == m_lastLeafInserted) {
523             removeNode(m_firstNodeInserted.get());
524             m_firstNodeInserted = 0;
525             m_lastLeafInserted = 0;
526             return;
527         }
528         RefPtr<Node> next = m_firstNodeInserted->traverseNextSibling();
529         removeNode(m_firstNodeInserted.get());
530         m_firstNodeInserted = next;
531     }
532 }
533 
handlePasteAsQuotationNode()534 void ReplaceSelectionCommand::handlePasteAsQuotationNode()
535 {
536     Node* node = m_firstNodeInserted.get();
537     if (isMailPasteAsQuotationNode(node))
538         removeNodeAttribute(static_cast<Element*>(node), classAttr);
539 }
540 
positionAtEndOfInsertedContent()541 VisiblePosition ReplaceSelectionCommand::positionAtEndOfInsertedContent()
542 {
543     Node* lastNode = m_lastLeafInserted.get();
544     // FIXME: Why is this hack here?  What's special about <select> tags?
545     Node* enclosingSelect = enclosingNodeWithTag(firstPositionInOrBeforeNode(lastNode), selectTag);
546     if (enclosingSelect)
547         lastNode = enclosingSelect;
548     return lastPositionInOrAfterNode(lastNode);
549 }
550 
positionAtStartOfInsertedContent()551 VisiblePosition ReplaceSelectionCommand::positionAtStartOfInsertedContent()
552 {
553     // Return the inserted content's first VisiblePosition.
554     return VisiblePosition(nextCandidate(positionInParentBeforeNode(m_firstNodeInserted.get())));
555 }
556 
557 // Remove style spans before insertion if they are unnecessary.  It's faster because we'll
558 // avoid doing a layout.
handleStyleSpansBeforeInsertion(ReplacementFragment & fragment,const Position & insertionPos)559 static bool handleStyleSpansBeforeInsertion(ReplacementFragment& fragment, const Position& insertionPos)
560 {
561     Node* topNode = fragment.firstChild();
562 
563     // Handling the case where we are doing Paste as Quotation or pasting into quoted content is more complicated (see handleStyleSpans)
564     // and doesn't receive the optimization.
565     if (isMailPasteAsQuotationNode(topNode) || enclosingNodeOfType(firstPositionInOrBeforeNode(topNode), isMailBlockquote, CanCrossEditingBoundary))
566         return false;
567 
568     // Either there are no style spans in the fragment or a WebKit client has added content to the fragment
569     // before inserting it.  Look for and handle style spans after insertion.
570     if (!isStyleSpan(topNode))
571         return false;
572 
573     Node* wrappingStyleSpan = topNode;
574     RefPtr<EditingStyle> styleAtInsertionPos = EditingStyle::create(insertionPos.parentAnchoredEquivalent());
575     String styleText = styleAtInsertionPos->style()->cssText();
576 
577     // FIXME: This string comparison is a naive way of comparing two styles.
578     // We should be taking the diff and check that the diff is empty.
579     if (styleText != static_cast<Element*>(wrappingStyleSpan)->getAttribute(styleAttr))
580         return false;
581 
582     fragment.removeNodePreservingChildren(wrappingStyleSpan);
583     return true;
584 }
585 
586 // At copy time, WebKit wraps copied content in a span that contains the source document's
587 // default styles.  If the copied Range inherits any other styles from its ancestors, we put
588 // those styles on a second span.
589 // This function removes redundant styles from those spans, and removes the spans if all their
590 // styles are redundant.
591 // We should remove the Apple-style-span class when we're done, see <rdar://problem/5685600>.
592 // We should remove styles from spans that are overridden by all of their children, either here
593 // or at copy time.
handleStyleSpans()594 void ReplaceSelectionCommand::handleStyleSpans()
595 {
596     HTMLElement* wrappingStyleSpan = 0;
597     // The style span that contains the source document's default style should be at
598     // the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
599     // so search for the top level style span instead of assuming it's at the top.
600     for (Node* node = m_firstNodeInserted.get(); node; node = node->traverseNextNode()) {
601         if (isStyleSpan(node)) {
602             wrappingStyleSpan = toHTMLElement(node);
603             break;
604         }
605     }
606 
607     // There might not be any style spans if we're pasting from another application or if
608     // we are here because of a document.execCommand("InsertHTML", ...) call.
609     if (!wrappingStyleSpan)
610         return;
611 
612     RefPtr<EditingStyle> style = EditingStyle::create(wrappingStyleSpan->getInlineStyleDecl());
613     ContainerNode* context = wrappingStyleSpan->parentNode();
614 
615     // If Mail wraps the fragment with a Paste as Quotation blockquote, or if you're pasting into a quoted region,
616     // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
617     Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
618     if (blockquoteNode)
619         context = document()->documentElement();
620 
621     // This operation requires that only editing styles to be removed from sourceDocumentStyle.
622     style->prepareToApplyAt(firstPositionInNode(context));
623 
624     // Remove block properties in the span's style. This prevents properties that probably have no effect
625     // currently from affecting blocks later if the style is cloned for a new block element during a future
626     // editing operation.
627     // FIXME: They *can* have an effect currently if blocks beneath the style span aren't individually marked
628     // with block styles by the editing engine used to style them.  WebKit doesn't do this, but others might.
629     style->removeBlockProperties();
630 
631     if (style->isEmpty() || !wrappingStyleSpan->firstChild())
632         removeNodePreservingChildren(wrappingStyleSpan);
633     else
634         setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->cssText());
635 }
636 
637 // Take the style attribute of a span and apply it to it's children instead.  This allows us to
638 // convert invalid HTML where a span contains block elements into valid HTML while preserving
639 // styles.
copyStyleToChildren(Node * parentNode,const CSSMutableStyleDeclaration * parentStyle)640 void ReplaceSelectionCommand::copyStyleToChildren(Node* parentNode, const CSSMutableStyleDeclaration* parentStyle)
641 {
642     ASSERT(parentNode->hasTagName(spanTag));
643     NodeVector childNodes;
644     for (RefPtr<Node> childNode = parentNode->firstChild(); childNode; childNode = childNode->nextSibling())
645         childNodes.append(childNode);
646 
647     for (NodeVector::const_iterator it = childNodes.begin(); it != childNodes.end(); it++) {
648         Node* childNode = it->get();
649         if (childNode->isTextNode() || !isBlock(childNode) || childNode->hasTagName(preTag)) {
650             // In this case, put a span tag around the child node.
651             RefPtr<Node> newNode = parentNode->cloneNode(false);
652             ASSERT(newNode->hasTagName(spanTag));
653             HTMLElement* newSpan = toHTMLElement(newNode.get());
654             setNodeAttribute(newSpan, styleAttr, parentStyle->cssText());
655             insertNodeAfter(newSpan, childNode);
656             ExceptionCode ec = 0;
657             newSpan->appendChild(childNode, ec);
658             ASSERT(!ec);
659             childNode = newSpan;
660         } else if (childNode->isHTMLElement()) {
661             // Copy the style attribute and merge them into the child node.  We don't want to override
662             // existing styles, so don't clobber on merge.
663             RefPtr<CSSMutableStyleDeclaration> newStyle = parentStyle->copy();
664             HTMLElement* childElement = toHTMLElement(childNode);
665             RefPtr<CSSMutableStyleDeclaration> existingStyles = childElement->getInlineStyleDecl()->copy();
666             existingStyles->merge(newStyle.get(), false);
667             setNodeAttribute(childElement, styleAttr, existingStyles->cssText());
668         }
669     }
670 }
671 
mergeEndIfNeeded()672 void ReplaceSelectionCommand::mergeEndIfNeeded()
673 {
674     if (!m_shouldMergeEnd)
675         return;
676 
677     VisiblePosition startOfInsertedContent(positionAtStartOfInsertedContent());
678     VisiblePosition endOfInsertedContent(positionAtEndOfInsertedContent());
679 
680     // Bail to avoid infinite recursion.
681     if (m_movingParagraph) {
682         ASSERT_NOT_REACHED();
683         return;
684     }
685 
686     // Merging two paragraphs will destroy the moved one's block styles.  Always move the end of inserted forward
687     // to preserve the block style of the paragraph already in the document, unless the paragraph to move would
688     // include the what was the start of the selection that was pasted into, so that we preserve that paragraph's
689     // block styles.
690     bool mergeForward = !(inSameParagraph(startOfInsertedContent, endOfInsertedContent) && !isStartOfParagraph(startOfInsertedContent));
691 
692     VisiblePosition destination = mergeForward ? endOfInsertedContent.next() : endOfInsertedContent;
693     VisiblePosition startOfParagraphToMove = mergeForward ? startOfParagraph(endOfInsertedContent) : endOfInsertedContent.next();
694 
695     // Merging forward could result in deleting the destination anchor node.
696     // To avoid this, we add a placeholder node before the start of the paragraph.
697     if (endOfParagraph(startOfParagraphToMove) == destination) {
698         RefPtr<Node> placeholder = createBreakElement(document());
699         insertNodeBefore(placeholder, startOfParagraphToMove.deepEquivalent().deprecatedNode());
700         destination = VisiblePosition(positionBeforeNode(placeholder.get()));
701     }
702 
703     moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
704 
705     // Merging forward will remove m_lastLeafInserted from the document.
706     // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes.  The nodes are
707     // only ever used to create positions where inserted content starts/ends.  Also, we sometimes insert content
708     // directly into text nodes already in the document, in which case tracking inserted nodes is inadequate.
709     if (mergeForward) {
710         m_lastLeafInserted = destination.previous().deepEquivalent().deprecatedNode();
711         if (!m_firstNodeInserted->inDocument())
712             m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().deprecatedNode();
713         // If we merged text nodes, m_lastLeafInserted could be null. If this is the case,
714         // we use m_firstNodeInserted.
715         if (!m_lastLeafInserted)
716             m_lastLeafInserted = m_firstNodeInserted;
717     }
718 }
719 
enclosingInline(Node * node)720 static Node* enclosingInline(Node* node)
721 {
722     while (ContainerNode* parent = node->parentNode()) {
723         if (parent->isBlockFlow() || parent->hasTagName(bodyTag))
724             return node;
725         // Stop if any previous sibling is a block.
726         for (Node* sibling = node->previousSibling(); sibling; sibling = sibling->previousSibling()) {
727             if (sibling->isBlockFlow())
728                 return node;
729         }
730         node = parent;
731     }
732     return node;
733 }
734 
isInlineNodeWithStyle(const Node * node)735 static bool isInlineNodeWithStyle(const Node* node)
736 {
737     // We don't want to skip over any block elements.
738     if (!node->renderer() || !node->renderer()->isInline())
739         return false;
740 
741     if (!node->isHTMLElement())
742         return false;
743 
744     // We can skip over elements whose class attribute is
745     // one of our internal classes.
746     const HTMLElement* element = static_cast<const HTMLElement*>(node);
747     AtomicString classAttributeValue = element->getAttribute(classAttr);
748     if (classAttributeValue == AppleStyleSpanClass
749         || classAttributeValue == AppleTabSpanClass
750         || classAttributeValue == AppleConvertedSpace
751         || classAttributeValue == ApplePasteAsQuotation)
752         return true;
753 
754     // We can skip inline elements that don't have attributes or whose only
755     // attribute is the style attribute.
756     const NamedNodeMap* attributeMap = element->attributeMap();
757     if (!attributeMap || attributeMap->isEmpty() || (attributeMap->length() == 1 && element->hasAttribute(styleAttr)))
758         return true;
759 
760     return false;
761 }
762 
doApply()763 void ReplaceSelectionCommand::doApply()
764 {
765     VisibleSelection selection = endingSelection();
766     ASSERT(selection.isCaretOrRange());
767     ASSERT(selection.start().deprecatedNode());
768     if (!selection.isNonOrphanedCaretOrRange() || !selection.start().deprecatedNode())
769         return;
770 
771     bool selectionIsPlainText = !selection.isContentRichlyEditable();
772 
773     Element* currentRoot = selection.rootEditableElement();
774     ReplacementFragment fragment(document(), m_documentFragment.get(), m_matchStyle, selection);
775 
776     if (performTrivialReplace(fragment))
777         return;
778 
779     // We can skip matching the style if the selection is plain text.
780     if ((selection.start().deprecatedNode()->renderer() && selection.start().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY)
781         && (selection.end().deprecatedNode()->renderer() && selection.end().deprecatedNode()->renderer()->style()->userModify() == READ_WRITE_PLAINTEXT_ONLY))
782         m_matchStyle = false;
783 
784     if (m_matchStyle) {
785         m_insertionStyle = EditingStyle::create(selection.start());
786         m_insertionStyle->mergeTypingStyle(document());
787     }
788 
789     VisiblePosition visibleStart = selection.visibleStart();
790     VisiblePosition visibleEnd = selection.visibleEnd();
791 
792     bool selectionEndWasEndOfParagraph = isEndOfParagraph(visibleEnd);
793     bool selectionStartWasStartOfParagraph = isStartOfParagraph(visibleStart);
794 
795     Node* startBlock = enclosingBlock(visibleStart.deepEquivalent().deprecatedNode());
796 
797     Position insertionPos = selection.start();
798     bool startIsInsideMailBlockquote = enclosingNodeOfType(insertionPos, isMailBlockquote, CanCrossEditingBoundary);
799 
800     if ((selectionStartWasStartOfParagraph && selectionEndWasEndOfParagraph && !startIsInsideMailBlockquote) ||
801         startBlock == currentRoot || isListItem(startBlock) || selectionIsPlainText)
802         m_preventNesting = false;
803 
804     if (selection.isRange()) {
805         // When the end of the selection being pasted into is at the end of a paragraph, and that selection
806         // spans multiple blocks, not merging may leave an empty line.
807         // When the start of the selection being pasted into is at the start of a block, not merging
808         // will leave hanging block(s).
809         // Merge blocks if the start of the selection was in a Mail blockquote, since we handle
810         // that case specially to prevent nesting.
811         bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
812         // FIXME: We should only expand to include fully selected special elements if we are copying a
813         // selection and pasting it on top of itself.
814         deleteSelection(false, mergeBlocksAfterDelete, true, false);
815         visibleStart = endingSelection().visibleStart();
816         if (fragment.hasInterchangeNewlineAtStart()) {
817             if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
818                 if (!isEndOfDocument(visibleStart))
819                     setEndingSelection(visibleStart.next());
820             } else
821                 insertParagraphSeparator();
822         }
823         insertionPos = endingSelection().start();
824     } else {
825         ASSERT(selection.isCaret());
826         if (fragment.hasInterchangeNewlineAtStart()) {
827             VisiblePosition next = visibleStart.next(CannotCrossEditingBoundary);
828             if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart) && next.isNotNull())
829                 setEndingSelection(next);
830             else
831                 insertParagraphSeparator();
832         }
833         // We split the current paragraph in two to avoid nesting the blocks from the fragment inside the current block.
834         // For example paste <div>foo</div><div>bar</div><div>baz</div> into <div>x^x</div>, where ^ is the caret.
835         // As long as the  div styles are the same, visually you'd expect: <div>xbar</div><div>bar</div><div>bazx</div>,
836         // not <div>xbar<div>bar</div><div>bazx</div></div>.
837         // Don't do this if the selection started in a Mail blockquote.
838         if (m_preventNesting && !startIsInsideMailBlockquote && !isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
839             insertParagraphSeparator();
840             setEndingSelection(endingSelection().visibleStart().previous());
841         }
842         insertionPos = endingSelection().start();
843     }
844 
845     // We don't want any of the pasted content to end up nested in a Mail blockquote, so first break
846     // out of any surrounding Mail blockquotes. Unless we're inserting in a table, in which case
847     // breaking the blockquote will prevent the content from actually being inserted in the table.
848     if (startIsInsideMailBlockquote && m_preventNesting && !(enclosingNodeOfType(insertionPos, &isTableStructureNode))) {
849         applyCommandToComposite(BreakBlockquoteCommand::create(document()));
850         // This will leave a br between the split.
851         Node* br = endingSelection().start().deprecatedNode();
852         ASSERT(br->hasTagName(brTag));
853         // Insert content between the two blockquotes, but remove the br (since it was just a placeholder).
854         insertionPos = positionInParentBeforeNode(br);
855         removeNode(br);
856     }
857 
858     // Inserting content could cause whitespace to collapse, e.g. inserting <div>foo</div> into hello^ world.
859     prepareWhitespaceAtPositionForSplit(insertionPos);
860 
861     // If the downstream node has been removed there's no point in continuing.
862     if (!insertionPos.downstream().deprecatedNode())
863       return;
864 
865     // NOTE: This would be an incorrect usage of downstream() if downstream() were changed to mean the last position after
866     // 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
867     // away, there are positions after the br which map to the same visible position as [br, 0]).
868     Node* endBR = insertionPos.downstream().deprecatedNode()->hasTagName(brTag) ? insertionPos.downstream().deprecatedNode() : 0;
869     VisiblePosition originalVisPosBeforeEndBR;
870     if (endBR)
871         originalVisPosBeforeEndBR = VisiblePosition(positionBeforeNode(endBR), DOWNSTREAM).previous();
872 
873     startBlock = enclosingBlock(insertionPos.deprecatedNode());
874 
875     // Adjust insertionPos to prevent nesting.
876     // If the start was in a Mail blockquote, we will have already handled adjusting insertionPos above.
877     if (m_preventNesting && startBlock && !startIsInsideMailBlockquote) {
878         ASSERT(startBlock != currentRoot);
879         VisiblePosition visibleInsertionPos(insertionPos);
880         if (isEndOfBlock(visibleInsertionPos) && !(isStartOfBlock(visibleInsertionPos) && fragment.hasInterchangeNewlineAtEnd()))
881             insertionPos = positionInParentAfterNode(startBlock);
882         else if (isStartOfBlock(visibleInsertionPos))
883             insertionPos = positionInParentBeforeNode(startBlock);
884     }
885 
886     // Paste at start or end of link goes outside of link.
887     insertionPos = positionAvoidingSpecialElementBoundary(insertionPos);
888 
889     // FIXME: Can this wait until after the operation has been performed?  There doesn't seem to be
890     // any work performed after this that queries or uses the typing style.
891     if (Frame* frame = document()->frame())
892         frame->selection()->clearTypingStyle();
893 
894     // We don't want the destination to end up inside nodes that weren't selected.  To avoid that, we move the
895     // position forward without changing the visible position so we're still at the same visible location, but
896     // outside of preceding tags.
897     insertionPos = positionAvoidingPrecedingNodes(insertionPos);
898 
899     // Paste into run of tabs splits the tab span.
900     insertionPos = positionOutsideTabSpan(insertionPos);
901 
902     bool handledStyleSpans = handleStyleSpansBeforeInsertion(fragment, insertionPos);
903 
904     // If we are not trying to match the destination style we prefer a position
905     // that is outside inline elements that provide style.
906     // This way we can produce a less verbose markup.
907     // We can skip this optimization for fragments not wrapped in one of
908     // our style spans and for positions inside list items
909     // since insertAsListItems already does the right thing.
910     if (!m_matchStyle && !enclosingList(insertionPos.containerNode()) && isStyleSpan(fragment.firstChild())) {
911         if (insertionPos.containerNode()->isTextNode() && insertionPos.offsetInContainerNode() && !insertionPos.atLastEditingPositionForNode()) {
912             splitTextNodeContainingElement(static_cast<Text*>(insertionPos.containerNode()), insertionPos.offsetInContainerNode());
913             insertionPos = firstPositionInNode(insertionPos.containerNode());
914         }
915 
916         // FIXME: isInlineNodeWithStyle does not check editability.
917         if (RefPtr<Node> nodeToSplitTo = highestEnclosingNodeOfType(insertionPos, isInlineNodeWithStyle)) {
918             if (insertionPos.containerNode() != nodeToSplitTo) {
919                 nodeToSplitTo = splitTreeToNode(insertionPos.anchorNode(), nodeToSplitTo.get(), true).get();
920                 insertionPos = positionInParentBeforeNode(nodeToSplitTo.get());
921             }
922         }
923     }
924 
925     // FIXME: When pasting rich content we're often prevented from heading down the fast path by style spans.  Try
926     // again here if they've been removed.
927 
928     // We're finished if there is nothing to add.
929     if (fragment.isEmpty() || !fragment.firstChild())
930         return;
931 
932     // 1) Insert the content.
933     // 2) Remove redundant styles and style tags, this inner <b> for example: <b>foo <b>bar</b> baz</b>.
934     // 3) Merge the start of the added content with the content before the position being pasted into.
935     // 4) Do one of the following: a) expand the last br if the fragment ends with one and it collapsed,
936     // b) merge the last paragraph of the incoming fragment with the paragraph that contained the
937     // end of the selection that was pasted into, or c) handle an interchange newline at the end of the
938     // incoming fragment.
939     // 5) Add spaces for smart replace.
940     // 6) Select the replacement if requested, and match style if requested.
941 
942     VisiblePosition startOfInsertedContent, endOfInsertedContent;
943 
944     RefPtr<Node> refNode = fragment.firstChild();
945     RefPtr<Node> node = refNode->nextSibling();
946 
947     fragment.removeNode(refNode);
948 
949     Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
950     if ((isListElement(refNode.get()) || (isStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
951         && blockStart->renderer()->isListItem())
952         refNode = insertAsListItems(refNode, blockStart, insertionPos);
953     else
954         insertNodeAtAndUpdateNodesInserted(refNode, insertionPos);
955 
956     // Mutation events (bug 22634) may have already removed the inserted content
957     if (!refNode->inDocument())
958         return;
959 
960     bool plainTextFragment = isPlainTextMarkup(refNode.get());
961 
962     while (node) {
963         RefPtr<Node> next = node->nextSibling();
964         fragment.removeNode(node.get());
965         insertNodeAfterAndUpdateNodesInserted(node, refNode.get());
966 
967         // Mutation events (bug 22634) may have already removed the inserted content
968         if (!node->inDocument())
969             return;
970 
971         refNode = node;
972         if (node && plainTextFragment)
973             plainTextFragment = isPlainTextMarkup(node.get());
974         node = next;
975     }
976 
977     removeUnrenderedTextNodesAtEnds();
978 
979     negateStyleRulesThatAffectAppearance();
980 
981     if (!handledStyleSpans)
982         handleStyleSpans();
983 
984     // Mutation events (bug 20161) may have already removed the inserted content
985     if (!m_firstNodeInserted || !m_firstNodeInserted->inDocument())
986         return;
987 
988     endOfInsertedContent = positionAtEndOfInsertedContent();
989     startOfInsertedContent = positionAtStartOfInsertedContent();
990 
991     // We inserted before the startBlock to prevent nesting, and the content before the startBlock wasn't in its own block and
992     // didn't have a br after it, so the inserted content ended up in the same paragraph.
993     if (startBlock && insertionPos.deprecatedNode() == startBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < startBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
994         insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
995 
996     Position lastPositionToSelect;
997 
998     bool interchangeNewlineAtEnd = fragment.hasInterchangeNewlineAtEnd();
999 
1000     if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR)))
1001         removeNodeAndPruneAncestors(endBR);
1002 
1003     // Determine whether or not we should merge the end of inserted content with what's after it before we do
1004     // the start merge so that the start merge doesn't effect our decision.
1005     m_shouldMergeEnd = shouldMergeEnd(selectionEndWasEndOfParagraph);
1006 
1007     if (shouldMergeStart(selectionStartWasStartOfParagraph, fragment.hasInterchangeNewlineAtStart(), startIsInsideMailBlockquote)) {
1008         VisiblePosition destination = startOfInsertedContent.previous();
1009         VisiblePosition startOfParagraphToMove = startOfInsertedContent;
1010         // We need to handle the case where we need to merge the end
1011         // but our destination node is inside an inline that is the last in the block.
1012         // We insert a placeholder before the newly inserted content to avoid being merged into the inline.
1013         Node* destinationNode = destination.deepEquivalent().deprecatedNode();
1014         if (m_shouldMergeEnd && destinationNode != enclosingInline(destinationNode) && enclosingInline(destinationNode)->nextSibling())
1015             insertNodeBefore(createBreakElement(document()), refNode.get());
1016 
1017         // Merging the the first paragraph of inserted content with the content that came
1018         // before the selection that was pasted into would also move content after
1019         // the selection that was pasted into if: only one paragraph was being pasted,
1020         // and it was not wrapped in a block, the selection that was pasted into ended
1021         // at the end of a block and the next paragraph didn't start at the start of a block.
1022         // Insert a line break just after the inserted content to separate it from what
1023         // comes after and prevent that from happening.
1024         VisiblePosition endOfInsertedContent = positionAtEndOfInsertedContent();
1025         if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
1026             insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
1027             // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
1028             if (!startOfParagraphToMove.deepEquivalent().anchorNode()->inDocument())
1029                 return;
1030         }
1031 
1032         // FIXME: Maintain positions for the start and end of inserted content instead of keeping nodes.  The nodes are
1033         // only ever used to create positions where inserted content starts/ends.
1034         moveParagraph(startOfParagraphToMove, endOfParagraph(startOfParagraphToMove), destination);
1035         m_firstNodeInserted = endingSelection().visibleStart().deepEquivalent().downstream().deprecatedNode();
1036         if (!m_lastLeafInserted->inDocument())
1037             m_lastLeafInserted = endingSelection().visibleEnd().deepEquivalent().upstream().deprecatedNode();
1038     }
1039 
1040     endOfInsertedContent = positionAtEndOfInsertedContent();
1041     startOfInsertedContent = positionAtStartOfInsertedContent();
1042 
1043     if (interchangeNewlineAtEnd) {
1044         VisiblePosition next = endOfInsertedContent.next(CannotCrossEditingBoundary);
1045 
1046         if (selectionEndWasEndOfParagraph || !isEndOfParagraph(endOfInsertedContent) || next.isNull()) {
1047             if (!isStartOfParagraph(endOfInsertedContent)) {
1048                 setEndingSelection(endOfInsertedContent);
1049                 Node* enclosingNode = enclosingBlock(endOfInsertedContent.deepEquivalent().deprecatedNode());
1050                 if (isListItem(enclosingNode)) {
1051                     RefPtr<Node> newListItem = createListItemElement(document());
1052                     insertNodeAfter(newListItem, enclosingNode);
1053                     setEndingSelection(VisiblePosition(firstPositionInNode(newListItem.get())));
1054                 } else
1055                     // Use a default paragraph element (a plain div) for the empty paragraph, using the last paragraph
1056                     // block's style seems to annoy users.
1057                     insertParagraphSeparator(true);
1058 
1059                 // Select up to the paragraph separator that was added.
1060                 lastPositionToSelect = endingSelection().visibleStart().deepEquivalent();
1061                 updateNodesInserted(lastPositionToSelect.deprecatedNode());
1062             }
1063         } else {
1064             // Select up to the beginning of the next paragraph.
1065             lastPositionToSelect = next.deepEquivalent().downstream();
1066         }
1067 
1068     } else
1069         mergeEndIfNeeded();
1070 
1071     handlePasteAsQuotationNode();
1072 
1073     endOfInsertedContent = positionAtEndOfInsertedContent();
1074     startOfInsertedContent = positionAtStartOfInsertedContent();
1075 
1076     // Add spaces for smart replace.
1077     if (m_smartReplace && currentRoot) {
1078         // Disable smart replace for password fields.
1079         Node* start = currentRoot->shadowAncestorNode();
1080         if (start->hasTagName(inputTag) && static_cast<HTMLInputElement*>(start)->isPasswordField())
1081             m_smartReplace = false;
1082     }
1083     if (m_smartReplace) {
1084         bool needsTrailingSpace = !isEndOfParagraph(endOfInsertedContent) &&
1085                                   !isCharacterSmartReplaceExempt(endOfInsertedContent.characterAfter(), false);
1086         if (needsTrailingSpace) {
1087             RenderObject* renderer = m_lastLeafInserted->renderer();
1088             bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
1089             Node* endNode = positionAtEndOfInsertedContent().deepEquivalent().upstream().deprecatedNode();
1090             if (endNode->isTextNode()) {
1091                 Text* text = static_cast<Text*>(endNode);
1092                 insertTextIntoNode(text, text->length(), collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1093             } else {
1094                 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1095                 insertNodeAfterAndUpdateNodesInserted(node, endNode);
1096             }
1097         }
1098 
1099         bool needsLeadingSpace = !isStartOfParagraph(startOfInsertedContent) &&
1100                                  !isCharacterSmartReplaceExempt(startOfInsertedContent.previous().characterAfter(), true);
1101         if (needsLeadingSpace) {
1102             RenderObject* renderer = m_lastLeafInserted->renderer();
1103             bool collapseWhiteSpace = !renderer || renderer->style()->collapseWhiteSpace();
1104             Node* startNode = positionAtStartOfInsertedContent().deepEquivalent().downstream().deprecatedNode();
1105             if (startNode->isTextNode()) {
1106                 Text* text = static_cast<Text*>(startNode);
1107                 insertTextIntoNode(text, 0, collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1108             } else {
1109                 RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
1110                 // Don't updateNodesInserted.  Doing so would set m_lastLeafInserted to be the node containing the
1111                 // leading space, but m_lastLeafInserted is supposed to mark the end of pasted content.
1112                 insertNodeBefore(node, startNode);
1113                 // FIXME: Use positions to track the start/end of inserted content.
1114                 m_firstNodeInserted = node;
1115             }
1116         }
1117     }
1118 
1119     // If we are dealing with a fragment created from plain text
1120     // no style matching is necessary.
1121     if (plainTextFragment)
1122         m_matchStyle = false;
1123 
1124     completeHTMLReplacement(lastPositionToSelect);
1125 }
1126 
shouldRemoveEndBR(Node * endBR,const VisiblePosition & originalVisPosBeforeEndBR)1127 bool ReplaceSelectionCommand::shouldRemoveEndBR(Node* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
1128 {
1129     if (!endBR || !endBR->inDocument())
1130         return false;
1131 
1132     VisiblePosition visiblePos(positionBeforeNode(endBR));
1133 
1134     // Don't remove the br if nothing was inserted.
1135     if (visiblePos.previous() == originalVisPosBeforeEndBR)
1136         return false;
1137 
1138     // Remove the br if it is collapsed away and so is unnecessary.
1139     if (!document()->inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
1140         return true;
1141 
1142     // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
1143     // A br that was originally acting as a line break should still be acting as a line break, not as a placeholder.
1144     return isStartOfParagraph(visiblePos) && isEndOfParagraph(visiblePos);
1145 }
1146 
completeHTMLReplacement(const Position & lastPositionToSelect)1147 void ReplaceSelectionCommand::completeHTMLReplacement(const Position &lastPositionToSelect)
1148 {
1149     Position start;
1150     Position end;
1151 
1152     // FIXME: This should never not be the case.
1153     if (m_firstNodeInserted && m_firstNodeInserted->inDocument() && m_lastLeafInserted && m_lastLeafInserted->inDocument()) {
1154 
1155         start = positionAtStartOfInsertedContent().deepEquivalent();
1156         end = positionAtEndOfInsertedContent().deepEquivalent();
1157 
1158         // FIXME (11475): Remove this and require that the creator of the fragment to use nbsps.
1159         rebalanceWhitespaceAt(start);
1160         rebalanceWhitespaceAt(end);
1161 
1162         if (m_matchStyle) {
1163             ASSERT(m_insertionStyle);
1164             applyStyle(m_insertionStyle.get(), start, end);
1165         }
1166 
1167         if (lastPositionToSelect.isNotNull())
1168             end = lastPositionToSelect;
1169     } else if (lastPositionToSelect.isNotNull())
1170         start = end = lastPositionToSelect;
1171     else
1172         return;
1173 
1174     if (m_selectReplacement)
1175         setEndingSelection(VisibleSelection(start, end, SEL_DEFAULT_AFFINITY));
1176     else
1177         setEndingSelection(VisibleSelection(end, SEL_DEFAULT_AFFINITY));
1178 }
1179 
editingAction() const1180 EditAction ReplaceSelectionCommand::editingAction() const
1181 {
1182     return m_editAction;
1183 }
1184 
insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild,Node * refChild)1185 void ReplaceSelectionCommand::insertNodeAfterAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1186 {
1187     Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1188     insertNodeAfter(insertChild, refChild);
1189     updateNodesInserted(nodeToUpdate);
1190 }
1191 
insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild,const Position & p)1192 void ReplaceSelectionCommand::insertNodeAtAndUpdateNodesInserted(PassRefPtr<Node> insertChild, const Position& p)
1193 {
1194     Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1195     insertNodeAt(insertChild, p);
1196     updateNodesInserted(nodeToUpdate);
1197 }
1198 
insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild,Node * refChild)1199 void ReplaceSelectionCommand::insertNodeBeforeAndUpdateNodesInserted(PassRefPtr<Node> insertChild, Node* refChild)
1200 {
1201     Node* nodeToUpdate = insertChild.get(); // insertChild will be cleared when passed
1202     insertNodeBefore(insertChild, refChild);
1203     updateNodesInserted(nodeToUpdate);
1204 }
1205 
1206 // If the user is inserting a list into an existing list, instead of nesting the list,
1207 // we put the list items into the existing list.
insertAsListItems(PassRefPtr<Node> listElement,Node * insertionBlock,const Position & insertPos)1208 Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<Node> listElement, Node* insertionBlock, const Position& insertPos)
1209 {
1210     while (listElement->hasChildNodes() && isListElement(listElement->firstChild()) && listElement->childNodeCount() == 1)
1211         listElement = listElement->firstChild();
1212 
1213     bool isStart = isStartOfParagraph(insertPos);
1214     bool isEnd = isEndOfParagraph(insertPos);
1215     bool isMiddle = !isStart && !isEnd;
1216     Node* lastNode = insertionBlock;
1217 
1218     // If we're in the middle of a list item, we should split it into two separate
1219     // list items and insert these nodes between them.
1220     if (isMiddle) {
1221         int textNodeOffset = insertPos.offsetInContainerNode();
1222         if (insertPos.deprecatedNode()->isTextNode() && textNodeOffset > 0)
1223             splitTextNode(static_cast<Text*>(insertPos.deprecatedNode()), textNodeOffset);
1224         splitTreeToNode(insertPos.deprecatedNode(), lastNode, true);
1225     }
1226 
1227     while (RefPtr<Node> listItem = listElement->firstChild()) {
1228         ExceptionCode ec = 0;
1229         toContainerNode(listElement.get())->removeChild(listItem.get(), ec);
1230         ASSERT(!ec);
1231         if (isStart || isMiddle)
1232             insertNodeBefore(listItem, lastNode);
1233         else if (isEnd) {
1234             insertNodeAfter(listItem, lastNode);
1235             lastNode = listItem.get();
1236         } else
1237             ASSERT_NOT_REACHED();
1238     }
1239     if (isStart || isMiddle)
1240         lastNode = lastNode->previousSibling();
1241     if (isMiddle)
1242         insertNodeAfter(createListItemElement(document()), lastNode);
1243     updateNodesInserted(lastNode);
1244     return lastNode;
1245 }
1246 
updateNodesInserted(Node * node)1247 void ReplaceSelectionCommand::updateNodesInserted(Node *node)
1248 {
1249     if (!node)
1250         return;
1251 
1252     if (!m_firstNodeInserted)
1253         m_firstNodeInserted = node;
1254 
1255     if (node == m_lastLeafInserted)
1256         return;
1257 
1258     m_lastLeafInserted = node->lastDescendant();
1259 }
1260 
1261 // During simple pastes, where we're just pasting a text node into a run of text, we insert the text node
1262 // directly into the text node that holds the selection.  This is much faster than the generalized code in
1263 // ReplaceSelectionCommand, and works around <https://bugs.webkit.org/show_bug.cgi?id=6148> since we don't
1264 // split text nodes.
performTrivialReplace(const ReplacementFragment & fragment)1265 bool ReplaceSelectionCommand::performTrivialReplace(const ReplacementFragment& fragment)
1266 {
1267     if (!fragment.firstChild() || fragment.firstChild() != fragment.lastChild() || !fragment.firstChild()->isTextNode())
1268         return false;
1269 
1270     // FIXME: Would be nice to handle smart replace in the fast path.
1271     if (m_smartReplace || fragment.hasInterchangeNewlineAtStart() || fragment.hasInterchangeNewlineAtEnd())
1272         return false;
1273 
1274     Text* textNode = static_cast<Text*>(fragment.firstChild());
1275     // Our fragment creation code handles tabs, spaces, and newlines, so we don't have to worry about those here.
1276     String text(textNode->data());
1277 
1278     Position start = endingSelection().start().parentAnchoredEquivalent();
1279     Position end = endingSelection().end().parentAnchoredEquivalent();
1280     ASSERT(start.anchorType() == Position::PositionIsOffsetInAnchor);
1281     ASSERT(end.anchorType() == Position::PositionIsOffsetInAnchor);
1282 
1283     if (start.containerNode() != end.containerNode() || !start.containerNode()->isTextNode())
1284         return false;
1285 
1286     replaceTextInNode(static_cast<Text*>(start.containerNode()), start.offsetInContainerNode(), end.offsetInContainerNode() - start.offsetInContainerNode(), text);
1287 
1288     end = Position(start.containerNode(), start.offsetInContainerNode() + text.length(), Position::PositionIsOffsetInAnchor);
1289 
1290     VisibleSelection selectionAfterReplace(m_selectReplacement ? start : end, end);
1291 
1292     setEndingSelection(selectionAfterReplace);
1293 
1294     return true;
1295 }
1296 
1297 } // namespace WebCore
1298