delete_selection_command.cpp 31.6 KB
Newer Older
mjs's avatar
mjs committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright (C) 2005 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

mjs's avatar
mjs committed
26
#include "config.h"
mjs's avatar
mjs committed
27 28 29 30 31
#include "delete_selection_command.h"

#include "css/css_computedstyle.h"
#include "htmlediting.h"
#include "khtml_part.h"
32
#include "htmlnames.h"
mjs's avatar
mjs committed
33 34 35 36 37 38 39 40 41
#include "rendering/render_line.h"
#include "rendering/render_object.h"
#include "visible_text.h"
#include "visible_units.h"
#include "xml/dom2_rangeimpl.h"
#include "xml/dom_position.h"
#include "xml/dom_textimpl.h"


mjs's avatar
mjs committed
42
#include <kxmlcore/Assertions.h>
mjs's avatar
mjs committed
43 44
#include "KWQLogging.h"

darin's avatar
darin committed
45 46
using namespace DOM::HTMLNames;

mjs's avatar
mjs committed
47
using DOM::CSSComputedStyleDeclarationImpl;
justing's avatar
justing committed
48
using DOM::CSSMutableStyleDeclarationImpl;
mjs's avatar
mjs committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
using DOM::DOMString;
using DOM::DocumentImpl;
using DOM::NodeImpl;
using DOM::Position;
using DOM::RangeImpl;
using DOM::TextImpl;

namespace khtml {

static bool isListStructureNode(const NodeImpl *node)
{
    // FIXME: Irritating that we can get away with just going at the render tree for isTableStructureNode,
    // but here we also have to peek at the type of DOM node?
    RenderObject *r = node->renderer();
    return (r && r->isListItem())
64 65 66 67 68 69
        || node->hasTagName(olTag)
        || node->hasTagName(ulTag)
        || node->hasTagName(ddTag)
        || node->hasTagName(dtTag)
        || node->hasTagName(dirTag)
        || node->hasTagName(menuTag);
mjs's avatar
mjs committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
}

static int maxDeepOffset(NodeImpl *n)
{
    if (n->isAtomicNode())
        return n->caretMaxOffset();

    if (n->isElementNode())
        return n->childNodeCount();

    return 1;
}

static void debugPosition(const char *prefix, const Position &pos)
{
    if (!prefix)
        prefix = "";
    if (pos.isNull())
        LOG(Editing, "%s <null>", prefix);
    else
darin's avatar
darin committed
90
        LOG(Editing, "%s%s %p : %d", prefix, pos.node()->nodeName().qstring().latin1(), pos.node(), pos.offset());
mjs's avatar
mjs committed
91 92 93 94 95 96 97 98 99
}

static void debugNode(const char *prefix, const NodeImpl *node)
{
    if (!prefix)
        prefix = "";
    if (!node)
        LOG(Editing, "%s <null>", prefix);
    else
darin's avatar
darin committed
100
        LOG(Editing, "%s%s %p", prefix, node->nodeName().qstring().latin1(), node);
mjs's avatar
mjs committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
}

static Position positionBeforePossibleContainingSpecialElement(const Position &pos)
{
    if (isFirstVisiblePositionInSpecialElement(pos)) {
        return positionBeforeContainingSpecialElement(pos);
    } 

    return pos;
}

static Position positionAfterPossibleContainingSpecialElement(const Position &pos)
{
    if (isLastVisiblePositionInSpecialElement(pos)) {
        return positionAfterContainingSpecialElement(pos);
    }

    return pos;
}

DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, bool smartDelete, bool mergeBlocksAfterDelete)
    : CompositeEditCommand(document), 
      m_hasSelectionToDelete(false), 
      m_smartDelete(smartDelete), 
      m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
      m_startBlock(0),
      m_endBlock(0),
      m_startNode(0),
justing's avatar
justing committed
129 130
      m_typingStyle(0),
      m_deleteIntoBlockquoteStyle(0)
mjs's avatar
mjs committed
131 132 133
{
}

darin's avatar
darin committed
134
DeleteSelectionCommand::DeleteSelectionCommand(DocumentImpl *document, const SelectionController &selection, bool smartDelete, bool mergeBlocksAfterDelete)
mjs's avatar
mjs committed
135 136 137 138 139 140 141 142
    : CompositeEditCommand(document), 
      m_hasSelectionToDelete(true), 
      m_smartDelete(smartDelete), 
      m_mergeBlocksAfterDelete(mergeBlocksAfterDelete),
      m_selectionToDelete(selection),
      m_startBlock(0),
      m_endBlock(0),
      m_startNode(0),
