void SVGPointList::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, RawPtr<SVGPropertyBase> fromValue, RawPtr<SVGPropertyBase> toValue, RawPtr<SVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
{
    RawPtr<SVGPointList> fromList = toSVGPointList(fromValue);
    RawPtr<SVGPointList> toList = toSVGPointList(toValue);
    RawPtr<SVGPointList> toAtEndOfDurationList = toSVGPointList(toAtEndOfDurationValue);

    size_t fromPointListSize = fromList->length();
    size_t toPointListSize = toList->length();
    size_t toAtEndOfDurationListSize = toAtEndOfDurationList->length();

    if (!adjustFromToListValues(fromList, toList, percentage, animationElement->getAnimationMode()))
        return;

    for (size_t i = 0; i < toPointListSize; ++i) {
        float animatedX = at(i)->x();
        float animatedY = at(i)->y();

        FloatPoint effectiveFrom;
        if (fromPointListSize)
            effectiveFrom = fromList->at(i)->value();
        FloatPoint effectiveTo = toList->at(i)->value();
        FloatPoint effectiveToAtEnd;
        if (i < toAtEndOfDurationListSize)
            effectiveToAtEnd = toAtEndOfDurationList->at(i)->value();

        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.x(), effectiveTo.x(), effectiveToAtEnd.x(), animatedX);
        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.y(), effectiveTo.y(), effectiveToAtEnd.y(), animatedY);
        at(i)->setValue(FloatPoint(animatedX, animatedY));
    }
}
void SVGPointList::add(RawPtr<SVGPropertyBase> other, SVGElement* contextElement)
{
    RawPtr<SVGPointList> otherList = toSVGPointList(other);

    if (length() != otherList->length())
        return;

    for (size_t i = 0; i < length(); ++i)
        at(i)->setValue(at(i)->value() + otherList->at(i)->value());
}
RawPtr<Node> Text::mergeNextSiblingNodesIfPossible()
{
    RawPtr<Node> protect(this);

    // Remove empty text nodes.
    if (!length()) {
        // Care must be taken to get the next node before removing the current node.
        RawPtr<Node> nextNode(NodeTraversal::nextPostOrder(*this));
        remove(IGNORE_EXCEPTION);
        return nextNode.release();
    }

    // Merge text nodes.
    while (Node* nextSibling = this->nextSibling()) {
        if (nextSibling->getNodeType() != TEXT_NODE)
            break;

        RawPtr<Text> nextText = toText(nextSibling);

        // Remove empty text nodes.
        if (!nextText->length()) {
            nextText->remove(IGNORE_EXCEPTION);
            continue;
        }

        // Both non-empty text nodes. Merge them.
        unsigned offset = length();
        String nextTextData = nextText->data();
        String oldTextData = data();
        setDataWithoutUpdate(data() + nextTextData);
        updateTextLayoutObject(oldTextData.length(), 0);

        // Empty nextText for layout update.
        nextText->setDataWithoutUpdate(emptyString());
        nextText->updateTextLayoutObject(0, nextTextData.length());

        document().didMergeTextNodes(*nextText, offset);

        // Restore nextText for mutation event.
        nextText->setDataWithoutUpdate(nextTextData);
        nextText->updateTextLayoutObject(0, 0);

        document().incDOMTreeVersion();
        didModifyData(oldTextData, CharacterData::UpdateFromNonParser);
        nextText->remove(IGNORE_EXCEPTION);
    }

    return NodeTraversal::nextPostOrder(*this);
}
void InsertParagraphSeparatorCommand::doApply(EditingState* editingState)
{
    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    Position insertionPosition = endingSelection().start();

    TextAffinity affinity = endingSelection().affinity();

    // Delete the current selection.
    if (endingSelection().isRange()) {
        calculateStyleBeforeInsertion(insertionPosition);
        deleteSelection(editingState, false, true);
        if (editingState->isAborted())
            return;
        insertionPosition = endingSelection().start();
        affinity = endingSelection().affinity();
    }

    // FIXME: The parentAnchoredEquivalent conversion needs to be moved into enclosingBlock.
    RawPtr<Element> startBlock = enclosingBlock(insertionPosition.parentAnchoredEquivalent().computeContainerNode());
    Node* listChildNode = enclosingListChild(insertionPosition.parentAnchoredEquivalent().computeContainerNode());
    RawPtr<HTMLElement> listChild = listChildNode && listChildNode->isHTMLElement() ? toHTMLElement(listChildNode) : 0;
    Position canonicalPos = createVisiblePosition(insertionPosition).deepEquivalent();
    if (!startBlock
        || !startBlock->nonShadowBoundaryParentNode()
        || isTableCell(startBlock.get())
        || isHTMLFormElement(*startBlock)
        // FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
        || (!canonicalPos.isNull() && isDisplayInsideTable(canonicalPos.anchorNode()))
        || (!canonicalPos.isNull() && isHTMLHRElement(*canonicalPos.anchorNode()))) {
        applyCommandToComposite(InsertLineBreakCommand::create(document()), editingState);
        return;
    }

    // Use the leftmost candidate.
    insertionPosition = mostBackwardCaretPosition(insertionPosition);
    if (!isVisuallyEquivalentCandidate(insertionPosition))
        insertionPosition = mostForwardCaretPosition(insertionPosition);

    // Adjust the insertion position after the delete
    const Position originalInsertionPosition = insertionPosition;
    const Element* enclosingAnchor = enclosingAnchorElement(originalInsertionPosition);
    insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition, editingState);
    if (editingState->isAborted())
        return;
    if (listChild == enclosingAnchor) {
        // |positionAvoidingSpecialElementBoundary()| creates new A element and
        // move to another place.
        listChild = toHTMLElement(enclosingAnchorElement(originalInsertionPosition));
    }
    VisiblePosition visiblePos = createVisiblePosition(insertionPosition, affinity);
    calculateStyleBeforeInsertion(insertionPosition);

    //---------------------------------------------------------------------
    // Handle special case of typing return on an empty list item
    if (breakOutOfEmptyListItem(editingState) || editingState->isAborted())
        return;

    //---------------------------------------------------------------------
    // Prepare for more general cases.

    bool isFirstInBlock = isStartOfBlock(visiblePos);
    bool isLastInBlock = isEndOfBlock(visiblePos);
    bool nestNewBlock = false;

    // Create block to be inserted.
    RawPtr<Element> blockToInsert = nullptr;
    if (startBlock->isRootEditableElement()) {
        blockToInsert = createDefaultParagraphElement(document());
        nestNewBlock = true;
    } else if (shouldUseDefaultParagraphElement(startBlock.get())) {
        blockToInsert = createDefaultParagraphElement(document());
    } else {
        blockToInsert = startBlock->cloneElementWithoutChildren();
    }

    //---------------------------------------------------------------------
    // Handle case when position is in the last visible position in its block,
    // including when the block is empty.
    if (isLastInBlock) {
        if (nestNewBlock) {
            if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
                // The block is empty.  Create an empty block to
                // represent the paragraph that we're leaving.
                RawPtr<HTMLElement> extraBlock = createDefaultParagraphElement(document());
                appendNode(extraBlock, startBlock, editingState);
                if (editingState->isAborted())
                    return;
                appendBlockPlaceholder(extraBlock, editingState);
                if (editingState->isAborted())
                    return;
            }
            appendNode(blockToInsert, startBlock, editingState);
            if (editingState->isAborted())
                return;
        } else {
            // We can get here if we pasted a copied portion of a blockquote with a newline at the end and are trying to paste it
            // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
            if (m_pasteBlockquoteIntoUnquotedArea) {
                if (HTMLQuoteElement* highestBlockquote = toHTMLQuoteElement(highestEnclosingNodeOfType(canonicalPos, &isMailHTMLBlockquoteElement)))
                    startBlock = highestBlockquote;
            }

            if (listChild && listChild != startBlock) {
                RawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
                appendNode(blockToInsert, listChildToInsert.get(), editingState);
                if (editingState->isAborted())
                    return;
                insertNodeAfter(listChildToInsert.get(), listChild, editingState);
            } else {
                // Most of the time we want to stay at the nesting level of the startBlock (e.g., when nesting within lists). However,
                // for div nodes, this can result in nested div tags that are hard to break out of.
                Element* siblingElement = startBlock.get();
                if (isHTMLDivElement(*blockToInsert))
                    siblingElement = highestVisuallyEquivalentDivBelowRoot(startBlock.get());
                insertNodeAfter(blockToInsert, siblingElement, editingState);
            }
            if (editingState->isAborted())
                return;
        }

        // Recreate the same structure in the new paragraph.

        HeapVector<Member<Element>> ancestors;
        getAncestorsInsideBlock(positionOutsideTabSpan(insertionPosition).anchorNode(), startBlock.get(), ancestors);
        RawPtr<Element> parent = cloneHierarchyUnderNewBlock(ancestors, blockToInsert, editingState);
        if (editingState->isAborted())
            return;

        appendBlockPlaceholder(parent, editingState);
        if (editingState->isAborted())
            return;

        setEndingSelection(VisibleSelection(firstPositionInNode(parent.get()), TextAffinity::Downstream, endingSelection().isDirectional()));
        return;
    }


    //---------------------------------------------------------------------
    // Handle case when position is in the first visible position in its block, and
    // similar case where previous position is in another, presumeably nested, block.
    if (isFirstInBlock || !inSameBlock(visiblePos, previousPositionOf(visiblePos))) {
        Node* refNode = nullptr;
        insertionPosition = positionOutsideTabSpan(insertionPosition);

        if (isFirstInBlock && !nestNewBlock) {
            if (listChild && listChild != startBlock) {
                RawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
                appendNode(blockToInsert, listChildToInsert.get(), editingState);
                if (editingState->isAborted())
                    return;
                insertNodeBefore(listChildToInsert.get(), listChild, editingState);
                if (editingState->isAborted())
                    return;
            } else {
                refNode = startBlock.get();
            }
        } else if (isFirstInBlock && nestNewBlock) {
            // startBlock should always have children, otherwise isLastInBlock would be true and it's handled above.
            ASSERT(startBlock->hasChildren());
            refNode = startBlock->firstChild();
        } else if (insertionPosition.anchorNode() == startBlock && nestNewBlock) {
            refNode = NodeTraversal::childAt(*startBlock, insertionPosition.computeEditingOffset());
            ASSERT(refNode); // must be true or we'd be in the end of block case
        } else {
            refNode = insertionPosition.anchorNode();
        }

        // find ending selection position easily before inserting the paragraph
        insertionPosition = mostForwardCaretPosition(insertionPosition);

        if (refNode) {
            insertNodeBefore(blockToInsert, refNode, editingState);
            if (editingState->isAborted())
                return;
        }

        // Recreate the same structure in the new paragraph.

        HeapVector<Member<Element>> ancestors;
        insertionPosition = positionAvoidingSpecialElementBoundary(positionOutsideTabSpan(insertionPosition), editingState);
        if (editingState->isAborted())
            return;
        getAncestorsInsideBlock(insertionPosition.anchorNode(), startBlock.get(), ancestors);

        RawPtr<Element> placeholder = cloneHierarchyUnderNewBlock(ancestors, blockToInsert, editingState);
        if (editingState->isAborted())
            return;
        appendBlockPlaceholder(placeholder.release(), editingState);
        if (editingState->isAborted())
            return;

        // In this case, we need to set the new ending selection.
        setEndingSelection(VisibleSelection(insertionPosition, TextAffinity::Downstream, endingSelection().isDirectional()));
        return;
    }

    //---------------------------------------------------------------------
    // Handle the (more complicated) general case,

    // All of the content in the current block after visiblePos is
    // about to be wrapped in a new paragraph element.  Add a br before
    // it if visiblePos is at the start of a paragraph so that the
    // content will move down a line.
    if (isStartOfParagraph(visiblePos)) {
        RawPtr<HTMLBRElement> br = HTMLBRElement::create(document());
        insertNodeAt(br.get(), insertionPosition, editingState);
        if (editingState->isAborted())
            return;
        insertionPosition = positionInParentAfterNode(*br);
        // If the insertion point is a break element, there is nothing else
        // we need to do.
        if (visiblePos.deepEquivalent().anchorNode()->layoutObject()->isBR()) {
            setEndingSelection(VisibleSelection(insertionPosition, TextAffinity::Downstream, endingSelection().isDirectional()));
            return;
        }
    }

    // Move downstream. Typing style code will take care of carrying along the
    // style of the upstream position.
    insertionPosition = mostForwardCaretPosition(insertionPosition);

    // At this point, the insertionPosition's node could be a container, and we want to make sure we include
    // all of the correct nodes when building the ancestor list.  So this needs to be the deepest representation of the position
    // before we walk the DOM tree.
    insertionPosition = positionOutsideTabSpan(createVisiblePosition(insertionPosition).deepEquivalent());

    // If the returned position lies either at the end or at the start of an element that is ignored by editing
    // we should move to its upstream or downstream position.
    if (editingIgnoresContent(insertionPosition.anchorNode())) {
        if (insertionPosition.atLastEditingPositionForNode())
            insertionPosition = mostForwardCaretPosition(insertionPosition);
        else if (insertionPosition.atFirstEditingPositionForNode())
            insertionPosition = mostBackwardCaretPosition(insertionPosition);
    }

    // Make sure we do not cause a rendered space to become unrendered.
    // FIXME: We need the affinity for pos, but mostForwardCaretPosition does not give it
    Position leadingWhitespace = leadingWhitespacePosition(insertionPosition, VP_DEFAULT_AFFINITY);
    // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
    // after the preserved newline, causing the newline to be turned into a nbsp.
    if (leadingWhitespace.isNotNull() && leadingWhitespace.anchorNode()->isTextNode()) {
        Text* textNode = toText(leadingWhitespace.anchorNode());
        ASSERT(!textNode->layoutObject() || textNode->layoutObject()->style()->collapseWhiteSpace());
        replaceTextInNodePreservingMarkers(textNode, leadingWhitespace.computeOffsetInContainerNode(), 1, nonBreakingSpaceString());
    }

    // Split at pos if in the middle of a text node.
    Position positionAfterSplit;
    if (insertionPosition.isOffsetInAnchor() && insertionPosition.computeContainerNode()->isTextNode()) {
        RawPtr<Text> textNode = toText(insertionPosition.computeContainerNode());
        int textOffset = insertionPosition.offsetInContainerNode();
        bool atEnd = static_cast<unsigned>(textOffset) >= textNode->length();
        if (textOffset > 0 && !atEnd) {
            splitTextNode(textNode, textOffset);
            positionAfterSplit = firstPositionInNode(textNode.get());
            insertionPosition = Position(textNode->previousSibling(), textOffset);
            visiblePos = createVisiblePosition(insertionPosition);
        }
    }

    // If we got detached due to mutation events, just bail out.
    if (!startBlock->parentNode())
        return;

    // Put the added block in the tree.
    if (nestNewBlock) {
        appendNode(blockToInsert.get(), startBlock, editingState);
    } else if (listChild && listChild != startBlock) {
        RawPtr<Element> listChildToInsert = listChild->cloneElementWithoutChildren();
        appendNode(blockToInsert.get(), listChildToInsert.get(), editingState);
        if (editingState->isAborted())
            return;
        insertNodeAfter(listChildToInsert.get(), listChild, editingState);
    } else {
        insertNodeAfter(blockToInsert.get(), startBlock, editingState);
    }
    if (editingState->isAborted())
        return;

    document().updateLayoutIgnorePendingStylesheets();

    // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
    // created.  All of the nodes, starting at visiblePos, are about to be added to the new paragraph
    // element.  If the first node to be inserted won't be one that will hold an empty line open, add a br.
    if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visiblePos)) {
        appendNode(HTMLBRElement::create(document()).get(), blockToInsert.get(), editingState);
        if (editingState->isAborted())
            return;
    }

    // Move the start node and the siblings of the start node.
    if (createVisiblePosition(insertionPosition).deepEquivalent() != createVisiblePosition(positionBeforeNode(blockToInsert.get())).deepEquivalent()) {
        Node* n;
        if (insertionPosition.computeContainerNode() == startBlock) {
            n = insertionPosition.computeNodeAfterPosition();
        } else {
            Node* splitTo = insertionPosition.computeContainerNode();
            if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
                splitTo = NodeTraversal::next(*splitTo, startBlock.get());
            if (splitTo)
                splitTreeToNode(splitTo, startBlock.get());

            for (n = startBlock->firstChild(); n; n = n->nextSibling()) {
                VisiblePosition beforeNodePosition = createVisiblePosition(positionBeforeNode(n));
                if (!beforeNodePosition.isNull() && comparePositions(createVisiblePosition(insertionPosition), beforeNodePosition) <= 0)
                    break;
            }
        }

        moveRemainingSiblingsToNewParent(n, blockToInsert.get(), blockToInsert, editingState);
        if (editingState->isAborted())
            return;
    }

    // Handle whitespace that occurs after the split
    if (positionAfterSplit.isNotNull()) {
        document().updateLayoutIgnorePendingStylesheets();
        // TODO(yosin) |isRenderedCharacter()| should be removed, and we should
        // use |VisiblePosition::characterAfter()|.
        if (!isRenderedCharacter(positionAfterSplit)) {
            // Clear out all whitespace and insert one non-breaking space
            ASSERT(!positionAfterSplit.computeContainerNode()->layoutObject() || positionAfterSplit.computeContainerNode()->layoutObject()->style()->collapseWhiteSpace());
            deleteInsignificantTextDownstream(positionAfterSplit);
            if (positionAfterSplit.anchorNode()->isTextNode())
                insertTextIntoNode(toText(positionAfterSplit.computeContainerNode()), 0, nonBreakingSpaceString());
        }
    }

    setEndingSelection(VisibleSelection(firstPositionInNode(blockToInsert.get()), TextAffinity::Downstream, endingSelection().isDirectional()));
    applyStyleAfterInsertion(startBlock.get(), editingState);
}