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