justing's avatar
justing committed
143 144
      m_typingStyle(0),
      m_deleteIntoBlockquoteStyle(0)
mjs's avatar
mjs committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
{
}

void DeleteSelectionCommand::initializePositionData()
{
    //
    // Handle setting some basic positions
    //
    Position start = m_selectionToDelete.start();
    start = positionOutsideContainingSpecialElement(start);
    Position end = m_selectionToDelete.end();
    end = positionOutsideContainingSpecialElement(end);

    m_upstreamStart = positionBeforePossibleContainingSpecialElement(start.upstream());
    m_downstreamStart = positionBeforePossibleContainingSpecialElement(start.downstream());
    m_upstreamEnd = positionAfterPossibleContainingSpecialElement(end.upstream());
    m_downstreamEnd = positionAfterPossibleContainingSpecialElement(end.downstream());

    //
    // Handle leading and trailing whitespace, as well as smart delete adjustments to the selection
    //
    m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.startAffinity());
    m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);

    if (m_smartDelete) {
    
        // skip smart delete if the selection to delete already starts or ends with whitespace
        Position pos = VisiblePosition(m_upstreamStart, m_selectionToDelete.startAffinity()).deepEquivalent();
        bool skipSmartDelete = pos.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();
        if (!skipSmartDelete)
            skipSmartDelete = m_downstreamEnd.leadingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull();

        // extend selection upstream if there is whitespace there
        bool hasLeadingWhitespaceBeforeAdjustment = m_upstreamStart.leadingWhitespacePosition(m_selectionToDelete.startAffinity(), true).isNotNull();
        if (!skipSmartDelete && hasLeadingWhitespaceBeforeAdjustment) {
            VisiblePosition visiblePos = VisiblePosition(start, m_selectionToDelete.startAffinity()).previous();
            pos = visiblePos.deepEquivalent();
            // Expand out one character upstream for smart delete and recalculate
            // positions based on this change.
            m_upstreamStart = pos.upstream();
            m_downstreamStart = pos.downstream();
            m_leadingWhitespace = m_upstreamStart.leadingWhitespacePosition(visiblePos.affinity());
        }
        
        // trailing whitespace is only considered for smart delete if there is no leading
        // whitespace, as in the case where you double-click the first word of a paragraph.
        if (!skipSmartDelete && !hasLeadingWhitespaceBeforeAdjustment && m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY, true).isNotNull()) {
            // Expand out one character downstream for smart delete and recalculate
            // positions based on this change.
            pos = VisiblePosition(end, m_selectionToDelete.endAffinity()).next().deepEquivalent();
            m_upstreamEnd = pos.upstream();
            m_downstreamEnd = pos.downstream();
            m_trailingWhitespace = m_downstreamEnd.trailingWhitespacePosition(VP_DEFAULT_AFFINITY);
        }
    }
    
    m_trailingWhitespaceValid = true;
    
    //
    // Handle setting start and end blocks and the start node.
    //
    m_startBlock = m_downstreamStart.node()->enclosingBlockFlowElement();
    m_endBlock = m_upstreamEnd.node()->enclosingBlockFlowElement();
    m_startNode = m_upstreamStart.node();

    //
    // Handle detecting if the line containing the selection end is itself fully selected.
    // This is one of the tests that determines if block merging of content needs to be done.
    //
    VisiblePosition visibleEnd(end, m_selectionToDelete.endAffinity());
harrison's avatar
harrison committed
215
    if (isEndOfParagraph(visibleEnd)) {
mjs's avatar
mjs committed
216 217 218 219 220 221 222 223 224 225 226
        Position previousLineStart = previousLinePosition(visibleEnd, 0).deepEquivalent();
        if (previousLineStart.isNull() || RangeImpl::compareBoundaryPoints(previousLineStart, m_downstreamStart) >= 0)
            m_mergeBlocksAfterDelete = false;
    }

    debugPosition("m_upstreamStart      ", m_upstreamStart);
    debugPosition("m_downstreamStart    ", m_downstreamStart);
    debugPosition("m_upstreamEnd        ", m_upstreamEnd);
    debugPosition("m_downstreamEnd      ", m_downstreamEnd);
    debugPosition("m_leadingWhitespace  ", m_leadingWhitespace);
    debugPosition("m_trailingWhitespace ", m_trailingWhitespace);
