Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Implementation of the DOM Range object.
*/
#include "nscore.h"
#include "nsRange.h"
#include "nsDebug.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsIContent.h"
#include "mozilla/dom/Document.h"
#include "nsError.h"
#include "nsINodeList.h"
#include "nsGkAtoms.h"
#include "nsContentUtils.h"
#include "nsTextFrame.h"
#include "mozilla/Assertions.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/ContentIterator.h"
#include "mozilla/dom/CharacterData.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DocumentType.h"
#include "mozilla/dom/RangeBinding.h"
#include "mozilla/dom/DOMRect.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/Text.h"
#include "mozilla/Maybe.h"
#include "mozilla/PresShell.h"
#include "mozilla/RangeUtils.h"
#include "mozilla/Telemetry.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Likely.h"
#include "nsCSSFrameConstructor.h"
#include "nsStyleStruct.h"
#include "nsStyleStructInlines.h"
#include "nsComputedDOMStyle.h"
#include "mozilla/dom/InspectorFontFace.h"
using namespace mozilla;
using namespace mozilla::dom;
template already_AddRefed<nsRange> nsRange::Create(
const RangeBoundary& aStartBoundary, const RangeBoundary& aEndBoundary,
ErrorResult& aRv);
template already_AddRefed<nsRange> nsRange::Create(
const RangeBoundary& aStartBoundary, const RawRangeBoundary& aEndBoundary,
ErrorResult& aRv);
template already_AddRefed<nsRange> nsRange::Create(
const RawRangeBoundary& aStartBoundary, const RangeBoundary& aEndBoundary,
ErrorResult& aRv);
template already_AddRefed<nsRange> nsRange::Create(
const RawRangeBoundary& aStartBoundary,
const RawRangeBoundary& aEndBoundary, ErrorResult& aRv);
template nsresult nsRange::SetStartAndEnd(const RangeBoundary& aStartBoundary,
const RangeBoundary& aEndBoundary);
template nsresult nsRange::SetStartAndEnd(const RangeBoundary& aStartBoundary,
const RawRangeBoundary& aEndBoundary);
template nsresult nsRange::SetStartAndEnd(
const RawRangeBoundary& aStartBoundary, const RangeBoundary& aEndBoundary);
template nsresult nsRange::SetStartAndEnd(
const RawRangeBoundary& aStartBoundary,
const RawRangeBoundary& aEndBoundary);
template void nsRange::DoSetRange(const RangeBoundary& aStartBoundary,
const RangeBoundary& aEndBoundary,
nsINode* aRootNode, bool aNotInsertedYet);
template void nsRange::DoSetRange(const RangeBoundary& aStartBoundary,
const RawRangeBoundary& aEndBoundary,
nsINode* aRootNode, bool aNotInsertedYet);
template void nsRange::DoSetRange(const RawRangeBoundary& aStartBoundary,
const RangeBoundary& aEndBoundary,
nsINode* aRootNode, bool aNotInsertedYet);
template void nsRange::DoSetRange(const RawRangeBoundary& aStartBoundary,
const RawRangeBoundary& aEndBoundary,
nsINode* aRootNode, bool aNotInsertedYet);
JSObject* nsRange::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return Range_Binding::Wrap(aCx, this, aGivenProto);
}
DocGroup* nsRange::GetDocGroup() const {
return mOwner ? mOwner->GetDocGroup() : nullptr;
}
/******************************************************
* stack based utilty class for managing monitor
******************************************************/
static void InvalidateAllFrames(nsINode* aNode) {
MOZ_ASSERT(aNode, "bad arg");
nsIFrame* frame = nullptr;
switch (aNode->NodeType()) {
case nsINode::TEXT_NODE:
case nsINode::ELEMENT_NODE: {
nsIContent* content = static_cast<nsIContent*>(aNode);
frame = content->GetPrimaryFrame();
break;
}
case nsINode::DOCUMENT_NODE: {
Document* doc = static_cast<Document*>(aNode);
PresShell* presShell = doc ? doc->GetPresShell() : nullptr;
frame = presShell ? presShell->GetRootFrame() : nullptr;
break;
}
}
for (nsIFrame* f = frame; f; f = f->GetNextContinuation()) {
f->InvalidateFrameSubtree();
}
}
/******************************************************
* constructor/destructor
******************************************************/
nsTArray<RefPtr<nsRange>>* nsRange::sCachedRanges = nullptr;
nsRange::~nsRange() {
NS_ASSERTION(!IsInSelection(), "deleting nsRange that is in use");
// we want the side effects (releases and list removals)
DoSetRange(RawRangeBoundary(), RawRangeBoundary(), nullptr);
}
nsRange::nsRange(nsINode* aNode)
: AbstractRange(aNode),
mRegisteredClosestCommonInclusiveAncestor(nullptr),
mNextStartRef(nullptr),
mNextEndRef(nullptr) {
// printf("Size of nsRange: %zu\n", sizeof(nsRange));
static_assert(sizeof(nsRange) <= 192,
"nsRange size shouldn't be increased as far as possible");
}
/* static */
already_AddRefed<nsRange> nsRange::Create(nsINode* aNode) {
MOZ_ASSERT(aNode);
if (!sCachedRanges || sCachedRanges->IsEmpty()) {
return do_AddRef(new nsRange(aNode));
}
RefPtr<nsRange> range = sCachedRanges->PopLastElement().forget();
range->Init(aNode);
return range.forget();
}
/* static */
template <typename SPT, typename SRT, typename EPT, typename ERT>
already_AddRefed<nsRange> nsRange::Create(
const RangeBoundaryBase<SPT, SRT>& aStartBoundary,
const RangeBoundaryBase<EPT, ERT>& aEndBoundary, ErrorResult& aRv) {
// If we fail to initialize the range a lot, nsRange should have a static
// initializer since the allocation cost is not cheap in hot path.
RefPtr<nsRange> range = nsRange::Create(aStartBoundary.Container());
aRv = range->SetStartAndEnd(aStartBoundary, aEndBoundary);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
return range.forget();
}
/******************************************************
* nsISupports
******************************************************/
NS_IMPL_MAIN_THREAD_ONLY_CYCLE_COLLECTING_ADDREF(nsRange)
NS_IMPL_MAIN_THREAD_ONLY_CYCLE_COLLECTING_RELEASE_WITH_INTERRUPTABLE_LAST_RELEASE(
nsRange, DoSetRange(RawRangeBoundary(), RawRangeBoundary(), nullptr),
MaybeInterruptLastRelease())
// QueryInterface implementation for nsRange
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsRange)
NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_END_INHERITING(AbstractRange)
NS_IMPL_CYCLE_COLLECTION_CLASS(nsRange)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsRange, AbstractRange)
// We _could_ just rely on Reset() to
// UnregisterClosestCommonInclusiveAncestor(), but it wouldn't know we're
// calling it from Unlink and so would do more work than it really needs to.
if (tmp->mRegisteredClosestCommonInclusiveAncestor) {
tmp->UnregisterClosestCommonInclusiveAncestor(
tmp->mRegisteredClosestCommonInclusiveAncestor, true);
}
tmp->Reset();
MOZ_DIAGNOSTIC_ASSERT(!tmp->isInList(),
"Shouldn't be registered now that we're unlinking");
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsRange, AbstractRange)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRoot)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(nsRange, AbstractRange)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
bool nsRange::MaybeInterruptLastRelease() {
bool interrupt = AbstractRange::MaybeCacheToReuse(*this);
MOZ_ASSERT(!interrupt || IsCleared());
return interrupt;
}
static void MarkDescendants(nsINode* aNode) {
// Set NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection on
// aNode's descendants unless aNode is already marked as a range common
// ancestor or a descendant of one, in which case all of our descendants have
// the bit set already.
if (!aNode->IsMaybeSelected()) {
// don't set the Descendant bit on |aNode| itself
nsINode* node = aNode->GetNextNode(aNode);
while (node) {
node->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
if (!node->IsClosestCommonInclusiveAncestorForRangeInSelection()) {
node = node->GetNextNode(aNode);
} else {
// optimize: skip this sub-tree since it's marked already.
node = node->GetNextNonChildNode(aNode);
}
}
}
}
static void UnmarkDescendants(nsINode* aNode) {
// Unset NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection
// on aNode's descendants unless aNode is a descendant of another range common
// ancestor. Also, exclude descendants of range common ancestors (but not the
// common ancestor itself).
if (!aNode
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
// we know |aNode| doesn't have any bit set
nsINode* node = aNode->GetNextNode(aNode);
while (node) {
node->ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
if (!node->IsClosestCommonInclusiveAncestorForRangeInSelection()) {
node = node->GetNextNode(aNode);
} else {
// We found an ancestor of an overlapping range, skip its descendants.
node = node->GetNextNonChildNode(aNode);
}
}
}
}
void nsRange::RegisterClosestCommonInclusiveAncestor(nsINode* aNode) {
MOZ_ASSERT(aNode, "bad arg");
MOZ_DIAGNOSTIC_ASSERT(IsInSelection(), "registering range not in selection");
mRegisteredClosestCommonInclusiveAncestor = aNode;
MarkDescendants(aNode);
UniquePtr<LinkedList<nsRange>>& ranges =
aNode->GetClosestCommonInclusiveAncestorRangesPtr();
if (!ranges) {
ranges = MakeUnique<LinkedList<nsRange>>();
}
MOZ_DIAGNOSTIC_ASSERT(!isInList());
ranges->insertBack(this);
aNode->SetClosestCommonInclusiveAncestorForRangeInSelection();
}
void nsRange::UnregisterClosestCommonInclusiveAncestor(nsINode* aNode,
bool aIsUnlinking) {
MOZ_ASSERT(aNode, "bad arg");
NS_ASSERTION(aNode->IsClosestCommonInclusiveAncestorForRangeInSelection(),
"wrong node");
MOZ_DIAGNOSTIC_ASSERT(aNode == mRegisteredClosestCommonInclusiveAncestor,
"wrong node");
LinkedList<nsRange>* ranges =
aNode->GetExistingClosestCommonInclusiveAncestorRanges();
MOZ_ASSERT(ranges);
mRegisteredClosestCommonInclusiveAncestor = nullptr;
#ifdef DEBUG
bool found = false;
for (nsRange* range : *ranges) {
if (range == this) {
found = true;
break;
}
}
MOZ_ASSERT(found,
"We should be in the list on our registered common ancestor");
#endif // DEBUG
remove();
// We don't want to waste time unmarking flags on nodes that are
// being unlinked anyway.
if (!aIsUnlinking && ranges->isEmpty()) {
aNode->ClearClosestCommonInclusiveAncestorForRangeInSelection();
UnmarkDescendants(aNode);
}
}
void nsRange::AdjustNextRefsOnCharacterDataSplit(
const nsIContent& aContent, const CharacterDataChangeInfo& aInfo) {
// If the splitted text node is immediately before a range boundary point
// that refers to a child index (i.e. its parent is the boundary container)
// then we need to adjust the corresponding boundary to account for the new
// text node that will be inserted. However, because the new sibling hasn't
// been inserted yet, that would result in an invalid boundary. Therefore,
// we store the new child in mNext*Ref to make sure we adjust the boundary
// in the next ContentInserted or ContentAppended call.
nsINode* parentNode = aContent.GetParentNode();
if (parentNode == mEnd.Container()) {
if (&aContent == mEnd.Ref()) {
MOZ_ASSERT(aInfo.mDetails->mNextSibling);
mNextEndRef = aInfo.mDetails->mNextSibling;
}
}
if (parentNode == mStart.Container()) {
if (&aContent == mStart.Ref()) {
MOZ_ASSERT(aInfo.mDetails->mNextSibling);
mNextStartRef = aInfo.mDetails->mNextSibling;
}
}
}
nsRange::RangeBoundariesAndRoot
nsRange::DetermineNewRangeBoundariesAndRootOnCharacterDataMerge(
nsIContent* aContent, const CharacterDataChangeInfo& aInfo) const {
RawRangeBoundary newStart;
RawRangeBoundary newEnd;
nsINode* newRoot = nullptr;
// normalize(), aInfo.mDetails->mNextSibling is the merged text node
// that will be removed
nsIContent* removed = aInfo.mDetails->mNextSibling;
if (removed == mStart.Container()) {
CheckedUint32 newStartOffset{
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets)};
newStartOffset += aInfo.mChangeStart;
// newStartOffset.isValid() isn't checked explicitly here, because
// newStartOffset.value() contains an assertion.
newStart = {aContent, newStartOffset.value()};
if (MOZ_UNLIKELY(removed == mRoot)) {
newRoot = RangeUtils::ComputeRootNode(newStart.Container());
}
}
if (removed == mEnd.Container()) {
CheckedUint32 newEndOffset{
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets)};
newEndOffset += aInfo.mChangeStart;
// newEndOffset.isValid() isn't checked explicitly here, because
// newEndOffset.value() contains an assertion.
newEnd = {aContent, newEndOffset.value()};
if (MOZ_UNLIKELY(removed == mRoot)) {
newRoot = {RangeUtils::ComputeRootNode(newEnd.Container())};
}
}
// When the removed text node's parent is one of our boundary nodes we may
// need to adjust the offset to account for the removed node. However,
// there will also be a ContentRemoved notification later so the only cases
// we need to handle here is when the removed node is the text node after
// the boundary. (The m*Offset > 0 check is an optimization - a boundary
// point before the first child is never affected by normalize().)
nsINode* parentNode = aContent->GetParentNode();
if (parentNode == mStart.Container() &&
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) > 0 &&
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <
parentNode->GetChildCount() &&
removed == mStart.GetChildAtOffset()) {
newStart = {aContent, aInfo.mChangeStart};
}
if (parentNode == mEnd.Container() &&
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) > 0 &&
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <
parentNode->GetChildCount() &&
removed == mEnd.GetChildAtOffset()) {
newEnd = {aContent, aInfo.mChangeEnd};
}
return {newStart, newEnd, newRoot};
}
/******************************************************
* nsIMutationObserver implementation
******************************************************/
void nsRange::CharacterDataChanged(nsIContent* aContent,
const CharacterDataChangeInfo& aInfo) {
MOZ_ASSERT(aContent);
MOZ_ASSERT(mIsPositioned);
MOZ_ASSERT(!mNextEndRef);
MOZ_ASSERT(!mNextStartRef);
nsINode* newRoot = nullptr;
RawRangeBoundary newStart;
RawRangeBoundary newEnd;
if (aInfo.mDetails &&
aInfo.mDetails->mType == CharacterDataChangeInfo::Details::eSplit) {
AdjustNextRefsOnCharacterDataSplit(*aContent, aInfo);
}
// If the changed node contains our start boundary and the change starts
// before the boundary we'll need to adjust the offset.
if (aContent == mStart.Container() &&
aInfo.mChangeStart <
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets)) {
if (aInfo.mDetails) {
// splitText(), aInfo->mDetails->mNextSibling is the new text node
NS_ASSERTION(
aInfo.mDetails->mType == CharacterDataChangeInfo::Details::eSplit,
"only a split can start before the end");
NS_ASSERTION(
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <=
aInfo.mChangeEnd + 1,
"mStart.Offset() is beyond the end of this node");
const uint32_t newStartOffset =
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) -
aInfo.mChangeStart;
newStart = {aInfo.mDetails->mNextSibling, newStartOffset};
if (MOZ_UNLIKELY(aContent == mRoot)) {
newRoot = RangeUtils::ComputeRootNode(newStart.Container());
}
bool isCommonAncestor =
IsInSelection() && mStart.Container() == mEnd.Container();
if (isCommonAncestor) {
UnregisterClosestCommonInclusiveAncestor(mStart.Container(), false);
RegisterClosestCommonInclusiveAncestor(newStart.Container());
}
if (mStart.Container()
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
newStart.Container()
->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
}
} else {
// If boundary is inside changed text, position it before change
// else adjust start offset for the change in length.
CheckedUint32 newStartOffset{0};
if (*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <=
aInfo.mChangeEnd) {
newStartOffset = aInfo.mChangeStart;
} else {
newStartOffset =
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets);
newStartOffset -= aInfo.LengthOfRemovedText();
newStartOffset += aInfo.mReplaceLength;
}
// newStartOffset.isValid() isn't checked explicitly here, because
// newStartOffset.value() contains an assertion.
newStart = {mStart.Container(), newStartOffset.value()};
}
}
// Do the same thing for the end boundary, except for splitText of a node
// with no parent then only switch to the new node if the start boundary
// did so too (otherwise the range would end up with disconnected nodes).
if (aContent == mEnd.Container() &&
aInfo.mChangeStart <
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets)) {
if (aInfo.mDetails && (aContent->GetParentNode() || newStart.Container())) {
// splitText(), aInfo.mDetails->mNextSibling is the new text node
NS_ASSERTION(
aInfo.mDetails->mType == CharacterDataChangeInfo::Details::eSplit,
"only a split can start before the end");
MOZ_ASSERT(
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <=
aInfo.mChangeEnd + 1,
"mEnd.Offset() is beyond the end of this node");
const uint32_t newEndOffset{
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) -
aInfo.mChangeStart};
newEnd = {aInfo.mDetails->mNextSibling, newEndOffset};
bool isCommonAncestor =
IsInSelection() && mStart.Container() == mEnd.Container();
if (isCommonAncestor && !newStart.Container()) {
// The split occurs inside the range.
UnregisterClosestCommonInclusiveAncestor(mStart.Container(), false);
RegisterClosestCommonInclusiveAncestor(
mStart.Container()->GetParentNode());
newEnd.Container()
->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
} else if (
mEnd.Container()
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
newEnd.Container()
->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
}
} else {
CheckedUint32 newEndOffset{0};
if (*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets) <=
aInfo.mChangeEnd) {
newEndOffset = aInfo.mChangeStart;
} else {
newEndOffset =
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOrInvalidOffsets);
newEndOffset -= aInfo.LengthOfRemovedText();
newEndOffset += aInfo.mReplaceLength;
}
// newEndOffset.isValid() isn't checked explicitly here, because
// newEndOffset.value() contains an assertion.
newEnd = {mEnd.Container(), newEndOffset.value()};
}
}
if (aInfo.mDetails &&
aInfo.mDetails->mType == CharacterDataChangeInfo::Details::eMerge) {
MOZ_ASSERT(!newStart.IsSet());
MOZ_ASSERT(!newEnd.IsSet());
RangeBoundariesAndRoot rangeBoundariesAndRoot =
DetermineNewRangeBoundariesAndRootOnCharacterDataMerge(aContent, aInfo);
newStart = rangeBoundariesAndRoot.mStart;
newEnd = rangeBoundariesAndRoot.mEnd;
newRoot = rangeBoundariesAndRoot.mRoot;
}
if (newStart.IsSet() || newEnd.IsSet()) {
if (!newStart.IsSet()) {
newStart = mStart;
}
if (!newEnd.IsSet()) {
newEnd = mEnd;
}
DoSetRange(newStart, newEnd, newRoot ? newRoot : mRoot.get(),
!newEnd.Container()->GetParentNode() ||
!newStart.Container()->GetParentNode());
}
}
void nsRange::ContentAppended(nsIContent* aFirstNewContent) {
MOZ_ASSERT(mIsPositioned);
nsINode* container = aFirstNewContent->GetParentNode();
MOZ_ASSERT(container);
if (container->IsMaybeSelected() && IsInSelection()) {
nsINode* child = aFirstNewContent;
while (child) {
if (!child
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
MarkDescendants(child);
child
->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
}
child = child->GetNextSibling();
}
}
if (mNextStartRef || mNextEndRef) {
// A splitText has occurred, if any mNext*Ref was set, we need to adjust
// the range boundaries.
if (mNextStartRef) {
mStart = {mStart.Container(), mNextStartRef};
MOZ_ASSERT(mNextStartRef == aFirstNewContent);
mNextStartRef = nullptr;
}
if (mNextEndRef) {
mEnd = {mEnd.Container(), mNextEndRef};
MOZ_ASSERT(mNextEndRef == aFirstNewContent);
mNextEndRef = nullptr;
}
DoSetRange(mStart, mEnd, mRoot, true);
}
}
void nsRange::ContentInserted(nsIContent* aChild) {
MOZ_ASSERT(mIsPositioned);
bool updateBoundaries = false;
nsINode* container = aChild->GetParentNode();
MOZ_ASSERT(container);
RawRangeBoundary newStart(mStart);
RawRangeBoundary newEnd(mEnd);
MOZ_ASSERT(aChild->GetParentNode() == container);
// Invalidate boundary offsets if a child that may have moved them was
// inserted.
if (container == mStart.Container()) {
newStart.InvalidateOffset();
updateBoundaries = true;
}
if (container == mEnd.Container()) {
newEnd.InvalidateOffset();
updateBoundaries = true;
}
if (container->IsMaybeSelected() &&
!aChild
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
MarkDescendants(aChild);
aChild->SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
}
if (mNextStartRef || mNextEndRef) {
if (mNextStartRef) {
newStart = {mStart.Container(), mNextStartRef};
MOZ_ASSERT(mNextStartRef == aChild);
mNextStartRef = nullptr;
}
if (mNextEndRef) {
newEnd = {mEnd.Container(), mNextEndRef};
MOZ_ASSERT(mNextEndRef == aChild);
mNextEndRef = nullptr;
}
updateBoundaries = true;
}
if (updateBoundaries) {
DoSetRange(newStart, newEnd, mRoot);
}
}
void nsRange::ContentRemoved(nsIContent* aChild, nsIContent* aPreviousSibling) {
MOZ_ASSERT(mIsPositioned);
nsINode* container = aChild->GetParentNode();
MOZ_ASSERT(container);
RawRangeBoundary newStart;
RawRangeBoundary newEnd;
Maybe<bool> gravitateStart;
bool gravitateEnd;
// Adjust position if a sibling was removed...
if (container == mStart.Container()) {
// We're only interested if our boundary reference was removed, otherwise
// we can just invalidate the offset.
if (aChild == mStart.Ref()) {
newStart = {container, aPreviousSibling};
} else {
newStart = mStart;
newStart.InvalidateOffset();
}
} else {
gravitateStart = Some(mStart.Container()->IsInclusiveDescendantOf(aChild));
if (gravitateStart.value()) {
newStart = {container, aPreviousSibling};
}
}
// Do same thing for end boundry.
if (container == mEnd.Container()) {
if (aChild == mEnd.Ref()) {
newEnd = {container, aPreviousSibling};
} else {
newEnd = mEnd;
newEnd.InvalidateOffset();
}
} else {
if (mStart.Container() == mEnd.Container() && gravitateStart.isSome()) {
gravitateEnd = gravitateStart.value();
} else {
gravitateEnd = mEnd.Container()->IsInclusiveDescendantOf(aChild);
}
if (gravitateEnd) {
newEnd = {container, aPreviousSibling};
}
}
if (newStart.IsSet() || newEnd.IsSet()) {
DoSetRange(newStart.IsSet() ? newStart : mStart.AsRaw(),
newEnd.IsSet() ? newEnd : mEnd.AsRaw(), mRoot);
}
MOZ_ASSERT(mStart.Ref() != aChild);
MOZ_ASSERT(mEnd.Ref() != aChild);
if (container->IsMaybeSelected() &&
aChild
->IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection()) {
aChild
->ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection();
UnmarkDescendants(aChild);
}
}
void nsRange::ParentChainChanged(nsIContent* aContent) {
NS_ASSERTION(mRoot == aContent, "Wrong ParentChainChanged notification?");
nsINode* newRoot = RangeUtils::ComputeRootNode(mStart.Container());
NS_ASSERTION(newRoot, "No valid boundary or root found!");
if (newRoot != RangeUtils::ComputeRootNode(mEnd.Container())) {
// Sometimes ordering involved in cycle collection can lead to our
// start parent and/or end parent being disconnected from our root
// without our getting a ContentRemoved notification.
// See bug 846096 for more details.
NS_ASSERTION(mEnd.Container()->IsInNativeAnonymousSubtree(),
"This special case should happen only with "
"native-anonymous content");
// When that happens, bail out and set pointers to null; since we're
// in cycle collection and unreachable it shouldn't matter.
Reset();
return;
}
// This is safe without holding a strong ref to self as long as the change
// of mRoot is the last thing in DoSetRange.
DoSetRange(mStart, mEnd, newRoot);
}
bool nsRange::IsPointComparableToRange(const nsINode& aContainer,
uint32_t aOffset,
ErrorResult& aErrorResult) const {
// our range is in a good state?
if (!mIsPositioned) {
aErrorResult.Throw(NS_ERROR_NOT_INITIALIZED);
return false;
}
if (!aContainer.IsInclusiveDescendantOf(mRoot)) {
aErrorResult.Throw(NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
return false;
}
if (aContainer.NodeType() == nsINode::DOCUMENT_TYPE_NODE) {
aErrorResult.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return false;
}
if (aOffset > aContainer.Length()) {
aErrorResult.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return false;
}
return true;
}
bool nsRange::IsPointInRange(const nsINode& aContainer, uint32_t aOffset,
ErrorResult& aRv) const {
uint16_t compareResult = ComparePoint(aContainer, aOffset, aRv);
// If the node isn't in the range's document, it clearly isn't in the range.
if (aRv.ErrorCodeIs(NS_ERROR_DOM_WRONG_DOCUMENT_ERR)) {
aRv.SuppressException();
return false;
}
return compareResult == 0;
}
int16_t nsRange::ComparePoint(const nsINode& aContainer, uint32_t aOffset,
ErrorResult& aRv) const {
if (!IsPointComparableToRange(aContainer, aOffset, aRv)) {
return 0;
}
const RawRangeBoundary point{const_cast<nsINode*>(&aContainer), aOffset};
MOZ_ASSERT(point.IsSetAndValid());
Maybe<int32_t> order = nsContentUtils::ComparePoints(point, mStart);
// `order` must contain a value, because `IsPointComparableToRange()` was
// checked above.
if (*order <= 0) {
return *order;
}
order = nsContentUtils::ComparePoints(mEnd, point);
// `order` must contain a value, because `IsPointComparableToRange()` was
// checked above.
if (*order == -1) {
return 1;
}
return 0;
}
bool nsRange::IntersectsNode(nsINode& aNode, ErrorResult& aRv) {
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return false;
}
nsINode* parent = aNode.GetParentNode();
if (!parent) {
// |parent| is null, so |node|'s root is |node| itself.
return GetRoot() == &aNode;
}
const int32_t nodeIndex = parent->ComputeIndexOf(&aNode);
const Maybe<int32_t> startOrder = nsContentUtils::ComparePoints(
mStart.Container(),
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOffsets), parent,
nodeIndex + 1);
if (startOrder && (*startOrder < 0)) {
const Maybe<int32_t> endOrder = nsContentUtils::ComparePoints(
parent, nodeIndex, mEnd.Container(),
*mEnd.Offset(RangeBoundary::OffsetFilter::kValidOffsets));
return endOrder && (*endOrder < 0);
}
return false;
}
void nsRange::NotifySelectionListenersAfterRangeSet() {
if (mSelection) {
// Our internal code should not move focus with using this instance while
// it's calling Selection::NotifySelectionListeners() which may move focus
// or calls selection listeners. So, let's set mCalledByJS to false here
// since non-*JS() methods don't set it to false.
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = false;
// Be aware, this range may be modified or stop being a range for selection
// after this call. Additionally, the selection instance may have gone.
RefPtr<Selection> selection = mSelection.get();
selection->NotifySelectionListeners(calledByJSRestorer.SavedValue());
}
}
/******************************************************
* Private helper routines
******************************************************/
// It's important that all setting of the range start/end points
// go through this function, which will do all the right voodoo
// for content notification of range ownership.
// Calling DoSetRange with either parent argument null will collapse
// the range to have both endpoints point to the other node
template <typename SPT, typename SRT, typename EPT, typename ERT>
void nsRange::DoSetRange(const RangeBoundaryBase<SPT, SRT>& aStartBoundary,
const RangeBoundaryBase<EPT, ERT>& aEndBoundary,
nsINode* aRootNode,
bool aNotInsertedYet /* = false */) {
mIsPositioned = aStartBoundary.IsSetAndValid() &&
aEndBoundary.IsSetAndValid() && aRootNode;
MOZ_ASSERT(mIsPositioned || (!aStartBoundary.IsSet() &&
!aEndBoundary.IsSet() && !aRootNode),
"Set all or none");
MOZ_ASSERT(
!aRootNode || aNotInsertedYet ||
(aStartBoundary.Container()->IsInclusiveDescendantOf(aRootNode) &&
aEndBoundary.Container()->IsInclusiveDescendantOf(aRootNode) &&
aRootNode ==
RangeUtils::ComputeRootNode(aStartBoundary.Container()) &&
aRootNode == RangeUtils::ComputeRootNode(aEndBoundary.Container())),
"Wrong root");
MOZ_ASSERT(!aRootNode ||
(aStartBoundary.Container()->IsContent() &&
aEndBoundary.Container()->IsContent() &&
aRootNode ==
RangeUtils::ComputeRootNode(aStartBoundary.Container()) &&
aRootNode ==
RangeUtils::ComputeRootNode(aEndBoundary.Container())) ||
(!aRootNode->GetParentNode() &&
(aRootNode->IsDocument() || aRootNode->IsAttr() ||
aRootNode->IsDocumentFragment() ||
/*For backward compatibility*/
aRootNode->IsContent())),
"Bad root");
if (mRoot != aRootNode) {
if (mRoot) {
mRoot->RemoveMutationObserver(this);
}
if (aRootNode) {
aRootNode->AddMutationObserver(this);
}
}
bool checkCommonAncestor =
(mStart.Container() != aStartBoundary.Container() ||
mEnd.Container() != aEndBoundary.Container()) &&
IsInSelection() && !aNotInsertedYet;
// GetClosestCommonInclusiveAncestor is unreliable while we're unlinking
// (could return null if our start/end have already been unlinked), so make
// sure to not use it here to determine our "old" current ancestor.
mStart = aStartBoundary;
mEnd = aEndBoundary;
if (checkCommonAncestor) {
nsINode* oldCommonAncestor = mRegisteredClosestCommonInclusiveAncestor;
nsINode* newCommonAncestor = GetClosestCommonInclusiveAncestor();
if (newCommonAncestor != oldCommonAncestor) {
if (oldCommonAncestor) {
UnregisterClosestCommonInclusiveAncestor(oldCommonAncestor, false);
}
if (newCommonAncestor) {
RegisterClosestCommonInclusiveAncestor(newCommonAncestor);
} else {
NS_ASSERTION(!mIsPositioned, "unexpected disconnected nodes");
mSelection = nullptr;
MOZ_DIAGNOSTIC_ASSERT(
!mRegisteredClosestCommonInclusiveAncestor,
"How can we have a registered common ancestor when we "
"didn't register ourselves?");
MOZ_DIAGNOSTIC_ASSERT(!isInList(),
"Shouldn't be registered if we have no "
"mRegisteredClosestCommonInclusiveAncestor");
}
}
}
// This needs to be the last thing this function does, other than notifying
// selection listeners. See comment in ParentChainChanged.
mRoot = aRootNode;
// Notify any selection listeners. This has to occur last because otherwise
// the world could be observed by a selection listener while the range was in
// an invalid state. So we run it off of a script runner to ensure it runs
// after the mutation observers have finished running.
if (mSelection) {
nsContentUtils::AddScriptRunner(
NewRunnableMethod("NotifySelectionListenersAfterRangeSet", this,
&nsRange::NotifySelectionListenersAfterRangeSet));
}
}
static int32_t IndexOf(nsINode* aChild) {
nsINode* parent = aChild->GetParentNode();
return parent ? parent->ComputeIndexOf(aChild) : -1;
}
void nsRange::RegisterSelection(Selection& aSelection) {
// A range can belong to at most one Selection instance.
MOZ_ASSERT(!mSelection);
if (mSelection == &aSelection) {
return;
}
// Extra step in case our parent failed to ensure the above precondition.
if (mSelection) {
const RefPtr<nsRange> range{this};
const RefPtr<Selection> selection{mSelection};
selection->RemoveRangeAndUnselectFramesAndNotifyListeners(*range,
IgnoreErrors());
}
mSelection = &aSelection;
nsINode* commonAncestor = GetClosestCommonInclusiveAncestor();
MOZ_ASSERT(commonAncestor, "unexpected disconnected nodes");
RegisterClosestCommonInclusiveAncestor(commonAncestor);
}
void nsRange::UnregisterSelection() {
mSelection = nullptr;
if (mRegisteredClosestCommonInclusiveAncestor) {
UnregisterClosestCommonInclusiveAncestor(
mRegisteredClosestCommonInclusiveAncestor, false);
MOZ_DIAGNOSTIC_ASSERT(
!mRegisteredClosestCommonInclusiveAncestor,
"How can we have a registered common ancestor when we "
"just unregistered?");
MOZ_DIAGNOSTIC_ASSERT(
!isInList(),
"Shouldn't be registered if we have no "
"mRegisteredClosestCommonInclusiveAncestor after unregistering");
}
}
void nsRange::Reset() {
DoSetRange(RawRangeBoundary(), RawRangeBoundary(), nullptr);
}
/******************************************************
* public functionality
******************************************************/
void nsRange::SetStartJS(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetStart(aNode, aOffset, aErr);
}
bool nsRange::CanAccess(const nsINode& aNode) const {
if (nsContentUtils::LegacyIsCallerNativeCode()) {
return true;
}
return nsContentUtils::CanCallerAccess(&aNode);
}
void nsRange::SetStart(nsINode& aNode, uint32_t aOffset, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
SetStart(RawRangeBoundary(&aNode, aOffset), aRv);
}
void nsRange::SetStart(const RawRangeBoundary& aPoint, ErrorResult& aRv) {
nsINode* newRoot = RangeUtils::ComputeRootNode(aPoint.Container());
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
if (!aPoint.IsSetAndValid()) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
// Collapse if not positioned yet, if positioned in another doc or
// if the new start is after end.
const bool collapse = [&]() {
if (!mIsPositioned || (newRoot != mRoot)) {
return true;
}
const Maybe<int32_t> order = nsContentUtils::ComparePoints(aPoint, mEnd);
if (order) {
return *order == 1;
}
MOZ_ASSERT_UNREACHABLE();
return true;
}();
if (collapse) {
DoSetRange(aPoint, aPoint, newRoot);
return;
}
DoSetRange(aPoint, mEnd, mRoot);
}
void nsRange::SetStartBeforeJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetStartBefore(aNode, aErr);
}
void nsRange::SetStartBefore(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
// If the node is being removed from its parent, GetRawRangeBoundaryBefore()
// returns unset instance. Then, SetStart() will throw
// NS_ERROR_DOM_INVALID_NODE_TYPE_ERR.
SetStart(RangeUtils::GetRawRangeBoundaryBefore(&aNode), aRv);
}
void nsRange::SetStartAfterJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetStartAfter(aNode, aErr);
}
void nsRange::SetStartAfter(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
// If the node is being removed from its parent, GetRawRangeBoundaryAfter()
// returns unset instance. Then, SetStart() will throw
// NS_ERROR_DOM_INVALID_NODE_TYPE_ERR.
SetStart(RangeUtils::GetRawRangeBoundaryAfter(&aNode), aRv);
}
void nsRange::SetEndJS(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetEnd(aNode, aOffset, aErr);
}
void nsRange::SetEnd(nsINode& aNode, uint32_t aOffset, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
SetEnd(RawRangeBoundary(&aNode, aOffset), aRv);
}
void nsRange::SetEnd(const RawRangeBoundary& aPoint, ErrorResult& aRv) {
nsINode* newRoot = RangeUtils::ComputeRootNode(aPoint.Container());
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
if (!aPoint.IsSetAndValid()) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
// Collapse if not positioned yet, if positioned in another doc or
// if the new end is before start.
const bool collapse = [&]() {
if (!mIsPositioned || (newRoot != mRoot)) {
return true;
}
const Maybe<int32_t> order = nsContentUtils::ComparePoints(mStart, aPoint);
if (order) {
return *order == 1;
}
MOZ_ASSERT_UNREACHABLE();
return true;
}();
if (collapse) {
DoSetRange(aPoint, aPoint, newRoot);
return;
}
DoSetRange(mStart, aPoint, mRoot);
}
void nsRange::SelectNodesInContainer(nsINode* aContainer,
nsIContent* aStartContent,
nsIContent* aEndContent) {
MOZ_ASSERT(aContainer);
MOZ_ASSERT(aContainer->ComputeIndexOf(aStartContent) <=
aContainer->ComputeIndexOf(aEndContent));
MOZ_ASSERT(aStartContent && aContainer->ComputeIndexOf(aStartContent) != -1);
MOZ_ASSERT(aEndContent && aContainer->ComputeIndexOf(aEndContent) != -1);
nsINode* newRoot = RangeUtils::ComputeRootNode(aContainer);
MOZ_ASSERT(newRoot);
if (!newRoot) {
return;
}
RawRangeBoundary start(aContainer, aStartContent->GetPreviousSibling());
RawRangeBoundary end(aContainer, aEndContent);
DoSetRange(start, end, newRoot);
}
void nsRange::SetEndBeforeJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetEndBefore(aNode, aErr);
}
void nsRange::SetEndBefore(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
// If the node is being removed from its parent, GetRawRangeBoundaryBefore()
// returns unset instance. Then, SetEnd() will throw
// NS_ERROR_DOM_INVALID_NODE_TYPE_ERR.
SetEnd(RangeUtils::GetRawRangeBoundaryBefore(&aNode), aRv);
}
void nsRange::SetEndAfterJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SetEndAfter(aNode, aErr);
}
void nsRange::SetEndAfter(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
// If the node is being removed from its parent, GetRawRangeBoundaryAfter()
// returns unset instance. Then, SetEnd() will throw
// NS_ERROR_DOM_INVALID_NODE_TYPE_ERR.
SetEnd(RangeUtils::GetRawRangeBoundaryAfter(&aNode), aRv);
}
void nsRange::Collapse(bool aToStart) {
if (!mIsPositioned) return;
AutoInvalidateSelection atEndOfBlock(this);
if (aToStart) {
DoSetRange(mStart, mStart, mRoot);
} else {
DoSetRange(mEnd, mEnd, mRoot);
}
}
void nsRange::CollapseJS(bool aToStart) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
Collapse(aToStart);
}
void nsRange::SelectNodeJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SelectNode(aNode, aErr);
}
void nsRange::SelectNode(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
nsINode* container = aNode.GetParentNode();
nsINode* newRoot = RangeUtils::ComputeRootNode(container);
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
int32_t index = container->ComputeIndexOf(&aNode);
// MOZ_ASSERT(index != -1);
// We need to compute the index here unfortunately, because, while we have
// support for XBL, |container| may be the node's binding parent without
// actually containing it.
if (NS_WARN_IF(index < 0)) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
DoSetRange(RawRangeBoundary{container, static_cast<uint32_t>(index)},
RawRangeBoundary{container, static_cast<uint32_t>(index + 1)},
newRoot);
}
void nsRange::SelectNodeContentsJS(nsINode& aNode, ErrorResult& aErr) {
AutoCalledByJSRestore calledByJSRestorer(*this);
mCalledByJS = true;
SelectNodeContents(aNode, aErr);
}
void nsRange::SelectNodeContents(nsINode& aNode, ErrorResult& aRv) {
if (!CanAccess(aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
nsINode* newRoot = RangeUtils::ComputeRootNode(&aNode);
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
DoSetRange(RawRangeBoundary(&aNode, 0u),
RawRangeBoundary(&aNode, aNode.Length()), newRoot);
}
// The Subtree Content Iterator only returns subtrees that are
// completely within a given range. It doesn't return a CharacterData
// node that contains either the start or end point of the range.,
// nor does it return element nodes when nothing in the element is selected.
// We need an iterator that will also include these start/end points
// so that our methods/algorithms aren't cluttered with special
// case code that tries to include these points while iterating.
//
// The RangeSubtreeIterator class mimics the ContentSubtreeIterator
// methods we need, so should the Content Iterator support the
// start/end points in the future, we can switchover relatively
// easy.
class MOZ_STACK_CLASS RangeSubtreeIterator {
private:
enum RangeSubtreeIterState { eDone = 0, eUseStart, eUseIterator, eUseEnd };
Maybe<ContentSubtreeIterator> mSubtreeIter;
RangeSubtreeIterState mIterState;
nsCOMPtr<nsINode> mStart;
nsCOMPtr<nsINode> mEnd;
public:
RangeSubtreeIterator() : mIterState(eDone) {}
~RangeSubtreeIterator() = default;
nsresult Init(nsRange* aRange);
already_AddRefed<nsINode> GetCurrentNode();
void First();
void Last();
void Next();
void Prev();
bool IsDone() { return mIterState == eDone; }
};
nsresult RangeSubtreeIterator::Init(nsRange* aRange) {
mIterState = eDone;
if (aRange->Collapsed()) {
return NS_OK;
}
// Grab the start point of the range and QI it to
// a CharacterData pointer. If it is CharacterData store
// a pointer to the node.
if (!aRange->IsPositioned()) {
return NS_ERROR_FAILURE;
}
nsINode* node = aRange->GetStartContainer();
if (NS_WARN_IF(!node)) {
return NS_ERROR_FAILURE;
}
if (node->IsCharacterData() ||
(node->IsElement() &&
node->AsElement()->GetChildCount() == aRange->StartOffset())) {
mStart = node;
}
// Grab the end point of the range and QI it to
// a CharacterData pointer. If it is CharacterData store
// a pointer to the node.
node = aRange->GetEndContainer();
if (NS_WARN_IF(!node)) {
return NS_ERROR_FAILURE;
}
if (node->IsCharacterData() ||
(node->IsElement() && aRange->EndOffset() == 0)) {
mEnd = node;
}
if (mStart && mStart == mEnd) {
// The range starts and stops in the same CharacterData
// node. Null out the end pointer so we only visit the
// node once!
mEnd = nullptr;
} else {
// Now create a Content Subtree Iterator to be used
// for the subtrees between the end points!
mSubtreeIter.emplace();
nsresult res = mSubtreeIter->Init(aRange);
if (NS_FAILED(res)) return res;
if (mSubtreeIter->IsDone()) {
// The subtree iterator thinks there's nothing
// to iterate over, so just free it up so we
// don't accidentally call into it.
mSubtreeIter.reset();
}
}
// Initialize the iterator by calling First().
// Note that we are ignoring the return value on purpose!
First();
return NS_OK;
}
already_AddRefed<nsINode> RangeSubtreeIterator::GetCurrentNode() {
nsCOMPtr<nsINode> node;
if (mIterState == eUseStart && mStart) {
node = mStart;
} else if (mIterState == eUseEnd && mEnd) {
node = mEnd;
} else if (mIterState == eUseIterator && mSubtreeIter) {
node = mSubtreeIter->GetCurrentNode();
}
return node.forget();
}
void RangeSubtreeIterator::First() {
if (mStart)
mIterState = eUseStart;
else if (mSubtreeIter) {
mSubtreeIter->First();
mIterState = eUseIterator;
} else if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
}
void RangeSubtreeIterator::Last() {
if (mEnd)
mIterState = eUseEnd;
else if (mSubtreeIter) {
mSubtreeIter->Last();
mIterState = eUseIterator;
} else if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
}
void RangeSubtreeIterator::Next() {
if (mIterState == eUseStart) {
if (mSubtreeIter) {
mSubtreeIter->First();
mIterState = eUseIterator;
} else if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
} else if (mIterState == eUseIterator) {
mSubtreeIter->Next();
if (mSubtreeIter->IsDone()) {
if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
}
} else
mIterState = eDone;
}
void RangeSubtreeIterator::Prev() {
if (mIterState == eUseEnd) {
if (mSubtreeIter) {
mSubtreeIter->Last();
mIterState = eUseIterator;
} else if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
} else if (mIterState == eUseIterator) {
mSubtreeIter->Prev();
if (mSubtreeIter->IsDone()) {
if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
}
} else
mIterState = eDone;
}
// CollapseRangeAfterDelete() is a utility method that is used by
// DeleteContents() and ExtractContents() to collapse the range
// in the correct place, under the range's root container (the
// range end points common container) as outlined by the Range spec:
//
// The assumption made by this method is that the delete or extract
// has been done already, and left the range in a state where there is
// no content between the 2 end points.
static nsresult CollapseRangeAfterDelete(nsRange* aRange) {
NS_ENSURE_ARG_POINTER(aRange);
// Check if range gravity took care of collapsing the range for us!
if (aRange->Collapsed()) {
// aRange is collapsed so there's nothing for us to do.
//
// There are 2 possible scenarios here:
//
// 1. aRange could've been collapsed prior to the delete/extract,
// which would've resulted in nothing being removed, so aRange
// is already where it should be.
//
// 2. Prior to the delete/extract, aRange's start and end were in
// the same container which would mean everything between them
// was removed, causing range gravity to collapse the range.
return NS_OK;
}
// aRange isn't collapsed so figure out the appropriate place to collapse!
// First get both end points and their common ancestor.
if (!aRange->IsPositioned()) {
return NS_ERROR_NOT_INITIALIZED;
}
nsCOMPtr<nsINode> commonAncestor =
aRange->GetClosestCommonInclusiveAncestor();
nsCOMPtr<nsINode> startContainer = aRange->GetStartContainer();
nsCOMPtr<nsINode> endContainer = aRange->GetEndContainer();
// Collapse to one of the end points if they are already in the
// commonAncestor. This should work ok since this method is called
// immediately after a delete or extract that leaves no content
// between the 2 end points!
if (startContainer == commonAncestor) {
aRange->Collapse(true);
return NS_OK;
}
if (endContainer == commonAncestor) {
aRange->Collapse(false);
return NS_OK;
}
// End points are at differing levels. We want to collapse to the
// point that is between the 2 subtrees that contain each point,
// under the common ancestor.
nsCOMPtr<nsINode> nodeToSelect(startContainer);
while (nodeToSelect) {
nsCOMPtr<nsINode> parent = nodeToSelect->GetParentNode();
if (parent == commonAncestor) break; // We found the nodeToSelect!
nodeToSelect = parent;
}
if (!nodeToSelect) return NS_ERROR_FAILURE; // This should never happen!
ErrorResult error;
aRange->SelectNode(*nodeToSelect, error);
if (error.Failed()) {
return error.StealNSResult();
}
aRange->Collapse(false);
return NS_OK;
}
NS_IMETHODIMP
PrependChild(nsINode* aContainer, nsINode* aChild) {
nsCOMPtr<nsINode> first = aContainer->GetFirstChild();
ErrorResult rv;
aContainer->InsertBefore(*aChild, first, rv);
return rv.StealNSResult();
}
// Helper function for CutContents, making sure that the current node wasn't
// removed by mutation events (bug 766426)
static bool ValidateCurrentNode(nsRange* aRange, RangeSubtreeIterator& aIter) {
bool before, after;
nsCOMPtr<nsINode> node = aIter.GetCurrentNode();
if (!node) {
// We don't have to worry that the node was removed if it doesn't exist,
// e.g., the iterator is done.
return true;
}
nsresult rv = RangeUtils::CompareNodeToRange(node, aRange, &before, &after);
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
if (before || after) {
if (node->IsCharacterData()) {
// If we're dealing with the start/end container which is a character
// node, pretend that the node is in the range.
if (before && node == aRange->GetStartContainer()) {
before = false;
}
if (after && node == aRange->GetEndContainer()) {
after = false;
}
}
}
return !before && !after;
}
nsresult nsRange::CutContents(DocumentFragment** aFragment) {
if (aFragment) {
*aFragment = nullptr;
}
if (!CanAccess(*mStart.Container()) || !CanAccess(*mEnd.Container())) {
return NS_ERROR_DOM_SECURITY_ERR;
}
nsCOMPtr<Document> doc = mStart.Container()->OwnerDoc();
ErrorResult res;
nsCOMPtr<nsINode> commonAncestor = GetCommonAncestorContainer(res);
NS_ENSURE_TRUE(!res.Failed(), res.StealNSResult());
// If aFragment isn't null, create a temporary fragment to hold our return.
RefPtr<DocumentFragment> retval;
if (aFragment) {
retval =
new (doc->NodeInfoManager()) DocumentFragment(doc->NodeInfoManager());
}
nsCOMPtr<nsINode> commonCloneAncestor = retval.get();
// Batch possible DOMSubtreeModified events.
mozAutoSubtreeModified subtree(mRoot ? mRoot->OwnerDoc() : nullptr, nullptr);
// Save the range end points locally to avoid interference
// of Range gravity during our edits!
nsCOMPtr<nsINode> startContainer = mStart.Container();
// `GetCommonAncestorContainer()` above ensures the range is positioned, hence
// there have to be valid offsets.
uint32_t startOffset =
*mStart.Offset(RangeBoundary::OffsetFilter::kValidOffsets);
nsCOMPtr<nsINode> endContainer = mEnd.Container();
uint32_t endOffset = *mEnd.Offset(RangeBoundary::OffsetFilter::kValidOffsets);
if (retval) {
// For extractContents(), abort early if there's a doctype (bug 719533).
// This can happen only if the common ancestor is a document, in which case
// we just need to find its doctype child and check if that's in the range.
nsCOMPtr<Document> commonAncestorDocument =
do_QueryInterface(commonAncestor);
if (commonAncestorDocument) {
RefPtr<DocumentType> doctype = commonAncestorDocument->GetDoctype();
// `GetCommonAncestorContainer()` above ensured the range is positioned.
// Hence, start and end are both set and valid. If available, `doctype`
// has a common ancestor with start and end, hence both have to be
// comparable to it.
if (doctype &&
*nsContentUtils::ComparePoints(startContainer,
static_cast<int32_t>(startOffset),
doctype, 0) < 0 &&
*nsContentUtils::ComparePoints(doctype, 0, endContainer,
static_cast<int32_t>(endOffset)) < 0) {
return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
}
}
}
// Create and initialize a subtree iterator that will give
// us all the subtrees within the range.
RangeSubtreeIterator iter;
nsresult rv = iter.Init(this);
if (NS_FAILED(rv)) return rv;
if (iter.IsDone()) {
// There's nothing for us to delete.
rv = CollapseRangeAfterDelete(this);
if (NS_SUCCEEDED(rv) && aFragment) {
retval.forget(aFragment);
}
return rv;
}
iter.First();
bool handled = false;
// With the exception of text nodes that contain one of the range
// end points, the subtree iterator should only give us back subtrees
// that are completely contained between the range's end points.
while (!iter.IsDone()) {
nsCOMPtr<nsINode> nodeToResult;
nsCOMPtr<nsINode> node = iter.GetCurrentNode();
// Before we delete anything, advance the iterator to the next node that's
// not a descendant of this one. XXX It's a bit silly to iterate through
// the descendants only to throw them out, we should use an iterator that
// skips the descendants to begin with.
iter.Next();
nsCOMPtr<nsINode> nextNode = iter.GetCurrentNode();
while (nextNode && nextNode->IsInclusiveDescendantOf(node)) {
iter.Next();
nextNode = iter.GetCurrentNode();
}
handled = false;
// If it's CharacterData, make sure we might need to delete
// part of the data, instead of removing the whole node.
//
// XXX_kin: We need to also handle ProcessingInstruction
// XXX_kin: according to the spec.
if (auto charData = CharacterData::FromNode(node)) {
uint32_t dataLength = 0;
if (node == startContainer) {
if (node == endContainer) {
// This range is completely contained within a single text node.
// Delete or extract the data between startOffset and endOffset.
if (endOffset > startOffset) {
if (retval) {
nsAutoString cutValue;
ErrorResult err;
charData->SubstringData(startOffset, endOffset - startOffset,
cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nsCOMPtr<nsINode> clone = node->CloneNode(false, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
clone->SetNodeValue(cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nodeToResult = clone;
}
nsMutationGuard guard;
ErrorResult err;
charData->DeleteData(startOffset, endOffset - startOffset, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
NS_ENSURE_STATE(!guard.Mutated(0) ||
ValidateCurrentNode(this, iter));
}
handled = true;
} else {
// Delete or extract everything after startOffset.
dataLength = charData->Length();
if (dataLength >= startOffset) {
if (retval) {
nsAutoString cutValue;
ErrorResult err;
charData->SubstringData(startOffset, dataLength, cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nsCOMPtr<nsINode> clone = node->CloneNode(false, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
clone->SetNodeValue(cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nodeToResult = clone;
}
nsMutationGuard guard;
ErrorResult err;
charData->DeleteData(startOffset, dataLength, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_STATE(!guard.Mutated(0) ||
ValidateCurrentNode(this, iter));
}
handled = true;
}
} else if (node == endContainer) {
// Delete or extract everything before endOffset.
if (retval) {
nsAutoString cutValue;
ErrorResult err;
charData->SubstringData(0, endOffset, cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nsCOMPtr<nsINode> clone = node->CloneNode(false, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
clone->SetNodeValue(cutValue, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
nodeToResult = clone;
}
nsMutationGuard guard;
ErrorResult err;
charData->DeleteData(0, endOffset, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
NS_ENSURE_STATE(!guard.Mutated(0) || ValidateCurrentNode(this, iter));
handled = true;
}
}
if (!handled && (node == endContainer || node == startContainer)) {
if (node && node->IsElement() &&
((node == endContainer && endOffset == 0) ||
(node == startContainer &&
node->AsElement()->GetChildCount() == startOffset))) {
if (retval) {
ErrorResult rv;
nodeToResult = node->CloneNode(false, rv);
NS_ENSURE_TRUE(!rv.Failed(), rv.StealNSResult());
}
handled = true;
}
}
if (!handled) {
// node was not handled above, so it must be completely contained
// within the range. Just remove it from the tree!
nodeToResult = node;
}
uint32_t parentCount = 0;
// Set the result to document fragment if we have 'retval'.
if (retval) {
nsCOMPtr<nsINode> oldCommonAncestor = commonAncestor;
if (!iter.IsDone()) {
// Setup the parameters for the next iteration of the loop.
NS_ENSURE_STATE(nextNode);
// Get node's and nextNode's common parent. Do this before moving
// nodes from original DOM to result fragment.
commonAncestor =
nsContentUtils::GetClosestCommonInclusiveAncestor(node, nextNode);
NS_ENSURE_STATE(commonAncestor);
nsCOMPtr<nsINode> parentCounterNode = node;
while (parentCounterNode && parentCounterNode != commonAncestor) {
++parentCount;
parentCounterNode = parentCounterNode->GetParentNode();
NS_ENSURE_STATE(parentCounterNode);
}
}
// Clone the parent hierarchy between commonAncestor and node.
nsCOMPtr<nsINode> closestAncestor, farthestAncestor;
rv = CloneParentsBetween(oldCommonAncestor, node,
getter_AddRefs(closestAncestor),
getter_AddRefs(farthestAncestor));
NS_ENSURE_SUCCESS(rv, rv);
ErrorResult res;
if (farthestAncestor) {
commonCloneAncestor->AppendChild(*farthestAncestor, res);
res.WouldReportJSException();
if (NS_WARN_IF(res.Failed())) {
return res.StealNSResult();
}
}
nsMutationGuard guard;
nsCOMPtr<nsINode> parent = nodeToResult->GetParentNode();
if (closestAncestor) {
closestAncestor->AppendChild(*nodeToResult, res);
} else {
commonCloneAncestor->AppendChild(*nodeToResult, res);
}
res.WouldReportJSException();
if (NS_WARN_IF(res.Failed())) {
return res.StealNSResult();
}
NS_ENSURE_STATE(!guard.Mutated(parent ? 2 : 1) ||
ValidateCurrentNode(this, iter));
} else if (nodeToResult) {
nsMutationGuard guard;
nsCOMPtr<nsINode> node = nodeToResult;
nsCOMPtr<nsINode> parent = node->GetParentNode();
if (parent) {
mozilla::ErrorResult error;
parent->RemoveChild(*node, error);
NS_ENSURE_FALSE(error.Failed(), error.StealNSResult());
}
NS_ENSURE_STATE(!guard.Mutated(1) || ValidateCurrentNode(this, iter));
}
if (!iter.IsDone() && retval) {
// Find the equivalent of commonAncestor in the cloned tree.
nsCOMPtr<nsINode> newCloneAncestor = nodeToResult;
for (uint32_t i = parentCount; i; --i) {
newCloneAncestor = newCloneAncestor->GetParentNode();
NS_ENSURE_STATE(newCloneAncestor);
}
commonCloneAncestor = newCloneAncestor;
}
}
rv = CollapseRangeAfterDelete(this);
if (NS_SUCCEEDED(rv) && aFragment) {
retval.forget(aFragment);
}
return rv;
}
void nsRange::DeleteContents(ErrorResult& aRv) { aRv = CutContents(nullptr); }
already_AddRefed<DocumentFragment> nsRange::ExtractContents(ErrorResult& rv) {
RefPtr<DocumentFragment> fragment;
rv = CutContents(getter_AddRefs(fragment));
return fragment.forget();
}
int16_t nsRange::CompareBoundaryPoints(uint16_t aHow,
const nsRange& aOtherRange,
ErrorResult& aRv) {
if (!mIsPositioned || !aOtherRange.IsPositioned()) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
nsINode *ourNode, *otherNode;
uint32_t ourOffset, otherOffset;
switch (aHow) {
case Range_Binding::START_TO_START:
ourNode = mStart.Container();
ourOffset = *mStart.Offset(RangeBoundary::OffsetFilter::kValidOffsets);
otherNode = aOtherRange.GetStartContainer();
otherOffset = aOtherRange.StartOffset();
break;
case Range_Binding::START_TO_END:
ourNode = mEnd.Container();