File: compare_positions.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (466 lines) | stat: -rw-r--r-- 17,231 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/core/editing/editing_utilities.h"

#include "third_party/blink/renderer/core/editing/editing_strategy.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"

namespace blink {

namespace {

constexpr int kInvalidOffset = -1;

// The `Comparator` class implements `ComparePositions()` logic.
template <typename Traversal>
class Comparator {
  STATIC_ONLY(Comparator);

 public:
  // Integer offset version of `ComparePositions()`.
  //
  // Returns
  //  -1 if `node_a` is before `node_b`
  //   0 if `node_a == node_b`
  //   1 if `node_a` is after `node_b`
  //    where
  //      * `node_a == Traversal::ChildAt(*container_a, offset_a)`
  //      * `node_b == Traversal::ChildAt(*container_a, offset_b)`
  // and set `disconnected` to true if `node_a` and `node_b` are in different
  // tree scopes.
  static int16_t ComparePositions(const Node* container_a,
                                  int offset_a,
                                  const Node* container_b,
                                  int offset_b,
                                  bool* disconnected) {
    return ComparePositionsInternal(container_a, IntAsOffset(offset_a),
                                    container_b, IntAsOffset(offset_b),
                                    disconnected);
  }

  // Integer/Node offset version of `ComparePositions()`.
  //
  // Returns
  //  -1 if `node_a` is before `node_b`
  //   0 if `node_a == node_b`
  //   1 if `node_a` is after `node_b`
  //    where
  //      * `node_a == Traversal::ChildAt(*container_a, offset_a)`
  //      * `node_b == Traversal::ChildAt(*container_a, offset_b)`
  // and set `disconnected` to true if `node_a` and `node_b` are in different
  // tree scopes.
  static int16_t ComparePositions(const Node* container_a,
                                  int offset_a,
                                  const Node* child_a,
                                  const Node* container_b,
                                  int offset_b,
                                  const Node* child_b,
                                  bool* disconnected = nullptr) {
    if (offset_a == kInvalidOffset && offset_b == kInvalidOffset) {
      return ComparePositionsInternal(container_a, NodeAsOffset(child_a),
                                      container_b, NodeAsOffset(child_b),
                                      disconnected);
    }

    if (offset_a == kInvalidOffset) {
      return ComparePositionsInternal(container_a, NodeAsOffset(child_a),
                                      container_b, IntAsOffset(offset_b),
                                      disconnected);
    }

    if (offset_b == kInvalidOffset) {
      return ComparePositionsInternal(container_a, IntAsOffset(offset_a),
                                      container_b, NodeAsOffset(child_b),
                                      disconnected);
    }

    return ComparePositionsInternal(container_a, IntAsOffset(offset_a),
                                    container_b, IntAsOffset(offset_b),
                                    disconnected);
  }

 private:
  enum Result : int16_t {
    kAIsBeforeB = -1,
    kAIsEqualToB = 0,
    kAIsAfterB = 1,
  };

  // The wrapper class of `int` offset.
  class IntAsOffset {
    STACK_ALLOCATED();

   public:
    explicit IntAsOffset(int value) : value_(value) {}
    int Get() const { return value_; }

   private:
    int value_;
  };

  // The wrapper class of offset in `Node*` before position.
  class NodeAsOffset {
    STACK_ALLOCATED();

   public:
    explicit NodeAsOffset(const Node* value) : value_(value) {}
    const Node* Get() const { return value_; }

   private:
    const Node* value_;
  };