eseidel's avatar
eseidel committed
227 228 229
    debugNode(    "m_startBlock         ", m_startBlock.get());
    debugNode(    "m_endBlock           ", m_endBlock.get());    
    debugNode(    "m_startNode          ", m_startNode.get());    
mjs's avatar
mjs committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
}

void DeleteSelectionCommand::insertPlaceholderForAncestorBlockContent()
{
    // This code makes sure a line does not disappear when deleting in this case:
    // <p>foo</p>bar<p>baz</p>
    // Select "bar" and hit delete. If nothing is done, the line containing bar will disappear.
    // It needs to be held open by inserting a placeholder.
    // Also see:
    // <rdar://problem/3928305> selecting an entire line and typing over causes new inserted text at top of document
    //
    // The checks below detect the case where the selection contains content in an ancestor block 
    // surrounded by child blocks.
    //
    VisiblePosition visibleStart(m_upstreamStart, VP_DEFAULT_AFFINITY);
    VisiblePosition beforeStart = visibleStart.previous();
    NodeImpl *startBlock = enclosingBlockFlowElement(visibleStart);
    NodeImpl *beforeStartBlock = enclosingBlockFlowElement(beforeStart);
    
    if (!beforeStart.isNull() &&
        !inSameBlock(visibleStart, beforeStart) &&
        beforeStartBlock->isAncestor(startBlock) &&
        startBlock != m_upstreamStart.node()) {

        VisiblePosition visibleEnd(m_downstreamEnd, VP_DEFAULT_AFFINITY);
        VisiblePosition afterEnd = visibleEnd.next();
        
        if ((!afterEnd.isNull() && !inSameBlock(afterEnd, visibleEnd) && !inSameBlock(afterEnd, visibleStart)) ||
harrison's avatar
harrison committed
258
            (m_downstreamEnd == m_selectionToDelete.end() && isEndOfParagraph(visibleEnd) && !m_downstreamEnd.node()->hasTagName(brTag))) {
mjs's avatar
mjs committed
259 260 261 262 263 264 265 266 267 268 269 270 271
            NodeImpl *block = createDefaultParagraphElement(document());
            insertNodeBefore(block, m_upstreamStart.node());
            addBlockPlaceholderIfNeeded(block);
            m_endingPosition = Position(block, 0);
        }
    }
}

void DeleteSelectionCommand::saveTypingStyleState()
{
    // Figure out the typing style in effect before the delete is done.
    // FIXME: Improve typing style.
    // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
eseidel's avatar
eseidel committed
272
    RefPtr<CSSComputedStyleDeclarationImpl> computedStyle = positionBeforeTabSpan(m_selectionToDelete.start()).computedStyle();
mjs's avatar
mjs committed
273
    m_typingStyle = computedStyle->copyInheritableProperties();
justing's avatar
justing committed
274 275 276 277 278 279 280 281
    
    // If we're deleting into a Mail blockquote, save the style at end() instead of start()
    // We'll use this later in computeTypingStyleAfterDelete if we end up outside of a Mail blockquote
    if (nearestMailBlockquote(m_selectionToDelete.start().node())) {
        computedStyle = m_selectionToDelete.end().computedStyle();
        m_deleteIntoBlockquoteStyle = computedStyle->copyInheritableProperties();
    } else
        m_deleteIntoBlockquoteStyle = 0;
mjs's avatar
mjs committed
282 283 284 285 286
}

bool DeleteSelectionCommand::handleSpecialCaseBRDelete()
{
    // Check for special-case where the selection contains only a BR on a line by itself after another BR.
287 288
    bool upstreamStartIsBR = m_startNode->hasTagName(brTag);
    bool downstreamStartIsBR = m_downstreamStart.node()->hasTagName(brTag);
mjs's avatar
mjs committed
289 290
    bool isBROnLineByItself = upstreamStartIsBR && downstreamStartIsBR && m_downstreamStart.node() == m_upstreamEnd.node();
    if (isBROnLineByItself) {
harrison's avatar
harrison committed
291
        m_endingPosition = Position(m_downstreamStart.node()->parentNode(), m_downstreamStart.node()->nodeIndex());
mjs's avatar
mjs committed
292
        removeNode(m_downstreamStart.node());
harrison's avatar
harrison committed
293
        m_endingPosition = m_endingPosition.equivalentDeepPosition();
mjs's avatar
mjs committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        m_mergeBlocksAfterDelete = false;
        return true;
    }

    // Not a special-case delete per se, but we can detect that the merging of content between blocks
    // should not be done.
    if (upstreamStartIsBR && downstreamStartIsBR)
        m_mergeBlocksAfterDelete = false;

    return false;
}

