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