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