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