  // Returns
  //  -1 if `child_a` is before `child_b`
  //   0 if `child_a == child_b`
  //   1 if `child_a` is after `child_b`
  //    where
  //      * `child_a == Traversal::ChildAt(*container_a, offset_a)`
  //      * `child_b == Traversal::ChildAt(*container_a, offset_b)`
  // and set `disconnected` to true if `child_a` and `child_b` are in different
  // tree scopes.
  template <typename OffsetA, typename OffsetB>
  static int16_t ComparePositionsInternal(const Node* container_a,
                                          OffsetA offset_a,
                                          const Node* container_b,
                                          OffsetB offset_b,
                                          bool* disconnected) {
    DCHECK(container_a);
    DCHECK(container_b);

    if (disconnected)
      *disconnected = false;

    if (!container_a)
      return kAIsBeforeB;
    if (!container_b)
      return kAIsAfterB;

    // see DOM2 traversal & range section 2.5

    // Case 1: both points have the same container
    if (container_a == container_b)
      return CompareNodesInSameParent(offset_a.Get(), offset_b.Get());

    // Case 2: node C (container B or an ancestor) is a child node of A, e.g.
    //  * A < B
    //      `<a>...A...<c2>...<b>...B...</b>...</c2>...</a>`
    //  * A > B
    //      `<a>...<c2>...<b>...B...</b>...</c2>...A...</a>`
    //  * A == C2
    //             A
    //      `<a>...<c2>...<b>...B...</b>...</c2>...</a>`
    if (const Node* node_c2 =
            FindChildInAncestors(*container_b, *container_a)) {
      return CompareNodesInSameParent(
          offset_a.Get(), Traversal::PreviousSibling(*node_c2), kAIsBeforeB);
    }

    // Case 3: node C (container A or an ancestor) is a child node of B, e.g.
    //  * B < A
    //      `<b>...B....<c3>...<a>...A...</a>...</b>`
    //  * B > A
    //      `<b>...<c3>...<a>...A...</a>...</c3>...B...</b>`
    //  * B == C3
    //             B
    //      `<b>...<c3>...<a>...A...</a>...</b>`
    if (const Node* node_c3 =
            FindChildInAncestors(*container_a, *container_b)) {
      return -CompareNodesInSameParent(
          offset_b.Get(), Traversal::PreviousSibling(*node_c3), kAIsBeforeB);
    }

    // case 4: containers A & B are siblings, or children of siblings
    // ### we need to do a traversal here instead
    Node* const common_ancestor =
        Traversal::CommonAncestor(*container_a, *container_b);
    if (!common_ancestor) {
      if (disconnected)
        *disconnected = true;
      return kAIsEqualToB;
    }

    const Node* const child_a =
        FindChildInAncestors(*container_a, *common_ancestor);
    const Node* const adjusted_child_a =
        child_a ? child_a : Traversal::LastChild(*common_ancestor);
    const Node* const child_b =
        FindChildInAncestors(*container_b, *common_ancestor);
    const Node* const adjusted_child_b =
        child_b ? child_b : Traversal::LastChild(*common_ancestor);
    return CompareNodesInSameParent(adjusted_child_a, adjusted_child_b);
  }

  // Returns
  //  -1 if `offset_a < offset_b`
  //   0 if `offset_a == offset_b`
  //   1 if `offset_a > offset_b`
  //     where ```
  //        offset_b =  child_before_position_b
  //            ? Traversal::Index(*child_before_position_b) + 1
  //            : 0 ```
  // The number of iteration is `std::min(offset_a, offset_b)`.
  static Result CompareNodesInSameParent(
      int offset_a,
      const Node* child_before_position_b,
      Result result_of_a_is_equal_to_b = kAIsEqualToB) {
    if (!child_before_position_b)
      return !offset_a ? result_of_a_is_equal_to_b : kAIsAfterB;
    if (!offset_a)
      return kAIsBeforeB;
    // Starts from offset 1 and after `child_before_position_b`.
    const Node& child_b = *child_before_position_b;
    int offset = 1;
    for (const Node& child :
         Traversal::ChildrenOf(*Traversal::Parent(child_b))) {
      if (offset_a == offset)
        return child == child_b ? result_of_a_is_equal_to_b : kAIsBeforeB;
      if (child == child_b)
        return kAIsAfterB;
      ++offset;
    }
    NOTREACHED();
  }

