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