void DeleteSelectionCommand::handleGeneralDelete()
{
    int startOffset = m_upstreamStart.offset();
    VisiblePosition visibleEnd = VisiblePosition(m_downstreamEnd, m_selectionToDelete.endAffinity());
    bool endAtEndOfBlock = isEndOfBlock(visibleEnd);

    // Handle some special cases where the selection begins and ends on specific visible units.
    // Sometimes a node that is actually selected needs to be retained in order to maintain
    // user expectations for the delete operation. Here is an example:
    //     1. Open a new Blot or Mail document
    //     2. hit Return ten times or so
    //     3. Type a letter (do not hit Return after it)
    //     4. Type shift-up-arrow to select the line containing the letter and the previous blank line
    //     5. Hit Delete
    // You expect the insertion point to wind up at the start of the line where your selection began.
    // Because of the nature of HTML, the editing code needs to perform a special check to get
    // this behavior. So:
    // If the entire start block is selected, and the selection does not extend to the end of the 
    // end of a block other than the block containing the selection start, then do not delete the 
    // start block, otherwise delete the start block.
326
    if (startOffset == 1 && m_startNode && m_startNode->hasTagName(brTag)) {
eseidel's avatar
eseidel committed
327
        m_startNode = m_startNode->traverseNextNode();
mjs's avatar
mjs committed
328 329
        startOffset = 0;
    }
harrison's avatar
harrison committed
330
    if (m_startBlock != m_endBlock && isStartOfBlock(VisiblePosition(m_upstreamStart, m_selectionToDelete.startAffinity()))) {
eseidel's avatar
eseidel committed
331
        if (!m_startBlock->isAncestor(m_endBlock.get()) && !isStartOfBlock(visibleEnd) && endAtEndOfBlock) {
mjs's avatar
mjs committed
332
            // Delete all the children of the block, but not the block itself.
eseidel's avatar
eseidel committed
333
            m_startNode = m_startBlock->firstChild();
mjs's avatar
mjs committed
334 335 336 337 338 339 340 341 342 343 344 345
            startOffset = 0;
        }
    }
    else if (startOffset >= m_startNode->caretMaxOffset() &&
             (m_startNode->isAtomicNode() || startOffset == 0)) {
        // Move the start node to the next node in the tree since the startOffset is equal to
        // or beyond the start node's caretMaxOffset This means there is nothing visible to delete. 
        // But don't do this if the node is not atomic - we don't want to move into the first child.

        // Also, before moving on, delete any insignificant text that may be present in a text node.
        if (m_startNode->isTextNode()) {
            // Delete any insignificant text from this node.
eseidel's avatar
eseidel committed
346
            TextImpl *text = static_cast<TextImpl *>(m_startNode.get());
mjs's avatar
mjs committed
347 348 349 350 351
            if (text->length() > (unsigned)m_startNode->caretMaxOffset())
                deleteTextFromNode(text, m_startNode->caretMaxOffset(), text->length() - m_startNode->caretMaxOffset());
        }
        
        // shift the start node to the next
eseidel's avatar
eseidel committed
352
        m_startNode = m_startNode->traverseNextNode();
mjs's avatar
mjs committed
353 354 355 356 357 358 359 360 361 362
        startOffset = 0;
    }

    // Done adjusting the start.  See if we're all done.
    if (!m_startNode)
        return;

    if (m_startNode == m_downstreamEnd.node()) {
        // The selection to delete is all in one node.
        if (!m_startNode->renderer() || 
eseidel's avatar
eseidel committed
363
            (startOffset == 0 && m_downstreamEnd.offset() >= maxDeepOffset(m_startNode.get()))) {
mjs's avatar
mjs committed
364
            // just delete
eseidel's avatar
eseidel committed
365
            removeFullySelectedNode(m_startNode.get());
mjs's avatar
mjs committed
366 367 368
        } else if (m_downstreamEnd.offset() - startOffset > 0) {
            if (m_startNode->isTextNode()) {
                // in a text node that needs to be trimmed
eseidel's avatar
eseidel committed
369
                TextImpl *text = static_cast<TextImpl *>(m_startNode.get());
mjs's avatar
mjs committed
370 371 372
                deleteTextFromNode(text, startOffset, m_downstreamEnd.offset() - startOffset);
                m_trailingWhitespaceValid = false;
            } else {
eseidel's avatar
eseidel committed
373
                removeChildrenInRange(m_startNode.get(), startOffset, m_downstreamEnd.offset());
mjs's avatar
mjs committed
374 375 376 377 378 379
                m_endingPosition = m_upstreamStart;
            }
        }
    }
    else {
        // The selection to delete spans more than one node.
eseidel's avatar
eseidel committed
380
        NodeImpl *node = m_startNode.get();
mjs's avatar
mjs committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        
        if (startOffset > 0) {
            if (m_startNode->isTextNode()) {
                // in a text node that needs to be trimmed
                TextImpl *text = static_cast<TextImpl *>(node);
                deleteTextFromNode(text, startOffset, text->length() - startOffset);
                node = node->traverseNextNode();
            } else {
                node = m_startNode->childNode(startOffset);
            }
        }
        
        // handle deleting all nodes that are completely selected
        while (node && node != m_downstreamEnd.node()) {
            if (RangeImpl::compareBoundaryPoints(Position(node, 0), m_downstreamEnd) >= 0) {
                // traverseNextSibling just blew past the end position, so stop deleting
                node = 0;
            } else if (!m_downstreamEnd.node()->isAncestor(node)) {
                NodeImpl *nextNode = node->traverseNextSibling();
                // if we just removed a node from the end container, update end position so the
                // check above will work
                if (node->parentNode() == m_downstreamEnd.node()) {
                    ASSERT(node->nodeIndex() < (unsigned)m_downstreamEnd.offset());
                    m_downstreamEnd = Position(m_downstreamEnd.node(), m_downstreamEnd.offset() - 1);
                }
                removeFullySelectedNode(node);
                node = nextNode;
            } else {
                NodeImpl *n = node->lastChild();
                while (n && n->lastChild())
                    n = n->lastChild();
                if (n == m_downstreamEnd.node() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMaxOffset()) {
                    removeFullySelectedNode(node);
                    m_trailingWhitespaceValid = false;
                    node = 0;
                } 
                else {
                    node = node->traverseNextNode();
                }
            }
        }

        
        if (m_downstreamEnd.node() != m_startNode && !m_upstreamStart.node()->isAncestor(m_downstreamEnd.node()) && m_downstreamEnd.node()->inDocument() && m_downstreamEnd.offset() >= m_downstreamEnd.node()->caretMinOffset()) {
            if (m_downstreamEnd.offset() >= maxDeepOffset(m_downstreamEnd.node())) {
                // need to delete whole node
                // we can get here if this is the last node in the block
                // remove an ancestor of m_downstreamEnd.node(), and thus m_downstreamEnd.node() itself
                if (!m_upstreamStart.node()->inDocument() ||
                    m_upstreamStart.node() == m_downstreamEnd.node() ||
                    m_upstreamStart.node()->isAncestor(m_downstreamEnd.node())) {
                    m_upstreamStart = Position(m_downstreamEnd.node()->parentNode(), m_downstreamEnd.node()->nodeIndex());
                }
                
                removeFullySelectedNode(m_downstreamEnd.node());
                m_trailingWhitespaceValid = false;
            } else {
                if (m_downstreamEnd.node()->isTextNode()) {
                    // in a text node that needs to be trimmed
                    TextImpl *text = static_cast<TextImpl *>(m_downstreamEnd.node());
                    if (m_downstreamEnd.offset() > 0) {
                        deleteTextFromNode(text, 0, m_downstreamEnd.offset());
                        m_downstreamEnd = Position(text, 0);
                        m_trailingWhitespaceValid = false;
                    }
                } else {
                    int offset = 0;
                    if (m_upstreamStart.node()->isAncestor(m_downstreamEnd.node())) {
                        NodeImpl *n = m_upstreamStart.node();
                        while (n && n->parentNode() != m_downstreamEnd.node())
                            n = n->parentNode();
                        if (n)
                            offset = n->nodeIndex() + 1;
                    }
                    removeChildrenInRange(m_downstreamEnd.node(), offset, m_downstreamEnd.offset());
                    m_downstreamEnd = Position(m_downstreamEnd.node(), offset);
                }
            }
        }
    }
}

