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