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