  static int16_t CompareNodesInSameParent(
      int offset_a,
      int offset_b,
      Result result_of_a_is_equal_to_b = kAIsEqualToB) {
    if (offset_a == offset_b)
      return result_of_a_is_equal_to_b;
    return offset_a < offset_b ? kAIsBeforeB : kAIsAfterB;
  }

  static int16_t CompareNodesInSameParent(const Node* child_before_position_a,
                                          int offset_b) {
    return -CompareNodesInSameParent(offset_b, child_before_position_a);
  }

  // Returns
  //  -1 if `Traversal::Index(*child_a) < Traversal::Index(*child_b)`
  //   0 if `Traversal::Index(*child_a) == Traversal::Index(*child_b)`
  //   1 if `Traversal::Index(*child_a) > Traversal::Index(*child_b)`
  //  `child_a` and `child_b` should be in a same parent nod or `nullptr`.
  //
  //  When `child_a` < `child_b`. ```
  //                   child_a                           child_b
  ///   <-- backward_a --|-- forward_a --><-- backward_b --|-- forward_b -->
  //  |------------------+---------------------------------+----------------|
  //  ```
  //  When `child_a` > `child_b`. ```
  //                   child_b                           child_a
  ///   <-- backward_b --|-- forward_b --><-- backward_a --|-- forward_a -->
  //  |------------------+---------------------------------+----------------|
  //  ```
  //
  //  The number of iterations is: ```
  //    std::min(offset_a, offset_b,
  //             abs(offset_a - offset_b) / 2,
  //             number_of_children - offset_a,
  //             number_of_children - offset_b)
  //  where
  //    `offset_a` == `Traversal::Index(*child_a)`
  //    `offset_b` == `Traversal::Index(*child_b)`
  //
  //  ```
  // Note: this number can't exceed `number_of_children / 4`.
  //
  // Note: We call this function both "node before position" and "node after
  // position" cases. For "node after position" case, `child_a` and `child_b`
  // should not be `nullptr`.
  static int16_t CompareNodesInSameParent(
      const Node* child_a,
      const Node* child_b,
      Result result_of_a_is_equal_to_b = kAIsEqualToB) {
    if (child_a == child_b)
      return result_of_a_is_equal_to_b;
    if (!child_a)
      return kAIsBeforeB;
    if (!child_b)
      return kAIsAfterB;
    DCHECK_EQ(Traversal::Parent(*child_a), Traversal::Parent(*child_b));
    const Node* backward_a = child_a;
    const Node* forward_a = child_a;
    const Node* backward_b = child_b;
    const Node* forward_b = child_b;

    for (;;) {
      backward_a = Traversal::PreviousSibling(*backward_a);
      if (!backward_a)
        return kAIsBeforeB;
      if (backward_a == forward_b)
        return kAIsAfterB;

      forward_a = Traversal::NextSibling(*forward_a);
      if (!forward_a)
        return kAIsAfterB;
      if (forward_a == backward_b)
        return kAIsBeforeB;

      backward_b = Traversal::PreviousSibling(*backward_b);
      if (!backward_b)
        return kAIsAfterB;
      if (forward_a == backward_b)
        return kAIsBeforeB;

      forward_b = Traversal::NextSibling(*forward_b);
      if (!forward_b)
        return kAIsBeforeB;
      if (backward_a == forward_b)
        return kAIsAfterB;
    }

    NOTREACHED();
  }

