Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / editing / InsertParagraphSeparatorCommand.cpp
1 /*
2  * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "core/editing/InsertParagraphSeparatorCommand.h"
28
29 #include "core/HTMLNames.h"
30 #include "core/dom/Document.h"
31 #include "core/dom/NodeTraversal.h"
32 #include "core/dom/Text.h"
33 #include "core/editing/EditingStyle.h"
34 #include "core/editing/InsertLineBreakCommand.h"
35 #include "core/editing/VisibleUnits.h"
36 #include "core/editing/htmlediting.h"
37 #include "core/html/HTMLBRElement.h"
38 #include "core/html/HTMLElement.h"
39 #include "core/html/HTMLQuoteElement.h"
40 #include "core/rendering/RenderObject.h"
41 #include "core/rendering/RenderText.h"
42
43 namespace blink {
44
45 using namespace HTMLNames;
46
47 // When inserting a new line, we want to avoid nesting empty divs if we can.  Otherwise, when
48 // pasting, it's easy to have each new line be a div deeper than the previous.  E.g., in the case
49 // below, we want to insert at ^ instead of |.
50 // <div>foo<div>bar</div>|</div>^
51 static Element* highestVisuallyEquivalentDivBelowRoot(Element* startBlock)
52 {
53     Element* curBlock = startBlock;
54     // We don't want to return a root node (if it happens to be a div, e.g., in a document fragment) because there are no
55     // siblings for us to append to.
56     while (!curBlock->nextSibling() && isHTMLDivElement(*curBlock->parentElement()) && curBlock->parentElement()->parentElement()) {
57         if (curBlock->parentElement()->hasAttributes())
58             break;
59         curBlock = curBlock->parentElement();
60     }
61     return curBlock;
62 }
63
64 InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(Document& document, bool mustUseDefaultParagraphElement, bool pasteBlockquoteIntoUnquotedArea)
65     : CompositeEditCommand(document)
66     , m_mustUseDefaultParagraphElement(mustUseDefaultParagraphElement)
67     , m_pasteBlockquoteIntoUnquotedArea(pasteBlockquoteIntoUnquotedArea)
68 {
69 }
70
71 bool InsertParagraphSeparatorCommand::preservesTypingStyle() const
72 {
73     return true;
74 }
75
76 void InsertParagraphSeparatorCommand::calculateStyleBeforeInsertion(const Position &pos)
77 {
78     // It is only important to set a style to apply later if we're at the boundaries of
79     // a paragraph. Otherwise, content that is moved as part of the work of the command
80     // will lend their styles to the new paragraph without any extra work needed.
81     VisiblePosition visiblePos(pos, VP_DEFAULT_AFFINITY);
82     if (!isStartOfParagraph(visiblePos) && !isEndOfParagraph(visiblePos))
83         return;
84
85     ASSERT(pos.isNotNull());
86     m_style = EditingStyle::create(pos);
87     m_style->mergeTypingStyle(pos.document());
88 }
89
90 void InsertParagraphSeparatorCommand::applyStyleAfterInsertion(Element* originalEnclosingBlock)
91 {
92     // Not only do we break out of header tags, but we also do not preserve the typing style,
93     // in order to match other browsers.
94     if (originalEnclosingBlock->hasTagName(h1Tag) ||
95         originalEnclosingBlock->hasTagName(h2Tag) ||
96         originalEnclosingBlock->hasTagName(h3Tag) ||
97         originalEnclosingBlock->hasTagName(h4Tag) ||
98         originalEnclosingBlock->hasTagName(h5Tag))
99         return;
100
101     if (!m_style)
102         return;
103
104     m_style->prepareToApplyAt(endingSelection().start());
105     if (!m_style->isEmpty())
106         applyStyle(m_style.get());
107 }
108
109 bool InsertParagraphSeparatorCommand::shouldUseDefaultParagraphElement(Element* enclosingBlock) const
110 {
111     if (m_mustUseDefaultParagraphElement)
112         return true;
113
114     // Assumes that if there was a range selection, it was already deleted.
115     if (!isEndOfBlock(endingSelection().visibleStart()))
116         return false;
117
118     return enclosingBlock->hasTagName(h1Tag) ||
119            enclosingBlock->hasTagName(h2Tag) ||
120            enclosingBlock->hasTagName(h3Tag) ||
121            enclosingBlock->hasTagName(h4Tag) ||
122            enclosingBlock->hasTagName(h5Tag);
123 }
124
125 void InsertParagraphSeparatorCommand::getAncestorsInsideBlock(const Node* insertionNode, Element* outerBlock, WillBeHeapVector<RefPtrWillBeMember<Element>>& ancestors)
126 {
127     ancestors.clear();
128
129     // Build up list of ancestors elements between the insertion node and the outer block.
130     if (insertionNode != outerBlock) {
131         for (Element* n = insertionNode->parentElement(); n && n != outerBlock; n = n->parentElement())
132             ancestors.append(n);
133     }
134 }
135
136 PassRefPtrWillBeRawPtr<Element> InsertParagraphSeparatorCommand::cloneHierarchyUnderNewBlock(const WillBeHeapVector<RefPtrWillBeMember<Element>>& ancestors, PassRefPtrWillBeRawPtr<Element> blockToInsert)
137 {
138     // Make clones of ancestors in between the start node and the start block.
139     RefPtrWillBeRawPtr<Element> parent = blockToInsert;
140     for (size_t i = ancestors.size(); i != 0; --i) {
141         RefPtrWillBeRawPtr<Element> child = ancestors[i - 1]->cloneElementWithoutChildren();
142         // It should always be okay to remove id from the cloned elements, since the originals are not deleted.
143         child->removeAttribute(idAttr);
144         appendNode(child, parent);
145         parent = child.release();
146     }
147
148     return parent.release();
149 }
150
151 void InsertParagraphSeparatorCommand::doApply()
152 {
153     if (!endingSelection().isNonOrphanedCaretOrRange())
154         return;
155
156     Position insertionPosition = endingSelection().start();
157
158     EAffinity affinity = endingSelection().affinity();
159
160     // Delete the current selection.
161     if (endingSelection().isRange()) {
162         calculateStyleBeforeInsertion(insertionPosition);
163         deleteSelection(false, true);
164         insertionPosition = endingSelection().start();
165         affinity = endingSelection().affinity();
166     }
167
168     // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enclosingBlock.
169     RefPtrWillBeRawPtr<Element> startBlock = enclosingBlock(insertionPosition.parentAnchoredEquivalent().containerNode());
170     Node* listChildNode = enclosingListChild(insertionPosition.parentAnchoredEquivalent().containerNode());
171     RefPtrWillBeRawPtr<HTMLElement> listChild = listChildNode && listChildNode->isHTMLElement() ? toHTMLElement(listChildNode) : 0;
172     Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
173     if (!startBlock
174         || !startBlock->nonShadowBoundaryParentNode()
175         || isTableCell(startBlock.get())
176         || isHTMLFormElement(*startBlock)
177         // FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
178         || (!canonicalPos.isNull() && isRenderedTableElement(canonicalPos.deprecatedNode()))
179         || (!canonicalPos.isNull() && isHTMLHRElement(*canonicalPos.deprecatedNode()))) {
180         applyCommandToComposite(InsertLineBreakCommand::create(document()));
181         return;
182     }
183
184     // Use the leftmost candidate.
185     insertionPosition = insertionPosition.upstream();
186     if (!insertionPosition.isCandidate())
187         insertionPosition = insertionPosition.downstream();
188
189     // Adjust the insertion position after the delete
190     insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition);
191     VisiblePosition visiblePos(insertionPosition, affinity);
192     calculateStyleBeforeInsertion(insertionPosition);
193
194     //---------------------------------------------------------------------
195     // Handle special case of typing return on an empty list item
196     if (breakOutOfEmptyListItem())
197         return;
198
199     //---------------------------------------------------------------------
200     // Prepare for more general cases.
201
202     bool isFirstInBlock = isStartOfBlock(visiblePos);
203     bool isLastInBlock = isEndOfBlock(visiblePos);
204     bool nestNewBlock = false;
205
206     // Create block to be inserted.
207     RefPtrWillBeRawPtr<Element> blockToInsert = nullptr;
208     if (startBlock->isRootEditableElement()) {
209         blockToInsert = createDefaultParagraphElement(document());
210         nestNewBlock = true;
211     } else if (shouldUseDefaultParagraphElement(startBlock.get())) {
212         blockToInsert = createDefaultParagraphElement(document());
213     } else {
214         blockToInsert = startBlock->cloneElementWithoutChildren();
215     }
216
217     //---------------------------------------------------------------------
218     // Handle case when position is in the last visible position in its block,
219     // including when the block is empty.
220     if (isLastInBlock) {
221         if (nestNewBlock) {
222             if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
223                 // The block is empty.  Create an empty block to
224                 // represent the paragraph that we're leaving.
225                 RefPtrWillBeRawPtr<HTMLElement> extraBlock = createDefaultParagraphElement(document());
226                 appendNode(extraBlock, startBlock);
227                 appendBlockPlaceholder(extraBlock);
228             }
229             appendNode(blockToInsert, startBlock);
230         } else {
231             // We can get here if we pasted a copied portion of a blockquote with a newline at the end and are trying to paste it
232             // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
233             if (m_pasteBlockquoteIntoUnquotedArea) {
234                 if (HTMLQuoteElement* highestBlockquote = toHTMLQuoteElement(highestEnclosingNodeOfType(canonicalPos, &isMailHTMLBlockquoteElement)))
235                     startBlock = highestBlockquote;
236             }
237
238             if (listChild && listChild != startBlock) {
239                 RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
240                 appendNode(blockToInsert, listChildToInsert.get());
241                 insertNodeAfter(listChildToInsert.get(), listChild);
242             } else {
243                 // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists). However,
244                 // for div nodes, this can result in nested div tags that are hard to break out of.
245                 Element* siblingElement = startBlock.get();
246                 if (isHTMLDivElement(*blockToInsert))
247                     siblingElement = highestVisuallyEquivalentDivBelowRoot(startBlock.get());
248                 insertNodeAfter(blockToInsert, siblingElement);
249             }
250         }
251
252         // Recreate the same structure in the new paragraph.
253
254         WillBeHeapVector<RefPtrWillBeMember<Element>> ancestors;
255         getAncestorsInsideBlock(positionOutsideTabSpan(insertionPosition).deprecatedNode(), startBlock.get(), ancestors);
256         RefPtrWillBeRawPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert);
257
258         appendBlockPlaceholder(parent);
259
260         setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), DOWNSTREAM, endingSelection().isDirectional()));
261         return;
262     }
263
264
265     //---------------------------------------------------------------------
266     // Handle case when position is in the first visible position in its block, and
267     // similar case where previous position is in another, presumeably nested, block.
268     if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
269         Node* refNode = nullptr;
270         insertionPosition = positionOutsideTabSpan(insertionPosition);
271
272         if (isFirstInBlock && !nestNewBlock) {
273             if (listChild && listChild != startBlock) {
274                 RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
275                 appendNode(blockToInsert, listChildToInsert.get());
276                 insertNodeBefore(listChildToInsert.get(), listChild);
277             } else {
278                 refNode = startBlock.get();
279             }
280         } else if (isFirstInBlock && nestNewBlock) {
281             // startBlock should always have children, otherwise isLastInBlock would be true and it's handled above.
282             ASSERT(startBlock->hasChildren());
283             refNode = startBlock->firstChild();
284         }
285         else if (insertionPosition.deprecatedNode() == startBlock && nestNewBlock) {
286             refNode = NodeTraversal::childAt(*startBlock, insertionPosition.deprecatedEditingOffset());
287             ASSERT(refNode); // must be true or we'd be in the end of block case
288         } else
289             refNode = insertionPosition.deprecatedNode();
290
291         // find ending selection position easily before inserting the paragraph
292         insertionPosition = insertionPosition.downstream();
293
294         if (refNode)
295             insertNodeBefore(blockToInsert, refNode);
296
297         // Recreate the same structure in the new paragraph.
298
299         WillBeHeapVector<RefPtrWillBeMember<Element>> ancestors;
300         getAncestorsInsideBlock(positionAvoidingSpecialElementBoundary(positionOutsideTabSpan(insertionPosition)).deprecatedNode(), startBlock.get(), ancestors);
301
302         appendBlockPlaceholder(cloneHierarchyUnderNewBlock(ancestors, blockToInsert));
303
304         // In this case, we need to set the new ending selection.
305         setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endingSelection().isDirectional()));
306         return;
307     }
308
309     //---------------------------------------------------------------------
310     // Handle the (more complicated) general case,
311
312     // All of the content in the current block after visiblePos is
313     // about to be wrapped in a new paragraph element.  Add a br before
314     // it if visiblePos is at the start of a paragraph so that the
315     // content will move down a line.
316     if (isStartOfParagraph(visiblePos)) {
317         RefPtrWillBeRawPtr<HTMLBRElement> br = createBreakElement(document());
318         insertNodeAt(br.get(), insertionPosition);
319         insertionPosition = positionInParentAfterNode(*br);
320         // If the insertion point is a break element, there is nothing else
321         // we need to do.
322         if (visiblePos.deepEquivalent().anchorNode()->renderer()->isBR()) {
323             setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM, endingSelection().isDirectional()));
324             return;
325         }
326     }
327
328     // Move downstream. Typing style code will take care of carrying along the
329     // style of the upstream position.
330     insertionPosition = insertionPosition.downstream();
331
332     // At this point, the insertionPosition's node could be a container, and we want to make sure we include
333     // all of the correct nodes when building the ancestor list.  So this needs to be the deepest representation of the position
334     // before we walk the DOM tree.
335     insertionPosition = positionOutsideTabSpan(VisiblePosition(insertionPosition).deepEquivalent());
336
337     // If the returned position lies either at the end or at the start of an element that is ignored by editing
338     // we should move to its upstream or downstream position.
339     if (editingIgnoresContent(insertionPosition.deprecatedNode())) {
340         if (insertionPosition.atLastEditingPositionForNode())
341             insertionPosition = insertionPosition.downstream();
342         else if (insertionPosition.atFirstEditingPositionForNode())
343             insertionPosition = insertionPosition.upstream();
344     }
345
346     // Make sure we do not cause a rendered space to become unrendered.
347     // FIXME: We need the affinity for pos, but pos.downstream() does not give it
348     Position leadingWhitespace = leadingWhitespacePosition(insertionPosition, VP_DEFAULT_AFFINITY);
349     // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
350     // after the preserved newline, causing the newline to be turned into a nbsp.
351     if (leadingWhitespace.isNotNull() && leadingWhitespace.deprecatedNode()->isTextNode()) {
352         Text* textNode = toText(leadingWhitespace.deprecatedNode());
353         ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
354         replaceTextInNodePreservingMarkers(textNode, leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
355     }
356
357     // Split at pos if in the middle of a text node.
358     Position positionAfterSplit;
359     if (insertionPosition.anchorType() == Position::PositionIsOffsetInAnchor && insertionPosition.containerNode()->isTextNode()) {
360         RefPtrWillBeRawPtr<Text> textNode = toText(insertionPosition.containerNode());
361         bool atEnd = static_cast<unsigned>(insertionPosition.offsetInContainerNode()) >= textNode->length();
362         if (insertionPosition.deprecatedEditingOffset() > 0 && !atEnd) {
363             splitTextNode(textNode, insertionPosition.offsetInContainerNode());
364             positionAfterSplit = firstPositionInNode(textNode.get());
365             insertionPosition.moveToPosition(textNode->previousSibling(), insertionPosition.offsetInContainerNode());
366             visiblePos = VisiblePosition(insertionPosition);
367         }
368     }
369
370     // If we got detached due to mutation events, just bail out.
371     if (!startBlock->parentNode())
372         return;
373
374     // Put the added block in the tree.
375     if (nestNewBlock) {
376         appendNode(blockToInsert.get(), startBlock);
377     } else if (listChild && listChild != startBlock) {
378         RefPtrWillBeRawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
379         appendNode(blockToInsert.get(), listChildToInsert.get());
380         insertNodeAfter(listChildToInsert.get(), listChild);
381     } else {
382         insertNodeAfter(blockToInsert.get(), startBlock);
383     }
384
385     document().updateLayoutIgnorePendingStylesheets();
386
387     // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
388     // created.  All of the nodes, starting at visiblePos, are about to be added to the new paragraph
389     // element.  If the first node to be inserted won't be one that will hold an empty line open, add a br.
390     if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visiblePos))
391         appendNode(createBreakElement(document()).get(), blockToInsert.get());
392
393     // Move the start node and the siblings of the start node.
394     if (VisiblePosition(insertionPosition) != VisiblePosition(positionBeforeNode(blockToInsert.get()))) {
395         Node* n;
396         if (insertionPosition.containerNode() == startBlock)
397             n = insertionPosition.computeNodeAfterPosition();
398         else {
399             Node* splitTo = insertionPosition.containerNode();
400             if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
401                 splitTo = NodeTraversal::next(*splitTo, startBlock.get());
402             ASSERT(splitTo);
403             splitTreeToNode(splitTo, startBlock.get());
404
405             for (n = startBlock->firstChild(); n; n = n->nextSibling()) {
406                 VisiblePosition beforeNodePosition(positionBeforeNode(n));
407                 if (!beforeNodePosition.isNull() && comparePositions(VisiblePosition(insertionPosition), beforeNodePosition) <= 0)
408                     break;
409             }
410         }
411
412         moveRemainingSiblingsToNewParent(n, blockToInsert.get(), blockToInsert);
413     }
414
415     // Handle whitespace that occurs after the split
416     if (positionAfterSplit.isNotNull()) {
417         document().updateLayoutIgnorePendingStylesheets();
418         if (!positionAfterSplit.isRenderedCharacter()) {
419             // Clear out all whitespace and insert one non-breaking space
420             ASSERT(!positionAfterSplit.containerNode()->renderer() || positionAfterSplit.containerNode()->renderer()->style()->collapseWhiteSpace());
421             deleteInsignificantTextDownstream(positionAfterSplit);
422             if (positionAfterSplit.deprecatedNode()->isTextNode())
423                 insertTextIntoNode(toText(positionAfterSplit.containerNode()), 0, nonBreakingSpaceString());
424         }
425     }
426
427     setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()), DOWNSTREAM, endingSelection().isDirectional()));
428     applyStyleAfterInsertion(startBlock.get());
429 }
430
431 void InsertParagraphSeparatorCommand::trace(Visitor *visitor)
432 {
433     visitor->trace(m_style);
434     CompositeEditCommand::trace(visitor);
435 }
436
437
438 } // namespace blink