// FIXME: Can't really determine this without taking white-space mode into account.
static inline bool nextCharacterIsCollapsibleWhitespace(const Position &pos)
{
    if (!pos.node())
        return false;
    if (!pos.node()->isTextNode())
        return false;
    return isCollapsibleWhitespace(static_cast<TextImpl *>(pos.node())->data()[pos.offset()]);
}

void DeleteSelectionCommand::fixupWhitespace()
{
darin's avatar
darin committed
475
    updateLayout();
mjs's avatar
mjs committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    if (m_leadingWhitespace.isNotNull() && (m_trailingWhitespace.isNotNull() || !m_leadingWhitespace.isRenderedCharacter())) {
        LOG(Editing, "replace leading");
        TextImpl *textNode = static_cast<TextImpl *>(m_leadingWhitespace.node());
        replaceTextInNode(textNode, m_leadingWhitespace.offset(), 1, nonBreakingSpaceString());
    }
    else if (m_trailingWhitespace.isNotNull()) {
        if (m_trailingWhitespaceValid) {
            if (!m_trailingWhitespace.isRenderedCharacter()) {
                LOG(Editing, "replace trailing [valid]");
                TextImpl *textNode = static_cast<TextImpl *>(m_trailingWhitespace.node());
                replaceTextInNode(textNode, m_trailingWhitespace.offset(), 1, nonBreakingSpaceString());
            }
        }
        else {
            Position pos = m_endingPosition.downstream();
            pos = Position(pos.node(), pos.offset() - 1);
            if (nextCharacterIsCollapsibleWhitespace(pos) && !pos.isRenderedCharacter()) {
                LOG(Editing, "replace trailing [invalid]");
                TextImpl *textNode = static_cast<TextImpl *>(pos.node());
                replaceTextInNode(textNode, pos.offset(), 1, nonBreakingSpaceString());
                // need to adjust ending position since the trailing position is not valid.
                m_endingPosition = pos;
            }
        }
    }
}

