1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef mozilla_EditorDOMPoint_h
7 #define mozilla_EditorDOMPoint_h
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Attributes.h"
11 #include "mozilla/EditorForwards.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/RangeBoundary.h"
14 #include "mozilla/ToString.h"
15 #include "mozilla/dom/AbstractRange.h"
16 #include "mozilla/dom/Element.h"
17 #include "mozilla/dom/Selection.h" // for Selection::InterlinePosition
18 #include "mozilla/dom/Text.h"
21 #include "nsContentUtils.h"
23 #include "nsGkAtoms.h"
24 #include "nsIContent.h"
26 #include "nsStyledElement.h"
28 #include <type_traits>
33 * EditorDOMPoint and EditorRawDOMPoint are simple classes which refers
34 * a point in the DOM tree at creating the instance or initializing the
35 * instance with calling Set().
37 * EditorDOMPoint refers container node (and child node if it's already set)
38 * with nsCOMPtr. EditorRawDOMPoint refers them with raw pointer.
39 * So, EditorRawDOMPoint is useful when you access the nodes only before
40 * changing DOM tree since increasing refcount may appear in micro benchmark
41 * if it's in a hot path. On the other hand, if you need to refer them even
42 * after changing DOM tree, you must use EditorDOMPoint.
44 * When initializing an instance only with child node or offset, the instance
45 * starts to refer the child node or offset in the container. In this case,
46 * the other information hasn't been initialized due to performance reason.
47 * When you retrieve the other information with calling Offset() or
48 * GetChild(), the other information is computed with the current DOM tree.
49 * Therefore, e.g., in the following case, the other information may be
52 * EditorDOMPoint pointA(container1, childNode1);
53 * EditorDOMPoint pointB(container1, childNode1);
54 * Unused << pointA.Offset(); // The offset is computed now.
55 * container1->RemoveChild(childNode1->GetPreviousSibling());
56 * Unused << pointB.Offset(); // Now, pointB.Offset() equals pointA.Offset() - 1
60 * EditorDOMPoint pointA(container1, 5);
61 * EditorDOMPoint pointB(container1, 5);
62 * Unused << pointA.GetChild(); // The child is computed now.
63 * container1->RemoveChild(childNode1->GetFirstChild());
64 * Unused << pointB.GetChild(); // Now, pointB.GetChild() equals
65 * // pointA.GetChild()->GetPreviousSibling().
67 * So, when you initialize an instance only with one information, you need to
68 * be careful when you access the other information after changing the DOM tree.
69 * When you need to lock the child node or offset and recompute the other
70 * information with new DOM tree, you can use
71 * AutoEditorDOMPointOffsetInvalidator and AutoEditorDOMPointChildInvalidator.
74 // FYI: Don't make the following instantiating macros end with `;` because
75 // using them without `;`, VSCode may be confused and cause wrong red-
76 // wavy underlines in the following code of the macro.
77 #define NS_INSTANTIATE_EDITOR_DOM_POINT_METHOD(aResultType, aMethodName, ...) \
78 template aResultType EditorDOMPoint::aMethodName(__VA_ARGS__); \
79 template aResultType EditorRawDOMPoint::aMethodName(__VA_ARGS__); \
80 template aResultType EditorDOMPointInText::aMethodName(__VA_ARGS__); \
81 template aResultType EditorRawDOMPointInText::aMethodName(__VA_ARGS__)
83 #define NS_INSTANTIATE_EDITOR_DOM_POINT_CONST_METHOD(aResultType, aMethodName, \
85 template aResultType EditorDOMPoint::aMethodName(__VA_ARGS__) const; \
86 template aResultType EditorRawDOMPoint::aMethodName(__VA_ARGS__) const; \
87 template aResultType EditorDOMPointInText::aMethodName(__VA_ARGS__) const; \
88 template aResultType EditorRawDOMPointInText::aMethodName(__VA_ARGS__) const
90 #define NS_INSTANTIATE_METHOD_RETURNING_ANY_EDITOR_DOM_POINT(aMethodName, ...) \
91 template EditorDOMPoint aMethodName(__VA_ARGS__); \
92 template EditorRawDOMPoint aMethodName(__VA_ARGS__); \
93 template EditorDOMPointInText aMethodName(__VA_ARGS__); \
94 template EditorRawDOMPointInText aMethodName(__VA_ARGS__)
96 #define NS_INSTANTIATE_CONST_METHOD_RETURNING_ANY_EDITOR_DOM_POINT( \
98 template EditorDOMPoint aMethodName(__VA_ARGS__) const; \
99 template EditorRawDOMPoint aMethodName(__VA_ARGS__) const; \
100 template EditorDOMPointInText aMethodName(__VA_ARGS__) const; \
101 template EditorRawDOMPointInText aMethodName(__VA_ARGS__) const
103 template <typename ParentType
, typename ChildType
>
104 class EditorDOMPointBase final
{
105 using SelfType
= EditorDOMPointBase
<ParentType
, ChildType
>;
108 using InterlinePosition
= dom::Selection::InterlinePosition
;
110 EditorDOMPointBase() = default;
112 template <typename ContainerType
>
114 const ContainerType
* aContainer
, uint32_t aOffset
,
115 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
)
116 : mParent(const_cast<ContainerType
*>(aContainer
)),
118 mOffset(Some(aOffset
)),
119 mInterlinePosition(aInterlinePosition
) {
120 NS_WARNING_ASSERTION(
121 !mParent
|| mOffset
.value() <= mParent
->Length(),
122 "The offset is larger than the length of aContainer or negative");
128 template <typename ContainerType
, template <typename
> typename StrongPtr
>
130 const StrongPtr
<ContainerType
>& aContainer
, uint32_t aOffset
,
131 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
)
132 : EditorDOMPointBase(aContainer
.get(), aOffset
, aInterlinePosition
) {}
134 template <typename ContainerType
, template <typename
> typename StrongPtr
>
136 const StrongPtr
<const ContainerType
>& aContainer
, uint32_t aOffset
,
137 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
)
138 : EditorDOMPointBase(aContainer
.get(), aOffset
, aInterlinePosition
) {}
141 * Different from RangeBoundary, aPointedNode should be a child node
142 * which you want to refer.
144 explicit EditorDOMPointBase(
145 const nsINode
* aPointedNode
,
146 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
)
147 : mParent(aPointedNode
&& aPointedNode
->IsContent()
148 ? aPointedNode
->GetParentNode()
150 mChild(aPointedNode
&& aPointedNode
->IsContent()
151 ? const_cast<nsIContent
*>(aPointedNode
->AsContent())
153 mInterlinePosition(aInterlinePosition
) {
154 mIsChildInitialized
= aPointedNode
&& mChild
;
155 NS_WARNING_ASSERTION(IsSet(),
156 "The child is nullptr or doesn't have its parent");
157 NS_WARNING_ASSERTION(mChild
&& mChild
->GetParentNode() == mParent
,
158 "Initializing RangeBoundary with invalid value");
162 nsINode
* aContainer
, nsIContent
* aPointedNode
, uint32_t aOffset
,
163 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
)
164 : mParent(aContainer
),
165 mChild(aPointedNode
),
166 mOffset(mozilla::Some(aOffset
)),
167 mInterlinePosition(aInterlinePosition
),
168 mIsChildInitialized(true) {
169 MOZ_DIAGNOSTIC_ASSERT(
170 aContainer
, "This constructor shouldn't be used when pointing nowhere");
171 MOZ_ASSERT(mOffset
.value() <= mParent
->Length());
172 MOZ_ASSERT(mChild
|| mParent
->Length() == mOffset
.value() ||
173 !mParent
->IsContainerNode());
174 MOZ_ASSERT(!mChild
|| mParent
== mChild
->GetParentNode());
175 MOZ_ASSERT(mParent
->GetChildAt_Deprecated(mOffset
.value()) == mChild
);
178 template <typename PT
, typename CT
>
179 explicit EditorDOMPointBase(const RangeBoundaryBase
<PT
, CT
>& aOther
)
180 : mParent(aOther
.mParent
),
181 mChild(aOther
.mRef
? aOther
.mRef
->GetNextSibling()
182 : (aOther
.mParent
? aOther
.mParent
->GetFirstChild()
184 mOffset(aOther
.mOffset
),
185 mIsChildInitialized(aOther
.mRef
|| (aOther
.mOffset
.isSome() &&
186 !aOther
.mOffset
.value())) {}
188 void SetInterlinePosition(InterlinePosition aInterlinePosition
) {
190 mInterlinePosition
= aInterlinePosition
;
192 InterlinePosition
GetInterlinePosition() const {
193 return IsSet() ? mInterlinePosition
: InterlinePosition::Undefined
;
197 * GetContainer() returns the container node at the point.
198 * GetContainerAs() returns the container node as specific type.
200 nsINode
* GetContainer() const { return mParent
; }
201 template <typename ContentNodeType
>
202 ContentNodeType
* GetContainerAs() const {
203 return ContentNodeType::FromNodeOrNull(mParent
);
207 * ContainerAs() returns the container node with just casting to the specific
208 * type. Therefore, callers need to guarantee that the result is not nullptr
211 template <typename ContentNodeType
>
212 ContentNodeType
* ContainerAs() const {
214 MOZ_DIAGNOSTIC_ASSERT(
215 ContentNodeType::FromNode(static_cast<const nsINode
*>(mParent
)));
216 return static_cast<ContentNodeType
*>(GetContainer());
220 * GetContainerParent() returns parent of the container node at the point.
222 nsINode
* GetContainerParent() const {
223 return mParent
? mParent
->GetParent() : nullptr;
225 template <typename ContentNodeType
>
226 ContentNodeType
* GetContainerParentAs() const {
227 return ContentNodeType::FromNodeOrNull(GetContainerParent());
229 template <typename ContentNodeType
>
230 ContentNodeType
* ContainerParentAs() const {
231 MOZ_DIAGNOSTIC_ASSERT(GetContainerParentAs
<ContentNodeType
>());
232 return static_cast<ContentNodeType
*>(GetContainerParent());
235 dom::Element
* GetContainerOrContainerParentElement() const {
236 if (MOZ_UNLIKELY(!mParent
)) {
239 return mParent
->IsElement() ? ContainerAs
<dom::Element
>()
240 : GetContainerParentAs
<dom::Element
>();
244 * CanContainerHaveChildren() returns true if the container node can have
245 * child nodes. Otherwise, e.g., when the container is a text node, returns
248 bool CanContainerHaveChildren() const {
249 return mParent
&& mParent
->IsContainerNode();
253 * IsContainerEmpty() returns true if it has no children or its text is empty.
255 bool IsContainerEmpty() const { return mParent
&& !mParent
->Length(); }
258 * IsInContentNode() returns true if the container is a subclass of
261 bool IsInContentNode() const { return mParent
&& mParent
->IsContent(); }
264 * IsInDataNode() returns true if the container node is a data node including
267 bool IsInDataNode() const { return mParent
&& mParent
->IsCharacterData(); }
270 * IsInTextNode() returns true if the container node is a text node.
272 bool IsInTextNode() const { return mParent
&& mParent
->IsText(); }
275 * IsInNativeAnonymousSubtree() returns true if the container is in
276 * native anonymous subtree.
278 bool IsInNativeAnonymousSubtree() const {
279 return mParent
&& mParent
->IsInNativeAnonymousSubtree();
283 * Returns true if the container node is an element node.
285 bool IsContainerElement() const { return mParent
&& mParent
->IsElement(); }
288 * Returns true if the container node is an editing host.
290 [[nodiscard
]] bool IsContainerEditableRoot() const;
293 * IsContainerHTMLElement() returns true if the container node is an HTML
294 * element node and its node name is aTag.
296 bool IsContainerHTMLElement(nsAtom
* aTag
) const {
297 return mParent
&& mParent
->IsHTMLElement(aTag
);
301 * IsContainerAnyOfHTMLElements() returns true if the container node is an
302 * HTML element node and its node name is one of the arguments.
304 template <typename First
, typename
... Args
>
305 bool IsContainerAnyOfHTMLElements(First aFirst
, Args
... aArgs
) const {
306 return mParent
&& mParent
->IsAnyOfHTMLElements(aFirst
, aArgs
...);
310 * GetChild() returns a child node which is pointed by the instance.
311 * If mChild hasn't been initialized yet, this computes the child node
312 * from mParent and mOffset with *current* DOM tree.
314 nsIContent
* GetChild() const {
315 if (!mParent
|| !mParent
->IsContainerNode()) {
318 if (mIsChildInitialized
) {
321 // Fix child node now.
322 const_cast<SelfType
*>(this)->EnsureChild();
326 template <typename ContentNodeType
>
327 ContentNodeType
* GetChildAs() const {
328 return ContentNodeType::FromNodeOrNull(GetChild());
330 template <typename ContentNodeType
>
331 ContentNodeType
* ChildAs() const {
332 MOZ_DIAGNOSTIC_ASSERT(GetChildAs
<ContentNodeType
>());
333 return static_cast<ContentNodeType
*>(GetChild());
337 * GetCurrentChildAtOffset() returns current child at mOffset.
338 * I.e., mOffset needs to be fixed before calling this.
340 nsIContent
* GetCurrentChildAtOffset() const {
341 MOZ_ASSERT(mOffset
.isSome());
342 if (mOffset
.isNothing()) {
345 return mParent
? mParent
->GetChildAt_Deprecated(*mOffset
) : nullptr;
349 * GetChildOrContainerIfDataNode() returns the child content node,
350 * or container content node if the container is a data node.
352 nsIContent
* GetChildOrContainerIfDataNode() const {
353 if (IsInDataNode()) {
354 return ContainerAs
<nsIContent
>();
360 * GetNextSiblingOfChild() returns next sibling of the child node.
361 * If this refers after the last child or the container cannot have children,
362 * this returns nullptr with warning.
363 * If mChild hasn't been initialized yet, this computes the child node
364 * from mParent and mOffset with *current* DOM tree.
366 nsIContent
* GetNextSiblingOfChild() const {
367 if (NS_WARN_IF(!mParent
) || !mParent
->IsContainerNode()) {
370 if (mIsChildInitialized
) {
371 return mChild
? mChild
->GetNextSibling() : nullptr;
373 MOZ_ASSERT(mOffset
.isSome());
374 if (NS_WARN_IF(mOffset
.value() > mParent
->Length())) {
375 // If this has been set only offset and now the offset is invalid,
376 // let's just return nullptr.
379 // Fix child node now.
380 const_cast<SelfType
*>(this)->EnsureChild();
381 return mChild
? mChild
->GetNextSibling() : nullptr;
383 template <typename ContentNodeType
>
384 ContentNodeType
* GetNextSiblingOfChildAs() const {
385 return ContentNodeType::FromNodeOrNull(GetNextSiblingOfChild());
387 template <typename ContentNodeType
>
388 ContentNodeType
* NextSiblingOfChildAs() const {
390 MOZ_DIAGNOSTIC_ASSERT(GetNextSiblingOfChildAs
<ContentNodeType
>());
391 return static_cast<ContentNodeType
*>(GetNextSiblingOfChild());
395 * GetPreviousSiblingOfChild() returns previous sibling of a child
396 * at offset. If this refers the first child or the container cannot have
397 * children, this returns nullptr with warning.
398 * If mChild hasn't been initialized yet, this computes the child node
399 * from mParent and mOffset with *current* DOM tree.
401 nsIContent
* GetPreviousSiblingOfChild() const {
402 if (NS_WARN_IF(!mParent
) || !mParent
->IsContainerNode()) {
405 if (mIsChildInitialized
) {
406 return mChild
? mChild
->GetPreviousSibling() : mParent
->GetLastChild();
408 MOZ_ASSERT(mOffset
.isSome());
409 if (NS_WARN_IF(mOffset
.value() > mParent
->Length())) {
410 // If this has been set only offset and now the offset is invalid,
411 // let's just return nullptr.
414 // Fix child node now.
415 const_cast<SelfType
*>(this)->EnsureChild();
416 return mChild
? mChild
->GetPreviousSibling() : mParent
->GetLastChild();
418 template <typename ContentNodeType
>
419 ContentNodeType
* GetPreviousSiblingOfChildAs() const {
420 return ContentNodeType::FromNodeOrNull(GetPreviousSiblingOfChild());
422 template <typename ContentNodeType
>
423 ContentNodeType
* PreviousSiblingOfChildAs() const {
425 MOZ_DIAGNOSTIC_ASSERT(GetPreviousSiblingOfChildAs
<ContentNodeType
>());
426 return static_cast<ContentNodeType
*>(GetPreviousSiblingOfChild());
430 * Simple accessors of the character in dom::Text so that when you call
431 * these methods, you need to guarantee that the container is a dom::Text.
433 MOZ_NEVER_INLINE_DEBUG char16_t
Char() const {
434 MOZ_ASSERT(IsSetAndValid());
435 MOZ_ASSERT(!IsEndOfContainer());
436 return ContainerAs
<dom::Text
>()->TextFragment().CharAt(mOffset
.value());
438 MOZ_NEVER_INLINE_DEBUG
bool IsCharASCIISpace() const {
439 return nsCRT::IsAsciiSpace(Char());
441 MOZ_NEVER_INLINE_DEBUG
bool IsCharNBSP() const { return Char() == 0x00A0; }
442 MOZ_NEVER_INLINE_DEBUG
bool IsCharASCIISpaceOrNBSP() const {
443 char16_t ch
= Char();
444 return nsCRT::IsAsciiSpace(ch
) || ch
== 0x00A0;
446 MOZ_NEVER_INLINE_DEBUG
bool IsCharNewLine() const { return Char() == '\n'; }
447 MOZ_NEVER_INLINE_DEBUG
bool IsCharPreformattedNewLine() const;
448 MOZ_NEVER_INLINE_DEBUG
bool
449 IsCharPreformattedNewLineCollapsedWithWhiteSpaces() const;
451 * IsCharCollapsibleASCIISpace(), IsCharCollapsibleNBSP() and
452 * IsCharCollapsibleASCIISpaceOrNBSP() checks whether the white-space is
453 * preformatted or collapsible with the style of the container text node
454 * without flushing pending notifications.
456 bool IsCharCollapsibleASCIISpace() const;
457 bool IsCharCollapsibleNBSP() const;
458 bool IsCharCollapsibleASCIISpaceOrNBSP() const;
460 MOZ_NEVER_INLINE_DEBUG
bool IsCharHighSurrogateFollowedByLowSurrogate()
462 MOZ_ASSERT(IsSetAndValid());
463 MOZ_ASSERT(!IsEndOfContainer());
464 return ContainerAs
<dom::Text
>()
466 .IsHighSurrogateFollowedByLowSurrogateAt(mOffset
.value());
468 MOZ_NEVER_INLINE_DEBUG
bool IsCharLowSurrogateFollowingHighSurrogate() const {
469 MOZ_ASSERT(IsSetAndValid());
470 MOZ_ASSERT(!IsEndOfContainer());
471 return ContainerAs
<dom::Text
>()
473 .IsLowSurrogateFollowingHighSurrogateAt(mOffset
.value());
476 MOZ_NEVER_INLINE_DEBUG char16_t
PreviousChar() const {
477 MOZ_ASSERT(IsSetAndValid());
478 MOZ_ASSERT(!IsStartOfContainer());
479 return ContainerAs
<dom::Text
>()->TextFragment().CharAt(mOffset
.value() - 1);
481 MOZ_NEVER_INLINE_DEBUG
bool IsPreviousCharASCIISpace() const {
482 return nsCRT::IsAsciiSpace(PreviousChar());
484 MOZ_NEVER_INLINE_DEBUG
bool IsPreviousCharNBSP() const {
485 return PreviousChar() == 0x00A0;
487 MOZ_NEVER_INLINE_DEBUG
bool IsPreviousCharASCIISpaceOrNBSP() const {
488 char16_t ch
= PreviousChar();
489 return nsCRT::IsAsciiSpace(ch
) || ch
== 0x00A0;
491 MOZ_NEVER_INLINE_DEBUG
bool IsPreviousCharNewLine() const {
492 return PreviousChar() == '\n';
494 MOZ_NEVER_INLINE_DEBUG
bool IsPreviousCharPreformattedNewLine() const;
495 MOZ_NEVER_INLINE_DEBUG
bool
496 IsPreviousCharPreformattedNewLineCollapsedWithWhiteSpaces() const;
498 * IsPreviousCharCollapsibleASCIISpace(), IsPreviousCharCollapsibleNBSP() and
499 * IsPreviousCharCollapsibleASCIISpaceOrNBSP() checks whether the white-space
500 * is preformatted or collapsible with the style of the container text node
501 * without flushing pending notifications.
503 bool IsPreviousCharCollapsibleASCIISpace() const;
504 bool IsPreviousCharCollapsibleNBSP() const;
505 bool IsPreviousCharCollapsibleASCIISpaceOrNBSP() const;
507 MOZ_NEVER_INLINE_DEBUG char16_t
NextChar() const {
508 MOZ_ASSERT(IsSetAndValid());
509 MOZ_ASSERT(!IsAtLastContent() && !IsEndOfContainer());
510 return ContainerAs
<dom::Text
>()->TextFragment().CharAt(mOffset
.value() + 1);
512 MOZ_NEVER_INLINE_DEBUG
bool IsNextCharASCIISpace() const {
513 return nsCRT::IsAsciiSpace(NextChar());
515 MOZ_NEVER_INLINE_DEBUG
bool IsNextCharNBSP() const {
516 return NextChar() == 0x00A0;
518 MOZ_NEVER_INLINE_DEBUG
bool IsNextCharASCIISpaceOrNBSP() const {
519 char16_t ch
= NextChar();
520 return nsCRT::IsAsciiSpace(ch
) || ch
== 0x00A0;
522 MOZ_NEVER_INLINE_DEBUG
bool IsNextCharNewLine() const {
523 return NextChar() == '\n';
525 MOZ_NEVER_INLINE_DEBUG
bool IsNextCharPreformattedNewLine() const;
526 MOZ_NEVER_INLINE_DEBUG
bool
527 IsNextCharPreformattedNewLineCollapsedWithWhiteSpaces() const;
529 * IsNextCharCollapsibleASCIISpace(), IsNextCharCollapsibleNBSP() and
530 * IsNextCharCollapsibleASCIISpaceOrNBSP() checks whether the white-space is
531 * preformatted or collapsible with the style of the container text node
532 * without flushing pending notifications.
534 bool IsNextCharCollapsibleASCIISpace() const;
535 bool IsNextCharCollapsibleNBSP() const;
536 bool IsNextCharCollapsibleASCIISpaceOrNBSP() const;
538 [[nodiscard
]] bool HasOffset() const { return mOffset
.isSome(); }
539 uint32_t Offset() const {
540 if (mOffset
.isSome()) {
541 MOZ_ASSERT(mOffset
.isSome());
542 return mOffset
.value();
544 if (MOZ_UNLIKELY(!mParent
)) {
548 MOZ_ASSERT(mParent
->IsContainerNode(),
549 "If the container cannot have children, mOffset.isSome() should "
552 // We're referring after the last child. Fix offset now.
553 const_cast<SelfType
*>(this)->mOffset
= mozilla::Some(mParent
->Length());
554 return mOffset
.value();
556 MOZ_ASSERT(mChild
->GetParentNode() == mParent
);
558 if (mChild
== mParent
->GetFirstChild()) {
559 const_cast<SelfType
*>(this)->mOffset
= mozilla::Some(0u);
562 const_cast<SelfType
*>(this)->mOffset
= mParent
->ComputeIndexOf(mChild
);
563 MOZ_DIAGNOSTIC_ASSERT(mOffset
.isSome());
564 return mOffset
.valueOr(0u); // Avoid crash in Release/Beta
568 * Set() sets a point to aOffset or aChild.
569 * If it's set with aOffset, mChild is invalidated. If it's set with aChild,
570 * mOffset may be invalidated.
572 template <typename ContainerType
>
573 void Set(ContainerType
* aContainer
, uint32_t aOffset
) {
574 mParent
= aContainer
;
576 mOffset
= mozilla::Some(aOffset
);
577 mIsChildInitialized
= false;
578 mInterlinePosition
= InterlinePosition::Undefined
;
579 NS_ASSERTION(!mParent
|| mOffset
.value() <= mParent
->Length(),
580 "The offset is out of bounds");
582 template <typename ContainerType
, template <typename
> typename StrongPtr
>
583 void Set(const StrongPtr
<ContainerType
>& aContainer
, uint32_t aOffset
) {
584 Set(aContainer
.get(), aOffset
);
586 void Set(const nsINode
* aChild
) {
588 if (NS_WARN_IF(!aChild
->IsContent())) {
592 mParent
= aChild
->GetParentNode();
593 mChild
= const_cast<nsIContent
*>(aChild
->AsContent());
595 mIsChildInitialized
= true;
596 mInterlinePosition
= InterlinePosition::Undefined
;
600 * SetToEndOf() sets this to the end of aContainer. Then, mChild is always
601 * nullptr but marked as initialized and mOffset is always set.
603 template <typename ContainerType
>
604 MOZ_NEVER_INLINE_DEBUG
void SetToEndOf(const ContainerType
* aContainer
) {
605 MOZ_ASSERT(aContainer
);
606 mParent
= const_cast<ContainerType
*>(aContainer
);
608 mOffset
= mozilla::Some(mParent
->Length());
609 mIsChildInitialized
= true;
610 mInterlinePosition
= InterlinePosition::Undefined
;
612 template <typename ContainerType
, template <typename
> typename StrongPtr
>
613 MOZ_NEVER_INLINE_DEBUG
void SetToEndOf(
614 const StrongPtr
<ContainerType
>& aContainer
) {
615 SetToEndOf(aContainer
.get());
617 template <typename ContainerType
>
618 MOZ_NEVER_INLINE_DEBUG
static SelfType
AtEndOf(
619 const ContainerType
& aContainer
,
620 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
) {
622 point
.SetToEndOf(&aContainer
);
623 point
.mInterlinePosition
= aInterlinePosition
;
626 template <typename ContainerType
, template <typename
> typename StrongPtr
>
627 MOZ_NEVER_INLINE_DEBUG
static SelfType
AtEndOf(
628 const StrongPtr
<ContainerType
>& aContainer
,
629 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
) {
630 MOZ_ASSERT(aContainer
.get());
631 return AtEndOf(*aContainer
.get(), aInterlinePosition
);
635 * SetAfter() sets mChild to next sibling of aChild.
637 void SetAfter(const nsINode
* aChild
) {
639 nsIContent
* nextSibling
= aChild
->GetNextSibling();
644 nsINode
* parentNode
= aChild
->GetParentNode();
645 if (NS_WARN_IF(!parentNode
)) {
649 SetToEndOf(parentNode
);
651 void SetAfterContainer() {
655 template <typename ContainerType
>
656 static SelfType
After(
657 const ContainerType
& aContainer
,
658 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
) {
660 point
.SetAfter(&aContainer
);
661 point
.mInterlinePosition
= aInterlinePosition
;
664 template <typename ContainerType
, template <typename
> typename StrongPtr
>
665 MOZ_NEVER_INLINE_DEBUG
static SelfType
After(
666 const StrongPtr
<ContainerType
>& aContainer
,
667 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
) {
668 MOZ_ASSERT(aContainer
.get());
669 return After(*aContainer
.get(), aInterlinePosition
);
671 template <typename PT
, typename CT
>
672 MOZ_NEVER_INLINE_DEBUG
static SelfType
After(
673 const EditorDOMPointBase
<PT
, CT
>& aPoint
,
674 InterlinePosition aInterlinePosition
= InterlinePosition::Undefined
) {
675 MOZ_ASSERT(aPoint
.IsSet());
677 return After(*aPoint
.mChild
, aInterlinePosition
);
679 if (NS_WARN_IF(aPoint
.IsEndOfContainer())) {
682 auto point
= aPoint
.NextPoint().template To
<SelfType
>();
683 point
.mInterlinePosition
= aInterlinePosition
;
688 * ParentPoint() returns a point whose child is the container.
690 template <typename EditorDOMPointType
= SelfType
>
691 EditorDOMPointType
ParentPoint() const {
693 if (MOZ_UNLIKELY(!mParent
) || !mParent
->IsContent()) {
694 return EditorDOMPointType();
696 return EditorDOMPointType(ContainerAs
<nsIContent
>());
700 * NextPoint() and PreviousPoint() returns next/previous DOM point in
703 template <typename EditorDOMPointType
= SelfType
>
704 EditorDOMPointType
NextPoint() const {
705 NS_ASSERTION(!IsEndOfContainer(), "Should not be at end of the container");
706 auto result
= this->template To
<EditorDOMPointType
>();
707 result
.AdvanceOffset();
710 template <typename EditorDOMPointType
= SelfType
>
711 EditorDOMPointType
NextPointOrAfterContainer() const {
712 MOZ_ASSERT(IsInContentNode());
713 if (!IsEndOfContainer()) {
714 return NextPoint
<EditorDOMPointType
>();
716 return AfterContainer
<EditorDOMPointType
>();
718 template <typename EditorDOMPointType
= SelfType
>
719 EditorDOMPointType
AfterContainer() const {
720 MOZ_ASSERT(IsInContentNode());
721 return EditorDOMPointType::After(*ContainerAs
<nsIContent
>());
723 template <typename EditorDOMPointType
= SelfType
>
724 EditorDOMPointType
PreviousPoint() const {
725 NS_ASSERTION(!IsStartOfContainer(),
726 "Should not be at start of the container");
727 EditorDOMPointType result
= this->template To
<EditorDOMPointType
>();
728 result
.RewindOffset();
733 * Clear() makes the instance not point anywhere.
739 mIsChildInitialized
= false;
740 mInterlinePosition
= InterlinePosition::Undefined
;
744 * AdvanceOffset() tries to refer next sibling of mChild and/of next offset.
745 * If the container can have children and there is no next sibling or the
746 * offset reached the length of the container, this outputs warning and does
747 * nothing. So, callers need to check if there is next sibling which you
750 * @return true if there is a next DOM point to refer.
752 bool AdvanceOffset() {
753 if (NS_WARN_IF(!mParent
)) {
756 // If only mOffset is available, just compute the offset.
757 if ((mOffset
.isSome() && !mIsChildInitialized
) ||
758 !mParent
->IsContainerNode()) {
759 MOZ_ASSERT(mOffset
.isSome());
761 if (NS_WARN_IF(mOffset
.value() >= mParent
->Length())) {
762 // We're already referring the start of the container.
765 mOffset
= mozilla::Some(mOffset
.value() + 1);
766 mInterlinePosition
= InterlinePosition::Undefined
;
770 MOZ_ASSERT(mIsChildInitialized
);
771 MOZ_ASSERT(!mOffset
.isSome() || mOffset
.isSome());
772 if (NS_WARN_IF(!mParent
->HasChildren()) || NS_WARN_IF(!mChild
) ||
773 NS_WARN_IF(mOffset
.isSome() && mOffset
.value() >= mParent
->Length())) {
774 // We're already referring the end of the container (or outside).
778 if (mOffset
.isSome()) {
779 MOZ_ASSERT(mOffset
.isSome());
780 mOffset
= mozilla::Some(mOffset
.value() + 1);
782 mChild
= mChild
->GetNextSibling();
783 mInterlinePosition
= InterlinePosition::Undefined
;
788 * RewindOffset() tries to refer previous sibling of mChild and/or previous
789 * offset. If the container can have children and there is no next previous
790 * or the offset is 0, this outputs warning and does nothing. So, callers
791 * need to check if there is previous sibling which you need to refer.
793 * @return true if there is a previous DOM point to refer.
795 bool RewindOffset() {
796 if (NS_WARN_IF(!mParent
)) {
799 // If only mOffset is available, just compute the offset.
800 if ((mOffset
.isSome() && !mIsChildInitialized
) ||
801 !mParent
->IsContainerNode()) {
802 MOZ_ASSERT(mOffset
.isSome());
804 if (NS_WARN_IF(!mOffset
.value()) ||
805 NS_WARN_IF(mOffset
.value() > mParent
->Length())) {
806 // We're already referring the start of the container or
807 // the offset is invalid since perhaps, the offset was set before
808 // the last DOM tree change.
809 NS_ASSERTION(false, "Failed to rewind offset");
812 mOffset
= mozilla::Some(mOffset
.value() - 1);
813 mInterlinePosition
= InterlinePosition::Undefined
;
817 MOZ_ASSERT(mIsChildInitialized
);
818 MOZ_ASSERT(!mOffset
.isSome() || mOffset
.isSome());
819 if (NS_WARN_IF(!mParent
->HasChildren()) ||
820 NS_WARN_IF(mChild
&& !mChild
->GetPreviousSibling()) ||
821 NS_WARN_IF(mOffset
.isSome() && !mOffset
.value())) {
822 // We're already referring the start of the container (or the child has
823 // been moved from the container?).
827 nsIContent
* previousSibling
=
828 mChild
? mChild
->GetPreviousSibling() : mParent
->GetLastChild();
829 if (NS_WARN_IF(!previousSibling
)) {
830 // We're already referring the first child of the container.
834 if (mOffset
.isSome()) {
835 mOffset
= mozilla::Some(mOffset
.value() - 1);
837 mChild
= previousSibling
;
838 mInterlinePosition
= InterlinePosition::Undefined
;
843 * GetNonAnonymousSubtreePoint() returns a DOM point which is NOT in
844 * native-anonymous subtree. If the instance isn't in native-anonymous
845 * subtree, this returns same point. Otherwise, climbs up until finding
846 * non-native-anonymous parent and returns the point of it. I.e.,
847 * container is parent of the found non-anonymous-native node.
849 template <typename EditorDOMPointType
>
850 EditorDOMPointType
GetNonAnonymousSubtreePoint() const {
851 if (NS_WARN_IF(!IsSet())) {
852 return EditorDOMPointType();
854 if (!IsInNativeAnonymousSubtree()) {
855 return this->template To
<EditorDOMPointType
>();
858 for (parent
= mParent
->GetParentNode();
859 parent
&& parent
->IsInNativeAnonymousSubtree();
860 parent
= parent
->GetParentNode()) {
863 return EditorDOMPointType();
865 return EditorDOMPointType(parent
);
868 [[nodiscard
]] bool IsSet() const {
869 return mParent
&& (mIsChildInitialized
|| mOffset
.isSome());
872 [[nodiscard
]] bool IsSetAndValid() const {
878 (mChild
->GetParentNode() != mParent
|| mChild
->IsBeingRemoved())) {
881 if (mOffset
.isSome() && mOffset
.value() > mParent
->Length()) {
887 [[nodiscard
]] bool IsInContentNodeAndValid() const {
888 return IsInContentNode() && IsSetAndValid();
891 [[nodiscard
]] bool IsInComposedDoc() const {
892 return IsSet() && mParent
->IsInComposedDoc();
895 [[nodiscard
]] bool IsSetAndValidInComposedDoc() const {
896 return IsInComposedDoc() && IsSetAndValid();
899 [[nodiscard
]] bool IsInContentNodeAndValidInComposedDoc() const {
900 return IsInContentNode() && IsSetAndValidInComposedDoc();
903 bool IsStartOfContainer() const {
904 // If we're referring the first point in the container:
905 // If mParent is not a container like a text node, mOffset is 0.
906 // If mChild is initialized and it's first child of mParent.
907 // If mChild isn't initialized and the offset is 0.
908 if (NS_WARN_IF(!mParent
)) {
911 if (!mParent
->IsContainerNode()) {
912 return !mOffset
.value();
914 if (mIsChildInitialized
) {
915 if (mParent
->GetFirstChild() == mChild
) {
916 NS_WARNING_ASSERTION(!mOffset
.isSome() || !mOffset
.value(),
917 "If mOffset was initialized, it should be 0");
920 NS_WARNING_ASSERTION(!mOffset
.isSome() || mParent
->GetChildAt_Deprecated(
921 mOffset
.value()) == mChild
,
922 "mOffset and mChild are mismatched");
925 MOZ_ASSERT(mOffset
.isSome());
926 return !mOffset
.value();
929 bool IsEndOfContainer() const {
930 // If we're referring after the last point of the container:
931 // If mParent is not a container like text node, mOffset is same as the
932 // length of the container.
933 // If mChild is initialized and it's nullptr.
934 // If mChild isn't initialized and mOffset is same as the length of the
936 if (NS_WARN_IF(!mParent
)) {
939 if (!mParent
->IsContainerNode()) {
940 return mOffset
.value() == mParent
->Length();
942 if (mIsChildInitialized
) {
944 NS_WARNING_ASSERTION(
945 !mOffset
.isSome() || mOffset
.value() == mParent
->Length(),
946 "If mOffset was initialized, it should be length of the container");
949 NS_WARNING_ASSERTION(!mOffset
.isSome() || mParent
->GetChildAt_Deprecated(
950 mOffset
.value()) == mChild
,
951 "mOffset and mChild are mismatched");
954 MOZ_ASSERT(mOffset
.isSome());
955 return mOffset
.value() == mParent
->Length();
959 * IsAtLastContent() returns true when it refers last child of the container
960 * or last character offset of text node.
962 bool IsAtLastContent() const {
963 if (NS_WARN_IF(!mParent
)) {
966 if (mParent
->IsContainerNode() && mOffset
.isSome()) {
967 return mOffset
.value() == mParent
->Length() - 1;
969 if (mIsChildInitialized
) {
970 if (mChild
&& mChild
== mParent
->GetLastChild()) {
971 NS_WARNING_ASSERTION(
972 !mOffset
.isSome() || mOffset
.value() == mParent
->Length() - 1,
973 "If mOffset was initialized, it should be length - 1 of the "
977 NS_WARNING_ASSERTION(!mOffset
.isSome() || mParent
->GetChildAt_Deprecated(
978 mOffset
.value()) == mChild
,
979 "mOffset and mChild are mismatched");
982 MOZ_ASSERT(mOffset
.isSome());
983 return mOffset
.value() == mParent
->Length() - 1;
986 bool IsBRElementAtEndOfContainer() const {
987 if (NS_WARN_IF(!mParent
)) {
990 if (!mParent
->IsContainerNode()) {
993 const_cast<SelfType
*>(this)->EnsureChild();
994 if (!mChild
|| mChild
->GetNextSibling()) {
997 return mChild
->IsHTMLElement(nsGkAtoms::br
);
1001 * Return a point in text node if "this" points around a text node.
1002 * EditorDOMPointType can always be EditorDOMPoint or EditorRawDOMPoint,
1003 * but EditorDOMPointInText or EditorRawDOMPointInText is also available
1004 * only when "this type" is one of them.
1005 * If the point is in the anonymous <div> of a TextEditor, use
1006 * TextEditor::FindBetterInsertionPoint() instead.
1008 template <typename EditorDOMPointType
>
1009 EditorDOMPointType
GetPointInTextNodeIfPointingAroundTextNode() const {
1010 if (NS_WARN_IF(!IsSet()) || !mParent
->HasChildren()) {
1011 return To
<EditorDOMPointType
>();
1013 if (IsStartOfContainer()) {
1014 if (auto* firstTextChild
=
1015 dom::Text::FromNode(mParent
->GetFirstChild())) {
1016 return EditorDOMPointType(firstTextChild
, 0u);
1018 return To
<EditorDOMPointType
>();
1020 if (auto* previousSiblingChild
= dom::Text::FromNodeOrNull(
1021 GetPreviousSiblingOfChildAs
<dom::Text
>())) {
1022 return EditorDOMPointType::AtEndOf(*previousSiblingChild
);
1024 if (auto* child
= dom::Text::FromNodeOrNull(GetChildAs
<dom::Text
>())) {
1025 return EditorDOMPointType(child
, 0u);
1027 return To
<EditorDOMPointType
>();
1030 template <typename A
, typename B
>
1031 EditorDOMPointBase
& operator=(const RangeBoundaryBase
<A
, B
>& aOther
) {
1032 mParent
= aOther
.mParent
;
1033 mChild
= aOther
.mRef
? aOther
.mRef
->GetNextSibling()
1034 : (aOther
.mParent
&& aOther
.mParent
->IsContainerNode()
1035 ? aOther
.mParent
->GetFirstChild()
1037 mOffset
= aOther
.mOffset
;
1038 mIsChildInitialized
=
1039 aOther
.mRef
|| (aOther
.mParent
&& !aOther
.mParent
->IsContainerNode()) ||
1040 (aOther
.mOffset
.isSome() && !aOther
.mOffset
.value());
1041 mInterlinePosition
= InterlinePosition::Undefined
;
1045 template <typename EditorDOMPointType
>
1046 constexpr EditorDOMPointType
To() const {
1047 // XXX Cannot specialize this method due to implicit instantiatation caused
1048 // by the inline CC functions below.
1049 if (std::is_same
<SelfType
, EditorDOMPointType
>::value
) {
1050 return reinterpret_cast<const EditorDOMPointType
&>(*this);
1052 EditorDOMPointType result
;
1053 result
.mParent
= mParent
;
1054 result
.mChild
= mChild
;
1055 result
.mOffset
= mOffset
;
1056 result
.mIsChildInitialized
= mIsChildInitialized
;
1057 result
.mInterlinePosition
= mInterlinePosition
;
1062 * Don't compare mInterlinePosition. If it's required to check, perhaps,
1063 * another compare operator like `===` should be created.
1065 template <typename A
, typename B
>
1066 bool operator==(const EditorDOMPointBase
<A
, B
>& aOther
) const {
1067 if (mParent
!= aOther
.mParent
) {
1071 if (mOffset
.isSome() && aOther
.mOffset
.isSome()) {
1072 // If both mOffset are set, we need to compare both mRef too because
1073 // the relation of mRef and mOffset have already broken by DOM tree
1075 if (mOffset
!= aOther
.mOffset
) {
1078 if (mChild
== aOther
.mChild
) {
1081 if (NS_WARN_IF(mIsChildInitialized
&& aOther
.mIsChildInitialized
)) {
1082 // In this case, relation between mChild and mOffset of one of or both
1083 // of them doesn't match with current DOM tree since the DOM tree might
1084 // have been changed after computing mChild or mOffset.
1087 // If one of mChild hasn't been computed yet, we should compare them only
1088 // with mOffset. Perhaps, we shouldn't copy mChild from non-nullptr one
1089 // to the other since if we copy it here, it may be unexpected behavior
1090 // for some callers.
1094 MOZ_ASSERT(mIsChildInitialized
|| aOther
.mIsChildInitialized
);
1096 if (mOffset
.isSome() && !mIsChildInitialized
&& !aOther
.mOffset
.isSome() &&
1097 aOther
.mIsChildInitialized
) {
1098 // If this has only mOffset and the other has only mChild, this needs to
1099 // compute mChild now.
1100 const_cast<SelfType
*>(this)->EnsureChild();
1101 return mChild
== aOther
.mChild
;
1104 if (!mOffset
.isSome() && mIsChildInitialized
&& aOther
.mOffset
.isSome() &&
1105 !aOther
.mIsChildInitialized
) {
1106 // If this has only mChild and the other has only mOffset, the other needs
1107 // to compute mChild now.
1108 const_cast<EditorDOMPointBase
<A
, B
>&>(aOther
).EnsureChild();
1109 return mChild
== aOther
.mChild
;
1112 // If mOffset of one of them hasn't been computed from mChild yet, we should
1113 // compare only with mChild. Perhaps, we shouldn't copy mOffset from being
1114 // some one to not being some one since if we copy it here, it may be
1115 // unexpected behavior for some callers.
1116 return mChild
== aOther
.mChild
;
1119 template <typename A
, typename B
>
1120 bool operator==(const RangeBoundaryBase
<A
, B
>& aOther
) const {
1121 // TODO: Optimize this with directly comparing with RangeBoundaryBase
1123 return *this == SelfType(aOther
);
1126 template <typename A
, typename B
>
1127 bool operator!=(const EditorDOMPointBase
<A
, B
>& aOther
) const {
1128 return !(*this == aOther
);
1131 template <typename A
, typename B
>
1132 bool operator!=(const RangeBoundaryBase
<A
, B
>& aOther
) const {
1133 return !(*this == aOther
);
1137 * This operator should be used if API of other modules take RawRangeBoundary,
1138 * e.g., methods of Selection and nsRange.
1140 operator const RawRangeBoundary() const { return ToRawRangeBoundary(); }
1141 const RawRangeBoundary
ToRawRangeBoundary() const {
1142 if (!IsSet() || NS_WARN_IF(!mIsChildInitialized
&& !mOffset
.isSome())) {
1143 return RawRangeBoundary();
1145 if (!mParent
->IsContainerNode()) {
1146 MOZ_ASSERT(mOffset
.value() <= mParent
->Length());
1147 // If the container is a data node like a text node, we need to create
1148 // RangeBoundaryBase instance only with mOffset because mChild is always
1150 return RawRangeBoundary(mParent
, mOffset
.value());
1152 if (mIsChildInitialized
&& mOffset
.isSome()) {
1153 // If we've already set both child and offset, we should create
1154 // RangeBoundary with offset after validation.
1157 MOZ_ASSERT(mParent
== mChild
->GetParentNode());
1158 MOZ_ASSERT(mParent
->GetChildAt_Deprecated(mOffset
.value()) == mChild
);
1160 MOZ_ASSERT(mParent
->Length() == mOffset
.value());
1162 #endif // #ifdef DEBUG
1163 return RawRangeBoundary(mParent
, mOffset
.value());
1165 // Otherwise, we should create RangeBoundaryBase only with available
1167 if (mOffset
.isSome()) {
1168 return RawRangeBoundary(mParent
, mOffset
.value());
1171 return RawRangeBoundary(mParent
, mChild
->GetPreviousSibling());
1173 return RawRangeBoundary(mParent
, mParent
->GetLastChild());
1176 already_AddRefed
<nsRange
> CreateCollapsedRange(ErrorResult
& aRv
) const {
1177 const RawRangeBoundary boundary
= ToRawRangeBoundary();
1178 RefPtr
<nsRange
> range
= nsRange::Create(boundary
, boundary
, aRv
);
1179 if (MOZ_UNLIKELY(aRv
.Failed() || !range
)) {
1182 return range
.forget();
1185 EditorDOMPointInText
GetAsInText() const {
1186 return IsInTextNode() ? EditorDOMPointInText(ContainerAs
<dom::Text
>(),
1187 Offset(), mInterlinePosition
)
1188 : EditorDOMPointInText();
1190 MOZ_NEVER_INLINE_DEBUG EditorDOMPointInText
AsInText() const {
1191 MOZ_ASSERT(IsInTextNode());
1192 return EditorDOMPointInText(ContainerAs
<dom::Text
>(), Offset(),
1193 mInterlinePosition
);
1196 template <typename A
, typename B
>
1197 bool IsBefore(const EditorDOMPointBase
<A
, B
>& aOther
) const {
1198 if (!IsSetAndValid() || !aOther
.IsSetAndValid()) {
1201 Maybe
<int32_t> comp
= nsContentUtils::ComparePoints(
1202 ToRawRangeBoundary(), aOther
.ToRawRangeBoundary());
1203 return comp
.isSome() && comp
.value() == -1;
1206 template <typename A
, typename B
>
1207 bool EqualsOrIsBefore(const EditorDOMPointBase
<A
, B
>& aOther
) const {
1208 if (!IsSetAndValid() || !aOther
.IsSetAndValid()) {
1211 Maybe
<int32_t> comp
= nsContentUtils::ComparePoints(
1212 ToRawRangeBoundary(), aOther
.ToRawRangeBoundary());
1213 return comp
.isSome() && comp
.value() <= 0;
1216 friend std::ostream
& operator<<(std::ostream
& aStream
,
1217 const SelfType
& aDOMPoint
) {
1218 aStream
<< "{ mParent=" << aDOMPoint
.GetContainer();
1219 if (aDOMPoint
.mParent
) {
1220 aStream
<< " (" << *aDOMPoint
.mParent
1221 << ", Length()=" << aDOMPoint
.mParent
->Length() << ")";
1223 aStream
<< ", mChild=" << static_cast<nsIContent
*>(aDOMPoint
.mChild
);
1224 if (aDOMPoint
.mChild
) {
1225 aStream
<< " (" << *aDOMPoint
.mChild
<< ")";
1227 aStream
<< ", mOffset=" << aDOMPoint
.mOffset
<< ", mIsChildInitialized="
1228 << (aDOMPoint
.mIsChildInitialized
? "true" : "false")
1229 << ", mInterlinePosition=" << aDOMPoint
.mInterlinePosition
<< " }";
1234 void EnsureChild() {
1235 if (mIsChildInitialized
) {
1239 MOZ_ASSERT(!mOffset
.isSome());
1242 MOZ_ASSERT(mOffset
.isSome());
1243 MOZ_ASSERT(mOffset
.value() <= mParent
->Length());
1244 mIsChildInitialized
= true;
1245 if (!mParent
->IsContainerNode()) {
1248 mChild
= mParent
->GetChildAt_Deprecated(mOffset
.value());
1249 MOZ_ASSERT(mChild
|| mOffset
.value() == mParent
->Length());
1252 ParentType mParent
= nullptr;
1253 ChildType mChild
= nullptr;
1255 Maybe
<uint32_t> mOffset
;
1256 InterlinePosition mInterlinePosition
= InterlinePosition::Undefined
;
1257 bool mIsChildInitialized
= false;
1259 template <typename PT
, typename CT
>
1260 friend class EditorDOMPointBase
;
1262 friend void ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback
&,
1263 EditorDOMPoint
&, const char*,
1265 friend void ImplCycleCollectionUnlink(EditorDOMPoint
&);
1268 inline void ImplCycleCollectionUnlink(EditorDOMPoint
& aField
) {
1269 ImplCycleCollectionUnlink(aField
.mParent
);
1270 ImplCycleCollectionUnlink(aField
.mChild
);
1273 inline void ImplCycleCollectionTraverse(
1274 nsCycleCollectionTraversalCallback
& aCallback
, EditorDOMPoint
& aField
,
1275 const char* aName
, uint32_t aFlags
) {
1276 ImplCycleCollectionTraverse(aCallback
, aField
.mParent
, "mParent", 0);
1277 ImplCycleCollectionTraverse(aCallback
, aField
.mChild
, "mChild", 0);
1281 * EditorDOMRangeBase class stores a pair of same EditorDOMPointBase type.
1282 * The instance must be created with valid DOM points and start must be
1283 * before or same as end.
1285 #define NS_INSTANTIATE_EDITOR_DOM_RANGE_METHOD(aResultType, aMethodName, ...) \
1286 template aResultType EditorDOMRange::aMethodName(__VA_ARGS__); \
1287 template aResultType EditorRawDOMRange::aMethodName(__VA_ARGS__); \
1288 template aResultType EditorDOMRangeInTexts::aMethodName(__VA_ARGS__); \
1289 template aResultType EditorRawDOMRangeInTexts::aMethodName(__VA_ARGS__)
1291 #define NS_INSTANTIATE_EDITOR_DOM_RANGE_CONST_METHOD(aResultType, aMethodName, \
1293 template aResultType EditorDOMRange::aMethodName(__VA_ARGS__) const; \
1294 template aResultType EditorRawDOMRange::aMethodName(__VA_ARGS__) const; \
1295 template aResultType EditorDOMRangeInTexts::aMethodName(__VA_ARGS__) const; \
1296 template aResultType EditorRawDOMRangeInTexts::aMethodName(__VA_ARGS__) const
1297 template <typename EditorDOMPointType
>
1298 class EditorDOMRangeBase final
{
1299 using SelfType
= EditorDOMRangeBase
<EditorDOMPointType
>;
1302 using PointType
= EditorDOMPointType
;
1304 EditorDOMRangeBase() = default;
1305 template <typename PT
, typename CT
>
1306 explicit EditorDOMRangeBase(const EditorDOMPointBase
<PT
, CT
>& aStart
)
1307 : mStart(aStart
), mEnd(aStart
) {
1308 MOZ_ASSERT(!mStart
.IsSet() || mStart
.IsSetAndValid());
1310 template <typename StartPointType
, typename EndPointType
>
1311 explicit EditorDOMRangeBase(const StartPointType
& aStart
,
1312 const EndPointType
& aEnd
)
1313 : mStart(aStart
.template To
<PointType
>()),
1314 mEnd(aEnd
.template To
<PointType
>()) {
1315 MOZ_ASSERT_IF(mStart
.IsSet(), mStart
.IsSetAndValid());
1316 MOZ_ASSERT_IF(mEnd
.IsSet(), mEnd
.IsSetAndValid());
1317 MOZ_ASSERT_IF(mStart
.IsSet() && mEnd
.IsSet(),
1318 mStart
.EqualsOrIsBefore(mEnd
));
1320 explicit EditorDOMRangeBase(EditorDOMPointType
&& aStart
,
1321 EditorDOMPointType
&& aEnd
)
1322 : mStart(std::move(aStart
)), mEnd(std::move(aEnd
)) {
1323 MOZ_ASSERT_IF(mStart
.IsSet(), mStart
.IsSetAndValid());
1324 MOZ_ASSERT_IF(mEnd
.IsSet(), mEnd
.IsSetAndValid());
1325 MOZ_ASSERT_IF(mStart
.IsSet() && mEnd
.IsSet(),
1326 mStart
.EqualsOrIsBefore(mEnd
));
1328 template <typename OtherPointType
>
1329 explicit EditorDOMRangeBase(const EditorDOMRangeBase
<OtherPointType
>& aOther
)
1330 : mStart(aOther
.StartRef().template To
<PointType
>()),
1331 mEnd(aOther
.EndRef().template To
<PointType
>()) {
1332 MOZ_ASSERT_IF(mStart
.IsSet(), mStart
.IsSetAndValid());
1333 MOZ_ASSERT_IF(mEnd
.IsSet(), mEnd
.IsSetAndValid());
1334 MOZ_ASSERT(mStart
.IsSet() == mEnd
.IsSet());
1336 explicit EditorDOMRangeBase(const dom::AbstractRange
& aRange
)
1337 : mStart(aRange
.StartRef()), mEnd(aRange
.EndRef()) {
1338 MOZ_ASSERT_IF(mStart
.IsSet(), mStart
.IsSetAndValid());
1339 MOZ_ASSERT_IF(mEnd
.IsSet(), mEnd
.IsSetAndValid());
1340 MOZ_ASSERT_IF(mStart
.IsSet() && mEnd
.IsSet(),
1341 mStart
.EqualsOrIsBefore(mEnd
));
1344 template <typename MaybeOtherPointType
>
1345 void SetStart(const MaybeOtherPointType
& aStart
) {
1346 mStart
= aStart
.template To
<PointType
>();
1348 void SetStart(PointType
&& aStart
) { mStart
= std::move(aStart
); }
1349 template <typename MaybeOtherPointType
>
1350 void SetEnd(const MaybeOtherPointType
& aEnd
) {
1351 mEnd
= aEnd
.template To
<PointType
>();
1353 void SetEnd(PointType
&& aEnd
) { mEnd
= std::move(aEnd
); }
1354 template <typename StartPointType
, typename EndPointType
>
1355 void SetStartAndEnd(const StartPointType
& aStart
, const EndPointType
& aEnd
) {
1356 MOZ_ASSERT_IF(aStart
.IsSet() && aEnd
.IsSet(),
1357 aStart
.EqualsOrIsBefore(aEnd
));
1358 mStart
= aStart
.template To
<PointType
>();
1359 mEnd
= aEnd
.template To
<PointType
>();
1361 template <typename StartPointType
>
1362 void SetStartAndEnd(const StartPointType
& aStart
, PointType
&& aEnd
) {
1363 MOZ_ASSERT_IF(aStart
.IsSet() && aEnd
.IsSet(),
1364 aStart
.EqualsOrIsBefore(aEnd
));
1365 mStart
= aStart
.template To
<PointType
>();
1366 mEnd
= std::move(aEnd
);
1368 template <typename EndPointType
>
1369 void SetStartAndEnd(PointType
&& aStart
, const EndPointType
& aEnd
) {
1370 MOZ_ASSERT_IF(aStart
.IsSet() && aEnd
.IsSet(),
1371 aStart
.EqualsOrIsBefore(aEnd
));
1372 mStart
= std::move(aStart
);
1373 mEnd
= aEnd
.template To
<PointType
>();
1375 void SetStartAndEnd(PointType
&& aStart
, PointType
&& aEnd
) {
1376 MOZ_ASSERT_IF(aStart
.IsSet() && aEnd
.IsSet(),
1377 aStart
.EqualsOrIsBefore(aEnd
));
1378 mStart
= std::move(aStart
);
1379 mEnd
= std::move(aEnd
);
1381 template <typename PT
, typename CT
>
1382 void MergeWith(const EditorDOMPointBase
<PT
, CT
>& aPoint
) {
1383 MOZ_ASSERT(aPoint
.IsSet());
1384 if (!IsPositioned()) {
1385 SetStartAndEnd(aPoint
, aPoint
);
1388 MOZ_ASSERT(nsContentUtils::GetClosestCommonInclusiveAncestor(
1389 GetClosestCommonInclusiveAncestor(), aPoint
.GetContainer()));
1390 if (mEnd
.EqualsOrIsBefore(aPoint
)) {
1394 if (aPoint
.IsBefore(mStart
)) {
1399 void MergeWith(PointType
&& aPoint
) {
1400 MOZ_ASSERT(aPoint
.IsSet());
1401 if (!IsPositioned()) {
1402 SetStartAndEnd(aPoint
, aPoint
);
1405 MOZ_ASSERT(GetClosestCommonInclusiveAncestor());
1406 MOZ_ASSERT(nsContentUtils::GetClosestCommonInclusiveAncestor(
1407 GetClosestCommonInclusiveAncestor(), aPoint
.GetContainer()));
1408 if (mEnd
.EqualsOrIsBefore(aPoint
)) {
1409 SetEnd(std::move(aPoint
));
1412 if (aPoint
.IsBefore(mStart
)) {
1413 SetStart(std::move(aPoint
));
1417 template <typename PT
, typename CT
>
1418 void MergeWith(const EditorDOMRangeBase
<EditorDOMPointBase
<PT
, CT
>>& aRange
) {
1419 MOZ_ASSERT(aRange
.IsPositioned());
1420 MOZ_ASSERT(aRange
.GetClosestCommonInclusiveAncestor());
1421 if (!IsPositioned()) {
1422 SetStartAndEnd(aRange
.mStart
, aRange
.mEnd
);
1425 MOZ_ASSERT(GetClosestCommonInclusiveAncestor());
1426 MOZ_ASSERT(nsContentUtils::GetClosestCommonInclusiveAncestor(
1427 GetClosestCommonInclusiveAncestor(),
1428 aRange
.GetClosestCommonInclusiveAncestor()));
1429 if (mEnd
.IsBefore(aRange
.mEnd
)) {
1430 SetEnd(aRange
.mEnd
);
1432 if (aRange
.mStart
.IsBefore(mStart
)) {
1433 SetStart(aRange
.mStart
);
1436 void MergeWith(SelfType
&& aRange
) {
1437 MOZ_ASSERT(aRange
.IsPositioned());
1438 MOZ_ASSERT(aRange
.GetClosestCommonInclusiveAncestor());
1439 if (!IsPositioned()) {
1440 SetStartAndEnd(std::move(aRange
.mStart
), std::move(aRange
.mEnd
));
1443 MOZ_ASSERT(GetClosestCommonInclusiveAncestor());
1444 MOZ_ASSERT(nsContentUtils::GetClosestCommonInclusiveAncestor(
1445 GetClosestCommonInclusiveAncestor(),
1446 aRange
.GetClosestCommonInclusiveAncestor()));
1447 if (mEnd
.IsBefore(aRange
.mEnd
)) {
1448 SetEnd(std::move(aRange
.mEnd
));
1450 if (aRange
.mStart
.IsBefore(mStart
)) {
1451 SetStart(std::move(aRange
.mStart
));
1460 const PointType
& StartRef() const { return mStart
; }
1461 const PointType
& EndRef() const { return mEnd
; }
1463 bool Collapsed() const {
1464 MOZ_ASSERT(IsPositioned());
1465 return mStart
== mEnd
;
1467 bool IsPositioned() const { return mStart
.IsSet() && mEnd
.IsSet(); }
1468 bool IsPositionedAndValid() const {
1469 return mStart
.IsSetAndValid() && mEnd
.IsSetAndValid() &&
1470 mStart
.EqualsOrIsBefore(mEnd
);
1472 bool IsPositionedAndValidInComposedDoc() const {
1473 return IsPositionedAndValid() && mStart
.GetContainer()->IsInComposedDoc();
1475 template <typename OtherPointType
>
1476 MOZ_NEVER_INLINE_DEBUG
bool Contains(const OtherPointType
& aPoint
) const {
1477 MOZ_ASSERT(aPoint
.IsSetAndValid());
1478 return IsPositioned() && aPoint
.IsSet() &&
1479 mStart
.EqualsOrIsBefore(aPoint
) && aPoint
.IsBefore(mEnd
);
1481 [[nodiscard
]] nsINode
* GetClosestCommonInclusiveAncestor() const;
1482 bool InSameContainer() const {
1483 MOZ_ASSERT(IsPositioned());
1484 return IsPositioned() && mStart
.GetContainer() == mEnd
.GetContainer();
1486 bool InAdjacentSiblings() const {
1487 MOZ_ASSERT(IsPositioned());
1488 return IsPositioned() &&
1489 mStart
.GetContainer()->GetNextSibling() == mEnd
.GetContainer();
1491 bool IsInContentNodes() const {
1492 MOZ_ASSERT(IsPositioned());
1493 return IsPositioned() && mStart
.IsInContentNode() && mEnd
.IsInContentNode();
1495 bool IsInTextNodes() const {
1496 MOZ_ASSERT(IsPositioned());
1497 return IsPositioned() && mStart
.IsInTextNode() && mEnd
.IsInTextNode();
1499 template <typename OtherRangeType
>
1500 bool operator==(const OtherRangeType
& aOther
) const {
1501 return (!IsPositioned() && !aOther
.IsPositioned()) ||
1502 (mStart
== aOther
.mStart
&& mEnd
== aOther
.mEnd
);
1504 template <typename OtherRangeType
>
1505 bool operator!=(const OtherRangeType
& aOther
) const {
1506 return !(*this == aOther
);
1509 EditorDOMRangeInTexts
GetAsInTexts() const {
1510 return IsInTextNodes()
1511 ? EditorDOMRangeInTexts(mStart
.AsInText(), mEnd
.AsInText())
1512 : EditorDOMRangeInTexts();
1514 MOZ_NEVER_INLINE_DEBUG EditorDOMRangeInTexts
AsInTexts() const {
1515 MOZ_ASSERT(IsInTextNodes());
1516 return EditorDOMRangeInTexts(mStart
.AsInText(), mEnd
.AsInText());
1519 bool EnsureNotInNativeAnonymousSubtree() {
1520 if (mStart
.IsInNativeAnonymousSubtree()) {
1521 nsIContent
* parent
= nullptr;
1522 for (parent
= mStart
.template ContainerAs
<nsIContent
>()
1523 ->GetClosestNativeAnonymousSubtreeRootParentOrHost();
1524 parent
&& parent
->IsInNativeAnonymousSubtree();
1526 parent
->GetClosestNativeAnonymousSubtreeRootParentOrHost()) {
1528 if (MOZ_UNLIKELY(!parent
)) {
1533 if (mEnd
.IsInNativeAnonymousSubtree()) {
1534 nsIContent
* parent
= nullptr;
1535 for (parent
= mEnd
.template ContainerAs
<nsIContent
>()
1536 ->GetClosestNativeAnonymousSubtreeRootParentOrHost();
1537 parent
&& parent
->IsInNativeAnonymousSubtree();
1539 parent
->GetClosestNativeAnonymousSubtreeRootParentOrHost()) {
1541 if (MOZ_UNLIKELY(!parent
)) {
1544 mEnd
.SetAfter(parent
);
1549 already_AddRefed
<nsRange
> CreateRange(ErrorResult
& aRv
) const {
1550 RefPtr
<nsRange
> range
= nsRange::Create(mStart
.ToRawRangeBoundary(),
1551 mEnd
.ToRawRangeBoundary(), aRv
);
1552 if (MOZ_UNLIKELY(aRv
.Failed() || !range
)) {
1555 return range
.forget();
1558 friend std::ostream
& operator<<(std::ostream
& aStream
,
1559 const SelfType
& aRange
) {
1560 if (aRange
.Collapsed()) {
1561 aStream
<< "{ mStart=mEnd=" << aRange
.mStart
<< " }";
1563 aStream
<< "{ mStart=" << aRange
.mStart
<< ", mEnd=" << aRange
.mEnd
1570 EditorDOMPointType mStart
;
1571 EditorDOMPointType mEnd
;
1573 friend void ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback
&,
1574 EditorDOMRange
&, const char*,
1576 friend void ImplCycleCollectionUnlink(EditorDOMRange
&);
1579 inline void ImplCycleCollectionUnlink(EditorDOMRange
& aField
) {
1580 ImplCycleCollectionUnlink(aField
.mStart
);
1581 ImplCycleCollectionUnlink(aField
.mEnd
);
1584 inline void ImplCycleCollectionTraverse(
1585 nsCycleCollectionTraversalCallback
& aCallback
, EditorDOMRange
& aField
,
1586 const char* aName
, uint32_t aFlags
) {
1587 ImplCycleCollectionTraverse(aCallback
, aField
.mStart
, "mStart", 0);
1588 ImplCycleCollectionTraverse(aCallback
, aField
.mEnd
, "mEnd", 0);
1592 * AutoEditorDOMPointOffsetInvalidator is useful if DOM tree will be changed
1593 * when EditorDOMPoint instance is available and keeps referring same child
1596 * This class automatically guarantees that given EditorDOMPoint instance
1597 * stores the child node and invalidates its offset when the instance is
1598 * destroyed. Additionally, users of this class can invalidate the offset
1599 * manually when they need.
1601 class MOZ_STACK_CLASS AutoEditorDOMPointOffsetInvalidator final
{
1603 AutoEditorDOMPointOffsetInvalidator() = delete;
1604 AutoEditorDOMPointOffsetInvalidator(
1605 const AutoEditorDOMPointOffsetInvalidator
&) = delete;
1606 AutoEditorDOMPointOffsetInvalidator(AutoEditorDOMPointOffsetInvalidator
&&) =
1608 const AutoEditorDOMPointOffsetInvalidator
& operator=(
1609 const AutoEditorDOMPointOffsetInvalidator
&) = delete;
1610 explicit AutoEditorDOMPointOffsetInvalidator(EditorDOMPoint
& aPoint
)
1611 : mPoint(aPoint
), mCanceled(false) {
1612 MOZ_ASSERT(aPoint
.IsSetAndValid());
1613 MOZ_ASSERT(mPoint
.CanContainerHaveChildren());
1614 mChild
= mPoint
.GetChild();
1617 ~AutoEditorDOMPointOffsetInvalidator() {
1624 * Manually, invalidate offset of the given point.
1626 void InvalidateOffset() {
1630 // If the point referred after the last child, let's keep referring
1631 // after current last node of the old container.
1632 mPoint
.SetToEndOf(mPoint
.GetContainer());
1637 * After calling Cancel(), mPoint won't be modified by the destructor.
1639 void Cancel() { mCanceled
= true; }
1642 EditorDOMPoint
& mPoint
;
1643 // Needs to store child node by ourselves because EditorDOMPoint stores
1644 // child node with mRef which is previous sibling of current child node.
1645 // Therefore, we cannot keep referring it if it's first child.
1646 nsCOMPtr
<nsIContent
> mChild
;
1651 class MOZ_STACK_CLASS AutoEditorDOMRangeOffsetsInvalidator final
{
1653 explicit AutoEditorDOMRangeOffsetsInvalidator(EditorDOMRange
& aRange
)
1654 : mStartInvalidator(const_cast<EditorDOMPoint
&>(aRange
.StartRef())),
1655 mEndInvalidator(const_cast<EditorDOMPoint
&>(aRange
.EndRef())) {}
1657 void InvalidateOffsets() {
1658 mStartInvalidator
.InvalidateOffset();
1659 mEndInvalidator
.InvalidateOffset();
1663 mStartInvalidator
.Cancel();
1664 mEndInvalidator
.Cancel();
1668 AutoEditorDOMPointOffsetInvalidator mStartInvalidator
;
1669 AutoEditorDOMPointOffsetInvalidator mEndInvalidator
;
1673 * AutoEditorDOMPointChildInvalidator is useful if DOM tree will be changed
1674 * when EditorDOMPoint instance is available and keeps referring same container
1677 * This class automatically guarantees that given EditorDOMPoint instance
1678 * stores offset and invalidates its child node when the instance is destroyed.
1679 * Additionally, users of this class can invalidate the child manually when
1682 class MOZ_STACK_CLASS AutoEditorDOMPointChildInvalidator final
{
1684 AutoEditorDOMPointChildInvalidator() = delete;
1685 AutoEditorDOMPointChildInvalidator(
1686 const AutoEditorDOMPointChildInvalidator
&) = delete;
1687 AutoEditorDOMPointChildInvalidator(AutoEditorDOMPointChildInvalidator
&&) =
1689 const AutoEditorDOMPointChildInvalidator
& operator=(
1690 const AutoEditorDOMPointChildInvalidator
&) = delete;
1691 explicit AutoEditorDOMPointChildInvalidator(EditorDOMPoint
& aPoint
)
1692 : mPoint(aPoint
), mCanceled(false) {
1693 MOZ_ASSERT(aPoint
.IsSetAndValid());
1694 Unused
<< mPoint
.Offset();
1697 ~AutoEditorDOMPointChildInvalidator() {
1704 * Manually, invalidate child of the given point.
1706 void InvalidateChild() { mPoint
.Set(mPoint
.GetContainer(), mPoint
.Offset()); }
1709 * After calling Cancel(), mPoint won't be modified by the destructor.
1711 void Cancel() { mCanceled
= true; }
1714 EditorDOMPoint
& mPoint
;
1719 class MOZ_STACK_CLASS AutoEditorDOMRangeChildrenInvalidator final
{
1721 explicit AutoEditorDOMRangeChildrenInvalidator(EditorDOMRange
& aRange
)
1722 : mStartInvalidator(const_cast<EditorDOMPoint
&>(aRange
.StartRef())),
1723 mEndInvalidator(const_cast<EditorDOMPoint
&>(aRange
.EndRef())) {}
1725 void InvalidateChildren() {
1726 mStartInvalidator
.InvalidateChild();
1727 mEndInvalidator
.InvalidateChild();
1731 mStartInvalidator
.Cancel();
1732 mEndInvalidator
.Cancel();
1736 AutoEditorDOMPointChildInvalidator mStartInvalidator
;
1737 AutoEditorDOMPointChildInvalidator mEndInvalidator
;
1740 } // namespace mozilla
1742 #endif // #ifndef mozilla_EditorDOMPoint_h