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