Home | History | Annotate | Download | only in editing
      1 /*
      2  * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
      3  * Copyright (C) 2010 Google Inc. All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  *
     14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     15  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     16  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     17  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     18  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     20  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     25  */
     26 
     27 #include "config.h"
     28 #include "core/editing/ApplyBlockElementCommand.h"
     29 
     30 #include "HTMLNames.h"
     31 #include "bindings/v8/ExceptionState.h"
     32 #include "core/dom/NodeRenderStyle.h"
     33 #include "core/dom/Text.h"
     34 #include "core/editing/VisiblePosition.h"
     35 #include "core/editing/VisibleUnits.h"
     36 #include "core/editing/htmlediting.h"
     37 #include "core/html/HTMLElement.h"
     38 #include "core/rendering/RenderObject.h"
     39 #include "core/rendering/style/RenderStyle.h"
     40 
     41 namespace WebCore {
     42 
     43 using namespace HTMLNames;
     44 
     45 ApplyBlockElementCommand::ApplyBlockElementCommand(Document& document, const QualifiedName& tagName, const AtomicString& inlineStyle)
     46     : CompositeEditCommand(document)
     47     , m_tagName(tagName)
     48     , m_inlineStyle(inlineStyle)
     49 {
     50 }
     51 
     52 ApplyBlockElementCommand::ApplyBlockElementCommand(Document& document, const QualifiedName& tagName)
     53     : CompositeEditCommand(document)
     54     , m_tagName(tagName)
     55 {
     56 }
     57 
     58 void ApplyBlockElementCommand::doApply()
     59 {
     60     if (!endingSelection().rootEditableElement())
     61         return;
     62 
     63     VisiblePosition visibleEnd = endingSelection().visibleEnd();
     64     VisiblePosition visibleStart = endingSelection().visibleStart();
     65     if (visibleStart.isNull() || visibleStart.isOrphan() || visibleEnd.isNull() || visibleEnd.isOrphan())
     66         return;
     67 
     68     // When a selection ends at the start of a paragraph, we rarely paint
     69     // the selection gap before that paragraph, because there often is no gap.
     70     // In a case like this, it's not obvious to the user that the selection
     71     // ends "inside" that paragraph, so it would be confusing if Indent/Outdent
     72     // operated on that paragraph.
     73     // FIXME: We paint the gap before some paragraphs that are indented with left
     74     // margin/padding, but not others.  We should make the gap painting more consistent and
     75     // then use a left margin/padding rule here.
     76     if (visibleEnd != visibleStart && isStartOfParagraph(visibleEnd))
     77         setEndingSelection(VisibleSelection(visibleStart, visibleEnd.previous(CannotCrossEditingBoundary), endingSelection().isDirectional()));
     78 
     79     VisibleSelection selection = selectionForParagraphIteration(endingSelection());
     80     VisiblePosition startOfSelection = selection.visibleStart();
     81     VisiblePosition endOfSelection = selection.visibleEnd();
     82     ASSERT(!startOfSelection.isNull());
     83     ASSERT(!endOfSelection.isNull());
     84     RefPtr<ContainerNode> startScope;
     85     int startIndex = indexForVisiblePosition(startOfSelection, startScope);
     86     RefPtr<ContainerNode> endScope;
     87     int endIndex = indexForVisiblePosition(endOfSelection, endScope);
     88 
     89     formatSelection(startOfSelection, endOfSelection);
     90 
     91     document().updateLayoutIgnorePendingStylesheets();
     92 
     93     ASSERT(startScope == endScope);
     94     ASSERT(startIndex >= 0);
     95     ASSERT(startIndex <= endIndex);
     96     if (startScope == endScope && startIndex >= 0 && startIndex <= endIndex) {
     97         VisiblePosition start(visiblePositionForIndex(startIndex, startScope.get()));
     98         VisiblePosition end(visiblePositionForIndex(endIndex, endScope.get()));
     99         if (start.isNotNull() && end.isNotNull())
    100             setEndingSelection(VisibleSelection(start, end, endingSelection().isDirectional()));
    101     }
    102 }
    103 
    104 void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection)
    105 {
    106     // Special case empty unsplittable elements because there's nothing to split
    107     // and there's nothing to move.
    108     Position start = startOfSelection.deepEquivalent().downstream();
    109     if (isAtUnsplittableElement(start)) {
    110         RefPtr<Element> blockquote = createBlockElement();
    111         insertNodeAt(blockquote, start);
    112         RefPtr<Element> placeholder = createBreakElement(document());
    113         appendNode(placeholder, blockquote);
    114         setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional()));
    115         return;
    116     }
    117 
    118     RefPtr<Element> blockquoteForNextIndent;
    119     VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
    120     VisiblePosition endOfLastParagraph = endOfParagraph(endOfSelection);
    121     VisiblePosition endAfterSelection = endOfParagraph(endOfLastParagraph.next());
    122     m_endOfLastParagraph = endOfLastParagraph.deepEquivalent();
    123 
    124     bool atEnd = false;
    125     Position end;
    126     while (endOfCurrentParagraph != endAfterSelection && !atEnd) {
    127         if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph)
    128             atEnd = true;
    129 
    130         rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end);
    131         endOfCurrentParagraph = end;
    132 
    133         Node* enclosingCell = enclosingNodeOfType(start, &isTableCell);
    134         VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end);
    135 
    136         formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent);
    137 
    138         // Don't put the next paragraph in the blockquote we just created for this paragraph unless
    139         // the next paragraph is in the same cell.
    140         if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell))
    141             blockquoteForNextIndent = 0;
    142 
    143         // indentIntoBlockquote could move more than one paragraph if the paragraph
    144         // is in a list item or a table. As a result, endAfterSelection could refer to a position
    145         // no longer in the document.
    146         if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
    147             break;
    148         // Sanity check: Make sure our moveParagraph calls didn't remove endOfNextParagraph.deepEquivalent().deprecatedNode()
    149         // If somehow, e.g. mutation event handler, we did, return to prevent crashes.
    150         if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument())
    151             return;
    152         endOfCurrentParagraph = endOfNextParagraph;
    153     }
    154 }
    155 
    156 static bool isNewLineAtPosition(const Position& position)
    157 {
    158     Node* textNode = position.containerNode();
    159     int offset = position.offsetInContainerNode();
    160     if (!textNode || !textNode->isTextNode() || offset < 0 || offset >= textNode->maxCharacterOffset())
    161         return false;
    162 
    163     TrackExceptionState exceptionState;
    164     String textAtPosition = toText(textNode)->substringData(offset, 1, exceptionState);
    165     if (exceptionState.hadException())
    166         return false;
    167 
    168     return textAtPosition[0] == '\n';
    169 }
    170 
    171 static RenderStyle* renderStyleOfEnclosingTextNode(const Position& position)
    172 {
    173     if (position.anchorType() != Position::PositionIsOffsetInAnchor || !position.containerNode() || !position.containerNode()->isTextNode())
    174         return 0;
    175     return position.containerNode()->renderStyle();
    176 }
    177 
    178 void ApplyBlockElementCommand::rangeForParagraphSplittingTextNodesIfNeeded(const VisiblePosition& endOfCurrentParagraph, Position& start, Position& end)
    179 {
    180     start = startOfParagraph(endOfCurrentParagraph).deepEquivalent();
    181     end = endOfCurrentParagraph.deepEquivalent();
    182 
    183     document().updateStyleIfNeeded();
    184 
    185     bool isStartAndEndOnSameNode = false;
    186     if (RenderStyle* startStyle = renderStyleOfEnclosingTextNode(start)) {
    187         isStartAndEndOnSameNode = renderStyleOfEnclosingTextNode(end) && start.containerNode() == end.containerNode();
    188         bool isStartAndEndOfLastParagraphOnSameNode = renderStyleOfEnclosingTextNode(m_endOfLastParagraph) && start.containerNode() == m_endOfLastParagraph.containerNode();
    189 
    190         // Avoid obtanining the start of next paragraph for start
    191         if (startStyle->preserveNewline() && isNewLineAtPosition(start) && !isNewLineAtPosition(start.previous()) && start.offsetInContainerNode() > 0)
    192             start = startOfParagraph(end.previous()).deepEquivalent();
    193 
    194         // If start is in the middle of a text node, split.
    195         if (!startStyle->collapseWhiteSpace() && start.offsetInContainerNode() > 0) {
    196             int startOffset = start.offsetInContainerNode();
    197             Text* startText = start.containerText();
    198             splitTextNode(startText, startOffset);
    199             start = firstPositionInNode(startText);
    200             if (isStartAndEndOnSameNode) {
    201                 ASSERT(end.offsetInContainerNode() >= startOffset);
    202                 end = Position(startText, end.offsetInContainerNode() - startOffset);
    203             }
    204             if (isStartAndEndOfLastParagraphOnSameNode) {
    205                 ASSERT(m_endOfLastParagraph.offsetInContainerNode() >= startOffset);
    206                 m_endOfLastParagraph = Position(startText, m_endOfLastParagraph.offsetInContainerNode() - startOffset);
    207             }
    208         }
    209     }
    210 
    211     document().updateStyleIfNeeded();
    212 
    213     if (RenderStyle* endStyle = renderStyleOfEnclosingTextNode(end)) {
    214         bool isEndAndEndOfLastParagraphOnSameNode = renderStyleOfEnclosingTextNode(m_endOfLastParagraph) && end.deprecatedNode() == m_endOfLastParagraph.deprecatedNode();
    215         // Include \n at the end of line if we're at an empty paragraph
    216         if (endStyle->preserveNewline() && start == end && end.offsetInContainerNode() < end.containerNode()->maxCharacterOffset()) {
    217             int endOffset = end.offsetInContainerNode();
    218             if (!isNewLineAtPosition(end.previous()) && isNewLineAtPosition(end))
    219                 end = Position(end.containerText(), endOffset + 1);
    220             if (isEndAndEndOfLastParagraphOnSameNode && end.offsetInContainerNode() >= m_endOfLastParagraph.offsetInContainerNode())
    221                 m_endOfLastParagraph = end;
    222         }
    223 
    224         // If end is in the middle of a text node, split.
    225         if (!endStyle->collapseWhiteSpace() && end.offsetInContainerNode() && end.offsetInContainerNode() < end.containerNode()->maxCharacterOffset()) {
    226             RefPtr<Text> endContainer = end.containerText();
    227             splitTextNode(endContainer, end.offsetInContainerNode());
    228             if (isStartAndEndOnSameNode)
    229                 start = firstPositionInOrBeforeNode(endContainer->previousSibling());
    230             if (isEndAndEndOfLastParagraphOnSameNode) {
    231                 if (m_endOfLastParagraph.offsetInContainerNode() == end.offsetInContainerNode())
    232                     m_endOfLastParagraph = lastPositionInOrAfterNode(endContainer->previousSibling());
    233                 else
    234                     m_endOfLastParagraph = Position(endContainer, m_endOfLastParagraph.offsetInContainerNode() - end.offsetInContainerNode());
    235             }
    236             end = lastPositionInNode(endContainer->previousSibling());
    237         }
    238     }
    239 }
    240 
    241 VisiblePosition ApplyBlockElementCommand::endOfNextParagrahSplittingTextNodesIfNeeded(VisiblePosition& endOfCurrentParagraph, Position& start, Position& end)
    242 {
    243     VisiblePosition endOfNextParagraph = endOfParagraph(endOfCurrentParagraph.next());
    244     Position position = endOfNextParagraph.deepEquivalent();
    245     RenderStyle* style = renderStyleOfEnclosingTextNode(position);
    246     if (!style)
    247         return endOfNextParagraph;
    248 
    249     RefPtr<Text> text = position.containerText();
    250     if (!style->preserveNewline() || !position.offsetInContainerNode() || !isNewLineAtPosition(firstPositionInNode(text.get())))
    251         return endOfNextParagraph;
    252 
    253     // \n at the beginning of the text node immediately following the current paragraph is trimmed by moveParagraphWithClones.
    254     // If endOfNextParagraph was pointing at this same text node, endOfNextParagraph will be shifted by one paragraph.
    255     // Avoid this by splitting "\n"
    256     splitTextNode(text, 1);
    257 
    258     if (text == start.containerNode() && text->previousSibling() && text->previousSibling()->isTextNode()) {
    259         ASSERT(start.offsetInContainerNode() < position.offsetInContainerNode());
    260         start = Position(toText(text->previousSibling()), start.offsetInContainerNode());
    261     }
    262     if (text == end.containerNode() && text->previousSibling() && text->previousSibling()->isTextNode()) {
    263         ASSERT(end.offsetInContainerNode() < position.offsetInContainerNode());
    264         end = Position(toText(text->previousSibling()), end.offsetInContainerNode());
    265     }
    266     if (text == m_endOfLastParagraph.containerNode()) {
    267         if (m_endOfLastParagraph.offsetInContainerNode() < position.offsetInContainerNode()) {
    268             // We can only fix endOfLastParagraph if the previous node was still text and hasn't been modified by script.
    269             if (text->previousSibling()->isTextNode()
    270                 && static_cast<unsigned>(m_endOfLastParagraph.offsetInContainerNode()) <= toText(text->previousSibling())->length())
    271                 m_endOfLastParagraph = Position(toText(text->previousSibling()), m_endOfLastParagraph.offsetInContainerNode());
    272         } else
    273             m_endOfLastParagraph = Position(text.get(), m_endOfLastParagraph.offsetInContainerNode() - 1);
    274     }
    275 
    276     return Position(text.get(), position.offsetInContainerNode() - 1);
    277 }
    278 
    279 PassRefPtr<Element> ApplyBlockElementCommand::createBlockElement() const
    280 {
    281     RefPtr<Element> element = createHTMLElement(document(), m_tagName);
    282     if (m_inlineStyle.length())
    283         element->setAttribute(styleAttr, m_inlineStyle);
    284     return element.release();
    285 }
    286 
    287 }
    288