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