File: AutoClonedRangeArray.h

package info (click to toggle)
firefox 147.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,484 kB
  • sloc: cpp: 7,607,246; javascript: 6,533,185; ansic: 3,775,227; python: 1,415,393; xml: 634,561; asm: 438,951; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (629 lines) | stat: -rw-r--r-- 24,239 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

#ifndef AutoClonedRangeArray_h
#define AutoClonedRangeArray_h

#include "EditAction.h"      // for EditSubAction
#include "EditorBase.h"      // for EditorBase
#include "EditorDOMPoint.h"  // for EditorDOMPoint, EditorDOMRange, etc
#include "EditorForwards.h"
#include "HTMLEditHelpers.h"  // for BlockInlineCheck
#include "HTMLEditor.h"       // for HTMLEditor
#include "SelectionState.h"   // for SelectionState

#include "mozilla/ErrorResult.h"              // for ErrorResult
#include "mozilla/IntegerRange.h"             // for IntegerRange
#include "mozilla/Maybe.h"                    // for Maybe
#include "mozilla/RangeBoundary.h"            // for RangeBoundary
#include "mozilla/Result.h"                   // for Result<>
#include "mozilla/dom/Element.h"              // for dom::Element
#include "mozilla/dom/HTMLBRElement.h"        // for dom::HTMLBRElement
#include "mozilla/dom/Selection.h"            // for dom::Selection
#include "mozilla/dom/Text.h"                 // for dom::Text
#include "mozilla/intl/BidiEmbeddingLevel.h"  // for BidiEmbeddingLevel

#include "nsDebug.h"           // for NS_WARNING, etc
#include "nsDirection.h"       // for nsDirection
#include "nsError.h"           // for NS_SUCCESS_* and NS_ERROR_*
#include "nsFrameSelection.h"  // for nsFrameSelection
#include "nsRange.h"           // for nsRange

namespace mozilla {

enum class CaretAssociationHint;

/******************************************************************************
 * AutoClonedRangeArray stores closed ranges and has similar API to Selection.
 *****************************************************************************/

class MOZ_STACK_CLASS AutoClonedRangeArray {
 public:
  template <typename PointType>
  explicit AutoClonedRangeArray(const EditorDOMRangeBase<PointType>& aRange);
  template <typename PT, typename CT>
  explicit AutoClonedRangeArray(const EditorDOMPointBase<PT, CT>& aPoint);
  explicit AutoClonedRangeArray(const nsRange& aRange);
  // The copy constructor copies everything except saved ranges.
  explicit AutoClonedRangeArray(const AutoClonedRangeArray& aOther);

  virtual ~AutoClonedRangeArray() = default;

  /**
   * Check whether all ranges in content nodes or not.  If the ranges is empty,
   * this returns false.
   */
  [[nodiscard]] bool IsInContent() const {
    if (mRanges.IsEmpty()) {
      return false;
    }
    for (const OwningNonNull<nsRange>& range : mRanges) {
      if (MOZ_UNLIKELY(!range->IsPositioned() || !range->GetStartContainer() ||
                       !range->GetStartContainer()->IsContent() ||
                       !range->GetEndContainer() ||
                       !range->GetEndContainer()->IsContent())) {
        return false;
      }
    }
    return true;
  }

  /**
   * EnsureOnlyEditableRanges() removes ranges which cannot modify.
   * Note that this is designed only for `HTMLEditor` because this must not
   * be required by `TextEditor`.
   */
  void EnsureOnlyEditableRanges(const dom::Element& aEditingHost);

  /**
   * EnsureRangesInTextNode() is designed for TextEditor to guarantee that
   * all ranges are in its text node which is first child of the anonymous <div>
   * element and is first child.
   */
  void EnsureRangesInTextNode(const dom::Text& aTextNode);

  /**
   * Extend ranges to make each range select starting from a line start edge and
   * ending after a line end edge to handle per line edit sub-actions.
   */
  void ExtendRangesToWrapLines(EditSubAction aEditSubAction,
                               BlockInlineCheck aBlockInlineCheck,
                               const dom::Element& aAncestorLimiter);

  /**
   * Check whether the range is in aEditingHost and both containers of start and
   * end boundaries of the range are editable.
   */
  [[nodiscard]] static bool IsEditableRange(const dom::AbstractRange& aRange,
                                            const dom::Element& aEditingHost);