// This function moves nodes in the block containing startNode to dstBlock, starting
// from startNode and proceeding to the end of the paragraph. Nodes in the block containing
// startNode that appear in document order before startNode are not moved.
// This function is an important helper for deleting selections that cross paragraph
// boundaries.
void DeleteSelectionCommand::moveNodesAfterNode()
{
    if (!m_mergeBlocksAfterDelete)
        return;

    if (m_endBlock == m_startBlock)
        return;

    NodeImpl *startNode = m_downstreamEnd.node();
    NodeImpl *dstNode = m_upstreamStart.node();

    if (!startNode->inDocument() || !dstNode->inDocument())
        return;

    NodeImpl *startBlock = startNode->enclosingBlockFlowElement();
    if (isTableStructureNode(startBlock) || isListStructureNode(startBlock))
        // Do not move content between parts of a table or list.
        return;

    // Now that we are about to add content, check to see if a placeholder element
    // can be removed.
    removeBlockPlaceholder(startBlock);

    // Move the subtree containing node
    NodeImpl *node = startNode->enclosingInlineElement();

    // Insert after the subtree containing destNode
    NodeImpl *refNode = dstNode->enclosingInlineElement();

    // Nothing to do if start is already at the beginning of dstBlock
    NodeImpl *dstBlock = refNode->enclosingBlockFlowElement();
    if (startBlock == dstBlock->firstChild())
        return;

    // Do the move.
    NodeImpl *rootNode = refNode->rootEditableElement();
    while (node && node->isAncestor(startBlock)) {
        NodeImpl *moveNode = node;
        node = node->nextSibling();
        removeNode(moveNode);
548
        if (moveNode->hasTagName(brTag) && !moveNode->renderer()) {
mjs's avatar
mjs committed
549 550 551 552 553 554 555 556 557 558
            // Just remove this node, and don't put it back.
            // If the BR was not rendered (since it was at the end of a block, for instance), 
            // putting it back in the document might make it appear, and that is not desirable.
            break;
        }
        if (refNode == rootNode)
            insertNodeAt(moveNode, refNode, 0);
        else
            insertNodeAfter(moveNode, refNode);
        refNode = moveNode;
559
        if (moveNode->hasTagName(brTag))
mjs's avatar
mjs committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
            break;
    }

    // If the startBlock no longer has any kids, we may need to deal with adding a BR
    // to make the layout come out right. Consider this document:
    //
    // One
    // <div>Two</div>
    // Three
    // 
    // Placing the insertion before before the 'T' of 'Two' and hitting delete will
    // move the contents of the div to the block containing 'One' and delete the div.
    // This will have the side effect of moving 'Three' on to the same line as 'One'
    // and 'Two'. This is undesirable. We fix this up by adding a BR before the 'Three'.
    // This may not be ideal, but it is better than nothing.
darin's avatar
darin committed
575
    updateLayout();
mjs's avatar
mjs committed
576 577
    if (!startBlock->renderer() || !startBlock->renderer()->firstChild()) {
        removeNode(startBlock);
darin's avatar
darin committed
578
        updateLayout();
mjs's avatar
mjs committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        if (refNode->renderer() && refNode->renderer()->inlineBox() && refNode->renderer()->inlineBox()->nextOnLineExists()) {
            insertNodeAfter(createBreakElement(document()), refNode);
        }
    }
}

