DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Implementation

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
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
/* -*- 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.
 */

#ifndef nsRange_h___
#define nsRange_h___

#include "nsCOMPtr.h"
#include "mozilla/dom/AbstractRange.h"
#include "nsLayoutUtils.h"
#include "prmon.h"
#include "nsStubMutationObserver.h"
#include "nsWrapperCache.h"
#include "mozilla/Attributes.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/GuardObjects.h"
#include "mozilla/LinkedList.h"
#include "mozilla/RangeBoundary.h"

namespace mozilla {
namespace dom {
struct ClientRectsAndTexts;
class DocGroup;
class DocumentFragment;
class DOMRect;
class DOMRectList;
class InspectorFontFace;
class Selection;
}  // namespace dom
}  // namespace mozilla

class nsRange final : public mozilla::dom::AbstractRange,
                      public nsStubMutationObserver,
                      // For linking together selection-associated ranges.
                      public mozilla::LinkedListElement<nsRange> {
  typedef mozilla::ErrorResult ErrorResult;
  typedef mozilla::dom::AbstractRange AbstractRange;
  typedef mozilla::dom::DocGroup DocGroup;
  typedef mozilla::dom::DOMRect DOMRect;
  typedef mozilla::dom::DOMRectList DOMRectList;
  typedef mozilla::RangeBoundary RangeBoundary;
  typedef mozilla::RawRangeBoundary RawRangeBoundary;

  virtual ~nsRange();

 public:
  explicit nsRange(nsINode* aNode);

  /**
   * Create() may return `nsRange` instance which is initialized with
   * given range or points.  If it fails initializing new range with the
   * arguments, returns `nullptr`.  `ErrorResult` is set to an error only
   * when this returns `nullptr`.  The error code indicates the reason why
   * it couldn't initialize the instance.
   */
  static already_AddRefed<nsRange> Create(const AbstractRange* aAbstractRange,
                                          ErrorResult& aRv) {
    return nsRange::Create(aAbstractRange->StartRef(), aAbstractRange->EndRef(),
                           aRv);
  }
  static already_AddRefed<nsRange> Create(nsINode* aStartContainer,
                                          uint32_t aStartOffset,
                                          nsINode* aEndContainer,
                                          uint32_t aEndOffset,
                                          ErrorResult& aRv) {
    return nsRange::Create(RawRangeBoundary(aStartContainer, aStartOffset),
                           RawRangeBoundary(aEndContainer, aEndOffset), aRv);
  }
  template <typename SPT, typename SRT, typename EPT, typename ERT>
  static already_AddRefed<nsRange> Create(
      const mozilla::RangeBoundaryBase<SPT, SRT>& aStartBoundary,
      const mozilla::RangeBoundaryBase<EPT, ERT>& aEndBoundary,
      ErrorResult& aRv);

  NS_DECL_ISUPPORTS_INHERITED
  NS_IMETHODIMP_(void) DeleteCycleCollectable(void) override;
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(nsRange, AbstractRange)

  nsrefcnt GetRefCount() const { return mRefCnt; }

  nsINode* GetRoot() const { return mRoot; }

  /**
   * Return true iff this range is part of a Selection object
   * and isn't detached.
   */
  bool IsInSelection() const { return !!mSelection; }

  /**
   * Called when the range is added/removed from a Selection.
   */
  void SetSelection(mozilla::dom::Selection* aSelection);

  /**
   * Returns pointer to a Selection if the range is associated with a Selection.
   */
  mozilla::dom::Selection* GetSelection() const { return mSelection; }

  /**
   * Return true if this range was generated.
   * @see SetIsGenerated
   */
  bool IsGenerated() const { return mIsGenerated; }

  /**
   * Mark this range as being generated or not.
   * Currently it is used for marking ranges that are created when splitting up
   * a range to exclude a -moz-user-select:none region.
   * @see Selection::AddRangesForSelectableNodes
   * @see ExcludeNonSelectableNodes
   */
  void SetIsGenerated(bool aIsGenerated) { mIsGenerated = aIsGenerated; }

  void Reset();

  /**
   * ResetTemporarily() is called when Selection starts to cache the instance
   * to reuse later.  This method clears mStart, mEnd and mIsPositioned but
   * does not clear mRoot for reducing the cost to register this as a mutation
   * observer again.
   */
  void ResetTemporarily() {
    DoSetRange(RawRangeBoundary(), RawRangeBoundary(), mRoot);
  }

  /**
   * SetStart() and SetEnd() sets start point or end point separately.
   * However, this is expensive especially when it's a range of Selection.
   * When you set both start and end of a range, you should use
   * SetStartAndEnd() instead.
   */
  nsresult SetStart(nsINode* aContainer, uint32_t aOffset) {
    ErrorResult error;
    SetStart(RawRangeBoundary(aContainer, aOffset), error);
    return error.StealNSResult();
  }
  nsresult SetEnd(nsINode* aContainer, uint32_t aOffset) {
    ErrorResult error;
    SetEnd(RawRangeBoundary(aContainer, aOffset), error);
    return error.StealNSResult();
  }

  already_AddRefed<nsRange> CloneRange() const;

  /**
   * SetStartAndEnd() works similar to call both SetStart() and SetEnd().
   * Different from calls them separately, this does nothing if either
   * the start point or the end point is invalid point.
   * If the specified start point is after the end point, the range will be
   * collapsed at the end point.  Similarly, if they are in different root,
   * the range will be collapsed at the end point.
   */
  nsresult SetStartAndEnd(nsINode* aStartContainer, uint32_t aStartOffset,
                          nsINode* aEndContainer, uint32_t aEndOffset) {
    return SetStartAndEnd(RawRangeBoundary(aStartContainer, aStartOffset),
                          RawRangeBoundary(aEndContainer, aEndOffset));
  }
  template <typename SPT, typename SRT, typename EPT, typename ERT>
  nsresult SetStartAndEnd(
      const mozilla::RangeBoundaryBase<SPT, SRT>& aStartBoundary,
      const mozilla::RangeBoundaryBase<EPT, ERT>& aEndBoundary) {
    return AbstractRange::SetStartAndEndInternal(aStartBoundary, aEndBoundary,
                                                 this);
  }

  /**
   * Adds all nodes between |aStartContent| and |aEndContent| to the range.
   * The start offset will be set before |aStartContent|,
   * while the end offset will be set immediately after |aEndContent|.
   *
   * Caller must guarantee both nodes are non null and
   * children of |aContainer| and that |aEndContent| is after |aStartContent|.
   */
  void SelectNodesInContainer(nsINode* aContainer, nsIContent* aStartContent,
                              nsIContent* aEndContent);

  /**
   * CollapseTo() works similar to call both SetStart() and SetEnd() with
   * same node and offset.  This just calls SetStartAndParent() to set
   * collapsed range at aContainer and aOffset.
   */
  nsresult CollapseTo(nsINode* aContainer, uint32_t aOffset) {
    return CollapseTo(RawRangeBoundary(aContainer, aOffset));
  }
  nsresult CollapseTo(const RawRangeBoundary& aPoint) {
    return SetStartAndEnd(aPoint, aPoint);
  }

  // aMaxRanges is the maximum number of text ranges to record for each face
  // (pass 0 to just get the list of faces, without recording exact ranges
  // where each face was used).
  nsresult GetUsedFontFaces(
      nsTArray<nsAutoPtr<mozilla::dom::InspectorFontFace>>& aResult,
      uint32_t aMaxRanges, bool aSkipCollapsedWhitespace);

  // nsIMutationObserver methods
  NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATACHANGED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
  NS_DECL_NSIMUTATIONOBSERVER_PARENTCHAINCHANGED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED

  // WebIDL
  static already_AddRefed<nsRange> Constructor(
      const mozilla::dom::GlobalObject& global, mozilla::ErrorResult& aRv);

  already_AddRefed<mozilla::dom::DocumentFragment> CreateContextualFragment(
      const nsAString& aString, ErrorResult& aError);
  already_AddRefed<mozilla::dom::DocumentFragment> CloneContents(
      ErrorResult& aErr);
  int16_t CompareBoundaryPoints(uint16_t aHow, nsRange& aOther,
                                ErrorResult& aErr);
  int16_t ComparePoint(nsINode& aContainer, uint32_t aOffset,
                       ErrorResult& aErr) {
    return ComparePoint(RawRangeBoundary(&aContainer, aOffset), aErr);
  }
  int16_t ComparePoint(const RawRangeBoundary& aPoint, ErrorResult& aErr);
  void DeleteContents(ErrorResult& aRv);
  already_AddRefed<mozilla::dom::DocumentFragment> ExtractContents(
      ErrorResult& aErr);
  nsINode* GetCommonAncestorContainer(ErrorResult& aRv) const {
    if (!mIsPositioned) {
      aRv.Throw(NS_ERROR_NOT_INITIALIZED);
      return nullptr;
    }
    return GetCommonAncestor();
  }
  void InsertNode(nsINode& aNode, ErrorResult& aErr);
  bool IntersectsNode(nsINode& aNode, ErrorResult& aRv);
  bool IsPointInRange(nsINode& aContainer, uint32_t aOffset,
                      ErrorResult& aErr) {
    return IsPointInRange(RawRangeBoundary(&aContainer, aOffset), aErr);
  }
  bool IsPointInRange(const RawRangeBoundary& aPoint, ErrorResult& aErr);
  void ToString(nsAString& aReturn, ErrorResult& aErr);
  void Detach();

  // *JS() methods are mapped to Range.*() of DOM.
  // They may move focus only when the range represents normal selection.
  // These methods shouldn't be used from internal.
  void CollapseJS(bool aToStart);
  void SelectNodeJS(nsINode& aNode, ErrorResult& aErr);
  void SelectNodeContentsJS(nsINode& aNode, ErrorResult& aErr);
  void SetEndJS(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr);
  void SetEndAfterJS(nsINode& aNode, ErrorResult& aErr);
  void SetEndBeforeJS(nsINode& aNode, ErrorResult& aErr);
  void SetStartJS(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr);
  void SetStartAfterJS(nsINode& aNode, ErrorResult& aErr);
  void SetStartBeforeJS(nsINode& aNode, ErrorResult& aErr);

  void SurroundContents(nsINode& aNode, ErrorResult& aErr);
  already_AddRefed<DOMRect> GetBoundingClientRect(bool aClampToEdge = true,
                                                  bool aFlushLayout = true);
  already_AddRefed<DOMRectList> GetClientRects(bool aClampToEdge = true,
                                               bool aFlushLayout = true);
  void GetClientRectsAndTexts(mozilla::dom::ClientRectsAndTexts& aResult,
                              ErrorResult& aErr);

  // Following methods should be used for internal use instead of *JS().
  void SelectNode(nsINode& aNode, ErrorResult& aErr);
  void SelectNodeContents(nsINode& aNode, ErrorResult& aErr);
  void SetEnd(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr);
  void SetEnd(const RawRangeBoundary& aPoint, ErrorResult& aErr);
  void SetEndAfter(nsINode& aNode, ErrorResult& aErr);
  void SetEndBefore(nsINode& aNode, ErrorResult& aErr);
  void SetStart(nsINode& aNode, uint32_t aOffset, ErrorResult& aErr);
  void SetStart(const RawRangeBoundary& aPoint, ErrorResult& aErr);
  void SetStartAfter(nsINode& aNode, ErrorResult& aErr);
  void SetStartBefore(nsINode& aNode, ErrorResult& aErr);
  void Collapse(bool aToStart);

  static void GetInnerTextNoFlush(mozilla::dom::DOMString& aValue,
                                  mozilla::ErrorResult& aError,
                                  nsIContent* aContainer);

  virtual JSObject* WrapObject(JSContext* cx,
                               JS::Handle<JSObject*> aGivenProto) final;
  DocGroup* GetDocGroup() const;

 private:
  // no copy's or assigns
  nsRange(const nsRange&);
  nsRange& operator=(const nsRange&);

  /**
   * Cut or delete the range's contents.
   *
   * @param aFragment DocumentFragment containing the nodes.
   *                  May be null to indicate the caller doesn't want a
   * fragment.
   */
  nsresult CutContents(mozilla::dom::DocumentFragment** frag);

  static nsresult CloneParentsBetween(nsINode* aAncestor, nsINode* aNode,
                                      nsINode** aClosestAncestor,
                                      nsINode** aFarthestAncestor);

  /**
   * Returns whether a node is safe to be accessed by the current caller.
   */
  bool CanAccess(const nsINode&) const;

 public:
  /**
   * Return true if any part of (aNode, aStartOffset) .. (aNode, aEndOffset)
   * overlaps any nsRange in aNode's GetNextRangeCommonAncestor ranges (i.e.
   * where aNode is a descendant of a range's common ancestor node).
   * If a nsRange starts in (aNode, aEndOffset) or if it ends in
   * (aNode, aStartOffset) then it is non-overlapping and the result is false
   * for that nsRange.  Collapsed ranges always counts as non-overlapping.
   */
  static bool IsNodeSelected(nsINode* aNode, uint32_t aStartOffset,
                             uint32_t aEndOffset);

  /**
   * This helper function gets rects and correlated text for the given range.
   * @param aTextList optional where nullptr = don't retrieve text
   */
  static void CollectClientRectsAndText(
      nsLayoutUtils::RectCallback* aCollector,
      mozilla::dom::Sequence<nsString>* aTextList, nsRange* aRange,
      nsINode* aStartContainer, uint32_t aStartOffset, nsINode* aEndContainer,
      uint32_t aEndOffset, bool aClampToEdge, bool aFlushLayout);

  /**
   * Scan this range for -moz-user-select:none nodes and split it up into
   * multiple ranges to exclude those nodes.  The resulting ranges are put
   * in aOutRanges.  If no -moz-user-select:none node is found in the range
   * then |this| is unmodified and is the only range in aOutRanges.
   * Otherwise, |this| will be modified so that it ends before the first
   * -moz-user-select:none node and additional ranges may also be created.
   * If all nodes in the range are -moz-user-select:none then aOutRanges
   * will be empty.
   * @param aOutRanges the resulting set of ranges
   */
  void ExcludeNonSelectableNodes(nsTArray<RefPtr<nsRange>>* aOutRanges);

  /**
   * Notify the selection listeners after a range has been modified.
   */
  MOZ_CAN_RUN_SCRIPT void NotifySelectionListenersAfterRangeSet();

  typedef nsTHashtable<nsPtrHashKey<nsRange>> RangeHashTable;

 protected:
  void RegisterCommonAncestor(nsINode* aNode);
  void UnregisterCommonAncestor(nsINode* aNode, bool aIsUnlinking);

  /**
   * DoSetRange() is called when `AbstractRange::SetStartAndEndInternal()` sets
   * mStart and mEnd, or some other internal methods modify `mStart` and/or
   * `mEnd`.  Therefore, this shouldn't be a virtual method.
   *
   * @param aStartBoundary      Computed start point.  This must equals or be
   *                            before aEndBoundary in the DOM tree order.
   * @param aEndBoundary        Computed end point.
   * @param aRootNode           The root node.
   * @param aNotInsertedYet     true if this is called by CharacterDataChanged()
   *                            to disable assertion and suppress re-registering
   *                            a range common ancestor node since the new text
   *                            node of a splitText hasn't been inserted yet.
   *                            CharacterDataChanged() does the re-registering
   *                            when needed.  Otherwise, false.
   */
  template <typename SPT, typename SRT, typename EPT, typename ERT>
  MOZ_CAN_RUN_SCRIPT_BOUNDARY void DoSetRange(
      const mozilla::RangeBoundaryBase<SPT, SRT>& aStartBoundary,
      const mozilla::RangeBoundaryBase<EPT, ERT>& aEndBoundary,
      nsINode* aRootNode, bool aNotInsertedYet = false);

  /**
   * For a range for which IsInSelection() is true, return the common ancestor
   * for the range, which we had to compute when the common ancestor changed or
   * IsInSelection became true, so we could register with it.  That is, it's a
   * faster version of GetCommonAncestor that only works for ranges in a
   * Selection.  The method will assert and the behavior is undefined if called
   * on a range where IsInSelection() is false.
   */
  nsINode* GetRegisteredCommonAncestor();

  // Helper to IsNodeSelected.
  static bool IsNodeInSortedRanges(nsINode* aNode, uint32_t aStartOffset,
                                   uint32_t aEndOffset,
                                   const nsTArray<const nsRange*>& aRanges,
                                   size_t aRangeStart, size_t aRangeEnd);

  // Assume that this is guaranteed that this is held by the caller when
  // this is used.  (Note that we cannot use AutoRestore for mCalledByJS
  // due to a bit field.)
  class MOZ_RAII AutoCalledByJSRestore final {
   private:
    nsRange& mRange;
    bool mOldValue;
    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER

   public:
    explicit AutoCalledByJSRestore(
        nsRange& aRange MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
        : mRange(aRange), mOldValue(aRange.mCalledByJS) {
      MOZ_GUARD_OBJECT_NOTIFIER_INIT;
    }
    ~AutoCalledByJSRestore() { mRange.mCalledByJS = mOldValue; }
    bool SavedValue() const { return mOldValue; }
  };

  struct MOZ_STACK_CLASS AutoInvalidateSelection {
    explicit AutoInvalidateSelection(nsRange* aRange) : mRange(aRange) {
      if (!mRange->IsInSelection() || sIsNested) {
        return;
      }
      sIsNested = true;
      mCommonAncestor = mRange->GetRegisteredCommonAncestor();
    }
    ~AutoInvalidateSelection();
    nsRange* mRange;
    RefPtr<nsINode> mCommonAncestor;
    static bool sIsNested;
  };

  nsCOMPtr<nsINode> mRoot;
  // mRegisteredCommonAncestor is only non-null when the range
  // IsInSelection().  It's kept alive via mStartContainer/mEndContainer,
  // because we update it any time those could become disconnected from it.
  nsINode* MOZ_NON_OWNING_REF mRegisteredCommonAncestor;
  mozilla::WeakPtr<mozilla::dom::Selection> mSelection;

  // These raw pointers are used to remember a child that is about
  // to be inserted between a CharacterData call and a subsequent
  // ContentInserted or ContentAppended call. It is safe to store
  // these refs because the caller is guaranteed to trigger both
  // notifications while holding a strong reference to the new child.
  nsIContent* MOZ_NON_OWNING_REF mNextStartRef;
  nsIContent* MOZ_NON_OWNING_REF mNextEndRef;

  friend class mozilla::dom::AbstractRange;
};

#endif /* nsRange_h___ */