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