  // Returns the child node in `parent` if `parent` is one of inclusive
  // ancestors of `node`, otherwise `nullptr`.
  // See https://dom.spec.whatwg.org/#boundary-points
  static const Node* FindChildInAncestors(const Node& node,
                                          const Node& parent) {
    DCHECK_NE(node, parent);
    const Node* candidate = &node;
    for (const Node& child : Traversal::AncestorsOf(node)) {
      if (child == parent)
        return candidate;
      candidate = &child;
    }
    return nullptr;
  }
};

}  // namespace

int16_t ComparePositionsInDOMTree(const Node* container_a,
                                  int offset_a,
                                  const Node* container_b,
                                  int offset_b,
                                  bool* disconnected) {
  return Comparator<NodeTraversal>::ComparePositions(
      container_a, offset_a, container_b, offset_b, disconnected);
}

int16_t ComparePositionsInFlatTree(const Node* container_a,
                                   int offset_a,
                                   const Node* container_b,
                                   int offset_b,
                                   bool* disconnected) {
  if (container_a->IsShadowRoot()) {
    container_a = container_a->OwnerShadowHost();
  }
  if (container_b->IsShadowRoot()) {
    container_b = container_b->OwnerShadowHost();
  }
  return Comparator<FlatTreeTraversal>::ComparePositions(
      container_a, offset_a, container_b, offset_b, disconnected);
}

int16_t ComparePositions(const Position& position_a,
                         const Position& position_b) {
  DCHECK(position_a.IsNotNull());
  DCHECK(position_b.IsNotNull());

  const TreeScope* common_scope =
      Position::CommonAncestorTreeScope(position_a, position_b);

  DCHECK(common_scope);
  if (!common_scope)
    return 0;

  Node* const container_a = position_a.ComputeContainerNode();
  Node* const node_a = common_scope->AncestorInThisScope(container_a);
  DCHECK(node_a);
  const bool has_descendant_a = node_a != container_a;

  Node* const container_b = position_b.ComputeContainerNode();
  Node* const node_b = common_scope->AncestorInThisScope(container_b);
  DCHECK(node_b);
  const bool has_descendant_b = node_b != container_b;

  const int offset_a = position_a.IsOffsetInAnchor() && !has_descendant_a
                           ? position_a.OffsetInContainerNode()
                           : kInvalidOffset;

  const int offset_b = position_b.IsOffsetInAnchor() && !has_descendant_b
                           ? position_b.OffsetInContainerNode()
                           : kInvalidOffset;

  Node* const child_a = position_a.IsOffsetInAnchor() || has_descendant_a
                            ? nullptr
                            : position_a.ComputeNodeBeforePosition();

  Node* const child_b = position_b.IsOffsetInAnchor() || has_descendant_b
                            ? nullptr
                            : position_b.ComputeNodeBeforePosition();

  const int16_t bias = node_a != node_b   ? 0
                       : has_descendant_a ? 1
                       : has_descendant_b ? -1
                                          : 0;

  const int16_t result = Comparator<NodeTraversal>::ComparePositions(
      node_a, offset_a, child_a, node_b, offset_b, child_b);
  return result ? result : bias;
}

int16_t ComparePositions(const PositionWithAffinity& a,
                         const PositionWithAffinity& b) {
  return ComparePositions(a.GetPosition(), b.GetPosition());
}

int16_t ComparePositions(const VisiblePosition& a, const VisiblePosition& b) {
  return ComparePositions(a.DeepEquivalent(), b.DeepEquivalent());
}

int16_t ComparePositions(const PositionInFlatTree& position_a,
                         const PositionInFlatTree& position_b) {
  DCHECK(position_a.IsNotNull());
  DCHECK(position_b.IsNotNull());

  Node* const container_a = position_a.ComputeContainerNode();
  Node* const container_b = position_b.ComputeContainerNode();

  const int offset_a = position_a.IsOffsetInAnchor()
                           ? position_a.OffsetInContainerNode()
                           : kInvalidOffset;

  const int offset_b = position_b.IsOffsetInAnchor()
                           ? position_b.OffsetInContainerNode()
                           : kInvalidOffset;

  Node* const child_a = position_a.IsOffsetInAnchor()
                            ? nullptr
                            : position_a.ComputeNodeBeforePosition();

  Node* const child_b = position_b.IsOffsetInAnchor()
                            ? nullptr
                            : position_b.ComputeNodeBeforePosition();

  return Comparator<FlatTreeTraversal>::ComparePositions(
      container_a, offset_a, child_a, container_b, offset_b, child_b);
}

}  // namespace blink