  /**
   * Check whether the first range is in aEditingHost and both containers of
   * start and end boundaries of the first range are editable.
   */
  [[nodiscard]] bool IsFirstRangeEditable(
      const dom::Element& aEditingHost) const {
    return IsEditableRange(FirstRangeRef(), aEditingHost);
  }

  /**
   * IsAtLeastOneContainerOfRangeBoundariesInclusiveDescendantOf() returns true
   * if at least one of the containers of the range boundaries is an inclusive
   * descendant of aContent.
   */
  [[nodiscard]] bool
  IsAtLeastOneContainerOfRangeBoundariesInclusiveDescendantOf(
      const nsIContent& aContent) const {
    for (const OwningNonNull<nsRange>& range : mRanges) {
      nsINode* startContainer = range->GetStartContainer();
      if (startContainer &&
          startContainer->IsInclusiveDescendantOf(&aContent)) {
        return true;
      }
      nsINode* endContainer = range->GetEndContainer();
      if (startContainer == endContainer) {
        continue;
      }
      if (endContainer && endContainer->IsInclusiveDescendantOf(&aContent)) {
        return true;
      }
    }
    return false;
  }

  [[nodiscard]] auto& Ranges() { return mRanges; }
  [[nodiscard]] const auto& Ranges() const { return mRanges; }
  [[nodiscard]] OwningNonNull<nsRange>& FirstRangeRef() { return mRanges[0]; }
  [[nodiscard]] const OwningNonNull<nsRange>& FirstRangeRef() const {
    return mRanges[0];
  }

  template <template <typename> typename StrongPtrType>
  [[nodiscard]] AutoTArray<StrongPtrType<nsRange>, 8> CloneRanges() const {
    AutoTArray<StrongPtrType<nsRange>, 8> ranges;
    for (const auto& range : mRanges) {
      ranges.AppendElement(range->CloneRange());
    }
    return ranges;
  }

  template <typename EditorDOMPointType>
  [[nodiscard]] EditorDOMPointType GetFirstRangeStartPoint() const {
    if (mRanges.IsEmpty() || !mRanges[0]->IsPositioned()) {
      return EditorDOMPointType();
    }
    return EditorDOMPointType(mRanges[0]->StartRef());
  }
  template <typename EditorDOMPointType>
  [[nodiscard]] EditorDOMPointType GetFirstRangeEndPoint() const {
    if (mRanges.IsEmpty() || !mRanges[0]->IsPositioned()) {
      return EditorDOMPointType();
    }
    return EditorDOMPointType(mRanges[0]->EndRef());
  }

  nsresult SelectNode(nsINode& aNode) {
    mRanges.Clear();
    if (!mAnchorFocusRange) {
      mAnchorFocusRange = nsRange::Create(&aNode);
      if (!mAnchorFocusRange) {
        return NS_ERROR_FAILURE;
      }
    }
    ErrorResult error;
    mAnchorFocusRange->SelectNode(aNode, error);
    if (error.Failed()) {
      mAnchorFocusRange = nullptr;
      return error.StealNSResult();
    }
    mRanges.AppendElement(*mAnchorFocusRange);
    return NS_OK;
  }

  /**
   * For compatiblity with the other browsers, we should shrink ranges to
   * start from an atomic content and/or end after one instead of start
   * from end of a preceding text node and end by start of a follwing text
   * node.  Returns true if this modifies a range.
   */
  enum class IfSelectingOnlyOneAtomicContent {
    Collapse,  // Collapse to the range selecting only one atomic content to
               // start or after of it.  Whether to collapse start or after
               // it depends on aDirectionAndAmount.  This is ignored if
               // there are multiple ranges.
    KeepSelecting,  // Won't collapse the range.
  };
  Result<bool, nsresult> ShrinkRangesIfStartFromOrEndAfterAtomicContent(
      const HTMLEditor& aHTMLEditor, nsIEditor::EDirection aDirectionAndAmount,
      IfSelectingOnlyOneAtomicContent aIfSelectingOnlyOneAtomicContent);

