Repaint issue with vertical text in an out of flow container.
[WebKit-https.git] / Source / WebCore / rendering / RenderObject.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2000 Dirk Mueller (mueller@kde.org)
5  *           (C) 2004 Allan Sandfeld Jensen (kde@carewolf.com)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011, 2013 Apple Inc. All rights reserved.
7  * Copyright (C) 2009 Google Inc. All rights reserved.
8  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  *
25  */
26
27 #include "config.h"
28 #include "RenderObject.h"
29
30 #include "AXObjectCache.h"
31 #include "AnimationController.h"
32 #include "EventHandler.h"
33 #include "FloatQuad.h"
34 #include "FlowThreadController.h"
35 #include "FrameSelection.h"
36 #include "FrameView.h"
37 #include "GeometryUtilities.h"
38 #include "GraphicsContext.h"
39 #include "HTMLAnchorElement.h"
40 #include "HTMLElement.h"
41 #include "HTMLImageElement.h"
42 #include "HTMLNames.h"
43 #include "HTMLTableCellElement.h"
44 #include "HTMLTableElement.h"
45 #include "HitTestResult.h"
46 #include "LogicalSelectionOffsetCaches.h"
47 #include "MainFrame.h"
48 #include "Page.h"
49 #include "PseudoElement.h"
50 #include "RenderChildIterator.h"
51 #include "RenderCounter.h"
52 #include "RenderFlowThread.h"
53 #include "RenderGeometryMap.h"
54 #include "RenderInline.h"
55 #include "RenderIterator.h"
56 #include "RenderLayer.h"
57 #include "RenderLayerBacking.h"
58 #include "RenderMultiColumnFlowThread.h"
59 #include "RenderNamedFlowFragment.h"
60 #include "RenderNamedFlowThread.h" 
61 #include "RenderRuby.h"
62 #include "RenderSVGResourceContainer.h"
63 #include "RenderScrollbarPart.h"
64 #include "RenderTableRow.h"
65 #include "RenderTableSection.h"
66 #include "RenderTheme.h"
67 #include "RenderView.h"
68 #include "RenderWidget.h"
69 #include "SVGRenderSupport.h"
70 #include "Settings.h"
71 #include "StyleResolver.h"
72 #include "TransformState.h"
73 #include "htmlediting.h"
74 #include <algorithm>
75 #include <stdio.h>
76 #include <wtf/RefCountedLeakCounter.h>
77
78 #if PLATFORM(IOS)
79 #include "SelectionRect.h"
80 #endif
81
82 namespace WebCore {
83
84 using namespace HTMLNames;
85
86 #ifndef NDEBUG
87
88 RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject, bool isForbidden)
89     : m_renderObject(renderObject)
90     , m_preexistingForbidden(m_renderObject->isSetNeedsLayoutForbidden())
91 {
92     m_renderObject->setNeedsLayoutIsForbidden(isForbidden);
93 }
94
95 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
96 {
97     m_renderObject->setNeedsLayoutIsForbidden(m_preexistingForbidden);
98 }
99 #endif
100
101 struct SameSizeAsRenderObject {
102     virtual ~SameSizeAsRenderObject() { } // Allocate vtable pointer.
103     void* pointers[4];
104 #ifndef NDEBUG
105     unsigned m_debugBitfields : 2;
106 #endif
107     unsigned m_bitfields;
108 };
109
110 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
111
112 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
113
114 RenderObject::RenderObject(Node& node)
115     : CachedImageClient()
116     , m_node(node)
117     , m_parent(nullptr)
118     , m_previous(nullptr)
119     , m_next(nullptr)
120 #ifndef NDEBUG
121     , m_hasAXObject(false)
122     , m_setNeedsLayoutForbidden(false)
123 #endif
124     , m_bitfields(node)
125 {
126     if (RenderView* renderView = node.document().renderView())
127         renderView->didCreateRenderer();
128 #ifndef NDEBUG
129     renderObjectCounter.increment();
130 #endif
131 }
132
133 RenderObject::~RenderObject()
134 {
135     view().didDestroyRenderer();
136 #ifndef NDEBUG
137     ASSERT(!m_hasAXObject);
138     renderObjectCounter.decrement();
139 #endif
140     ASSERT(!hasRareData());
141 }
142
143 RenderTheme& RenderObject::theme() const
144 {
145     ASSERT(document().page());
146     return document().page()->theme();
147 }
148
149 bool RenderObject::isDescendantOf(const RenderObject* ancestor) const
150 {
151     for (const RenderObject* renderer = this; renderer; renderer = renderer->m_parent) {
152         if (renderer == ancestor)
153             return true;
154     }
155     return false;
156 }
157
158 bool RenderObject::isLegend() const
159 {
160     return node() && node()->hasTagName(legendTag);
161 }
162
163 bool RenderObject::isHTMLMarquee() const
164 {
165     return node() && node()->renderer() == this && node()->hasTagName(marqueeTag);
166 }
167
168 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
169 {
170     setFlowThreadState(state);
171
172     if (!is<RenderElement>(*this))
173         return;
174
175     for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this))) {
176         // If the child is a fragmentation context it already updated the descendants flag accordingly.
177         if (child.isRenderFlowThread())
178             continue;
179         ASSERT(state != child.flowThreadState());
180         child.setFlowThreadStateIncludingDescendants(state);
181     }
182 }
183
184 void RenderObject::setParent(RenderElement* parent)
185 {
186     m_parent = parent;
187
188     // Only update if our flow thread state is different from our new parent and if we're not a RenderFlowThread.
189     // A RenderFlowThread is always considered to be inside itself, so it never has to change its state
190     // in response to parent changes.
191     FlowThreadState newState = parent ? parent->flowThreadState() : NotInsideFlowThread;
192     if (newState != flowThreadState() && !isRenderFlowThread())
193         setFlowThreadStateIncludingDescendants(newState);
194 }
195
196 void RenderObject::removeFromParent()
197 {
198     if (parent())
199         parent()->removeChild(*this);
200 }
201
202 RenderObject* RenderObject::nextInPreOrder() const
203 {
204     if (RenderObject* o = firstChildSlow())
205         return o;
206
207     return nextInPreOrderAfterChildren();
208 }
209
210 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
211 {
212     RenderObject* o;
213     if (!(o = nextSibling())) {
214         o = parent();
215         while (o && !o->nextSibling())
216             o = o->parent();
217         if (o)
218             o = o->nextSibling();
219     }
220
221     return o;
222 }
223
224 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
225 {
226     if (RenderObject* o = firstChildSlow())
227         return o;
228
229     return nextInPreOrderAfterChildren(stayWithin);
230 }
231
232 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
233 {
234     if (this == stayWithin)
235         return nullptr;
236
237     const RenderObject* current = this;
238     RenderObject* next;
239     while (!(next = current->nextSibling())) {
240         current = current->parent();
241         if (!current || current == stayWithin)
242             return nullptr;
243     }
244     return next;
245 }
246
247 RenderObject* RenderObject::previousInPreOrder() const
248 {
249     if (RenderObject* o = previousSibling()) {
250         while (RenderObject* last = o->lastChildSlow())
251             o = last;
252         return o;
253     }
254
255     return parent();
256 }
257
258 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
259 {
260     if (this == stayWithin)
261         return nullptr;
262
263     return previousInPreOrder();
264 }
265
266 RenderObject* RenderObject::childAt(unsigned index) const
267 {
268     RenderObject* child = firstChildSlow();
269     for (unsigned i = 0; child && i < index; i++)
270         child = child->nextSibling();
271     return child;
272 }
273
274 RenderObject* RenderObject::firstLeafChild() const
275 {
276     RenderObject* r = firstChildSlow();
277     while (r) {
278         RenderObject* n = nullptr;
279         n = r->firstChildSlow();
280         if (!n)
281             break;
282         r = n;
283     }
284     return r;
285 }
286
287 RenderObject* RenderObject::lastLeafChild() const
288 {
289     RenderObject* r = lastChildSlow();
290     while (r) {
291         RenderObject* n = nullptr;
292         n = r->lastChildSlow();
293         if (!n)
294             break;
295         r = n;
296     }
297     return r;
298 }
299
300 #if ENABLE(IOS_TEXT_AUTOSIZING)
301
302 // Non-recursive version of the DFS search.
303 RenderObject* RenderObject::traverseNext(const RenderObject* stayWithin, HeightTypeTraverseNextInclusionFunction inclusionFunction, int& currentDepth, int& newFixedDepth) const
304 {
305     BlockContentHeightType overflowType;
306
307     // Check for suitable children.
308     for (RenderObject* child = firstChildSlow(); child; child = child->nextSibling()) {
309         overflowType = inclusionFunction(*child);
310         if (overflowType != FixedHeight) {
311             currentDepth++;
312             if (overflowType == OverflowHeight)
313                 newFixedDepth = currentDepth;
314             ASSERT(!stayWithin || child->isDescendantOf(stayWithin));
315             return child;
316         }
317     }
318
319     if (this == stayWithin)
320         return nullptr;
321
322     // Now we traverse other nodes if they exist, otherwise
323     // we go to the parent node and try doing the same.
324     const RenderObject* n = this;
325     while (n) {
326         while (n && !n->nextSibling() && (!stayWithin || n->parent() != stayWithin)) {
327             n = n->parent();
328             currentDepth--;
329         }
330         if (!n)
331             return nullptr;
332         for (RenderObject* sibling = n->nextSibling(); sibling; sibling = sibling->nextSibling()) {
333             overflowType = inclusionFunction(*sibling);
334             if (overflowType != FixedHeight) {
335                 if (overflowType == OverflowHeight)
336                     newFixedDepth = currentDepth;
337                 ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
338                 return sibling;
339             }
340         }
341         if (!stayWithin || n->parent() != stayWithin) {
342             n = n->parent();
343             currentDepth--;
344         } else
345             return nullptr;
346     }
347     return nullptr;
348 }
349
350 #endif // ENABLE(IOS_TEXT_AUTOSIZING)
351
352 RenderLayer* RenderObject::enclosingLayer() const
353 {
354     for (auto& renderer : lineageOfType<RenderLayerModelObject>(*this)) {
355         if (renderer.hasLayer())
356             return renderer.layer();
357     }
358     return nullptr;
359 }
360
361 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
362 {
363     RenderLayer* enclosingLayer = this->enclosingLayer();
364     if (!enclosingLayer)
365         return false;
366
367     enclosingLayer->scrollRectToVisible(rect, alignX, alignY);
368     return true;
369 }
370
371 RenderBox& RenderObject::enclosingBox() const
372 {
373     return *lineageOfType<RenderBox>(const_cast<RenderObject&>(*this)).first();
374 }
375
376 RenderBoxModelObject& RenderObject::enclosingBoxModelObject() const
377 {
378     return *lineageOfType<RenderBoxModelObject>(const_cast<RenderObject&>(*this)).first();
379 }
380
381 bool RenderObject::fixedPositionedWithNamedFlowContainingBlock() const
382 {
383     return ((flowThreadState() == RenderObject::InsideOutOfFlowThread)
384         && (style().position() == FixedPosition)
385         && (containingBlock()->isOutOfFlowRenderFlowThread()));
386 }
387
388 static bool hasFixedPosInNamedFlowContainingBlock(const RenderObject* renderer)
389 {
390     ASSERT(renderer->flowThreadState() != RenderObject::NotInsideFlowThread);
391
392     RenderObject* curr = const_cast<RenderObject*>(renderer);
393     while (curr && !is<RenderView>(*curr)) {
394         if (curr->fixedPositionedWithNamedFlowContainingBlock())
395             return true;
396         curr = curr->containingBlock();
397     }
398
399     return false;
400 }
401
402 RenderBlock* RenderObject::firstLineBlock() const
403 {
404     return nullptr;
405 }
406
407 static inline bool objectIsRelayoutBoundary(const RenderElement* object)
408 {
409     // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
410     if (object->isRenderView())
411         return true;
412
413     if (object->isTextControl())
414         return true;
415
416     if (object->isSVGRoot())
417         return true;
418
419     if (!object->hasOverflowClip())
420         return false;
421
422     if (object->style().width().isIntrinsicOrAuto() || object->style().height().isIntrinsicOrAuto() || object->style().height().isPercentOrCalculated())
423         return false;
424
425     // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
426     if (object->isTablePart())
427         return false;
428
429     return true;
430 }
431
432 void RenderObject::clearNeedsLayout()
433 {
434     m_bitfields.setNeedsLayout(false);
435     setEverHadLayout(true);
436     setPosChildNeedsLayoutBit(false);
437     setNeedsSimplifiedNormalFlowLayoutBit(false);
438     setNormalChildNeedsLayoutBit(false);
439     setNeedsPositionedMovementLayoutBit(false);
440     if (is<RenderElement>(*this))
441         downcast<RenderElement>(*this).setAncestorLineBoxDirty(false);
442 #ifndef NDEBUG
443     checkBlockPositionedObjectsNeedLayout();
444 #endif
445 }
446
447 static void scheduleRelayoutForSubtree(RenderElement& renderer)
448 {
449     if (is<RenderView>(renderer)) {
450         downcast<RenderView>(renderer).frameView().scheduleRelayout();
451         return;
452     }
453
454     if (renderer.isRooted())
455         renderer.view().frameView().scheduleRelayoutOfSubtree(renderer);
456 }
457
458 void RenderObject::markContainingBlocksForLayout(ScheduleRelayout scheduleRelayout, RenderElement* newRoot)
459 {
460     ASSERT(scheduleRelayout == ScheduleRelayout::No || !newRoot);
461     ASSERT(!isSetNeedsLayoutForbidden());
462
463     auto ancestor = container();
464
465     bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
466     bool hasOutOfFlowPosition = !isText() && style().hasOutOfFlowPosition();
467
468     while (ancestor) {
469 #ifndef NDEBUG
470         // FIXME: Remove this once we remove the special cases for counters, quotes and mathml
471         // calling setNeedsLayout during preferred width computation.
472         SetLayoutNeededForbiddenScope layoutForbiddenScope(ancestor, isSetNeedsLayoutForbidden());
473 #endif
474         // Don't mark the outermost object of an unrooted subtree. That object will be
475         // marked when the subtree is added to the document.
476         auto container = ancestor->container();
477         if (!container && !ancestor->isRenderView())
478             return;
479         if (hasOutOfFlowPosition) {
480             bool willSkipRelativelyPositionedInlines = !ancestor->isRenderBlock() || ancestor->isAnonymousBlock();
481             // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
482             while (ancestor && (!ancestor->isRenderBlock() || ancestor->isAnonymousBlock()))
483                 ancestor = ancestor->container();
484             if (!ancestor || ancestor->posChildNeedsLayout())
485                 return;
486             if (willSkipRelativelyPositionedInlines)
487                 container = ancestor->container();
488             ancestor->setPosChildNeedsLayoutBit(true);
489             simplifiedNormalFlowLayout = true;
490         } else if (simplifiedNormalFlowLayout) {
491             if (ancestor->needsSimplifiedNormalFlowLayout())
492                 return;
493             ancestor->setNeedsSimplifiedNormalFlowLayoutBit(true);
494         } else {
495             if (ancestor->normalChildNeedsLayout())
496                 return;
497             ancestor->setNormalChildNeedsLayoutBit(true);
498         }
499         ASSERT(!ancestor->isSetNeedsLayoutForbidden());
500
501         if (ancestor == newRoot)
502             return;
503
504         if (scheduleRelayout == ScheduleRelayout::Yes && objectIsRelayoutBoundary(ancestor))
505             break;
506
507         hasOutOfFlowPosition = ancestor->style().hasOutOfFlowPosition();
508         ancestor = container;
509     }
510
511     if (scheduleRelayout == ScheduleRelayout::Yes && ancestor)
512         scheduleRelayoutForSubtree(*ancestor);
513 }
514
515 #ifndef NDEBUG
516 void RenderObject::checkBlockPositionedObjectsNeedLayout()
517 {
518     ASSERT(!needsLayout());
519
520     if (is<RenderBlock>(*this))
521         downcast<RenderBlock>(*this).checkPositionedObjectsNeedLayout();
522 }
523 #endif
524
525 void RenderObject::setPreferredLogicalWidthsDirty(bool shouldBeDirty, MarkingBehavior markParents)
526 {
527     bool alreadyDirty = preferredLogicalWidthsDirty();
528     m_bitfields.setPreferredLogicalWidthsDirty(shouldBeDirty);
529     if (shouldBeDirty && !alreadyDirty && markParents == MarkContainingBlockChain && (isText() || !style().hasOutOfFlowPosition()))
530         invalidateContainerPreferredLogicalWidths();
531 }
532
533 void RenderObject::invalidateContainerPreferredLogicalWidths()
534 {
535     // In order to avoid pathological behavior when inlines are deeply nested, we do include them
536     // in the chain that we mark dirty (even though they're kind of irrelevant).
537     auto o = isTableCell() ? containingBlock() : container();
538     while (o && !o->preferredLogicalWidthsDirty()) {
539         // Don't invalidate the outermost object of an unrooted subtree. That object will be 
540         // invalidated when the subtree is added to the document.
541         auto container = o->isTableCell() ? o->containingBlock() : o->container();
542         if (!container && !o->isRenderView())
543             break;
544
545         o->m_bitfields.setPreferredLogicalWidthsDirty(true);
546         if (o->style().hasOutOfFlowPosition())
547             // A positioned object has no effect on the min/max width of its containing block ever.
548             // We can optimize this case and not go up any further.
549             break;
550         o = container;
551     }
552 }
553
554 void RenderObject::setLayerNeedsFullRepaint()
555 {
556     ASSERT(hasLayer());
557     downcast<RenderLayerModelObject>(*this).layer()->setRepaintStatus(NeedsFullRepaint);
558 }
559
560 void RenderObject::setLayerNeedsFullRepaintForPositionedMovementLayout()
561 {
562     ASSERT(hasLayer());
563     downcast<RenderLayerModelObject>(*this).layer()->setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
564 }
565
566 RenderBlock* RenderObject::containingBlock() const
567 {
568     auto containingBlockForRenderer = [](const RenderObject& renderer)
569     {
570         auto& style = renderer.style();
571         if (style.position() == AbsolutePosition)
572             return renderer.containingBlockForAbsolutePosition();
573         if (style.position() == FixedPosition)
574             return renderer.containingBlockForFixedPosition();
575         return renderer.containingBlockForObjectInFlow();
576     };
577
578     if (is<RenderText>(*this))
579         return containingBlockForObjectInFlow();
580
581     if (!parent() && is<RenderScrollbarPart>(*this)) {
582         if (auto* renderer = downcast<RenderScrollbarPart>(*this).rendererOwningScrollbar())
583             return containingBlockForRenderer(*renderer);
584         return nullptr;
585     }
586     return containingBlockForRenderer(*this);
587 }
588
589 RenderBlock* RenderObject::containingBlockForFixedPosition() const
590 {
591     auto* renderer = parent();
592     while (renderer && !renderer->canContainFixedPositionObjects())
593         renderer = renderer->parent();
594
595     ASSERT(!renderer || !renderer->isAnonymousBlock());
596     return downcast<RenderBlock>(renderer);
597 }
598
599 RenderBlock* RenderObject::containingBlockForAbsolutePosition() const
600 {
601     // RenderInlines forward their absolute positioned descendants to the containing block, so
602     // we need to start searching from 'this' and not from 'parent()'.
603     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
604     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
605         renderer = renderer->parent();
606
607     // For a relatively positioned inline, return its nearest non-anonymous containing block,
608     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
609     // and use RenderBlock* as RenderElement::containingBlock's return type.
610     // Use RenderBlock::container() to obtain the inline.
611     if (renderer && !is<RenderBlock>(*renderer))
612         renderer = renderer->containingBlock();
613
614     while (renderer && renderer->isAnonymousBlock())
615         renderer = renderer->containingBlock();
616
617     return downcast<RenderBlock>(renderer);
618 }
619
620 RenderBlock* RenderObject::containingBlockForObjectInFlow() const
621 {
622     auto* renderer = parent();
623     while (renderer && ((renderer->isInline() && !renderer->isReplaced()) || !renderer->isRenderBlock()))
624         renderer = renderer->parent();
625     return downcast<RenderBlock>(renderer);
626 }
627
628 void RenderObject::addPDFURLRect(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
629 {
630     Vector<LayoutRect> focusRingRects;
631     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
632     LayoutRect urlRect = unionRect(focusRingRects);
633
634     if (urlRect.isEmpty())
635         return;
636     Node* node = this->node();
637     if (!is<Element>(node) || !node->isLink())
638         return;
639     const AtomicString& href = downcast<Element>(*node).getAttribute(hrefAttr);
640     if (href.isNull())
641         return;
642     paintInfo.context().setURLForRect(node->document().completeURL(href), snappedIntRect(urlRect));
643 }
644
645 #if PLATFORM(IOS)
646 // This function is similar in spirit to RenderText::absoluteRectsForRange, but returns rectangles
647 // which are annotated with additional state which helps iOS draw selections in its unique way.
648 // No annotations are added in this class.
649 // FIXME: Move to RenderText with absoluteRectsForRange()?
650 void RenderObject::collectSelectionRects(Vector<SelectionRect>& rects, unsigned start, unsigned end)
651 {
652     Vector<FloatQuad> quads;
653
654     if (!firstChildSlow()) {
655         // FIXME: WebKit's position for an empty span after a BR is incorrect, so we can't trust 
656         // quads for them. We don't need selection rects for those anyway though, since they 
657         // are just empty containers. See <https://bugs.webkit.org/show_bug.cgi?id=49358>.
658         RenderObject* previous = previousSibling();
659         Node* node = this->node();
660         if (!previous || !previous->isBR() || !node || !node->isContainerNode() || !isInline()) {
661             // For inline elements we don't use absoluteQuads, since it takes into account continuations and leads to wrong results.
662             absoluteQuadsForSelection(quads);
663         }
664     } else {
665         unsigned offset = start;
666         for (RenderObject* child = childAt(start); child && offset < end; child = child->nextSibling(), ++offset)
667             child->absoluteQuads(quads);
668     }
669
670     unsigned numberOfQuads = quads.size();
671     for (unsigned i = 0; i < numberOfQuads; ++i)
672         rects.append(SelectionRect(quads[i].enclosingBoundingBox(), isHorizontalWritingMode(), view().pageNumberForBlockProgressionOffset(quads[i].enclosingBoundingBox().x())));
673 }
674 #endif
675
676 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms, bool* wasFixed) const
677 {
678     if (useTransforms) {
679         Vector<FloatQuad> quads;
680         absoluteQuads(quads, wasFixed);
681
682         size_t n = quads.size();
683         if (!n)
684             return IntRect();
685     
686         IntRect result = quads[0].enclosingBoundingBox();
687         for (size_t i = 1; i < n; ++i)
688             result.unite(quads[i].enclosingBoundingBox());
689         return result;
690     }
691
692     FloatPoint absPos = localToAbsolute(FloatPoint(), 0 /* ignore transforms */, wasFixed);
693     Vector<IntRect> rects;
694     absoluteRects(rects, flooredLayoutPoint(absPos));
695
696     size_t n = rects.size();
697     if (!n)
698         return IntRect();
699
700     LayoutRect result = rects[0];
701     for (size_t i = 1; i < n; ++i)
702         result.unite(rects[i]);
703     return snappedIntRect(result);
704 }
705
706 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
707 {
708     Vector<LayoutRect> rects;
709     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
710     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
711     // implicitly assumes that. This doesn't work correctly with transformed
712     // descendants.
713     FloatPoint absolutePoint = localToAbsolute();
714     addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
715     float deviceScaleFactor = document().deviceScaleFactor();
716     for (auto rect : rects) {
717         rect.moveBy(LayoutPoint(-absolutePoint));
718         quads.append(localToAbsoluteQuad(FloatQuad(snapRectToDevicePixels(rect, deviceScaleFactor))));
719     }
720 }
721
722 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
723 {
724     if (!range)
725         return FloatRect();
726
727     range->ownerDocument().updateLayout();
728
729     Vector<FloatQuad> quads;
730     range->absoluteTextQuads(quads);
731
732     if (quads.isEmpty())
733         return FloatRect();
734
735     FloatRect result = quads[0].boundingBox();
736     for (size_t i = 1; i < quads.size(); ++i)
737         result.uniteEvenIfEmpty(quads[i].boundingBox());
738
739     return result;
740 }
741
742 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
743 {
744     if (hasLayer())
745         result.unite(absoluteBoundingBoxRectIgnoringTransforms());
746
747     if (!is<RenderElement>(*this))
748         return;
749
750     for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this)))
751         child.addAbsoluteRectForLayer(result);
752 }
753
754 // FIXME: change this to use the subtreePaint terminology
755 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
756 {
757     LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
758     topLevelRect = result;
759     if (is<RenderElement>(*this)) {
760         for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this)))
761             child.addAbsoluteRectForLayer(result);
762     }
763     return result;
764 }
765
766 RenderLayerModelObject* RenderObject::containerForRepaint() const
767 {
768     RenderLayerModelObject* repaintContainer = nullptr;
769
770     if (view().usesCompositing()) {
771         if (RenderLayer* parentLayer = enclosingLayer()) {
772             RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
773             if (compLayer)
774                 repaintContainer = &compLayer->renderer();
775         }
776     }
777     if (view().hasSoftwareFilters()) {
778         if (RenderLayer* parentLayer = enclosingLayer()) {
779             RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
780             if (enclosingFilterLayer)
781                 return &enclosingFilterLayer->renderer();
782         }
783     }
784
785     // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
786     // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
787     // repainting to do individual region repaints.
788     RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
789     if (parentRenderFlowThread) {
790         // If the element has a fixed positioned element with named flow as CB along the CB chain
791         // then the repaint container is not the flow thread.
792         if (hasFixedPosInNamedFlowContainingBlock(this))
793             return repaintContainer;
794         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
795         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
796         RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : nullptr;
797         if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
798             repaintContainer = parentRenderFlowThread;
799     }
800     return repaintContainer;
801 }
802
803 void RenderObject::propagateRepaintToParentWithOutlineAutoIfNeeded(const RenderLayerModelObject& repaintContainer, const LayoutRect& repaintRect) const
804 {
805     if (!hasOutlineAutoAncestor())
806         return;
807
808     // FIXME: We should really propagate only when the the child renderer sticks out.
809     bool repaintRectNeedsConverting = false;
810     // Issue repaint on the renderer with outline: auto.
811     for (const auto* renderer = this; renderer; renderer = renderer->parent()) {
812         bool rendererHasOutlineAutoAncestor = renderer->hasOutlineAutoAncestor();
813         ASSERT(rendererHasOutlineAutoAncestor
814             || renderer->outlineStyleForRepaint().outlineStyleIsAuto()
815             || (is<RenderElement>(*renderer) && downcast<RenderElement>(*renderer).hasContinuation()));
816         if (renderer == &repaintContainer && rendererHasOutlineAutoAncestor)
817             repaintRectNeedsConverting = true;
818         if (rendererHasOutlineAutoAncestor)
819             continue;
820         // Issue repaint on the correct repaint container.
821         LayoutRect adjustedRepaintRect = repaintRect;
822         adjustedRepaintRect.inflate(renderer->outlineStyleForRepaint().outlineSize());
823         if (!repaintRectNeedsConverting)
824             repaintContainer.repaintRectangle(adjustedRepaintRect);
825         else if (is<RenderLayerModelObject>(renderer)) {
826             const auto& rendererWithOutline = downcast<RenderLayerModelObject>(*renderer);
827             adjustedRepaintRect = LayoutRect(repaintContainer.localToContainerQuad(FloatRect(adjustedRepaintRect), &rendererWithOutline).boundingBox());
828             rendererWithOutline.repaintRectangle(adjustedRepaintRect);
829         }
830         return;
831     }
832     ASSERT_NOT_REACHED();
833 }
834
835 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const LayoutRect& r, bool shouldClipToLayer) const
836 {
837     if (r.isEmpty())
838         return;
839
840     if (!repaintContainer)
841         repaintContainer = &view();
842
843     if (is<RenderFlowThread>(*repaintContainer)) {
844         downcast<RenderFlowThread>(*repaintContainer).repaintRectangleInRegions(r);
845         return;
846     }
847
848     propagateRepaintToParentWithOutlineAutoIfNeeded(*repaintContainer, r);
849
850     if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
851         repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r);
852         return;
853     }
854
855     if (repaintContainer->isRenderView()) {
856         RenderView& view = this->view();
857         ASSERT(repaintContainer == &view);
858         bool viewHasCompositedLayer = view.isComposited();
859         if (!viewHasCompositedLayer || view.layer()->backing()->paintsIntoWindow()) {
860             LayoutRect rect = r;
861             if (viewHasCompositedLayer && view.layer()->transform())
862                 rect = LayoutRect(view.layer()->transform()->mapRect(snapRectToDevicePixels(rect, document().deviceScaleFactor())));
863             view.repaintViewRectangle(rect);
864             return;
865         }
866     }
867
868     if (view().usesCompositing()) {
869         ASSERT(repaintContainer->isComposited());
870         repaintContainer->layer()->setBackingNeedsRepaintInRect(r, shouldClipToLayer ? GraphicsLayer::ClipToLayer : GraphicsLayer::DoNotClipToLayer);
871     }
872 }
873
874 void RenderObject::repaint() const
875 {
876     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
877     if (!isRooted())
878         return;
879
880     const RenderView& view = this->view();
881     if (view.printing())
882         return;
883
884     RenderLayerModelObject* repaintContainer = containerForRepaint();
885     repaintUsingContainer(repaintContainer, clippedOverflowRectForRepaint(repaintContainer));
886 }
887
888 void RenderObject::repaintRectangle(const LayoutRect& r, bool shouldClipToLayer) const
889 {
890     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
891     if (!isRooted())
892         return;
893
894     const RenderView& view = this->view();
895     if (view.printing())
896         return;
897
898     LayoutRect dirtyRect(r);
899     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
900     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
901     dirtyRect.move(view.layoutDelta());
902
903     RenderLayerModelObject* repaintContainer = containerForRepaint();
904     repaintUsingContainer(repaintContainer, computeRectForRepaint(dirtyRect, repaintContainer), shouldClipToLayer);
905 }
906
907 void RenderObject::repaintSlowRepaintObject() const
908 {
909     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
910     if (!isRooted())
911         return;
912
913     const RenderView& view = this->view();
914     if (view.printing())
915         return;
916
917     const RenderLayerModelObject* repaintContainer = containerForRepaint();
918     if (!repaintContainer)
919         repaintContainer = &view;
920
921     bool shouldClipToLayer = true;
922     IntRect repaintRect;
923     // If this is the root background, we need to check if there is an extended background rect. If
924     // there is, then we should not allow painting to clip to the layer size.
925     if (isDocumentElementRenderer() || isBody()) {
926         shouldClipToLayer = !view.frameView().hasExtendedBackgroundRectForPainting();
927         repaintRect = snappedIntRect(view.backgroundRect());
928     } else
929         repaintRect = snappedIntRect(clippedOverflowRectForRepaint(repaintContainer));
930
931     repaintUsingContainer(repaintContainer, repaintRect, shouldClipToLayer);
932 }
933
934 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
935 {
936     return snappedIntRect(absoluteClippedOverflowRect());
937 }
938
939 bool RenderObject::hasSelfPaintingLayer() const
940 {
941     if (!hasLayer())
942         return false;
943     auto* layer = downcast<RenderLayerModelObject>(*this).layer();
944     if (!layer)
945         return false;
946     return layer->isSelfPaintingLayer();
947 }
948     
949 bool RenderObject::checkForRepaintDuringLayout() const
950 {
951     return !document().view()->needsFullRepaint() && everHadLayout() && !hasSelfPaintingLayer();
952 }
953
954 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
955 {
956     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
957     r.inflate(outlineWidth);
958     return r;
959 }
960
961 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
962 {
963     ASSERT_NOT_REACHED();
964     return LayoutRect();
965 }
966
967 LayoutRect RenderObject::computeRectForRepaint(const LayoutRect& rect, const RenderLayerModelObject* repaintContainer, RepaintContext context) const
968 {
969     if (repaintContainer == this)
970         return rect;
971
972     auto* parent = this->parent();
973     if (!parent)
974         return rect;
975
976     LayoutRect adjustedRect = rect;
977     if (parent->hasOverflowClip()) {
978         downcast<RenderBox>(*parent).applyCachedClipAndScrollOffsetForRepaint(adjustedRect);
979         if (adjustedRect.isEmpty())
980             return adjustedRect;
981     }
982     return parent->computeRectForRepaint(adjustedRect, repaintContainer, context);
983 }
984
985 FloatRect RenderObject::computeFloatRectForRepaint(const FloatRect&, const RenderLayerModelObject*, bool) const
986 {
987     ASSERT_NOT_REACHED();
988     return FloatRect();
989 }
990
991 #if ENABLE(TREE_DEBUGGING)
992
993 static void showRenderTreeLegend()
994 {
995     fprintf(stderr, "\n(B)lock/(I)nline/I(N)line-block, (R)elative/A(B)solute/Fi(X)ed/Stick(Y) positioned, (O)verflow clipping, (A)nonymous, (G)enerated, (F)loating, has(L)ayer, (C)omposited, (D)irty layout, Dirty (S)tyle\n");
996 }
997
998 void RenderObject::showNodeTreeForThis() const
999 {
1000     if (!node())
1001         return;
1002     node()->showTreeForThis();
1003 }
1004
1005 void RenderObject::showRenderTreeForThis() const
1006 {
1007     const WebCore::RenderObject* root = this;
1008     while (root->parent())
1009         root = root->parent();
1010     showRenderTreeLegend();
1011     root->showRenderSubTreeAndMark(this, 1);
1012 }
1013
1014 void RenderObject::showLineTreeForThis() const
1015 {
1016     if (!is<RenderBlockFlow>(*this))
1017         return;
1018     showRenderTreeLegend();
1019     showRenderObject(false, 1);
1020     downcast<RenderBlockFlow>(*this).showLineTreeAndMark(nullptr, 2);
1021 }
1022
1023 static const RenderFlowThread* flowThreadContainingBlockFromRenderer(const RenderObject* renderer)
1024 {
1025     if (!renderer)
1026         return nullptr;
1027
1028     if (renderer->flowThreadState() == RenderObject::NotInsideFlowThread)
1029         return nullptr;
1030
1031     if (is<RenderFlowThread>(*renderer))
1032         return downcast<RenderFlowThread>(renderer);
1033
1034     if (is<RenderBlock>(*renderer))
1035         return downcast<RenderBlock>(*renderer).cachedFlowThreadContainingBlock();
1036
1037     return nullptr;
1038 }
1039
1040 void RenderObject::showRegionsInformation() const
1041 {
1042     const RenderFlowThread* ftcb = flowThreadContainingBlockFromRenderer(this);
1043
1044     if (!ftcb) {
1045         // Only the boxes have region range information.
1046         // Try to get the flow thread containing block information
1047         // from the containing block of this box.
1048         if (is<RenderBox>(*this))
1049             ftcb = flowThreadContainingBlockFromRenderer(containingBlock());
1050     }
1051
1052     if (!ftcb)
1053         return;
1054
1055     RenderRegion* startRegion = nullptr;
1056     RenderRegion* endRegion = nullptr;
1057     ftcb->getRegionRangeForBox(downcast<RenderBox>(this), startRegion, endRegion);
1058     fprintf(stderr, " [Rs:%p Re:%p]", startRegion, endRegion);
1059 }
1060
1061 void RenderObject::showRenderObject(bool mark, int depth) const
1062 {
1063     if (isInlineBlockOrInlineTable())
1064         fputc('N', stderr);
1065     else if (isInline())
1066         fputc('I', stderr);
1067     else
1068         fputc('B', stderr);
1069     
1070     if (isPositioned()) {
1071         if (isRelPositioned())
1072             fputc('R', stderr);
1073         else if (isStickyPositioned())
1074             fputc('Y', stderr);
1075         else if (isOutOfFlowPositioned()) {
1076             if (style().position() == AbsolutePosition)
1077                 fputc('B', stderr);
1078             else
1079                 fputc('X', stderr);
1080         }
1081     } else
1082         fputc('-', stderr);
1083
1084     if (hasOverflowClip())
1085         fputc('O', stderr);
1086     else
1087         fputc('-', stderr);
1088
1089     if (isAnonymous())
1090         fputc('A', stderr);
1091     else
1092         fputc('-', stderr);
1093
1094     if (isPseudoElement() || isAnonymous())
1095         fputc('G', stderr);
1096     else
1097         fputc('-', stderr);
1098
1099     if (isFloating())
1100         fputc('F', stderr);
1101     else
1102         fputc('-', stderr);
1103
1104     if (hasLayer())
1105         fputc('L', stderr);
1106     else
1107         fputc('-', stderr);
1108
1109     if (isComposited())
1110         fputc('C', stderr);
1111     else
1112         fputc('-', stderr);
1113
1114     fputc(' ', stderr);
1115
1116     if (needsLayout())
1117         fputc('D', stderr);
1118     else
1119         fputc('-', stderr);
1120
1121     if (node() && node()->needsStyleRecalc())
1122         fputc('S', stderr);
1123     else
1124         fputc('-', stderr);
1125
1126     int printedCharacters = 0;
1127     if (mark) {
1128         fprintf(stderr, "*");
1129         ++printedCharacters;
1130     }
1131
1132     while (++printedCharacters <= depth * 2)
1133         fputc(' ', stderr);
1134
1135     if (node())
1136         fprintf(stderr, "%s ", node()->nodeName().utf8().data());
1137
1138     String name = renderName();
1139     // FIXME: Renderer's name should not include property value listing.
1140     int pos = name.find('(');
1141     if (pos > 0)
1142         fprintf(stderr, "%s", name.left(pos - 1).utf8().data());
1143     else
1144         fprintf(stderr, "%s", name.utf8().data());
1145
1146     if (is<RenderBox>(*this)) {
1147         FloatRect boxRect = downcast<RenderBox>(*this).frameRect();
1148         fprintf(stderr, "  (%.2f, %.2f) (%.2f, %.2f)", boxRect.x(), boxRect.y(), boxRect.width(), boxRect.height());
1149     } else if (is<RenderInline>(*this) && isInFlowPositioned()) {
1150         FloatSize inlineOffset = downcast<RenderInline>(*this).offsetForInFlowPosition();
1151         fprintf(stderr, "  (%.2f, %.2f)", inlineOffset.width(), inlineOffset.height());
1152     }
1153
1154     fprintf(stderr, " renderer->(%p)", this);
1155     if (node()) {
1156         fprintf(stderr, " node->(%p)", node());
1157         if (node()->isTextNode()) {
1158             String value = node()->nodeValue();
1159             fprintf(stderr, " length->(%u)", value.length());
1160
1161             value.replaceWithLiteral('\\', "\\\\");
1162             value.replaceWithLiteral('\n', "\\n");
1163             
1164             const int maxPrintedLength = 80;
1165             if (value.length() > maxPrintedLength) {
1166                 String substring = value.substring(0, maxPrintedLength);
1167                 fprintf(stderr, " \"%s\"...", substring.utf8().data());
1168             } else
1169                 fprintf(stderr, " \"%s\"", value.utf8().data());
1170         }
1171     }
1172
1173     showRegionsInformation();
1174     fprintf(stderr, "\n");
1175 }
1176
1177 void RenderObject::showRenderSubTreeAndMark(const RenderObject* markedObject, int depth) const
1178 {
1179     showRenderObject(markedObject == this, depth);
1180     if (is<RenderBlockFlow>(*this))
1181         downcast<RenderBlockFlow>(*this).showLineTreeAndMark(nullptr, depth + 1);
1182
1183     for (const RenderObject* child = firstChildSlow(); child; child = child->nextSibling())
1184         child->showRenderSubTreeAndMark(markedObject, depth + 1);
1185 }
1186
1187 #endif // NDEBUG
1188
1189 SelectionSubtreeRoot& RenderObject::selectionRoot() const
1190 {
1191     RenderFlowThread* flowThread = flowThreadContainingBlock();
1192     if (!flowThread)
1193         return view();
1194
1195     if (is<RenderNamedFlowThread>(*flowThread))
1196         return downcast<RenderNamedFlowThread>(*flowThread);
1197     if (is<RenderMultiColumnFlowThread>(*flowThread)) {
1198         if (!flowThread->containingBlock())
1199             return view();
1200         return flowThread->containingBlock()->selectionRoot();
1201     }
1202     ASSERT_NOT_REACHED();
1203     return view();
1204 }
1205
1206 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1207 {
1208     selectionRoot().selectionData().selectionStartEndPositions(spos, epos);
1209 }
1210
1211 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode, bool* wasFixed) const
1212 {
1213     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1214     mapLocalToContainer(nullptr, transformState, mode | ApplyContainerFlip, wasFixed);
1215     transformState.flatten();
1216     
1217     return transformState.lastPlanarPoint();
1218 }
1219
1220 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
1221 {
1222     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1223     mapAbsoluteToLocalPoint(mode, transformState);
1224     transformState.flatten();
1225     
1226     return transformState.lastPlanarPoint();
1227 }
1228
1229 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
1230 {
1231     TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
1232     mapAbsoluteToLocalPoint(mode, transformState);
1233     transformState.flatten();
1234     return transformState.lastPlanarQuad();
1235 }
1236
1237 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1238 {
1239     if (repaintContainer == this)
1240         return;
1241
1242     auto* parent = this->parent();
1243     if (!parent)
1244         return;
1245
1246     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1247     LayoutPoint centerPoint(transformState.mappedPoint());
1248     if (mode & ApplyContainerFlip && is<RenderBox>(*parent)) {
1249         if (parent->style().isFlippedBlocksWritingMode())
1250             transformState.move(downcast<RenderBox>(parent)->flipForWritingMode(LayoutPoint(transformState.mappedPoint())) - centerPoint);
1251         mode &= ~ApplyContainerFlip;
1252     }
1253
1254     if (is<RenderBox>(*parent))
1255         transformState.move(-toLayoutSize(downcast<RenderBox>(*parent).scrollPosition()));
1256
1257     parent->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1258 }
1259
1260 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1261 {
1262     ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
1263
1264     auto* container = parent();
1265     if (!container)
1266         return nullptr;
1267
1268     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1269     LayoutSize offset;
1270     if (is<RenderBox>(*container))
1271         offset = -toLayoutSize(downcast<RenderBox>(*container).scrollPosition());
1272
1273     geometryMap.push(this, offset, false);
1274     
1275     return container;
1276 }
1277
1278 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1279 {
1280     if (auto* parent = this->parent()) {
1281         parent->mapAbsoluteToLocalPoint(mode, transformState);
1282         if (is<RenderBox>(*parent))
1283             transformState.move(toLayoutSize(downcast<RenderBox>(*parent).scrollPosition()));
1284     }
1285 }
1286
1287 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1288 {
1289 #if ENABLE(3D_TRANSFORMS)
1290     return hasTransform() || (containerObject && containerObject->style().hasPerspective());
1291 #else
1292     UNUSED_PARAM(containerObject);
1293     return hasTransform();
1294 #endif
1295 }
1296
1297 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
1298 {
1299     transform.makeIdentity();
1300     transform.translate(offsetInContainer.width(), offsetInContainer.height());
1301     RenderLayer* layer;
1302     if (hasLayer() && (layer = downcast<RenderLayerModelObject>(*this).layer()) && layer->transform())
1303         transform.multiply(layer->currentTransform());
1304     
1305 #if ENABLE(3D_TRANSFORMS)
1306     if (containerObject && containerObject->hasLayer() && containerObject->style().hasPerspective()) {
1307         // Perpsective on the container affects us, so we have to factor it in here.
1308         ASSERT(containerObject->hasLayer());
1309         FloatPoint perspectiveOrigin = downcast<RenderLayerModelObject>(*containerObject).layer()->perspectiveOrigin();
1310
1311         TransformationMatrix perspectiveMatrix;
1312         perspectiveMatrix.applyPerspective(containerObject->style().perspective());
1313         
1314         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1315         transform = perspectiveMatrix * transform;
1316         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1317     }
1318 #else
1319     UNUSED_PARAM(containerObject);
1320 #endif
1321 }
1322
1323 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1324 {
1325     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1326     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1327     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
1328     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
1329     transformState.flatten();
1330     
1331     return transformState.lastPlanarQuad();
1332 }
1333
1334 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1335 {
1336     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1337     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
1338     transformState.flatten();
1339
1340     return transformState.lastPlanarPoint();
1341 }
1342
1343 LayoutSize RenderObject::offsetFromContainer(RenderElement& container, const LayoutPoint&, bool* offsetDependsOnPoint) const
1344 {
1345     ASSERT(&container == this->container());
1346
1347     LayoutSize offset;
1348     if (is<RenderBox>(container))
1349         offset -= toLayoutSize(downcast<RenderBox>(container).scrollPosition());
1350
1351     if (offsetDependsOnPoint)
1352         *offsetDependsOnPoint = is<RenderFlowThread>(container);
1353
1354     return offset;
1355 }
1356
1357 LayoutSize RenderObject::offsetFromAncestorContainer(RenderElement& container) const
1358 {
1359     LayoutSize offset;
1360     LayoutPoint referencePoint;
1361     const RenderObject* currContainer = this;
1362     do {
1363         RenderElement* nextContainer = currContainer->container();
1364         ASSERT(nextContainer);  // This means we reached the top without finding container.
1365         if (!nextContainer)
1366             break;
1367         ASSERT(!currContainer->hasTransform());
1368         LayoutSize currentOffset = currContainer->offsetFromContainer(*nextContainer, referencePoint);
1369         offset += currentOffset;
1370         referencePoint.move(currentOffset);
1371         currContainer = nextContainer;
1372     } while (currContainer != &container);
1373
1374     return offset;
1375 }
1376
1377 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
1378 {
1379     if (extraWidthToEndOfLine)
1380         *extraWidthToEndOfLine = 0;
1381
1382     return LayoutRect();
1383 }
1384
1385 bool RenderObject::isRooted() const
1386 {
1387     return isDescendantOf(&view());
1388 }
1389
1390 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
1391 {
1392 #if USE(CG) || USE(CAIRO)
1393     // This can only be enabled for ports which honor the orientation flag in their drawing code.
1394     if (document().isImageDocument())
1395         return RespectImageOrientation;
1396 #endif
1397     // Respect the image's orientation if it's being used as a full-page image or it's
1398     // an <img> and the setting to respect it everywhere is set.
1399     return (frame().settings().shouldRespectImageOrientation() && is<HTMLImageElement>(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
1400 }
1401
1402 bool RenderObject::hasOutlineAnnotation() const
1403 {
1404     return node() && node()->isLink() && document().printing();
1405 }
1406
1407 bool RenderObject::hasEntirelyFixedBackground() const
1408 {
1409     return style().hasEntirelyFixedBackground();
1410 }
1411
1412 static inline RenderElement* containerForElement(const RenderObject& renderer, const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped)
1413 {
1414     // This method is extremely similar to containingBlock(), but with a few notable
1415     // exceptions.
1416     // (1) For normal flow elements, it just returns the parent.
1417     // (2) For absolute positioned elements, it will return a relative positioned inline, while
1418     // containingBlock() skips to the non-anonymous containing block.
1419     // This does mean that computePositionedLogicalWidth and computePositionedLogicalHeight have to use container().
1420     EPosition pos = renderer.style().position();
1421     auto* parent = renderer.parent();
1422     if (is<RenderText>(renderer) || (pos != FixedPosition && pos != AbsolutePosition))
1423         return parent;
1424     for (; parent && (pos == AbsolutePosition ? !parent->canContainAbsolutelyPositionedObjects() : !parent->canContainFixedPositionObjects()); parent = parent->parent()) {
1425         if (repaintContainerSkipped && repaintContainer == parent)
1426             *repaintContainerSkipped = true;
1427     }
1428     return parent;
1429 }
1430
1431 RenderElement* RenderObject::container() const
1432 {
1433     return containerForElement(*this, nullptr, nullptr);
1434 }
1435
1436 RenderElement* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool& repaintContainerSkipped) const
1437 {
1438     repaintContainerSkipped = false;
1439     return containerForElement(*this, repaintContainer, &repaintContainerSkipped);
1440 }
1441
1442 bool RenderObject::isSelectionBorder() const
1443 {
1444     SelectionState st = selectionState();
1445     return st == SelectionStart
1446         || st == SelectionEnd
1447         || st == SelectionBoth
1448         || view().selectionUnsplitStart() == this
1449         || view().selectionUnsplitEnd() == this;
1450 }
1451
1452 void RenderObject::willBeDestroyed()
1453 {
1454     // For accessibility management, notify the parent of the imminent change to its child set.
1455     // We do it now, before remove(), while the parent pointer is still available.
1456     if (AXObjectCache* cache = document().existingAXObjectCache())
1457         cache->childrenChanged(this->parent());
1458
1459     removeFromParent();
1460
1461     ASSERT(documentBeingDestroyed() || !is<RenderElement>(*this) || !view().frameView().hasSlowRepaintObject(downcast<RenderElement>(*this)));
1462
1463     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
1464     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
1465     if (AXObjectCache* cache = document().existingAXObjectCache())
1466         cache->remove(this);
1467
1468     // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
1469     // be moved into RenderBoxModelObject::destroy.
1470     if (hasLayer()) {
1471         setHasLayer(false);
1472         downcast<RenderLayerModelObject>(*this).destroyLayer();
1473     }
1474
1475     removeRareData();
1476 }
1477
1478 void RenderObject::insertedIntoTree()
1479 {
1480     // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
1481
1482     if (!isFloating() && parent()->childrenInline())
1483         parent()->dirtyLinesFromChangedChild(*this);
1484
1485     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1486         flowThread->flowThreadDescendantInserted(this);
1487 }
1488
1489 void RenderObject::willBeRemovedFromTree()
1490 {
1491     // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
1492
1493     removeFromRenderFlowThread();
1494
1495     // Update cached boundaries in SVG renderers, if a child is removed.
1496     parent()->setNeedsBoundariesUpdate();
1497 }
1498
1499 void RenderObject::removeFromRenderFlowThread()
1500 {
1501     if (flowThreadState() == NotInsideFlowThread)
1502         return;
1503
1504     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
1505     // It's only until later when we actually destroy it and remove all the children from it.
1506     // Currently, that happens for firstLetter elements and list markers.
1507     // Pass in the flow thread so that we don't have to look it up for all the children.
1508     removeFromRenderFlowThreadIncludingDescendants(true);
1509 }
1510
1511 void RenderObject::removeFromRenderFlowThreadIncludingDescendants(bool shouldUpdateState)
1512 {
1513     // Once we reach another flow thread we don't need to update the flow thread state
1514     // but we have to continue cleanup the flow thread info.
1515     if (isRenderFlowThread())
1516         shouldUpdateState = false;
1517
1518     if (is<RenderElement>(*this)) {
1519         for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this)))
1520             child.removeFromRenderFlowThreadIncludingDescendants(shouldUpdateState);
1521     }
1522
1523     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
1524     RenderFlowThread* flowThreadContainingBlock = this->flowThreadContainingBlock();
1525     while (flowThreadContainingBlock) {
1526         flowThreadContainingBlock->removeFlowChildInfo(this);
1527         if (flowThreadContainingBlock->flowThreadState() == NotInsideFlowThread)
1528             break;
1529         RenderObject* parent = flowThreadContainingBlock->parent();
1530         if (!parent)
1531             break;
1532         flowThreadContainingBlock = parent->flowThreadContainingBlock();
1533     }
1534     if (is<RenderBlock>(*this))
1535         downcast<RenderBlock>(*this).setCachedFlowThreadContainingBlockNeedsUpdate();
1536
1537     if (shouldUpdateState)
1538         setFlowThreadState(NotInsideFlowThread);
1539 }
1540
1541 void RenderObject::invalidateFlowThreadContainingBlockIncludingDescendants(RenderFlowThread* flowThread)
1542 {
1543     if (flowThreadState() == NotInsideFlowThread)
1544         return;
1545
1546     if (is<RenderBlock>(*this)) {
1547         RenderBlock& block = downcast<RenderBlock>(*this);
1548
1549         if (block.cachedFlowThreadContainingBlockNeedsUpdate())
1550             return;
1551
1552         flowThread = block.cachedFlowThreadContainingBlock();
1553         block.setCachedFlowThreadContainingBlockNeedsUpdate();
1554     }
1555
1556     if (flowThread)
1557         flowThread->removeFlowChildInfo(this);
1558
1559     if (!is<RenderElement>(*this))
1560         return;
1561
1562     for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this)))
1563         child.invalidateFlowThreadContainingBlockIncludingDescendants(flowThread);
1564 }
1565
1566 static void collapseAnonymousTableRowsIfNeeded(const RenderObject& rendererToBeDestroyed)
1567 {
1568     if (!is<RenderTableRow>(rendererToBeDestroyed))
1569         return;
1570
1571     auto& rowToBeDestroyed = downcast<RenderTableRow>(rendererToBeDestroyed);
1572     auto* section = downcast<RenderTableSection>(rowToBeDestroyed.parent());
1573     if (!section)
1574         return;
1575
1576     // All siblings generated?
1577     for (auto* current = section->firstRow(); current; current = current->nextRow()) {
1578         if (current == &rendererToBeDestroyed)
1579             continue;
1580         if (!current->isAnonymous())
1581             return;
1582     }
1583
1584     RenderTableRow* rowToInsertInto = nullptr;
1585     auto* currentRow = section->firstRow();
1586     while (currentRow) {
1587         if (currentRow == &rendererToBeDestroyed) {
1588             currentRow = currentRow->nextRow();
1589             continue;
1590         }
1591         if (!rowToInsertInto) {
1592             rowToInsertInto = currentRow;
1593             currentRow = currentRow->nextRow();
1594             continue;
1595         }
1596         currentRow->moveAllChildrenTo(rowToInsertInto);
1597         auto* destroyThis = currentRow;
1598         currentRow = currentRow->nextRow();
1599         destroyThis->destroy();
1600     }
1601     if (rowToInsertInto)
1602         rowToInsertInto->setNeedsLayout();
1603 }
1604
1605 void RenderObject::destroyAndCleanupAnonymousWrappers()
1606 {
1607     // If the tree is destroyed, there is no need for a clean-up phase.
1608     if (documentBeingDestroyed()) {
1609         destroy();
1610         return;
1611     }
1612
1613     auto* destroyRoot = this;
1614     auto* destroyRootParent = destroyRoot->parent();
1615     while (destroyRootParent && destroyRootParent->isAnonymous()) {
1616         if (!destroyRootParent->isTableCell() && !destroyRootParent->isTableRow()
1617             && !destroyRootParent->isTableCaption() && !destroyRootParent->isTableSection() && !destroyRootParent->isTable())
1618             break;
1619         // single child?
1620         if (!(destroyRootParent->firstChild() == destroyRoot && destroyRootParent->lastChild() == destroyRoot))
1621             break;
1622         destroyRoot = destroyRootParent;
1623         destroyRootParent = destroyRootParent->parent();
1624     }
1625     collapseAnonymousTableRowsIfNeeded(*destroyRoot);
1626     destroyRoot->destroy();
1627     // WARNING: |this| is deleted here.
1628 }
1629
1630 void RenderObject::destroy()
1631 {
1632     m_bitfields.setBeingDestroyed(true);
1633
1634 #if PLATFORM(IOS)
1635     if (hasLayer())
1636         downcast<RenderBoxModelObject>(*this).layer()->willBeDestroyed();
1637 #endif
1638
1639     willBeDestroyed();
1640     if (is<RenderWidget>(*this)) {
1641         downcast<RenderWidget>(*this).deref();
1642         return;
1643     }
1644     delete this;
1645 }
1646
1647 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&, const RenderRegion*)
1648 {
1649     return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
1650 }
1651
1652 void RenderObject::updateDragState(bool dragOn)
1653 {
1654     bool valueChanged = (dragOn != isDragging());
1655     setIsDragging(dragOn);
1656     if (valueChanged && node() && (style().affectedByDrag() || (is<Element>(*node()) && downcast<Element>(*node()).childrenAffectedByDrag())))
1657         node()->setNeedsStyleRecalc();
1658
1659     if (!is<RenderElement>(*this))
1660         return;
1661
1662     for (auto& child : childrenOfType<RenderObject>(downcast<RenderElement>(*this)))
1663         child.updateDragState(dragOn);
1664 }
1665
1666 bool RenderObject::isComposited() const
1667 {
1668     return hasLayer() && downcast<RenderLayerModelObject>(*this).layer()->isComposited();
1669 }
1670
1671 bool RenderObject::isAnonymousInlineBlock() const
1672 {
1673     return isAnonymous() && style().display() == INLINE_BLOCK && style().styleType() == NOPSEUDO && isRenderBlockFlow() && !isRubyRun() && !isRubyBase() && !isRuby(parent());
1674 }
1675
1676 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
1677 {
1678     bool inside = false;
1679     if (hitTestFilter != HitTestSelf) {
1680         // First test the foreground layer (lines and inlines).
1681         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
1682
1683         // Test floats next.
1684         if (!inside)
1685             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
1686
1687         // Finally test to see if the mouse is in the background (within a child block's background).
1688         if (!inside)
1689             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
1690     }
1691
1692     // See if the mouse is inside us but not any of our descendants
1693     if (hitTestFilter != HitTestDescendants && !inside)
1694         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
1695
1696     return inside;
1697 }
1698
1699 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
1700 {
1701     if (result.innerNode())
1702         return;
1703
1704     Node* node = this->node();
1705
1706     // If we hit the anonymous renderers inside generated content we should
1707     // actually hit the generated content so walk up to the PseudoElement.
1708     if (!node && parent() && parent()->isBeforeOrAfterContent()) {
1709         for (auto* renderer = parent(); renderer && !node; renderer = renderer->parent())
1710             node = renderer->element();
1711     }
1712
1713     if (node) {
1714         result.setInnerNode(node);
1715         if (!result.innerNonSharedNode())
1716             result.setInnerNonSharedNode(node);
1717         result.setLocalPoint(point);
1718     }
1719 }
1720
1721 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
1722 {
1723     return false;
1724 }
1725
1726 int RenderObject::innerLineHeight() const
1727 {
1728     return style().computedLineHeight();
1729 }
1730
1731 static Color decorationColor(const RenderStyle* style)
1732 {
1733     Color result;
1734     // Check for text decoration color first.
1735     result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
1736     if (result.isValid())
1737         return result;
1738     if (style->textStrokeWidth() > 0) {
1739         // Prefer stroke color if possible but not if it's fully transparent.
1740         result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
1741         if (result.alpha())
1742             return result;
1743     }
1744     
1745     result = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
1746     return result;
1747 }
1748
1749 void RenderObject::getTextDecorationColorsAndStyles(int decorations, Color& underlineColor, Color& overlineColor, Color& linethroughColor,
1750     TextDecorationStyle& underlineStyle, TextDecorationStyle& overlineStyle, TextDecorationStyle& linethroughStyle, bool firstlineStyle) const
1751 {
1752     const RenderObject* current = this;
1753     const RenderStyle* styleToUse = nullptr;
1754     TextDecoration currDecs = TextDecorationNone;
1755     Color resultColor;
1756     do {
1757         styleToUse = firstlineStyle ? &current->firstLineStyle() : &current->style();
1758         currDecs = styleToUse->textDecoration();
1759         resultColor = decorationColor(styleToUse);
1760         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
1761         if (currDecs) {
1762             if (currDecs & TextDecorationUnderline) {
1763                 decorations &= ~TextDecorationUnderline;
1764                 underlineColor = resultColor;
1765                 underlineStyle = styleToUse->textDecorationStyle();
1766             }
1767             if (currDecs & TextDecorationOverline) {
1768                 decorations &= ~TextDecorationOverline;
1769                 overlineColor = resultColor;
1770                 overlineStyle = styleToUse->textDecorationStyle();
1771             }
1772             if (currDecs & TextDecorationLineThrough) {
1773                 decorations &= ~TextDecorationLineThrough;
1774                 linethroughColor = resultColor;
1775                 linethroughStyle = styleToUse->textDecorationStyle();
1776             }
1777         }
1778         if (current->isRubyText())
1779             return;
1780         current = current->parent();
1781         if (current && current->isAnonymousBlock() && downcast<RenderBlock>(*current).continuation())
1782             current = downcast<RenderBlock>(*current).continuation();
1783     } while (current && decorations && (!current->node() || (!is<HTMLAnchorElement>(*current->node()) && !current->node()->hasTagName(fontTag))));
1784
1785     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
1786     if (decorations && current) {
1787         styleToUse = firstlineStyle ? &current->firstLineStyle() : &current->style();
1788         resultColor = decorationColor(styleToUse);
1789         if (decorations & TextDecorationUnderline) {
1790             underlineColor = resultColor;
1791             underlineStyle = styleToUse->textDecorationStyle();
1792         }
1793         if (decorations & TextDecorationOverline) {
1794             overlineColor = resultColor;
1795             overlineStyle = styleToUse->textDecorationStyle();
1796         }
1797         if (decorations & TextDecorationLineThrough) {
1798             linethroughColor = resultColor;
1799             linethroughStyle = styleToUse->textDecorationStyle();
1800         }
1801     }
1802 }
1803
1804 #if ENABLE(DASHBOARD_SUPPORT)
1805 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
1806 {
1807     // Convert the style regions to absolute coordinates.
1808     if (style().visibility() != VISIBLE || !is<RenderBox>(*this))
1809         return;
1810     
1811     auto& box = downcast<RenderBox>(*this);
1812     FloatPoint absPos = localToAbsolute();
1813
1814     const Vector<StyleDashboardRegion>& styleRegions = style().dashboardRegions();
1815     for (const auto& styleRegion : styleRegions) {
1816         LayoutUnit w = box.width();
1817         LayoutUnit h = box.height();
1818
1819         AnnotatedRegionValue region;
1820         region.label = styleRegion.label;
1821         region.bounds = LayoutRect(styleRegion.offset.left().value(),
1822                                    styleRegion.offset.top().value(),
1823                                    w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
1824                                    h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
1825         region.type = styleRegion.type;
1826
1827         region.clip = region.bounds;
1828         computeAbsoluteRepaintRect(region.clip);
1829         if (region.clip.height() < 0) {
1830             region.clip.setHeight(0);
1831             region.clip.setWidth(0);
1832         }
1833
1834         region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
1835         region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
1836
1837         regions.append(region);
1838     }
1839 }
1840
1841 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
1842 {
1843     // RenderTexts don't have their own style, they just use their parent's style,
1844     // so we don't want to include them.
1845     if (is<RenderText>(*this))
1846         return;
1847
1848     addAnnotatedRegions(regions);
1849     for (RenderObject* current = downcast<RenderElement>(*this).firstChild(); current; current = current->nextSibling())
1850         current->collectAnnotatedRegions(regions);
1851 }
1852 #endif
1853
1854 int RenderObject::caretMinOffset() const
1855 {
1856     return 0;
1857 }
1858
1859 int RenderObject::caretMaxOffset() const
1860 {
1861     if (isReplaced())
1862         return node() ? std::max(1U, node()->countChildNodes()) : 1;
1863     if (isHR())
1864         return 1;
1865     return 0;
1866 }
1867
1868 int RenderObject::previousOffset(int current) const
1869 {
1870     return current - 1;
1871 }
1872
1873 int RenderObject::previousOffsetForBackwardDeletion(int current) const
1874 {
1875     return current - 1;
1876 }
1877
1878 int RenderObject::nextOffset(int current) const
1879 {
1880     return current + 1;
1881 }
1882
1883 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
1884 {
1885     LayoutUnit outlineSize = outlineStyleForRepaint().outlineSize();
1886     if (const ShadowData* boxShadow = style().boxShadow()) {
1887         boxShadow->adjustRectForShadow(rect, outlineSize);
1888         return;
1889     }
1890     rect.inflate(outlineSize);
1891 }
1892
1893 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
1894 {
1895     imageChanged(static_cast<WrappedImagePtr>(image), rect);
1896 }
1897
1898 RenderBoxModelObject* RenderObject::offsetParent() const
1899 {
1900     // If any of the following holds true return null and stop this algorithm:
1901     // A is the root element.
1902     // A is the HTML body element.
1903     // The computed value of the position property for element A is fixed.
1904     if (isDocumentElementRenderer() || isBody() || (isOutOfFlowPositioned() && style().position() == FixedPosition))
1905         return nullptr;
1906
1907     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
1908     // chain return the nearest ancestor map HTML element and stop this algorithm.
1909     // FIXME: Implement!
1910     
1911     // Return the nearest ancestor element of A for which at least one of the following is
1912     // true and stop this algorithm if such an ancestor is found:
1913     //     * The computed value of the position property is not static.
1914     //     * It is the HTML body element.
1915     //     * The computed value of the position property of A is static and the ancestor
1916     //       is one of the following HTML elements: td, th, or table.
1917     //     * Our own extension: if there is a difference in the effective zoom
1918
1919     bool skipTables = isPositioned();
1920     float currZoom = style().effectiveZoom();
1921     auto current = parent();
1922     while (current && (!current->element() || (!current->isPositioned() && !current->isBody())) && !is<RenderNamedFlowThread>(*current)) {
1923         Element* element = current->element();
1924         if (!skipTables && element && (is<HTMLTableElement>(*element) || is<HTMLTableCellElement>(*element)))
1925             break;
1926  
1927         float newZoom = current->style().effectiveZoom();
1928         if (currZoom != newZoom)
1929             break;
1930         currZoom = newZoom;
1931         current = current->parent();
1932     }
1933     
1934     // CSS regions specification says that region flows should return the body element as their offsetParent.
1935     if (is<RenderNamedFlowThread>(current)) {
1936         auto* body = document().bodyOrFrameset();
1937         current = body ? body->renderer() : nullptr;
1938     }
1939     
1940     return is<RenderBoxModelObject>(current) ? downcast<RenderBoxModelObject>(current) : nullptr;
1941 }
1942
1943 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity) const
1944 {
1945     // If this is a non-anonymous renderer in an editable area, then it's simple.
1946     if (Node* node = nonPseudoNode()) {
1947         if (!node->hasEditableStyle()) {
1948             // If it can be found, we prefer a visually equivalent position that is editable. 
1949             Position position = createLegacyEditingPosition(node, offset);
1950             Position candidate = position.downstream(CanCrossEditingBoundary);
1951             if (candidate.deprecatedNode()->hasEditableStyle())
1952                 return VisiblePosition(candidate, affinity);
1953             candidate = position.upstream(CanCrossEditingBoundary);
1954             if (candidate.deprecatedNode()->hasEditableStyle())
1955                 return VisiblePosition(candidate, affinity);
1956         }
1957         // FIXME: Eliminate legacy editing positions
1958         return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
1959     }
1960
1961     // We don't want to cross the boundary between editable and non-editable
1962     // regions of the document, but that is either impossible or at least
1963     // extremely unlikely in any normal case because we stop as soon as we
1964     // find a single non-anonymous renderer.
1965
1966     // Find a nearby non-anonymous renderer.
1967     const RenderObject* child = this;
1968     while (const auto parent = child->parent()) {
1969         // Find non-anonymous content after.
1970         const RenderObject* renderer = child;
1971         while ((renderer = renderer->nextInPreOrder(parent))) {
1972             if (Node* node = renderer->nonPseudoNode())
1973                 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
1974         }
1975
1976         // Find non-anonymous content before.
1977         renderer = child;
1978         while ((renderer = renderer->previousInPreOrder())) {
1979             if (renderer == parent)
1980                 break;
1981             if (Node* node = renderer->nonPseudoNode())
1982                 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
1983         }
1984
1985         // Use the parent itself unless it too is anonymous.
1986         if (Element* element = parent->nonPseudoElement())
1987             return VisiblePosition(firstPositionInOrBeforeNode(element), DOWNSTREAM);
1988
1989         // Repeat at the next level up.
1990         child = parent;
1991     }
1992
1993     // Everything was anonymous. Give up.
1994     return VisiblePosition();
1995 }
1996
1997 VisiblePosition RenderObject::createVisiblePosition(const Position& position) const
1998 {
1999     if (position.isNotNull())
2000         return VisiblePosition(position);
2001
2002     ASSERT(!node());
2003     return createVisiblePosition(0, DOWNSTREAM);
2004 }
2005
2006 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
2007 {
2008     return SetCursorBasedOnStyle;
2009 }
2010
2011 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
2012 {
2013     if (needsLayout())
2014         return false;
2015
2016     RenderBlock* containingBlock = this->containingBlock();
2017     return containingBlock ? !containingBlock->needsLayout() : true;
2018 }
2019
2020 // We only create "generated" child renderers like one for first-letter if:
2021 // - the firstLetterBlock can have children in the DOM and
2022 // - the block doesn't have any special assumption on its text children.
2023 // This correctly prevents form controls from having such renderers.
2024 bool RenderObject::canHaveGeneratedChildren() const
2025 {
2026     return canHaveChildren();
2027 }
2028
2029 Node* RenderObject::generatingPseudoHostElement() const
2030 {
2031     return downcast<PseudoElement>(*node()).hostElement();
2032 }
2033
2034 void RenderObject::setNeedsBoundariesUpdate()
2035 {
2036     if (auto renderer = parent())
2037         renderer->setNeedsBoundariesUpdate();
2038 }
2039
2040 FloatRect RenderObject::objectBoundingBox() const
2041 {
2042     ASSERT_NOT_REACHED();
2043     return FloatRect();
2044 }
2045
2046 FloatRect RenderObject::strokeBoundingBox() const
2047 {
2048     ASSERT_NOT_REACHED();
2049     return FloatRect();
2050 }
2051
2052 // Returns the smallest rectangle enclosing all of the painted content
2053 // respecting clipping, masking, filters, opacity, stroke-width and markers
2054 FloatRect RenderObject::repaintRectInLocalCoordinates() const
2055 {
2056     ASSERT_NOT_REACHED();
2057     return FloatRect();
2058 }
2059
2060 AffineTransform RenderObject::localTransform() const
2061 {
2062     static const AffineTransform identity;
2063     return identity;
2064 }
2065
2066 const AffineTransform& RenderObject::localToParentTransform() const
2067 {
2068     static const AffineTransform identity;
2069     return identity;
2070 }
2071
2072 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2073 {
2074     ASSERT_NOT_REACHED();
2075     return false;
2076 }
2077
2078 RenderNamedFlowFragment* RenderObject::currentRenderNamedFlowFragment() const
2079 {
2080     RenderFlowThread* flowThread = flowThreadContainingBlock();
2081     if (!is<RenderNamedFlowThread>(flowThread))
2082         return nullptr;
2083
2084     // FIXME: Once regions are fully integrated with the compositing system we should uncomment this assert.
2085     // This assert needs to be disabled because it's possible to ask for the ancestor clipping rectangle of
2086     // a layer without knowing the containing region in advance.
2087     // ASSERT(flowThread->currentRegion() && flowThread->currentRegion()->isRenderNamedFlowFragment());
2088
2089     return downcast<RenderNamedFlowFragment>(flowThread->currentRegion());
2090 }
2091
2092 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
2093 {
2094     RenderBlock* containingBlock = this->containingBlock();
2095     return containingBlock ? containingBlock->flowThreadContainingBlock() : nullptr;
2096 }
2097
2098 void RenderObject::calculateBorderStyleColor(const EBorderStyle& style, const BoxSide& side, Color& color)
2099 {
2100     ASSERT(style == INSET || style == OUTSET);
2101     // This values were derived empirically.
2102     const RGBA32 baseDarkColor = 0xFF202020;
2103     const RGBA32 baseLightColor = 0xFFEBEBEB;
2104     enum Operation { Darken, Lighten };
2105
2106     Operation operation = (side == BSTop || side == BSLeft) == (style == INSET) ? Darken : Lighten;
2107
2108     // Here we will darken the border decoration color when needed. This will yield a similar behavior as in FF.
2109     if (operation == Darken) {
2110         if (differenceSquared(color, Color::black) > differenceSquared(baseDarkColor, Color::black))
2111             color = color.dark();
2112     } else {
2113         if (differenceSquared(color, Color::white) > differenceSquared(baseLightColor, Color::white))
2114             color = color.light();
2115     }
2116 }
2117
2118 void RenderObject::setIsDragging(bool isDragging)
2119 {
2120     if (isDragging || hasRareData())
2121         ensureRareData().setIsDragging(isDragging);
2122 }
2123
2124 void RenderObject::setHasReflection(bool hasReflection)
2125 {
2126     if (hasReflection || hasRareData())
2127         ensureRareData().setHasReflection(hasReflection);
2128 }
2129
2130 void RenderObject::setIsRenderFlowThread(bool isFlowThread)
2131 {
2132     if (isFlowThread || hasRareData())
2133         ensureRareData().setIsRenderFlowThread(isFlowThread);
2134 }
2135
2136 void RenderObject::setHasOutlineAutoAncestor(bool hasOutlineAutoAncestor)
2137 {
2138     if (hasOutlineAutoAncestor || hasRareData())
2139         ensureRareData().setHasOutlineAutoAncestor(hasOutlineAutoAncestor);
2140 }
2141
2142 void RenderObject::setIsRegisteredForVisibleInViewportCallback(bool registered)
2143 {
2144     if (registered || hasRareData())
2145         ensureRareData().setIsRegisteredForVisibleInViewportCallback(registered);
2146 }
2147
2148 void RenderObject::setVisibleInViewportState(VisibleInViewportState visible)
2149 {
2150     if (visible != VisibilityUnknown || hasRareData())
2151         ensureRareData().setVisibleInViewportState(visible);
2152 }
2153
2154 RenderObject::RareDataHash& RenderObject::rareDataMap()
2155 {
2156     static NeverDestroyed<RareDataHash> map;
2157     return map;
2158 }
2159
2160 RenderObject::RenderObjectRareData RenderObject::rareData() const
2161 {
2162     if (!hasRareData())
2163         return RenderObjectRareData();
2164
2165     return rareDataMap().get(this);
2166 }
2167
2168 RenderObject::RenderObjectRareData& RenderObject::ensureRareData()
2169 {
2170     setHasRareData(true);
2171     return rareDataMap().add(this, RenderObjectRareData()).iterator->value;
2172 }
2173
2174 void RenderObject::removeRareData()
2175 {
2176     rareDataMap().remove(this);
2177     setHasRareData(false);
2178 }
2179
2180 #if ENABLE(TREE_DEBUGGING)
2181
2182 void printRenderTreeForLiveDocuments()
2183 {
2184     for (const auto* document : Document::allDocuments()) {
2185         if (!document->renderView() || document->inPageCache())
2186             continue;
2187         if (document->frame() && document->frame()->isMainFrame())
2188             fprintf(stderr, "----------------------main frame--------------------------\n");
2189         fprintf(stderr, "%s", document->url().string().utf8().data());
2190         showRenderTree(document->renderView());
2191     }
2192 }
2193
2194 void printLayerTreeForLiveDocuments()
2195 {
2196     for (const auto* document : Document::allDocuments()) {
2197         if (!document->renderView() || document->inPageCache())
2198             continue;
2199         if (document->frame() && document->frame()->isMainFrame())
2200             fprintf(stderr, "----------------------main frame--------------------------\n");
2201         fprintf(stderr, "%s", document->url().string().utf8().data());
2202         showLayerTree(document->renderView());
2203     }
2204 }
2205
2206 #endif // ENABLE(TREE_DEBUGGING)
2207
2208 } // namespace WebCore
2209
2210 #if ENABLE(TREE_DEBUGGING)
2211
2212 void showNodeTree(const WebCore::RenderObject* object)
2213 {
2214     if (!object)
2215         return;
2216     object->showNodeTreeForThis();
2217 }
2218
2219 void showLineTree(const WebCore::RenderObject* object)
2220 {
2221     if (!object)
2222         return;
2223     object->showLineTreeForThis();
2224 }
2225
2226 void showRenderTree(const WebCore::RenderObject* object)
2227 {
2228     if (!object)
2229         return;
2230     object->showRenderTreeForThis();
2231 }
2232
2233 #endif