void DeleteSelectionCommand::calculateEndingPosition()
{
    if (m_endingPosition.isNotNull() && m_endingPosition.node()->inDocument())
        return;

    m_endingPosition = m_upstreamStart;
    if (m_endingPosition.node()->inDocument())
        return;
    
    m_endingPosition = m_downstreamEnd;
    if (m_endingPosition.node()->inDocument())
        return;

eseidel's avatar
eseidel committed
598
    m_endingPosition = Position(m_startBlock.get(), 0);
mjs's avatar
mjs committed
599 600 601
    if (m_endingPosition.node()->inDocument())
        return;

eseidel's avatar
eseidel committed
602
    m_endingPosition = Position(m_endBlock.get(), 0);
mjs's avatar
mjs committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    if (m_endingPosition.node()->inDocument())
        return;

    m_endingPosition = Position(document()->documentElement(), 0);
}

void DeleteSelectionCommand::calculateTypingStyleAfterDelete(NodeImpl *insertedPlaceholder)
{
    // Compute the difference between the style before the delete and the style now
    // after the delete has been done. Set this style on the part, so other editing
    // commands being composed with this one will work, and also cache it on the command,
    // so the KHTMLPart::appliedEditing can set it after the whole composite command 
    // has completed.
    // FIXME: Improve typing style.
    // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
justing's avatar
justing committed
618
    
eseidel's avatar
eseidel committed
619 620 621 622
    // If we deleted into a blockquote, but are now no longer in a blockquote, use the alternate typing style
    if (m_deleteIntoBlockquoteStyle && !nearestMailBlockquote(m_endingPosition.node()))
        m_typingStyle = m_deleteIntoBlockquoteStyle;
    m_deleteIntoBlockquoteStyle = 0;
justing's avatar
justing committed
623
    
eseidel's avatar
eseidel committed
624 625 626
    RefPtr<CSSComputedStyleDeclarationImpl> endingStyle = new CSSComputedStyleDeclarationImpl(m_endingPosition.node());
    endingStyle->diff(m_typingStyle.get());
    if (!m_typingStyle->length())
mjs's avatar
mjs committed
627 628 629 630 631 632 633 634
        m_typingStyle = 0;
    if (insertedPlaceholder && m_typingStyle) {
        // Apply style to the placeholder. This makes sure that the single line in the
        // paragraph has the right height, and that the paragraph takes on the style
        // of the preceding line and retains it even if you click away, click back, and
        // then start typing. In this case, the typing style is applied right now, and
        // is not retained until the next typing action.

justing's avatar
justing committed
635
        setEndingSelection(SelectionController(Position(insertedPlaceholder, 0), DOWNSTREAM));
eseidel's avatar
eseidel committed
636
        applyStyle(m_typingStyle.get(), EditActionUnspecified);
mjs's avatar
mjs committed
637 638 639 640
        m_typingStyle = 0;
    }
    // Set m_typingStyle as the typing style.
    // It's perfectly OK for m_typingStyle to be null.
eseidel's avatar
eseidel committed
641 642
    document()->part()->setTypingStyle(m_typingStyle.get());
    setTypingStyle(m_typingStyle.get());
mjs's avatar
mjs committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
}