  /**
   * The following methods are same as `Selection`'s methods.
   */
  [[nodiscard]] bool IsCollapsed() const {
    return mRanges.IsEmpty() ||
           (mRanges.Length() == 1 && mRanges[0]->Collapsed());
  }
  template <typename PT, typename CT>
  nsresult Collapse(const EditorDOMPointBase<PT, CT>& aPoint) {
    mRanges.Clear();
    if (!mAnchorFocusRange) {
      ErrorResult error;
      mAnchorFocusRange = nsRange::Create(aPoint.ToRawRangeBoundary(),
                                          aPoint.ToRawRangeBoundary(), error);
      if (error.Failed()) {
        mAnchorFocusRange = nullptr;
        return error.StealNSResult();
      }
    } else {
      nsresult rv = mAnchorFocusRange->CollapseTo(aPoint.ToRawRangeBoundary());
      if (NS_FAILED(rv)) {
        mAnchorFocusRange = nullptr;
        return rv;
      }
    }
    mRanges.AppendElement(*mAnchorFocusRange);
    SetNewCaretAssociationHint(aPoint.ToRawRangeBoundary(),
                               aPoint.GetInterlinePosition());
    return NS_OK;
  }
  template <typename SPT, typename SCT, typename EPT, typename ECT>
  nsresult SetStartAndEnd(const EditorDOMPointBase<SPT, SCT>& aStart,
                          const EditorDOMPointBase<EPT, ECT>& aEnd) {
    mRanges.Clear();
    if (!mAnchorFocusRange) {
      ErrorResult error;
      mAnchorFocusRange = nsRange::Create(aStart.ToRawRangeBoundary(),
                                          aEnd.ToRawRangeBoundary(), error);
      if (error.Failed()) {
        mAnchorFocusRange = nullptr;
        return error.StealNSResult();
      }
    } else {
      nsresult rv = mAnchorFocusRange->SetStartAndEnd(
          aStart.ToRawRangeBoundary(), aEnd.ToRawRangeBoundary());
      if (NS_FAILED(rv)) {
        mAnchorFocusRange = nullptr;
        return rv;
      }
    }
    mRanges.AppendElement(*mAnchorFocusRange);
    return NS_OK;
  }
  template <typename SPT, typename SCT, typename EPT, typename ECT>
  nsresult SetBaseAndExtent(const EditorDOMPointBase<SPT, SCT>& aAnchor,
                            const EditorDOMPointBase<EPT, ECT>& aFocus) {
    if (MOZ_UNLIKELY(!aAnchor.IsSet()) || MOZ_UNLIKELY(!aFocus.IsSet())) {
      mRanges.Clear();
      mAnchorFocusRange = nullptr;
      return NS_ERROR_INVALID_ARG;
    }
    return aAnchor.EqualsOrIsBefore(aFocus) ? SetStartAndEnd(aAnchor, aFocus)
                                            : SetStartAndEnd(aFocus, aAnchor);
  }
  [[nodiscard]] const nsRange* GetAnchorFocusRange() const {
    return mAnchorFocusRange;
  }
  [[nodiscard]] nsDirection GetDirection() const { return mDirection; }

  void SetDirection(nsDirection aDirection) { mDirection = aDirection; }

  [[nodiscard]] const RangeBoundary& AnchorRef() const {
    if (!mAnchorFocusRange) {
      static RangeBoundary sEmptyRangeBoundary;
      return sEmptyRangeBoundary;
    }
    return mDirection == nsDirection::eDirNext ? mAnchorFocusRange->StartRef()
                                               : mAnchorFocusRange->EndRef();
  }
  [[nodiscard]] nsINode* GetAnchorNode() const {
    return AnchorRef().IsSet() ? AnchorRef().GetContainer() : nullptr;
  }
  [[nodiscard]] uint32_t GetAnchorOffset() const {
    return AnchorRef().IsSet()
               ? AnchorRef()
                     .Offset(RangeBoundary::OffsetFilter::kValidOffsets)
                     .valueOr(0)
               : 0;
  }
  [[nodiscard]] nsIContent* GetChildAtAnchorOffset() const {
    return AnchorRef().IsSet() ? AnchorRef().GetChildAtOffset() : nullptr;
  }

  [[nodiscard]] const RangeBoundary& FocusRef() const {
    if (!mAnchorFocusRange) {
      static RangeBoundary sEmptyRangeBoundary;
      return sEmptyRangeBoundary;
    }
    return mDirection == nsDirection::eDirNext ? mAnchorFocusRange->EndRef()
                                               : mAnchorFocusRange->StartRef();
  }
  [[nodiscard]] nsINode* GetFocusNode() const {
    return FocusRef().IsSet() ? FocusRef().GetContainer() : nullptr;
  }
  [[nodiscard]] uint32_t FocusOffset() const {
    return FocusRef().IsSet()
               ? FocusRef()
                     .Offset(RangeBoundary::OffsetFilter::kValidOffsets)
                     .valueOr(0)
               : 0;
  }
  [[nodiscard]] nsIContent* GetChildAtFocusOffset() const {
    return FocusRef().IsSet() ? FocusRef().GetChildAtOffset() : nullptr;
  }

