2010-10-01 Ryosuke Niwa <rniwa@webkit.org>
[WebKit-https.git] / WebCore / editing / IndentOutdentCommand.cpp
1 /*
2  * Copyright (C) 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 (IndentOutdentCommandINCLUDING, 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 "IndentOutdentCommand.h"
28
29 #include "Document.h"
30 #include "Element.h"
31 #include "HTMLBlockquoteElement.h"
32 #include "HTMLNames.h"
33 #include "InsertLineBreakCommand.h"
34 #include "InsertListCommand.h"
35 #include "Range.h"
36 #include "SplitElementCommand.h"
37 #include "Text.h"
38 #include "TextIterator.h"
39 #include "htmlediting.h"
40 #include "visible_units.h"
41 #include <wtf/StdLibExtras.h>
42
43 namespace WebCore {
44
45 using namespace HTMLNames;
46
47 static bool isListOrIndentBlockquote(const Node* node)
48 {
49     return node && (node->hasTagName(ulTag) || node->hasTagName(olTag) || node->hasTagName(blockquoteTag));
50 }
51
52 IndentOutdentCommand::IndentOutdentCommand(Document* document, EIndentType typeOfAction, int marginInPixels)
53     : ApplyBlockElementCommand(document, blockquoteTag, "webkit-indent-blockquote", "margin: 0 0 0 40px; border: none; padding: 0px;")
54     , m_typeOfAction(typeOfAction)
55     , m_marginInPixels(marginInPixels)
56 {
57 }
58
59 bool IndentOutdentCommand::tryIndentingAsListItem(const VisiblePosition& endOfCurrentParagraph)
60 {
61     // If our selection is not inside a list, bail out.
62     Node* lastNodeInSelectedParagraph = endOfCurrentParagraph.deepEquivalent().node();
63     RefPtr<Element> listNode = enclosingList(lastNodeInSelectedParagraph);
64     if (!listNode)
65         return false;
66
67     // Find the block that we want to indent.  If it's not a list item (e.g., a div inside a list item), we bail out.
68     Element* selectedListItem = static_cast<Element*>(enclosingBlock(lastNodeInSelectedParagraph));
69
70     // FIXME: we need to deal with the case where there is no li (malformed HTML)
71     if (!selectedListItem->hasTagName(liTag))
72         return false;
73     
74     // FIXME: previousElementSibling does not ignore non-rendered content like <span></span>.  Should we?
75     Element* previousList = selectedListItem->previousElementSibling();
76     Element* nextList = selectedListItem->nextElementSibling();
77
78     RefPtr<Element> newList = document()->createElement(listNode->tagQName(), false);
79     insertNodeBefore(newList, selectedListItem);
80
81     moveParagraphWithClones(startOfParagraph(endOfCurrentParagraph), endOfCurrentParagraph, newList.get(), selectedListItem);
82
83     if (canMergeLists(previousList, newList.get()))
84         mergeIdenticalElements(previousList, newList);
85     if (canMergeLists(newList.get(), nextList))
86         mergeIdenticalElements(newList, nextList);
87
88     return true;
89 }
90     
91 void IndentOutdentCommand::indentIntoBlockquote(const VisiblePosition& endOfCurrentParagraph, RefPtr<Element>& targetBlockquote)
92 {
93     Position start = startOfParagraph(endOfCurrentParagraph).deepEquivalent();
94     Node* enclosingCell = enclosingNodeOfType(start, &isTableCell);
95     Node* nodeToSplitTo;
96     if (enclosingCell)
97         nodeToSplitTo = enclosingCell;
98     else if (enclosingList(start.node()))
99         nodeToSplitTo = enclosingBlock(start.node());
100     else
101         nodeToSplitTo = editableRootForPosition(start);
102
103     RefPtr<Node> outerBlock = (start.node() == nodeToSplitTo) ? start.node() : splitTreeToNode(start.node(), nodeToSplitTo);
104
105     if (!targetBlockquote) {
106         // Create a new blockquote and insert it as a child of the root editable element. We accomplish
107         // this by splitting all parents of the current paragraph up to that point.
108         targetBlockquote = createBlockElement();
109         insertNodeBefore(targetBlockquote, outerBlock);
110     }
111
112     moveParagraphWithClones(startOfParagraph(endOfCurrentParagraph), endOfCurrentParagraph, targetBlockquote.get(), outerBlock.get());
113 }
114
115 void IndentOutdentCommand::outdentParagraph()
116 {
117     VisiblePosition visibleStartOfParagraph = startOfParagraph(endingSelection().visibleStart());
118     VisiblePosition visibleEndOfParagraph = endOfParagraph(visibleStartOfParagraph);
119
120     Node* enclosingNode = enclosingNodeOfType(visibleStartOfParagraph.deepEquivalent(), &isListOrIndentBlockquote);
121     if (!enclosingNode || !enclosingNode->parentNode()->isContentEditable())  // We can't outdent if there is no place to go!
122         return;
123
124     // Use InsertListCommand to remove the selection from the list
125     if (enclosingNode->hasTagName(olTag)) {
126         applyCommandToComposite(InsertListCommand::create(document(), InsertListCommand::OrderedList));
127         return;        
128     }
129     if (enclosingNode->hasTagName(ulTag)) {
130         applyCommandToComposite(InsertListCommand::create(document(), InsertListCommand::UnorderedList));
131         return;
132     }
133     
134     // The selection is inside a blockquote i.e. enclosingNode is a blockquote
135     VisiblePosition positionInEnclosingBlock = VisiblePosition(Position(enclosingNode, 0));
136     VisiblePosition startOfEnclosingBlock = startOfBlock(positionInEnclosingBlock);
137     VisiblePosition lastPositionInEnclosingBlock = VisiblePosition(Position(enclosingNode, enclosingNode->childNodeCount()));
138     VisiblePosition endOfEnclosingBlock = endOfBlock(lastPositionInEnclosingBlock);
139     if (visibleStartOfParagraph == startOfEnclosingBlock &&
140         visibleEndOfParagraph == endOfEnclosingBlock) {
141         // The blockquote doesn't contain anything outside the paragraph, so it can be totally removed.
142         Node* splitPoint = enclosingNode->nextSibling();
143         removeNodePreservingChildren(enclosingNode);
144         // outdentRegion() assumes it is operating on the first paragraph of an enclosing blockquote, but if there are multiply nested blockquotes and we've
145         // just removed one, then this assumption isn't true. By splitting the next containing blockquote after this node, we keep this assumption true
146         if (splitPoint) {
147             if (Node* splitPointParent = splitPoint->parentNode()) {
148                 if (splitPointParent->hasTagName(blockquoteTag)
149                     && !splitPoint->hasTagName(blockquoteTag)
150                     && splitPointParent->parentNode()->isContentEditable()) // We can't outdent if there is no place to go!
151                     splitElement(static_cast<Element*>(splitPointParent), splitPoint);
152             }
153         }
154         
155         updateLayout();
156         visibleStartOfParagraph = VisiblePosition(visibleStartOfParagraph.deepEquivalent());
157         visibleEndOfParagraph = VisiblePosition(visibleEndOfParagraph.deepEquivalent());
158         if (visibleStartOfParagraph.isNotNull() && !isStartOfParagraph(visibleStartOfParagraph))
159             insertNodeAt(createBreakElement(document()), visibleStartOfParagraph.deepEquivalent());
160         if (visibleEndOfParagraph.isNotNull() && !isEndOfParagraph(visibleEndOfParagraph))
161             insertNodeAt(createBreakElement(document()), visibleEndOfParagraph.deepEquivalent());
162
163         return;
164     }
165     Node* enclosingBlockFlow = enclosingBlock(visibleStartOfParagraph.deepEquivalent().node());
166     RefPtr<Node> splitBlockquoteNode = enclosingNode;
167     if (enclosingBlockFlow != enclosingNode)
168         splitBlockquoteNode = splitTreeToNode(enclosingBlockFlow, enclosingNode, true);
169     else {
170         // We split the blockquote at where we start outdenting.
171         splitElement(static_cast<Element*>(enclosingNode), visibleStartOfParagraph.deepEquivalent().node());
172     }
173     RefPtr<Node> placeholder = createBreakElement(document());
174     insertNodeBefore(placeholder, splitBlockquoteNode);
175     moveParagraph(startOfParagraph(visibleStartOfParagraph), endOfParagraph(visibleEndOfParagraph), VisiblePosition(Position(placeholder.get(), 0)), true);
176 }
177
178 // FIXME: We should merge this function with ApplyBlockElementCommand::formatSelection
179 void IndentOutdentCommand::outdentRegion(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection)
180 {
181     VisiblePosition endOfLastParagraph = endOfParagraph(endOfSelection);
182
183     if (endOfParagraph(startOfSelection) == endOfLastParagraph) {
184         outdentParagraph();
185         return;
186     }
187     
188     Position originalSelectionEnd = endingSelection().end();
189     VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
190     VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next());
191
192     while (endOfCurrentParagraph != endAfterSelection) {
193         VisiblePosition endOfNextParagraph = endOfParagraph(endOfCurrentParagraph.next());
194         if (endOfCurrentParagraph == endOfLastParagraph)
195             setEndingSelection(VisibleSelection(originalSelectionEnd, DOWNSTREAM));
196         else
197             setEndingSelection(endOfCurrentParagraph);
198         
199         outdentParagraph();
200         
201         // outdentParagraph could move more than one paragraph if the paragraph
202         // is in a list item. As a result, endAfterSelection and endOfNextParagraph
203         // could refer to positions no longer in the document.
204         if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().node()->inDocument())
205             break;
206             
207         if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().node()->inDocument()) {
208             endOfCurrentParagraph = endingSelection().end();
209             endOfNextParagraph = endOfParagraph(endOfCurrentParagraph.next());
210         }
211         endOfCurrentParagraph = endOfNextParagraph;
212     }
213 }
214
215 void IndentOutdentCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection)
216 {
217     if (m_typeOfAction == Indent)
218         ApplyBlockElementCommand::formatSelection(startOfSelection, endOfSelection);
219     else
220         outdentRegion(startOfSelection, endOfSelection);
221 }
222
223 void IndentOutdentCommand::formatParagraph(const VisiblePosition& endOfCurrentParagraph, RefPtr<Element>& blockquoteForNextIndent)
224 {
225     if (tryIndentingAsListItem(endOfCurrentParagraph))
226         blockquoteForNextIndent = 0;
227     else
228         indentIntoBlockquote(endOfCurrentParagraph, blockquoteForNextIndent);
229 }
230
231 }