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