  void RemoveAllRanges() {
    mRanges.Clear();
    mAnchorFocusRange = nullptr;
    mDirection = nsDirection::eDirNext;
  }

  void RemoveCollapsedRanges();

  /**
   * If the points are same (i.e., mean a collapsed range) and in an empty block
   * element except the padding <br> element, this makes aStartPoint and
   * aEndPoint contain the padding <br> element.
   */
  static void UpdatePointsToSelectAllChildrenIfCollapsedInEmptyBlockElement(
      EditorDOMPoint& aStartPoint, EditorDOMPoint& aEndPoint,
      const dom::Element& aEditingHost);

  /**
   * CreateRangeExtendedToHardLineStartAndEnd() creates an nsRange instance
   * which may be expanded to start/end of hard line at both edges of the given
   * range.  If this fails handling something, returns nullptr.
   */
  static already_AddRefed<nsRange>
  CreateRangeWrappingStartAndEndLinesContainingBoundaries(
      const EditorDOMRange& aRange, EditSubAction aEditSubAction,
      BlockInlineCheck aBlockInlineCheck, const dom::Element& aEditingHost) {
    if (!aRange.IsPositioned()) {
      return nullptr;
    }
    return CreateRangeWrappingStartAndEndLinesContainingBoundaries(
        aRange.StartRef(), aRange.EndRef(), aEditSubAction, aBlockInlineCheck,
        aEditingHost);
  }
  static already_AddRefed<nsRange>
  CreateRangeWrappingStartAndEndLinesContainingBoundaries(
      const EditorDOMPoint& aStartPoint, const EditorDOMPoint& aEndPoint,
      EditSubAction aEditSubAction, BlockInlineCheck aBlockInlineCheck,
      const dom::Element& aEditingHost) {
    RefPtr<nsRange> range =
        nsRange::Create(aStartPoint.ToRawRangeBoundary(),
                        aEndPoint.ToRawRangeBoundary(), IgnoreErrors());
    if (MOZ_UNLIKELY(!range)) {
      return nullptr;
    }
    if (NS_FAILED(ExtendRangeToWrapStartAndEndLinesContainingBoundaries(
            *range, aEditSubAction, aBlockInlineCheck, aEditingHost)) ||
        MOZ_UNLIKELY(!range->IsPositioned())) {
      return nullptr;
    }
    return range.forget();
  }

