#include "config.h"
#include "Range.h"
#include "ClientRect.h"
#include "ClientRectList.h"
#include "DocumentFragment.h"
#include "ExceptionCode.h"
#include "FloatQuad.h"
#include "Frame.h"
#include "FrameView.h"
#include "HTMLElement.h"
#include "HTMLNames.h"
#include "Node.h"
#include "NodeWithIndex.h"
#include "Page.h"
#include "ProcessingInstruction.h"
#include "RangeException.h"
#include "RenderBoxModelObject.h"
#include "RenderText.h"
#include "Text.h"
#include "TextIterator.h"
#include "VisiblePosition.h"
#include "htmlediting.h"
#include "markup.h"
#include "visible_units.h"
#include <stdio.h>
#include <wtf/RefCountedLeakCounter.h>
#include <wtf/Vector.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
#include "HTMLNames.h"
#include "htmlediting.h"
namespace WebCore {
using namespace std;
using namespace HTMLNames;
DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, rangeCounter, ("Range"));
inline Range::Range(PassRefPtr<Document> ownerDocument)
: m_ownerDocument(ownerDocument)
, m_start(m_ownerDocument)
, m_end(m_ownerDocument)
{
#ifndef NDEBUG
rangeCounter.increment();
#endif
m_ownerDocument->attachRange(this);
}
PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument)
{
return adoptRef(new Range(ownerDocument));
}
inline Range::Range(PassRefPtr<Document> ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
: m_ownerDocument(ownerDocument)
, m_start(m_ownerDocument)
, m_end(m_ownerDocument)
{
#ifndef NDEBUG
rangeCounter.increment();
#endif
m_ownerDocument->attachRange(this);
setStart(startContainer, startOffset);
setEnd(endContainer, endOffset);
}
PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
{
return adoptRef(new Range(ownerDocument, startContainer, startOffset, endContainer, endOffset));
}
PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument, const Position& start, const Position& end)
{
return adoptRef(new Range(ownerDocument, start.containerNode(), start.computeOffsetInContainerNode(), end.containerNode(), end.computeOffsetInContainerNode()));
}
PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument, const VisiblePosition& visibleStart, const VisiblePosition& visibleEnd)
{
Position start = visibleStart.deepEquivalent().parentAnchoredEquivalent();
Position end = visibleEnd.deepEquivalent().parentAnchoredEquivalent();
return adoptRef(new Range(ownerDocument, start.anchorNode(), start.deprecatedEditingOffset(), end.anchorNode(), end.deprecatedEditingOffset()));
}
Range::~Range()
{
m_ownerDocument->detachRange(this);
#ifndef NDEBUG
rangeCounter.decrement();
#endif
}
void Range::setDocument(Document* document)
{
ASSERT(m_ownerDocument != document);
if (m_ownerDocument)
m_ownerDocument->detachRange(this);
m_ownerDocument = document;
m_start.setToStartOfNode(document);
m_end.setToStartOfNode(document);
m_ownerDocument->attachRange(this);
}
Node* Range::startContainer(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return m_start.container();
}
int Range::startOffset(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return m_start.offset();
}
Node* Range::endContainer(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return m_end.container();
}
int Range::endOffset(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return m_end.offset();
}
Node* Range::commonAncestorContainer(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return commonAncestorContainer(m_start.container(), m_end.container());
}
Node* Range::commonAncestorContainer(Node* containerA, Node* containerB)
{
for (Node* parentA = containerA; parentA; parentA = parentA->parentNode()) {
for (Node* parentB = containerB; parentB; parentB = parentB->parentNode()) {
if (parentA == parentB)
return parentA;
}
}
return 0;
}
bool Range::collapsed(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return m_start == m_end;
}
void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
Node* childNode = checkNodeWOffset(refNode.get(), offset, ec);
if (ec)
return;
m_start.set(refNode, offset, childNode);
Node* endRootContainer = m_end.container();
while (endRootContainer->parentNode())
endRootContainer = endRootContainer->parentNode();
Node* startRootContainer = m_start.container();
while (startRootContainer->parentNode())
startRootContainer = startRootContainer->parentNode();
if (startRootContainer != endRootContainer)
collapse(true, ec);
else if (compareBoundaryPoints(m_start, m_end, ec) > 0) {
ASSERT(!ec);
collapse(true, ec);
}
}
void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
Node* childNode = checkNodeWOffset(refNode.get(), offset, ec);
if (ec)
return;
m_end.set(refNode, offset, childNode);
Node* endRootContainer = m_end.container();
while (endRootContainer->parentNode())
endRootContainer = endRootContainer->parentNode();
Node* startRootContainer = m_start.container();
while (startRootContainer->parentNode())
startRootContainer = startRootContainer->parentNode();
if (startRootContainer != endRootContainer)
collapse(false, ec);
if (compareBoundaryPoints(m_start, m_end, ec) > 0) {
ASSERT(!ec);
collapse(false, ec);
}
}
void Range::setStart(const Position& start, ExceptionCode& ec)
{
Position parentAnchored = start.parentAnchoredEquivalent();
setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), ec);
}
void Range::setEnd(const Position& end, ExceptionCode& ec)
{
Position parentAnchored = end.parentAnchoredEquivalent();
setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), ec);
}
void Range::collapse(bool toStart, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (toStart)
m_end = m_start;
else
m_start = m_end;
}
bool Range::isPointInRange(Node* refNode, int offset, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return false;
}
if (!refNode) {
ec = HIERARCHY_REQUEST_ERR;
return false;
}
if (!refNode->attached()) {
return false;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return false;
}
ec = 0;
checkNodeWOffset(refNode, offset, ec);
if (ec)
return false;
return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), ec) >= 0 && !ec
&& compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), ec) <= 0 && !ec;
}
short Range::comparePoint(Node* refNode, int offset, ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
if (!refNode) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
if (!refNode->attached() || refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return 0;
}
ec = 0;
checkNodeWOffset(refNode, offset, ec);
if (ec)
return 0;
if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), ec) < 0)
return -1;
if (ec)
return 0;
if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), ec) > 0 && !ec)
return 1;
return 0;
}
Range::CompareResults Range::compareNode(Node* refNode, ExceptionCode& ec) const
{
if (!refNode) {
ec = NOT_FOUND_ERR;
return NODE_BEFORE;
}
if (!m_start.container() && refNode->attached()) {
ec = INVALID_STATE_ERR;
return NODE_BEFORE;
}
if (m_start.container() && !refNode->attached()) {
return NODE_BEFORE;
}
if (refNode->document() != m_ownerDocument) {
return NODE_BEFORE;
}
ContainerNode* parentNode = refNode->parentNode();
int nodeIndex = refNode->nodeIndex();
if (!parentNode) {
ec = NOT_FOUND_ERR;
return NODE_BEFORE;
}
if (comparePoint(parentNode, nodeIndex, ec) < 0) { if (comparePoint(parentNode, nodeIndex + 1, ec) > 0) return NODE_BEFORE_AND_AFTER;
return NODE_BEFORE; } else { if (comparePoint(parentNode, nodeIndex + 1, ec) > 0) return NODE_AFTER;
return NODE_INSIDE; }
}
short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
if (!sourceRange) {
ec = NOT_FOUND_ERR;
return 0;
}
ec = 0;
Node* thisCont = commonAncestorContainer(ec);
if (ec)
return 0;
Node* sourceCont = sourceRange->commonAncestorContainer(ec);
if (ec)
return 0;
if (thisCont->document() != sourceCont->document()) {
ec = WRONG_DOCUMENT_ERR;
return 0;
}
Node* thisTop = thisCont;
Node* sourceTop = sourceCont;
while (thisTop->parentNode())
thisTop = thisTop->parentNode();
while (sourceTop->parentNode())
sourceTop = sourceTop->parentNode();
if (thisTop != sourceTop) { ec = WRONG_DOCUMENT_ERR;
return 0;
}
switch (how) {
case START_TO_START:
return compareBoundaryPoints(m_start, sourceRange->m_start, ec);
case START_TO_END:
return compareBoundaryPoints(m_end, sourceRange->m_start, ec);
case END_TO_END:
return compareBoundaryPoints(m_end, sourceRange->m_end, ec);
case END_TO_START:
return compareBoundaryPoints(m_start, sourceRange->m_end, ec);
}
ec = SYNTAX_ERR;
return 0;
}
short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionCode& ec)
{
ASSERT(containerA);
ASSERT(containerB);
if (!containerA)
return -1;
if (!containerB)
return 1;
if (containerA == containerB) {
if (offsetA == offsetB)
return 0; if (offsetA < offsetB)
return -1; else
return 1; }
Node* c = containerB;
while (c && c->parentNode() != containerA)
c = c->parentNode();
if (c) {
int offsetC = 0;
Node* n = containerA->firstChild();
while (n != c && offsetC < offsetA) {
offsetC++;
n = n->nextSibling();
}
if (offsetA <= offsetC)
return -1; else
return 1; }
c = containerA;
while (c && c->parentNode() != containerB)
c = c->parentNode();
if (c) {
int offsetC = 0;
Node* n = containerB->firstChild();
while (n != c && offsetC < offsetB) {
offsetC++;
n = n->nextSibling();
}
if (offsetC < offsetB)
return -1; else
return 1; }
Node* commonAncestor = commonAncestorContainer(containerA, containerB);
if (!commonAncestor) {
ec = WRONG_DOCUMENT_ERR;
return 0;
}
Node* childA = containerA;
while (childA && childA->parentNode() != commonAncestor)
childA = childA->parentNode();
if (!childA)
childA = commonAncestor;
Node* childB = containerB;
while (childB && childB->parentNode() != commonAncestor)
childB = childB->parentNode();
if (!childB)
childB = commonAncestor;
if (childA == childB)
return 0;
Node* n = commonAncestor->firstChild();
while (n) {
if (n == childA)
return -1; if (n == childB)
return 1; n = n->nextSibling();
}
ASSERT_NOT_REACHED();
return 0;
}
short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionCode& ec)
{
return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), ec);
}
bool Range::boundaryPointsValid() const
{
ExceptionCode ec = 0;
return m_start.container() && compareBoundaryPoints(m_start, m_end, ec) <= 0 && !ec;
}
void Range::deleteContents(ExceptionCode& ec)
{
checkDeleteExtract(ec);
if (ec)
return;
processContents(DELETE_CONTENTS, ec);
}
bool Range::intersectsNode(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return false;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return false;
}
if (!refNode->attached() || refNode->document() != m_ownerDocument) {
return false;
}
ContainerNode* parentNode = refNode->parentNode();
int nodeIndex = refNode->nodeIndex();
if (!parentNode) {
ec = NOT_FOUND_ERR;
return false;
}
if (comparePoint(parentNode, nodeIndex, ec) < 0 && comparePoint(parentNode, nodeIndex + 1, ec) < 0) { return false;
} else if (comparePoint(parentNode, nodeIndex, ec) > 0 && comparePoint(parentNode, nodeIndex + 1, ec) > 0) { return false;
}
return true; }
static inline Node* highestAncestorUnderCommonRoot(Node* node, Node* commonRoot)
{
if (node == commonRoot)
return 0;
ASSERT(commonRoot->contains(node));
while (node->parentNode() != commonRoot)
node = node->parentNode();
return node;
}
static inline Node* childOfCommonRootBeforeOffset(Node* container, unsigned offset, Node* commonRoot)
{
ASSERT(container);
ASSERT(commonRoot);
if (!commonRoot->contains(container))
return 0;
if (container == commonRoot) {
container = container->firstChild();
for (unsigned i = 0; container && i < offset; i++)
container = container->nextSibling();
} else {
while (container->parentNode() != commonRoot)
container = container->parentNode();
}
return container;
}
static inline unsigned lengthOfContentsInNode(Node* node)
{
switch (node->nodeType()) {
case Node::TEXT_NODE:
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
return static_cast<CharacterData*>(node)->length();
case Node::PROCESSING_INSTRUCTION_NODE:
return static_cast<ProcessingInstruction*>(node)->data().length();
case Node::ELEMENT_NODE:
case Node::ATTRIBUTE_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::ENTITY_NODE:
case Node::DOCUMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::NOTATION_NODE:
case Node::XPATH_NAMESPACE_NODE:
return node->childNodeCount();
}
ASSERT_NOT_REACHED();
return 0;
}
PassRefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionCode& ec)
{
typedef Vector<RefPtr<Node> > NodeVector;
RefPtr<DocumentFragment> fragment;
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS)
fragment = DocumentFragment::create(m_ownerDocument.get());
ec = 0;
if (collapsed(ec))
return fragment.release();
if (ec)
return 0;
RefPtr<Node> commonRoot = commonAncestorContainer(ec);
if (ec)
return 0;
ASSERT(commonRoot);
if (m_start.container() == m_end.container()) {
processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), ec);
return fragment;
}
RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(m_start.container(), commonRoot.get());
RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(m_end.container(), commonRoot.get());
RefPtr<Node> leftContents;
if (m_start.container() != commonRoot && commonRoot->contains(m_start.container())) {
leftContents = processContentsBetweenOffsets(action, 0, m_start.container(), m_start.offset(), lengthOfContentsInNode(m_start.container()), ec);
leftContents = processAncestorsAndTheirSiblings(action, m_start.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
}
RefPtr<Node> rightContents;
if (m_end.container() != commonRoot && commonRoot->contains(m_end.container())) {
rightContents = processContentsBetweenOffsets(action, 0, m_end.container(), 0, m_end.offset(), ec);
rightContents = processAncestorsAndTheirSiblings(action, m_end.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
}
RefPtr<Node> processStart = childOfCommonRootBeforeOffset(m_start.container(), m_start.offset(), commonRoot.get());
if (processStart && m_start.container() != commonRoot) processStart = processStart->nextSibling();
RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(m_end.container(), m_end.offset(), commonRoot.get());
if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
if (partialStart && commonRoot->contains(partialStart.get()))
setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, ec);
else if (partialEnd && commonRoot->contains(partialEnd.get()))
setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), ec);
if (ec)
return 0;
m_end = m_start;
}
if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && leftContents)
fragment->appendChild(leftContents, ec);
if (processStart) {
NodeVector nodes;
for (Node* n = processStart.get(); n && n != processEnd; n = n->nextSibling())
nodes.append(n);
processNodes(action, nodes, commonRoot, fragment, ec);
}
if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && rightContents)
fragment->appendChild(rightContents, ec);
return fragment.release();
}
static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionCode& ec)
{
if (data->length() - endOffset)
data->deleteData(endOffset, data->length() - endOffset, ec);
if (startOffset)
data->deleteData(0, startOffset, ec);
}
PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRefPtr<DocumentFragment> fragment,
Node* container, unsigned startOffset, unsigned endOffset, ExceptionCode& ec)
{
ASSERT(container);
ASSERT(startOffset <= endOffset);
RefPtr<Node> result;
switch (container->nodeType()) {
case Node::TEXT_NODE:
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
ASSERT(endOffset <= static_cast<CharacterData*>(container)->length());
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
RefPtr<CharacterData> c = static_pointer_cast<CharacterData>(container->cloneNode(true));
deleteCharacterData(c, startOffset, endOffset, ec);
if (fragment) {
result = fragment;
result->appendChild(c.release(), ec);
} else
result = c.release();
}
if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS)
static_cast<CharacterData*>(container)->deleteData(startOffset, endOffset - startOffset, ec);
break;
case Node::PROCESSING_INSTRUCTION_NODE:
ASSERT(endOffset <= static_cast<ProcessingInstruction*>(container)->data().length());
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
RefPtr<ProcessingInstruction> c = static_pointer_cast<ProcessingInstruction>(container->cloneNode(true));
c->setData(c->data().substring(startOffset, endOffset - startOffset), ec);
if (fragment) {
result = fragment;
result->appendChild(c.release(), ec);
} else
result = c.release();
}
if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(container);
String data(pi->data());
data.remove(startOffset, endOffset - startOffset);
pi->setData(data, ec);
}
break;
case Node::ELEMENT_NODE:
case Node::ATTRIBUTE_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::ENTITY_NODE:
case Node::DOCUMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::NOTATION_NODE:
case Node::XPATH_NAMESPACE_NODE:
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
if (fragment)
result = fragment;
else
result = container->cloneNode(false);
}
Node* n = container->firstChild();
Vector<RefPtr<Node> > nodes;
for (unsigned i = startOffset; n && i; i--)
n = n->nextSibling();
for (unsigned i = startOffset; n && i < endOffset; i++, n = n->nextSibling())
nodes.append(n);
processNodes(action, nodes, container, result, ec);
break;
}
return result.release();
}
void Range::processNodes(ActionType action, Vector<RefPtr<Node> >& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionCode& ec)
{
for (unsigned i = 0; i < nodes.size(); i++) {
switch (action) {
case DELETE_CONTENTS:
oldContainer->removeChild(nodes[i].get(), ec);
break;
case EXTRACT_CONTENTS:
newContainer->appendChild(nodes[i].release(), ec); break;
case CLONE_CONTENTS:
newContainer->appendChild(nodes[i]->cloneNode(true), ec);
break;
}
}
}
PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionCode& ec)
{
typedef Vector<RefPtr<Node> > NodeVector;
RefPtr<Node> clonedContainer = passedClonedContainer;
Vector<RefPtr<Node> > ancestors;
for (ContainerNode* n = container->parentNode(); n && n != commonRoot; n = n->parentNode())
ancestors.append(n);
RefPtr<Node> firstChildInAncestorToProcess = direction == ProcessContentsForward ? container->nextSibling() : container->previousSibling();
for (Vector<RefPtr<Node> >::const_iterator it = ancestors.begin(); it != ancestors.end(); it++) {
RefPtr<Node> ancestor = *it;
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
if (RefPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { clonedAncestor->appendChild(clonedContainer, ec);
clonedContainer = clonedAncestor;
}
}
ASSERT(!firstChildInAncestorToProcess || firstChildInAncestorToProcess->parentNode() == ancestor);
NodeVector nodes;
for (Node* child = firstChildInAncestorToProcess.get(); child;
child = (direction == ProcessContentsForward) ? child->nextSibling() : child->previousSibling())
nodes.append(child);
for (NodeVector::const_iterator it = nodes.begin(); it != nodes.end(); it++) {
Node* child = it->get();
switch (action) {
case DELETE_CONTENTS:
ancestor->removeChild(child, ec);
break;
case EXTRACT_CONTENTS: if (direction == ProcessContentsForward)
clonedContainer->appendChild(child, ec);
else
clonedContainer->insertBefore(child, clonedContainer->firstChild(), ec);
break;
case CLONE_CONTENTS:
if (direction == ProcessContentsForward)
clonedContainer->appendChild(child->cloneNode(true), ec);
else
clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), ec);
break;
}
}
firstChildInAncestorToProcess = direction == ProcessContentsForward ? ancestor->nextSibling() : ancestor->previousSibling();
}
return clonedContainer.release();
}
PassRefPtr<DocumentFragment> Range::extractContents(ExceptionCode& ec)
{
checkDeleteExtract(ec);
if (ec)
return 0;
return processContents(EXTRACT_CONTENTS, ec);
}
PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return processContents(CLONE_CONTENTS, ec);
}
void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionCode& ec)
{
RefPtr<Node> newNode = prpNewNode;
ec = 0;
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!newNode) {
ec = NOT_FOUND_ERR;
return;
}
if (containedByReadOnly()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return;
}
bool startIsText = m_start.container()->isTextNode();
if (startIsText && !m_start.container()->parentNode()) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
Node* checkAgainst;
if (startIsText)
checkAgainst = m_start.container()->parentNode();
else
checkAgainst = m_start.container();
Node::NodeType newNodeType = newNode->nodeType();
int numNewChildren;
if (newNodeType == Node::DOCUMENT_FRAGMENT_NODE && !newNode->isShadowRoot()) {
numNewChildren = 0;
for (Node* c = newNode->firstChild(); c; c = c->nextSibling()) {
if (!checkAgainst->childTypeAllowed(c->nodeType())) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
++numNewChildren;
}
} else {
numNewChildren = 1;
if (!checkAgainst->childTypeAllowed(newNodeType)) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
}
for (Node* n = m_start.container(); n; n = n->parentNode()) {
if (n == newNode) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
}
switch (newNodeType) {
case Node::ATTRIBUTE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
case Node::DOCUMENT_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
default:
if (newNode->isShadowRoot()) {
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
}
break;
}
bool collapsed = m_start == m_end;
RefPtr<Node> container;
if (startIsText) {
container = m_start.container();
RefPtr<Text> newText = toText(container.get())->splitText(m_start.offset(), ec);
if (ec)
return;
container = m_start.container();
container->parentNode()->insertBefore(newNode.release(), newText.get(), ec);
if (ec)
return;
if (collapsed)
m_end.setToBeforeChild(newText.get());
} else {
RefPtr<Node> lastChild;
if (collapsed)
lastChild = (newNodeType == Node::DOCUMENT_FRAGMENT_NODE) ? newNode->lastChild() : newNode;
int startOffset = m_start.offset();
container = m_start.container();
container->insertBefore(newNode.release(), container->childNode(startOffset), ec);
if (ec)
return;
if (collapsed && numNewChildren)
m_end.set(m_start.container(), startOffset + numNewChildren, lastChild.get());
}
}
String Range::toString(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return String();
}
StringBuilder builder;
Node* pastLast = pastLastNode();
for (Node* n = firstNode(); n != pastLast; n = n->traverseNextNode()) {
if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
String data = static_cast<CharacterData*>(n)->data();
int length = data.length();
int start = (n == m_start.container()) ? min(max(0, m_start.offset()), length) : 0;
int end = (n == m_end.container()) ? min(max(start, m_end.offset()), length) : length;
builder.append(data.characters() + start, end - start);
}
}
return builder.toString();
}
String Range::toHTML() const
{
return createMarkup(this);
}
String Range::text() const
{
if (!m_start.container())
return String();
m_start.container()->document()->updateLayout();
return plainText(this);
}
static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
{
ExceptionCode ignoredExceptionCode;
RefPtr<Node> nextChild;
for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) {
nextChild = child->nextSibling();
element->removeChild(child.get(), ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
fragment->insertBefore(child, element, ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
}
fragment->removeChild(element, ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
}
PassRefPtr<DocumentFragment> Range::createDocumentFragmentForElement(const String& markup, Element* element, FragmentScriptingPermission scriptingPermission)
{
ASSERT(element);
HTMLElement* htmlElement = toHTMLElement(element);
if (htmlElement->ieForbidsInsertHTML())
return 0;
if (htmlElement->hasLocalName(colTag) || htmlElement->hasLocalName(colgroupTag) || htmlElement->hasLocalName(framesetTag)
|| htmlElement->hasLocalName(headTag) || htmlElement->hasLocalName(styleTag) || htmlElement->hasLocalName(titleTag))
return 0;
RefPtr<DocumentFragment> fragment = element->document()->createDocumentFragment();
if (element->document()->isHTMLDocument())
fragment->parseHTML(markup, element, scriptingPermission);
else if (!fragment->parseXML(markup, element, scriptingPermission))
return 0;
RefPtr<Node> nextNode;
for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
nextNode = node->nextSibling();
if (node->hasTagName(htmlTag) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
HTMLElement* element = toHTMLElement(node.get());
if (Node* firstChild = element->firstChild())
nextNode = firstChild;
removeElementPreservingChildren(fragment, element);
}
}
return fragment.release();
}
PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionCode& ec, FragmentScriptingPermission scriptingPermission)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
if (!element || !element->isHTMLElement()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
RefPtr<DocumentFragment> fragment = createDocumentFragmentForElement(markup, toElement(element), scriptingPermission);
if (!fragment) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return fragment.release();
}
void Range::detach(ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
m_ownerDocument->detachRange(this);
m_start.clear();
m_end.clear();
}
Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionCode& ec) const
{
switch (n->nodeType()) {
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return 0;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::TEXT_NODE:
if (static_cast<unsigned>(offset) > static_cast<CharacterData*>(n)->length())
ec = INDEX_SIZE_ERR;
return 0;
case Node::PROCESSING_INSTRUCTION_NODE:
if (static_cast<unsigned>(offset) > static_cast<ProcessingInstruction*>(n)->data().length())
ec = INDEX_SIZE_ERR;
return 0;
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::XPATH_NAMESPACE_NODE: {
if (!offset)
return 0;
Node* childBefore = n->childNode(offset - 1);
if (!childBefore)
ec = INDEX_SIZE_ERR;
return childBefore;
}
}
ASSERT_NOT_REACHED();
return 0;
}
void Range::checkNodeBA(Node* n, ExceptionCode& ec) const
{
switch (n->nodeType()) {
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
break;
}
Node* root = n;
while (ContainerNode* parent = root->parentNode())
root = parent;
switch (root->nodeType()) {
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
break;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::NOTATION_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
}
}
PassRefPtr<Range> Range::cloneRange(ExceptionCode& ec) const
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
return Range::create(m_ownerDocument, m_start.container(), m_start.offset(), m_end.container(), m_end.offset());
}
void Range::setStartAfter(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
checkNodeBA(refNode, ec);
if (ec)
return;
setStart(refNode->parentNode(), refNode->nodeIndex() + 1, ec);
}
void Range::setEndBefore(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
checkNodeBA(refNode, ec);
if (ec)
return;
setEnd(refNode->parentNode(), refNode->nodeIndex(), ec);
}
void Range::setEndAfter(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
checkNodeBA(refNode, ec);
if (ec)
return;
setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, ec);
}
void Range::selectNode(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
for (ContainerNode* anc = refNode->parentNode(); anc; anc = anc->parentNode()) {
switch (anc->nodeType()) {
case Node::ATTRIBUTE_NODE:
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
break;
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
}
}
switch (refNode->nodeType()) {
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
break;
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
}
if (m_ownerDocument != refNode->document())
setDocument(refNode->document());
ec = 0;
setStartBefore(refNode, ec);
if (ec)
return;
setEndAfter(refNode, ec);
}
void Range::selectNodeContents(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
for (Node* n = refNode; n; n = n->parentNode()) {
switch (n->nodeType()) {
case Node::ATTRIBUTE_NODE:
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
break;
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
}
}
if (m_ownerDocument != refNode->document())
setDocument(refNode->document());
m_start.setToStartOfNode(refNode);
m_end.setToEndOfNode(refNode);
}
void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionCode& ec)
{
RefPtr<Node> newParent = passNewParent;
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!newParent) {
ec = NOT_FOUND_ERR;
return;
}
switch (newParent->nodeType()) {
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
case Node::DOCUMENT_NODE:
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
ec = RangeException::INVALID_NODE_TYPE_ERR;
return;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::ELEMENT_NODE:
case Node::ENTITY_REFERENCE_NODE:
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
break;
}
if (containedByReadOnly()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return;
}
Node* parentOfNewParent = m_start.container();
if (parentOfNewParent->isCharacterDataNode())
parentOfNewParent = parentOfNewParent->parentNode();
if (!parentOfNewParent || !parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
if (m_start.container() == newParent || m_start.container()->isDescendantOf(newParent.get())) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
Node* startNonTextContainer = m_start.container();
if (startNonTextContainer->nodeType() == Node::TEXT_NODE)
startNonTextContainer = startNonTextContainer->parentNode();
Node* endNonTextContainer = m_end.container();
if (endNonTextContainer->nodeType() == Node::TEXT_NODE)
endNonTextContainer = endNonTextContainer->parentNode();
if (startNonTextContainer != endNonTextContainer) {
ec = RangeException::BAD_BOUNDARYPOINTS_ERR;
return;
}
ec = 0;
while (Node* n = newParent->firstChild()) {
toContainerNode(newParent.get())->removeChild(n, ec);
if (ec)
return;
}
RefPtr<DocumentFragment> fragment = extractContents(ec);
if (ec)
return;
insertNode(newParent, ec);
if (ec)
return;
newParent->appendChild(fragment.release(), ec);
if (ec)
return;
selectNode(newParent.get(), ec);
}
void Range::setStartBefore(Node* refNode, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
if (!refNode) {
ec = NOT_FOUND_ERR;
return;
}
if (refNode->document() != m_ownerDocument) {
ec = WRONG_DOCUMENT_ERR;
return;
}
ec = 0;
checkNodeBA(refNode, ec);
if (ec)
return;
setStart(refNode->parentNode(), refNode->nodeIndex(), ec);
}
void Range::checkDeleteExtract(ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
ec = 0;
if (!commonAncestorContainer(ec) || ec)
return;
Node* pastLast = pastLastNode();
for (Node* n = firstNode(); n != pastLast; n = n->traverseNextNode()) {
if (n->isReadOnlyNode()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return;
}
if (n->nodeType() == Node::DOCUMENT_TYPE_NODE) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
}
if (containedByReadOnly()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return;
}
}
bool Range::containedByReadOnly() const
{
for (Node* n = m_start.container(); n; n = n->parentNode()) {
if (n->isReadOnlyNode())
return true;
}
for (Node* n = m_end.container(); n; n = n->parentNode()) {
if (n->isReadOnlyNode())
return true;
}
return false;
}
Node* Range::firstNode() const
{
if (!m_start.container())
return 0;
if (m_start.container()->offsetInCharacters())
return m_start.container();
if (Node* child = m_start.container()->childNode(m_start.offset()))
return child;
if (!m_start.offset())
return m_start.container();
return m_start.container()->traverseNextSibling();
}
Node* Range::shadowTreeRootNode() const
{
return startContainer() ? startContainer()->shadowTreeRootNode() : 0;
}
Node* Range::pastLastNode() const
{
if (!m_start.container() || !m_end.container())
return 0;
if (m_end.container()->offsetInCharacters())
return m_end.container()->traverseNextSibling();
if (Node* child = m_end.container()->childNode(m_end.offset()))
return child;
return m_end.container()->traverseNextSibling();
}
IntRect Range::boundingBox()
{
IntRect result;
Vector<IntRect> rects;
textRects(rects);
const size_t n = rects.size();
for (size_t i = 0; i < n; ++i)
result.unite(rects[i]);
return result;
}
void Range::textRects(Vector<IntRect>& rects, bool useSelectionHeight, RangeInFixedPosition* inFixed)
{
Node* startContainer = m_start.container();
Node* endContainer = m_end.container();
if (!startContainer || !endContainer) {
if (inFixed)
*inFixed = NotFixedPosition;
return;
}
bool allFixed = true;
bool someFixed = false;
Node* stopNode = pastLastNode();
for (Node* node = firstNode(); node != stopNode; node = node->traverseNextNode()) {
RenderObject* r = node->renderer();
if (!r || !r->isText())
continue;
RenderText* renderText = toRenderText(r);
int startOffset = node == startContainer ? m_start.offset() : 0;
int endOffset = node == endContainer ? m_end.offset() : numeric_limits<int>::max();
bool isFixed = false;
renderText->absoluteRectsForRange(rects, startOffset, endOffset, useSelectionHeight, &isFixed);
allFixed &= isFixed;
someFixed |= isFixed;
}
if (inFixed)
*inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition);
}
void Range::textQuads(Vector<FloatQuad>& quads, bool useSelectionHeight, RangeInFixedPosition* inFixed) const
{
Node* startContainer = m_start.container();
Node* endContainer = m_end.container();
if (!startContainer || !endContainer) {
if (inFixed)
*inFixed = NotFixedPosition;
return;
}
bool allFixed = true;
bool someFixed = false;
Node* stopNode = pastLastNode();
for (Node* node = firstNode(); node != stopNode; node = node->traverseNextNode()) {
RenderObject* r = node->renderer();
if (!r || !r->isText())
continue;
RenderText* renderText = toRenderText(r);
int startOffset = node == startContainer ? m_start.offset() : 0;
int endOffset = node == endContainer ? m_end.offset() : numeric_limits<int>::max();
bool isFixed = false;
renderText->absoluteQuadsForRange(quads, startOffset, endOffset, useSelectionHeight, &isFixed);
allFixed &= isFixed;
someFixed |= isFixed;
}
if (inFixed)
*inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition);
}
static bool intervalsSufficientlyOverlap(int startA, int endA, int startB, int endB)
{
if (endA <= startA || endB <= startB)
return false;
const float sufficientOverlap = .75;
int lengthA = endA - startA;
int lengthB = endB - startB;
int maxStart = max(startA, startB);
int minEnd = min(endA, endB);
if (maxStart > minEnd)
return false;
return minEnd - maxStart >= sufficientOverlap * min(lengthA, lengthB);
}
void Range::collectSelectionRects(Vector<SelectionRect>& rects)
{
if (!m_start.container() || !m_end.container())
return;
Node* startContainer = m_start.container();
Node* endContainer = m_end.container();
int startOffset = m_start.offset();
int endOffset = m_end.offset();
bool hasFlippedWritingMode = false;
Vector<SelectionRect> newRects;
Node* stopNode = pastLastNode();
for (Node* node = firstNode(); node && node != stopNode; node = node->traverseNextNode()) {
RenderObject* r = node->renderer();
if (r && !r->firstChild() && r->style()->userSelect() != SELECT_NONE) {
hasFlippedWritingMode = r->style()->isFlippedBlocksWritingMode();
bool isStartNode = (r->node() == startContainer);
bool isEndNode = (r->node() == endContainer);
int soff = isStartNode ? startOffset : 0;
int eoff = isEndNode ? endOffset : INT_MAX;
r->collectSelectionRects(newRects, soff, eoff);
for (unsigned i = 0; i < newRects.size(); i++) {
SelectionRect &s = newRects[i];
if (s.containsStart() && !isStartNode)
s.setContainsStart(false);
if (s.containsEnd() && !isEndNode)
s.setContainsEnd(false);
}
rects.append(newRects);
newRects.shrink(0);
}
}
if (stopNode && stopNode->hasTagName(HTMLNames::brTag) && rects.size()) {
VisiblePosition endPos(createLegacyEditingPosition(endContainer, endOffset), VP_DEFAULT_AFFINITY);
VisiblePosition brPos(createLegacyEditingPosition(stopNode, 0), VP_DEFAULT_AFFINITY);
if (endPos == brPos)
rects.last().setIsLineBreak(true);
}
int lineTop = numeric_limits<int>::max();
int lineBottom = numeric_limits<int>::min();
int lastLineTop = lineTop;
int lastLineBottom = lineBottom;
int lineNumber = 0;
for (size_t i = 0, size = rects.size(); i < size; ++i) {
int currentRectTop = rects[i].logicalTop();
int currentRectBottom = currentRectTop + rects[i].logicalHeight();
if (intervalsSufficientlyOverlap(currentRectTop, currentRectBottom, lineTop, lineBottom)) {
lineTop = min(lineTop, currentRectTop);
lineBottom = max(lineBottom, currentRectBottom);
if (!hasFlippedWritingMode)
lineTop = max(lastLineBottom, lineTop);
else
lineBottom = min(lastLineTop, lineBottom);
} else {
for (size_t j = i; j > 0; --j) {
if (rects[j - 1].lineNumber())
break;
rects[j - 1].setLineNumber(lineNumber);
rects[j - 1].setLogicalTop(lineTop);
rects[j - 1].setLogicalHeight(lineBottom - lineTop);
}
if (!hasFlippedWritingMode) {
lastLineTop = lineTop;
if (currentRectBottom >= lastLineTop) {
lastLineBottom = lineBottom;
lineTop = lastLineBottom;
} else {
lineTop = currentRectTop;
lastLineBottom = numeric_limits<int>::min();
}
lineBottom = currentRectBottom;
} else {
lastLineBottom = lineBottom;
if (currentRectTop <= lastLineBottom) {
lastLineTop = lineTop;
lineBottom = lastLineTop;
} else {
lastLineTop = numeric_limits<int>::max();
lineBottom = currentRectBottom;
}
lineTop = currentRectTop;
}
lineNumber++;
}
}
for (size_t j = rects.size(); j > 0; --j) {
if (rects[j - 1].lineNumber())
break;
rects[j - 1].setLineNumber(lineNumber);
rects[j - 1].setLogicalTop(lineTop);
rects[j - 1].setLogicalHeight(lineBottom - lineTop);
}
int maxLineNumber = lineNumber;
for (unsigned i = 0; i < rects.size(); i++) {
SelectionRect &s = rects[i];
if (s.isLineBreak() || s.lineNumber() < maxLineNumber) {
if (s.direction() == RTL && s.isFirstOnLine()) {
s.setLogicalWidth(s.logicalWidth() + s.logicalLeft() - s.minX());
s.setLogicalLeft(s.minX());
} else if (s.direction() == LTR && s.isLastOnLine())
s.setLogicalWidth(s.maxX() - s.logicalLeft());
}
}
Vector<SelectionRect> unionedRects;
IntRect interiorUnionRect;
for (unsigned i = 0; i < rects.size(); i++) {
SelectionRect& s = rects[i];
if (s.lineNumber() == 1) {
ASSERT(interiorUnionRect.isEmpty());
if (!unionedRects.isEmpty()) {
SelectionRect& previousRect = unionedRects.last();
if (previousRect.rect().intersects(s.rect())) {
previousRect = SelectionRect(unionRect(previousRect.rect(), s.rect()), s.isHorizontal());
continue;
}
}
unionedRects.append(s);
} else if (s.lineNumber() < maxLineNumber) {
if (interiorUnionRect.isEmpty()) {
interiorUnionRect = s.rect();
} else if (interiorUnionRect.intersects(s.rect())
|| interiorUnionRect.maxX() == s.rect().x()
|| interiorUnionRect.maxY() == s.rect().y()
|| interiorUnionRect.x() == s.rect().maxX()
|| interiorUnionRect.y() == s.rect().maxY()) {
interiorUnionRect.unite(s.rect());
} else {
SelectionRect srect(interiorUnionRect, s.isHorizontal());
unionedRects.append(srect);
interiorUnionRect = s.rect();
}
} else {
if (!interiorUnionRect.isEmpty()) {
SelectionRect srect(interiorUnionRect, s.isHorizontal());
unionedRects.append(srect);
interiorUnionRect = IntRect();
}
ASSERT(!unionedRects.isEmpty());
SelectionRect& previousRect = unionedRects.last();
if (previousRect.rect().y() == s.rect().y() && previousRect.rect().intersects(s.rect())) {
previousRect = SelectionRect(unionRect(previousRect.rect(), s.rect()), s.isHorizontal());
continue;
}
unionedRects.append(s);
}
}
rects.swap(unionedRects);
}
#ifndef NDEBUG
#define FormatBufferSize 1024
void Range::formatForDebugger(char* buffer, unsigned length) const
{
String result;
String s;
if (!m_start.container() || !m_end.container())
result = "<empty>";
else {
char s[FormatBufferSize];
result += "from offset ";
result += String::number(m_start.offset());
result += " of ";
m_start.container()->formatForDebugger(s, FormatBufferSize);
result += s;
result += " to offset ";
result += String::number(m_end.offset());
result += " of ";
m_end.container()->formatForDebugger(s, FormatBufferSize);
result += s;
}
strncpy(buffer, result.utf8().data(), length - 1);
}
#undef FormatBufferSize
#endif
bool areRangesEqual(const Range* a, const Range* b)
{
if (a == b)
return true;
if (!a || !b)
return false;
return a->startPosition() == b->startPosition() && a->endPosition() == b->endPosition();
}
PassRefPtr<Range> rangeOfContents(Node* node)
{
ASSERT(node);
RefPtr<Range> range = Range::create(node->document());
int exception = 0;
range->selectNodeContents(node, exception);
return range.release();
}
int Range::maxStartOffset() const
{
if (!m_start.container())
return 0;
if (!m_start.container()->offsetInCharacters())
return m_start.container()->childNodeCount();
return m_start.container()->maxCharacterOffset();
}
int Range::maxEndOffset() const
{
if (!m_end.container())
return 0;
if (!m_end.container()->offsetInCharacters())
return m_end.container()->childNodeCount();
return m_end.container()->maxCharacterOffset();
}
static inline void boundaryNodeChildrenChanged(RangeBoundaryPoint& boundary, ContainerNode* container)
{
if (!boundary.childBefore())
return;
if (boundary.container() != container)
return;
boundary.invalidateOffset();
}
void Range::nodeChildrenChanged(ContainerNode* container)
{
ASSERT(container);
ASSERT(container->document() == m_ownerDocument);
boundaryNodeChildrenChanged(m_start, container);
boundaryNodeChildrenChanged(m_end, container);
}
static inline void boundaryNodeChildrenWillBeRemoved(RangeBoundaryPoint& boundary, ContainerNode* container)
{
for (Node* nodeToBeRemoved = container->firstChild(); nodeToBeRemoved; nodeToBeRemoved = nodeToBeRemoved->nextSibling()) {
if (boundary.childBefore() == nodeToBeRemoved) {
boundary.setToStartOfNode(container);
return;
}
for (Node* n = boundary.container(); n; n = n->parentNode()) {
if (n == nodeToBeRemoved) {
boundary.setToStartOfNode(container);
return;
}
}
}
}
void Range::nodeChildrenWillBeRemoved(ContainerNode* container)
{
ASSERT(container);
ASSERT(container->document() == m_ownerDocument);
boundaryNodeChildrenWillBeRemoved(m_start, container);
boundaryNodeChildrenWillBeRemoved(m_end, container);
}
static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node* nodeToBeRemoved)
{
if (boundary.childBefore() == nodeToBeRemoved) {
boundary.childBeforeWillBeRemoved();
return;
}
for (Node* n = boundary.container(); n; n = n->parentNode()) {
if (n == nodeToBeRemoved) {
boundary.setToBeforeChild(nodeToBeRemoved);
return;
}
}
}
void Range::nodeWillBeRemoved(Node* node)
{
ASSERT(node);
ASSERT(node->document() == m_ownerDocument);
ASSERT(node != m_ownerDocument);
ASSERT(node->parentNode());
boundaryNodeWillBeRemoved(m_start, node);
boundaryNodeWillBeRemoved(m_end, node);
}
static inline void boundaryTextInserted(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length)
{
if (boundary.container() != text)
return;
unsigned boundaryOffset = boundary.offset();
if (offset >= boundaryOffset)
return;
boundary.setOffset(boundaryOffset + length);
}
void Range::textInserted(Node* text, unsigned offset, unsigned length)
{
ASSERT(text);
ASSERT(text->document() == m_ownerDocument);
boundaryTextInserted(m_start, text, offset, length);
boundaryTextInserted(m_end, text, offset, length);
}
static inline void boundaryTextRemoved(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length)
{
if (boundary.container() != text)
return;
unsigned boundaryOffset = boundary.offset();
if (offset >= boundaryOffset)
return;
if (offset + length >= boundaryOffset)
boundary.setOffset(offset);
else
boundary.setOffset(boundaryOffset - length);
}
void Range::textRemoved(Node* text, unsigned offset, unsigned length)
{
ASSERT(text);
ASSERT(text->document() == m_ownerDocument);
boundaryTextRemoved(m_start, text, offset, length);
boundaryTextRemoved(m_end, text, offset, length);
}
static inline void boundaryTextNodesMerged(RangeBoundaryPoint& boundary, NodeWithIndex& oldNode, unsigned offset)
{
if (boundary.container() == oldNode.node())
boundary.set(oldNode.node()->previousSibling(), boundary.offset() + offset, 0);
else if (boundary.container() == oldNode.node()->parentNode() && boundary.offset() == oldNode.index())
boundary.set(oldNode.node()->previousSibling(), offset, 0);
}
void Range::textNodesMerged(NodeWithIndex& oldNode, unsigned offset)
{
ASSERT(oldNode.node());
ASSERT(oldNode.node()->document() == m_ownerDocument);
ASSERT(oldNode.node()->parentNode());
ASSERT(oldNode.node()->isTextNode());
ASSERT(oldNode.node()->previousSibling());
ASSERT(oldNode.node()->previousSibling()->isTextNode());
boundaryTextNodesMerged(m_start, oldNode, offset);
boundaryTextNodesMerged(m_end, oldNode, offset);
}
static inline void boundaryTextNodesSplit(RangeBoundaryPoint& boundary, Text* oldNode)
{
if (boundary.container() != oldNode)
return;
unsigned boundaryOffset = boundary.offset();
if (boundaryOffset <= oldNode->length())
return;
boundary.set(oldNode->nextSibling(), boundaryOffset - oldNode->length(), 0);
}
void Range::textNodeSplit(Text* oldNode)
{
ASSERT(oldNode);
ASSERT(oldNode->document() == m_ownerDocument);
ASSERT(oldNode->parentNode());
ASSERT(oldNode->isTextNode());
ASSERT(oldNode->nextSibling());
ASSERT(oldNode->nextSibling()->isTextNode());
boundaryTextNodesSplit(m_start, oldNode);
boundaryTextNodesSplit(m_end, oldNode);
}
void Range::expand(const String& unit, ExceptionCode& ec)
{
VisiblePosition start(startPosition());
VisiblePosition end(endPosition());
if (unit == "word") {
start = startOfWord(start);
end = endOfWord(end);
} else if (unit == "sentence") {
start = startOfSentence(start);
end = endOfSentence(end);
} else if (unit == "block") {
start = startOfParagraph(start);
end = endOfParagraph(end);
} else if (unit == "document") {
start = startOfDocument(start);
end = endOfDocument(end);
} else
return;
setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), ec);
setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), ec);
}
PassRefPtr<ClientRectList> Range::getClientRects() const
{
if (!m_start.container())
return ClientRectList::create();
m_ownerDocument->updateLayoutIgnorePendingStylesheets();
Vector<FloatQuad> quads;
getBorderAndTextQuads(quads);
return ClientRectList::create(quads);
}
PassRefPtr<ClientRect> Range::getBoundingClientRect() const
{
return ClientRect::create(boundingRect());
}
static void adjustFloatQuadsForScrollAndAbsoluteZoomAndPageScale(Vector<FloatQuad>& quads, Document* document, RenderObject* renderer)
{
FrameView* view = document->view();
if (!view)
return;
float pageScale = 1;
if (Page* page = document->page())
pageScale = page->pageScaleFactor();
LayoutRect visibleContentRect = view->actualVisibleContentRect();
for (size_t i = 0; i < quads.size(); ++i) {
quads[i].move(-visibleContentRect.x(), -visibleContentRect.y());
adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
if (pageScale != 1)
adjustFloatQuadForPageScale(quads[i], pageScale);
}
}
void Range::getBorderAndTextQuads(Vector<FloatQuad>& quads) const
{
Node* startContainer = m_start.container();
Node* endContainer = m_end.container();
Node* stopNode = pastLastNode();
HashSet<Node*> nodeSet;
for (Node* node = firstNode(); node != stopNode; node = node->traverseNextNode()) {
if (node->isElementNode())
nodeSet.add(node);
}
for (Node* node = firstNode(); node != stopNode; node = node->traverseNextNode()) {
if (node->isElementNode()) {
if (!nodeSet.contains(node->parentNode())) {
if (RenderBoxModelObject* renderBoxModelObject = static_cast<Element*>(node)->renderBoxModelObject()) {
Vector<FloatQuad> elementQuads;
renderBoxModelObject->absoluteQuads(elementQuads);
adjustFloatQuadsForScrollAndAbsoluteZoomAndPageScale(elementQuads, m_ownerDocument.get(), renderBoxModelObject);
quads.append(elementQuads);
}
}
} else if (node->isTextNode()) {
if (RenderObject* renderer = toText(node)->renderer()) {
RenderText* renderText = toRenderText(renderer);
int startOffset = (node == startContainer) ? m_start.offset() : 0;
int endOffset = (node == endContainer) ? m_end.offset() : INT_MAX;
Vector<FloatQuad> textQuads;
renderText->absoluteQuadsForRange(textQuads, startOffset, endOffset);
adjustFloatQuadsForScrollAndAbsoluteZoomAndPageScale(textQuads, m_ownerDocument.get(), renderText);
quads.append(textQuads);
}
}
}
}
FloatRect Range::boundingRect() const
{
if (!m_start.container())
return FloatRect();
m_ownerDocument->updateLayoutIgnorePendingStylesheets();
Vector<FloatQuad> quads;
getBorderAndTextQuads(quads);
if (quads.isEmpty())
return FloatRect();
FloatRect result;
for (size_t i = 0; i < quads.size(); ++i)
result.unite(quads[i].boundingBox());
return result;
}
}
#ifndef NDEBUG
void showTree(const WebCore::Range* range)
{
if (range && range->boundaryPointsValid()) {
range->startContainer()->showTreeAndMark(range->startContainer(), "S", range->endContainer(), "E");
fprintf(stderr, "start offset: %d, end offset: %d\n", range->startOffset(), range->endOffset());
}
}
#endif