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