void DeleteSelectionCommand::clearTransientState()
{
    m_selectionToDelete.clear();
    m_upstreamStart.clear();
    m_downstreamStart.clear();
    m_upstreamEnd.clear();
    m_downstreamEnd.clear();
    m_endingPosition.clear();
    m_leadingWhitespace.clear();
    m_trailingWhitespace.clear();
}

void DeleteSelectionCommand::doApply()
{
    // If selection has not been set to a custom selection when the command was created,
    // use the current ending selection.
    if (!m_hasSelectionToDelete)
        m_selectionToDelete = endingSelection();
        
    if (!m_selectionToDelete.isRange())
        return;

    // save this to later make the selection with
    EAffinity affinity = m_selectionToDelete.startAffinity();
    
    // set up our state
    initializePositionData();
    if (!m_startBlock || !m_endBlock) {
        // Can't figure out what blocks we're in. This can happen if
        // the document structure is not what we are expecting, like if
        // the document has no body element, or if the editable block
        // has been changed to display: inline. Some day it might
        // be nice to be able to deal with this, but for now, bail.
        clearTransientState();
        return;
    }
harrison's avatar
harrison committed
681 682 683 684 685 686 687 688 689 690

    // if all we are deleting is complete paragraph(s), we need to make
    // sure a blank paragraph remains when we are done
    bool forceBlankParagraph = isStartOfParagraph(VisiblePosition(m_upstreamStart, VP_DEFAULT_AFFINITY)) &&
                               isEndOfParagraph(VisiblePosition(m_downstreamEnd, VP_DEFAULT_AFFINITY));

    // Delete any text that may hinder our ability to fixup whitespace after the detele
    deleteInsignificantTextDownstream(m_trailingWhitespace);    

    saveTypingStyleState();
mjs's avatar
mjs committed
691
    
harrison's avatar
harrison committed
692 693 694 695 696
    // deleting just a BR is handled specially, at least because we do not
    // want to replace it with a placeholder BR!
    if (handleSpecialCaseBRDelete()) {
        calculateTypingStyleAfterDelete(false);
        debugPosition("endingPosition   ", m_endingPosition);
darin's avatar
darin committed
697
        setEndingSelection(SelectionController(m_endingPosition, affinity));
harrison's avatar
harrison committed
698 699 700 701
        clearTransientState();
        rebalanceWhitespace();
        return;
    }
mjs's avatar
mjs committed
702
    
harrison's avatar
harrison committed
703 704
    insertPlaceholderForAncestorBlockContent();
    handleGeneralDelete();
mjs's avatar
mjs committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    
    // Do block merge if start and end of selection are in different blocks.
    moveNodesAfterNode();
    
    calculateEndingPosition();
    fixupWhitespace();

    // if the m_endingPosition is already a blank paragraph, there is
    // no need to force a new one
    if (forceBlankParagraph &&
        isStartOfParagraph(VisiblePosition(m_endingPosition, VP_DEFAULT_AFFINITY)) &&
        isEndOfParagraph(VisiblePosition(m_endingPosition, VP_DEFAULT_AFFINITY))) {
        forceBlankParagraph = false;
    }
    
    NodeImpl *addedPlaceholder = forceBlankParagraph ? insertBlockPlaceholder(m_endingPosition) :
        addBlockPlaceholderIfNeeded(m_endingPosition.node());

    calculateTypingStyleAfterDelete(addedPlaceholder);
harrison's avatar
harrison committed
724

mjs's avatar
mjs committed
725
    debugPosition("endingPosition   ", m_endingPosition);
darin's avatar
darin committed
726
    setEndingSelection(SelectionController(m_endingPosition, affinity));
mjs's avatar
mjs committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    clearTransientState();
    rebalanceWhitespace();
}

EditAction DeleteSelectionCommand::editingAction() const
{
    // Note that DeleteSelectionCommand is also used when the user presses the Delete key,
    // but in that case there's a TypingCommand that supplies the editingAction(), so
    // the Undo menu correctly shows "Undo Typing"
    return EditActionCut;
}

bool DeleteSelectionCommand::preservesTypingStyle() const
{
    return true;
}

} // namespace khtml