Remove unused support for DRAGGABLE_REGION
[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, int x1, int y1, int x2, int y2,
740     BoxSide side, Color color, EBorderStyle borderStyle, int adjacentWidth1, int adjacentWidth2, bool antialias)
741 {
742     int thickness;
743     int 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     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
753     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
754     if (!thickness || !length)
755         return;
756
757     if (borderStyle == DOUBLE && thickness < 3)
758         borderStyle = SOLID;
759
760     const RenderStyle& style = this->style();
761     switch (borderStyle) {
762         case BNONE:
763         case BHIDDEN:
764             return;
765         case DOTTED:
766         case DASHED: {
767             if (thickness > 0) {
768                 bool wasAntialiased = graphicsContext->shouldAntialias();
769                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
770                 graphicsContext->setShouldAntialias(antialias);
771                 graphicsContext->setStrokeColor(color, style.colorSpace());
772                 graphicsContext->setStrokeThickness(thickness);
773                 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
774
775                 switch (side) {
776                     case BSBottom:
777                     case BSTop:
778                         graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
779                         break;
780                     case BSRight:
781                     case BSLeft:
782                         graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
783                         break;
784                 }
785                 graphicsContext->setShouldAntialias(wasAntialiased);
786                 graphicsContext->setStrokeStyle(oldStrokeStyle);
787             }
788             break;
789         }
790         case DOUBLE: {
791             int thirdOfThickness = (thickness + 1) / 3;
792             ASSERT(thirdOfThickness);
793
794             if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
795                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
796                 graphicsContext->setStrokeStyle(NoStroke);
797                 graphicsContext->setFillColor(color, style.colorSpace());
798                 
799                 bool wasAntialiased = graphicsContext->shouldAntialias();
800                 graphicsContext->setShouldAntialias(antialias);
801
802                 switch (side) {
803                     case BSTop:
804                     case BSBottom:
805                         graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
806                         graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
807                         break;
808                     case BSLeft:
809                     case BSRight:
810                         // FIXME: Why do we offset the border by 1 in this case but not the other one?
811                         if (length > 1) {
812                             graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
813                             graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
814                         }
815                         break;
816                 }
817
818                 graphicsContext->setShouldAntialias(wasAntialiased);
819                 graphicsContext->setStrokeStyle(oldStrokeStyle);
820             } else {
821                 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
822                 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
823
824                 switch (side) {
825                     case BSTop:
826                         drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
827                                    y1, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
828                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
829                         drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
830                                    y2 - thirdOfThickness, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
831                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
832                         break;
833                     case BSLeft:
834                         drawLineForBoxSide(graphicsContext, x1, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
835                                    x1 + thirdOfThickness, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
836                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
837                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
838                                    x2, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
839                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
840                         break;
841                     case BSBottom:
842                         drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
843                                    y1, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
844                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
845                         drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
846                                    y2 - thirdOfThickness, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
847                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
848                         break;
849                     case BSRight:
850                         drawLineForBoxSide(graphicsContext, x1, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
851                                    x1 + thirdOfThickness, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
852                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
853                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
854                                    x2, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
855                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
856                         break;
857                     default:
858                         break;
859                 }
860             }
861             break;
862         }
863         case RIDGE:
864         case GROOVE: {
865             EBorderStyle s1;
866             EBorderStyle s2;
867             if (borderStyle == GROOVE) {
868                 s1 = INSET;
869                 s2 = OUTSET;
870             } else {
871                 s1 = OUTSET;
872                 s2 = INSET;
873             }
874
875             int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
876             int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
877
878             switch (side) {
879                 case BSTop:
880                     drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1, 0) / 2, y1, x2 - std::max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
881                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
882                     drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(adjacentWidth2 + 1, 0) / 2, y2,
883                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
884                     break;
885                 case BSLeft:
886                     drawLineForBoxSide(graphicsContext, x1, y1 + std::max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(-adjacentWidth2, 0) / 2,
887                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
888                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(adjacentWidth2 + 1, 0) / 2,
889                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
890                     break;
891                 case BSBottom:
892                     drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1, 0) / 2, y1, x2 - std::max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
893                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
894                     drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(-adjacentWidth2 + 1, 0) / 2, y2,
895                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
896                     break;
897                 case BSRight:
898                     drawLineForBoxSide(graphicsContext, x1, y1 + std::max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(adjacentWidth2, 0) / 2,
899                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
900                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(-adjacentWidth2 + 1, 0) / 2,
901                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
902                     break;
903             }
904             break;
905         }
906         case INSET:
907             // FIXME: Maybe we should lighten the colors on one side like Firefox.
908             // https://bugs.webkit.org/show_bug.cgi?id=58608
909             if (side == BSTop || side == BSLeft)
910                 color = color.dark();
911             // fall through
912         case OUTSET:
913             if (borderStyle == OUTSET && (side == BSBottom || side == BSRight))
914                 color = color.dark();
915             // fall through
916         case SOLID: {
917             StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
918             graphicsContext->setStrokeStyle(NoStroke);
919             graphicsContext->setFillColor(color, style.colorSpace());
920             ASSERT(x2 >= x1);
921             ASSERT(y2 >= y1);
922             if (!adjacentWidth1 && !adjacentWidth2) {
923                 // Turn off antialiasing to match the behavior of drawConvexPolygon();
924                 // this matters for rects in transformed contexts.
925                 bool wasAntialiased = graphicsContext->shouldAntialias();
926                 graphicsContext->setShouldAntialias(antialias);
927                 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
928                 graphicsContext->setShouldAntialias(wasAntialiased);
929                 graphicsContext->setStrokeStyle(oldStrokeStyle);
930                 return;
931             }
932             FloatPoint quad[4];
933             switch (side) {
934                 case BSTop:
935                     quad[0] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y1);
936                     quad[1] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y2);
937                     quad[2] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y2);
938                     quad[3] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y1);
939                     break;
940                 case BSBottom:
941                     quad[0] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y1);
942                     quad[1] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y2);
943                     quad[2] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y2);
944                     quad[3] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y1);
945                     break;
946                 case BSLeft:
947                     quad[0] = FloatPoint(x1, y1 + std::max(-adjacentWidth1, 0));
948                     quad[1] = FloatPoint(x1, y2 - std::max(-adjacentWidth2, 0));
949                     quad[2] = FloatPoint(x2, y2 - std::max(adjacentWidth2, 0));
950                     quad[3] = FloatPoint(x2, y1 + std::max(adjacentWidth1, 0));
951                     break;
952                 case BSRight:
953                     quad[0] = FloatPoint(x1, y1 + std::max(adjacentWidth1, 0));
954                     quad[1] = FloatPoint(x1, y2 - std::max(adjacentWidth2, 0));
955                     quad[2] = FloatPoint(x2, y2 - std::max(-adjacentWidth2, 0));
956                     quad[3] = FloatPoint(x2, y1 + std::max(-adjacentWidth1, 0));
957                     break;
958             }
959
960             graphicsContext->drawConvexPolygon(4, quad, antialias);
961             graphicsContext->setStrokeStyle(oldStrokeStyle);
962             break;
963         }
964     }
965 }
966
967 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
968 {
969     Vector<IntRect> focusRingRects;
970     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
971     if (style->outlineStyleIsAuto())
972         paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
973     else
974         addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
975 }
976
977 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
978 {
979     if (rect.isEmpty())
980         return;
981     Node* n = node();
982     if (!n || !n->isLink() || !n->isElementNode())
983         return;
984     const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
985     if (href.isNull())
986         return;
987     context->setURLForRect(n->document().completeURL(href), pixelSnappedIntRect(rect));
988 }
989
990 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
991 {
992     if (!hasOutline())
993         return;
994
995     RenderStyle& styleToUse = style();
996     LayoutUnit outlineWidth = styleToUse.outlineWidth();
997
998     int outlineOffset = styleToUse.outlineOffset();
999
1000     if (styleToUse.outlineStyleIsAuto() || hasOutlineAnnotation()) {
1001         if (!theme().supportsFocusRing(&styleToUse)) {
1002             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1003             paintFocusRing(paintInfo, paintRect.location(), &styleToUse);
1004         }
1005     }
1006
1007     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
1008         return;
1009
1010     IntRect inner = pixelSnappedIntRect(paintRect);
1011     inner.inflate(outlineOffset);
1012
1013     IntRect outer = pixelSnappedIntRect(inner);
1014     outer.inflate(outlineWidth);
1015
1016     // FIXME: This prevents outlines from painting inside the object. See bug 12042
1017     if (outer.isEmpty())
1018         return;
1019
1020     EBorderStyle outlineStyle = styleToUse.outlineStyle();
1021     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
1022
1023     GraphicsContext* graphicsContext = paintInfo.context;
1024     bool useTransparencyLayer = outlineColor.hasAlpha();
1025     if (useTransparencyLayer) {
1026         if (outlineStyle == SOLID) {
1027             Path path;
1028             path.addRect(outer);
1029             path.addRect(inner);
1030             graphicsContext->setFillRule(RULE_EVENODD);
1031             graphicsContext->setFillColor(outlineColor, styleToUse.colorSpace());
1032             graphicsContext->fillPath(path);
1033             return;
1034         }
1035         graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1036         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1037     }
1038
1039     int leftOuter = outer.x();
1040     int leftInner = inner.x();
1041     int rightOuter = outer.maxX();
1042     int rightInner = inner.maxX();
1043     int topOuter = outer.y();
1044     int topInner = inner.y();
1045     int bottomOuter = outer.maxY();
1046     int bottomInner = inner.maxY();
1047     
1048     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1049     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1050     drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1051     drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1052
1053     if (useTransparencyLayer)
1054         graphicsContext->endTransparencyLayer();
1055 }
1056
1057 // FIXME: Make this return an unsigned integer?
1058 int RenderObject::columnNumberForOffset(int offset)
1059 {
1060     int columnNumber = 0;
1061     RenderBlock* containingBlock = this->containingBlock();
1062     RenderView& view = containingBlock->view();
1063     const Pagination& pagination = view.frameView().frame().page()->pagination();
1064     if (pagination.mode == Pagination::Unpaginated)
1065         return columnNumber;
1066
1067     ColumnInfo* columnInfo = view.columnInfo();
1068     if (columnInfo && columnInfo->progressionAxis() == ColumnInfo::BlockAxis) {
1069         if (!columnInfo->progressionIsReversed())
1070             columnNumber = (pagination.pageLength + pagination.gap - offset) / (pagination.pageLength + pagination.gap);
1071         else
1072             columnNumber = offset / (pagination.pageLength + pagination.gap);
1073     }
1074     return columnNumber;
1075 }
1076
1077 #if PLATFORM(IOS)
1078 // This function is similar in spirit to RenderText::absoluteRectsForRange, but returns rectangles
1079 // which are annotated with additional state which helps iOS draw selections in its unique way.
1080 // No annotations are added in this class.
1081 // FIXME: Move to RenderText with absoluteRectsForRange()?
1082 void RenderObject::collectSelectionRects(Vector<SelectionRect>& rects, unsigned start, unsigned end)
1083 {
1084     Vector<FloatQuad> quads;
1085
1086     if (!firstChildSlow()) {
1087         // FIXME: WebKit's position for an empty span after a BR is incorrect, so we can't trust 
1088         // quads for them. We don't need selection rects for those anyway though, since they 
1089         // are just empty containers. See <https://bugs.webkit.org/show_bug.cgi?id=49358>.
1090         RenderObject* previous = previousSibling();
1091         Node* node = this->node();
1092         if (!previous || !previous->isBR() || !node || !node->isContainerNode() || !isInline()) {
1093             // For inline elements we don't use absoluteQuads, since it takes into account continuations and leads to wrong results.
1094             absoluteQuadsForSelection(quads);
1095         }
1096     } else {
1097         unsigned offset = start;
1098         for (RenderObject* child = childAt(start); child && offset < end; child = child->nextSibling(), ++offset)
1099             child->absoluteQuads(quads);
1100     }
1101
1102     unsigned numberOfQuads = quads.size();
1103     for (unsigned i = 0; i < numberOfQuads; ++i)
1104         rects.append(SelectionRect(quads[i].enclosingBoundingBox(), isHorizontalWritingMode(), columnNumberForOffset(quads[i].enclosingBoundingBox().x())));
1105 }
1106 #endif
1107
1108 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms) const
1109 {
1110     if (useTransforms) {
1111         Vector<FloatQuad> quads;
1112         absoluteQuads(quads);
1113
1114         size_t n = quads.size();
1115         if (!n)
1116             return IntRect();
1117     
1118         IntRect result = quads[0].enclosingBoundingBox();
1119         for (size_t i = 1; i < n; ++i)
1120             result.unite(quads[i].enclosingBoundingBox());
1121         return result;
1122     }
1123
1124     FloatPoint absPos = localToAbsolute();
1125     Vector<IntRect> rects;
1126     absoluteRects(rects, flooredLayoutPoint(absPos));
1127
1128     size_t n = rects.size();
1129     if (!n)
1130         return IntRect();
1131
1132     LayoutRect result = rects[0];
1133     for (size_t i = 1; i < n; ++i)
1134         result.unite(rects[i]);
1135     return pixelSnappedIntRect(result);
1136 }
1137
1138 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1139 {
1140     Vector<IntRect> rects;
1141     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1142     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1143     // implicitly assumes that. This doesn't work correctly with transformed
1144     // descendants.
1145     FloatPoint absolutePoint = localToAbsolute();
1146     addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
1147     size_t count = rects.size();
1148     for (size_t i = 0; i < count; ++i) {
1149         IntRect rect = rects[i];
1150         rect.move(-absolutePoint.x(), -absolutePoint.y());
1151         quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1152     }
1153 }
1154
1155 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1156 {
1157     if (!range || !range->startContainer())
1158         return FloatRect();
1159
1160     range->ownerDocument().updateLayout();
1161
1162     Vector<FloatQuad> quads;
1163     range->textQuads(quads);
1164
1165     if (quads.isEmpty())
1166         return FloatRect();
1167
1168     FloatRect result = quads[0].boundingBox();
1169     for (size_t i = 1; i < quads.size(); ++i)
1170         result.uniteEvenIfEmpty(quads[i].boundingBox());
1171
1172     return result;
1173 }
1174
1175 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1176 {
1177     if (hasLayer())
1178         result.unite(absoluteBoundingBoxRectIgnoringTransforms());
1179     for (RenderObject* current = firstChildSlow(); current; current = current->nextSibling())
1180         current->addAbsoluteRectForLayer(result);
1181 }
1182
1183 // FIXME: change this to use the subtreePaint terminology
1184 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1185 {
1186     LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
1187     topLevelRect = result;
1188     for (RenderObject* current = firstChildSlow(); current; current = current->nextSibling())
1189         current->addAbsoluteRectForLayer(result);
1190     return result;
1191 }
1192
1193 RenderLayerModelObject* RenderObject::containerForRepaint() const
1194 {
1195     RenderLayerModelObject* repaintContainer = 0;
1196
1197 #if USE(ACCELERATED_COMPOSITING)
1198     if (view().usesCompositing()) {
1199         if (RenderLayer* parentLayer = enclosingLayer()) {
1200             RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
1201             if (compLayer)
1202                 repaintContainer = &compLayer->renderer();
1203         }
1204     }
1205 #endif
1206     
1207 #if ENABLE(CSS_FILTERS)
1208     if (view().hasSoftwareFilters()) {
1209         if (RenderLayer* parentLayer = enclosingLayer()) {
1210             RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
1211             if (enclosingFilterLayer)
1212                 return &enclosingFilterLayer->renderer();
1213         }
1214     }
1215 #endif
1216
1217     // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1218     // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1219     // repainting to do individual region repaints.
1220     RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
1221     if (parentRenderFlowThread) {
1222         // If the element has a fixed positioned element with named flow as CB along the CB chain
1223         // then the repaint container is not the flow thread.
1224         if (hasFixedPosInNamedFlowContainingBlock(this))
1225             return repaintContainer;
1226         // The ancestor document will do the reparenting when the repaint propagates further up.
1227         // We're just a seamless child document, and we don't need to do the hacking.
1228         if (parentRenderFlowThread && &parentRenderFlowThread->document() != &document())
1229             return repaintContainer;
1230         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
1231         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
1232         RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : 0;
1233         if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
1234             repaintContainer = parentRenderFlowThread;
1235     }
1236     return repaintContainer;
1237 }
1238
1239 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const IntRect& r, bool immediate, bool shouldClipToLayer) const
1240 {
1241     if (!repaintContainer) {
1242         view().repaintViewRectangle(r, immediate);
1243         return;
1244     }
1245
1246     if (repaintContainer->isRenderFlowThread()) {
1247         toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r, immediate);
1248         return;
1249     }
1250
1251 #if ENABLE(CSS_FILTERS)
1252     if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
1253         repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r, immediate);
1254         return;
1255     }
1256 #endif
1257
1258 #if USE(ACCELERATED_COMPOSITING)
1259     RenderView& v = view();
1260     if (repaintContainer->isRenderView()) {
1261         ASSERT(repaintContainer == &v);
1262         bool viewHasCompositedLayer = v.hasLayer() && v.layer()->isComposited();
1263         if (!viewHasCompositedLayer || v.layer()->backing()->paintsIntoWindow()) {
1264             v.repaintViewRectangle(viewHasCompositedLayer && v.layer()->transform() ? v.layer()->transform()->mapRect(r) : r, immediate);
1265             return;
1266         }
1267     }
1268     
1269     if (v.usesCompositing()) {
1270         ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1271         repaintContainer->layer()->setBackingNeedsRepaintInRect(r, shouldClipToLayer ? GraphicsLayer::ClipToLayer : GraphicsLayer::DoNotClipToLayer);
1272     }
1273 #else
1274     if (repaintContainer->isRenderView())
1275         toRenderView(*repaintContainer).repaintViewRectangle(r, immediate);
1276 #endif
1277 }
1278
1279 void RenderObject::repaint(bool immediate) const
1280 {
1281     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1282     RenderView* view;
1283     if (!isRooted(&view))
1284         return;
1285
1286     if (view->printing())
1287         return; // Don't repaint if we're printing.
1288
1289     RenderLayerModelObject* repaintContainer = containerForRepaint();
1290     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)), immediate);
1291 }
1292
1293 void RenderObject::repaintRectangle(const LayoutRect& r, bool immediate, bool shouldClipToLayer) const
1294 {
1295     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1296     RenderView* view;
1297     if (!isRooted(&view))
1298         return;
1299
1300     if (view->printing())
1301         return; // Don't repaint if we're printing.
1302
1303     LayoutRect dirtyRect(r);
1304
1305     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1306     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1307     dirtyRect.move(view->layoutDelta());
1308
1309     RenderLayerModelObject* repaintContainer = containerForRepaint();
1310     computeRectForRepaint(repaintContainer, dirtyRect);
1311     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(dirtyRect), immediate, shouldClipToLayer);
1312 }
1313
1314 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1315 {
1316     return pixelSnappedIntRect(absoluteClippedOverflowRect());
1317 }
1318
1319 bool RenderObject::checkForRepaintDuringLayout() const
1320 {
1321     return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
1322 }
1323
1324 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
1325 {
1326     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
1327     r.inflate(outlineWidth);
1328     return r;
1329 }
1330
1331 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
1332 {
1333     ASSERT_NOT_REACHED();
1334     return LayoutRect();
1335 }
1336
1337 void RenderObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1338 {
1339     if (repaintContainer == this)
1340         return;
1341
1342     if (auto o = parent()) {
1343         if (o->isRenderBlockFlow()) {
1344             RenderBlock* cb = toRenderBlock(o);
1345             if (cb->hasColumns())
1346                 cb->adjustRectForColumns(rect);
1347         }
1348
1349         if (o->hasOverflowClip()) {
1350             RenderBox* boxParent = toRenderBox(o);
1351             boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1352             if (rect.isEmpty())
1353                 return;
1354         }
1355
1356         o->computeRectForRepaint(repaintContainer, rect, fixed);
1357     }
1358 }
1359
1360 void RenderObject::computeFloatRectForRepaint(const RenderLayerModelObject*, FloatRect&, bool) const
1361 {
1362     ASSERT_NOT_REACHED();
1363 }
1364
1365 #ifndef NDEBUG
1366
1367 void RenderObject::showTreeForThis() const
1368 {
1369     if (node())
1370         node()->showTreeForThis();
1371 }
1372
1373 void RenderObject::showRenderTreeForThis() const
1374 {
1375     showRenderTree(this, 0);
1376 }
1377
1378 void RenderObject::showLineTreeForThis() const
1379 {
1380     if (containingBlock())
1381         containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1382 }
1383
1384 void RenderObject::showRenderObject() const
1385 {
1386     showRenderObject(0);
1387 }
1388
1389 void RenderObject::showRenderObject(int printedCharacters) const
1390 {
1391     // As this function is intended to be used when debugging, the
1392     // this pointer may be 0.
1393     if (!this) {
1394         fputs("(null)\n", stderr);
1395         return;
1396     }
1397
1398     printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1399
1400     if (node()) {
1401         if (printedCharacters)
1402             for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1403                 fputc(' ', stderr);
1404         fputc('\t', stderr);
1405         node()->showNode();
1406     } else
1407         fputc('\n', stderr);
1408 }
1409
1410 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1411 {
1412     int printedCharacters = 0;
1413     if (markedObject1 == this && markedLabel1)
1414         printedCharacters += fprintf(stderr, "%s", markedLabel1);
1415     if (markedObject2 == this && markedLabel2)
1416         printedCharacters += fprintf(stderr, "%s", markedLabel2);
1417     for (; printedCharacters < depth * 2; printedCharacters++)
1418         fputc(' ', stderr);
1419
1420     showRenderObject(printedCharacters);
1421     if (!this)
1422         return;
1423
1424     for (const RenderObject* child = firstChildSlow(); child; child = child->nextSibling())
1425         child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1426 }
1427
1428 #endif // NDEBUG
1429
1430 Color RenderObject::selectionBackgroundColor() const
1431 {
1432     Color color;
1433     if (style().userSelect() != SELECT_NONE) {
1434         if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1435             color = style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1436         else {
1437             RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1438             if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1439                 color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1440             else
1441                 color = frame().selection().isFocusedAndActive() ? theme().activeSelectionBackgroundColor() : theme().inactiveSelectionBackgroundColor();
1442         }
1443     }
1444
1445     return color;
1446 }
1447
1448 Color RenderObject::selectionColor(int colorProperty) const
1449 {
1450     Color color;
1451     // If the element is unselectable, or we are only painting the selection,
1452     // don't override the foreground color with the selection foreground color.
1453     if (style().userSelect() == SELECT_NONE
1454         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1455         return color;
1456
1457     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
1458         color = pseudoStyle->visitedDependentColor(colorProperty);
1459         if (!color.isValid())
1460             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1461     } else
1462         color = frame().selection().isFocusedAndActive() ? theme().activeSelectionForegroundColor() : theme().inactiveSelectionForegroundColor();
1463
1464     return color;
1465 }
1466
1467 Color RenderObject::selectionForegroundColor() const
1468 {
1469     return selectionColor(CSSPropertyWebkitTextFillColor);
1470 }
1471
1472 Color RenderObject::selectionEmphasisMarkColor() const
1473 {
1474     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1475 }
1476
1477 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1478 {
1479     view().selectionStartEnd(spos, epos);
1480 }
1481
1482 void RenderObject::handleDynamicFloatPositionChange()
1483 {
1484     // We have gone from not affecting the inline status of the parent flow to suddenly
1485     // having an impact.  See if there is a mismatch between the parent flow's
1486     // childrenInline() state and our state.
1487     setInline(style().isDisplayInlineType());
1488     if (isInline() != parent()->childrenInline()) {
1489         if (!isInline())
1490             toRenderBoxModelObject(parent())->childBecameNonInline(this);
1491         else {
1492             // An anonymous block must be made to wrap this inline.
1493             RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1494             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
1495             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
1496             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
1497         }
1498     }
1499 }
1500
1501 void RenderObject::removeAnonymousWrappersForInlinesIfNecessary()
1502 {
1503     // We have changed to floated or out-of-flow positioning so maybe all our parent's
1504     // children can be inline now. Bail if there are any block children left on the line,
1505     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
1506     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
1507     // if we find a continuation.
1508     RenderObject* curr = parent()->firstChild();
1509     while (curr && ((curr->isAnonymousBlock() && !toRenderBlock(curr)->isAnonymousBlockContinuation()) || curr->style().isFloating() || curr->style().hasOutOfFlowPosition()))
1510         curr = curr->nextSibling();
1511
1512     if (curr)
1513         return;
1514
1515     curr = parent()->firstChild();
1516     RenderBlock* parentBlock = toRenderBlock(parent());
1517     while (curr) {
1518         RenderObject* next = curr->nextSibling();
1519         if (curr->isAnonymousBlock())
1520             parentBlock->collapseAnonymousBoxChild(parentBlock, toRenderBlock(curr));
1521         curr = next;
1522     }
1523 }
1524
1525 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
1526 {
1527     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1528     mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
1529     transformState.flatten();
1530     
1531     return transformState.lastPlanarPoint();
1532 }
1533
1534 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
1535 {
1536     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1537     mapAbsoluteToLocalPoint(mode, transformState);
1538     transformState.flatten();
1539     
1540     return transformState.lastPlanarPoint();
1541 }
1542
1543 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
1544 {
1545     TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
1546     mapAbsoluteToLocalPoint(mode, transformState);
1547     transformState.flatten();
1548     return transformState.lastPlanarQuad();
1549 }
1550
1551 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1552 {
1553     if (repaintContainer == this)
1554         return;
1555
1556     auto o = parent();
1557     if (!o)
1558         return;
1559
1560     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1561     LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
1562     if (mode & ApplyContainerFlip && o->isBox()) {
1563         if (o->style().isFlippedBlocksWritingMode())
1564             transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
1565         mode &= ~ApplyContainerFlip;
1566     }
1567
1568     LayoutSize columnOffset;
1569     o->adjustForColumns(columnOffset, roundedLayoutPoint(transformState.mappedPoint()));
1570     if (!columnOffset.isZero())
1571         transformState.move(columnOffset);
1572
1573     if (o->hasOverflowClip())
1574         transformState.move(-toRenderBox(o)->scrolledContentOffset());
1575
1576     o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1577 }
1578
1579 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1580 {
1581     ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
1582
1583     auto container = parent();
1584     if (!container)
1585         return 0;
1586
1587     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
1588     LayoutSize offset;
1589     if (container->hasOverflowClip())
1590         offset = -toRenderBox(container)->scrolledContentOffset();
1591
1592     geometryMap.push(this, offset, hasColumns());
1593     
1594     return container;
1595 }
1596
1597 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1598 {
1599     auto o = parent();
1600     if (o) {
1601         o->mapAbsoluteToLocalPoint(mode, transformState);
1602         if (o->hasOverflowClip())
1603             transformState.move(toRenderBox(o)->scrolledContentOffset());
1604     }
1605 }
1606
1607 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1608 {
1609 #if ENABLE(3D_RENDERING)
1610     // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
1611     // so check the layer's transform directly.
1612     return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style().hasPerspective());
1613 #else
1614     UNUSED_PARAM(containerObject);
1615     return hasTransform();
1616 #endif
1617 }
1618
1619 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
1620 {
1621     transform.makeIdentity();
1622     transform.translate(offsetInContainer.width(), offsetInContainer.height());
1623     RenderLayer* layer;
1624     if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
1625         transform.multiply(layer->currentTransform());
1626     
1627 #if ENABLE(3D_RENDERING)
1628     if (containerObject && containerObject->hasLayer() && containerObject->style().hasPerspective()) {
1629         // Perpsective on the container affects us, so we have to factor it in here.
1630         ASSERT(containerObject->hasLayer());
1631         FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
1632
1633         TransformationMatrix perspectiveMatrix;
1634         perspectiveMatrix.applyPerspective(containerObject->style().perspective());
1635         
1636         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1637         transform = perspectiveMatrix * transform;
1638         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1639     }
1640 #else
1641     UNUSED_PARAM(containerObject);
1642 #endif
1643 }
1644
1645 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1646 {
1647     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1648     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1649     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
1650     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
1651     transformState.flatten();
1652     
1653     return transformState.lastPlanarQuad();
1654 }
1655
1656 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
1657 {
1658     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1659     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
1660     transformState.flatten();
1661
1662     return transformState.lastPlanarPoint();
1663 }
1664
1665 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1666 {
1667     ASSERT(o == container());
1668
1669     LayoutSize offset;
1670
1671     o->adjustForColumns(offset, point);
1672
1673     if (o->hasOverflowClip())
1674         offset -= toRenderBox(o)->scrolledContentOffset();
1675
1676     if (offsetDependsOnPoint)
1677         *offsetDependsOnPoint = hasColumns() || o->isRenderFlowThread();
1678
1679     return offset;
1680 }
1681
1682 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
1683 {
1684     LayoutSize offset;
1685     LayoutPoint referencePoint;
1686     const RenderObject* currContainer = this;
1687     do {
1688         auto nextContainer = currContainer->container();
1689         ASSERT(nextContainer);  // This means we reached the top without finding container.
1690         if (!nextContainer)
1691             break;
1692         ASSERT(!currContainer->hasTransform());
1693         LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
1694         offset += currentOffset;
1695         referencePoint.move(currentOffset);
1696         currContainer = nextContainer;
1697     } while (currContainer != container);
1698
1699     return offset;
1700 }
1701
1702 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
1703 {
1704     if (extraWidthToEndOfLine)
1705         *extraWidthToEndOfLine = 0;
1706
1707     return LayoutRect();
1708 }
1709
1710 bool RenderObject::isRooted(RenderView** view) const
1711 {
1712     const RenderObject* o = this;
1713     while (o->parent())
1714         o = o->parent();
1715
1716     if (!o->isRenderView())
1717         return false;
1718
1719     if (view)
1720         *view = &const_cast<RenderView&>(toRenderView(*o));
1721
1722     return true;
1723 }
1724
1725 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
1726 {
1727 #if USE(CG) || USE(CAIRO)
1728     // This can only be enabled for ports which honor the orientation flag in their drawing code.
1729     if (document().isImageDocument())
1730         return RespectImageOrientation;
1731 #endif
1732     // Respect the image's orientation if it's being used as a full-page image or it's
1733     // an <img> and the setting to respect it everywhere is set.
1734     return (frame().settings().shouldRespectImageOrientation() && node() && isHTMLImageElement(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
1735 }
1736
1737 bool RenderObject::hasOutlineAnnotation() const
1738 {
1739     return node() && node()->isLink() && document().printing();
1740 }
1741
1742 bool RenderObject::hasEntirelyFixedBackground() const
1743 {
1744     return style().hasEntirelyFixedBackground();
1745 }
1746
1747 RenderElement* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
1748 {
1749     if (repaintContainerSkipped)
1750         *repaintContainerSkipped = false;
1751
1752     // This method is extremely similar to containingBlock(), but with a few notable
1753     // exceptions.
1754     // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
1755     // the object is not part of the primary document subtree yet.
1756     // (2) For normal flow elements, it just returns the parent.
1757     // (3) For absolute positioned elements, it will return a relative positioned inline.
1758     // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
1759     // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
1760     // computePositionedLogicalHeight have to use container().
1761     auto o = parent();
1762
1763     if (isText())
1764         return o;
1765
1766     EPosition pos = style().position();
1767     if (pos == FixedPosition) {
1768         // container() can be called on an object that is not in the
1769         // tree yet.  We don't call view() since it will assert if it
1770         // can't get back to the canvas.  Instead we just walk as high up
1771         // as we can.  If we're in the tree, we'll get the root.  If we
1772         // aren't we'll get the root of our little subtree (most likely
1773         // we'll just return 0).
1774         // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
1775         // be safe now to use it.
1776         while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
1777 #if ENABLE(SVG)
1778             // foreignObject is the containing block for its contents.
1779             if (o->isSVGForeignObject())
1780                 break;
1781 #endif
1782             // The render flow thread is the top most containing block
1783             // for the fixed positioned elements.
1784             if (o->isOutOfFlowRenderFlowThread())
1785                 break;
1786
1787             if (repaintContainerSkipped && o == repaintContainer)
1788                 *repaintContainerSkipped = true;
1789
1790             o = o->parent();
1791         }
1792     } else if (pos == AbsolutePosition) {
1793         // Same goes here.  We technically just want our containing block, but
1794         // we may not have one if we're part of an uninstalled subtree.  We'll
1795         // climb as high as we can though.
1796         while (o && o->style().position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
1797 #if ENABLE(SVG)
1798             if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
1799                 break;
1800 #endif
1801             if (repaintContainerSkipped && o == repaintContainer)
1802                 *repaintContainerSkipped = true;
1803
1804             o = o->parent();
1805         }
1806     }
1807
1808     return o;
1809 }
1810
1811 bool RenderObject::isSelectionBorder() const
1812 {
1813     SelectionState st = selectionState();
1814     return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
1815 }
1816
1817 inline void RenderObject::clearLayoutRootIfNeeded() const
1818 {
1819     if (documentBeingDestroyed())
1820         return;
1821
1822     if (view().frameView().layoutRoot() == this) {
1823         ASSERT_NOT_REACHED();
1824         // This indicates a failure to layout the child, which is why
1825         // the layout root is still set to |this|. Make sure to clear it
1826         // since we are getting destroyed.
1827         view().frameView().clearLayoutRoot();
1828     }
1829 }
1830
1831 void RenderObject::willBeDestroyed()
1832 {
1833     // For accessibility management, notify the parent of the imminent change to its child set.
1834     // We do it now, before remove(), while the parent pointer is still available.
1835     if (AXObjectCache* cache = document().existingAXObjectCache())
1836         cache->childrenChanged(this->parent());
1837
1838     removeFromParent();
1839
1840     ASSERT(documentBeingDestroyed() || !isRenderElement() || !view().frameView().hasSlowRepaintObject(toRenderElement(this)));
1841
1842     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
1843     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
1844     if (AXObjectCache* cache = document().existingAXObjectCache())
1845         cache->remove(this);
1846
1847 #ifndef NDEBUG
1848     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1849         // After remove, the object and the associated information should not be in any flow thread.
1850         const RenderNamedFlowThreadList* flowThreadList = view().flowThreadController().renderNamedFlowThreadList();
1851         for (RenderNamedFlowThreadList::const_iterator iter = flowThreadList->begin(); iter != flowThreadList->end(); ++iter) {
1852             const RenderNamedFlowThread* renderFlowThread = *iter;
1853             ASSERT(!renderFlowThread->hasChild(this));
1854             ASSERT(!renderFlowThread->hasChildInfo(this));
1855         }
1856     }
1857 #endif
1858
1859     // If this renderer had a parent, remove should have destroyed any counters
1860     // attached to this renderer and marked the affected other counters for
1861     // reevaluation. This apparently redundant check is here for the case when
1862     // this renderer had no parent at the time remove() was called.
1863
1864     if (hasCounterNodeMap())
1865         RenderCounter::destroyCounterNodes(this);
1866
1867     // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
1868     // be moved into RenderBoxModelObject::destroy.
1869     if (hasLayer()) {
1870         setHasLayer(false);
1871         toRenderLayerModelObject(this)->destroyLayer();
1872     }
1873
1874     clearLayoutRootIfNeeded();
1875 }
1876
1877 void RenderObject::insertedIntoTree()
1878 {
1879     // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
1880
1881     if (!isFloating() && parent()->childrenInline())
1882         parent()->dirtyLinesFromChangedChild(this);
1883
1884     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1885         containerFlowThread->addFlowChild(this);
1886 }
1887
1888 void RenderObject::willBeRemovedFromTree()
1889 {
1890     // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
1891
1892     removeFromRenderFlowThread();
1893
1894     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1895         containerFlowThread->removeFlowChild(this);
1896
1897 #if ENABLE(SVG)
1898     // Update cached boundaries in SVG renderers, if a child is removed.
1899     parent()->setNeedsBoundariesUpdate();
1900 #endif
1901 }
1902
1903 void RenderObject::removeFromRenderFlowThread()
1904 {
1905     if (flowThreadState() == NotInsideFlowThread)
1906         return;
1907     
1908     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
1909     // It's only until later when we actually destroy it and remove all the children from it. 
1910     // Currently, that happens for firstLetter elements and list markers.
1911     // Pass in the flow thread so that we don't have to look it up for all the children.
1912     removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
1913 }
1914
1915 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
1916 {
1917     for (RenderObject* child = firstChildSlow(); child; child = child->nextSibling())
1918         child->removeFromRenderFlowThreadRecursive(renderFlowThread);
1919
1920     RenderFlowThread* localFlowThread = renderFlowThread;
1921     if (flowThreadState() == InsideInFlowThread)
1922         localFlowThread = flowThreadContainingBlock(); // We have to ask. We can't just assume we are in the same flow thread.
1923     if (localFlowThread)
1924         localFlowThread->removeFlowChildInfo(this);
1925     setFlowThreadState(NotInsideFlowThread);
1926 }
1927
1928 void RenderObject::destroyAndCleanupAnonymousWrappers()
1929 {
1930     // If the tree is destroyed, there is no need for a clean-up phase.
1931     if (documentBeingDestroyed()) {
1932         destroy();
1933         return;
1934     }
1935
1936     RenderObject* destroyRoot = this;
1937     for (auto destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
1938         // Currently we only remove anonymous cells' and table sections' wrappers but we should remove all unneeded
1939         // wrappers. See http://webkit.org/b/52123 as an example where this is needed.
1940         if (!destroyRootParent->isTableCell() && !destroyRootParent->isTableSection())
1941             break;
1942
1943         if (destroyRootParent->firstChild() != this || destroyRootParent->lastChild() != this)
1944             break;
1945     }
1946
1947     destroyRoot->destroy();
1948
1949     // WARNING: |this| is deleted here.
1950 }
1951
1952 void RenderObject::destroy()
1953 {
1954 #if PLATFORM(IOS)
1955     if (hasLayer())
1956         toRenderBoxModelObject(this)->layer()->willBeDestroyed();
1957 #endif
1958
1959     willBeDestroyed();
1960     delete this;
1961 }
1962
1963 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&)
1964 {
1965     return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
1966 }
1967
1968 void RenderObject::updateDragState(bool dragOn)
1969 {
1970     bool valueChanged = (dragOn != isDragging());
1971     setIsDragging(dragOn);
1972     if (valueChanged && node() && (style().affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())))
1973         node()->setNeedsStyleRecalc();
1974     for (RenderObject* curr = firstChildSlow(); curr; curr = curr->nextSibling())
1975         curr->updateDragState(dragOn);
1976 }
1977
1978 bool RenderObject::isComposited() const
1979 {
1980     return hasLayer() && toRenderLayerModelObject(this)->layer()->isComposited();
1981 }
1982
1983 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
1984 {
1985     bool inside = false;
1986     if (hitTestFilter != HitTestSelf) {
1987         // First test the foreground layer (lines and inlines).
1988         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
1989
1990         // Test floats next.
1991         if (!inside)
1992             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
1993
1994         // Finally test to see if the mouse is in the background (within a child block's background).
1995         if (!inside)
1996             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
1997     }
1998
1999     // See if the mouse is inside us but not any of our descendants
2000     if (hitTestFilter != HitTestDescendants && !inside)
2001         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2002
2003     return inside;
2004 }
2005
2006 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2007 {
2008     if (result.innerNode())
2009         return;
2010
2011     Node* node = this->node();
2012
2013     // If we hit the anonymous renderers inside generated content we should
2014     // actually hit the generated content so walk up to the PseudoElement.
2015     if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2016         for (auto renderer = parent(); renderer && !node; renderer = renderer->parent())
2017             node = renderer->element();
2018     }
2019
2020     if (node) {
2021         result.setInnerNode(node);
2022         if (!result.innerNonSharedNode())
2023             result.setInnerNonSharedNode(node);
2024         result.setLocalPoint(point);
2025     }
2026 }
2027
2028 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2029 {
2030     return false;
2031 }
2032
2033 int RenderObject::innerLineHeight() const
2034 {
2035     return style().computedLineHeight();
2036 }
2037
2038 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2039 {
2040     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
2041         return 0;
2042
2043     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
2044     if (cachedStyle)
2045         return cachedStyle;
2046     
2047     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2048     if (result)
2049         return style().addCachedPseudoStyle(result.release());
2050     return 0;
2051 }
2052
2053 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2054 {
2055     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
2056         return 0;
2057     
2058     if (!parentStyle) {
2059         ASSERT(!ownStyle);
2060         parentStyle = &style();
2061     }
2062
2063     // FIXME: This "find nearest element parent" should be a helper function.
2064     Node* n = node();
2065     while (n && !n->isElementNode())
2066         n = n->parentNode();
2067     if (!n)
2068         return 0;
2069     Element* element = toElement(n);
2070
2071     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2072         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
2073         result->setStyleType(FIRST_LINE_INHERITED);
2074         return result.release();
2075     }
2076
2077     return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2078 }
2079
2080 static Color decorationColor(RenderStyle* style)
2081 {
2082     Color result;
2083     // Check for text decoration color first.
2084     result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
2085     if (result.isValid())
2086         return result;
2087     if (style->textStrokeWidth() > 0) {
2088         // Prefer stroke color if possible but not if it's fully transparent.
2089         result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2090         if (result.alpha())
2091             return result;
2092     }
2093     
2094     result = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2095     return result;
2096 }
2097
2098 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2099                                            Color& linethrough, bool quirksMode, bool firstlineStyle)
2100 {
2101     RenderObject* curr = this;
2102     RenderStyle* styleToUse = 0;
2103     TextDecoration currDecs = TextDecorationNone;
2104     Color resultColor;
2105     do {
2106         styleToUse = firstlineStyle ? &curr->firstLineStyle() : &curr->style();
2107         currDecs = styleToUse->textDecoration();
2108         resultColor = decorationColor(styleToUse);
2109         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2110         if (currDecs) {
2111             if (currDecs & TextDecorationUnderline) {
2112                 decorations &= ~TextDecorationUnderline;
2113                 underline = resultColor;
2114             }
2115             if (currDecs & TextDecorationOverline) {
2116                 decorations &= ~TextDecorationOverline;
2117                 overline = resultColor;
2118             }
2119             if (currDecs & TextDecorationLineThrough) {
2120                 decorations &= ~TextDecorationLineThrough;
2121                 linethrough = resultColor;
2122             }
2123         }
2124         if (curr->isRubyText())
2125             return;
2126         curr = curr->parent();
2127         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2128             curr = toRenderBlock(curr)->continuation();
2129     } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(curr->node()) && !curr->node()->hasTagName(fontTag))));
2130
2131     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2132     if (decorations && curr) {
2133         styleToUse = firstlineStyle ? &curr->firstLineStyle() : &curr->style();
2134         resultColor = decorationColor(styleToUse);
2135         if (decorations & TextDecorationUnderline)
2136             underline = resultColor;
2137         if (decorations & TextDecorationOverline)
2138             overline = resultColor;
2139         if (decorations & TextDecorationLineThrough)
2140             linethrough = resultColor;
2141     }
2142 }
2143
2144 #if ENABLE(DASHBOARD_SUPPORT)
2145 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2146 {
2147     // Convert the style regions to absolute coordinates.
2148     if (style().visibility() != VISIBLE || !isBox())
2149         return;
2150     
2151     RenderBox* box = toRenderBox(this);
2152     FloatPoint absPos = localToAbsolute();
2153
2154     const Vector<StyleDashboardRegion>& styleRegions = style().dashboardRegions();
2155     unsigned i, count = styleRegions.size();
2156     for (i = 0; i < count; i++) {
2157         StyleDashboardRegion styleRegion = styleRegions[i];
2158
2159         LayoutUnit w = box->width();
2160         LayoutUnit h = box->height();
2161
2162         AnnotatedRegionValue region;
2163         region.label = styleRegion.label;
2164         region.bounds = LayoutRect(styleRegion.offset.left().value(),
2165                                    styleRegion.offset.top().value(),
2166                                    w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2167                                    h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2168         region.type = styleRegion.type;
2169
2170         region.clip = region.bounds;
2171         computeAbsoluteRepaintRect(region.clip);
2172         if (region.clip.height() < 0) {
2173             region.clip.setHeight(0);
2174             region.clip.setWidth(0);
2175         }
2176
2177         region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2178         region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2179
2180         regions.append(region);
2181     }
2182 }
2183
2184 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2185 {
2186     // RenderTexts don't have their own style, they just use their parent's style,
2187     // so we don't want to include them.
2188     if (isText())
2189         return;
2190
2191     addAnnotatedRegions(regions);
2192     for (RenderObject* curr = toRenderElement(this)->firstChild(); curr; curr = curr->nextSibling())
2193         curr->collectAnnotatedRegions(regions);
2194 }
2195 #endif
2196
2197 bool RenderObject::willRenderImage(CachedImage*)
2198 {
2199     // Without visibility we won't render (and therefore don't care about animation).
2200     if (style().visibility() != VISIBLE)
2201         return false;
2202
2203 #if PLATFORM(IOS)
2204     if (document().frame()->timersPaused())
2205         return false;
2206 #else
2207     // We will not render a new image when Active DOM is suspended
2208     if (document().activeDOMObjectsAreSuspended())
2209         return false;
2210 #endif
2211
2212     // 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)
2213     // then we don't want to render either.
2214     return !document().inPageCache() && !document().view()->isOffscreen();
2215 }
2216
2217 int RenderObject::maximalOutlineSize(PaintPhase p) const
2218 {
2219     if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2220         return 0;
2221     return view().maximalOutlineSize();
2222 }
2223
2224 int RenderObject::caretMinOffset() const
2225 {
2226     return 0;
2227 }
2228
2229 int RenderObject::caretMaxOffset() const
2230 {
2231     if (isReplaced())
2232         return node() ? std::max(1U, node()->childNodeCount()) : 1;
2233     if (isHR())
2234         return 1;
2235     return 0;
2236 }
2237
2238 int RenderObject::previousOffset(int current) const
2239 {
2240     return current - 1;
2241 }
2242
2243 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2244 {
2245     return current - 1;
2246 }
2247
2248 int RenderObject::nextOffset(int current) const
2249 {
2250     return current + 1;
2251 }
2252
2253 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
2254 {
2255     int outlineSize = outlineStyleForRepaint().outlineSize();
2256     if (const ShadowData* boxShadow = style().boxShadow()) {
2257         boxShadow->adjustRectForShadow(rect, outlineSize);
2258         return;
2259     }
2260
2261     rect.inflate(outlineSize);
2262 }
2263
2264 AnimationController& RenderObject::animation() const
2265 {
2266     return frame().animation();
2267 }
2268
2269 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
2270 {
2271     imageChanged(static_cast<WrappedImagePtr>(image), rect);
2272 }
2273
2274 RenderBoxModelObject* RenderObject::offsetParent() const
2275 {
2276     // If any of the following holds true return null and stop this algorithm:
2277     // A is the root element.
2278     // A is the HTML body element.
2279     // The computed value of the position property for element A is fixed.
2280     if (isRoot() || isBody() || (isOutOfFlowPositioned() && style().position() == FixedPosition))
2281         return 0;
2282
2283     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
2284     // chain return the nearest ancestor map HTML element and stop this algorithm.
2285     // FIXME: Implement!
2286     
2287     // Return the nearest ancestor element of A for which at least one of the following is
2288     // true and stop this algorithm if such an ancestor is found:
2289     //     * The computed value of the position property is not static.
2290     //     * It is the HTML body element.
2291     //     * The computed value of the position property of A is static and the ancestor
2292     //       is one of the following HTML elements: td, th, or table.
2293     //     * Our own extension: if there is a difference in the effective zoom
2294
2295     bool skipTables = isPositioned();
2296     float currZoom = style().effectiveZoom();
2297     auto curr = parent();
2298     while (curr && (!curr->element() || (!curr->isPositioned() && !curr->isBody())) && !curr->isRenderNamedFlowThread()) {
2299         Element* element = curr->element();
2300         if (!skipTables && element && (isHTMLTableElement(element) || element->hasTagName(tdTag) || element->hasTagName(thTag)))
2301             break;
2302  
2303         float newZoom = curr->style().effectiveZoom();
2304         if (currZoom != newZoom)
2305             break;
2306         currZoom = newZoom;
2307         curr = curr->parent();
2308     }
2309     
2310     // CSS regions specification says that region flows should return the body element as their offsetParent.
2311     if (curr && curr->isRenderNamedFlowThread())
2312         curr = document().body() ? document().body()->renderer() : 0;
2313     
2314     return curr && curr->isBoxModelObject() ? toRenderBoxModelObject(curr) : 0;
2315 }
2316
2317 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity) const
2318 {
2319     // If this is a non-anonymous renderer in an editable area, then it's simple.
2320     if (Node* node = nonPseudoNode()) {
2321         if (!node->hasEditableStyle()) {
2322             // If it can be found, we prefer a visually equivalent position that is editable. 
2323             Position position = createLegacyEditingPosition(node, offset);
2324             Position candidate = position.downstream(CanCrossEditingBoundary);
2325             if (candidate.deprecatedNode()->hasEditableStyle())
2326                 return VisiblePosition(candidate, affinity);
2327             candidate = position.upstream(CanCrossEditingBoundary);
2328             if (candidate.deprecatedNode()->hasEditableStyle())
2329                 return VisiblePosition(candidate, affinity);
2330         }
2331         // FIXME: Eliminate legacy editing positions
2332         return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
2333     }
2334
2335     // We don't want to cross the boundary between editable and non-editable
2336     // regions of the document, but that is either impossible or at least
2337     // extremely unlikely in any normal case because we stop as soon as we
2338     // find a single non-anonymous renderer.
2339
2340     // Find a nearby non-anonymous renderer.
2341     const RenderObject* child = this;
2342     while (const auto parent = child->parent()) {
2343         // Find non-anonymous content after.
2344         const RenderObject* renderer = child;
2345         while ((renderer = renderer->nextInPreOrder(parent))) {
2346             if (Node* node = renderer->nonPseudoNode())
2347                 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2348         }
2349
2350         // Find non-anonymous content before.
2351         renderer = child;
2352         while ((renderer = renderer->previousInPreOrder())) {
2353             if (renderer == parent)
2354                 break;
2355             if (Node* node = renderer->nonPseudoNode())
2356                 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
2357         }
2358
2359         // Use the parent itself unless it too is anonymous.
2360         if (Element* element = parent->nonPseudoElement())
2361             return VisiblePosition(firstPositionInOrBeforeNode(element), DOWNSTREAM);
2362
2363         // Repeat at the next level up.
2364         child = parent;
2365     }
2366
2367     // Everything was anonymous. Give up.
2368     return VisiblePosition();
2369 }
2370
2371 VisiblePosition RenderObject::createVisiblePosition(const Position& position) const
2372 {
2373     if (position.isNotNull())
2374         return VisiblePosition(position);
2375
2376     ASSERT(!node());
2377     return createVisiblePosition(0, DOWNSTREAM);
2378 }
2379
2380 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
2381 {
2382     return SetCursorBasedOnStyle;
2383 }
2384
2385 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
2386 {
2387     if (needsLayout())
2388         return false;
2389
2390     RenderBlock* containingBlock = this->containingBlock();
2391     return containingBlock ? !containingBlock->needsLayout() : true;
2392 }
2393
2394 // We only create "generated" child renderers like one for first-letter if:
2395 // - the firstLetterBlock can have children in the DOM and
2396 // - the block doesn't have any special assumption on its text children.
2397 // This correctly prevents form controls from having such renderers.
2398 bool RenderObject::canHaveGeneratedChildren() const
2399 {
2400     return canHaveChildren();
2401 }
2402
2403 Node* RenderObject::generatingPseudoHostElement() const
2404 {
2405     return toPseudoElement(node())->hostElement();
2406 }
2407
2408 bool RenderObject::canBeReplacedWithInlineRunIn() const
2409 {
2410     return true;
2411 }
2412
2413 #if ENABLE(SVG)
2414
2415 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
2416 {
2417     ASSERT_NOT_REACHED();
2418     return 0;
2419 }
2420
2421 void RenderObject::setNeedsBoundariesUpdate()
2422 {
2423     if (auto renderer = parent())
2424         renderer->setNeedsBoundariesUpdate();
2425 }
2426
2427 FloatRect RenderObject::objectBoundingBox() const
2428 {
2429     ASSERT_NOT_REACHED();
2430     return FloatRect();
2431 }
2432
2433 FloatRect RenderObject::strokeBoundingBox() const
2434 {
2435     ASSERT_NOT_REACHED();
2436     return FloatRect();
2437 }
2438
2439 // Returns the smallest rectangle enclosing all of the painted content
2440 // respecting clipping, masking, filters, opacity, stroke-width and markers
2441 FloatRect RenderObject::repaintRectInLocalCoordinates() const
2442 {
2443     ASSERT_NOT_REACHED();
2444     return FloatRect();
2445 }
2446
2447 AffineTransform RenderObject::localTransform() const
2448 {
2449     static const AffineTransform identity;
2450     return identity;
2451 }
2452
2453 const AffineTransform& RenderObject::localToParentTransform() const
2454 {
2455     static const AffineTransform identity;
2456     return identity;
2457 }
2458
2459 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2460 {
2461     ASSERT_NOT_REACHED();
2462     return false;
2463 }
2464
2465 #endif // ENABLE(SVG)
2466
2467 } // namespace WebCore
2468
2469 #ifndef NDEBUG
2470
2471 void showTree(const WebCore::RenderObject* object)
2472 {
2473     if (object)
2474         object->showTreeForThis();
2475 }
2476
2477 void showLineTree(const WebCore::RenderObject* object)
2478 {
2479     if (object)
2480         object->showLineTreeForThis();
2481 }
2482
2483 void showRenderTree(const WebCore::RenderObject* object1)
2484 {
2485     showRenderTree(object1, 0);
2486 }
2487
2488 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
2489 {
2490     if (object1) {
2491         const WebCore::RenderObject* root = object1;
2492         while (root->parent())
2493             root = root->parent();
2494         root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
2495     }
2496 }
2497
2498 #endif