  /**
   * Splits text nodes if each range end is in middle of a text node, then,
   * calls HTMLEditor::SplitParentInlineElementsAtRangeBoundaries() for each
   * range.  Finally, updates ranges to keep edit target ranges as expected.
   *
   * @param aHTMLEditor         The HTMLEditor which will handle the splittings.
   * @param aBlockInlineCheck   Considering block vs inline with whether the
   *                            computed style or the HTML default style.
   * @param aElement            The editing host.
   * @param aAncestorLimiter    A content node which you don't want this to
   *                            split it.
   * @return                    A suggest point to put caret if succeeded, but
   *                            it may be unset.
   */
  [[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<EditorDOMPoint, nsresult>
  SplitTextAtEndBoundariesAndInlineAncestorsAtBothBoundaries(
      HTMLEditor& aHTMLEditor, BlockInlineCheck aBlockInlineCheck,
      const dom::Element& aEditingHost,
      const nsIContent* aAncestorLimiter = nullptr);

  /**
   * CollectEditTargetNodes() collects edit target nodes the ranges.
   * First, this collects all nodes in given ranges, then, modifies the
   * result for specific edit sub-actions.
   */
  enum class CollectNonEditableNodes { No, Yes };
  nsresult CollectEditTargetNodes(
      const HTMLEditor& aHTMLEditor,
      nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
      EditSubAction aEditSubAction,
      CollectNonEditableNodes aCollectNonEditableNodes) const;

  /**
   * Retrieve a closest ancestor list element of a common ancestor of _A_ range
   * of the ranges.  This tries to retrieve it from the first range to the last
   * range.
   */
  dom::Element* GetClosestAncestorAnyListElementOfRange() const;

  [[nodiscard]] virtual bool HasSavedRanges() const { return false; }

  /**
   * Extend all ranges to contain surrounding invisible white-spaces if there
   * are.
   *
   * @param aStripWrappers      nsIEditor::eStrip if the caller wants to delete
   *                            inline ancestors too.
   */
  void ExtendRangeToContainSurroundingInvisibleWhiteSpaces(
      nsIEditor::EStripWrappers aStripWrappers);

 protected:
  AutoClonedRangeArray() = default;

  static nsresult ExtendRangeToWrapStartAndEndLinesContainingBoundaries(
      nsRange& aRange, EditSubAction aEditSubAction,
      BlockInlineCheck aBlockInlineCheck, const dom::Element& aEditingHost);

  using InterlinePosition = dom::Selection::InterlinePosition;
  virtual void SetNewCaretAssociationHint(
      const RawRangeBoundary& aPoint, InterlinePosition aInterlinePosition) {}

  AutoTArray<mozilla::OwningNonNull<nsRange>, 8> mRanges;
  RefPtr<nsRange> mAnchorFocusRange;
  nsDirection mDirection = nsDirection::eDirNext;
};

/******************************************************************************
 * AutoClonedSelectionRangeArray stores closed ranges and have similar API of
 * Selection.  So, different from `AutoSelectionRangeArray`, this can be used
 * for ranges which may need to be modified before touching the DOM tree, but
 * does not want to modify `Selection` for the performance.
 *****************************************************************************/

class MOZ_STACK_CLASS AutoClonedSelectionRangeArray final
    : public AutoClonedRangeArray {
  using Selection = dom::Selection;

 public:
  AutoClonedSelectionRangeArray() = delete;
  explicit AutoClonedSelectionRangeArray(const Selection& aSelection);
  template <typename PointType>
  AutoClonedSelectionRangeArray(
      const EditorDOMRangeBase<PointType>& aRange,
      const LimitersAndCaretData& aLimitersAndCaretData);
  template <typename PT, typename CT>
  AutoClonedSelectionRangeArray(
      const EditorDOMPointBase<PT, CT>& aPoint,
      const LimitersAndCaretData& aLimitersAndCaretData);
  AutoClonedSelectionRangeArray(
      const nsRange& aRange, const LimitersAndCaretData& aLimitersAndCaretData);
  // The copy constructor copies everything except saved ranges.
  explicit AutoClonedSelectionRangeArray(
      const AutoClonedSelectionRangeArray& aOther);

  ~AutoClonedSelectionRangeArray() override {
    if (HasSavedRanges()) {
      ClearSavedRanges();
    }
  }

  void Initialize(const Selection& aSelection) {
    ClearSavedRanges();
    mDirection = aSelection.GetDirection();
    mRanges.Clear();
    if (nsFrameSelection* frameSelection = aSelection.GetFrameSelection()) {
      mLimitersAndCaretData = LimitersAndCaretData(*frameSelection);
    }
    for (const uint32_t i : IntegerRange(aSelection.RangeCount())) {
      MOZ_ASSERT(aSelection.GetRangeAt(i));
      const nsRange* const range = aSelection.GetRangeAt(i);
      if (!RangeIsInLimiters(*range)) {
        continue;
      }
      mRanges.AppendElement(range->CloneRange());
      if (range == aSelection.GetAnchorFocusRange()) {
        mAnchorFocusRange = mRanges.LastElement();
      }
    }
  }

  /**
   * APIs to store ranges with only container node and offset in it, and track
   * them with RangeUpdater.
   */
  [[nodiscard]] bool SaveAndTrackRanges(HTMLEditor& aHTMLEditor);
  [[nodiscard]] bool HasSavedRanges() const override {
    return mSavedRanges.isSome();
  }
  void ClearSavedRanges();
  void RestoreFromSavedRanges() {
    MOZ_DIAGNOSTIC_ASSERT(mSavedRanges.isSome());
    if (MOZ_UNLIKELY(mSavedRanges.isNothing())) {
      return;
    }
    mSavedRanges->ApplyTo(*this);
    ClearSavedRanges();
  }

  /**
   * Apply mRanges and mDirection to aSelection.
   */
  MOZ_CAN_RUN_SCRIPT nsresult ApplyTo(dom::Selection& aSelection) {
    dom::SelectionBatcher selectionBatcher(aSelection, __FUNCTION__);
    aSelection.RemoveAllRanges(IgnoreErrors());
    MOZ_ASSERT(!aSelection.RangeCount());
    aSelection.SetDirection(mDirection);
    IgnoredErrorResult error;
    for (const OwningNonNull<nsRange>& range : mRanges) {
      // MOZ_KnownLive(range) due to bug 1622253
      aSelection.AddRangeAndSelectFramesAndNotifyListeners(MOZ_KnownLive(range),
                                                           error);
      if (MOZ_UNLIKELY(error.Failed())) {
        return error.StealNSResult();
      }
    }
    // FIXME: If and only if the interline position is set explicitly, we need
    // to call `Selection::SetInterlinePosition` here with the specified value.
    // However, currently nobody does it.
    return NS_OK;
  }

  [[nodiscard]] const LimitersAndCaretData& LimitersAndCaretDataRef() const {
    return mLimitersAndCaretData;
  }

  /**
   * Equivalent to nsFrameSelection::GetIndependentSelectionRootElement().
   * NOTE: This should be called only when IsForSelection() returns true.
   */
  [[nodiscard]] dom::Element* GetIndependentSelectionRootElement() const {
    return mLimitersAndCaretData.mIndependentSelectionRootElement;
  }
  /**
   * Equivalent to nsFrameSelection::GetAncestorLimiter()
   * NOTE: This should be called only when IsForSelection() returns true.
   */
  [[nodiscard]] dom::Element* GetAncestorLimiter() const {
    return mLimitersAndCaretData.mAncestorLimiter;
  }
  /**
   * Equivalent to nsFrameSelection::GetHint(), this may be updated when
   * Collapse() is called.  Otherwise, this value may mismatch with what
   * nsFrameSelection returns if you worked with nsFrameSelection and
   * Selection directly.
   */
  [[nodiscard]] CaretAssociationHint GetHint() const {
    return mLimitersAndCaretData.mCaretAssociationHint;
  }
  /**
   * Equivalent to nsFrameSelection::GetCaretBidiLevel(), this returns the value
   * when this is initialized with nsFrameSelection or inherits another
   * instance.  Therefore, the value may be invalid once you already modified
   * the ranges.
   */
  [[nodiscard]] intl::BidiEmbeddingLevel GetCaretBidiLevel() const {
    return mLimitersAndCaretData.mCaretBidiLevel;
  }

  void SetAncestorLimiter(const dom::Element* aSelectionAncestorLimiter) {
    if (mLimitersAndCaretData.mAncestorLimiter == aSelectionAncestorLimiter) {
      return;
    }
    mLimitersAndCaretData.mAncestorLimiter =
        const_cast<dom::Element*>(aSelectionAncestorLimiter);
    if (NodeIsInLimiters(GetFocusNode())) {
      return;
    }
    RemoveAllRanges();
  }

  void SetInterlinePosition(Selection::InterlinePosition aInterlinePosition) {
    switch (aInterlinePosition) {
      case Selection::InterlinePosition::EndOfLine:
        mLimitersAndCaretData.mCaretAssociationHint =
            CaretAssociationHint::Before;
        break;
      case Selection::InterlinePosition::StartOfNextLine:
        mLimitersAndCaretData.mCaretAssociationHint =
            CaretAssociationHint::After;
        break;
      case Selection::InterlinePosition::Undefined:
        break;
    }
  }

  void SetCaretBidiLevel(intl::BidiEmbeddingLevel aBidiLevel) {
    mLimitersAndCaretData.mCaretBidiLevel = aBidiLevel;
  }

  [[nodiscard]] bool NodeIsInLimiters(const nsINode* aContainerNode) const {
    return mLimitersAndCaretData.NodeIsInLimiters(aContainerNode);
  }
  [[nodiscard]] bool RangeIsInLimiters(const dom::AbstractRange& aRange) const {
    return mLimitersAndCaretData.RangeInLimiters(aRange);
  }

  /**
   * ExtendAnchorFocusRangeFor() extends the anchor-focus range for deleting
   * content for aDirectionAndAmount.  The range won't be extended to outer of
   * selection limiter.  Note that if a range is extened, the range is
   * recreated.  Therefore, caller cannot cache pointer of any ranges before
   * calling this.
   */
  [[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<nsIEditor::EDirection, nsresult>
  ExtendAnchorFocusRangeFor(const EditorBase& aEditorBase,
                            nsIEditor::EDirection aDirectionAndAmount);

 private:
  void SetNewCaretAssociationHint(
      const RawRangeBoundary& aRawRangeBoundary,
      InterlinePosition aInternlinePosition) override;

  Maybe<SelectionState> mSavedRanges;
  RefPtr<HTMLEditor> mTrackingHTMLEditor;
  LimitersAndCaretData mLimitersAndCaretData;
};

}  // namespace mozilla

#endif  // #ifndef AutoClonedRangeArray_h