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