bbb3fb5c1144d5120e837e16cccff0f0ddb57cf6
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / 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 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 "core/rendering/RenderObject.h"
29
30 #include "HTMLNames.h"
31 #include "RuntimeEnabledFeatures.h"
32 #include "core/accessibility/AXObjectCache.h"
33 #include "core/animation/ActiveAnimations.h"
34 #include "core/css/resolver/StyleResolver.h"
35 #include "core/editing/EditingBoundary.h"
36 #include "core/editing/FrameSelection.h"
37 #include "core/editing/htmlediting.h"
38 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
39 #include "core/fetch/ResourceLoader.h"
40 #include "core/frame/FrameView.h"
41 #include "core/frame/LocalFrame.h"
42 #include "core/html/HTMLAnchorElement.h"
43 #include "core/html/HTMLElement.h"
44 #include "core/html/HTMLHtmlElement.h"
45 #include "core/html/HTMLTableCellElement.h"
46 #include "core/html/HTMLTableElement.h"
47 #include "core/page/AutoscrollController.h"
48 #include "core/page/EventHandler.h"
49 #include "core/page/Page.h"
50 #include "core/frame/Settings.h"
51 #include "core/frame/UseCounter.h"
52 #include "core/rendering/FlowThreadController.h"
53 #include "core/rendering/HitTestResult.h"
54 #include "core/rendering/LayoutRectRecorder.h"
55 #include "core/rendering/RenderCounter.h"
56 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
57 #include "core/rendering/RenderFlexibleBox.h"
58 #include "core/rendering/RenderFlowThread.h"
59 #include "core/rendering/RenderGeometryMap.h"
60 #include "core/rendering/RenderGrid.h"
61 #include "core/rendering/RenderImage.h"
62 #include "core/rendering/RenderImageResourceStyleImage.h"
63 #include "core/rendering/RenderInline.h"
64 #include "core/rendering/RenderLayer.h"
65 #include "core/rendering/RenderListItem.h"
66 #include "core/rendering/RenderMarquee.h"
67 #include "core/rendering/RenderScrollbarPart.h"
68 #include "core/rendering/RenderTableCaption.h"
69 #include "core/rendering/RenderTableCell.h"
70 #include "core/rendering/RenderTableCol.h"
71 #include "core/rendering/RenderTableRow.h"
72 #include "core/rendering/RenderTheme.h"
73 #include "core/rendering/RenderView.h"
74 #include "core/rendering/compositing/CompositedLayerMapping.h"
75 #include "core/rendering/compositing/RenderLayerCompositor.h"
76 #include "core/rendering/style/ContentData.h"
77 #include "core/rendering/style/CursorList.h"
78 #include "core/rendering/style/ShadowList.h"
79 #include "core/rendering/svg/SVGRenderSupport.h"
80 #include "platform/Partitions.h"
81 #include "platform/geometry/TransformState.h"
82 #include "platform/graphics/GraphicsContext.h"
83 #include "wtf/RefCountedLeakCounter.h"
84 #include "wtf/text/StringBuilder.h"
85 #include <algorithm>
86 #ifndef NDEBUG
87 #include <stdio.h>
88 #endif
89
90 using namespace std;
91
92 namespace WebCore {
93
94 using namespace HTMLNames;
95
96 #ifndef NDEBUG
97
98 RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject)
99     : m_renderObject(renderObject)
100     , m_preexistingForbidden(m_renderObject->isSetNeedsLayoutForbidden())
101 {
102     m_renderObject->setNeedsLayoutIsForbidden(true);
103 }
104
105 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
106 {
107     m_renderObject->setNeedsLayoutIsForbidden(m_preexistingForbidden);
108 }
109 #endif
110
111 struct SameSizeAsRenderObject {
112     virtual ~SameSizeAsRenderObject() { } // Allocate vtable pointer.
113     void* pointers[5];
114 #ifndef NDEBUG
115     unsigned m_debugBitfields : 2;
116 #endif
117     unsigned m_bitfields;
118     unsigned m_bitfields2;
119     LayoutRect rects[2]; // Stores the old/new repaint rects.
120 };
121
122 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
123
124 bool RenderObject::s_affectsParentBlock = false;
125
126 void* RenderObject::operator new(size_t sz)
127 {
128     ASSERT(isMainThread());
129     return partitionAlloc(Partitions::getRenderingPartition(), sz);
130 }
131
132 void RenderObject::operator delete(void* ptr)
133 {
134     ASSERT(isMainThread());
135     partitionFree(ptr);
136 }
137
138 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
139 {
140     // Minimal support for content properties replacing an entire element.
141     // Works only if we have exactly one piece of content and it's a URL.
142     // Otherwise acts as if we didn't support this feature.
143     const ContentData* contentData = style->contentData();
144     if (contentData && !contentData->next() && contentData->isImage() && !element->isPseudoElement()) {
145         RenderImage* image = new RenderImage(element);
146         // RenderImageResourceStyleImage requires a style being present on the image but we don't want to
147         // trigger a style change now as the node is not fully attached. Moving this code to style change
148         // doesn't make sense as it should be run once at renderer creation.
149         image->setStyleInternal(style);
150         if (const StyleImage* styleImage = static_cast<const ImageContentData*>(contentData)->image()) {
151             image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
152             image->setIsGeneratedContent();
153         } else
154             image->setImageResource(RenderImageResource::create());
155         image->setStyleInternal(nullptr);
156         return image;
157     }
158
159     switch (style->display()) {
160     case NONE:
161         return 0;
162     case INLINE:
163         return new RenderInline(element);
164     case BLOCK:
165     case INLINE_BLOCK:
166         return new RenderBlockFlow(element);
167     case LIST_ITEM:
168         return new RenderListItem(element);
169     case TABLE:
170     case INLINE_TABLE:
171         return new RenderTable(element);
172     case TABLE_ROW_GROUP:
173     case TABLE_HEADER_GROUP:
174     case TABLE_FOOTER_GROUP:
175         return new RenderTableSection(element);
176     case TABLE_ROW:
177         return new RenderTableRow(element);
178     case TABLE_COLUMN_GROUP:
179     case TABLE_COLUMN:
180         return new RenderTableCol(element);
181     case TABLE_CELL:
182         return new RenderTableCell(element);
183     case TABLE_CAPTION:
184         return new RenderTableCaption(element);
185     case BOX:
186     case INLINE_BOX:
187         return new RenderDeprecatedFlexibleBox(element);
188     case FLEX:
189     case INLINE_FLEX:
190         return new RenderFlexibleBox(element);
191     case GRID:
192     case INLINE_GRID:
193         return new RenderGrid(element);
194     }
195
196     return 0;
197 }
198
199 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
200
201 RenderObject::RenderObject(Node* node)
202     : ImageResourceClient()
203     , m_style(nullptr)
204     , m_node(node)
205     , m_parent(0)
206     , m_previous(0)
207     , m_next(0)
208 #ifndef NDEBUG
209     , m_hasAXObject(false)
210     , m_setNeedsLayoutForbidden(false)
211 #endif
212     , m_bitfields(node)
213 {
214 #ifndef NDEBUG
215     renderObjectCounter.increment();
216 #endif
217 }
218
219 RenderObject::~RenderObject()
220 {
221     ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
222 #ifndef NDEBUG
223     ASSERT(!m_hasAXObject);
224     renderObjectCounter.decrement();
225 #endif
226 }
227
228 String RenderObject::debugName() const
229 {
230     StringBuilder name;
231     name.append(renderName());
232
233     if (Node* node = this->node()) {
234         name.append(' ');
235         name.append(node->debugName());
236     }
237
238     return name.toString();
239 }
240
241 bool RenderObject::isDescendantOf(const RenderObject* obj) const
242 {
243     for (const RenderObject* r = this; r; r = r->m_parent) {
244         if (r == obj)
245             return true;
246     }
247     return false;
248 }
249
250 bool RenderObject::isBody() const
251 {
252     return isHTMLBodyElement(node());
253 }
254
255 bool RenderObject::isHR() const
256 {
257     return isHTMLHRElement(node());
258 }
259
260 bool RenderObject::isLegend() const
261 {
262     return isHTMLLegendElement(node());
263 }
264
265 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
266 {
267     for (RenderObject *object = this; object; object = object->nextInPreOrder(this)) {
268         // If object is a fragmentation context it already updated the descendants flag accordingly.
269         if (object->isRenderFlowThread())
270             continue;
271         ASSERT(state != object->flowThreadState());
272         object->setFlowThreadState(state);
273     }
274 }
275
276 bool RenderObject::requiresAnonymousTableWrappers(const RenderObject* newChild) const
277 {
278     // Check should agree with:
279     // CSS 2.1 Tables: 17.2.1 Anonymous table objects
280     // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
281     if (newChild->isRenderTableCol()) {
282         const RenderTableCol* newTableColumn = toRenderTableCol(newChild);
283         bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isRenderTableCol();
284         return !isTable() && !isColumnInColumnGroup;
285     } else if (newChild->isTableCaption())
286         return !isTable();
287     else if (newChild->isTableSection())
288         return !isTable();
289     else if (newChild->isTableRow())
290         return !isTableSection();
291     else if (newChild->isTableCell())
292         return !isTableRow();
293     return false;
294 }
295
296 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
297 {
298     RenderObjectChildList* children = virtualChildren();
299     ASSERT(children);
300     if (!children)
301         return;
302
303     if (requiresAnonymousTableWrappers(newChild)) {
304         // Generate an anonymous table or reuse existing one from previous child
305         // Per: 17.2.1 Anonymous table objects 3. Generate missing parents
306         // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
307         RenderTable* table;
308         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
309         if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent())
310             table = toRenderTable(afterChild);
311         else {
312             table = RenderTable::createAnonymousWithParentRenderer(this);
313             addChild(table, beforeChild);
314         }
315         table->addChild(newChild);
316     } else
317         children->insertChildNode(this, newChild, beforeChild);
318
319     if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE)
320         toRenderText(newChild)->transformText();
321
322     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
323     // <g>s to have renderers - at least that's how our implementation works. Consider:
324     // <g display="none"><foreignObject><body style="position: relative">FOO...
325     // - layerTypeRequired() would return true for the <body>, creating a new RenderLayer
326     // - when the document is painted, both layers are painted. The <body> layer doesn't
327     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
328     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
329     // and stop creating layers at all for these cases - they're not used anyways.
330     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
331         toRenderLayerModelObject(newChild)->layer()->removeOnlyThisLayer();
332 }
333
334 void RenderObject::removeChild(RenderObject* oldChild)
335 {
336     RenderObjectChildList* children = virtualChildren();
337     ASSERT(children);
338     if (!children)
339         return;
340
341     children->removeChildNode(this, oldChild);
342 }
343
344 RenderObject* RenderObject::nextInPreOrder() const
345 {
346     if (RenderObject* o = firstChild())
347         return o;
348
349     return nextInPreOrderAfterChildren();
350 }
351
352 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
353 {
354     RenderObject* o;
355     if (!(o = nextSibling())) {
356         o = parent();
357         while (o && !o->nextSibling())
358             o = o->parent();
359         if (o)
360             o = o->nextSibling();
361     }
362
363     return o;
364 }
365
366 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
367 {
368     if (RenderObject* o = firstChild())
369         return o;
370
371     return nextInPreOrderAfterChildren(stayWithin);
372 }
373
374 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
375 {
376     if (this == stayWithin)
377         return 0;
378
379     const RenderObject* current = this;
380     RenderObject* next;
381     while (!(next = current->nextSibling())) {
382         current = current->parent();
383         if (!current || current == stayWithin)
384             return 0;
385     }
386     return next;
387 }
388
389 RenderObject* RenderObject::previousInPreOrder() const
390 {
391     if (RenderObject* o = previousSibling()) {
392         while (o->lastChild())
393             o = o->lastChild();
394         return o;
395     }
396
397     return parent();
398 }
399
400 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
401 {
402     if (this == stayWithin)
403         return 0;
404
405     return previousInPreOrder();
406 }
407
408 RenderObject* RenderObject::childAt(unsigned index) const
409 {
410     RenderObject* child = firstChild();
411     for (unsigned i = 0; child && i < index; i++)
412         child = child->nextSibling();
413     return child;
414 }
415
416 RenderObject* RenderObject::lastLeafChild() const
417 {
418     RenderObject* r = lastChild();
419     while (r) {
420         RenderObject* n = 0;
421         n = r->lastChild();
422         if (!n)
423             break;
424         r = n;
425     }
426     return r;
427 }
428
429 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
430                       RenderLayer*& beforeChild)
431 {
432     if (obj->hasLayer()) {
433         if (!beforeChild && newObject) {
434             // We need to figure out the layer that follows newObject. We only do
435             // this the first time we find a child layer, and then we update the
436             // pointer values for newObject and beforeChild used by everyone else.
437             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
438             newObject = 0;
439         }
440         parentLayer->addChild(toRenderLayerModelObject(obj)->layer(), beforeChild);
441         return;
442     }
443
444     for (RenderObject* curr = obj->firstChild(); curr; curr = curr->nextSibling())
445         addLayers(curr, parentLayer, newObject, beforeChild);
446 }
447
448 void RenderObject::addLayers(RenderLayer* parentLayer)
449 {
450     if (!parentLayer)
451         return;
452
453     RenderObject* object = this;
454     RenderLayer* beforeChild = 0;
455     WebCore::addLayers(this, parentLayer, object, beforeChild);
456 }
457
458 void RenderObject::removeLayers(RenderLayer* parentLayer)
459 {
460     if (!parentLayer)
461         return;
462
463     if (hasLayer()) {
464         parentLayer->removeChild(toRenderLayerModelObject(this)->layer());
465         return;
466     }
467
468     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
469         curr->removeLayers(parentLayer);
470 }
471
472 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
473 {
474     if (!newParent)
475         return;
476
477     if (hasLayer()) {
478         RenderLayer* layer = toRenderLayerModelObject(this)->layer();
479         ASSERT(oldParent == layer->parent());
480         if (oldParent)
481             oldParent->removeChild(layer);
482         newParent->addChild(layer);
483         return;
484     }
485
486     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
487         curr->moveLayers(oldParent, newParent);
488 }
489
490 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
491                                          bool checkParent)
492 {
493     // Error check the parent layer passed in. If it's null, we can't find anything.
494     if (!parentLayer)
495         return 0;
496
497     // Step 1: If our layer is a child of the desired parent, then return our layer.
498     RenderLayer* ourLayer = hasLayer() ? toRenderLayerModelObject(this)->layer() : 0;
499     if (ourLayer && ourLayer->parent() == parentLayer)
500         return ourLayer;
501
502     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
503     // into our siblings trying to find the next layer whose parent is the desired parent.
504     if (!ourLayer || ourLayer == parentLayer) {
505         for (RenderObject* curr = startPoint ? startPoint->nextSibling() : firstChild();
506              curr; curr = curr->nextSibling()) {
507             RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
508             if (nextLayer)
509                 return nextLayer;
510         }
511     }
512
513     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
514     // find anything.
515     if (parentLayer == ourLayer)
516         return 0;
517
518     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
519     // follow us to see if we can locate a layer.
520     if (checkParent && parent())
521         return parent()->findNextLayer(parentLayer, this, true);
522
523     return 0;
524 }
525
526 RenderLayer* RenderObject::enclosingLayer() const
527 {
528     for (const RenderObject* current = this; current; current = current->parent()) {
529         if (current->hasLayer())
530             return toRenderLayerModelObject(current)->layer();
531     }
532     // FIXME: We should remove the one caller that triggers this case and make
533     // this function return a reference.
534     ASSERT(!m_parent && !isRenderView());
535     return 0;
536 }
537
538 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
539 {
540     RenderBox* enclosingBox = this->enclosingBox();
541     if (!enclosingBox)
542         return false;
543
544     enclosingBox->scrollRectToVisible(rect, alignX, alignY);
545     return true;
546 }
547
548 RenderBox* RenderObject::enclosingBox() const
549 {
550     RenderObject* curr = const_cast<RenderObject*>(this);
551     while (curr) {
552         if (curr->isBox())
553             return toRenderBox(curr);
554         curr = curr->parent();
555     }
556
557     ASSERT_NOT_REACHED();
558     return 0;
559 }
560
561 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
562 {
563     RenderObject* curr = const_cast<RenderObject*>(this);
564     while (curr) {
565         if (curr->isBoxModelObject())
566             return toRenderBoxModelObject(curr);
567         curr = curr->parent();
568     }
569
570     ASSERT_NOT_REACHED();
571     return 0;
572 }
573
574 RenderBox* RenderObject::enclosingScrollableBox() const
575 {
576     for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
577         if (!ancestor->isBox())
578             continue;
579
580         RenderBox* ancestorBox = toRenderBox(ancestor);
581         if (ancestorBox->canBeScrolledAndHasScrollableArea())
582             return ancestorBox;
583     }
584
585     return 0;
586 }
587
588 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
589 {
590     ASSERT(flowThreadState() != NotInsideFlowThread);
591
592     // See if we have the thread cached because we're in the middle of layout.
593     RenderFlowThread* flowThread = view()->flowThreadController()->currentRenderFlowThread();
594     if (flowThread)
595         return flowThread;
596
597     // Not in the middle of layout so have to find the thread the slow way.
598     RenderObject* curr = const_cast<RenderObject*>(this);
599     while (curr) {
600         if (curr->isRenderFlowThread())
601             return toRenderFlowThread(curr);
602         curr = curr->containingBlock();
603     }
604     return 0;
605 }
606
607 RenderBlock* RenderObject::firstLineBlock() const
608 {
609     return 0;
610 }
611
612 static inline bool objectIsRelayoutBoundary(const RenderObject* object)
613 {
614     // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
615     if (object->isTextControl())
616         return true;
617
618     if (object->isSVGRoot())
619         return true;
620
621     if (!object->hasOverflowClip())
622         return false;
623
624     if (object->style()->width().isIntrinsicOrAuto() || object->style()->height().isIntrinsicOrAuto() || object->style()->height().isPercent())
625         return false;
626
627     // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
628     if (object->isTablePart())
629         return false;
630
631     return true;
632 }
633
634 void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot, SubtreeLayoutScope* layouter)
635 {
636     ASSERT(!scheduleRelayout || !newRoot);
637     ASSERT(!isSetNeedsLayoutForbidden());
638     ASSERT(!layouter || this != layouter->root());
639
640     RenderObject* object = container();
641     RenderObject* last = this;
642
643     bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
644
645     while (object) {
646         if (object->selfNeedsLayout())
647             return;
648
649         // Don't mark the outermost object of an unrooted subtree. That object will be
650         // marked when the subtree is added to the document.
651         RenderObject* container = object->container();
652         if (!container && !object->isRenderView())
653             return;
654         if (!last->isText() && last->style()->hasOutOfFlowPosition()) {
655             bool willSkipRelativelyPositionedInlines = !object->isRenderBlock() || object->isAnonymousBlock();
656             // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
657             while (object && (!object->isRenderBlock() || object->isAnonymousBlock()))
658                 object = object->container();
659             if (!object || object->posChildNeedsLayout())
660                 return;
661             if (willSkipRelativelyPositionedInlines)
662                 container = object->container();
663             object->setPosChildNeedsLayout(true);
664             simplifiedNormalFlowLayout = true;
665             ASSERT(!object->isSetNeedsLayoutForbidden());
666         } else if (simplifiedNormalFlowLayout) {
667             if (object->needsSimplifiedNormalFlowLayout())
668                 return;
669             object->setNeedsSimplifiedNormalFlowLayout(true);
670             ASSERT(!object->isSetNeedsLayoutForbidden());
671         } else {
672             if (object->normalChildNeedsLayout())
673                 return;
674             object->setNormalChildNeedsLayout(true);
675             ASSERT(!object->isSetNeedsLayoutForbidden());
676         }
677
678         if (layouter) {
679             layouter->addRendererToLayout(object);
680             if (object == layouter->root())
681                 return;
682         }
683
684         if (object == newRoot)
685             return;
686
687         last = object;
688         if (scheduleRelayout && objectIsRelayoutBoundary(last))
689             break;
690         object = container;
691     }
692
693     if (scheduleRelayout)
694         last->scheduleRelayout();
695 }
696
697 #ifndef NDEBUG
698 void RenderObject::checkBlockPositionedObjectsNeedLayout()
699 {
700     ASSERT(!needsLayout());
701
702     if (isRenderBlock())
703         toRenderBlock(this)->checkPositionedObjectsNeedLayout();
704 }
705 #endif
706
707 void RenderObject::setPreferredLogicalWidthsDirty(MarkingBehavior markParents)
708 {
709     bool alreadyDirty = preferredLogicalWidthsDirty();
710     m_bitfields.setPreferredLogicalWidthsDirty(true);
711     if (!alreadyDirty && markParents == MarkContainingBlockChain && (isText() || !style()->hasOutOfFlowPosition()))
712         invalidateContainerPreferredLogicalWidths();
713 }
714
715 void RenderObject::clearPreferredLogicalWidthsDirty()
716 {
717     m_bitfields.setPreferredLogicalWidthsDirty(false);
718 }
719
720 void RenderObject::invalidateContainerPreferredLogicalWidths()
721 {
722     // In order to avoid pathological behavior when inlines are deeply nested, we do include them
723     // in the chain that we mark dirty (even though they're kind of irrelevant).
724     RenderObject* o = isTableCell() ? containingBlock() : container();
725     while (o && !o->preferredLogicalWidthsDirty()) {
726         // Don't invalidate the outermost object of an unrooted subtree. That object will be
727         // invalidated when the subtree is added to the document.
728         RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
729         if (!container && !o->isRenderView())
730             break;
731
732         o->m_bitfields.setPreferredLogicalWidthsDirty(true);
733         if (o->style()->hasOutOfFlowPosition())
734             // A positioned object has no effect on the min/max width of its containing block ever.
735             // We can optimize this case and not go up any further.
736             break;
737         o = container;
738     }
739 }
740
741 void RenderObject::setLayerNeedsFullRepaint()
742 {
743     ASSERT(hasLayer());
744     if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
745         setShouldDoFullRepaintAfterLayout(true);
746     else
747         toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaint);
748 }
749
750 void RenderObject::setLayerNeedsFullRepaintForPositionedMovementLayout()
751 {
752     ASSERT(hasLayer());
753     toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
754 }
755
756 RenderBlock* RenderObject::containerForFixedPosition(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
757 {
758     ASSERT(!repaintContainerSkipped || !*repaintContainerSkipped);
759     ASSERT(!isText());
760     ASSERT(style()->position() == FixedPosition);
761
762     RenderObject* ancestor = parent();
763     for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
764         if (repaintContainerSkipped && ancestor == repaintContainer)
765             *repaintContainerSkipped = true;
766     }
767
768     ASSERT(!ancestor || !ancestor->isAnonymousBlock());
769     return toRenderBlock(ancestor);
770 }
771
772 RenderBlock* RenderObject::containingBlock() const
773 {
774     RenderObject* o = parent();
775     if (!o && isRenderScrollbarPart())
776         o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
777     if (!isText() && m_style->position() == FixedPosition) {
778         return containerForFixedPosition();
779     } else if (!isText() && m_style->position() == AbsolutePosition) {
780         while (o) {
781             // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
782             // to return the inline itself.  This allows us to avoid having a positioned objects
783             // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
784             // from this method.  The container() method can actually be used to obtain the
785             // inline directly.
786             if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
787                 break;
788
789             if (o->canContainAbsolutePositionObjects())
790                 break;
791
792             if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
793                 o = o->containingBlock();
794                 break;
795             }
796
797             o = o->parent();
798         }
799
800         if (o && !o->isRenderBlock())
801             o = o->containingBlock();
802
803         while (o && o->isAnonymousBlock())
804             o = o->containingBlock();
805     } else {
806         while (o && ((o->isInline() && !o->isReplaced()) || !o->isRenderBlock()))
807             o = o->parent();
808     }
809
810     if (!o || !o->isRenderBlock())
811         return 0; // This can still happen in case of an orphaned tree
812
813     return toRenderBlock(o);
814 }
815
816 RenderObject* RenderObject::clippingContainer() const
817 {
818     RenderObject* container = const_cast<RenderObject*>(this);
819     while (container) {
820         if (container->style()->position() == FixedPosition) {
821             for (container = container->parent(); container && !container->canContainFixedPositionObjects(); container = container->parent()) {
822                 // CSS clip applies to fixed position elements even for ancestors that are not what the
823                 // fixed element is positioned with respect to.
824                 if (container->hasClip())
825                     return container;
826             }
827         } else {
828             container = container->containingBlock();
829         }
830
831         if (!container)
832             return 0;
833         if (container->hasClipOrOverflowClip())
834             return container;
835     }
836     return 0;
837 }
838
839 static bool mustRepaintFillLayers(const RenderObject* renderer, const FillLayer* layer)
840 {
841     // Nobody will use multiple layers without wanting fancy positioning.
842     if (layer->next())
843         return true;
844
845     // Make sure we have a valid image.
846     StyleImage* img = layer->image();
847     if (!img || !img->canRender(renderer, renderer->style()->effectiveZoom()))
848         return false;
849
850     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
851         return true;
852
853     EFillSizeType sizeType = layer->sizeType();
854
855     if (sizeType == Contain || sizeType == Cover)
856         return true;
857
858     if (sizeType == SizeLength) {
859         if (layer->sizeLength().width().isPercent() || layer->sizeLength().height().isPercent())
860             return true;
861         if (img->isGeneratedImage() && (layer->sizeLength().width().isAuto() || layer->sizeLength().height().isAuto()))
862             return true;
863     } else if (img->usesImageContainerSize()) {
864         return true;
865     }
866
867     return false;
868 }
869
870 bool RenderObject::borderImageIsLoadedAndCanBeRendered() const
871 {
872     ASSERT(style()->hasBorder());
873
874     StyleImage* borderImage = style()->borderImage().image();
875     return borderImage && borderImage->canRender(this, style()->effectiveZoom()) && borderImage->isLoaded();
876 }
877
878 bool RenderObject::mustRepaintBackgroundOrBorder() const
879 {
880     if (hasMask() && mustRepaintFillLayers(this, style()->maskLayers()))
881         return true;
882
883     // If we don't have a background/border/mask, then nothing to do.
884     if (!hasBoxDecorations())
885         return false;
886
887     if (mustRepaintFillLayers(this, style()->backgroundLayers()))
888         return true;
889
890     // Our fill layers are ok.  Let's check border.
891     if (style()->hasBorder() && borderImageIsLoadedAndCanBeRendered())
892         return true;
893
894     return false;
895 }
896
897 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
898                                       BoxSide side, Color color, EBorderStyle style,
899                                       int adjacentWidth1, int adjacentWidth2, bool antialias)
900 {
901     int thickness;
902     int length;
903     if (side == BSTop || side == BSBottom) {
904         thickness = y2 - y1;
905         length = x2 - x1;
906     } else {
907         thickness = x2 - x1;
908         length = y2 - y1;
909     }
910
911     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
912     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
913     if (!thickness || !length)
914         return;
915
916     if (style == DOUBLE && thickness < 3)
917         style = SOLID;
918
919     switch (style) {
920     case BNONE:
921     case BHIDDEN:
922         return;
923     case DOTTED:
924     case DASHED:
925         drawDashedOrDottedBoxSide(graphicsContext, x1, y1, x2, y2, side,
926             color, thickness, style, antialias);
927         break;
928     case DOUBLE:
929         drawDoubleBoxSide(graphicsContext, x1, y1, x2, y2, length, side, color,
930             thickness, adjacentWidth1, adjacentWidth2, antialias);
931         break;
932     case RIDGE:
933     case GROOVE:
934         drawRidgeOrGrooveBoxSide(graphicsContext, x1, y1, x2, y2, side, color,
935             style, adjacentWidth1, adjacentWidth2, antialias);
936         break;
937     case INSET:
938         // FIXME: Maybe we should lighten the colors on one side like Firefox.
939         // https://bugs.webkit.org/show_bug.cgi?id=58608
940         if (side == BSTop || side == BSLeft)
941             color = color.dark();
942         // fall through
943     case OUTSET:
944         if (style == OUTSET && (side == BSBottom || side == BSRight))
945             color = color.dark();
946         // fall through
947     case SOLID:
948         drawSolidBoxSide(graphicsContext, x1, y1, x2, y2, side, color, adjacentWidth1, adjacentWidth2, antialias);
949         break;
950     }
951 }
952
953 void RenderObject::drawDashedOrDottedBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
954     BoxSide side, Color color, int thickness, EBorderStyle style, bool antialias)
955 {
956     if (thickness <= 0)
957         return;
958
959     bool wasAntialiased = graphicsContext->shouldAntialias();
960     StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
961     graphicsContext->setShouldAntialias(antialias);
962     graphicsContext->setStrokeColor(color);
963     graphicsContext->setStrokeThickness(thickness);
964     graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
965
966     switch (side) {
967     case BSBottom:
968     case BSTop:
969         graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
970         break;
971     case BSRight:
972     case BSLeft:
973         graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
974         break;
975     }
976     graphicsContext->setShouldAntialias(wasAntialiased);
977     graphicsContext->setStrokeStyle(oldStrokeStyle);
978 }
979
980 void RenderObject::drawDoubleBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
981     int length, BoxSide side, Color color, int thickness, int adjacentWidth1, int adjacentWidth2, bool antialias)
982 {
983     int thirdOfThickness = (thickness + 1) / 3;
984     ASSERT(thirdOfThickness);
985
986     if (!adjacentWidth1 && !adjacentWidth2) {
987         StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
988         graphicsContext->setStrokeStyle(NoStroke);
989         graphicsContext->setFillColor(color);
990
991         bool wasAntialiased = graphicsContext->shouldAntialias();
992         graphicsContext->setShouldAntialias(antialias);
993
994         switch (side) {
995         case BSTop:
996         case BSBottom:
997             graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
998             graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
999             break;
1000         case BSLeft:
1001         case BSRight:
1002             // FIXME: Why do we offset the border by 1 in this case but not the other one?
1003             if (length > 1) {
1004                 graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
1005                 graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
1006             }
1007             break;
1008         }
1009
1010         graphicsContext->setShouldAntialias(wasAntialiased);
1011         graphicsContext->setStrokeStyle(oldStrokeStyle);
1012         return;
1013     }
1014
1015     int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
1016     int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
1017
1018     switch (side) {
1019     case BSTop:
1020         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1021             y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1022             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1023         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1024             y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
1025             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1026         break;
1027     case BSLeft:
1028         drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1029             x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
1030             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1031         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1032             x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
1033             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1034         break;
1035     case BSBottom:
1036         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1037             y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1038             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1039         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1040             y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
1041             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1042         break;
1043     case BSRight:
1044         drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1045             x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
1046             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1047         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1048             x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
1049             side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1050         break;
1051     default:
1052         break;
1053     }
1054 }
1055
1056 void RenderObject::drawRidgeOrGrooveBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1057     BoxSide side, Color color, EBorderStyle style, int adjacentWidth1, int adjacentWidth2, bool antialias)
1058 {
1059     EBorderStyle s1;
1060     EBorderStyle s2;
1061     if (style == GROOVE) {
1062         s1 = INSET;
1063         s2 = OUTSET;
1064     } else {
1065         s1 = OUTSET;
1066         s2 = INSET;
1067     }
1068
1069     int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
1070     int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
1071
1072     switch (side) {
1073     case BSTop:
1074         drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1075             side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1076         drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
1077             side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1078         break;
1079     case BSLeft:
1080         drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
1081             side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1082         drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
1083             side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1084         break;
1085     case BSBottom:
1086         drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1087             side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1088         drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
1089             side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1090         break;
1091     case BSRight:
1092         drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
1093             side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1094         drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
1095             side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1096         break;
1097     }
1098 }
1099
1100 void RenderObject::drawSolidBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1101     BoxSide side, Color color, int adjacentWidth1, int adjacentWidth2, bool antialias)
1102 {
1103     StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1104     graphicsContext->setStrokeStyle(NoStroke);
1105     graphicsContext->setFillColor(color);
1106     ASSERT(x2 >= x1);
1107     ASSERT(y2 >= y1);
1108     if (!adjacentWidth1 && !adjacentWidth2) {
1109         // Turn off antialiasing to match the behavior of drawConvexPolygon();
1110         // this matters for rects in transformed contexts.
1111         bool wasAntialiased = graphicsContext->shouldAntialias();
1112         graphicsContext->setShouldAntialias(antialias);
1113         graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
1114         graphicsContext->setShouldAntialias(wasAntialiased);
1115         graphicsContext->setStrokeStyle(oldStrokeStyle);
1116         return;
1117     }
1118     FloatPoint quad[4];
1119     switch (side) {
1120     case BSTop:
1121         quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
1122         quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
1123         quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
1124         quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
1125         break;
1126     case BSBottom:
1127         quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
1128         quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
1129         quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
1130         quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
1131         break;
1132     case BSLeft:
1133         quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
1134         quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
1135         quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
1136         quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
1137         break;
1138     case BSRight:
1139         quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
1140         quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
1141         quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
1142         quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
1143         break;
1144     }
1145
1146     graphicsContext->drawConvexPolygon(4, quad, antialias);
1147     graphicsContext->setStrokeStyle(oldStrokeStyle);
1148 }
1149
1150 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
1151 {
1152     Vector<IntRect> focusRingRects;
1153     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer());
1154     if (style->outlineStyleIsAuto())
1155         paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), resolveColor(style, CSSPropertyOutlineColor));
1156     else
1157         addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
1158 }
1159
1160 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
1161 {
1162     if (rect.isEmpty())
1163         return;
1164     Node* n = node();
1165     if (!n || !n->isLink() || !n->isElementNode())
1166         return;
1167     const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
1168     if (href.isNull())
1169         return;
1170     KURL url = n->document().completeURL(href);
1171     if (!url.isValid())
1172         return;
1173     if (context->supportsURLFragments() && url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, n->document().baseURL())) {
1174         String name = url.fragmentIdentifier();
1175         if (document().findAnchor(name))
1176             context->setURLFragmentForRect(name, pixelSnappedIntRect(rect));
1177         return;
1178     }
1179     context->setURLForRect(url, pixelSnappedIntRect(rect));
1180 }
1181
1182 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1183 {
1184     if (!hasOutline())
1185         return;
1186
1187     RenderStyle* styleToUse = style();
1188     LayoutUnit outlineWidth = styleToUse->outlineWidth();
1189
1190     int outlineOffset = styleToUse->outlineOffset();
1191
1192     if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1193         if (RenderTheme::theme().shouldDrawDefaultFocusRing(this)) {
1194             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1195             paintFocusRing(paintInfo, paintRect.location(), styleToUse);
1196         }
1197     }
1198
1199     if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1200         return;
1201
1202     IntRect inner = pixelSnappedIntRect(paintRect);
1203     inner.inflate(outlineOffset);
1204
1205     IntRect outer = pixelSnappedIntRect(inner);
1206     outer.inflate(outlineWidth);
1207
1208     // FIXME: This prevents outlines from painting inside the object. See bug 12042
1209     if (outer.isEmpty())
1210         return;
1211
1212     EBorderStyle outlineStyle = styleToUse->outlineStyle();
1213     Color outlineColor = resolveColor(styleToUse, CSSPropertyOutlineColor);
1214
1215     GraphicsContext* graphicsContext = paintInfo.context;
1216     bool useTransparencyLayer = outlineColor.hasAlpha();
1217     if (useTransparencyLayer) {
1218         if (outlineStyle == SOLID) {
1219             Path path;
1220             path.addRect(outer);
1221             path.addRect(inner);
1222             graphicsContext->setFillRule(RULE_EVENODD);
1223             graphicsContext->setFillColor(outlineColor);
1224             graphicsContext->fillPath(path);
1225             return;
1226         }
1227         graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1228         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1229     }
1230
1231     int leftOuter = outer.x();
1232     int leftInner = inner.x();
1233     int rightOuter = outer.maxX();
1234     int rightInner = inner.maxX();
1235     int topOuter = outer.y();
1236     int topInner = inner.y();
1237     int bottomOuter = outer.maxY();
1238     int bottomInner = inner.maxY();
1239
1240     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1241     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1242     drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1243     drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1244
1245     if (useTransparencyLayer)
1246         graphicsContext->endLayer();
1247 }
1248
1249 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms) const
1250 {
1251     if (useTransforms) {
1252         Vector<FloatQuad> quads;
1253         absoluteQuads(quads);
1254
1255         size_t n = quads.size();
1256         if (!n)
1257             return IntRect();
1258
1259         IntRect result = quads[0].enclosingBoundingBox();
1260         for (size_t i = 1; i < n; ++i)
1261             result.unite(quads[i].enclosingBoundingBox());
1262         return result;
1263     }
1264
1265     FloatPoint absPos = localToAbsolute();
1266     Vector<IntRect> rects;
1267     absoluteRects(rects, flooredLayoutPoint(absPos));
1268
1269     size_t n = rects.size();
1270     if (!n)
1271         return IntRect();
1272
1273     LayoutRect result = rects[0];
1274     for (size_t i = 1; i < n; ++i)
1275         result.unite(rects[i]);
1276     return pixelSnappedIntRect(result);
1277 }
1278
1279 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1280 {
1281     Vector<IntRect> rects;
1282     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1283     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1284     // implicitly assumes that. This doesn't work correctly with transformed
1285     // descendants.
1286     FloatPoint absolutePoint = localToAbsolute();
1287     addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
1288     size_t count = rects.size();
1289     for (size_t i = 0; i < count; ++i) {
1290         IntRect rect = rects[i];
1291         rect.move(-absolutePoint.x(), -absolutePoint.y());
1292         quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1293     }
1294 }
1295
1296 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1297 {
1298     if (!range || !range->startContainer())
1299         return FloatRect();
1300
1301     range->ownerDocument().updateLayout();
1302
1303     Vector<FloatQuad> quads;
1304     range->textQuads(quads);
1305
1306     FloatRect result;
1307     for (size_t i = 0; i < quads.size(); ++i)
1308         result.unite(quads[i].boundingBox());
1309
1310     return result;
1311 }
1312
1313 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1314 {
1315     if (hasLayer())
1316         result.unite(absoluteBoundingBoxRectIgnoringTransforms());
1317     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1318         current->addAbsoluteRectForLayer(result);
1319 }
1320
1321 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1322 {
1323     LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
1324     topLevelRect = result;
1325     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1326         current->addAbsoluteRectForLayer(result);
1327     return result;
1328 }
1329
1330 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1331 {
1332 }
1333
1334 RenderLayerModelObject* RenderObject::containerForRepaint() const
1335 {
1336     RenderView* v = view();
1337     if (!v)
1338         return 0;
1339
1340     RenderLayerModelObject* repaintContainer = 0;
1341
1342     if (v->usesCompositing()) {
1343         // FIXME: CompositingState is not necessarily up to date for many callers of this function.
1344         DisableCompositingQueryAsserts disabler;
1345
1346         if (RenderLayer* compositingLayer = enclosingLayer()->enclosingCompositingLayerForRepaint())
1347             repaintContainer = compositingLayer->renderer();
1348     }
1349
1350     if (document().view()->hasSoftwareFilters()) {
1351         if (RenderLayer* enclosingFilterLayer = enclosingLayer()->enclosingFilterLayer())
1352             return enclosingFilterLayer->renderer();
1353     }
1354
1355     // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1356     // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1357     // repainting to do individual region repaints.
1358     RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
1359     if (parentRenderFlowThread) {
1360         // The ancestor document will do the reparenting when the repaint propagates further up.
1361         // We're just a seamless child document, and we don't need to do the hacking.
1362         if (parentRenderFlowThread->document() != document())
1363             return repaintContainer;
1364         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
1365         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
1366         RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : 0;
1367         if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
1368             repaintContainer = parentRenderFlowThread;
1369     }
1370     return repaintContainer;
1371 }
1372
1373 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const IntRect& r) const
1374 {
1375     if (!repaintContainer) {
1376         view()->repaintViewRectangle(r);
1377         return;
1378     }
1379
1380     // FIXME: Don't read compositing state here since we do this in the middle of recalc/layout.
1381     DisableCompositingQueryAsserts disabler;
1382     if (repaintContainer->compositingState() == PaintsIntoGroupedBacking) {
1383         ASSERT(repaintContainer->groupedMapping());
1384
1385         // Not clean, but if squashing layer does not yet exist here (e.g. repaint invalidation coming from within recomputing compositing requirements)
1386         // then it's ok to just exit here, since the squashing layer will get repainted when it is newly created.
1387         if (!repaintContainer->groupedMapping()->squashingLayer())
1388             return;
1389
1390
1391         IntRect offsetRect(r);
1392
1393         // First, convert the repaint rect into the space of the repaintContainer
1394         TransformState transformState(TransformState::ApplyTransformDirection, FloatQuad(FloatRect(r)));
1395         mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip);
1396         transformState.flatten();
1397         offsetRect = transformState.lastPlanarQuad().enclosingBoundingBox();
1398
1399         // FIXME: the repaint rect computed below could be tighter in uncommon nested transform cases, if we passed the quad
1400         // directly to the next chunk of code.
1401
1402         // Then, convert the repaint rect from repaintConainer space into the squashing GraphicsLayer's coordinates.
1403         if (repaintContainer->hasTransform())
1404             offsetRect = repaintContainer->layer()->transform()->mapRect(r);
1405         offsetRect.move(-repaintContainer->layer()->offsetFromSquashingLayerOrigin());
1406         repaintContainer->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(offsetRect);
1407         return;
1408     }
1409
1410     if (repaintContainer->isRenderFlowThread()) {
1411         toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r);
1412         return;
1413     }
1414
1415     if (repaintContainer->hasFilter() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
1416         repaintContainer->layer()->repainter().setFilterBackendNeedsRepaintingInRect(r);
1417         return;
1418     }
1419
1420     RenderView* v = view();
1421     if (repaintContainer->isRenderView()) {
1422         ASSERT(repaintContainer == v);
1423         bool viewHasCompositedLayer = v->hasLayer() && v->layer()->compositingState() == PaintsIntoOwnBacking;
1424         if (!viewHasCompositedLayer) {
1425             v->repaintViewRectangle(r);
1426             return;
1427         }
1428     }
1429
1430     if (v->usesCompositing()) {
1431         ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->compositingState() == PaintsIntoOwnBacking);
1432         repaintContainer->layer()->repainter().setBackingNeedsRepaintInRect(r);
1433     }
1434 }
1435
1436 void RenderObject::repaint() const
1437 {
1438     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1439     RenderView* view;
1440     if (!isRooted(&view))
1441         return;
1442
1443     if (view->document().printing())
1444         return; // Don't repaint if we're printing.
1445
1446     // FIXME: really, we're in the repaint phase here, and the following queries are legal.
1447     // Until those states are fully fledged, I'll just disable the ASSERTS.
1448     DisableCompositingQueryAsserts disabler;
1449     RenderLayerModelObject* repaintContainer = containerForRepaint();
1450     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)));
1451 }
1452
1453 void RenderObject::repaintRectangle(const LayoutRect& r) const
1454 {
1455     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1456     RenderView* view;
1457     if (!isRooted(&view))
1458         return;
1459
1460     if (view->document().printing())
1461         return; // Don't repaint if we're printing.
1462
1463     LayoutRect dirtyRect(r);
1464
1465     if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
1466         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1467         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1468         dirtyRect.move(view->layoutDelta());
1469     }
1470
1471     RenderLayerModelObject* repaintContainer = containerForRepaint();
1472     computeRectForRepaint(repaintContainer, dirtyRect);
1473     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(dirtyRect));
1474 }
1475
1476 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1477 {
1478     return pixelSnappedIntRect(absoluteClippedOverflowRect());
1479 }
1480
1481 bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, bool wasSelfLayout,
1482     const LayoutRect& oldBounds, const LayoutRect* newBoundsPtr)
1483 {
1484     RenderView* v = view();
1485     if (v->document().printing())
1486         return false; // Don't repaint if we're printing.
1487
1488     // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
1489     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1490     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1491
1492     bool fullRepaint = wasSelfLayout;
1493     // Presumably a background or a border exists if border-fit:lines was specified.
1494     if (!fullRepaint && style()->borderFit() == BorderFitLines)
1495         fullRepaint = true;
1496     if (!fullRepaint && style()->hasBorderRadius()) {
1497         // If a border-radius exists and width/height is smaller than
1498         // radius width/height, we cannot use delta-repaint.
1499         RoundedRect oldRoundedRect = style()->getRoundedBorderFor(oldBounds);
1500         RoundedRect newRoundedRect = style()->getRoundedBorderFor(newBounds);
1501         fullRepaint = oldRoundedRect.radii() != newRoundedRect.radii();
1502     }
1503
1504     if (!fullRepaint && (mustRepaintBackgroundOrBorder() && (newBounds != oldBounds)))
1505         fullRepaint = true;
1506
1507     // If we shifted, we don't know the exact reason so we are conservative and trigger a full invalidation. Shifting could
1508     // be caused by some layout property (left / top) or some in-flow renderer inserted / removed before us in the tree.
1509     if (!fullRepaint && newBounds.location() != oldBounds.location())
1510         fullRepaint = true;
1511
1512     if (!repaintContainer)
1513         repaintContainer = v;
1514
1515     if (fullRepaint) {
1516         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds));
1517         if (newBounds != oldBounds)
1518             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds));
1519         return true;
1520     }
1521
1522     if (oldBounds == newBounds)
1523         return false;
1524
1525     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1526     if (deltaLeft > 0)
1527         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1528     else if (deltaLeft < 0)
1529         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1530
1531     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1532     if (deltaRight > 0)
1533         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1534     else if (deltaRight < 0)
1535         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1536
1537     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1538     if (deltaTop > 0)
1539         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1540     else if (deltaTop < 0)
1541         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1542
1543     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1544     if (deltaBottom > 0)
1545         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1546     else if (deltaBottom < 0)
1547         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1548
1549     // FIXME: This is a limitation of our visual overflow being a single rectangle.
1550     if (!style()->boxShadow() && !style()->hasBorderImageOutsets() && !style()->hasOutline())
1551         return false;
1552
1553     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1554     // two rectangles (but typically only one).
1555     RenderStyle* outlineStyle = outlineStyleForRepaint();
1556     LayoutUnit outlineWidth = outlineStyle->outlineSize();
1557     LayoutBoxExtent insetShadowExtent = style()->getBoxShadowInsetExtent();
1558     LayoutUnit width = absoluteValue(newBounds.width() - oldBounds.width());
1559     if (width) {
1560         LayoutUnit shadowLeft;
1561         LayoutUnit shadowRight;
1562         style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1563         int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1564         LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : LayoutUnit();
1565         LayoutUnit minInsetRightShadowExtent = min<LayoutUnit>(-insetShadowExtent.right(), min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1566         LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth), valueForLength(style()->borderBottomRightRadius().width(), boxWidth)));
1567         LayoutUnit decorationsLeftWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowLeft);
1568         LayoutUnit decorationsRightWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
1569         LayoutRect rightRect(newBounds.x() + min(newBounds.width(), oldBounds.width()) - decorationsLeftWidth,
1570             newBounds.y(),
1571             width + decorationsLeftWidth + decorationsRightWidth,
1572             max(newBounds.height(), oldBounds.height()));
1573         LayoutUnit right = min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1574         if (rightRect.x() < right) {
1575             rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1576             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(rightRect));
1577         }
1578     }
1579     LayoutUnit height = absoluteValue(newBounds.height() - oldBounds.height());
1580     if (height) {
1581         LayoutUnit shadowTop;
1582         LayoutUnit shadowBottom;
1583         style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1584         int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1585         LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : LayoutUnit();
1586         LayoutUnit minInsetBottomShadowExtent = min<LayoutUnit>(-insetShadowExtent.bottom(), min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1587         LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight), valueForLength(style()->borderBottomRightRadius().height(), boxHeight)));
1588         LayoutUnit decorationsTopHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowTop);
1589         LayoutUnit decorationsBottomHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
1590         LayoutRect bottomRect(newBounds.x(),
1591             min(newBounds.maxY(), oldBounds.maxY()) - decorationsTopHeight,
1592             max(newBounds.width(), oldBounds.width()),
1593             height + decorationsTopHeight + decorationsBottomHeight);
1594         LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
1595         if (bottomRect.y() < bottom) {
1596             bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1597             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(bottomRect));
1598         }
1599     }
1600     return false;
1601 }
1602
1603 void RenderObject::repaintOverflow()
1604 {
1605 }
1606
1607 void RenderObject::repaintOverflowIfNeeded()
1608 {
1609     if (shouldRepaintOverflow())
1610         repaintOverflow();
1611 }
1612
1613 bool RenderObject::checkForRepaint() const
1614 {
1615     if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
1616         return !document().view()->needsFullRepaint() && everHadLayout();
1617
1618     return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
1619 }
1620
1621 bool RenderObject::checkForRepaintDuringLayout() const
1622 {
1623     return !RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && checkForRepaint();
1624 }
1625
1626 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
1627 {
1628     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
1629     r.inflate(outlineWidth);
1630     return r;
1631 }
1632
1633 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
1634 {
1635     ASSERT_NOT_REACHED();
1636     return LayoutRect();
1637 }
1638
1639 void RenderObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1640 {
1641     if (repaintContainer == this)
1642         return;
1643
1644     if (RenderObject* o = parent()) {
1645         if (o->isRenderBlockFlow()) {
1646             RenderBlock* cb = toRenderBlock(o);
1647             if (cb->hasColumns())
1648                 cb->adjustRectForColumns(rect);
1649         }
1650
1651         if (o->hasOverflowClip()) {
1652             RenderBox* boxParent = toRenderBox(o);
1653             boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1654             if (rect.isEmpty())
1655                 return;
1656         }
1657
1658         o->computeRectForRepaint(repaintContainer, rect, fixed);
1659     }
1660 }
1661
1662 void RenderObject::computeFloatRectForRepaint(const RenderLayerModelObject*, FloatRect&, bool) const
1663 {
1664     ASSERT_NOT_REACHED();
1665 }
1666
1667 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1668 {
1669 }
1670
1671 #ifndef NDEBUG
1672
1673 void RenderObject::showTreeForThis() const
1674 {
1675     if (node())
1676         node()->showTreeForThis();
1677 }
1678
1679 void RenderObject::showRenderTreeForThis() const
1680 {
1681     showRenderTree(this, 0);
1682 }
1683
1684 void RenderObject::showLineTreeForThis() const
1685 {
1686     if (containingBlock())
1687         containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1688 }
1689
1690 void RenderObject::showRenderObject() const
1691 {
1692     showRenderObject(0);
1693 }
1694
1695 void RenderObject::showRenderObject(int printedCharacters) const
1696 {
1697     // As this function is intended to be used when debugging, the
1698     // this pointer may be 0.
1699     if (!this) {
1700         fputs("(null)\n", stderr);
1701         return;
1702     }
1703
1704     printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1705
1706     if (node()) {
1707         if (printedCharacters)
1708             for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1709                 fputc(' ', stderr);
1710         fputc('\t', stderr);
1711         node()->showNode();
1712     } else
1713         fputc('\n', stderr);
1714 }
1715
1716 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1717 {
1718     int printedCharacters = 0;
1719     if (markedObject1 == this && markedLabel1)
1720         printedCharacters += fprintf(stderr, "%s", markedLabel1);
1721     if (markedObject2 == this && markedLabel2)
1722         printedCharacters += fprintf(stderr, "%s", markedLabel2);
1723     for (; printedCharacters < depth * 2; printedCharacters++)
1724         fputc(' ', stderr);
1725
1726     showRenderObject(printedCharacters);
1727     if (!this)
1728         return;
1729
1730     for (const RenderObject* child = firstChild(); child; child = child->nextSibling())
1731         child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1732 }
1733
1734 #endif // NDEBUG
1735
1736 bool RenderObject::isSelectable() const
1737 {
1738     return !isInert() && !(style()->userSelect() == SELECT_NONE && style()->userModify() == READ_ONLY);
1739 }
1740
1741 Color RenderObject::selectionBackgroundColor() const
1742 {
1743     if (!isSelectable())
1744         return Color::transparent;
1745
1746     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION)))
1747         return resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
1748     return frame()->selection().isFocusedAndActive() ?
1749         RenderTheme::theme().activeSelectionBackgroundColor() :
1750         RenderTheme::theme().inactiveSelectionBackgroundColor();
1751 }
1752
1753 Color RenderObject::selectionColor(int colorProperty) const
1754 {
1755     // If the element is unselectable, or we are only painting the selection,
1756     // don't override the foreground color with the selection foreground color.
1757     if (!isSelectable() || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1758         return resolveColor(colorProperty);
1759
1760     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION)))
1761         return resolveColor(pseudoStyle.get(), colorProperty);
1762     if (!RenderTheme::theme().supportsSelectionForegroundColors())
1763         return resolveColor(colorProperty);
1764     return frame()->selection().isFocusedAndActive() ?
1765         RenderTheme::theme().activeSelectionForegroundColor() :
1766         RenderTheme::theme().inactiveSelectionForegroundColor();
1767 }
1768
1769 Color RenderObject::selectionForegroundColor() const
1770 {
1771     return selectionColor(CSSPropertyWebkitTextFillColor);
1772 }
1773
1774 Color RenderObject::selectionEmphasisMarkColor() const
1775 {
1776     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1777 }
1778
1779 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1780 {
1781     view()->selectionStartEnd(spos, epos);
1782 }
1783
1784 void RenderObject::handleDynamicFloatPositionChange()
1785 {
1786     // We have gone from not affecting the inline status of the parent flow to suddenly
1787     // having an impact.  See if there is a mismatch between the parent flow's
1788     // childrenInline() state and our state.
1789     setInline(style()->isDisplayInlineType());
1790     if (isInline() != parent()->childrenInline()) {
1791         if (!isInline())
1792             toRenderBoxModelObject(parent())->childBecameNonInline(this);
1793         else {
1794             // An anonymous block must be made to wrap this inline.
1795             RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1796             RenderObjectChildList* childlist = parent()->virtualChildren();
1797             childlist->insertChildNode(parent(), block, this);
1798             block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1799         }
1800     }
1801 }
1802
1803 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1804 {
1805     // If transform changed, and the layer does not paint into its own separate backing, then we need to do a layout.
1806     // FIXME: The comment above is what the code does, but it is technically not following spec. This means we will
1807     // not to layout for 3d transforms, but we should be invoking a simplified relayout. Is it possible we are avoiding
1808     // doing this for some performance reason at this time?
1809     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1810         // Text nodes share style with their parents but transforms don't apply to them,
1811         // hence the !isText() check.
1812         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
1813         if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasDirectReasonsForCompositing())) {
1814             // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
1815             // then we actually need SimplifiedLayoutAndPositionedMovement.
1816             if (!hasLayer())
1817                 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
1818             else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
1819                 diff = StyleDifferenceSimplifiedLayout;
1820             else if (diff < StyleDifferenceSimplifiedLayout)
1821                 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
1822         } else if (diff < StyleDifferenceRecompositeLayer)
1823             diff = StyleDifferenceRecompositeLayer;
1824     }
1825
1826     // If opacity or filters changed, and the layer does not paint into its own separate backing, then we need to repaint (also
1827     // ignoring text nodes)
1828     if (contextSensitiveProperties & ContextSensitivePropertyOpacity && diff <= StyleDifferenceRepaintLayer) {
1829         if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasDirectReasonsForCompositing()))
1830             diff = StyleDifferenceRepaintLayer;
1831         else if (diff < StyleDifferenceRecompositeLayer)
1832             diff = StyleDifferenceRecompositeLayer;
1833     }
1834
1835     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer() && diff <= StyleDifferenceRepaintLayer) {
1836         RenderLayer* layer = toRenderLayerModelObject(this)->layer();
1837         if (!layer->hasDirectReasonsForCompositing() || layer->paintsWithFilters())
1838             diff = StyleDifferenceRepaintLayer;
1839         else if (diff < StyleDifferenceRecompositeLayer)
1840             diff = StyleDifferenceRecompositeLayer;
1841     }
1842
1843     // The answer to layerTypeRequired() for plugins, iframes, and canvas can change without the actual
1844     // style changing, since it depends on whether we decide to composite these elements. When the
1845     // layer status of one of these elements changes, we need to force a layout.
1846     if (diff == StyleDifferenceEqual && style() && isLayerModelObject()) {
1847         bool requiresLayer = toRenderLayerModelObject(this)->layerTypeRequired() != NoLayer;
1848         if (hasLayer() != requiresLayer)
1849             diff = StyleDifferenceLayout;
1850     }
1851
1852     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
1853     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
1854         diff = StyleDifferenceRepaint;
1855
1856     return diff;
1857 }
1858
1859 void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
1860 {
1861     ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER);
1862
1863     // FIXME: We should consider just making all pseudo items use an inherited style.
1864
1865     // Images are special and must inherit the pseudoStyle so the width and height of
1866     // the pseudo element doesn't change the size of the image. In all other cases we
1867     // can just share the style.
1868     //
1869     // Quotes are also RenderInline, so we need to create an inherited style to avoid
1870     // getting an inline with positioning or an invalid display.
1871     //
1872     if (isImage() || isQuote()) {
1873         RefPtr<RenderStyle> style = RenderStyle::create();
1874         style->inheritFrom(pseudoStyle.get());
1875         setStyle(style.release());
1876         return;
1877     }
1878
1879     setStyle(pseudoStyle);
1880 }
1881
1882 inline bool RenderObject::hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const
1883 {
1884     if (style()->hasBorder() || style()->hasOutline())
1885         return true;
1886     for (const RenderObject* r = firstChild(); r; r = r->nextSibling()) {
1887         if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
1888             return true;
1889         if (r->style()->hasOutline() || r->style()->hasBorder())
1890             return true;
1891     }
1892     return false;
1893 }
1894
1895 inline bool RenderObject::shouldRepaintForStyleDifference(StyleDifference diff) const
1896 {
1897     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrColorChange && hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor());
1898 }
1899
1900 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
1901 {
1902     if (m_style == style) {
1903         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
1904         // style sharing is disabled for them. That should ensure that we never hit this code path.
1905         ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
1906         return;
1907     }
1908
1909     StyleDifference diff = StyleDifferenceEqual;
1910     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
1911     if (m_style)
1912         diff = m_style->visualInvalidationDiff(style.get(), contextSensitiveProperties);
1913
1914     diff = adjustStyleDifference(diff, contextSensitiveProperties);
1915
1916     styleWillChange(diff, style.get());
1917
1918     RefPtr<RenderStyle> oldStyle = m_style.release();
1919     setStyleInternal(style);
1920
1921     updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
1922     updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
1923
1924     updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
1925     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
1926
1927     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : 0, m_style ? m_style->shapeOutside() : 0);
1928
1929     bool doesNotNeedLayout = !m_parent || isText();
1930
1931     styleDidChange(diff, oldStyle.get());
1932
1933     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
1934     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
1935     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
1936     // in the future as we move renderer changes out of layout and into style changes.
1937     if (doesNotNeedLayout)
1938         return;
1939
1940     // Now that the layer (if any) has been updated, we need to adjust the diff again,
1941     // check whether we should layout now, and decide if we need to repaint.
1942     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
1943
1944     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
1945         if (updatedDiff == StyleDifferenceLayout)
1946             setNeedsLayoutAndPrefWidthsRecalc();
1947         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
1948             setNeedsPositionedMovementLayout();
1949         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1950             setNeedsPositionedMovementLayout();
1951             setNeedsSimplifiedNormalFlowLayout();
1952         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
1953             setNeedsSimplifiedNormalFlowLayout();
1954     }
1955
1956     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
1957         // Do a repaint with the new style now, e.g., for example if we go from
1958         // not having an outline to having an outline.
1959         repaint();
1960     }
1961 }
1962
1963 static inline bool rendererHasBackground(const RenderObject* renderer)
1964 {
1965     return renderer && renderer->hasBackground();
1966 }
1967
1968 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1969 {
1970     if (m_style) {
1971         // If our z-index changes value or our visibility changes,
1972         // we need to dirty our stacking context's z-order list.
1973         if (newStyle) {
1974             bool visibilityChanged = m_style->visibility() != newStyle->visibility()
1975                 || m_style->zIndex() != newStyle->zIndex()
1976                 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1977             if (visibilityChanged) {
1978                 document().setAnnotatedRegionsDirty(true);
1979                 if (AXObjectCache* cache = document().existingAXObjectCache())
1980                     cache->childrenChanged(parent());
1981             }
1982
1983             // Keep layer hierarchy visibility bits up to date if visibility changes.
1984             if (m_style->visibility() != newStyle->visibility()) {
1985                 // We might not have an enclosing layer yet because we might not be in the tree.
1986                 if (RenderLayer* layer = enclosingLayer()) {
1987                     if (newStyle->visibility() == VISIBLE) {
1988                         layer->setHasVisibleContent();
1989                     } else if (layer->hasVisibleContent() && (this == layer->renderer() || layer->renderer()->style()->visibility() != VISIBLE)) {
1990                         layer->dirtyVisibleContentStatus();
1991                         if (diff > StyleDifferenceRepaintLayer)
1992                             repaint();
1993                     }
1994                 }
1995             }
1996         }
1997
1998         if (m_parent && (newStyle->outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
1999             repaint();
2000         if (isFloating() && (m_style->floating() != newStyle->floating()))
2001             // For changes in float styles, we need to conceivably remove ourselves
2002             // from the floating objects list.
2003             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2004         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle->position()))
2005             // For changes in positioning styles, we need to conceivably remove ourselves
2006             // from the positioned objects list.
2007             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2008
2009         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
2010             && (!newStyle->isFloating() && !newStyle->hasOutOfFlowPosition())
2011             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
2012
2013         // Clearing these bits is required to avoid leaving stale renderers.
2014         // FIXME: We shouldn't need that hack if our logic was totally correct.
2015         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
2016             setFloating(false);
2017             clearPositionedState();
2018         }
2019     } else
2020         s_affectsParentBlock = false;
2021
2022     if (view()->frameView()) {
2023         bool shouldBlitOnFixedBackgroundImage = false;
2024 #if ENABLE(FAST_MOBILE_SCROLLING)
2025         // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
2026         // when scrolling a page with a fixed background image. As an optimization, assuming there are
2027         // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
2028         // ignore the CSS property "background-attachment: fixed".
2029         shouldBlitOnFixedBackgroundImage = true;
2030 #endif
2031
2032         bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
2033         bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
2034
2035         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
2036         if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
2037             if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
2038                 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
2039                     newStyleSlowScroll = false;
2040
2041                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
2042                     oldStyleSlowScroll = false;
2043             }
2044         }
2045
2046         if (oldStyleSlowScroll != newStyleSlowScroll) {
2047             if (oldStyleSlowScroll)
2048                 view()->frameView()->removeSlowRepaintObject();
2049             if (newStyleSlowScroll)
2050                 view()->frameView()->addSlowRepaintObject();
2051         }
2052     }
2053
2054     // Elements with non-auto touch-action will send a SetTouchAction message
2055     // on touchstart in EventHandler::handleTouchEvent, and so effectively have
2056     // a touchstart handler that must be reported.
2057     //
2058     // Since a CSS property cannot be applied directly to a text node, a
2059     // handler will have already been added for its parent so ignore it.
2060     TouchAction oldTouchAction = m_style ? m_style->touchAction() : TouchActionAuto;
2061     if (node() && !node()->isTextNode() && (oldTouchAction == TouchActionAuto) != (newStyle->touchAction() == TouchActionAuto)) {
2062         if (newStyle->touchAction() != TouchActionAuto)
2063             document().didAddTouchEventHandler(node());
2064         else
2065             document().didRemoveTouchEventHandler(node());
2066     }
2067 }
2068
2069 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
2070 {
2071     ASSERT(a->cursors() != b->cursors());
2072     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
2073 }
2074
2075 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
2076 {
2077     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
2078 }
2079
2080 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
2081 {
2082     if (s_affectsParentBlock)
2083         handleDynamicFloatPositionChange();
2084
2085     if (!m_parent)
2086         return;
2087
2088     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
2089         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.get());
2090
2091         // If the object already needs layout, then setNeedsLayout won't do
2092         // any work. But if the containing block has changed, then we may need
2093         // to mark the new containing blocks for layout. The change that can
2094         // directly affect the containing block of this object is a change to
2095         // the position style.
2096         if (needsLayout() && oldStyle->position() != m_style->position())
2097             markContainingBlocksForLayout();
2098
2099         if (diff == StyleDifferenceLayout)
2100             setNeedsLayoutAndPrefWidthsRecalc();
2101         else
2102             setNeedsSimplifiedNormalFlowLayout();
2103     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
2104         setNeedsPositionedMovementLayout();
2105         setNeedsSimplifiedNormalFlowLayout();
2106     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
2107         setNeedsPositionedMovementLayout();
2108
2109     // Don't check for repaint here; we need to wait until the layer has been
2110     // updated by subclasses before we know if we have to repaint (in setStyle()).
2111
2112     if (oldStyle && !areCursorsEqual(oldStyle, style())) {
2113         if (LocalFrame* frame = this->frame())
2114             frame->eventHandler().scheduleCursorUpdate();
2115     }
2116 }
2117
2118 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
2119 {
2120     // FIXME: We could save this call when the change only affected non-inherited properties.
2121     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
2122         if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
2123             continue;
2124
2125         if (blockChildrenOnly && !child->isRenderBlock())
2126             continue;
2127
2128         if (child->isRenderFullScreen() || child->isRenderFullScreenPlaceholder())
2129             continue;
2130
2131         RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), child->style()->display());
2132         if (style()->specifiesColumns()) {
2133             if (child->style()->specifiesColumns())
2134                 newStyle->inheritColumnPropertiesFrom(style());
2135             if (child->style()->columnSpan())
2136                 newStyle->setColumnSpan(ColumnSpanAll);
2137         }
2138
2139         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
2140         // they contain block descendants of relative or sticky positioned inlines.
2141         if (child->isInFlowPositioned() && toRenderBlock(child)->isAnonymousBlockContinuation())
2142             newStyle->setPosition(child->style()->position());
2143
2144         child->setStyle(newStyle.release());
2145     }
2146 }
2147
2148 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
2149 {
2150     // Optimize the common case
2151     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
2152         return;
2153
2154     // Go through the new layers and addClients first, to avoid removing all clients of an image.
2155     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
2156         if (currNew->image())
2157             currNew->image()->addClient(this);
2158     }
2159
2160     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2161         if (currOld->image())
2162             currOld->image()->removeClient(this);
2163     }
2164 }
2165
2166 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2167 {
2168     if (oldImage != newImage) {
2169         if (oldImage)
2170             oldImage->removeClient(this);
2171         if (newImage)
2172             newImage->addClient(this);
2173     }
2174 }
2175
2176 void RenderObject::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
2177 {
2178     if (oldShapeValue || newShapeValue)
2179         updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
2180 }
2181
2182 LayoutRect RenderObject::viewRect() const
2183 {
2184     return view()->viewRect();
2185 }
2186
2187 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2188 {
2189     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2190     mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2191     transformState.flatten();
2192
2193     return transformState.lastPlanarPoint();
2194 }
2195
2196 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2197 {
2198     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2199     mapAbsoluteToLocalPoint(mode, transformState);
2200     transformState.flatten();
2201
2202     return transformState.lastPlanarPoint();
2203 }
2204
2205 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2206 {
2207     TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2208     mapAbsoluteToLocalPoint(mode, transformState);
2209     transformState.flatten();
2210     return transformState.lastPlanarQuad();
2211 }
2212
2213 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
2214 {
2215     if (repaintContainer == this)
2216         return;
2217
2218     RenderObject* o = parent();
2219     if (!o)
2220         return;
2221
2222     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2223     LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2224     if (mode & ApplyContainerFlip && o->isBox()) {
2225         if (o->style()->isFlippedBlocksWritingMode())
2226             transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2227         mode &= ~ApplyContainerFlip;
2228     }
2229
2230     LayoutSize columnOffset;
2231     o->adjustForColumns(columnOffset, roundedLayoutPoint(transformState.mappedPoint()));
2232     if (!columnOffset.isZero())
2233         transformState.move(columnOffset);
2234
2235     if (o->hasOverflowClip())
2236         transformState.move(-toRenderBox(o)->scrolledContentOffset());
2237
2238     o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2239 }
2240
2241 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2242 {
2243     ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
2244
2245     RenderObject* container = parent();
2246     if (!container)
2247         return 0;
2248
2249     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2250     LayoutSize offset;
2251     if (container->hasOverflowClip())
2252         offset = -toRenderBox(container)->scrolledContentOffset();
2253
2254     geometryMap.push(this, offset, hasColumns());
2255
2256     return container;
2257 }
2258
2259 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2260 {
2261     RenderObject* o = parent();
2262     if (o) {
2263         o->mapAbsoluteToLocalPoint(mode, transformState);
2264         if (o->hasOverflowClip())
2265             transformState.move(toRenderBox(o)->scrolledContentOffset());
2266     }
2267 }
2268
2269 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
2270 {
2271     // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2272     // so check the layer's transform directly.
2273     return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2274 }
2275
2276 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2277 {
2278     transform.makeIdentity();
2279     transform.translate(offsetInContainer.width().toFloat(), offsetInContainer.height().toFloat());
2280     RenderLayer* layer;
2281     if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
2282         transform.multiply(layer->currentTransform());
2283
2284     if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2285         // Perpsective on the container affects us, so we have to factor it in here.
2286         ASSERT(containerObject->hasLayer());
2287         FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
2288
2289         TransformationMatrix perspectiveMatrix;
2290         perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2291
2292         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2293         transform = perspectiveMatrix * transform;
2294         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2295     }
2296 }
2297
2298 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2299 {
2300     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2301     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2302     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2303     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2304     transformState.flatten();
2305
2306     return transformState.lastPlanarQuad();
2307 }
2308
2309 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2310 {
2311     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2312     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2313     transformState.flatten();
2314
2315     return transformState.lastPlanarPoint();
2316 }
2317
2318 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2319 {
2320     ASSERT(o == container());
2321
2322     LayoutSize offset;
2323
2324     o->adjustForColumns(offset, point);
2325
2326     if (o->hasOverflowClip())
2327         offset -= toRenderBox(o)->scrolledContentOffset();
2328
2329     if (offsetDependsOnPoint)
2330         *offsetDependsOnPoint = hasColumns() || o->isRenderFlowThread();
2331
2332     return offset;
2333 }
2334
2335 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
2336 {
2337     LayoutSize offset;
2338     LayoutPoint referencePoint;
2339     const RenderObject* currContainer = this;
2340     do {
2341         RenderObject* nextContainer = currContainer->container();
2342         ASSERT(nextContainer);  // This means we reached the top without finding container.
2343         if (!nextContainer)
2344             break;
2345         ASSERT(!currContainer->hasTransform());
2346         LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2347         offset += currentOffset;
2348         referencePoint.move(currentOffset);
2349         currContainer = nextContainer;
2350     } while (currContainer != container);
2351
2352     return offset;
2353 }
2354
2355 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2356 {
2357     if (extraWidthToEndOfLine)
2358         *extraWidthToEndOfLine = 0;
2359
2360     return LayoutRect();
2361 }
2362
2363 void RenderObject::computeLayerHitTestRects(LayerHitTestRects& layerRects) const
2364 {
2365     // Figure out what layer our container is in. Any offset (or new layer) for this
2366     // renderer within it's container will be applied in addLayerHitTestRects.
2367     LayoutPoint layerOffset;
2368     const RenderLayer* currentLayer = 0;
2369
2370     if (!hasLayer()) {
2371         RenderObject* container = this->container();
2372         currentLayer = container->enclosingLayer();
2373         if (container && currentLayer->renderer() != container) {
2374             layerOffset.move(container->offsetFromAncestorContainer(currentLayer->renderer()));
2375             // If the layer itself is scrolled, we have to undo the subtraction of its scroll
2376             // offset since we want the offset relative to the scrolling content, not the
2377             // element itself.
2378             if (currentLayer->renderer()->hasOverflowClip())
2379                 layerOffset.move(currentLayer->renderBox()->scrolledContentOffset());
2380         }
2381     }
2382
2383     this->addLayerHitTestRects(layerRects, currentLayer, layerOffset, LayoutRect());
2384 }
2385
2386 void RenderObject::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
2387 {
2388     ASSERT(currentLayer);
2389     ASSERT(currentLayer == this->enclosingLayer());
2390
2391     // Compute the rects for this renderer only and add them to the results.
2392     // Note that we could avoid passing the offset and instead adjust each result, but this
2393     // seems slightly simpler.
2394     Vector<LayoutRect> ownRects;
2395     LayoutRect newContainerRect;
2396     computeSelfHitTestRects(ownRects, layerOffset);
2397
2398     // When we get to have a lot of rects on a layer, the performance cost of tracking those
2399     // rects outweighs the benefit of doing compositor thread hit testing.
2400     // FIXME: This limit needs to be low due to the O(n^2) algorithm in
2401     // WebLayer::setTouchEventHandlerRegion - crbug.com/300282.
2402     const size_t maxRectsPerLayer = 100;
2403
2404     LayerHitTestRects::iterator iter = layerRects.find(currentLayer);
2405     Vector<WebCore::LayoutRect>* iterValue;
2406     if (iter == layerRects.end())
2407         iterValue = &layerRects.add(currentLayer, Vector<LayoutRect>()).storedValue->value;
2408     else
2409         iterValue = &iter->value;
2410     for (size_t i = 0; i < ownRects.size(); i++) {
2411         if (!containerRect.contains(ownRects[i])) {
2412             iterValue->append(ownRects[i]);
2413             if (iterValue->size() > maxRectsPerLayer) {
2414                 // Just mark the entire layer instead, and switch to walking the layer
2415                 // tree instead of the render tree.
2416                 layerRects.remove(currentLayer);
2417                 currentLayer->addLayerHitTestRects(layerRects);
2418                 return;
2419             }
2420             if (newContainerRect.isEmpty())
2421                 newContainerRect = ownRects[i];
2422         }
2423     }
2424     if (newContainerRect.isEmpty())
2425         newContainerRect = containerRect;
2426
2427     // If it's possible for children to have rects outside our bounds, then we need to descend into
2428     // the children and compute them.
2429     // Ideally there would be other cases where we could detect that children couldn't have rects
2430     // outside our bounds and prune the tree walk.
2431     // Note that we don't use Region here because Union is O(N) - better to just keep a list of
2432     // partially redundant rectangles. If we find examples where this is expensive, then we could
2433     // rewrite Region to be more efficient. See https://bugs.webkit.org/show_bug.cgi?id=100814.
2434     if (!isRenderView()) {
2435         for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
2436             curr->addLayerHitTestRects(layerRects, currentLayer,  layerOffset, newContainerRect);
2437         }
2438     }
2439 }
2440
2441 bool RenderObject::isRooted(RenderView** view) const
2442 {
2443     const RenderObject* o = this;
2444     while (o->parent())
2445         o = o->parent();
2446
2447     if (!o->isRenderView())
2448         return false;
2449
2450     if (view)
2451         *view = const_cast<RenderView*>(toRenderView(o));
2452
2453     return true;
2454 }
2455
2456 RenderObject* RenderObject::rendererForRootBackground()
2457 {
2458     ASSERT(isRoot());
2459     if (!hasBackground() && isHTMLHtmlElement(node())) {
2460         // Locate the <body> element using the DOM. This is easier than trying
2461         // to crawl around a render tree with potential :before/:after content and
2462         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
2463         // render object very easily via the DOM.
2464         HTMLElement* body = document().body();
2465         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
2466         if (bodyObject)
2467             return bodyObject;
2468     }
2469
2470     return this;
2471 }
2472
2473 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
2474 {
2475     // Respect the image's orientation if it's being used as a full-page image or it's
2476     // an <img> and the setting to respect it everywhere is set.
2477     return document().isImageDocument()
2478         || (document().settings() && document().settings()->shouldRespectImageOrientation() && isHTMLImageElement(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
2479 }
2480
2481 bool RenderObject::hasOutlineAnnotation() const
2482 {
2483     return node() && node()->isLink() && document().printing();
2484 }
2485
2486 bool RenderObject::hasEntirelyFixedBackground() const
2487 {
2488     return m_style->hasEntirelyFixedBackground();
2489 }
2490
2491 RenderObject* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
2492 {
2493     if (repaintContainerSkipped)
2494         *repaintContainerSkipped = false;
2495
2496     // This method is extremely similar to containingBlock(), but with a few notable
2497     // exceptions.
2498     // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2499     // the object is not part of the primary document subtree yet.
2500     // (2) For normal flow elements, it just returns the parent.
2501     // (3) For absolute positioned elements, it will return a relative positioned inline.
2502     // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2503     // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
2504     // computePositionedLogicalHeight have to use container().
2505     RenderObject* o = parent();
2506
2507     if (isText())
2508         return o;
2509
2510     EPosition pos = m_style->position();
2511     if (pos == FixedPosition) {
2512         return containerForFixedPosition(repaintContainer, repaintContainerSkipped);
2513     } else if (pos == AbsolutePosition) {
2514         // We technically just want our containing block, but
2515         // we may not have one if we're part of an uninstalled
2516         // subtree. We'll climb as high as we can though.
2517         while (o) {
2518             if (o->style()->position() != StaticPosition)
2519                 break;
2520
2521             if (o->canContainFixedPositionObjects())
2522                 break;
2523
2524             if (repaintContainerSkipped && o == repaintContainer)
2525                 *repaintContainerSkipped = true;
2526
2527             o = o->parent();
2528         }
2529     }
2530
2531     return o;
2532 }
2533
2534 bool RenderObject::isSelectionBorder() const
2535 {
2536     SelectionState st = selectionState();
2537     return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2538 }
2539
2540 inline void RenderObject::clearLayoutRootIfNeeded() const
2541 {
2542     if (frame()) {
2543         if (FrameView* view = frame()->view()) {
2544             if (view->layoutRoot() == this) {
2545                 if (!documentBeingDestroyed())
2546                     ASSERT_NOT_REACHED();
2547                 // This indicates a failure to layout the child, which is why
2548                 // the layout root is still set to |this|. Make sure to clear it
2549                 // since we are getting destroyed.
2550                 view->clearLayoutSubtreeRoot();
2551             }
2552         }
2553     }
2554 }
2555
2556 void RenderObject::willBeDestroyed()
2557 {
2558     // Destroy any leftover anonymous children.
2559     RenderObjectChildList* children = virtualChildren();
2560     if (children)
2561         children->destroyLeftoverChildren();
2562
2563     // If this renderer is being autoscrolled, stop the autoscrolling.
2564     if (LocalFrame* frame = this->frame()) {
2565         if (frame->page())
2566             frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
2567     }
2568
2569     // For accessibility management, notify the parent of the imminent change to its child set.
2570     // We do it now, before remove(), while the parent pointer is still available.
2571     if (AXObjectCache* cache = document().existingAXObjectCache())
2572         cache->childrenChanged(this->parent());
2573
2574     remove();
2575
2576     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
2577     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
2578     if (AXObjectCache* cache = document().existingAXObjectCache())
2579         cache->remove(this);
2580
2581     // If this renderer had a parent, remove should have destroyed any counters
2582     // attached to this renderer and marked the affected other counters for
2583     // reevaluation. This apparently redundant check is here for the case when
2584     // this renderer had no parent at the time remove() was called.
2585
2586     if (hasCounterNodeMap())
2587         RenderCounter::destroyCounterNodes(*this);
2588
2589     // Remove the handler if node had touch-action set. Don't call when
2590     // document is being destroyed as all handlers will have been cleared
2591     // previously. Handlers are not added for text nodes so don't try removing
2592     // for one too. Need to check if m_style is null in cases of partial construction.
2593     if (!documentBeingDestroyed() && node() && !node()->isTextNode() && m_style && m_style->touchAction() != TouchActionAuto)
2594         document().didRemoveTouchEventHandler(node());
2595
2596     setAncestorLineBoxDirty(false);
2597
2598     clearLayoutRootIfNeeded();
2599 }
2600
2601 void RenderObject::insertedIntoTree()
2602 {
2603     // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2604
2605     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2606     // and don't have a layer attached to ourselves.
2607     RenderLayer* layer = 0;
2608     if (firstChild() || hasLayer()) {
2609         layer = parent()->enclosingLayer();
2610         addLayers(layer);
2611     }
2612
2613     // If |this| is visible but this object was not, tell the layer it has some visible content
2614     // that needs to be drawn and layer visibility optimization can't be used
2615     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2616         if (!layer)
2617             layer = parent()->enclosingLayer();
2618         if (layer)
2619             layer->setHasVisibleContent();
2620     }
2621
2622     if (!isFloating() && parent()->childrenInline())
2623         parent()->dirtyLinesFromChangedChild(this);
2624 }
2625
2626 void RenderObject::willBeRemovedFromTree()
2627 {
2628     // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2629
2630     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2631     RenderLayer* layer = 0;
2632     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2633         layer = parent()->enclosingLayer();
2634         layer->dirtyVisibleContentStatus();
2635     }
2636
2637     // Keep our layer hierarchy updated.
2638     if (firstChild() || hasLayer()) {
2639         if (!layer)
2640             layer = parent()->enclosingLayer();
2641         removeLayers(layer);
2642     }
2643
2644     if (isOutOfFlowPositioned() && parent()->childrenInline())
2645         parent()->dirtyLinesFromChangedChild(this);
2646
2647     removeFromRenderFlowThread();
2648
2649     // Update cached boundaries in SVG renderers if a child is removed.
2650     if (parent()->isSVG())
2651         parent()->setNeedsBoundariesUpdate();
2652 }
2653
2654 void RenderObject::removeFromRenderFlowThread()
2655 {
2656     if (flowThreadState() == NotInsideFlowThread)
2657         return;
2658
2659     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2660     // It's only until later when we actually destroy it and remove all the children from it.
2661     // Currently, that happens for firstLetter elements and list markers.
2662     // Pass in the flow thread so that we don't have to look it up for all the children.
2663     removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
2664 }
2665
2666 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
2667 {
2668     if (const RenderObjectChildList* children = virtualChildren()) {
2669         for (RenderObject* child = children->firstChild(); child; child = child->nextSibling())
2670             child->removeFromRenderFlowThreadRecursive(renderFlowThread);
2671     }
2672
2673     setFlowThreadState(NotInsideFlowThread);
2674 }
2675
2676 void RenderObject::destroyAndCleanupAnonymousWrappers()
2677 {
2678     // If the tree is destroyed, there is no need for a clean-up phase.
2679     if (documentBeingDestroyed()) {
2680         destroy();
2681         return;
2682     }
2683
2684     RenderObject* destroyRoot = this;
2685     for (RenderObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2686         // Anonymous block continuations are tracked and destroyed elsewhere (see the bottom of RenderBlock::removeChild)
2687         if (destroyRootParent->isRenderBlock() && toRenderBlock(destroyRootParent)->isAnonymousBlockContinuation())
2688             break;
2689         // Render flow threads are tracked by the FlowThreadController, so we can't destroy them here.
2690         // Column spans are tracked elsewhere.
2691         if (destroyRootParent->isRenderFlowThread() || destroyRootParent->isAnonymousColumnSpanBlock())
2692             break;
2693
2694         if (destroyRootParent->firstChild() != this || destroyRootParent->lastChild() != this)
2695             break;
2696     }
2697
2698     destroyRoot->destroy();
2699
2700     // WARNING: |this| is deleted here.
2701 }
2702
2703 void RenderObject::removeShapeImageClient(ShapeValue* shapeValue)
2704 {
2705     if (!shapeValue)
2706         return;
2707     if (StyleImage* shapeImage = shapeValue->image())
2708         shapeImage->removeClient(this);
2709 }
2710
2711 void RenderObject::destroy()
2712 {
2713     willBeDestroyed();
2714     postDestroy();
2715 }
2716
2717 void RenderObject::postDestroy()
2718 {
2719     // It seems ugly that this is not in willBeDestroyed().
2720     if (m_style) {
2721         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2722             if (StyleImage* backgroundImage = bgLayer->image())
2723                 backgroundImage->removeClient(this);
2724         }
2725
2726         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2727             if (StyleImage* maskImage = maskLayer->image())
2728                 maskImage->removeClient(this);
2729         }
2730
2731         if (StyleImage* borderImage = m_style->borderImage().image())
2732             borderImage->removeClient(this);
2733
2734         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2735             maskBoxImage->removeClient(this);
2736
2737         removeShapeImageClient(m_style->shapeOutside());
2738     }
2739
2740     delete this;
2741 }
2742
2743 PositionWithAffinity RenderObject::positionForPoint(const LayoutPoint&)
2744 {
2745     return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2746 }
2747
2748 void RenderObject::updateDragState(bool dragOn)
2749 {
2750     bool valueChanged = (dragOn != isDragging());
2751     setIsDragging(dragOn);
2752     if (valueChanged && node()) {
2753         if (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())
2754             node()->setNeedsStyleRecalc(SubtreeStyleChange);
2755         else if (style()->affectedByDrag())
2756             node()->setNeedsStyleRecalc(LocalStyleChange);
2757     }
2758     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2759         curr->updateDragState(dragOn);
2760 }
2761
2762 CompositingState RenderObject::compositingState() const
2763 {
2764     return hasLayer() ? toRenderLayerModelObject(this)->layer()->compositingState() : NotComposited;
2765 }
2766
2767 CompositingReasons RenderObject::additionalCompositingReasons(CompositingTriggerFlags) const
2768 {
2769     return CompositingReasonNone;
2770 }
2771
2772 bool RenderObject::acceleratedCompositingForOverflowScrollEnabled() const
2773 {
2774     const Settings* settings = document().settings();
2775     return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
2776 }
2777
2778 // FIXME: This is a temporary flag and should be removed once accelerated
2779 // overflow scroll is ready (crbug.com/254111).
2780 bool RenderObject::compositorDrivenAcceleratedScrollingEnabled() const
2781 {
2782     const Settings* settings = document().settings();
2783     if (!settings)
2784         return false;
2785     return settings->acceleratedCompositingForOverflowScrollEnabled() && settings->compositorDrivenAcceleratedScrollingEnabled();
2786 }
2787
2788 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2789 {
2790     bool inside = false;
2791     if (hitTestFilter != HitTestSelf) {
2792         // First test the foreground layer (lines and inlines).
2793         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
2794
2795         // Test floats next.
2796         if (!inside)
2797             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2798
2799         // Finally test to see if the mouse is in the background (within a child block's background).
2800         if (!inside)
2801             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2802     }
2803
2804     // See if the mouse is inside us but not any of our descendants
2805     if (hitTestFilter != HitTestDescendants && !inside)
2806         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2807
2808     return inside;
2809 }
2810
2811 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2812 {
2813     if (result.innerNode())
2814         return;
2815
2816     Node* node = this->node();
2817
2818     // If we hit the anonymous renderers inside generated content we should
2819     // actually hit the generated content so walk up to the PseudoElement.
2820     if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2821         for (RenderObject* renderer = parent(); renderer && !node; renderer = renderer->parent())
2822             node = renderer->node();
2823     }
2824
2825     if (node) {
2826         result.setInnerNode(node);
2827         if (!result.innerNonSharedNode())
2828             result.setInnerNonSharedNode(node);
2829         result.setLocalPoint(point);
2830     }
2831 }
2832
2833 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2834 {
2835     return false;
2836 }
2837
2838 void RenderObject::scheduleRelayout()
2839 {
2840     if (isRenderView()) {
2841         FrameView* view = toRenderView(this)->frameView();
2842         if (view)
2843             view->scheduleRelayout();
2844     } else {
2845         if (isRooted()) {
2846             if (RenderView* renderView = view()) {
2847                 if (FrameView* frameView = renderView->frameView())
2848                     frameView->scheduleRelayoutOfSubtree(this);
2849             }
2850         }
2851     }
2852 }
2853
2854 void RenderObject::forceLayout()
2855 {
2856     setSelfNeedsLayout(true);
2857     setShouldDoFullRepaintAfterLayout(true);
2858     layout();
2859 }
2860
2861 // FIXME: Does this do anything different than forceLayout given that we don't walk
2862 // the containing block chain. If not, we should change all callers to use forceLayout.
2863 void RenderObject::forceChildLayout()
2864 {
2865     setNormalChildNeedsLayout(true);
2866     layout();
2867 }
2868
2869 enum StyleCacheState {
2870     Cached,
2871     Uncached
2872 };
2873
2874 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderObject* renderer, RenderStyle* style)
2875 {
2876     const RenderObject* rendererForFirstLineStyle = renderer;
2877     if (renderer->isBeforeOrAfterContent())
2878         rendererForFirstLineStyle = renderer->parent();
2879
2880     if (rendererForFirstLineStyle->isRenderBlockFlow() || rendererForFirstLineStyle->isRenderButton()) {
2881         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
2882             if (type == Cached)
2883                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2884             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == renderer ? style : 0);
2885         }
2886     } else if (!rendererForFirstLineStyle->isAnonymous() && rendererForFirstLineStyle->isRenderInline()) {
2887         RenderStyle* parentStyle = rendererForFirstLineStyle->parent()->firstLineStyle();
2888         if (parentStyle != rendererForFirstLineStyle->parent()->style()) {
2889             if (type == Cached) {
2890                 // A first-line style is in effect. Cache a first-line style for ourselves.
2891                 rendererForFirstLineStyle->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2892                 return rendererForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2893             }
2894             return rendererForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
2895         }
2896     }
2897     return nullptr;
2898 }
2899
2900 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2901 {
2902     if (!document().styleEngine()->usesFirstLineRules())
2903         return nullptr;
2904
2905     ASSERT(!isText());
2906
2907     return firstLineStyleForCachedUncachedType(Uncached, this, style);
2908 }
2909
2910 RenderStyle* RenderObject::cachedFirstLineStyle() const
2911 {
2912     ASSERT(document().styleEngine()->usesFirstLineRules());
2913
2914     if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
2915         return style.get();
2916
2917     return m_style.get();
2918 }
2919
2920 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2921 {
2922     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2923         return 0;
2924
2925     RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2926     if (cachedStyle)
2927         return cachedStyle;
2928
2929     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2930     if (result)
2931         return style()->addCachedPseudoStyle(result.release());
2932     return 0;
2933 }
2934
2935 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2936 {
2937     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
2938         return nullptr;
2939
2940     if (!parentStyle) {
2941         ASSERT(!ownStyle);
2942         parentStyle = style();
2943     }
2944
2945     // FIXME: This "find nearest element parent" should be a helper function.
2946     Node* n = node();
2947     while (n && !n->isElementNode())
2948         n = n->parentNode();
2949     if (!n)
2950         return nullptr;
2951     Element* element = toElement(n);
2952
2953     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2954         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
2955         result->setStyleType(FIRST_LINE_INHERITED);
2956         return result.release();
2957     }
2958
2959     return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2960 }
2961
2962 bool RenderObject::hasBlendMode() const
2963 {
2964     return RuntimeEnabledFeatures::cssCompositingEnabled() && style() && style()->hasBlendMode();
2965 }
2966
2967 static Color decorationColor(const RenderObject* object, RenderStyle* style)
2968 {
2969     // Check for text decoration color first.
2970     StyleColor result = style->visitedDependentDecorationColor();
2971     if (!result.isCurrentColor())
2972         return result.color();
2973
2974     if (style->textStrokeWidth() > 0) {
2975         // Prefer stroke color if possible but not if it's fully transparent.
2976         Color textStrokeColor = object->resolveColor(style, CSSPropertyWebkitTextStrokeColor);
2977         if (textStrokeColor.alpha())
2978             return textStrokeColor;
2979     }
2980
2981     return object->resolveColor(style, CSSPropertyWebkitTextFillColor);
2982 }
2983
2984 void RenderObject::getTextDecorations(unsigned decorations, AppliedTextDecoration& underline, AppliedTextDecoration& overline, AppliedTextDecoration& linethrough, bool quirksMode, bool firstlineStyle)
2985 {
2986     RenderObject* curr = this;
2987     RenderStyle* styleToUse = 0;
2988     unsigned currDecs = TextDecorationNone;
2989     Color resultColor;
2990     TextDecorationStyle resultStyle;
2991     do {
2992         styleToUse = curr->style(firstlineStyle);
2993         currDecs = styleToUse->textDecoration();
2994         currDecs &= decorations;
2995         resultColor = decorationColor(this, styleToUse);
2996         resultStyle = styleToUse->textDecorationStyle();
2997         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2998         if (currDecs) {
2999             if (currDecs & TextDecorationUnderline) {
3000                 decorations &= ~TextDecorationUnderline;
3001                 underline.color = resultColor;
3002                 underline.style = resultStyle;
3003             }
3004             if (currDecs & TextDecorationOverline) {
3005                 decorations &= ~TextDecorationOverline;
3006                 overline.color = resultColor;
3007                 overline.style = resultStyle;
3008             }
3009             if (currDecs & TextDecorationLineThrough) {
3010                 decorations &= ~TextDecorationLineThrough;
3011                 linethrough.color = resultColor;
3012                 linethrough.style = resultStyle;
3013             }
3014         }
3015         if (curr->isRubyText())
3016             return;
3017         curr = curr->parent();
3018         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
3019             curr = toRenderBlock(curr)->continuation();
3020     } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(*curr->node()) && !isHTMLFontElement(*curr->node()))));
3021
3022     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
3023     if (decorations && curr) {
3024         styleToUse = curr->style(firstlineStyle);
3025         resultColor = decorationColor(this, styleToUse);
3026         if (decorations & TextDecorationUnderline) {
3027             underline.color = resultColor;
3028             underline.style = resultStyle;
3029         }
3030         if (decorations & TextDecorationOverline) {
3031             overline.color = resultColor;
3032             overline.style = resultStyle;
3033         }
3034         if (decorations & TextDecorationLineThrough) {
3035             linethrough.color = resultColor;
3036             linethrough.style = resultStyle;
3037         }
3038     }
3039 }
3040
3041 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3042 {
3043     // Convert the style regions to absolute coordinates.
3044     if (style()->visibility() != VISIBLE || !isBox())
3045         return;
3046
3047     if (style()->getDraggableRegionMode() == DraggableRegionNone)
3048         return;
3049
3050     RenderBox* box = toRenderBox(this);
3051     FloatRect localBounds(FloatPoint(), FloatSize(box->width().toFloat(), box->height().toFloat()));
3052     FloatRect absBounds = localToAbsoluteQuad(localBounds).boundingBox();
3053
3054     AnnotatedRegionValue region;
3055     region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
3056     region.bounds = LayoutRect(absBounds);
3057     regions.append(region);
3058 }
3059
3060 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3061 {
3062     // RenderTexts don't have their own style, they just use their parent's style,
3063     // so we don't want to include them.
3064     if (isText())
3065         return;
3066
3067     addAnnotatedRegions(regions);
3068     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
3069         curr->collectAnnotatedRegions(regions);
3070 }
3071
3072 bool RenderObject::willRenderImage(ImageResource*)
3073 {
3074     // Without visibility we won't render (and therefore don't care about animation).
3075     if (style()->visibility() != VISIBLE)
3076         return false;
3077
3078     // We will not render a new image when Active DOM is suspended
3079     if (document().activeDOMObjectsAreSuspended())
3080         return false;
3081
3082     // If we're not in a window (i.e., we're dormant from being in a background tab)
3083     // then we don't want to render either.
3084     return document().view()->isVisible();
3085 }
3086
3087 int RenderObject::caretMinOffset() const
3088 {
3089     return 0;
3090 }
3091
3092 int RenderObject::caretMaxOffset() const
3093 {
3094     if (isReplaced())
3095         return node() ? max(1U, node()->countChildren()) : 1;
3096     if (isHR())
3097         return 1;
3098     return 0;
3099 }
3100
3101 int RenderObject::previousOffset(int current) const
3102 {
3103     return current - 1;
3104 }
3105
3106 int RenderObject::previousOffsetForBackwardDeletion(int current) const
3107 {
3108     return current - 1;
3109 }
3110
3111 int RenderObject::nextOffset(int current) const
3112 {
3113     return current + 1;
3114 }
3115
3116 bool RenderObject::isInert() const
3117 {
3118     const RenderObject* renderer = this;
3119     while (!renderer->node())
3120         renderer = renderer->parent();
3121     return renderer->node()->isInert();
3122 }
3123
3124 void RenderObject::imageChanged(ImageResource* image, const IntRect* rect)
3125 {
3126     imageChanged(static_cast<WrappedImagePtr>(image), rect);
3127 }
3128
3129 Element* RenderObject::offsetParent() const
3130 {
3131     if (isRoot() || isBody())
3132         return 0;
3133
3134     if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
3135         return 0;
3136
3137     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
3138     // chain return the nearest ancestor map HTML element and stop this algorithm.
3139     // FIXME: Implement!
3140
3141     float effectiveZoom = style()->effectiveZoom();
3142     Node* node = 0;
3143     for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
3144         // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
3145
3146         node = ancestor->node();
3147
3148         if (!node)
3149             continue;
3150
3151         if (ancestor->isPositioned())
3152             break;
3153
3154         if (isHTMLBodyElement(*node))
3155             break;
3156
3157         if (!isPositioned() && (isHTMLTableElement(*node) || isHTMLTableCellElement(*node)))
3158             break;
3159
3160         // Webkit specific extension where offsetParent stops at zoom level changes.
3161         if (effectiveZoom != ancestor->style()->effectiveZoom())
3162             break;
3163     }
3164
3165     return node && node->isElementNode() ? toElement(node) : 0;
3166 }
3167
3168 PositionWithAffinity RenderObject::createPositionWithAffinity(int offset, EAffinity affinity)
3169 {
3170     // If this is a non-anonymous renderer in an editable area, then it's simple.
3171     if (Node* node = nonPseudoNode()) {
3172         if (!node->rendererIsEditable()) {
3173             // If it can be found, we prefer a visually equivalent position that is editable.
3174             Position position = createLegacyEditingPosition(node, offset);
3175             Position candidate = position.downstream(CanCrossEditingBoundary);
3176             if (candidate.deprecatedNode()->rendererIsEditable())
3177                 return PositionWithAffinity(candidate, affinity);
3178             candidate = position.upstream(CanCrossEditingBoundary);
3179             if (candidate.deprecatedNode()->rendererIsEditable())
3180                 return PositionWithAffinity(candidate, affinity);
3181         }
3182         // FIXME: Eliminate legacy editing positions
3183         return PositionWithAffinity(createLegacyEditingPosition(node, offset), affinity);
3184     }
3185
3186     // We don't want to cross the boundary between editable and non-editable
3187     // regions of the document, but that is either impossible or at least
3188     // extremely unlikely in any normal case because we stop as soon as we
3189     // find a single non-anonymous renderer.
3190
3191     // Find a nearby non-anonymous renderer.
3192     RenderObject* child = this;
3193     while (RenderObject* parent = child->parent()) {
3194         // Find non-anonymous content after.
3195         RenderObject* renderer = child;
3196         while ((renderer = renderer->nextInPreOrder(parent))) {
3197             if (Node* node = renderer->nonPseudoNode())
3198                 return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3199         }
3200
3201         // Find non-anonymous content before.
3202         renderer = child;
3203         while ((renderer = renderer->previousInPreOrder())) {
3204             if (renderer == parent)
3205                 break;
3206             if (Node* node = renderer->nonPseudoNode())
3207                 return PositionWithAffinity(lastPositionInOrAfterNode(node), DOWNSTREAM);
3208         }
3209
3210         // Use the parent itself unless it too is anonymous.
3211         if (Node* node = parent->nonPseudoNode())
3212             return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3213
3214         // Repeat at the next level up.
3215         child = parent;
3216     }
3217
3218     // Everything was anonymous. Give up.
3219     return PositionWithAffinity();
3220 }
3221
3222 PositionWithAffinity RenderObject::createPositionWithAffinity(const Position& position)
3223 {
3224     if (position.isNotNull())
3225         return PositionWithAffinity(position);
3226
3227     ASSERT(!node());
3228     return createPositionWithAffinity(0, DOWNSTREAM);
3229 }
3230
3231 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
3232 {
3233     return SetCursorBasedOnStyle;
3234 }
3235
3236 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
3237 {
3238     if (needsLayout())
3239         return false;
3240
3241     RenderBlock* containingBlock = this->containingBlock();
3242     return containingBlock ? !containingBlock->needsLayout() : true;
3243 }
3244
3245 // We only create "generated" child renderers like one for first-letter if:
3246 // - the firstLetterBlock can have children in the DOM and
3247 // - the block doesn't have any special assumption on its text children.
3248 // This correctly prevents form controls from having such renderers.
3249 bool RenderObject::canHaveGeneratedChildren() const
3250 {
3251     return canHaveChildren();
3252 }
3253
3254 void RenderObject::setNeedsBoundariesUpdate()
3255 {
3256     if (RenderObject* renderer = parent())
3257         renderer->setNeedsBoundariesUpdate();
3258 }
3259
3260 FloatRect RenderObject::objectBoundingBox() const
3261 {
3262     ASSERT_NOT_REACHED();
3263     return FloatRect();
3264 }
3265
3266 FloatRect RenderObject::strokeBoundingBox() const
3267 {
3268     ASSERT_NOT_REACHED();
3269     return FloatRect();
3270 }
3271
3272 // Returns the smallest rectangle enclosing all of the painted content
3273 // respecting clipping, masking, filters, opacity, stroke-width and markers
3274 FloatRect RenderObject::repaintRectInLocalCoordinates() const
3275 {
3276     ASSERT_NOT_REACHED();
3277     return FloatRect();
3278 }
3279
3280 AffineTransform RenderObject::localTransform() const
3281 {
3282     static const AffineTransform identity;
3283     return identity;
3284 }
3285
3286 const AffineTransform& RenderObject::localToParentTransform() const
3287 {
3288     static const AffineTransform identity;
3289     return identity;
3290 }
3291
3292 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
3293 {
3294     ASSERT_NOT_REACHED();
3295     return false;
3296 }
3297
3298 bool RenderObject::isRelayoutBoundaryForInspector() const
3299 {
3300     return objectIsRelayoutBoundary(this);
3301 }
3302
3303 void RenderObject::clearRepaintState()
3304 {
3305     setShouldDoFullRepaintAfterLayout(false);
3306     setShouldDoFullRepaintIfSelfPaintingLayer(false);
3307     setShouldRepaintOverflow(false);
3308     setLayoutDidGetCalled(false);
3309 }
3310
3311 } // namespace WebCore
3312
3313 #ifndef NDEBUG
3314
3315 void showTree(const WebCore::RenderObject* object)
3316 {
3317     if (object)
3318         object->showTreeForThis();
3319 }
3320
3321 void showLineTree(const WebCore::RenderObject* object)
3322 {
3323     if (object)
3324         object->showLineTreeForThis();
3325 }
3326
3327 void showRenderTree(const WebCore::RenderObject* object1)
3328 {
3329     showRenderTree(object1, 0);
3330 }
3331
3332 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
3333 {
3334     if (object1) {
3335         const WebCore::RenderObject* root = object1;
3336         while (root->parent())
3337             root = root->parent();
3338         root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
3339     }
3340 }
3341
3342 #endif