OSDN Git Service

Merge WebKit at r73109: Initial merge by git.
[android-x86/external-webkit.git] / WebCore / editing / InsertLineBreakCommand.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 "InsertLineBreakCommand.h"
28
29 #include "CSSMutableStyleDeclaration.h"
30 #include "Document.h"
31 #include "Frame.h"
32 #include "HTMLElement.h"
33 #include "HTMLNames.h"
34 #include "Range.h"
35 #include "RenderObject.h"
36 #include "Text.h"
37 #include "VisiblePosition.h"
38 #include "htmlediting.h"
39 #include "visible_units.h"
40
41 namespace WebCore {
42
43 using namespace HTMLNames;
44
45 InsertLineBreakCommand::InsertLineBreakCommand(Document* document) 
46     : CompositeEditCommand(document)
47 {
48 }
49
50 bool InsertLineBreakCommand::preservesTypingStyle() const
51 {
52     return true;
53 }
54
55 void InsertLineBreakCommand::insertNodeAfterPosition(Node* node, const Position& pos)
56 {
57     // Insert the BR after the caret position. In the case the
58     // position is a block, do an append. We don't want to insert
59     // the BR *after* the block.
60     Element* cb = pos.node()->enclosingBlockFlowElement();
61     if (cb == pos.node())
62         appendNode(node, cb);
63     else
64         insertNodeAfter(node, pos.node());
65 }
66
67 void InsertLineBreakCommand::insertNodeBeforePosition(Node* node, const Position& pos)
68 {
69     // Insert the BR after the caret position. In the case the
70     // position is a block, do an append. We don't want to insert
71     // the BR *before* the block.
72     Element* cb = pos.node()->enclosingBlockFlowElement();
73     if (cb == pos.node())
74         appendNode(node, cb);
75     else
76         insertNodeBefore(node, pos.node());
77 }
78
79 // Whether we should insert a break element or a '\n'.
80 bool InsertLineBreakCommand::shouldUseBreakElement(const Position& insertionPos)
81 {
82     // An editing position like [input, 0] actually refers to the position before
83     // the input element, and in that case we need to check the input element's
84     // parent's renderer.
85     Position p(rangeCompliantEquivalent(insertionPos));
86     return p.node()->renderer() && !p.node()->renderer()->style()->preserveNewline();
87 }
88
89 void InsertLineBreakCommand::doApply()
90 {
91     deleteSelection();
92     VisibleSelection selection = endingSelection();
93     if (!selection.isNonOrphanedCaretOrRange())
94         return;
95     
96     VisiblePosition caret(selection.visibleStart());
97     // FIXME: If the node is hidden, we should still be able to insert text. 
98     // For now, we return to avoid a crash.  https://bugs.webkit.org/show_bug.cgi?id=40342
99     if (caret.isNull())
100         return;
101
102     Position pos(caret.deepEquivalent());
103
104     pos = positionAvoidingSpecialElementBoundary(pos);
105     
106     pos = positionOutsideTabSpan(pos);
107
108     RefPtr<Node> nodeToInsert;
109     if (shouldUseBreakElement(pos))
110         nodeToInsert = createBreakElement(document());
111     else
112         nodeToInsert = document()->createTextNode("\n");
113     
114     // FIXME: Need to merge text nodes when inserting just after or before text.
115     
116     if (isEndOfParagraph(caret) && !lineBreakExistsAtVisiblePosition(caret)) {
117         bool needExtraLineBreak = !pos.node()->hasTagName(hrTag) && !pos.node()->hasTagName(tableTag);
118         
119         insertNodeAt(nodeToInsert.get(), pos);
120         
121         if (needExtraLineBreak)
122             insertNodeBefore(nodeToInsert->cloneNode(false), nodeToInsert);
123         
124         VisiblePosition endingPosition(Position(nodeToInsert.get(), 0));
125         setEndingSelection(VisibleSelection(endingPosition));
126     } else if (pos.deprecatedEditingOffset() <= caretMinOffset(pos.node())) {
127         insertNodeAt(nodeToInsert.get(), pos);
128         
129         // Insert an extra br or '\n' if the just inserted one collapsed.
130         if (!isStartOfParagraph(VisiblePosition(Position(nodeToInsert.get(), 0))))
131             insertNodeBefore(nodeToInsert->cloneNode(false).get(), nodeToInsert.get());
132         
133         setEndingSelection(VisibleSelection(positionInParentAfterNode(nodeToInsert.get()), DOWNSTREAM));
134     // If we're inserting after all of the rendered text in a text node, or into a non-text node,
135     // a simple insertion is sufficient.
136     } else if (pos.deprecatedEditingOffset() >= caretMaxOffset(pos.node()) || !pos.node()->isTextNode()) {
137         insertNodeAt(nodeToInsert.get(), pos);
138         setEndingSelection(VisibleSelection(positionInParentAfterNode(nodeToInsert.get()), DOWNSTREAM));
139     } else if (pos.node()->isTextNode()) {
140         // Split a text node
141         Text* textNode = static_cast<Text*>(pos.node());
142         splitTextNode(textNode, pos.deprecatedEditingOffset());
143         insertNodeBefore(nodeToInsert, textNode);
144         Position endingPosition = Position(textNode, 0);
145         
146         // Handle whitespace that occurs after the split
147         updateLayout();
148         if (!endingPosition.isRenderedCharacter()) {
149             Position positionBeforeTextNode(positionInParentBeforeNode(textNode));
150             // Clear out all whitespace and insert one non-breaking space
151             deleteInsignificantTextDownstream(endingPosition);
152             ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
153             // Deleting insignificant whitespace will remove textNode if it contains nothing but insignificant whitespace.
154             if (textNode->inDocument())
155                 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
156             else {
157                 RefPtr<Text> nbspNode = document()->createTextNode(nonBreakingSpaceString());
158                 insertNodeAt(nbspNode.get(), positionBeforeTextNode);
159                 endingPosition = Position(nbspNode.get(), 0);
160             }
161         }
162         
163         setEndingSelection(VisibleSelection(endingPosition, DOWNSTREAM));
164     }
165
166     // Handle the case where there is a typing style.
167
168     RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle();
169
170     if (typingStyle && !typingStyle->isEmpty()) {
171         // Apply the typing style to the inserted line break, so that if the selection
172         // leaves and then comes back, new input will have the right style.
173         // FIXME: We shouldn't always apply the typing style to the line break here,
174         // see <rdar://problem/5794462>.
175         applyStyle(typingStyle->style(), firstDeepEditingPositionForNode(nodeToInsert.get()), lastDeepEditingPositionForNode(nodeToInsert.get()));
176         // Even though this applyStyle operates on a Range, it still sets an endingSelection().
177         // It tries to set a VisibleSelection around the content it operated on. So, that VisibleSelection
178         // will either (a) select the line break we inserted, or it will (b) be a caret just 
179         // before the line break (if the line break is at the end of a block it isn't selectable).
180         // So, this next call sets the endingSelection() to a caret just after the line break 
181         // that we inserted, or just before it if it's at the end of a block.
182         setEndingSelection(endingSelection().visibleEnd());
183     }
184
185     rebalanceWhitespace();
186 }
187
188 }