Add lineageOfType renderer iterator and start using it.
[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 "Frame.h"
36 #include "FrameSelection.h"
37 #include "FrameView.h"
38 #include "GraphicsContext.h"
39 #include "HTMLAnchorElement.h"
40 #include "HTMLElement.h"
41 #include "HTMLImageElement.h"
42 #include "HTMLNames.h"
43 #include "HTMLTableElement.h"
44 #include "HitTestResult.h"
45 #include "LogicalSelectionOffsetCaches.h"
46 #include "Page.h"
47 #include "PseudoElement.h"
48 #include "RenderCounter.h"
49 #include "RenderFlowThread.h"
50 #include "RenderGeometryMap.h"
51 #include "RenderInline.h"
52 #include "RenderIterator.h"
53 #include "RenderLayer.h"
54 #include "RenderLayerBacking.h"
55 #include "RenderNamedFlowThread.h"
56 #include "RenderScrollbarPart.h"
57 #include "RenderTheme.h"
58 #include "RenderView.h"
59 #include "Settings.h"
60 #include "StyleResolver.h"
61 #include "TransformState.h"
62 #include "htmlediting.h"
63 #include <algorithm>
64 #include <wtf/RefCountedLeakCounter.h>
65
66 #if ENABLE(SVG)
67 #include "RenderSVGResourceContainer.h"
68 #include "SVGRenderSupport.h"
69 #endif
70
71 #if PLATFORM(IOS)
72 #include "SelectionRect.h"
73 #endif
74
75 namespace WebCore {
76
77 using namespace HTMLNames;
78
79 #ifndef NDEBUG
80 RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject, bool isForbidden)
81     : m_renderObject(renderObject)
82     , m_preexistingForbidden(m_renderObject->isSetNeedsLayoutForbidden())
83 {
84     m_renderObject->setNeedsLayoutIsForbidden(isForbidden);
85 }
86
87 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
88 {
89     m_renderObject->setNeedsLayoutIsForbidden(m_preexistingForbidden);
90 }
91 #endif
92
93 struct SameSizeAsRenderObject {
94     virtual ~SameSizeAsRenderObject() { } // Allocate vtable pointer.
95     void* pointers[4];
96 #ifndef NDEBUG
97     unsigned m_debugBitfields : 2;
98 #endif
99     unsigned m_bitfields;
100 };
101
102 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
103
104 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
105
106 RenderObject::RenderObject(Node& node)
107     : CachedImageClient()
108     , m_node(node)
109     , m_parent(0)
110     , m_previous(0)
111     , m_next(0)
112 #ifndef NDEBUG
113     , m_hasAXObject(false)
114     , m_setNeedsLayoutForbidden(false)
115 #endif
116     , m_bitfields(node)
117 {
118     if (!node.isDocumentNode())
119         view().didCreateRenderer();
120 #ifndef NDEBUG
121     renderObjectCounter.increment();
122 #endif
123 }
124
125 RenderObject::~RenderObject()
126 {
127 #ifndef NDEBUG
128     ASSERT(!m_hasAXObject);
129     renderObjectCounter.decrement();
130 #endif
131     view().didDestroyRenderer();
132 }
133
134 RenderTheme& RenderObject::theme() const
135 {
136     ASSERT(document().page());
137     return document().page()->theme();
138 }
139
140 bool RenderObject::isDescendantOf(const RenderObject* obj) const
141 {
142     for (const RenderObject* r = this; r; r = r->m_parent) {
143         if (r == obj)
144             return true;
145     }
146     return false;
147 }
148
149 bool RenderObject::isLegend() const
150 {
151     return node() && node()->hasTagName(legendTag);
152 }
153
154 bool RenderObject::isHTMLMarquee() const
155 {
156     return node() && node()->renderer() == this && node()->hasTagName(marqueeTag);
157 }
158
159 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
160 {
161     setFlowThreadState(state);
162
163     for (RenderObject* child = firstChildSlow(); child; child = child->nextSibling()) {
164         // If the child is a fragmentation context it already updated the descendants flag accordingly.
165         if (child->isRenderFlowThread())
166             continue;
167         ASSERT(state != child->flowThreadState());
168         child->setFlowThreadStateIncludingDescendants(state);
169     }
170 }
171
172 void RenderObject::setParent(RenderElement* parent)
173 {
174     m_parent = parent;
175
176     // Only update if our flow thread state is different from our new parent and if we're not a RenderFlowThread.
177     // A RenderFlowThread is always considered to be inside itself, so it never has to change its state
178     // in response to parent changes.
179     FlowThreadState newState = parent ? parent->flowThreadState() : NotInsideFlowThread;
180     if (newState != flowThreadState() && !isRenderFlowThread())
181         setFlowThreadStateIncludingDescendants(newState);
182 }
183
184 void RenderObject::removeFromParent()
185 {
186     if (parent())
187         parent()->removeChild(*this);
188 }
189
190 RenderObject* RenderObject::nextInPreOrder() const
191 {
192     if (RenderObject* o = firstChildSlow())
193         return o;
194
195     return nextInPreOrderAfterChildren();
196 }
197
198 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
199 {
200     RenderObject* o;
201     if (!(o = nextSibling())) {
202         o = parent();
203         while (o && !o->nextSibling())
204             o = o->parent();
205         if (o)
206             o = o->nextSibling();
207     }
208
209     return o;
210 }
211
212 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
213 {
214     if (RenderObject* o = firstChildSlow())
215         return o;
216
217     return nextInPreOrderAfterChildren(stayWithin);
218 }
219
220 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
221 {
222     if (this == stayWithin)
223         return 0;
224
225     const RenderObject* current = this;
226     RenderObject* next;
227     while (!(next = current->nextSibling())) {
228         current = current->parent();
229         if (!current || current == stayWithin)
230             return 0;
231     }
232     return next;
233 }
234
235 RenderObject* RenderObject::previousInPreOrder() const
236 {
237     if (RenderObject* o = previousSibling()) {
238         while (RenderObject* last = o->lastChildSlow())
239             o = last;
240         return o;
241     }
242
243     return parent();
244 }
245
246 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
247 {
248     if (this == stayWithin)
249         return 0;
250
251     return previousInPreOrder();
252 }
253
254 RenderObject* RenderObject::childAt(unsigned index) const
255 {
256     RenderObject* child = firstChildSlow();
257     for (unsigned i = 0; child && i < index; i++)
258         child = child->nextSibling();
259     return child;
260 }
261
262 RenderObject* RenderObject::firstLeafChild() const
263 {
264     RenderObject* r = firstChildSlow();
265     while (r) {
266         RenderObject* n = 0;
267         n = r->firstChildSlow();
268         if (!n)
269             break;
270         r = n;
271     }
272     return r;
273 }
274
275 RenderObject* RenderObject::lastLeafChild() const
276 {
277     RenderObject* r = lastChildSlow();
278     while (r) {
279         RenderObject* n = 0;
280         n = r->lastChildSlow();
281         if (!n)
282             break;
283         r = n;
284     }
285     return r;
286 }
287
288 #if ENABLE(IOS_TEXT_AUTOSIZING)
289 // Inspired by Node::traverseNextNode.
290 RenderObject* RenderObject::traverseNext(const RenderObject* stayWithin) const
291 {
292     if (firstChild()) {
293         ASSERT(!stayWithin || firstChild()->isDescendantOf(stayWithin));
294         return firstChild();
295     }
296     if (this == stayWithin)
297         return 0;
298     if (nextSibling()) {
299         ASSERT(!stayWithin || nextSibling()->isDescendantOf(stayWithin));
300         return nextSibling();
301     }
302     const RenderObject* n = this;
303     while (n && !n->nextSibling() && (!stayWithin || n->parent() != stayWithin))
304         n = n->parent();
305     if (n) {
306         ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
307         return n->nextSibling();
308     }
309     return 0;
310 }
311
312 // Non-recursive version of the DFS search.
313 RenderObject* RenderObject::traverseNext(const RenderObject* stayWithin, HeightTypeTraverseNextInclusionFunction inclusionFunction, int& currentDepth, int& newFixedDepth) const
314 {
315     BlockContentHeightType overflowType;
316
317     // Check for suitable children.
318     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
319         overflowType = inclusionFunction(child);
320         if (overflowType != FixedHeight) {
321             currentDepth++;
322             if (overflowType == OverflowHeight)
323                 newFixedDepth = currentDepth;
324             ASSERT(!stayWithin || child->isDescendantOf(stayWithin));
325             return child;
326         }
327     }
328
329     if (this == stayWithin)
330         return 0;
331
332     // Now we traverse other nodes if they exist, otherwise
333     // we go to the parent node and try doing the same.
334     const RenderObject* n = this;
335     while (n) {
336         while (n && !n->nextSibling() && (!stayWithin || n->parent() != stayWithin)) {
337             n = n->parent();
338             currentDepth--;
339         }
340         if (!n)
341             return 0;
342         for (RenderObject* sibling = n->nextSibling(); sibling; sibling = sibling->nextSibling()) {
343             overflowType = inclusionFunction(sibling);
344             if (overflowType != FixedHeight) {
345                 if (overflowType == OverflowHeight)
346                     newFixedDepth = currentDepth;
347                 ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
348                 return sibling;
349             }
350         }
351         if (!stayWithin || n->parent() != stayWithin) {
352             n = n->parent();
353             currentDepth--;
354         } else
355             return 0;
356     }
357     return 0;
358 }
359
360 RenderObject* RenderObject::traverseNext(const RenderObject* stayWithin, TraverseNextInclusionFunction inclusionFunction) const
361 {
362     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
363         if (inclusionFunction(child)) {
364             ASSERT(!stayWithin || child->isDescendantOf(stayWithin));
365             return child;
366         }
367     }
368
369     if (this == stayWithin)
370         return 0;
371
372     for (RenderObject* sibling = nextSibling(); sibling; sibling = sibling->nextSibling()) {
373         if (inclusionFunction(sibling)) {
374             ASSERT(!stayWithin || sibling->isDescendantOf(stayWithin));
375             return sibling;
376         }
377     }
378
379     const RenderObject* n = this;
380     while (n) {
381         while (n && !n->nextSibling() && (!stayWithin || n->parent() != stayWithin))
382             n = n->parent();
383         if (n) {
384             for (RenderObject* sibling = n->nextSibling(); sibling; sibling = sibling->nextSibling()) {
385                 if (inclusionFunction(sibling)) {
386                     ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
387                     return sibling;
388                 }
389             }
390             if ((!stayWithin || n->parent() != stayWithin))
391                 n = n->parent();
392             else
393                 return 0;
394         }
395     }
396     return 0;
397 }
398
399 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject* render)
400 {
401     RenderStyle* style = render->style();
402     if (style) {
403         if (style->height().type() == Fixed) {
404             if (render->isRenderBlock()) {
405                 const RenderBlock* block = toRenderBlock(render);
406                 // For fixed height styles, if the overflow size of the element spills out of the specified
407                 // height, assume we can apply text auto-sizing.
408                 if (style->overflowY() == OVISIBLE && style->height().value() < block->layoutOverflowRect().maxY())
409                     return RenderObject::OverflowHeight;
410             }
411             return RenderObject::FixedHeight;
412         }
413     }
414     return RenderObject::FlexibleHeight;
415 }
416
417
418 void RenderObject::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
419 {
420     Document* document = view().frameView().frame().document();
421     if (!document)
422         return;
423
424     Vector<int> depthStack;
425     int currentDepth = 0;
426     int newFixedDepth = 0;
427
428     // We don't apply autosizing to nodes with fixed height normally.
429     // But we apply it to nodes which are located deep enough
430     // (nesting depth is greater than some const) inside of a parent block
431     // which has fixed height but its content overflows intentionally.
432     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
433         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
434             depthStack.remove(depthStack.size() - 1);
435         if (newFixedDepth)
436             depthStack.append(newFixedDepth);
437
438         int stackSize = depthStack.size();
439         if (descendent->isRenderBlock() && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
440             static_cast<RenderBlock*>(descendent)->adjustComputedFontSizes(size, visibleWidth);
441         newFixedDepth = 0;
442     }
443
444     // Remove style from auto-sizing table that are no longer valid.
445     document->validateAutoSizingNodes();
446 }
447
448 void RenderObject::resetTextAutosizing()
449 {
450     Document* document = view().frameView().frame().document();
451     if (!document)
452         return;
453
454     document->resetAutoSizingNodes();
455
456     Vector<int> depthStack;
457     int currentDepth = 0;
458     int newFixedDepth = 0;
459
460     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
461         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
462             depthStack.remove(depthStack.size() - 1);
463         if (newFixedDepth)
464             depthStack.append(newFixedDepth);
465
466         int stackSize = depthStack.size();
467         if (descendent->isRenderBlock() && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
468             toRenderBlock(descendent)->resetComputedFontSize();
469         newFixedDepth = 0;
470     }
471 }
472 #endif // ENABLE(IOS_TEXT_AUTOSIZING)
473
474 RenderLayer* RenderObject::enclosingLayer() const
475 {
476     for (auto& renderer : lineageOfType<RenderLayerModelObject>(*this)) {
477         if (renderer.layer())
478             return renderer.layer();
479     }
480     return nullptr;
481 }
482
483 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
484 {
485     RenderLayer* enclosingLayer = this->enclosingLayer();
486     if (!enclosingLayer)
487         return false;
488
489     enclosingLayer->scrollRectToVisible(rect, alignX, alignY);
490     return true;
491 }
492
493 RenderBox* RenderObject::enclosingBox() const
494 {
495     // FIXME: This should return a reference; it can always find the root RenderView.
496     return lineageOfType<RenderBox>(const_cast<RenderObject&>(*this)).first();
497 }
498
499 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
500 {
501     // FIXME: This should return a reference; it can always find the root RenderView.
502     return lineageOfType<RenderBoxModelObject>(const_cast<RenderObject&>(*this)).first();
503 }
504
505 bool RenderObject::fixedPositionedWithNamedFlowContainingBlock() const
506 {
507     return ((flowThreadState() == RenderObject::InsideOutOfFlowThread)
508         && (style().position() == FixedPosition)
509         && (containingBlock()->isOutOfFlowRenderFlowThread()));
510 }
511
512 static bool hasFixedPosInNamedFlowContainingBlock(const RenderObject* renderer)
513 {
514     ASSERT(renderer->flowThreadState() != RenderObject::NotInsideFlowThread);
515
516     RenderObject* curr = const_cast<RenderObject*>(renderer);
517     while (curr) {
518         if (curr->fixedPositionedWithNamedFlowContainingBlock())
519             return true;
520         curr = curr->containingBlock();
521     }
522
523     return false;
524 }
525
526 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
527 {
528     ASSERT(flowThreadState() != NotInsideFlowThread);
529
530     // See if we have the thread cached because we're in the middle of layout.
531     RenderFlowThread* flowThread = view().flowThreadController().currentRenderFlowThread();
532     if (flowThread)
533         return flowThread;
534     
535     // Not in the middle of layout so have to find the thread the slow way.
536     RenderObject* curr = const_cast<RenderObject*>(this);
537     while (curr) {
538         if (curr->isRenderFlowThread())
539             return toRenderFlowThread(curr);
540         curr = curr->containingBlock();
541     }
542     return 0;
543 }
544
545 RenderNamedFlowThread* RenderObject::renderNamedFlowThreadWrapper() const
546 {
547     RenderObject* object = const_cast<RenderObject*>(this);
548     while (object && object->isAnonymousBlock() && !object->isRenderNamedFlowThread())
549         object = object->parent();
550
551     return object && object->isRenderNamedFlowThread() ? toRenderNamedFlowThread(object) : 0;
552 }
553
554 RenderBlock* RenderObject::firstLineBlock() const
555 {
556     return 0;
557 }
558
559 static inline bool objectIsRelayoutBoundary(const RenderElement* object)
560 {
561     // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
562     if (object->isRenderView())
563         return true;
564
565     if (object->isTextControl())
566         return true;
567
568 #if ENABLE(SVG)
569     if (object->isSVGRoot())
570         return true;
571 #endif
572
573     if (!object->hasOverflowClip())
574         return false;
575
576     if (object->style().width().isIntrinsicOrAuto() || object->style().height().isIntrinsicOrAuto() || object->style().height().isPercent())
577         return false;
578
579     // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
580     if (object->isTablePart())
581         return false;
582
583     return true;
584 }
585
586 void RenderObject::clearNeedsLayout()
587 {
588     m_bitfields.setNeedsLayout(false);
589     setEverHadLayout(true);
590     setPosChildNeedsLayoutBit(false);
591     setNeedsSimplifiedNormalFlowLayoutBit(false);
592     setNormalChildNeedsLayoutBit(false);
593     setNeedsPositionedMovementLayoutBit(false);
594     if (isRenderElement())
595         toRenderElement(this)->setAncestorLineBoxDirty(false);
596 #ifndef NDEBUG
597     checkBlockPositionedObjectsNeedLayout();
598 #endif
599 }
600
601 static void scheduleRelayoutForSubtree(RenderElement& renderer)
602 {
603     if (!renderer.isRenderView()) {
604         if (!renderer.isRooted())
605             return;
606         renderer.view().frameView().scheduleRelayoutOfSubtree(renderer);
607         return;
608     }
609     toRenderView(renderer).frameView().scheduleRelayout();
610 }
611
612 void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderElement* newRoot)
613 {
614     ASSERT(!scheduleRelayout || !newRoot);
615     ASSERT(!isSetNeedsLayoutForbidden());
616
617     auto ancestor = container();
618
619     bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
620     bool hasOutOfFlowPosition = !isText() && style().hasOutOfFlowPosition();
621
622     while (ancestor) {
623 #ifndef NDEBUG
624         // FIXME: Remove this once we remove the special cases for counters, quotes and mathml
625         // calling setNeedsLayout during preferred width computation.
626         SetLayoutNeededForbiddenScope layoutForbiddenScope(ancestor, isSetNeedsLayoutForbidden());
627 #endif
628         // Don't mark the outermost object of an unrooted subtree. That object will be
629         // marked when the subtree is added to the document.
630         auto container = ancestor->container();
631         if (!container && !ancestor->isRenderView())
632             return;
633         if (hasOutOfFlowPosition) {
634             bool willSkipRelativelyPositionedInlines = !ancestor->isRenderBlock() || ancestor->isAnonymousBlock();
635             // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
636             while (ancestor && (!ancestor->isRenderBlock() || ancestor->isAnonymousBlock()))
637                 ancestor = ancestor->container();
638             if (!ancestor || ancestor->posChildNeedsLayout())
639                 return;
640             if (willSkipRelativelyPositionedInlines)
641                 container = ancestor->container();
642             ancestor->setPosChildNeedsLayoutBit(true);
643             simplifiedNormalFlowLayout = true;
644         } else if (simplifiedNormalFlowLayout) {
645             if (ancestor->needsSimplifiedNormalFlowLayout())
646                 return;
647             ancestor->setNeedsSimplifiedNormalFlowLayoutBit(true);
648         } else {
649             if (ancestor->normalChildNeedsLayout())
650                 return;
651             ancestor->setNormalChildNeedsLayoutBit(true);
652         }
653         ASSERT(!ancestor->isSetNeedsLayoutForbidden());
654
655         if (ancestor == newRoot)
656             return;
657
658         if (scheduleRelayout && objectIsRelayoutBoundary(ancestor))
659             break;
660
661         hasOutOfFlowPosition = ancestor->style().hasOutOfFlowPosition();
662         ancestor = container;
663     }
664
665     if (scheduleRelayout && ancestor)
666         scheduleRelayoutForSubtree(*ancestor);
667 }
668
669 #ifndef NDEBUG
670 void RenderObject::checkBlockPositionedObjectsNeedLayout()
671 {
672     ASSERT(!needsLayout());
673
674     if (isRenderBlock())
675         toRenderBlock(this)->checkPositionedObjectsNeedLayout();
676 }
677 #endif
678
679 void RenderObject::setPreferredLogicalWidthsDirty(bool shouldBeDirty, MarkingBehavior markParents)
680 {
681     bool alreadyDirty = preferredLogicalWidthsDirty();
682     m_bitfields.setPreferredLogicalWidthsDirty(shouldBeDirty);
683     if (shouldBeDirty && !alreadyDirty && markParents == MarkContainingBlockChain && (isText() || !style().hasOutOfFlowPosition()))
684         invalidateContainerPreferredLogicalWidths();
685 }
686
687 void RenderObject::invalidateContainerPreferredLogicalWidths()
688 {
689     // In order to avoid pathological behavior when inlines are deeply nested, we do include them
690     // in the chain that we mark dirty (even though they're kind of irrelevant).
691     auto o = isTableCell() ? containingBlock() : container();
692     while (o && !o->preferredLogicalWidthsDirty()) {
693         // Don't invalidate the outermost object of an unrooted subtree. That object will be 
694         // invalidated when the subtree is added to the document.
695         auto container = o->isTableCell() ? o->containingBlock() : o->container();
696         if (!container && !o->isRenderView())
697             break;
698
699         o->m_bitfields.setPreferredLogicalWidthsDirty(true);
700         if (o->style().hasOutOfFlowPosition())
701             // A positioned object has no effect on the min/max width of its containing block ever.
702             // We can optimize this case and not go up any further.
703             break;
704         o = container;
705     }
706 }
707
708 void RenderObject::setLayerNeedsFullRepaint()
709 {
710     ASSERT(hasLayer());
711     toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaint);
712 }
713
714 void RenderObject::setLayerNeedsFullRepaintForPositionedMovementLayout()
715 {
716     ASSERT(hasLayer());
717     toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
718 }
719
720 RenderBlock* RenderObject::containingBlock() const
721 {
722     auto o = parent();
723     if (!o && isRenderScrollbarPart())
724         o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
725
726     const RenderStyle& style = this->style();
727     if (!isText() && style.position() == FixedPosition)
728         o = containingBlockForFixedPosition(o);
729     else if (!isText() && style.position() == AbsolutePosition)
730         o = containingBlockForAbsolutePosition(o);
731     else
732         o = containingBlockForObjectInFlow(o);
733
734     if (!o || !o->isRenderBlock())
735         return 0; // This can still happen in case of an orphaned tree
736
737     return toRenderBlock(o);
738 }
739
740 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
741     BoxSide side, Color color, EBorderStyle borderStyle, int adjacentWidth1, int adjacentWidth2, bool antialias)
742 {
743     int thickness;
744     int length;
745     if (side == BSTop || side == BSBottom) {
746         thickness = y2 - y1;
747         length = x2 - x1;
748     } else {
749         thickness = x2 - x1;
750         length = y2 - y1;
751     }
752
753     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
754     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
755     if (!thickness || !length)
756         return;
757
758     if (borderStyle == DOUBLE && thickness < 3)
759         borderStyle = SOLID;
760
761     const RenderStyle& style = this->style();
762     switch (borderStyle) {
763         case BNONE:
764         case BHIDDEN:
765             return;
766         case DOTTED:
767         case DASHED: {
768             if (thickness > 0) {
769                 bool wasAntialiased = graphicsContext->shouldAntialias();
770                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
771                 graphicsContext->setShouldAntialias(antialias);
772                 graphicsContext->setStrokeColor(color, style.colorSpace());
773                 graphicsContext->setStrokeThickness(thickness);
774                 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
775
776                 switch (side) {
777                     case BSBottom:
778                     case BSTop:
779                         graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
780                         break;
781                     case BSRight:
782                     case BSLeft:
783                         graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
784                         break;
785                 }
786                 graphicsContext->setShouldAntialias(wasAntialiased);
787                 graphicsContext->setStrokeStyle(oldStrokeStyle);
788             }
789             break;
790         }
791         case DOUBLE: {
792             int thirdOfThickness = (thickness + 1) / 3;
793             ASSERT(thirdOfThickness);
794
795             if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
796                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
797                 graphicsContext->setStrokeStyle(NoStroke);
798                 graphicsContext->setFillColor(color, style.colorSpace());
799                 
800                 bool wasAntialiased = graphicsContext->shouldAntialias();
801                 graphicsContext->setShouldAntialias(antialias);
802
803                 switch (side) {
804                     case BSTop:
805                     case BSBottom:
806                         graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
807                         graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
808                         break;
809                     case BSLeft:
810                     case BSRight:
811                         // FIXME: Why do we offset the border by 1 in this case but not the other one?
812                         if (length > 1) {
813                             graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
814                             graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
815                         }
816                         break;
817                 }
818
819                 graphicsContext->setShouldAntialias(wasAntialiased);
820                 graphicsContext->setStrokeStyle(oldStrokeStyle);
821             } else {
822                 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
823                 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
824
825                 switch (side) {
826                     case BSTop:
827                         drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
828                                    y1, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
829                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
830                         drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
831                                    y2 - thirdOfThickness, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
832                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
833                         break;
834                     case BSLeft:
835                         drawLineForBoxSide(graphicsContext, x1, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
836                                    x1 + thirdOfThickness, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
837                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
838                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
839                                    x2, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
840                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
841                         break;
842                     case BSBottom:
843                         drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
844                                    y1, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
845                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
846                         drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
847                                    y2 - thirdOfThickness, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
848                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
849                         break;
850                     case BSRight:
851                         drawLineForBoxSide(graphicsContext, x1, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
852                                    x1 + thirdOfThickness, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
853                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
854                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
855                                    x2, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
856                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
857                         break;
858                     default:
859                         break;
860                 }
861             }
862             break;
863         }
864         case RIDGE:
865         case GROOVE: {
866             EBorderStyle s1;
867             EBorderStyle s2;
868             if (borderStyle == GROOVE) {
869                 s1 = INSET;
870                 s2 = OUTSET;
871             } else {
872                 s1 = OUTSET;
873                 s2 = INSET;
874             }
875
876             int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
877             int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
878
879             switch (side) {
880                 case BSTop:
881                     drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1, 0) / 2, y1, x2 - std::max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
882                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
883                     drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(adjacentWidth2 + 1, 0) / 2, y2,
884                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
885                     break;
886                 case BSLeft:
887                     drawLineForBoxSide(graphicsContext, x1, y1 + std::max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(-adjacentWidth2, 0) / 2,
888                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
889                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(adjacentWidth2 + 1, 0) / 2,
890                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
891                     break;
892                 case BSBottom:
893                     drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1, 0) / 2, y1, x2 - std::max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
894                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
895                     drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(-adjacentWidth2 + 1, 0) / 2, y2,
896                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
897                     break;
898                 case BSRight:
899                     drawLineForBoxSide(graphicsContext, x1, y1 + std::max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(adjacentWidth2, 0) / 2,
900                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
901                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(-adjacentWidth2 + 1, 0) / 2,
902                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
903                     break;
904             }
905             break;
906         }
907         case INSET:
908             // FIXME: Maybe we should lighten the colors on one side like Firefox.
909             // https://bugs.webkit.org/show_bug.cgi?id=58608
910             if (side == BSTop || side == BSLeft)
911                 color = color.dark();
912             // fall through
913         case OUTSET:
914             if (borderStyle == OUTSET && (side == BSBottom || side == BSRight))
915                 color = color.dark();
916             // fall through
917         case SOLID: {
918             StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
919             graphicsContext->setStrokeStyle(NoStroke);
920             graphicsContext->setFillColor(color, style.colorSpace());
921             ASSERT(x2 >= x1);
922             ASSERT(y2 >= y1);
923             if (!adjacentWidth1 && !adjacentWidth2) {
924                 // Turn off antialiasing to match the behavior of drawConvexPolygon();
925                 // this matters for rects in transformed contexts.
926                 bool wasAntialiased = graphicsContext->shouldAntialias();
927                 graphicsContext->setShouldAntialias(antialias);
928                 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
929                 graphicsContext->setShouldAntialias(wasAntialiased);
930                 graphicsContext->setStrokeStyle(oldStrokeStyle);
931                 return;
932             }
933             FloatPoint quad[4];
934             switch (side) {
935                 case BSTop:
936                     quad[0] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y1);
937                     quad[1] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y2);
938                     quad[2] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y2);
939                     quad[3] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y1);
940                     break;
941                 case BSBottom:
942                     quad[0] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y1);
943                     quad[1] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y2);
944                     quad[2] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y2);
945                     quad[3] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y1);
946                     break;
947                 case BSLeft:
948                     quad[0] = FloatPoint(x1, y1 + std::max(-adjacentWidth1, 0));
949                     quad[1] = FloatPoint(x1, y2 - std::max(-adjacentWidth2, 0));
950                     quad[2] = FloatPoint(x2, y2 - std::max(adjacentWidth2, 0));
951                     quad[3] = FloatPoint(x2, y1 + std::max(adjacentWidth1, 0));
952                     break;
953                 case BSRight:
954                     quad[0] = FloatPoint(x1, y1 + std::max(adjacentWidth1, 0));
955                     quad[1] = FloatPoint(x1, y2 - std::max(adjacentWidth2, 0));
956                     quad[2] = FloatPoint(x2, y2 - std::max(-adjacentWidth2, 0));
957                     quad[3] = FloatPoint(x2, y1 + std::max(-adjacentWidth1, 0));
958                     break;
959             }
960
961             graphicsContext->drawConvexPolygon(4, quad, antialias);
962             graphicsContext->setStrokeStyle(oldStrokeStyle);
963             break;
964         }
965     }
966 }
967
968 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
969 {
970     Vector<IntRect> focusRingRects;
971     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
972     if (style->outlineStyleIsAuto())
973         paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
974     else
975         addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
976 }
977
978 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
979 {
980     if (rect.isEmpty())
981         return;
982     Node* n = node();
983     if (!n || !n->isLink() || !n->isElementNode())
984         return;
985     const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
986     if (href.isNull())
987         return;
988     context->setURLForRect(n->document().completeURL(href), pixelSnappedIntRect(rect));
989 }
990
991 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
992 {
993     if (!hasOutline())
994         return;
995
996     RenderStyle& styleToUse = style();
997     LayoutUnit outlineWidth = styleToUse.outlineWidth();
998
999     int outlineOffset = styleToUse.outlineOffset();
1000
1001     if (styleToUse.outlineStyleIsAuto() || hasOutlineAnnotation()) {
1002         if (!theme().supportsFocusRing(&styleToUse)) {
1003             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1004             paintFocusRing(paintInfo, paintRect.location(), &styleToUse);
1005         }
1006     }
1007
1008     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
1009         return;
1010
1011     IntRect inner = pixelSnappedIntRect(paintRect);
1012     inner.inflate(outlineOffset);
1013
1014     IntRect outer = pixelSnappedIntRect(inner);
1015     outer.inflate(outlineWidth);
1016
1017     // FIXME: This prevents outlines from painting inside the object. See bug 12042
1018     if (outer.isEmpty())
1019         return;
1020
1021     EBorderStyle outlineStyle = styleToUse.outlineStyle();
1022     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
1023
1024     GraphicsContext* graphicsContext = paintInfo.context;
1025     bool useTransparencyLayer = outlineColor.hasAlpha();
1026     if (useTransparencyLayer) {
1027         if (outlineStyle == SOLID) {
1028             Path path;
1029             path.addRect(outer);
1030             path.addRect(inner);
1031             graphicsContext->setFillRule(RULE_EVENODD);
1032             graphicsContext->setFillColor(outlineColor, styleToUse.colorSpace());
1033             graphicsContext->fillPath(path);
1034             return;
1035         }
1036         graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1037         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1038     }
1039
1040     int leftOuter = outer.x();
1041     int leftInner = inner.x();
1042     int rightOuter = outer.maxX();
1043     int rightInner = inner.maxX();
1044     int topOuter = outer.y();
1045     int topInner = inner.y();
1046     int bottomOuter = outer.maxY();
1047     int bottomInner = inner.maxY();
1048     
1049     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1050     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1051     drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1052     drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1053
1054     if (useTransparencyLayer)
1055         graphicsContext->endTransparencyLayer();
1056 }
1057
1058 // FIXME: Make this return an unsigned integer?
1059 int RenderObject::columnNumberForOffset(int offset)
1060 {
1061     int columnNumber = 0;
1062     RenderBlock* containingBlock = this->containingBlock();
1063     RenderView& view = containingBlock->view();
1064     const Pagination& pagination = view.frameView().frame().page()->pagination();
1065     if (pagination.mode == Pagination::Unpaginated)
1066         return columnNumber;
1067
1068     ColumnInfo* columnInfo = view.columnInfo();
1069     if (columnInfo && columnInfo->progressionAxis() == ColumnInfo::BlockAxis) {
1070         if (!columnInfo->progressionIsReversed())
1071             columnNumber = (pagination.pageLength + pagination.gap - offset) / (pagination.pageLength + pagination.gap);
1072         else
1073             columnNumber = offset / (pagination.pageLength + pagination.gap);
1074     }
1075     return columnNumber;
1076 }
1077
1078 #if PLATFORM(IOS)
1079 // This function is similar in spirit to RenderText::absoluteRectsForRange, but returns rectangles
1080 // which are annotated with additional state which helps iOS draw selections in its unique way.
1081 // No annotations are added in this class.
1082 // FIXME: Move to RenderText with absoluteRectsForRange()?
1083 void RenderObject::collectSelectionRects(Vector<SelectionRect>& rects, unsigned start, unsigned end)
1084 {
1085     Vector<FloatQuad> quads;
1086
1087     if (!firstChildSlow()) {
1088         // FIXME: WebKit's position for an empty span after a BR is incorrect, so we can't trust 
1089         // quads for them. We don't need selection rects for those anyway though, since they 
1090         // are just empty containers. See <https://bugs.webkit.org/show_bug.cgi?id=49358>.
1091         RenderObject* previous = previousSibling();
1092         Node* node = this->node();
1093         if (!previous || !previous->isBR() || !node || !node->isContainerNode() || !isInline()) {
1094             // For inline elements we don't use absoluteQuads, since it takes into account continuations and leads to wrong results.
1095             absoluteQuadsForSelection(quads);
1096         }
1097     } else {
1098         unsigned offset = start;
1099         for (RenderObject* child = childAt(start); child && offset < end; child = child->nextSibling(), ++offset)
1100             child->absoluteQuads(quads);
1101     }
1102
1103     unsigned numberOfQuads = quads.size();
1104     for (unsigned i = 0; i < numberOfQuads; ++i)
1105         rects.append(SelectionRect(quads[i].enclosingBoundingBox(), isHorizontalWritingMode(), columnNumberForOffset(quads[i].enclosingBoundingBox().x())));
1106 }
1107 #endif
1108
1109 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms) const
1110 {
1111     if (useTransforms) {
1112         Vector<FloatQuad> quads;
1113         absoluteQuads(quads);
1114
1115         size_t n = quads.size();
1116         if (!n)
1117             return IntRect();
1118     
1119         IntRect result = quads[0].enclosingBoundingBox();
1120         for (size_t i = 1; i < n; ++i)
1121             result.unite(quads[i].enclosingBoundingBox());
1122         return result;
1123     }
1124
1125     FloatPoint absPos = localToAbsolute();
1126     Vector<IntRect> rects;
1127     absoluteRects(rects, flooredLayoutPoint(absPos));
1128
1129     size_t n = rects.size();
1130     if (!n)
1131         return IntRect();
1132
1133     LayoutRect result = rects[0];
1134     for (size_t i = 1; i < n; ++i)
1135         result.unite(rects[i]);
1136     return pixelSnappedIntRect(result);
1137 }
1138
1139 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1140 {
1141     Vector<IntRect> rects;
1142     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1143     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1144     // implicitly assumes that. This doesn't work correctly with transformed
1145     // descendants.
1146     FloatPoint absolutePoint = localToAbsolute();
1147     addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
1148     size_t count = rects.size();
1149     for (size_t i = 0; i < count; ++i) {
1150         IntRect rect = rects[i];
1151         rect.move(-absolutePoint.x(), -absolutePoint.y());
1152         quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1153     }
1154 }
1155
1156 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1157 {
1158     if (!range || !range->startContainer())
1159         return FloatRect();
1160
1161     range->ownerDocument().updateLayout();
1162
1163     Vector<FloatQuad> quads;
1164     range->textQuads(quads);
1165
1166     if (quads.isEmpty())
1167         return FloatRect();
1168
1169     FloatRect result = quads[0].boundingBox();
1170     for (size_t i = 1; i < quads.size(); ++i)
1171         result.uniteEvenIfEmpty(quads[i].boundingBox());
1172
1173     return result;
1174 }
1175
1176 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1177 {
1178     if (hasLayer())
1179         result.unite(absoluteBoundingBoxRectIgnoringTransforms());
1180     for (RenderObject* current = firstChildSlow(); current; current = current->nextSibling())
1181         current->addAbsoluteRectForLayer(result);
1182 }
1183
1184 // FIXME: change this to use the subtreePaint terminology
1185 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1186 {
1187     LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
1188     topLevelRect = result;
1189     for (RenderObject* current = firstChildSlow(); current; current = current->nextSibling())
1190         current->addAbsoluteRectForLayer(result);
1191     return result;
1192 }
1193
1194 RenderLayerModelObject* RenderObject::containerForRepaint() const
1195 {
1196     RenderLayerModelObject* repaintContainer = 0;
1197
1198 #if USE(ACCELERATED_COMPOSITING)
1199     if (view().usesCompositing()) {
1200         if (RenderLayer* parentLayer = enclosingLayer()) {
1201             RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
1202             if (compLayer)
1203                 repaintContainer = &compLayer->renderer();
1204         }
1205     }
1206 #endif
1207     
1208 #if ENABLE(CSS_FILTERS)
1209     if (view().hasSoftwareFilters()) {
1210         if (RenderLayer* parentLayer = enclosingLayer()) {
1211             RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
1212             if (enclosingFilterLayer)
1213                 return &enclosingFilterLayer->renderer();
1214         }
1215     }
1216 #endif
1217
1218     // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1219     // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1220     // repainting to do individual region repaints.
1221     RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
1222     if (parentRenderFlowThread) {
1223         // If the element has a fixed positioned element with named flow as CB along the CB chain
1224         // then the repaint container is not the flow thread.
1225         if (hasFixedPosInNamedFlowContainingBlock(this))
1226             return repaintContainer;
1227         // The ancestor document will do the reparenting when the repaint propagates further up.
1228         // We're just a seamless child document, and we don't need to do the hacking.
1229         if (parentRenderFlowThread && &parentRenderFlowThread->document() != &document())
1230             return repaintContainer;
1231         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
1232         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
1233         RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : 0;
1234         if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
1235             repaintContainer = parentRenderFlowThread;
1236     }
1237     return repaintContainer;
1238 }
1239
1240 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const IntRect& r, bool immediate) const
1241 {
1242     if (!repaintContainer) {
1243         view().repaintViewRectangle(r, immediate);
1244         return;
1245     }
1246
1247     if (repaintContainer->isRenderFlowThread()) {
1248         toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r, immediate);
1249         return;
1250     }
1251
1252 #if ENABLE(CSS_FILTERS)
1253     if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
1254         repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r, immediate);
1255         return;
1256     }
1257 #endif
1258
1259 #if USE(ACCELERATED_COMPOSITING)
1260     RenderView& v = view();
1261     if (repaintContainer->isRenderView()) {
1262         ASSERT(repaintContainer == &v);
1263         bool viewHasCompositedLayer = v.hasLayer() && v.layer()->isComposited();
1264         if (!viewHasCompositedLayer || v.layer()->backing()->paintsIntoWindow()) {
1265             v.repaintViewRectangle(viewHasCompositedLayer && v.layer()->transform() ? v.layer()->transform()->mapRect(r) : r, immediate);
1266             return;
1267         }
1268     }
1269     
1270     if (v.usesCompositing()) {
1271         ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1272         repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
1273     }
1274 #else
1275     if (repaintContainer->isRenderView())
1276         toRenderView(*repaintContainer).repaintViewRectangle(r, immediate);
1277 #endif
1278 }
1279
1280 void RenderObject::repaint(bool immediate) const
1281 {
1282     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1283     RenderView* view;
1284     if (!isRooted(&view))
1285         return;
1286
1287     if (view->printing())
1288         return; // Don't repaint if we're printing.
1289
1290     RenderLayerModelObject* repaintContainer = containerForRepaint();
1291     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)), immediate);
1292 }
1293
1294 void RenderObject::repaintRectangle(const LayoutRect& r, bool immediate) const
1295 {
1296     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1297     RenderView* view;
1298     if (!isRooted(&view))
1299         return;
1300
1301     if (view->printing())
1302         return; // Don't repaint if we're printing.
1303
1304     LayoutRect dirtyRect(r);
1305
1306     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1307     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1308     dirtyRect.move(view->layoutDelta());
1309
1310     RenderLayerModelObject* repaintContainer = containerForRepaint();
1311     computeRectForRepaint(repaintContainer, dirtyRect);
1312     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(dirtyRect), immediate);
1313 }
1314
1315 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1316 {
1317     return pixelSnappedIntRect(absoluteClippedOverflowRect());
1318 }
1319
1320 bool RenderObject::checkForRepaintDuringLayout() const
1321 {
1322     return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
1323 }
1324
1325 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
1326 {
1327     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
1328     r.inflate(outlineWidth);
1329     return r;
1330 }
1331
1332 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
1333 {
1334     ASSERT_NOT_REACHED();
1335     return LayoutRect();
1336 }
1337
1338 void RenderObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1339 {
1340     if (repaintContainer == this)
1341         return;
1342
1343     if (auto o = parent()) {
1344         if (o->isRenderBlockFlow()) {
1345             RenderBlock* cb = toRenderBlock(o);
1346             if (cb->hasColumns())
1347                 cb->adjustRectForColumns(rect);
1348         }
1349
1350         if (o->hasOverflowClip()) {
1351             RenderBox* boxParent = toRenderBox(o);
1352             boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1353             if (rect.isEmpty())
1354                 return;
1355         }
1356
1357         o->computeRectForRepaint(repaintContainer, rect, fixed);
1358     }
1359 }
1360
1361 void RenderObject::computeFloatRectForRepaint(const RenderLayerModelObject*, FloatRect&, bool) const
1362 {
1363     ASSERT_NOT_REACHED();
1364 }
1365
1366 #ifndef NDEBUG
1367
1368 void RenderObject::showTreeForThis() const
1369 {
1370     if (node())
1371         node()->showTreeForThis();
1372 }
1373
1374 void RenderObject::showRenderTreeForThis() const
1375 {
1376     showRenderTree(this, 0);
1377 }
1378
1379 void RenderObject::showLineTreeForThis() const
1380 {
1381     if (containingBlock())
1382         containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1383 }
1384
1385 void RenderObject::showRenderObject() const
1386 {
1387     showRenderObject(0);
1388 }
1389
1390 void RenderObject::showRenderObject(int printedCharacters) const
1391 {
1392     // As this function is intended to be used when debugging, the
1393     // this pointer may be 0.
1394     if (!this) {
1395         fputs("(null)\n", stderr);
1396         return;
1397     }
1398
1399     printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1400
1401     if (node()) {
1402         if (printedCharacters)
1403             for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1404                 fputc(' ', stderr);
1405         fputc('\t', stderr);
1406         node()->showNode();
1407     } else
1408         fputc('\n', stderr);
1409 }
1410
1411 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1412 {
1413     int printedCharacters = 0;
1414     if (markedObject1 == this && markedLabel1)
1415         printedCharacters += fprintf(stderr, "%s", markedLabel1);
1416     if (markedObject2 == this && markedLabel2)
1417         printedCharacters += fprintf(stderr, "%s", markedLabel2);
1418     for (; printedCharacters < depth * 2; printedCharacters++)
1419         fputc(' ', stderr);
1420
1421     showRenderObject(printedCharacters);
1422     if (!this)
1423         return;
1424
1425     for (const RenderObject* child = firstChildSlow(); child; child = child->nextSibling())
1426         child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1427 }
1428
1429 #endif // NDEBUG
1430
1431 Color RenderObject::selectionBackgroundColor() const
1432 {
1433     Color color;
1434     if (style().userSelect() != SELECT_NONE) {
1435         if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1436             color = style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1437         else {
1438             RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1439             if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1440                 color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1441             else
1442                 color = frame().selection().isFocusedAndActive() ? theme().activeSelectionBackgroundColor() : theme().inactiveSelectionBackgroundColor();
1443         }
1444     }
1445
1446     return color;
1447 }
1448
1449 Color RenderObject::selectionColor(int colorProperty) const
1450 {
1451     Color color;
1452     // If the element is unselectable, or we are only painting the selection,
1453     // don't override the foreground color with the selection foreground color.
1454     if (style().userSelect() == SELECT_NONE
1455         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1456         return color;
1457
1458     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
1459         color = pseudoStyle->visitedDependentColor(colorProperty);
1460         if (!color.isValid())
1461             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1462     } else
1463         color = frame().selection().isFocusedAndActive() ? theme().activeSelectionForegroundColor() : theme().inactiveSelectionForegroundColor();
1464
1465     return color;
1466 }
1467
1468 Color RenderObject::selectionForegroundColor() const
1469 {
1470     return selectionColor(CSSPropertyWebkitTextFillColor);
1471 }
1472
1473 Color RenderObject::selectionEmphasisMarkColor() const
1474 {
1475     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1476 }
1477
1478 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1479 {
1480     view().selectionStartEnd(spos, epos);
1481 }
1482
1483 void RenderObject::handleDynamicFloatPositionChange()
1484 {
1485     // We have gone from not affecting the inline status of the parent flow to suddenly
1486     // having an impact.  See if there is a mismatch between the parent flow's
1487     // childrenInline() state and our state.
1488     setInline(style().isDisplayInlineType());
1489     if (isInline() != parent()->childrenInline()) {
1490         if (!isInline())
1491             toRenderBoxModelObject(parent())->childBecameNonInline(this);
1492         else {
1493             // An anonymous block must be made to wrap this inline.
1494             RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1495             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
1496             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
1497             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
1498         }
1499     }
1500 }
1501
1502 void RenderObject::removeAnonymousWrappersForInlinesIfNecessary()
1503 {
1504     // We have changed to floated or out-of-flow positioning so maybe all our parent's
1505     // children can be inline now. Bail if there are any block children left on the line,
1506     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
1507     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
1508     // if we find a continuation.
1509     RenderObject* curr = parent()->firstChild();
1510     while (curr && ((curr->isAnonymousBlock() && !toRenderBlock(curr)->isAnonymousBlockContinuation()) || curr->style().isFloating() || curr->style().hasOutOfFlowPosition()))
1511         curr = curr->nextSibling();
1512
1513     if (curr)
1514         return;
1515
1516     curr = parent()->firstChild();
1517     RenderBlock* parentBlock = toRenderBlock(parent());
1518     while (curr) {
1519         RenderObject* next = curr->nextSibling();
1520         if (curr->isAnonymousBlock())
1521             parentBlock->collapseAnonymousBoxChild(parentBlock, toRenderBlock(curr));
1522         curr = next;
1523     }
1524 }
1525
1526 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
1527 {
1528     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1529     mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
1530     transformState.flatten();
1531     
1532     return transformState.lastPlanarPoint();
1533 }
1534
1535 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
1536 {
1537     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1538     mapAbsoluteToLocalPoint(mode, transformState);
1539     transformState.flatten();
1540     
1541     return transformState.lastPlanarPoint();
1542 }
1543
1544 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
1545 {
1546     TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
1547     mapAbsoluteToLocalPoint(mode, transformState);
1548     transformState.flatten();
1549     return transformState.lastPlanarQuad();
1550 }
1551
1552 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1553 {
1554     if (repaintContainer == this)
1555         return;
1556
1557     auto o = parent();
1558     if (!o)
1559         return;
1560
1561     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1562     LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
1563     if (mode & ApplyContainerFlip && o->isBox()) {
1564         if (o->style().isFlippedBlocksWritingMode())
1565             transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
1566         mode &= ~ApplyContainerFlip;
1567     }
1568
1569     LayoutSize columnOffset;
1570     o->adjustForColumns(columnOffset, roundedLayoutPoint(transformState.mappedPoint()));
1571     if (!columnOffset.isZero())
1572         transformState.move(columnOffset);
1573
1574     if (o->hasOverflowClip())
1575         transformState.move(-toRenderBox(o)->scrolledContentOffset());
1576
1577     o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1578 }
1579
1580 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1581 {
1582     ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
1583
1584     auto container = parent();
1585     if (!container)
1586         return 0;
1587
1588     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1589     LayoutSize offset;
1590     if (container->hasOverflowClip())
1591         offset = -toRenderBox(container)->scrolledContentOffset();
1592
1593     geometryMap.push(this, offset, hasColumns());
1594     
1595     return container;
1596 }
1597
1598 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1599 {
1600     auto o = parent();
1601     if (o) {
1602         o->mapAbsoluteToLocalPoint(mode, transformState);
1603         if (o->hasOverflowClip())
1604             transformState.move(toRenderBox(o)->scrolledContentOffset());
1605     }
1606 }
1607
1608 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1609 {
1610 #if ENABLE(3D_RENDERING)
1611     // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
1612     // so check the layer's transform directly.
1613     return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style().hasPerspective());
1614 #else
1615     UNUSED_PARAM(containerObject);
1616     return hasTransform();
1617 #endif
1618 }
1619
1620 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
1621 {
1622     transform.makeIdentity();
1623     transform.translate(offsetInContainer.width(), offsetInContainer.height());
1624     RenderLayer* layer;
1625     if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
1626         transform.multiply(layer->currentTransform());
1627     
1628 #if ENABLE(3D_RENDERING)
1629     if (containerObject && containerObject->hasLayer() && containerObject->style().hasPerspective()) {
1630         // Perpsective on the container affects us, so we have to factor it in here.
1631         ASSERT(containerObject->hasLayer());
1632         FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
1633
1634         TransformationMatrix perspectiveMatrix;
1635         perspectiveMatrix.applyPerspective(containerObject->style().perspective());
1636         
1637         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1638         transform = perspectiveMatrix * transform;
1639         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1640     }
1641 #else
1642     UNUSED_PARAM(containerObject);
1643 #endif
1644 }
1645
1646 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1647 {
1648     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1649     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1650     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
1651     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
1652     transformState.flatten();
1653     
1654     return transformState.lastPlanarQuad();
1655 }
1656
1657 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1658 {
1659     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1660     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
1661     transformState.flatten();
1662
1663     return transformState.lastPlanarPoint();
1664 }
1665
1666 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1667 {
1668     ASSERT(o == container());
1669
1670     LayoutSize offset;
1671
1672     o->adjustForColumns(offset, point);
1673
1674     if (o->hasOverflowClip())
1675         offset -= toRenderBox(o)->scrolledContentOffset();
1676
1677     if (offsetDependsOnPoint)
1678         *offsetDependsOnPoint = hasColumns() || o->isRenderFlowThread();
1679
1680     return offset;
1681 }
1682
1683 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
1684 {
1685     LayoutSize offset;
1686     LayoutPoint referencePoint;
1687     const RenderObject* currContainer = this;
1688     do {
1689         auto nextContainer = currContainer->container();
1690         ASSERT(nextContainer);  // This means we reached the top without finding container.
1691         if (!nextContainer)
1692             break;
1693         ASSERT(!currContainer->hasTransform());
1694         LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
1695         offset += currentOffset;
1696         referencePoint.move(currentOffset);
1697         currContainer = nextContainer;
1698     } while (currContainer != container);
1699
1700     return offset;
1701 }
1702
1703 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
1704 {
1705     if (extraWidthToEndOfLine)
1706         *extraWidthToEndOfLine = 0;
1707
1708     return LayoutRect();
1709 }
1710
1711 bool RenderObject::isRooted(RenderView** view) const
1712 {
1713     const RenderObject* o = this;
1714     while (o->parent())
1715         o = o->parent();
1716
1717     if (!o->isRenderView())
1718         return false;
1719
1720     if (view)
1721         *view = &const_cast<RenderView&>(toRenderView(*o));
1722
1723     return true;
1724 }
1725
1726 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
1727 {
1728 #if USE(CG) || USE(CAIRO) || PLATFORM(BLACKBERRY)
1729     // This can only be enabled for ports which honor the orientation flag in their drawing code.
1730     if (document().isImageDocument())
1731         return RespectImageOrientation;
1732 #endif
1733     // Respect the image's orientation if it's being used as a full-page image or it's
1734     // an <img> and the setting to respect it everywhere is set.
1735     return (frame().settings().shouldRespectImageOrientation() && node() && isHTMLImageElement(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
1736 }
1737
1738 bool RenderObject::hasOutlineAnnotation() const
1739 {
1740     return node() && node()->isLink() && document().printing();
1741 }
1742
1743 bool RenderObject::hasEntirelyFixedBackground() const
1744 {
1745     return style().hasEntirelyFixedBackground();
1746 }
1747
1748 RenderElement* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
1749 {
1750     if (repaintContainerSkipped)
1751         *repaintContainerSkipped = false;
1752
1753     // This method is extremely similar to containingBlock(), but with a few notable
1754     // exceptions.
1755     // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
1756     // the object is not part of the primary document subtree yet.
1757     // (2) For normal flow elements, it just returns the parent.
1758     // (3) For absolute positioned elements, it will return a relative positioned inline.
1759     // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
1760     // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
1761     // computePositionedLogicalHeight have to use container().
1762     auto o = parent();
1763
1764     if (isText())
1765         return o;
1766
1767     EPosition pos = style().position();
1768     if (pos == FixedPosition) {
1769         // container() can be called on an object that is not in the
1770         // tree yet.  We don't call view() since it will assert if it
1771         // can't get back to the canvas.  Instead we just walk as high up
1772         // as we can.  If we're in the tree, we'll get the root.  If we
1773         // aren't we'll get the root of our little subtree (most likely
1774         // we'll just return 0).
1775         // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
1776         // be safe now to use it.
1777         while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
1778 #if ENABLE(SVG)
1779             // foreignObject is the containing block for its contents.
1780             if (o->isSVGForeignObject())
1781                 break;
1782 #endif
1783             // The render flow thread is the top most containing block
1784             // for the fixed positioned elements.
1785             if (o->isOutOfFlowRenderFlowThread())
1786                 break;
1787
1788             if (repaintContainerSkipped && o == repaintContainer)
1789                 *repaintContainerSkipped = true;
1790
1791             o = o->parent();
1792         }
1793     } else if (pos == AbsolutePosition) {
1794         // Same goes here.  We technically just want our containing block, but
1795         // we may not have one if we're part of an uninstalled subtree.  We'll
1796         // climb as high as we can though.
1797         while (o && o->style().position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
1798 #if ENABLE(SVG)
1799             if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
1800                 break;
1801 #endif
1802             if (repaintContainerSkipped && o == repaintContainer)
1803                 *repaintContainerSkipped = true;
1804
1805             o = o->parent();
1806         }
1807     }
1808
1809     return o;
1810 }
1811
1812 bool RenderObject::isSelectionBorder() const
1813 {
1814     SelectionState st = selectionState();
1815     return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
1816 }
1817
1818 inline void RenderObject::clearLayoutRootIfNeeded() const
1819 {
1820     if (documentBeingDestroyed())
1821         return;
1822
1823     if (view().frameView().layoutRoot() == this) {
1824         ASSERT_NOT_REACHED();
1825         // This indicates a failure to layout the child, which is why
1826         // the layout root is still set to |this|. Make sure to clear it
1827         // since we are getting destroyed.
1828         view().frameView().clearLayoutRoot();
1829     }
1830 }
1831
1832 void RenderObject::willBeDestroyed()
1833 {
1834     // If this renderer is being autoscrolled, stop the autoscroll timer
1835     
1836     // FIXME: RenderObject::destroy should not get called with a renderer whose document
1837     // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
1838     // check that the frame is not null.
1839     if (frame().eventHandler().autoscrollRenderer() == this)
1840         frame().eventHandler().stopAutoscrollTimer(true);
1841
1842     // For accessibility management, notify the parent of the imminent change to its child set.
1843     // We do it now, before remove(), while the parent pointer is still available.
1844     if (AXObjectCache* cache = document().existingAXObjectCache())
1845         cache->childrenChanged(this->parent());
1846
1847     removeFromParent();
1848
1849     ASSERT(documentBeingDestroyed() || !isRenderElement() || !view().frameView().hasSlowRepaintObject(toRenderElement(this)));
1850
1851     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
1852     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
1853     if (AXObjectCache* cache = document().existingAXObjectCache())
1854         cache->remove(this);
1855
1856 #ifndef NDEBUG
1857     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1858         // After remove, the object and the associated information should not be in any flow thread.
1859         const RenderNamedFlowThreadList* flowThreadList = view().flowThreadController().renderNamedFlowThreadList();
1860         for (RenderNamedFlowThreadList::const_iterator iter = flowThreadList->begin(); iter != flowThreadList->end(); ++iter) {
1861             const RenderNamedFlowThread* renderFlowThread = *iter;
1862             ASSERT(!renderFlowThread->hasChild(this));
1863             ASSERT(!renderFlowThread->hasChildInfo(this));
1864         }
1865     }
1866 #endif
1867
1868     // If this renderer had a parent, remove should have destroyed any counters
1869     // attached to this renderer and marked the affected other counters for
1870     // reevaluation. This apparently redundant check is here for the case when
1871     // this renderer had no parent at the time remove() was called.
1872
1873     if (hasCounterNodeMap())
1874         RenderCounter::destroyCounterNodes(this);
1875
1876     // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
1877     // be moved into RenderBoxModelObject::destroy.
1878     if (hasLayer()) {
1879         setHasLayer(false);
1880         toRenderLayerModelObject(this)->destroyLayer();
1881     }
1882
1883     clearLayoutRootIfNeeded();
1884 }
1885
1886 void RenderObject::insertedIntoTree()
1887 {
1888     // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
1889
1890     if (!isFloating() && parent()->childrenInline())
1891         parent()->dirtyLinesFromChangedChild(this);
1892
1893     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1894         containerFlowThread->addFlowChild(this);
1895 }
1896
1897 void RenderObject::willBeRemovedFromTree()
1898 {
1899     // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
1900
1901     removeFromRenderFlowThread();
1902
1903     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1904         containerFlowThread->removeFlowChild(this);
1905
1906 #if ENABLE(SVG)
1907     // Update cached boundaries in SVG renderers, if a child is removed.
1908     parent()->setNeedsBoundariesUpdate();
1909 #endif
1910 }
1911
1912 void RenderObject::removeFromRenderFlowThread()
1913 {
1914     if (flowThreadState() == NotInsideFlowThread)
1915         return;
1916     
1917     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
1918     // It's only until later when we actually destroy it and remove all the children from it. 
1919     // Currently, that happens for firstLetter elements and list markers.
1920     // Pass in the flow thread so that we don't have to look it up for all the children.
1921     removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
1922 }
1923
1924 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
1925 {
1926     for (RenderObject* child = firstChildSlow(); child; child = child->nextSibling())
1927         child->removeFromRenderFlowThreadRecursive(renderFlowThread);
1928
1929     RenderFlowThread* localFlowThread = renderFlowThread;
1930     if (flowThreadState() == InsideInFlowThread)
1931         localFlowThread = flowThreadContainingBlock(); // We have to ask. We can't just assume we are in the same flow thread.
1932     if (localFlowThread)
1933         localFlowThread->removeFlowChildInfo(this);
1934     setFlowThreadState(NotInsideFlowThread);
1935 }
1936
1937 void RenderObject::destroyAndCleanupAnonymousWrappers()
1938 {
1939     // If the tree is destroyed, there is no need for a clean-up phase.
1940     if (documentBeingDestroyed()) {
1941         destroy();
1942         return;
1943     }
1944
1945     RenderObject* destroyRoot = this;
1946     for (auto destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
1947         // Currently we only remove anonymous cells' and table sections' wrappers but we should remove all unneeded
1948         // wrappers. See http://webkit.org/b/52123 as an example where this is needed.
1949         if (!destroyRootParent->isTableCell() && !destroyRootParent->isTableSection())
1950             break;
1951
1952         if (destroyRootParent->firstChild() != this || destroyRootParent->lastChild() != this)
1953             break;
1954     }
1955
1956     destroyRoot->destroy();
1957
1958     // WARNING: |this| is deleted here.
1959 }
1960
1961 void RenderObject::destroy()
1962 {
1963 #if PLATFORM(IOS)
1964     if (hasLayer())
1965         toRenderBoxModelObject(this)->layer()->willBeDestroyed();
1966 #endif
1967
1968     willBeDestroyed();
1969     delete this;
1970 }
1971
1972 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&)
1973 {
1974     return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
1975 }
1976
1977 void RenderObject::updateDragState(bool dragOn)
1978 {
1979     bool valueChanged = (dragOn != isDragging());
1980     setIsDragging(dragOn);
1981     if (valueChanged && node() && (style().affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())))
1982         node()->setNeedsStyleRecalc();
1983     for (RenderObject* curr = firstChildSlow(); curr; curr = curr->nextSibling())
1984         curr->updateDragState(dragOn);
1985 }
1986
1987 bool RenderObject::isComposited() const
1988 {
1989     return hasLayer() && toRenderLayerModelObject(this)->layer()->isComposited();
1990 }
1991
1992 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
1993 {
1994     bool inside = false;
1995     if (hitTestFilter != HitTestSelf) {
1996         // First test the foreground layer (lines and inlines).
1997         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
1998
1999         // Test floats next.
2000         if (!inside)
2001             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2002
2003         // Finally test to see if the mouse is in the background (within a child block's background).
2004         if (!inside)
2005             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2006     }
2007
2008     // See if the mouse is inside us but not any of our descendants
2009     if (hitTestFilter != HitTestDescendants && !inside)
2010         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2011
2012     return inside;
2013 }
2014
2015 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2016 {
2017     if (result.innerNode())
2018         return;
2019
2020     Node* node = this->node();
2021
2022     // If we hit the anonymous renderers inside generated content we should
2023     // actually hit the generated content so walk up to the PseudoElement.
2024     if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2025         for (auto renderer = parent(); renderer && !node; renderer = renderer->parent())
2026             node = renderer->element();
2027     }
2028
2029     if (node) {
2030         result.setInnerNode(node);
2031         if (!result.innerNonSharedNode())
2032             result.setInnerNonSharedNode(node);
2033         result.setLocalPoint(point);
2034     }
2035 }
2036
2037 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2038 {
2039     return false;
2040 }
2041
2042 int RenderObject::innerLineHeight() const
2043 {
2044     return style().computedLineHeight();
2045 }
2046
2047 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2048 {
2049     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
2050         return 0;
2051
2052     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
2053     if (cachedStyle)
2054         return cachedStyle;
2055     
2056     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2057     if (result)
2058         return style().addCachedPseudoStyle(result.release());
2059     return 0;
2060 }
2061
2062 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2063 {
2064     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
2065         return 0;
2066     
2067     if (!parentStyle) {
2068         ASSERT(!ownStyle);
2069         parentStyle = &style();
2070     }
2071
2072     // FIXME: This "find nearest element parent" should be a helper function.
2073     Node* n = node();
2074     while (n && !n->isElementNode())
2075         n = n->parentNode();
2076     if (!n)
2077         return 0;
2078     Element* element = toElement(n);
2079
2080     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2081         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
2082         result->setStyleType(FIRST_LINE_INHERITED);
2083         return result.release();
2084     }
2085
2086     return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2087 }
2088
2089 static Color decorationColor(RenderStyle* style)
2090 {
2091     Color result;
2092 #if ENABLE(CSS3_TEXT_DECORATION)
2093     // Check for text decoration color first.
2094     result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
2095     if (result.isValid())
2096         return result;
2097 #endif // CSS3_TEXT_DECORATION
2098     if (style->textStrokeWidth() > 0) {
2099         // Prefer stroke color if possible but not if it's fully transparent.
2100         result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2101         if (result.alpha())
2102             return result;
2103     }
2104     
2105     result = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2106     return result;
2107 }
2108
2109 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2110                                            Color& linethrough, bool quirksMode, bool firstlineStyle)
2111 {
2112     RenderObject* curr = this;
2113     RenderStyle* styleToUse = 0;
2114     TextDecoration currDecs = TextDecorationNone;
2115     Color resultColor;
2116     do {
2117         styleToUse = firstlineStyle ? &curr->firstLineStyle() : &curr->style();
2118         currDecs = styleToUse->textDecoration();
2119         resultColor = decorationColor(styleToUse);
2120         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2121         if (currDecs) {
2122             if (currDecs & TextDecorationUnderline) {
2123                 decorations &= ~TextDecorationUnderline;
2124                 underline = resultColor;
2125             }
2126             if (currDecs & TextDecorationOverline) {
2127                 decorations &= ~TextDecorationOverline;
2128                 overline = resultColor;
2129             }
2130             if (currDecs & TextDecorationLineThrough) {
2131                 decorations &= ~TextDecorationLineThrough;
2132                 linethrough = resultColor;
2133             }
2134         }
2135         if (curr->isRubyText())
2136             return;
2137         curr = curr->parent();
2138         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2139             curr = toRenderBlock(curr)->continuation();
2140     } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(curr->node()) && !curr->node()->hasTagName(fontTag))));
2141
2142     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2143     if (decorations && curr) {
2144         styleToUse = firstlineStyle ? &curr->firstLineStyle() : &curr->style();
2145         resultColor = decorationColor(styleToUse);
2146         if (decorations & TextDecorationUnderline)
2147             underline = resultColor;
2148         if (decorations & TextDecorationOverline)
2149             overline = resultColor;
2150         if (decorations & TextDecorationLineThrough)
2151             linethrough = resultColor;
2152     }
2153 }
2154
2155 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2156 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2157 {
2158     // Convert the style regions to absolute coordinates.
2159     if (style().visibility() != VISIBLE || !isBox())
2160         return;
2161     
2162     RenderBox* box = toRenderBox(this);
2163     FloatPoint absPos = localToAbsolute();
2164
2165 #if ENABLE(DASHBOARD_SUPPORT)
2166     const Vector<StyleDashboardRegion>& styleRegions = style().dashboardRegions();
2167     unsigned i, count = styleRegions.size();
2168     for (i = 0; i < count; i++) {
2169         StyleDashboardRegion styleRegion = styleRegions[i];
2170
2171         LayoutUnit w = box->width();
2172         LayoutUnit h = box->height();
2173
2174         AnnotatedRegionValue region;
2175         region.label = styleRegion.label;
2176         region.bounds = LayoutRect(styleRegion.offset.left().value(),
2177                                    styleRegion.offset.top().value(),
2178                                    w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2179                                    h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2180         region.type = styleRegion.type;
2181
2182         region.clip = region.bounds;
2183         computeAbsoluteRepaintRect(region.clip);
2184         if (region.clip.height() < 0) {
2185             region.clip.setHeight(0);
2186             region.clip.setWidth(0);
2187         }
2188
2189         region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2190         region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2191
2192         regions.append(region);
2193     }
2194 #else // ENABLE(DRAGGABLE_REGION)
2195     if (style().getDraggableRegionMode() == DraggableRegionNone)
2196         return;
2197     AnnotatedRegionValue region;
2198     region.draggable = style().getDraggableRegionMode() == DraggableRegionDrag;
2199     region.bounds = LayoutRect(absPos.x(), absPos.y(), box->width(), box->height());
2200     regions.append(region);
2201 #endif
2202 }
2203
2204 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2205 {
2206     // RenderTexts don't have their own style, they just use their parent's style,
2207     // so we don't want to include them.
2208     if (isText())
2209         return;
2210
2211     addAnnotatedRegions(regions);
2212     for (RenderObject* curr = toRenderElement(this)->firstChild(); curr; curr = curr->nextSibling())
2213         curr->collectAnnotatedRegions(regions);
2214 }
2215 #endif
2216
2217 bool RenderObject::willRenderImage(CachedImage*)
2218 {
2219     // Without visibility we won't render (and therefore don't care about animation).
2220     if (style().visibility() != VISIBLE)
2221         return false;
2222
2223 #if PLATFORM(IOS)
2224     if (document().frame()->timersPaused())
2225         return false;
2226 #else
2227     // We will not render a new image when Active DOM is suspended
2228     if (document().activeDOMObjectsAreSuspended())
2229         return false;
2230 #endif
2231
2232     // If we're not in a window (i.e., we're dormant from being put in the b/f cache or in a background tab)
2233     // then we don't want to render either.
2234     return !document().inPageCache() && !document().view()->isOffscreen();
2235 }
2236
2237 int RenderObject::maximalOutlineSize(PaintPhase p) const
2238 {
2239     if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2240         return 0;
2241     return view().maximalOutlineSize();
2242 }
2243
2244 int RenderObject::caretMinOffset() const
2245 {
2246     return 0;
2247 }
2248
2249 int RenderObject::caretMaxOffset() const
2250 {
2251     if (isReplaced())
2252         return node() ? std::max(1U, node()->childNodeCount()) : 1;
2253     if (isHR())
2254         return 1;
2255     return 0;
2256 }
2257
2258 int RenderObject::previousOffset(int current) const
2259 {
2260     return current - 1;
2261 }
2262
2263 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2264 {
2265     return current - 1;
2266 }
2267
2268 int RenderObject::nextOffset(int current) const
2269 {
2270     return current + 1;
2271 }
2272
2273 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
2274 {
2275     int outlineSize = outlineStyleForRepaint().outlineSize();
2276     if (const ShadowData* boxShadow = style().boxShadow()) {
2277         boxShadow->adjustRectForShadow(rect, outlineSize);
2278         return;
2279     }
2280
2281     rect.inflate(outlineSize);
2282 }
2283
2284 AnimationController& RenderObject::animation() const
2285 {
2286     return frame().animation();
2287 }
2288
2289 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
2290 {
2291     imageChanged(static_cast<WrappedImagePtr>(image), rect);
2292 }
2293
2294 RenderBoxModelObject* RenderObject::offsetParent() const
2295 {
2296     // If any of the following holds true return null and stop this algorithm:
2297     // A is the root element.
2298     // A is the HTML body element.
2299     // The computed value of the position property for element A is fixed.
2300     if (isRoot() || isBody() || (isOutOfFlowPositioned() && style().position() == FixedPosition))
2301         return 0;
2302
2303     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
2304     // chain return the nearest ancestor map HTML element and stop this algorithm.
2305     // FIXME: Implement!
2306     
2307     // Return the nearest ancestor element of A for which at least one of the following is
2308     // true and stop this algorithm if such an ancestor is found:
2309     //     * The computed value of the position property is not static.
2310     //     * It is the HTML body element.
2311     //     * The computed value of the position property of A is static and the ancestor
2312     //       is one of the following HTML elements: td, th, or table.
2313     //     * Our own extension: if there is a difference in the effective zoom
2314
2315     bool skipTables = isPositioned();
2316     float currZoom = style().effectiveZoom();
2317     auto curr = parent();
2318     while (curr && (!curr->element() || (!curr->isPositioned() && !curr->isBody())) && !curr->isRenderNamedFlowThread()) {
2319         Element* element = curr->element();
2320         if (!skipTables && element && (isHTMLTableElement(element) || element->hasTagName(tdTag) || element->hasTagName(thTag)))
2321             break;
2322  
2323         float newZoom = curr->style().effectiveZoom();
2324         if (currZoom != newZoom)
2325             break;
2326         currZoom = newZoom;
2327         curr = curr->parent();
2328     }
2329     
2330     // CSS regions specification says that region flows should return the body element as their offsetParent.
2331     if (curr && curr->isRenderNamedFlowThread())
2332         curr = document().body() ? document().body()->renderer() : 0;
2333     
2334     return curr && curr->isBoxModelObject() ? toRenderBoxModelObject(curr) : 0;
2335 }
2336
2337 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity) const
2338 {
2339     // If this is a non-anonymous renderer in an editable area, then it's simple.
2340     if (Node* node = nonPseudoNode()) {
2341         if (!node->hasEditableStyle()) {
2342             // If it can be found, we prefer a visually equivalent position that is editable. 
2343             Position position = createLegacyEditingPosition(node, offset);
2344             Position candidate = position.downstream(CanCrossEditingBoundary);
2345             if (candidate.deprecatedNode()->hasEditableStyle())
2346                 return VisiblePosition(candidate, affinity);
2347             candidate = position.upstream(CanCrossEditingBoundary);
2348             if (candidate.deprecatedNode()->hasEditableStyle())
2349                 return VisiblePosition(candidate, affinity);
2350         }
2351         // FIXME: Eliminate legacy editing positions
2352         return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
2353     }
2354
2355     // We don't want to cross the boundary between editable and non-editable
2356     // regions of the document, but that is either impossible or at least
2357     // extremely unlikely in any normal case because we stop as soon as we
2358     // find a single non-anonymous renderer.
2359
2360     // Find a nearby non-anonymous renderer.
2361     const RenderObject* child = this;
2362     while (const auto parent = child->parent()) {
2363         // Find non-anonymous content after.
2364         const RenderObject* renderer = child;
2365         while ((renderer = renderer->nextInPreOrder(parent))) {
2366             if (Node* node = renderer->nonPseudoNode())
2367                 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2368         }
2369
2370         // Find non-anonymous content before.
2371         renderer = child;
2372         while ((renderer = renderer->previousInPreOrder())) {
2373             if (renderer == parent)
2374                 break;
2375             if (Node* node = renderer->nonPseudoNode())
2376                 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
2377         }
2378
2379         // Use the parent itself unless it too is anonymous.
2380         if (Element* element = parent->nonPseudoElement())
2381             return VisiblePosition(firstPositionInOrBeforeNode(element), DOWNSTREAM);
2382
2383         // Repeat at the next level up.
2384         child = parent;
2385     }
2386
2387     // Everything was anonymous. Give up.
2388     return VisiblePosition();
2389 }
2390
2391 VisiblePosition RenderObject::createVisiblePosition(const Position& position) const
2392 {
2393     if (position.isNotNull())
2394         return VisiblePosition(position);
2395
2396     ASSERT(!node());
2397     return createVisiblePosition(0, DOWNSTREAM);
2398 }
2399
2400 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
2401 {
2402     return SetCursorBasedOnStyle;
2403 }
2404
2405 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
2406 {
2407     if (needsLayout())
2408         return false;
2409
2410     RenderBlock* containingBlock = this->containingBlock();
2411     return containingBlock ? !containingBlock->needsLayout() : true;
2412 }
2413
2414 // We only create "generated" child renderers like one for first-letter if:
2415 // - the firstLetterBlock can have children in the DOM and
2416 // - the block doesn't have any special assumption on its text children.
2417 // This correctly prevents form controls from having such renderers.
2418 bool RenderObject::canHaveGeneratedChildren() const
2419 {
2420     return canHaveChildren();
2421 }
2422
2423 Node* RenderObject::generatingPseudoHostElement() const
2424 {
2425     return toPseudoElement(node())->hostElement();
2426 }
2427
2428 bool RenderObject::canBeReplacedWithInlineRunIn() const
2429 {
2430     return true;
2431 }
2432
2433 #if ENABLE(SVG)
2434
2435 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
2436 {
2437     ASSERT_NOT_REACHED();
2438     return 0;
2439 }
2440
2441 void RenderObject::setNeedsBoundariesUpdate()
2442 {
2443     if (auto renderer = parent())
2444         renderer->setNeedsBoundariesUpdate();
2445 }
2446
2447 FloatRect RenderObject::objectBoundingBox() const
2448 {
2449     ASSERT_NOT_REACHED();
2450     return FloatRect();
2451 }
2452
2453 FloatRect RenderObject::strokeBoundingBox() const
2454 {
2455     ASSERT_NOT_REACHED();
2456     return FloatRect();
2457 }
2458
2459 // Returns the smallest rectangle enclosing all of the painted content
2460 // respecting clipping, masking, filters, opacity, stroke-width and markers
2461 FloatRect RenderObject::repaintRectInLocalCoordinates() const
2462 {
2463     ASSERT_NOT_REACHED();
2464     return FloatRect();
2465 }
2466
2467 AffineTransform RenderObject::localTransform() const
2468 {
2469     static const AffineTransform identity;
2470     return identity;
2471 }
2472
2473 const AffineTransform& RenderObject::localToParentTransform() const
2474 {
2475     static const AffineTransform identity;
2476     return identity;
2477 }
2478
2479 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2480 {
2481     ASSERT_NOT_REACHED();
2482     return false;
2483 }
2484
2485 #endif // ENABLE(SVG)
2486
2487 } // namespace WebCore
2488
2489 #ifndef NDEBUG
2490
2491 void showTree(const WebCore::RenderObject* object)
2492 {
2493     if (object)
2494         object->showTreeForThis();
2495 }
2496
2497 void showLineTree(const WebCore::RenderObject* object)
2498 {
2499     if (object)
2500         object->showLineTreeForThis();
2501 }
2502
2503 void showRenderTree(const WebCore::RenderObject* object1)
2504 {
2505     showRenderTree(object1, 0);
2506 }
2507
2508 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
2509 {
2510     if (object1) {
2511         const WebCore::RenderObject* root = object1;
2512         while (root->parent())
2513             root = root->parent();
2514         root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
2515     }
2516 }
2517
2518 #endif