Range.surroundContents() should check for partially contained non-Text nodes first
[WebKit-https.git] / Source / WebCore / dom / Range.cpp
1 /*
2  * (C) 1999 Lars Knoll (knoll@kde.org)
3  * (C) 2000 Gunnstein Lye (gunnstein@netcom.no)
4  * (C) 2000 Frederik Holljen (frederik.holljen@hig.no)
5  * (C) 2001 Peter Kelly (pmk@post.com)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
7  * Copyright (C) 2011 Motorola Mobility. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "Range.h"
27
28 #include "ClientRect.h"
29 #include "ClientRectList.h"
30 #include "DocumentFragment.h"
31 #include "Event.h"
32 #include "Frame.h"
33 #include "FrameView.h"
34 #include "HTMLElement.h"
35 #include "HTMLNames.h"
36 #include "NodeTraversal.h"
37 #include "NodeWithIndex.h"
38 #include "Page.h"
39 #include "ProcessingInstruction.h"
40 #include "RenderBoxModelObject.h"
41 #include "RenderText.h"
42 #include "ScopedEventQueue.h"
43 #include "TextIterator.h"
44 #include "VisiblePosition.h"
45 #include "VisibleUnits.h"
46 #include "htmlediting.h"
47 #include "markup.h"
48 #include <stdio.h>
49 #include <wtf/RefCountedLeakCounter.h>
50 #include <wtf/text/CString.h>
51 #include <wtf/text/StringBuilder.h>
52
53 #if PLATFORM(IOS)
54 #include "SelectionRect.h"
55 #endif
56
57 namespace WebCore {
58
59 using namespace HTMLNames;
60
61 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, rangeCounter, ("Range"));
62
63 inline Range::Range(Document& ownerDocument)
64     : m_ownerDocument(ownerDocument)
65     , m_start(&ownerDocument)
66     , m_end(&ownerDocument)
67 {
68 #ifndef NDEBUG
69     rangeCounter.increment();
70 #endif
71
72     m_ownerDocument->attachRange(this);
73 }
74
75 Ref<Range> Range::create(Document& ownerDocument)
76 {
77     return adoptRef(*new Range(ownerDocument));
78 }
79
80 inline Range::Range(Document& ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
81     : m_ownerDocument(ownerDocument)
82     , m_start(&ownerDocument)
83     , m_end(&ownerDocument)
84 {
85 #ifndef NDEBUG
86     rangeCounter.increment();
87 #endif
88
89     m_ownerDocument->attachRange(this);
90
91     // Simply setting the containers and offsets directly would not do any of the checking
92     // that setStart and setEnd do, so we call those functions.
93     setStart(startContainer, startOffset);
94     setEnd(endContainer, endOffset);
95 }
96
97 Ref<Range> Range::create(Document& ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
98 {
99     return adoptRef(*new Range(ownerDocument, startContainer, startOffset, endContainer, endOffset));
100 }
101
102 Ref<Range> Range::create(Document& ownerDocument, const Position& start, const Position& end)
103 {
104     return adoptRef(*new Range(ownerDocument, start.containerNode(), start.computeOffsetInContainerNode(), end.containerNode(), end.computeOffsetInContainerNode()));
105 }
106
107 Ref<Range> Range::create(Document& ownerDocument, const VisiblePosition& visibleStart, const VisiblePosition& visibleEnd)
108 {
109     Position start = visibleStart.deepEquivalent().parentAnchoredEquivalent();
110     Position end = visibleEnd.deepEquivalent().parentAnchoredEquivalent();
111     return adoptRef(*new Range(ownerDocument, start.anchorNode(), start.deprecatedEditingOffset(), end.anchorNode(), end.deprecatedEditingOffset()));
112 }
113
114 Range::~Range()
115 {
116     // Always detach (even if we've already detached) to fix https://bugs.webkit.org/show_bug.cgi?id=26044
117     m_ownerDocument->detachRange(this);
118
119 #ifndef NDEBUG
120     rangeCounter.decrement();
121 #endif
122 }
123
124 void Range::setDocument(Document& document)
125 {
126     ASSERT(m_ownerDocument.ptr() != &document);
127     m_ownerDocument->detachRange(this);
128     m_ownerDocument = document;
129     m_start.setToStartOfNode(&document);
130     m_end.setToStartOfNode(&document);
131     m_ownerDocument->attachRange(this);
132 }
133
134 Node* Range::commonAncestorContainer(Node* containerA, Node* containerB)
135 {
136     for (Node* parentA = containerA; parentA; parentA = parentA->parentNode()) {
137         for (Node* parentB = containerB; parentB; parentB = parentB->parentNode()) {
138             if (parentA == parentB)
139                 return parentA;
140         }
141     }
142     return nullptr;
143 }
144
145 static inline bool checkForDifferentRootContainer(const RangeBoundaryPoint& start, const RangeBoundaryPoint& end)
146 {
147     Node* endRootContainer = end.container();
148     while (endRootContainer->parentNode())
149         endRootContainer = endRootContainer->parentNode();
150     Node* startRootContainer = start.container();
151     while (startRootContainer->parentNode())
152         startRootContainer = startRootContainer->parentNode();
153
154     return startRootContainer != endRootContainer || (Range::compareBoundaryPoints(start, end, ASSERT_NO_EXCEPTION) > 0);
155 }
156
157 void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionCode& ec)
158 {
159     if (!refNode) {
160         ec = TypeError;
161         return;
162     }
163
164     bool didMoveDocument = false;
165     if (&refNode->document() != &ownerDocument()) {
166         setDocument(refNode->document());
167         didMoveDocument = true;
168     }
169
170     ec = 0;
171     Node* childNode = checkNodeWOffset(refNode.get(), offset, ec);
172     if (ec)
173         return;
174
175     m_start.set(refNode, offset, childNode);
176
177     if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
178         collapse(true);
179 }
180
181 void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionCode& ec)
182 {
183     if (!refNode) {
184         ec = TypeError;
185         return;
186     }
187
188     bool didMoveDocument = false;
189     if (&refNode->document() != &ownerDocument()) {
190         setDocument(refNode->document());
191         didMoveDocument = true;
192     }
193
194     ec = 0;
195     Node* childNode = checkNodeWOffset(refNode.get(), offset, ec);
196     if (ec)
197         return;
198
199     m_end.set(refNode, offset, childNode);
200
201     if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
202         collapse(false);
203 }
204
205 void Range::setStart(const Position& start, ExceptionCode& ec)
206 {
207     Position parentAnchored = start.parentAnchoredEquivalent();
208     setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), ec);
209 }
210
211 void Range::setEnd(const Position& end, ExceptionCode& ec)
212 {
213     Position parentAnchored = end.parentAnchoredEquivalent();
214     setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), ec);
215 }
216
217 void Range::collapse(bool toStart)
218 {
219     if (toStart)
220         m_end = m_start;
221     else
222         m_start = m_end;
223 }
224
225 bool Range::isPointInRange(Node* refNode, int offset, ExceptionCode& ec)
226 {
227     if (!refNode) {
228         ec = TypeError;
229         return false;
230     }
231
232     if (&refNode->document() != &ownerDocument()) {
233         return false;
234     }
235
236     ec = 0;
237     checkNodeWOffset(refNode, offset, ec);
238     if (ec) {
239         // DOM4 spec requires us to check whether refNode and start container have the same root first
240         // but we do it in the reverse order to avoid O(n) operation here in common case.
241         if (!commonAncestorContainer(refNode, &startContainer()))
242             ec = 0;
243         return false;
244     }
245
246     bool result = compareBoundaryPoints(refNode, offset, &startContainer(), m_start.offset(), ec) >= 0 && !ec
247         && compareBoundaryPoints(refNode, offset, &endContainer(), m_end.offset(), ec) <= 0 && !ec;
248     ASSERT(!ec || ec == WRONG_DOCUMENT_ERR);
249     ec = 0;
250     return result;
251 }
252
253 short Range::comparePoint(Node* refNode, int offset, ExceptionCode& ec) const
254 {
255     // http://developer.mozilla.org/en/docs/DOM:range.comparePoint
256     // This method returns -1, 0 or 1 depending on if the point described by the 
257     // refNode node and an offset within the node is before, same as, or after the range respectively.
258
259     if (!refNode) {
260         ec = TypeError;
261         return 0;
262     }
263
264     if (&refNode->document() != &ownerDocument()) {
265         ec = WRONG_DOCUMENT_ERR;
266         return 0;
267     }
268
269     ec = 0;
270     checkNodeWOffset(refNode, offset, ec);
271     if (ec) {
272         // DOM4 spec requires us to check whether refNode and start container have the same root first
273         // but we do it in the reverse order to avoid O(n) operation here in common case.
274         if (!refNode->inDocument() && !commonAncestorContainer(refNode, &startContainer()))
275             ec = WRONG_DOCUMENT_ERR;
276         return 0;
277     }
278
279     // compare to start, and point comes before
280     if (compareBoundaryPoints(refNode, offset, &startContainer(), m_start.offset(), ec) < 0)
281         return -1;
282
283     if (ec)
284         return 0;
285
286     // compare to end, and point comes after
287     if (compareBoundaryPoints(refNode, offset, &endContainer(), m_end.offset(), ec) > 0 && !ec)
288         return 1;
289
290     // point is in the middle of this range, or on the boundary points
291     return 0;
292 }
293
294 Range::CompareResults Range::compareNode(Node* refNode, ExceptionCode& ec) const
295 {
296     // http://developer.mozilla.org/en/docs/DOM:range.compareNode
297     // This method returns 0, 1, 2, or 3 based on if the node is before, after,
298     // before and after(surrounds), or inside the range, respectively
299
300     if (!refNode) {
301         ec = TypeError;
302         return NODE_BEFORE;
303     }
304
305     if (!refNode->inDocument()) {
306         // Firefox doesn't throw an exception for this case; it returns 0.
307         return NODE_BEFORE;
308     }
309
310     if (&refNode->document() != &ownerDocument()) {
311         // Firefox doesn't throw an exception for this case; it returns 0.
312         return NODE_BEFORE;
313     }
314
315     ContainerNode* parentNode = refNode->parentNode();
316     unsigned nodeIndex = refNode->computeNodeIndex();
317     
318     if (!parentNode) {
319         // if the node is the top document we should return NODE_BEFORE_AND_AFTER
320         // but we throw to match firefox behavior
321         ec = NOT_FOUND_ERR;
322         return NODE_BEFORE;
323     }
324
325     if (comparePoint(parentNode, nodeIndex, ec) < 0) { // starts before
326         if (comparePoint(parentNode, nodeIndex + 1, ec) > 0) // ends after the range
327             return NODE_BEFORE_AND_AFTER;
328         return NODE_BEFORE; // ends before or in the range
329     } else { // starts at or after the range start
330         if (comparePoint(parentNode, nodeIndex + 1, ec) > 0) // ends after the range
331             return NODE_AFTER;
332         return NODE_INSIDE; // ends inside the range
333     }
334 }
335
336 short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionCode& ec) const
337 {
338     if (!sourceRange) {
339         ec = TypeError;
340         return 0;
341     }
342
343     Node* thisCont = commonAncestorContainer();
344     Node* sourceCont = sourceRange->commonAncestorContainer();
345
346     if (&thisCont->document() != &sourceCont->document()) {
347         ec = WRONG_DOCUMENT_ERR;
348         return 0;
349     }
350
351     Node* thisTop = thisCont;
352     Node* sourceTop = sourceCont;
353     while (thisTop->parentNode())
354         thisTop = thisTop->parentNode();
355     while (sourceTop->parentNode())
356         sourceTop = sourceTop->parentNode();
357     if (thisTop != sourceTop) { // in different DocumentFragments
358         ec = WRONG_DOCUMENT_ERR;
359         return 0;
360     }
361
362     switch (how) {
363         case START_TO_START:
364             return compareBoundaryPoints(m_start, sourceRange->m_start, ec);
365         case START_TO_END:
366             return compareBoundaryPoints(m_end, sourceRange->m_start, ec);
367         case END_TO_END:
368             return compareBoundaryPoints(m_end, sourceRange->m_end, ec);
369         case END_TO_START:
370             return compareBoundaryPoints(m_start, sourceRange->m_end, ec);
371     }
372
373     ec = SYNTAX_ERR;
374     return 0;
375 }
376
377 short Range::compareBoundaryPointsForBindings(unsigned short compareHow, const Range* sourceRange, ExceptionCode& ec) const
378 {
379     if (compareHow > END_TO_START) {
380         ec = NOT_SUPPORTED_ERR;
381         return 0;
382     }
383     return compareBoundaryPoints(static_cast<CompareHow>(compareHow), sourceRange, ec);
384 }
385
386 short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionCode& ec)
387 {
388     ASSERT(containerA);
389     ASSERT(containerB);
390
391     if (!containerA)
392         return -1;
393     if (!containerB)
394         return 1;
395
396     // see DOM2 traversal & range section 2.5
397
398     // case 1: both points have the same container
399     if (containerA == containerB) {
400         if (offsetA == offsetB)
401             return 0;           // A is equal to B
402         if (offsetA < offsetB)
403             return -1;          // A is before B
404         else
405             return 1;           // A is after B
406     }
407
408     // case 2: node C (container B or an ancestor) is a child node of A
409     Node* c = containerB;
410     while (c && c->parentNode() != containerA)
411         c = c->parentNode();
412     if (c) {
413         int offsetC = 0;
414         Node* n = containerA->firstChild();
415         while (n != c && offsetC < offsetA) {
416             offsetC++;
417             n = n->nextSibling();
418         }
419
420         if (offsetA <= offsetC)
421             return -1;              // A is before B
422         else
423             return 1;               // A is after B
424     }
425
426     // case 3: node C (container A or an ancestor) is a child node of B
427     c = containerA;
428     while (c && c->parentNode() != containerB)
429         c = c->parentNode();
430     if (c) {
431         int offsetC = 0;
432         Node* n = containerB->firstChild();
433         while (n != c && offsetC < offsetB) {
434             offsetC++;
435             n = n->nextSibling();
436         }
437
438         if (offsetC < offsetB)
439             return -1;              // A is before B
440         else
441             return 1;               // A is after B
442     }
443
444     // case 4: containers A & B are siblings, or children of siblings
445     // ### we need to do a traversal here instead
446     Node* commonAncestor = commonAncestorContainer(containerA, containerB);
447     if (!commonAncestor) {
448         ec = WRONG_DOCUMENT_ERR;
449         return 0;
450     }
451     Node* childA = containerA;
452     while (childA && childA->parentNode() != commonAncestor)
453         childA = childA->parentNode();
454     if (!childA)
455         childA = commonAncestor;
456     Node* childB = containerB;
457     while (childB && childB->parentNode() != commonAncestor)
458         childB = childB->parentNode();
459     if (!childB)
460         childB = commonAncestor;
461
462     if (childA == childB)
463         return 0; // A is equal to B
464
465     Node* n = commonAncestor->firstChild();
466     while (n) {
467         if (n == childA)
468             return -1; // A is before B
469         if (n == childB)
470             return 1; // A is after B
471         n = n->nextSibling();
472     }
473
474     // Should never reach this point.
475     ASSERT_NOT_REACHED();
476     return 0;
477 }
478
479 short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionCode& ec)
480 {
481     return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), ec);
482 }
483
484 bool Range::boundaryPointsValid() const
485 {
486     ExceptionCode ec = 0;
487     return compareBoundaryPoints(m_start, m_end, ec) <= 0 && !ec;
488 }
489
490 void Range::deleteContents(ExceptionCode& ec)
491 {
492     processContents(Delete, ec);
493 }
494
495 bool Range::intersectsNode(Node* refNode, ExceptionCode& ec) const
496 {
497     if (!refNode) {
498         ec = TypeError;
499         return false;
500     }
501
502     if (!refNode->inDocument() || &refNode->document() != &ownerDocument())
503         return false;
504
505     ContainerNode* parentNode = refNode->parentNode();
506     if (!parentNode)
507         return true;
508
509     unsigned nodeIndex = refNode->computeNodeIndex();
510
511     // If (parent, offset) is before end and (parent, offset + 1) is after start, return true.
512     // Otherwise, return false.
513     short compareFirst = comparePoint(parentNode, nodeIndex, ec);
514     short compareSecond = comparePoint(parentNode, nodeIndex + 1, ec);
515
516     bool isFirstBeforeEnd = m_start == m_end ? compareFirst < 0 : compareFirst <= 0;
517     bool isSecondAfterStart = m_start == m_end ? compareSecond > 0 : compareSecond >= 0;
518
519     return isFirstBeforeEnd && isSecondAfterStart;
520 }
521
522 static inline Node* highestAncestorUnderCommonRoot(Node* node, Node* commonRoot)
523 {
524     if (node == commonRoot)
525         return 0;
526
527     ASSERT(commonRoot->contains(node));
528
529     while (node->parentNode() != commonRoot)
530         node = node->parentNode();
531
532     return node;
533 }
534
535 static inline Node* childOfCommonRootBeforeOffset(Node* container, unsigned offset, Node* commonRoot)
536 {
537     ASSERT(container);
538     ASSERT(commonRoot);
539     
540     if (!commonRoot->contains(container))
541         return 0;
542
543     if (container == commonRoot) {
544         container = container->firstChild();
545         for (unsigned i = 0; container && i < offset; i++)
546             container = container->nextSibling();
547     } else {
548         while (container->parentNode() != commonRoot)
549             container = container->parentNode();
550     }
551
552     return container;
553 }
554
555 static inline unsigned lengthOfContentsInNode(Node* node)
556 {
557     // This switch statement must be consistent with that of Range::processContentsBetweenOffsets.
558     switch (node->nodeType()) {
559     case Node::TEXT_NODE:
560     case Node::CDATA_SECTION_NODE:
561     case Node::COMMENT_NODE:
562     case Node::PROCESSING_INSTRUCTION_NODE:
563         return downcast<CharacterData>(*node).length();
564     case Node::ELEMENT_NODE:
565     case Node::ATTRIBUTE_NODE:
566     case Node::DOCUMENT_NODE:
567     case Node::DOCUMENT_TYPE_NODE:
568     case Node::DOCUMENT_FRAGMENT_NODE:
569     case Node::XPATH_NAMESPACE_NODE:
570         return node->countChildNodes();
571     }
572     ASSERT_NOT_REACHED();
573     return 0;
574 }
575
576 RefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionCode& ec)
577 {
578     typedef Vector<RefPtr<Node>> NodeVector;
579
580     RefPtr<DocumentFragment> fragment;
581     if (action == Extract || action == Clone)
582         fragment = DocumentFragment::create(ownerDocument());
583
584     if (collapsed())
585         return fragment;
586
587     RefPtr<Node> commonRoot = commonAncestorContainer();
588     ASSERT(commonRoot);
589
590     if (&startContainer() == &endContainer()) {
591         processContentsBetweenOffsets(action, fragment, &startContainer(), m_start.offset(), m_end.offset(), ec);
592         return fragment;
593     }
594
595     // Since mutation events can modify the range during the process, the boundary points need to be saved.
596     RangeBoundaryPoint originalStart(m_start);
597     RangeBoundaryPoint originalEnd(m_end);
598
599     // what is the highest node that partially selects the start / end of the range?
600     RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(originalStart.container(), commonRoot.get());
601     RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(originalEnd.container(), commonRoot.get());
602
603     // Start and end containers are different.
604     // There are three possibilities here:
605     // 1. Start container == commonRoot (End container must be a descendant)
606     // 2. End container == commonRoot (Start container must be a descendant)
607     // 3. Neither is commonRoot, they are both descendants
608     //
609     // In case 3, we grab everything after the start (up until a direct child
610     // of commonRoot) into leftContents, and everything before the end (up until
611     // a direct child of commonRoot) into rightContents. Then we process all
612     // commonRoot children between leftContents and rightContents
613     //
614     // In case 1 or 2, we skip either processing of leftContents or rightContents,
615     // in which case the last lot of nodes either goes from the first or last
616     // child of commonRoot.
617     //
618     // These are deleted, cloned, or extracted (i.e. both) depending on action.
619
620     // Note that we are verifying that our common root hierarchy is still intact
621     // after any DOM mutation event, at various stages below. See webkit bug 60350.
622
623     RefPtr<Node> leftContents;
624     if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) {
625         leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), ec);
626         leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
627     }
628
629     RefPtr<Node> rightContents;
630     if (&endContainer() != commonRoot && commonRoot->contains(originalEnd.container())) {
631         rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), ec);
632         rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
633     }
634
635     // delete all children of commonRoot between the start and end container
636     RefPtr<Node> processStart = childOfCommonRootBeforeOffset(originalStart.container(), originalStart.offset(), commonRoot.get());
637     if (processStart && originalStart.container() != commonRoot) // processStart contains nodes before m_start.
638         processStart = processStart->nextSibling();
639     RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(originalEnd.container(), originalEnd.offset(), commonRoot.get());
640
641     // Collapse the range, making sure that the result is not within a node that was partially selected.
642     ec = 0;
643     if (action == Extract || action == Delete) {
644         if (partialStart && commonRoot->contains(partialStart.get()))
645             setStart(partialStart->parentNode(), partialStart->computeNodeIndex() + 1, ec);
646         else if (partialEnd && commonRoot->contains(partialEnd.get()))
647             setStart(partialEnd->parentNode(), partialEnd->computeNodeIndex(), ec);
648         if (ec)
649             return nullptr;
650         m_end = m_start;
651     }
652
653     // Now add leftContents, stuff in between, and rightContents to the fragment
654     // (or just delete the stuff in between)
655
656     if ((action == Extract || action == Clone) && leftContents)
657         fragment->appendChild(*leftContents, ec);
658
659     if (processStart) {
660         NodeVector nodes;
661         for (Node* n = processStart.get(); n && n != processEnd; n = n->nextSibling())
662             nodes.append(n);
663         processNodes(action, nodes, commonRoot, fragment, ec);
664     }
665
666     if ((action == Extract || action == Clone) && rightContents)
667         fragment->appendChild(*rightContents, ec);
668
669     return fragment;
670 }
671
672 static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionCode& ec)
673 {
674     if (data->length() - endOffset)
675         data->deleteData(endOffset, data->length() - endOffset, ec);
676     if (startOffset)
677         data->deleteData(0, startOffset, ec);
678 }
679
680 RefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRefPtr<DocumentFragment> fragment, Node* container, unsigned startOffset, unsigned endOffset, ExceptionCode& ec)
681 {
682     ASSERT(container);
683     ASSERT(startOffset <= endOffset);
684
685     // This switch statement must be consistent with that of lengthOfContentsInNode.
686     RefPtr<Node> result;
687     switch (container->nodeType()) {
688     case Node::TEXT_NODE:
689     case Node::CDATA_SECTION_NODE:
690     case Node::COMMENT_NODE:
691         endOffset = std::min(endOffset, static_cast<CharacterData*>(container)->length());
692         startOffset = std::min(startOffset, endOffset);
693         if (action == Extract || action == Clone) {
694             RefPtr<CharacterData> c = static_cast<CharacterData*>(container->cloneNode(true).ptr());
695             deleteCharacterData(c, startOffset, endOffset, ec);
696             if (fragment) {
697                 result = fragment;
698                 result->appendChild(c.release(), ec);
699             } else
700                 result = c.release();
701         }
702         if (action == Extract || action == Delete)
703             downcast<CharacterData>(*container).deleteData(startOffset, endOffset - startOffset, ec);
704         break;
705     case Node::PROCESSING_INSTRUCTION_NODE:
706         endOffset = std::min(endOffset, static_cast<ProcessingInstruction*>(container)->data().length());
707         startOffset = std::min(startOffset, endOffset);
708         if (action == Extract || action == Clone) {
709             RefPtr<ProcessingInstruction> c = static_cast<ProcessingInstruction*>(container->cloneNode(true).ptr());
710             c->setData(c->data().substring(startOffset, endOffset - startOffset), ec);
711             if (fragment) {
712                 result = fragment;
713                 result->appendChild(c.release(), ec);
714             } else
715                 result = c.release();
716         }
717         if (action == Extract || action == Delete) {
718             ProcessingInstruction& pi = downcast<ProcessingInstruction>(*container);
719             String data(pi.data());
720             data.remove(startOffset, endOffset - startOffset);
721             pi.setData(data, ec);
722         }
723         break;
724     case Node::ELEMENT_NODE:
725     case Node::ATTRIBUTE_NODE:
726     case Node::DOCUMENT_NODE:
727     case Node::DOCUMENT_TYPE_NODE:
728     case Node::DOCUMENT_FRAGMENT_NODE:
729     case Node::XPATH_NAMESPACE_NODE:
730         // FIXME: Should we assert that some nodes never appear here?
731         if (action == Extract || action == Clone) {
732             if (fragment)
733                 result = fragment;
734             else
735                 result = container->cloneNode(false);
736         }
737
738         Node* n = container->firstChild();
739         Vector<RefPtr<Node>> nodes;
740         for (unsigned i = startOffset; n && i; i--)
741             n = n->nextSibling();
742         for (unsigned i = startOffset; n && i < endOffset; i++, n = n->nextSibling()) {
743             if (action != Delete && n->isDocumentTypeNode()) {
744                 ec = HIERARCHY_REQUEST_ERR;
745                 return nullptr;
746             }
747             nodes.append(n);
748         }
749
750         processNodes(action, nodes, container, result, ec);
751         break;
752     }
753
754     return result;
755 }
756
757 void Range::processNodes(ActionType action, Vector<RefPtr<Node>>& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionCode& ec)
758 {
759     for (unsigned i = 0; i < nodes.size(); i++) {
760         switch (action) {
761         case Delete:
762             oldContainer->removeChild(nodes[i].get(), ec);
763             break;
764         case Extract:
765             newContainer->appendChild(nodes[i].release(), ec); // will remove n from its parent
766             break;
767         case Clone:
768             newContainer->appendChild(nodes[i]->cloneNode(true), ec);
769             break;
770         }
771     }
772 }
773
774 RefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionCode& ec)
775 {
776     typedef Vector<RefPtr<Node>> NodeVector;
777
778     RefPtr<Node> clonedContainer = passedClonedContainer;
779     Vector<RefPtr<Node>> ancestors;
780     for (ContainerNode* n = container->parentNode(); n && n != commonRoot; n = n->parentNode())
781         ancestors.append(n);
782
783     RefPtr<Node> firstChildInAncestorToProcess = direction == ProcessContentsForward ? container->nextSibling() : container->previousSibling();
784     for (Vector<RefPtr<Node>>::const_iterator it = ancestors.begin(); it != ancestors.end(); ++it) {
785         RefPtr<Node> ancestor = *it;
786         if (action == Extract || action == Clone) {
787             if (RefPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { // Might have been removed already during mutation event.
788                 clonedAncestor->appendChild(clonedContainer, ec);
789                 clonedContainer = clonedAncestor;
790             }
791         }
792
793         // Copy siblings of an ancestor of start/end containers
794         // FIXME: This assertion may fail if DOM is modified during mutation event
795         // FIXME: Share code with Range::processNodes
796         ASSERT(!firstChildInAncestorToProcess || firstChildInAncestorToProcess->parentNode() == ancestor);
797         
798         NodeVector nodes;
799         for (Node* child = firstChildInAncestorToProcess.get(); child;
800             child = (direction == ProcessContentsForward) ? child->nextSibling() : child->previousSibling())
801             nodes.append(child);
802
803         for (NodeVector::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
804             Node* child = it->get();
805             switch (action) {
806             case Delete:
807                 ancestor->removeChild(child, ec);
808                 break;
809             case Extract: // will remove child from ancestor
810                 if (direction == ProcessContentsForward)
811                     clonedContainer->appendChild(child, ec);
812                 else
813                     clonedContainer->insertBefore(child, clonedContainer->firstChild(), ec);
814                 break;
815             case Clone:
816                 if (direction == ProcessContentsForward)
817                     clonedContainer->appendChild(child->cloneNode(true), ec);
818                 else
819                     clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), ec);
820                 break;
821             }
822         }
823         firstChildInAncestorToProcess = direction == ProcessContentsForward ? ancestor->nextSibling() : ancestor->previousSibling();
824     }
825
826     return clonedContainer;
827 }
828
829 RefPtr<DocumentFragment> Range::extractContents(ExceptionCode& ec)
830 {
831     return processContents(Extract, ec);
832 }
833
834 RefPtr<DocumentFragment> Range::cloneContents(ExceptionCode& ec)
835 {
836     return processContents(Clone, ec);
837 }
838
839 void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionCode& ec)
840 {
841     RefPtr<Node> newNode = prpNewNode;
842
843     ec = 0;
844     if (!newNode) {
845         ec = TypeError;
846         return;
847     }
848
849     // HIERARCHY_REQUEST_ERR: Raised if the container of the start of the Range is of a type that
850     // does not allow children of the type of newNode or if newNode is an ancestor of the container.
851
852     // an extra one here - if a text node is going to split, it must have a parent to insert into
853     bool startIsText = is<Text>(startContainer());
854     if (startIsText && !startContainer().parentNode()) {
855         ec = HIERARCHY_REQUEST_ERR;
856         return;
857     }
858
859     // In the case where the container is a text node, we check against the container's parent, because
860     // text nodes get split up upon insertion.
861     Node* checkAgainst;
862     if (startIsText)
863         checkAgainst = startContainer().parentNode();
864     else
865         checkAgainst = &startContainer();
866
867     Node::NodeType newNodeType = newNode->nodeType();
868     int numNewChildren;
869     if (newNodeType == Node::DOCUMENT_FRAGMENT_NODE && !newNode->isShadowRoot()) {
870         // check each child node, not the DocumentFragment itself
871         numNewChildren = 0;
872         for (Node* c = newNode->firstChild(); c; c = c->nextSibling()) {
873             if (!checkAgainst->childTypeAllowed(c->nodeType())) {
874                 ec = HIERARCHY_REQUEST_ERR;
875                 return;
876             }
877             ++numNewChildren;
878         }
879     } else {
880         numNewChildren = 1;
881         if (!checkAgainst->childTypeAllowed(newNodeType)) {
882             ec = HIERARCHY_REQUEST_ERR;
883             return;
884         }
885     }
886
887     for (Node* n = &startContainer(); n; n = n->parentNode()) {
888         if (n == newNode) {
889             ec = HIERARCHY_REQUEST_ERR;
890             return;
891         }
892     }
893
894     // INVALID_NODE_TYPE_ERR: Raised if newNode is an Attr, Entity, ShadowRoot or Document node.
895     switch (newNodeType) {
896     case Node::ATTRIBUTE_NODE:
897     case Node::DOCUMENT_NODE:
898         ec = INVALID_NODE_TYPE_ERR;
899         return;
900     default:
901         if (newNode->isShadowRoot()) {
902             ec = INVALID_NODE_TYPE_ERR;
903             return;
904         }
905         break;
906     }
907
908     EventQueueScope scope;
909     bool collapsed = m_start == m_end;
910     RefPtr<Node> container;
911     if (startIsText) {
912         container = &startContainer();
913         RefPtr<Text> newText = downcast<Text>(*container).splitText(m_start.offset(), ec);
914         if (ec)
915             return;
916         
917         container = &startContainer();
918         container->parentNode()->insertBefore(newNode.releaseNonNull(), newText.get(), ec);
919         if (ec)
920             return;
921
922         if (collapsed && newText->parentNode() == container && &container->document() == &ownerDocument())
923             m_end.setToBeforeChild(*newText);
924     } else {
925         container = &startContainer();
926         RefPtr<Node> firstInsertedChild = newNodeType == Node::DOCUMENT_FRAGMENT_NODE ? newNode->firstChild() : newNode;
927         RefPtr<Node> lastInsertedChild = newNodeType == Node::DOCUMENT_FRAGMENT_NODE ? newNode->lastChild() : newNode;
928         RefPtr<Node> childAfterInsertedContent = container->traverseToChildAt(m_start.offset());
929         container->insertBefore(newNode.release(), childAfterInsertedContent.get(), ec);
930         if (ec)
931             return;
932
933         if (collapsed && numNewChildren && &container->document() == &ownerDocument()) {
934             if (firstInsertedChild->parentNode() == container)
935                 m_start.setToBeforeChild(*firstInsertedChild);
936             if (lastInsertedChild->parentNode() == container)
937                 m_end.set(container, lastInsertedChild->computeNodeIndex() + 1, lastInsertedChild.get());
938         }
939     }
940 }
941
942 String Range::toString() const
943 {
944     StringBuilder builder;
945
946     Node* pastLast = pastLastNode();
947     for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
948         if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
949             const String& data = static_cast<CharacterData*>(n)->data();
950             int length = data.length();
951             int start = n == &startContainer() ? std::min(std::max(0, m_start.offset()), length) : 0;
952             int end = n == &endContainer() ? std::min(std::max(start, m_end.offset()), length) : length;
953             builder.append(data, start, end - start);
954         }
955     }
956
957     return builder.toString();
958 }
959
960 String Range::toHTML() const
961 {
962     return createMarkup(*this);
963 }
964
965 String Range::text() const
966 {
967     // We need to update layout, since plainText uses line boxes in the render tree.
968     // FIXME: As with innerText, we'd like this to work even if there are no render objects.
969     startContainer().document().updateLayout();
970
971     return plainText(this);
972 }
973
974 RefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionCode& ec)
975 {
976     Node* element = startContainer().isElementNode() ? &startContainer() : startContainer().parentNode();
977     if (!element || !element->isHTMLElement()) {
978         ec = NOT_SUPPORTED_ERR;
979         return nullptr;
980     }
981
982     return WebCore::createContextualFragment(markup, downcast<HTMLElement>(element), AllowScriptingContentAndDoNotMarkAlreadyStarted, ec);
983 }
984
985
986 void Range::detach()
987 {
988     // This is now a no-op as per the DOM specification.
989 }
990
991 Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionCode& ec) const
992 {
993     switch (n->nodeType()) {
994         case Node::DOCUMENT_TYPE_NODE:
995             ec = INVALID_NODE_TYPE_ERR;
996             return nullptr;
997         case Node::CDATA_SECTION_NODE:
998         case Node::COMMENT_NODE:
999         case Node::TEXT_NODE:
1000         case Node::PROCESSING_INSTRUCTION_NODE:
1001             if (static_cast<unsigned>(offset) > downcast<CharacterData>(*n).length())
1002                 ec = INDEX_SIZE_ERR;
1003             return nullptr;
1004         case Node::ATTRIBUTE_NODE:
1005         case Node::DOCUMENT_FRAGMENT_NODE:
1006         case Node::DOCUMENT_NODE:
1007         case Node::ELEMENT_NODE:
1008         case Node::XPATH_NAMESPACE_NODE: {
1009             if (!offset)
1010                 return nullptr;
1011             Node* childBefore = n->traverseToChildAt(offset - 1);
1012             if (!childBefore)
1013                 ec = INDEX_SIZE_ERR;
1014             return childBefore;
1015         }
1016     }
1017     ASSERT_NOT_REACHED();
1018     return nullptr;
1019 }
1020
1021 void Range::checkNodeBA(Node* n, ExceptionCode& ec) const
1022 {
1023     // INVALID_NODE_TYPE_ERR: Raised if the root container of refNode is not an
1024     // Attr, Document, DocumentFragment or ShadowRoot node, or part of a SVG shadow DOM tree,
1025     // or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, or Entity node.
1026
1027     switch (n->nodeType()) {
1028         case Node::ATTRIBUTE_NODE:
1029         case Node::DOCUMENT_FRAGMENT_NODE:
1030         case Node::DOCUMENT_NODE:
1031             ec = INVALID_NODE_TYPE_ERR;
1032             return;
1033         case Node::CDATA_SECTION_NODE:
1034         case Node::COMMENT_NODE:
1035         case Node::DOCUMENT_TYPE_NODE:
1036         case Node::ELEMENT_NODE:
1037         case Node::PROCESSING_INSTRUCTION_NODE:
1038         case Node::TEXT_NODE:
1039         case Node::XPATH_NAMESPACE_NODE:
1040             break;
1041     }
1042
1043     Node* root = n;
1044     while (ContainerNode* parent = root->parentNode())
1045         root = parent;
1046
1047     switch (root->nodeType()) {
1048         case Node::ATTRIBUTE_NODE:
1049         case Node::DOCUMENT_NODE:
1050         case Node::DOCUMENT_FRAGMENT_NODE:
1051             break;
1052         case Node::CDATA_SECTION_NODE:
1053         case Node::COMMENT_NODE:
1054         case Node::DOCUMENT_TYPE_NODE:
1055         case Node::ELEMENT_NODE:
1056         case Node::PROCESSING_INSTRUCTION_NODE:
1057         case Node::TEXT_NODE:
1058         case Node::XPATH_NAMESPACE_NODE:
1059             ec = INVALID_NODE_TYPE_ERR;
1060             return;
1061     }
1062 }
1063
1064 Ref<Range> Range::cloneRange() const
1065 {
1066     return Range::create(ownerDocument(), &startContainer(), m_start.offset(), &endContainer(), m_end.offset());
1067 }
1068
1069 void Range::setStartAfter(Node* refNode, ExceptionCode& ec)
1070 {
1071     if (!refNode) {
1072         ec = TypeError;
1073         return;
1074     }
1075
1076     ec = 0;
1077     checkNodeBA(refNode, ec);
1078     if (ec)
1079         return;
1080
1081     setStart(refNode->parentNode(), refNode->computeNodeIndex() + 1, ec);
1082 }
1083
1084 void Range::setEndBefore(Node* refNode, ExceptionCode& ec)
1085 {
1086     if (!refNode) {
1087         ec = TypeError;
1088         return;
1089     }
1090
1091     ec = 0;
1092     checkNodeBA(refNode, ec);
1093     if (ec)
1094         return;
1095
1096     setEnd(refNode->parentNode(), refNode->computeNodeIndex(), ec);
1097 }
1098
1099 void Range::setEndAfter(Node* refNode, ExceptionCode& ec)
1100 {
1101     if (!refNode) {
1102         ec = TypeError;
1103         return;
1104     }
1105
1106     ec = 0;
1107     checkNodeBA(refNode, ec);
1108     if (ec)
1109         return;
1110
1111     setEnd(refNode->parentNode(), refNode->computeNodeIndex() + 1, ec);
1112 }
1113
1114 void Range::selectNode(Node* refNode, ExceptionCode& ec)
1115 {
1116     if (!refNode) {
1117         ec = TypeError;
1118         return;
1119     }
1120
1121     // INVALID_NODE_TYPE_ERR: Raised if an ancestor of refNode is an Entity, or
1122     // DocumentType node or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, or Entity
1123     // node.
1124     for (ContainerNode* anc = refNode->parentNode(); anc; anc = anc->parentNode()) {
1125         switch (anc->nodeType()) {
1126             case Node::ATTRIBUTE_NODE:
1127             case Node::CDATA_SECTION_NODE:
1128             case Node::COMMENT_NODE:
1129             case Node::DOCUMENT_FRAGMENT_NODE:
1130             case Node::DOCUMENT_NODE:
1131             case Node::ELEMENT_NODE:
1132             case Node::PROCESSING_INSTRUCTION_NODE:
1133             case Node::TEXT_NODE:
1134             case Node::XPATH_NAMESPACE_NODE:
1135                 break;
1136             case Node::DOCUMENT_TYPE_NODE:
1137                 ec = INVALID_NODE_TYPE_ERR;
1138                 return;
1139         }
1140     }
1141
1142     switch (refNode->nodeType()) {
1143         case Node::CDATA_SECTION_NODE:
1144         case Node::COMMENT_NODE:
1145         case Node::DOCUMENT_TYPE_NODE:
1146         case Node::ELEMENT_NODE:
1147         case Node::PROCESSING_INSTRUCTION_NODE:
1148         case Node::TEXT_NODE:
1149         case Node::XPATH_NAMESPACE_NODE:
1150             break;
1151         case Node::ATTRIBUTE_NODE:
1152         case Node::DOCUMENT_FRAGMENT_NODE:
1153         case Node::DOCUMENT_NODE:
1154             ec = INVALID_NODE_TYPE_ERR;
1155             return;
1156     }
1157
1158     if (&ownerDocument() != &refNode->document())
1159         setDocument(refNode->document());
1160
1161     ec = 0;
1162     setStartBefore(refNode, ec);
1163     if (ec)
1164         return;
1165     setEndAfter(refNode, ec);
1166 }
1167
1168 void Range::selectNodeContents(Node* refNode, ExceptionCode& ec)
1169 {
1170     if (!refNode) {
1171         ec = TypeError;
1172         return;
1173     }
1174
1175     // INVALID_NODE_TYPE_ERR: Raised if refNode or an ancestor of refNode is an Entity,
1176     // or DocumentType node.
1177     for (Node* n = refNode; n; n = n->parentNode()) {
1178         switch (n->nodeType()) {
1179             case Node::ATTRIBUTE_NODE:
1180             case Node::CDATA_SECTION_NODE:
1181             case Node::COMMENT_NODE:
1182             case Node::DOCUMENT_FRAGMENT_NODE:
1183             case Node::DOCUMENT_NODE:
1184             case Node::ELEMENT_NODE:
1185             case Node::PROCESSING_INSTRUCTION_NODE:
1186             case Node::TEXT_NODE:
1187             case Node::XPATH_NAMESPACE_NODE:
1188                 break;
1189             case Node::DOCUMENT_TYPE_NODE:
1190                 ec = INVALID_NODE_TYPE_ERR;
1191                 return;
1192         }
1193     }
1194
1195     if (&ownerDocument() != &refNode->document())
1196         setDocument(refNode->document());
1197
1198     m_start.setToStartOfNode(refNode);
1199     m_end.setToEndOfNode(refNode);
1200 }
1201
1202 void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionCode& ec)
1203 {
1204     RefPtr<Node> newParent = passNewParent;
1205
1206     if (!newParent) {
1207         ec = TypeError;
1208         return;
1209     }
1210
1211     // INVALID_STATE_ERR: Raised if the Range partially selects a non-Text node.
1212     // https://dom.spec.whatwg.org/#dom-range-surroundcontents (step 1).
1213     Node* startNonTextContainer = &startContainer();
1214     if (startNonTextContainer->nodeType() == Node::TEXT_NODE)
1215         startNonTextContainer = startNonTextContainer->parentNode();
1216     Node* endNonTextContainer = &endContainer();
1217     if (endNonTextContainer->nodeType() == Node::TEXT_NODE)
1218         endNonTextContainer = endNonTextContainer->parentNode();
1219     if (startNonTextContainer != endNonTextContainer) {
1220         ec = INVALID_STATE_ERR;
1221         return;
1222     }
1223
1224     // INVALID_NODE_TYPE_ERR: Raised if node is an Attr, Entity, DocumentType,
1225     // Document, or DocumentFragment node.
1226     switch (newParent->nodeType()) {
1227         case Node::ATTRIBUTE_NODE:
1228         case Node::DOCUMENT_FRAGMENT_NODE:
1229         case Node::DOCUMENT_NODE:
1230         case Node::DOCUMENT_TYPE_NODE:
1231             ec = INVALID_NODE_TYPE_ERR;
1232             return;
1233         case Node::CDATA_SECTION_NODE:
1234         case Node::COMMENT_NODE:
1235         case Node::ELEMENT_NODE:
1236         case Node::PROCESSING_INSTRUCTION_NODE:
1237         case Node::TEXT_NODE:
1238         case Node::XPATH_NAMESPACE_NODE:
1239             break;
1240     }
1241
1242     // Raise a HIERARCHY_REQUEST_ERR if startContainer() doesn't accept children like newParent.
1243     Node* parentOfNewParent = &startContainer();
1244
1245     // If startContainer() is a character data node, it will be split and it will be its parent that will
1246     // need to accept newParent (or in the case of a comment, it logically "would" be inserted into the parent,
1247     // although this will fail below for another reason).
1248     if (parentOfNewParent->isCharacterDataNode())
1249         parentOfNewParent = parentOfNewParent->parentNode();
1250     if (!parentOfNewParent || !parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
1251         ec = HIERARCHY_REQUEST_ERR;
1252         return;
1253     }
1254     
1255     if (newParent->contains(&startContainer())) {
1256         ec = HIERARCHY_REQUEST_ERR;
1257         return;
1258     }
1259
1260     // FIXME: Do we need a check if the node would end up with a child node of a type not
1261     // allowed by the type of node?
1262
1263     ec = 0;
1264     while (Node* n = newParent->firstChild()) {
1265         downcast<ContainerNode>(*newParent).removeChild(*n, ec);
1266         if (ec)
1267             return;
1268     }
1269     RefPtr<DocumentFragment> fragment = extractContents(ec);
1270     if (ec)
1271         return;
1272     insertNode(newParent, ec);
1273     if (ec)
1274         return;
1275     newParent->appendChild(fragment.release(), ec);
1276     if (ec)
1277         return;
1278     selectNode(newParent.get(), ec);
1279 }
1280
1281 void Range::setStartBefore(Node* refNode, ExceptionCode& ec)
1282 {
1283     if (!refNode) {
1284         ec = TypeError;
1285         return;
1286     }
1287
1288     ec = 0;
1289     checkNodeBA(refNode, ec);
1290     if (ec)
1291         return;
1292
1293     setStart(refNode->parentNode(), refNode->computeNodeIndex(), ec);
1294 }
1295
1296 Node* Range::firstNode() const
1297 {
1298     if (startContainer().offsetInCharacters())
1299         return &startContainer();
1300     if (Node* child = startContainer().traverseToChildAt(m_start.offset()))
1301         return child;
1302     if (!m_start.offset())
1303         return &startContainer();
1304     return NodeTraversal::nextSkippingChildren(startContainer());
1305 }
1306
1307 ShadowRoot* Range::shadowRoot() const
1308 {
1309     return startContainer().containingShadowRoot();
1310 }
1311
1312 Node* Range::pastLastNode() const
1313 {
1314     if (endContainer().offsetInCharacters())
1315         return NodeTraversal::nextSkippingChildren(endContainer());
1316     if (Node* child = endContainer().traverseToChildAt(m_end.offset()))
1317         return child;
1318     return NodeTraversal::nextSkippingChildren(endContainer());
1319 }
1320
1321 IntRect Range::absoluteBoundingBox() const
1322 {
1323     IntRect result;
1324     Vector<IntRect> rects;
1325     absoluteTextRects(rects);
1326     const size_t n = rects.size();
1327     for (size_t i = 0; i < n; ++i)
1328         result.unite(rects[i]);
1329     return result;
1330 }
1331
1332 void Range::absoluteTextRects(Vector<IntRect>& rects, bool useSelectionHeight, RangeInFixedPosition* inFixed) const
1333 {
1334     bool allFixed = true;
1335     bool someFixed = false;
1336
1337     Node* stopNode = pastLastNode();
1338     for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
1339         RenderObject* renderer = node->renderer();
1340         if (!renderer)
1341             continue;
1342         bool isFixed = false;
1343         if (renderer->isBR())
1344             renderer->absoluteRects(rects, flooredLayoutPoint(renderer->localToAbsolute()));
1345         else if (is<RenderText>(*renderer)) {
1346             int startOffset = node == &startContainer() ? m_start.offset() : 0;
1347             int endOffset = node == &endContainer() ? m_end.offset() : std::numeric_limits<int>::max();
1348             rects.appendVector(downcast<RenderText>(*renderer).absoluteRectsForRange(startOffset, endOffset, useSelectionHeight, &isFixed));
1349         } else
1350             continue;
1351         allFixed &= isFixed;
1352         someFixed |= isFixed;
1353     }
1354     
1355     if (inFixed)
1356         *inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition);
1357 }
1358
1359 void Range::absoluteTextQuads(Vector<FloatQuad>& quads, bool useSelectionHeight, RangeInFixedPosition* inFixed) const
1360 {
1361     bool allFixed = true;
1362     bool someFixed = false;
1363
1364     Node* stopNode = pastLastNode();
1365     for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
1366         RenderObject* renderer = node->renderer();
1367         if (!renderer)
1368             continue;
1369         bool isFixed = false;
1370         if (renderer->isBR())
1371             renderer->absoluteQuads(quads, &isFixed);
1372         else if (is<RenderText>(*renderer)) {
1373             int startOffset = node == &startContainer() ? m_start.offset() : 0;
1374             int endOffset = node == &endContainer() ? m_end.offset() : std::numeric_limits<int>::max();
1375             quads.appendVector(downcast<RenderText>(*renderer).absoluteQuadsForRange(startOffset, endOffset, useSelectionHeight, &isFixed));
1376         } else
1377             continue;
1378         allFixed &= isFixed;
1379         someFixed |= isFixed;
1380     }
1381
1382     if (inFixed)
1383         *inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition);
1384 }
1385
1386 #if PLATFORM(IOS)
1387 static bool intervalsSufficientlyOverlap(int startA, int endA, int startB, int endB)
1388 {
1389     if (endA <= startA || endB <= startB)
1390         return false;
1391
1392     const float sufficientOverlap = .75;
1393
1394     int lengthA = endA - startA;
1395     int lengthB = endB - startB;
1396
1397     int maxStart = std::max(startA, startB);
1398     int minEnd = std::min(endA, endB);
1399
1400     if (maxStart > minEnd)
1401         return false;
1402
1403     return minEnd - maxStart >= sufficientOverlap * std::min(lengthA, lengthB);
1404 }
1405
1406 static inline void adjustLineHeightOfSelectionRects(Vector<SelectionRect>& rects, size_t numberOfRects, int lineNumber, int lineTop, int lineHeight)
1407 {
1408     ASSERT(rects.size() >= numberOfRects);
1409     for (size_t i = numberOfRects; i; ) {
1410         --i;
1411         if (rects[i].lineNumber())
1412             break;
1413         rects[i].setLineNumber(lineNumber);
1414         rects[i].setLogicalTop(lineTop);
1415         rects[i].setLogicalHeight(lineHeight);
1416     }
1417 }
1418
1419 static SelectionRect coalesceSelectionRects(const SelectionRect& original, const SelectionRect& previous)
1420 {
1421     SelectionRect result(unionRect(previous.rect(), original.rect()), original.isHorizontal(), original.pageNumber());
1422     result.setDirection(original.containsStart() || original.containsEnd() ? original.direction() : previous.direction());
1423     result.setContainsStart(previous.containsStart() || original.containsStart());
1424     result.setContainsEnd(previous.containsEnd() || original.containsEnd());
1425     result.setIsFirstOnLine(previous.isFirstOnLine() || original.isFirstOnLine());
1426     result.setIsLastOnLine(previous.isLastOnLine() || original.isLastOnLine());
1427     return result;
1428 }
1429
1430 // This function is similar in spirit to addLineBoxRects, but annotates the returned rectangles
1431 // with additional state which helps iOS draw selections in its unique way.
1432 void Range::collectSelectionRects(Vector<SelectionRect>& rects)
1433 {
1434     auto& startContainer = this->startContainer();
1435     auto& endContainer = this->endContainer();
1436     int startOffset = m_start.offset();
1437     int endOffset = m_end.offset();
1438
1439     Vector<SelectionRect> newRects;
1440     Node* stopNode = pastLastNode();
1441     bool hasFlippedWritingMode = startContainer.renderer() && startContainer.renderer()->style().isFlippedBlocksWritingMode();
1442     bool containsDifferentWritingModes = false;
1443     for (Node* node = firstNode(); node && node != stopNode; node = NodeTraversal::next(*node)) {
1444         RenderObject* renderer = node->renderer();
1445         // Only ask leaf render objects for their line box rects.
1446         if (renderer && !renderer->firstChildSlow() && renderer->style().userSelect() != SELECT_NONE) {
1447             bool isStartNode = renderer->node() == &startContainer;
1448             bool isEndNode = renderer->node() == &endContainer;
1449             if (hasFlippedWritingMode != renderer->style().isFlippedBlocksWritingMode())
1450                 containsDifferentWritingModes = true;
1451             // FIXME: Sending 0 for the startOffset is a weird way of telling the renderer that the selection
1452             // doesn't start inside it, since we'll also send 0 if the selection *does* start in it, at offset 0.
1453             //
1454             // FIXME: Selection endpoints aren't always inside leaves, and we only build SelectionRects for leaves,
1455             // so we can't accurately determine which SelectionRects contain the selection start and end using
1456             // only the offsets of the start and end. We need to pass the whole Range.
1457             int beginSelectionOffset = isStartNode ? startOffset : 0;
1458             int endSelectionOffset = isEndNode ? endOffset : std::numeric_limits<int>::max();
1459             renderer->collectSelectionRects(newRects, beginSelectionOffset, endSelectionOffset);
1460             size_t numberOfNewRects = newRects.size();
1461             for (size_t i = 0; i < numberOfNewRects; ++i) {
1462                 SelectionRect& selectionRect = newRects[i];
1463                 if (selectionRect.containsStart() && !isStartNode)
1464                     selectionRect.setContainsStart(false);
1465                 if (selectionRect.containsEnd() && !isEndNode)
1466                     selectionRect.setContainsEnd(false);
1467                 if (selectionRect.logicalWidth() || selectionRect.logicalHeight())
1468                     rects.append(newRects[i]);
1469             }
1470             newRects.shrink(0);
1471         }
1472     }
1473
1474     // The range could span over nodes with different writing modes.
1475     // If this is the case, we use the writing mode of the common ancestor.
1476     if (containsDifferentWritingModes) {
1477         if (Node* ancestor = commonAncestorContainer(&startContainer, &endContainer))
1478             hasFlippedWritingMode = ancestor->renderer()->style().isFlippedBlocksWritingMode();
1479     }
1480
1481     const size_t numberOfRects = rects.size();
1482
1483     // If the selection ends in a BR, then add the line break bit to the last
1484     // rect we have. This will cause its selection rect to extend to the
1485     // end of the line.
1486     if (stopNode && stopNode->hasTagName(HTMLNames::brTag) && numberOfRects) {
1487         // Only set the line break bit if the end of the range actually
1488         // extends all the way to include the <br>. VisiblePosition helps to
1489         // figure this out.
1490         VisiblePosition endPosition(createLegacyEditingPosition(&endContainer, endOffset), VP_DEFAULT_AFFINITY);
1491         VisiblePosition brPosition(createLegacyEditingPosition(stopNode, 0), VP_DEFAULT_AFFINITY);
1492         if (endPosition == brPosition)
1493             rects.last().setIsLineBreak(true);    
1494     }
1495
1496     int lineTop = std::numeric_limits<int>::max();
1497     int lineBottom = std::numeric_limits<int>::min();
1498     int lastLineTop = lineTop;
1499     int lastLineBottom = lineBottom;
1500     int lineNumber = 0;
1501
1502     for (size_t i = 0; i < numberOfRects; ++i) {
1503         int currentRectTop = rects[i].logicalTop();
1504         int currentRectBottom = currentRectTop + rects[i].logicalHeight();
1505
1506         // We don't want to count the ruby text as a separate line.
1507         if (intervalsSufficientlyOverlap(currentRectTop, currentRectBottom, lineTop, lineBottom) || (i && rects[i].isRubyText())) {
1508             // Grow the current line bounds.
1509             lineTop = std::min(lineTop, currentRectTop);
1510             lineBottom = std::max(lineBottom, currentRectBottom);
1511             // Avoid overlap with the previous line.
1512             if (!hasFlippedWritingMode)
1513                 lineTop = std::max(lastLineBottom, lineTop);
1514             else
1515                 lineBottom = std::min(lastLineTop, lineBottom);
1516         } else {
1517             adjustLineHeightOfSelectionRects(rects, i, lineNumber, lineTop, lineBottom - lineTop);
1518             if (!hasFlippedWritingMode) {
1519                 lastLineTop = lineTop;
1520                 if (currentRectBottom >= lastLineTop) {
1521                     lastLineBottom = lineBottom;
1522                     lineTop = lastLineBottom;
1523                 } else {
1524                     lineTop = currentRectTop;
1525                     lastLineBottom = std::numeric_limits<int>::min();
1526                 }
1527                 lineBottom = currentRectBottom;
1528             } else {
1529                 lastLineBottom = lineBottom;
1530                 if (currentRectTop <= lastLineBottom && i && rects[i].pageNumber() == rects[i - 1].pageNumber()) {
1531                     lastLineTop = lineTop;
1532                     lineBottom = lastLineTop;
1533                 } else {
1534                     lastLineTop = std::numeric_limits<int>::max();
1535                     lineBottom = currentRectBottom;
1536                 }
1537                 lineTop = currentRectTop;
1538             }
1539             ++lineNumber;
1540         }
1541     }
1542
1543     // Adjust line height.
1544     adjustLineHeightOfSelectionRects(rects, numberOfRects, lineNumber, lineTop, lineBottom - lineTop);
1545
1546     // Sort the rectangles and make sure there are no gaps. The rectangles could be unsorted when
1547     // there is ruby text and we could have gaps on the line when adjacent elements on the line
1548     // have a different orientation.
1549     size_t firstRectWithCurrentLineNumber = 0;
1550     for (size_t currentRect = 1; currentRect < numberOfRects; ++currentRect) {
1551         if (rects[currentRect].lineNumber() != rects[currentRect - 1].lineNumber()) {
1552             firstRectWithCurrentLineNumber = currentRect;
1553             continue;
1554         }
1555         if (rects[currentRect].logicalLeft() >= rects[currentRect - 1].logicalLeft())
1556             continue;
1557
1558         SelectionRect selectionRect = rects[currentRect];
1559         size_t i;
1560         for (i = currentRect; i > firstRectWithCurrentLineNumber && selectionRect.logicalLeft() < rects[i - 1].logicalLeft(); --i)
1561             rects[i] = rects[i - 1];
1562         rects[i] = selectionRect;
1563     }
1564
1565     for (size_t j = 1; j < numberOfRects; ++j) {
1566         if (rects[j].lineNumber() != rects[j - 1].lineNumber())
1567             continue;
1568         SelectionRect& previousRect = rects[j - 1];
1569         bool previousRectMayNotReachRightEdge = (previousRect.direction() == LTR && previousRect.containsEnd()) || (previousRect.direction() == RTL && previousRect.containsStart());
1570         if (previousRectMayNotReachRightEdge)
1571             continue;
1572         int adjustedWidth = rects[j].logicalLeft() - previousRect.logicalLeft();
1573         if (adjustedWidth > previousRect.logicalWidth())
1574             previousRect.setLogicalWidth(adjustedWidth);
1575     }
1576
1577     int maxLineNumber = lineNumber;
1578
1579     // Extend rects out to edges as needed.
1580     for (size_t i = 0; i < numberOfRects; ++i) {
1581         SelectionRect& selectionRect = rects[i];
1582         if (!selectionRect.isLineBreak() && selectionRect.lineNumber() >= maxLineNumber)
1583             continue;
1584         if (selectionRect.direction() == RTL && selectionRect.isFirstOnLine()) {
1585             selectionRect.setLogicalWidth(selectionRect.logicalWidth() + selectionRect.logicalLeft() - selectionRect.minX());
1586             selectionRect.setLogicalLeft(selectionRect.minX());
1587         } else if (selectionRect.direction() == LTR && selectionRect.isLastOnLine())
1588             selectionRect.setLogicalWidth(selectionRect.maxX() - selectionRect.logicalLeft());
1589     }
1590
1591     // Union all the rectangles on interior lines (i.e. not first or last).
1592     // On first and last lines, just avoid having overlaps by merging intersecting rectangles.
1593     Vector<SelectionRect> unionedRects;
1594     IntRect interiorUnionRect;
1595     for (size_t i = 0; i < numberOfRects; ++i) {
1596         SelectionRect& currentRect = rects[i];
1597         if (currentRect.lineNumber() == 1) {
1598             ASSERT(interiorUnionRect.isEmpty());
1599             if (!unionedRects.isEmpty()) {
1600                 SelectionRect& previousRect = unionedRects.last();
1601                 if (previousRect.rect().intersects(currentRect.rect())) {
1602                     previousRect = coalesceSelectionRects(currentRect, previousRect);
1603                     continue;
1604                 }
1605             }
1606             // Couldn't merge with previous rect, so just appending.
1607             unionedRects.append(currentRect);
1608         } else if (currentRect.lineNumber() < maxLineNumber) {
1609             if (interiorUnionRect.isEmpty()) {
1610                 // Start collecting interior rects.
1611                 interiorUnionRect = currentRect.rect();         
1612             } else if (interiorUnionRect.intersects(currentRect.rect())
1613                 || interiorUnionRect.maxX() == currentRect.rect().x()
1614                 || interiorUnionRect.maxY() == currentRect.rect().y()
1615                 || interiorUnionRect.x() == currentRect.rect().maxX()
1616                 || interiorUnionRect.y() == currentRect.rect().maxY()) {
1617                 // Only union the lines that are attached.
1618                 // For iBooks, the interior lines may cross multiple horizontal pages.
1619                 interiorUnionRect.unite(currentRect.rect());
1620             } else {
1621                 unionedRects.append(SelectionRect(interiorUnionRect, currentRect.isHorizontal(), currentRect.pageNumber()));
1622                 interiorUnionRect = currentRect.rect();
1623             }
1624         } else {
1625             // Processing last line.
1626             if (!interiorUnionRect.isEmpty()) {
1627                 unionedRects.append(SelectionRect(interiorUnionRect, currentRect.isHorizontal(), currentRect.pageNumber()));
1628                 interiorUnionRect = IntRect();
1629             }
1630
1631             ASSERT(!unionedRects.isEmpty());
1632             SelectionRect& previousRect = unionedRects.last();
1633             if (previousRect.logicalTop() == currentRect.logicalTop() && previousRect.rect().intersects(currentRect.rect())) {
1634                 // previousRect is also on the last line, and intersects the current one.
1635                 previousRect = coalesceSelectionRects(currentRect, previousRect);
1636                 continue;
1637             }
1638             // Couldn't merge with previous rect, so just appending.
1639             unionedRects.append(currentRect);
1640         }
1641     }
1642
1643     rects.swap(unionedRects);
1644 }
1645 #endif
1646
1647 #if ENABLE(TREE_DEBUGGING)
1648 void Range::formatForDebugger(char* buffer, unsigned length) const
1649 {
1650     StringBuilder result;
1651
1652     const int FormatBufferSize = 1024;
1653     char s[FormatBufferSize];
1654     result.appendLiteral("from offset ");
1655     result.appendNumber(m_start.offset());
1656     result.appendLiteral(" of ");
1657     startContainer().formatForDebugger(s, FormatBufferSize);
1658     result.append(s);
1659     result.appendLiteral(" to offset ");
1660     result.appendNumber(m_end.offset());
1661     result.appendLiteral(" of ");
1662     endContainer().formatForDebugger(s, FormatBufferSize);
1663     result.append(s);
1664
1665     strncpy(buffer, result.toString().utf8().data(), length - 1);
1666 }
1667 #endif
1668
1669 bool Range::contains(const Range& other) const
1670 {
1671     if (commonAncestorContainer()->ownerDocument() != other.commonAncestorContainer()->ownerDocument())
1672         return false;
1673
1674     short startToStart = compareBoundaryPoints(Range::START_TO_START, &other, ASSERT_NO_EXCEPTION);
1675     if (startToStart > 0)
1676         return false;
1677
1678     short endToEnd = compareBoundaryPoints(Range::END_TO_END, &other, ASSERT_NO_EXCEPTION);
1679     return endToEnd >= 0;
1680 }
1681
1682 bool Range::contains(const VisiblePosition& position) const
1683 {
1684     RefPtr<Range> positionRange = makeRange(position, position);
1685     if (!positionRange)
1686         return false;
1687     return contains(*positionRange);
1688 }
1689
1690 bool areRangesEqual(const Range* a, const Range* b)
1691 {
1692     if (a == b)
1693         return true;
1694     if (!a || !b)
1695         return false;
1696     return a->startPosition() == b->startPosition() && a->endPosition() == b->endPosition();
1697 }
1698
1699 bool rangesOverlap(const Range* a, const Range* b)
1700 {
1701     if (!a || !b)
1702         return false;
1703
1704     if (a == b)
1705         return true;
1706
1707     if (a->commonAncestorContainer()->ownerDocument() != b->commonAncestorContainer()->ownerDocument())
1708         return false;
1709
1710     short startToStart = a->compareBoundaryPoints(Range::START_TO_START, b, ASSERT_NO_EXCEPTION);
1711     short endToEnd = a->compareBoundaryPoints(Range::END_TO_END, b, ASSERT_NO_EXCEPTION);
1712
1713     // First range contains the second range.
1714     if (startToStart <= 0 && endToEnd >= 0)
1715         return true;
1716
1717     // End of first range is inside second range.
1718     if (a->compareBoundaryPoints(Range::START_TO_END, b, ASSERT_NO_EXCEPTION) >= 0 && endToEnd <= 0)
1719         return true;
1720
1721     // Start of first range is inside second range.
1722     if (startToStart >= 0 && a->compareBoundaryPoints(Range::END_TO_START, b, ASSERT_NO_EXCEPTION) <= 0)
1723         return true;
1724
1725     return false;
1726 }
1727
1728 Ref<Range> rangeOfContents(Node& node)
1729 {
1730     Ref<Range> range = Range::create(node.document());
1731     int exception = 0;
1732     range->selectNodeContents(&node, exception);
1733     return range;
1734 }
1735
1736 static inline void boundaryNodeChildrenChanged(RangeBoundaryPoint& boundary, ContainerNode& container)
1737 {
1738     if (!boundary.childBefore())
1739         return;
1740     if (boundary.container() != &container)
1741         return;
1742     boundary.invalidateOffset();
1743 }
1744
1745 void Range::nodeChildrenChanged(ContainerNode& container)
1746 {
1747     ASSERT(&container.document() == &ownerDocument());
1748     boundaryNodeChildrenChanged(m_start, container);
1749     boundaryNodeChildrenChanged(m_end, container);
1750 }
1751
1752 static inline void boundaryNodeChildrenWillBeRemoved(RangeBoundaryPoint& boundary, ContainerNode& container)
1753 {
1754     for (Node* nodeToBeRemoved = container.firstChild(); nodeToBeRemoved; nodeToBeRemoved = nodeToBeRemoved->nextSibling()) {
1755         if (boundary.childBefore() == nodeToBeRemoved) {
1756             boundary.setToStartOfNode(&container);
1757             return;
1758         }
1759
1760         for (Node* n = boundary.container(); n; n = n->parentNode()) {
1761             if (n == nodeToBeRemoved) {
1762                 boundary.setToStartOfNode(&container);
1763                 return;
1764             }
1765         }
1766     }
1767 }
1768
1769 void Range::nodeChildrenWillBeRemoved(ContainerNode& container)
1770 {
1771     ASSERT(&container.document() == &ownerDocument());
1772     boundaryNodeChildrenWillBeRemoved(m_start, container);
1773     boundaryNodeChildrenWillBeRemoved(m_end, container);
1774 }
1775
1776 static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node& nodeToBeRemoved)
1777 {
1778     if (boundary.childBefore() == &nodeToBeRemoved) {
1779         boundary.childBeforeWillBeRemoved();
1780         return;
1781     }
1782
1783     for (Node* n = boundary.container(); n; n = n->parentNode()) {
1784         if (n == &nodeToBeRemoved) {
1785             boundary.setToBeforeChild(nodeToBeRemoved);
1786             return;
1787         }
1788     }
1789 }
1790
1791 void Range::nodeWillBeRemoved(Node& node)
1792 {
1793     ASSERT(&node.document() == &ownerDocument());
1794     ASSERT(&node != &ownerDocument());
1795     ASSERT(node.parentNode());
1796     boundaryNodeWillBeRemoved(m_start, node);
1797     boundaryNodeWillBeRemoved(m_end, node);
1798 }
1799
1800 static inline void boundaryTextInserted(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length)
1801 {
1802     if (boundary.container() != text)
1803         return;
1804     unsigned boundaryOffset = boundary.offset();
1805     if (offset >= boundaryOffset)
1806         return;
1807     boundary.setOffset(boundaryOffset + length);
1808 }
1809
1810 void Range::textInserted(Node* text, unsigned offset, unsigned length)
1811 {
1812     ASSERT(text);
1813     ASSERT(&text->document() == &ownerDocument());
1814     boundaryTextInserted(m_start, text, offset, length);
1815     boundaryTextInserted(m_end, text, offset, length);
1816 }
1817
1818 static inline void boundaryTextRemoved(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length)
1819 {
1820     if (boundary.container() != text)
1821         return;
1822     unsigned boundaryOffset = boundary.offset();
1823     if (offset >= boundaryOffset)
1824         return;
1825     if (offset + length >= boundaryOffset)
1826         boundary.setOffset(offset);
1827     else
1828         boundary.setOffset(boundaryOffset - length);
1829 }
1830
1831 void Range::textRemoved(Node* text, unsigned offset, unsigned length)
1832 {
1833     ASSERT(text);
1834     ASSERT(&text->document() == &ownerDocument());
1835     boundaryTextRemoved(m_start, text, offset, length);
1836     boundaryTextRemoved(m_end, text, offset, length);
1837 }
1838
1839 static inline void boundaryTextNodesMerged(RangeBoundaryPoint& boundary, NodeWithIndex& oldNode, unsigned offset)
1840 {
1841     if (boundary.container() == oldNode.node())
1842         boundary.set(oldNode.node()->previousSibling(), boundary.offset() + offset, 0);
1843     else if (boundary.container() == oldNode.node()->parentNode() && boundary.offset() == oldNode.index())
1844         boundary.set(oldNode.node()->previousSibling(), offset, 0);
1845 }
1846
1847 void Range::textNodesMerged(NodeWithIndex& oldNode, unsigned offset)
1848 {
1849     ASSERT(oldNode.node());
1850     ASSERT(&oldNode.node()->document() == &ownerDocument());
1851     ASSERT(oldNode.node()->parentNode());
1852     ASSERT(oldNode.node()->isTextNode());
1853     ASSERT(oldNode.node()->previousSibling());
1854     ASSERT(oldNode.node()->previousSibling()->isTextNode());
1855     boundaryTextNodesMerged(m_start, oldNode, offset);
1856     boundaryTextNodesMerged(m_end, oldNode, offset);
1857 }
1858
1859 static inline void boundaryTextNodesSplit(RangeBoundaryPoint& boundary, Text* oldNode)
1860 {
1861     if (boundary.container() != oldNode)
1862         return;
1863     unsigned boundaryOffset = boundary.offset();
1864     if (boundaryOffset <= oldNode->length())
1865         return;
1866     boundary.set(oldNode->nextSibling(), boundaryOffset - oldNode->length(), 0);
1867 }
1868
1869 void Range::textNodeSplit(Text* oldNode)
1870 {
1871     ASSERT(oldNode);
1872     ASSERT(&oldNode->document() == &ownerDocument());
1873     ASSERT(oldNode->parentNode());
1874     ASSERT(oldNode->isTextNode());
1875     ASSERT(oldNode->nextSibling());
1876     ASSERT(oldNode->nextSibling()->isTextNode());
1877     boundaryTextNodesSplit(m_start, oldNode);
1878     boundaryTextNodesSplit(m_end, oldNode);
1879 }
1880
1881 void Range::expand(const String& unit, ExceptionCode& ec)
1882 {
1883     VisiblePosition start(startPosition());
1884     VisiblePosition end(endPosition());
1885     if (unit == "word") {
1886         start = startOfWord(start);
1887         end = endOfWord(end);
1888     } else if (unit == "sentence") {
1889         start = startOfSentence(start);
1890         end = endOfSentence(end);
1891     } else if (unit == "block") {
1892         start = startOfParagraph(start);
1893         end = endOfParagraph(end);
1894     } else if (unit == "document") {
1895         start = startOfDocument(start);
1896         end = endOfDocument(end);
1897     } else
1898         return;
1899     setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), ec);
1900     setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), ec);
1901 }
1902
1903 Ref<ClientRectList> Range::getClientRects() const
1904 {
1905     ownerDocument().updateLayoutIgnorePendingStylesheets();
1906
1907     Vector<FloatQuad> quads;
1908     getBorderAndTextQuads(quads, CoordinateSpace::Client);
1909
1910     return ClientRectList::create(quads);
1911 }
1912
1913 Ref<ClientRect> Range::getBoundingClientRect() const
1914 {
1915     return ClientRect::create(boundingRectInternal(CoordinateSpace::Client));
1916 }
1917
1918 void Range::getBorderAndTextQuads(Vector<FloatQuad>& quads, CoordinateSpace space) const
1919 {
1920     Node* stopNode = pastLastNode();
1921
1922     HashSet<Node*> selectedElementsSet;
1923     for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
1924         if (node->isElementNode())
1925             selectedElementsSet.add(node);
1926     }
1927
1928     // Don't include elements that are only partially selected.
1929     Node* lastNode = m_end.childBefore() ? m_end.childBefore() : &endContainer();
1930     for (Node* parent = lastNode->parentNode(); parent; parent = parent->parentNode())
1931         selectedElementsSet.remove(parent);
1932
1933     for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
1934         if (is<Element>(*node) && selectedElementsSet.contains(node) && !selectedElementsSet.contains(node->parentNode())) {
1935             if (RenderBoxModelObject* renderBoxModelObject = downcast<Element>(*node).renderBoxModelObject()) {
1936                 Vector<FloatQuad> elementQuads;
1937                 renderBoxModelObject->absoluteQuads(elementQuads);
1938
1939                 if (space == CoordinateSpace::Client)
1940                     ownerDocument().adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(elementQuads, renderBoxModelObject->style());
1941
1942                 quads.appendVector(elementQuads);
1943             }
1944         } else if (is<Text>(*node)) {
1945             if (RenderText* renderText = downcast<Text>(*node).renderer()) {
1946                 int startOffset = node == &startContainer() ? m_start.offset() : 0;
1947                 int endOffset = node == &endContainer() ? m_end.offset() : INT_MAX;
1948                 
1949                 auto textQuads = renderText->absoluteQuadsForRange(startOffset, endOffset);
1950
1951                 if (space == CoordinateSpace::Client)
1952                     ownerDocument().adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(textQuads, renderText->style());
1953
1954                 quads.appendVector(textQuads);
1955             }
1956         }
1957     }
1958 }
1959
1960 FloatRect Range::boundingRectInternal(CoordinateSpace space) const
1961 {
1962     ownerDocument().updateLayoutIgnorePendingStylesheets();
1963
1964     Vector<FloatQuad> quads;
1965     getBorderAndTextQuads(quads, space);
1966
1967     FloatRect result;
1968     for (auto& quad : quads)
1969         result.unite(quad.boundingBox());
1970
1971     return result;
1972 }
1973
1974 FloatRect Range::absoluteBoundingRect() const
1975 {
1976     return boundingRectInternal(CoordinateSpace::Absolute);
1977 }
1978
1979 } // namespace WebCore
1980
1981 #if ENABLE(TREE_DEBUGGING)
1982
1983 void showTree(const WebCore::Range* range)
1984 {
1985     if (range && range->boundaryPointsValid()) {
1986         range->startContainer().showTreeAndMark(&range->startContainer(), "S", &range->endContainer(), "E");
1987         fprintf(stderr, "start offset: %d, end offset: %d\n", range->startOffset(), range->endOffset());
1988     }
1989 }
1990
1991 #endif