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