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/)
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.
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.
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.
28 #include "core/rendering/RenderObject.h"
30 #include "core/HTMLNames.h"
31 #include "core/accessibility/AXObjectCache.h"
32 #include "core/css/resolver/StyleResolver.h"
33 #include "core/dom/ElementTraversal.h"
34 #include "core/dom/StyleEngine.h"
35 #include "core/dom/shadow/ShadowRoot.h"
36 #include "core/editing/EditingBoundary.h"
37 #include "core/editing/FrameSelection.h"
38 #include "core/editing/htmlediting.h"
39 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
40 #include "core/fetch/ResourceLoader.h"
41 #include "core/frame/EventHandlerRegistry.h"
42 #include "core/frame/FrameView.h"
43 #include "core/frame/LocalFrame.h"
44 #include "core/html/HTMLAnchorElement.h"
45 #include "core/html/HTMLElement.h"
46 #include "core/html/HTMLHtmlElement.h"
47 #include "core/html/HTMLTableCellElement.h"
48 #include "core/html/HTMLTableElement.h"
49 #include "core/page/AutoscrollController.h"
50 #include "core/page/EventHandler.h"
51 #include "core/page/Page.h"
52 #include "core/frame/Settings.h"
53 #include "core/frame/UseCounter.h"
54 #include "core/rendering/FlowThreadController.h"
55 #include "core/rendering/HitTestResult.h"
56 #include "core/rendering/RenderCounter.h"
57 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
58 #include "core/rendering/RenderFlexibleBox.h"
59 #include "core/rendering/RenderFlowThread.h"
60 #include "core/rendering/RenderGeometryMap.h"
61 #include "core/rendering/RenderGrid.h"
62 #include "core/rendering/RenderImage.h"
63 #include "core/rendering/RenderImageResourceStyleImage.h"
64 #include "core/rendering/RenderInline.h"
65 #include "core/rendering/RenderLayer.h"
66 #include "core/rendering/RenderListItem.h"
67 #include "core/rendering/RenderMarquee.h"
68 #include "core/rendering/RenderObjectInlines.h"
69 #include "core/rendering/RenderScrollbarPart.h"
70 #include "core/rendering/RenderTableCaption.h"
71 #include "core/rendering/RenderTableCell.h"
72 #include "core/rendering/RenderTableCol.h"
73 #include "core/rendering/RenderTableRow.h"
74 #include "core/rendering/RenderTheme.h"
75 #include "core/rendering/RenderView.h"
76 #include "core/rendering/compositing/CompositedLayerMapping.h"
77 #include "core/rendering/compositing/RenderLayerCompositor.h"
78 #include "core/rendering/style/ContentData.h"
79 #include "core/rendering/style/ShadowList.h"
80 #include "platform/JSONValues.h"
81 #include "platform/Partitions.h"
82 #include "platform/RuntimeEnabledFeatures.h"
83 #include "platform/TraceEvent.h"
84 #include "platform/TracedValue.h"
85 #include "platform/geometry/TransformState.h"
86 #include "platform/graphics/GraphicsContext.h"
87 #include "wtf/RefCountedLeakCounter.h"
88 #include "wtf/text/StringBuilder.h"
89 #include "wtf/text/WTFString.h"
99 static bool gModifyRenderTreeStructureAnyState = false;
103 using namespace HTMLNames;
107 RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject& renderObject)
108 : m_renderObject(renderObject)
109 , m_preexistingForbidden(m_renderObject.isSetNeedsLayoutForbidden())
111 m_renderObject.setNeedsLayoutIsForbidden(true);
114 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
116 m_renderObject.setNeedsLayoutIsForbidden(m_preexistingForbidden);
120 struct SameSizeAsRenderObject {
121 virtual ~SameSizeAsRenderObject() { } // Allocate vtable pointer.
124 unsigned m_debugBitfields : 2;
126 unsigned m_oilpanBitfields : 1;
129 unsigned m_bitfields;
130 unsigned m_bitfields2;
131 LayoutRect rect; // Stores the previous paint invalidation rect.
132 LayoutPoint position; // Stores the previous position from the paint invalidation container.
135 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
137 bool RenderObject::s_affectsParentBlock = false;
140 void* RenderObject::operator new(size_t sz)
142 ASSERT(isMainThread());
143 return partitionAlloc(Partitions::getRenderingPartition(), sz);
146 void RenderObject::operator delete(void* ptr)
148 ASSERT(isMainThread());
153 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
155 ASSERT(isAllowedToModifyRenderTreeStructure(element->document()));
157 // Minimal support for content properties replacing an entire element.
158 // Works only if we have exactly one piece of content and it's a URL.
159 // Otherwise acts as if we didn't support this feature.
160 const ContentData* contentData = style->contentData();
161 if (contentData && !contentData->next() && contentData->isImage() && !element->isPseudoElement()) {
162 RenderImage* image = new RenderImage(element);
163 // RenderImageResourceStyleImage requires a style being present on the image but we don't want to
164 // trigger a style change now as the node is not fully attached. Moving this code to style change
165 // doesn't make sense as it should be run once at renderer creation.
166 image->setStyleInternal(style);
167 if (const StyleImage* styleImage = toImageContentData(contentData)->image()) {
168 image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
169 image->setIsGeneratedContent();
171 image->setImageResource(RenderImageResource::create());
172 image->setStyleInternal(nullptr);
176 switch (style->display()) {
180 return new RenderInline(element);
183 return new RenderBlockFlow(element);
185 return new RenderListItem(element);
188 return new RenderTable(element);
189 case TABLE_ROW_GROUP:
190 case TABLE_HEADER_GROUP:
191 case TABLE_FOOTER_GROUP:
192 return new RenderTableSection(element);
194 return new RenderTableRow(element);
195 case TABLE_COLUMN_GROUP:
197 return new RenderTableCol(element);
199 return new RenderTableCell(element);
201 return new RenderTableCaption(element);
204 return new RenderDeprecatedFlexibleBox(*element);
207 return new RenderFlexibleBox(element);
210 return new RenderGrid(element);
216 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
217 unsigned RenderObject::s_instanceCount = 0;
219 RenderObject::RenderObject(Node* node)
220 : ImageResourceClient()
224 , m_previous(nullptr)
227 , m_hasAXObject(false)
228 , m_setNeedsLayoutForbidden(false)
230 , m_didCallDestroy(false)
236 renderObjectCounter.increment();
241 RenderObject::~RenderObject()
243 ASSERT(!m_hasAXObject);
245 ASSERT(m_didCallDestroy);
248 renderObjectCounter.decrement();
253 void RenderObject::trace(Visitor* visitor)
255 visitor->trace(m_node);
256 visitor->trace(m_parent);
257 visitor->trace(m_previous);
258 visitor->trace(m_next);
261 String RenderObject::debugName() const
264 name.append(renderName());
266 if (Node* node = this->node()) {
268 name.append(node->debugName());
271 return name.toString();
274 bool RenderObject::isDescendantOf(const RenderObject* obj) const
276 for (const RenderObject* r = this; r; r = r->m_parent) {
283 bool RenderObject::isHR() const
285 return isHTMLHRElement(node());
288 bool RenderObject::isLegend() const
290 return isHTMLLegendElement(node());
293 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
295 for (RenderObject *object = this; object; object = object->nextInPreOrder(this)) {
296 // If object is a fragmentation context it already updated the descendants flag accordingly.
297 if (object->isRenderFlowThread())
299 ASSERT(state != object->flowThreadState());
300 object->setFlowThreadState(state);
304 bool RenderObject::requiresAnonymousTableWrappers(const RenderObject* newChild) const
306 // Check should agree with:
307 // CSS 2.1 Tables: 17.2.1 Anonymous table objects
308 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
309 if (newChild->isRenderTableCol()) {
310 const RenderTableCol* newTableColumn = toRenderTableCol(newChild);
311 bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isRenderTableCol();
312 return !isTable() && !isColumnInColumnGroup;
313 } else if (newChild->isTableCaption())
315 else if (newChild->isTableSection())
317 else if (newChild->isTableRow())
318 return !isTableSection();
319 else if (newChild->isTableCell())
320 return !isTableRow();
324 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
326 ASSERT(isAllowedToModifyRenderTreeStructure(document()));
328 RenderObjectChildList* children = virtualChildren();
333 if (requiresAnonymousTableWrappers(newChild)) {
334 // Generate an anonymous table or reuse existing one from previous child
335 // Per: 17.2.1 Anonymous table objects 3. Generate missing parents
336 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
338 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
339 if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent())
340 table = toRenderTable(afterChild);
342 table = RenderTable::createAnonymousWithParentRenderer(this);
343 addChild(table, beforeChild);
345 table->addChild(newChild);
347 children->insertChildNode(this, newChild, beforeChild);
349 if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE)
350 toRenderText(newChild)->transformText();
352 // SVG creates renderers for <g display="none">, as SVG requires children of hidden
353 // <g>s to have renderers - at least that's how our implementation works. Consider:
354 // <g display="none"><foreignObject><body style="position: relative">FOO...
355 // - layerTypeRequired() would return true for the <body>, creating a new RenderLayer
356 // - when the document is painted, both layers are painted. The <body> layer doesn't
357 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
358 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
359 // and stop creating layers at all for these cases - they're not used anyways.
360 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
361 toRenderLayerModelObject(newChild)->layer()->removeOnlyThisLayer();
364 void RenderObject::removeChild(RenderObject* oldChild)
366 ASSERT(isAllowedToModifyRenderTreeStructure(document()));
368 RenderObjectChildList* children = virtualChildren();
373 children->removeChildNode(this, oldChild);
376 RenderObject* RenderObject::nextInPreOrder() const
378 if (RenderObject* o = slowFirstChild())
381 return nextInPreOrderAfterChildren();
384 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
386 RenderObject* o = nextSibling();
389 while (o && !o->nextSibling())
392 o = o->nextSibling();
398 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
400 if (RenderObject* o = slowFirstChild())
403 return nextInPreOrderAfterChildren(stayWithin);
406 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
408 if (this == stayWithin)
411 const RenderObject* current = this;
412 RenderObject* next = current->nextSibling();
413 for (; !next; next = current->nextSibling()) {
414 current = current->parent();
415 if (!current || current == stayWithin)
421 RenderObject* RenderObject::previousInPreOrder() const
423 if (RenderObject* o = previousSibling()) {
424 while (RenderObject* lastChild = o->slowLastChild())
432 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
434 if (this == stayWithin)
437 return previousInPreOrder();
440 RenderObject* RenderObject::childAt(unsigned index) const
442 RenderObject* child = slowFirstChild();
443 for (unsigned i = 0; child && i < index; i++)
444 child = child->nextSibling();
448 RenderObject* RenderObject::lastLeafChild() const
450 RenderObject* r = slowLastChild();
453 n = r->slowLastChild();
461 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
462 RenderLayer*& beforeChild)
464 if (obj->hasLayer()) {
465 if (!beforeChild && newObject) {
466 // We need to figure out the layer that follows newObject. We only do
467 // this the first time we find a child layer, and then we update the
468 // pointer values for newObject and beforeChild used by everyone else.
469 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
472 parentLayer->addChild(toRenderLayerModelObject(obj)->layer(), beforeChild);
476 for (RenderObject* curr = obj->slowFirstChild(); curr; curr = curr->nextSibling())
477 addLayers(curr, parentLayer, newObject, beforeChild);
480 void RenderObject::addLayers(RenderLayer* parentLayer)
485 RenderObject* object = this;
486 RenderLayer* beforeChild = 0;
487 blink::addLayers(this, parentLayer, object, beforeChild);
490 void RenderObject::removeLayers(RenderLayer* parentLayer)
496 parentLayer->removeChild(toRenderLayerModelObject(this)->layer());
500 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
501 curr->removeLayers(parentLayer);
504 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
510 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
511 ASSERT(oldParent == layer->parent());
513 oldParent->removeChild(layer);
514 newParent->addChild(layer);
518 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
519 curr->moveLayers(oldParent, newParent);
522 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
525 // Error check the parent layer passed in. If it's null, we can't find anything.
529 // Step 1: If our layer is a child of the desired parent, then return our layer.
530 RenderLayer* ourLayer = hasLayer() ? toRenderLayerModelObject(this)->layer() : 0;
531 if (ourLayer && ourLayer->parent() == parentLayer)
534 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
535 // into our siblings trying to find the next layer whose parent is the desired parent.
536 if (!ourLayer || ourLayer == parentLayer) {
537 for (RenderObject* curr = startPoint ? startPoint->nextSibling() : slowFirstChild();
538 curr; curr = curr->nextSibling()) {
539 RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
545 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
547 if (parentLayer == ourLayer)
550 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
551 // follow us to see if we can locate a layer.
552 if (checkParent && parent())
553 return parent()->findNextLayer(parentLayer, this, true);
558 RenderLayer* RenderObject::enclosingLayer() const
560 for (const RenderObject* current = this; current; current = current->parent()) {
561 if (current->hasLayer())
562 return toRenderLayerModelObject(current)->layer();
564 // FIXME: We should remove the one caller that triggers this case and make
565 // this function return a reference.
566 ASSERT(!m_parent && !isRenderView());
570 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
572 RenderBox* enclosingBox = this->enclosingBox();
576 enclosingBox->scrollRectToVisible(rect, alignX, alignY);
580 RenderBox* RenderObject::enclosingBox() const
582 RenderObject* curr = const_cast<RenderObject*>(this);
585 return toRenderBox(curr);
586 curr = curr->parent();
589 ASSERT_NOT_REACHED();
593 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
595 RenderObject* curr = const_cast<RenderObject*>(this);
597 if (curr->isBoxModelObject())
598 return toRenderBoxModelObject(curr);
599 curr = curr->parent();
602 ASSERT_NOT_REACHED();
606 RenderBox* RenderObject::enclosingScrollableBox() const
608 for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
609 if (!ancestor->isBox())
612 RenderBox* ancestorBox = toRenderBox(ancestor);
613 if (ancestorBox->canBeScrolledAndHasScrollableArea())
620 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
622 ASSERT(flowThreadState() != NotInsideFlowThread);
624 // See if we have the thread cached because we're in the middle of layout.
625 RenderFlowThread* flowThread = view()->flowThreadController()->currentRenderFlowThread();
629 // Not in the middle of layout so have to find the thread the slow way.
630 RenderObject* curr = const_cast<RenderObject*>(this);
632 if (curr->isRenderFlowThread())
633 return toRenderFlowThread(curr);
634 curr = curr->containingBlock();
639 bool RenderObject::skipInvalidationWhenLaidOutChildren() const
641 if (!neededLayoutBecauseOfChildren())
644 // SVG renderers need to be invalidated when their children are laid out.
645 // RenderBlocks with line boxes are responsible to invalidate them so we can't ignore them.
646 if (isSVG() || (isRenderBlockFlow() && toRenderBlockFlow(this)->firstLineBox()))
649 return rendererHasNoBoxEffect();
652 RenderBlock* RenderObject::firstLineBlock() const
657 static inline bool objectIsRelayoutBoundary(const RenderObject* object)
659 // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
660 if (object->isTextControl())
663 if (object->isSVGRoot())
666 if (!object->hasOverflowClip())
669 if (object->style()->width().isIntrinsicOrAuto() || object->style()->height().isIntrinsicOrAuto() || object->style()->height().isPercent())
672 // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
673 if (object->isTablePart())
679 void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot, SubtreeLayoutScope* layouter)
681 ASSERT(!scheduleRelayout || !newRoot);
682 ASSERT(!isSetNeedsLayoutForbidden());
683 ASSERT(!layouter || this != layouter->root());
685 RenderObject* object = container();
686 RenderObject* last = this;
688 bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
691 if (object->selfNeedsLayout())
694 // Don't mark the outermost object of an unrooted subtree. That object will be
695 // marked when the subtree is added to the document.
696 RenderObject* container = object->container();
697 if (!container && !object->isRenderView())
699 if (!last->isText() && last->style()->hasOutOfFlowPosition()) {
700 bool willSkipRelativelyPositionedInlines = !object->isRenderBlock() || object->isAnonymousBlock();
701 // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
702 while (object && (!object->isRenderBlock() || object->isAnonymousBlock()))
703 object = object->container();
704 if (!object || object->posChildNeedsLayout())
706 if (willSkipRelativelyPositionedInlines)
707 container = object->container();
708 object->setPosChildNeedsLayout(true);
709 simplifiedNormalFlowLayout = true;
710 ASSERT(!object->isSetNeedsLayoutForbidden());
711 } else if (simplifiedNormalFlowLayout) {
712 if (object->needsSimplifiedNormalFlowLayout())
714 object->setNeedsSimplifiedNormalFlowLayout(true);
715 ASSERT(!object->isSetNeedsLayoutForbidden());
717 if (object->normalChildNeedsLayout())
719 object->setNormalChildNeedsLayout(true);
720 ASSERT(!object->isSetNeedsLayoutForbidden());
724 layouter->addRendererToLayout(object);
725 if (object == layouter->root())
729 if (object == newRoot)
733 if (scheduleRelayout && objectIsRelayoutBoundary(last))
738 if (scheduleRelayout)
739 last->scheduleRelayout();
743 void RenderObject::checkBlockPositionedObjectsNeedLayout()
745 ASSERT(!needsLayout());
748 toRenderBlock(this)->checkPositionedObjectsNeedLayout();
752 void RenderObject::setPreferredLogicalWidthsDirty(MarkingBehavior markParents)
754 m_bitfields.setPreferredLogicalWidthsDirty(true);
755 if (markParents == MarkContainingBlockChain && (isText() || !style()->hasOutOfFlowPosition()))
756 invalidateContainerPreferredLogicalWidths();
759 void RenderObject::clearPreferredLogicalWidthsDirty()
761 m_bitfields.setPreferredLogicalWidthsDirty(false);
764 void RenderObject::invalidateContainerPreferredLogicalWidths()
766 // In order to avoid pathological behavior when inlines are deeply nested, we do include them
767 // in the chain that we mark dirty (even though they're kind of irrelevant).
768 RenderObject* o = isTableCell() ? containingBlock() : container();
769 while (o && !o->preferredLogicalWidthsDirty()) {
770 // Don't invalidate the outermost object of an unrooted subtree. That object will be
771 // invalidated when the subtree is added to the document.
772 RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
773 if (!container && !o->isRenderView())
776 o->m_bitfields.setPreferredLogicalWidthsDirty(true);
777 if (o->style()->hasOutOfFlowPosition())
778 // A positioned object has no effect on the min/max width of its containing block ever.
779 // We can optimize this case and not go up any further.
785 RenderBlock* RenderObject::containerForFixedPosition(const RenderLayerModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
787 ASSERT(!paintInvalidationContainerSkipped || !*paintInvalidationContainerSkipped);
789 ASSERT(style()->position() == FixedPosition);
791 RenderObject* ancestor = parent();
792 for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
793 if (paintInvalidationContainerSkipped && ancestor == paintInvalidationContainer)
794 *paintInvalidationContainerSkipped = true;
797 ASSERT(!ancestor || !ancestor->isAnonymousBlock());
798 return toRenderBlock(ancestor);
801 RenderBlock* RenderObject::containingBlock() const
803 RenderObject* o = parent();
804 if (!o && isRenderScrollbarPart())
805 o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
806 if (!isText() && m_style->position() == FixedPosition) {
807 return containerForFixedPosition();
808 } else if (!isText() && m_style->position() == AbsolutePosition) {
810 // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
811 // to return the inline itself. This allows us to avoid having a positioned objects
812 // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
813 // from this method. The container() method can actually be used to obtain the
815 if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
818 if (o->canContainFixedPositionObjects())
821 if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
822 o = o->containingBlock();
829 if (o && !o->isRenderBlock())
830 o = o->containingBlock();
832 while (o && o->isAnonymousBlock())
833 o = o->containingBlock();
835 while (o && ((o->isInline() && !o->isReplaced()) || !o->isRenderBlock()))
839 if (!o || !o->isRenderBlock())
840 return 0; // This can still happen in case of an orphaned tree
842 return toRenderBlock(o);
845 bool RenderObject::canRenderBorderImage() const
847 ASSERT(style()->hasBorder());
849 StyleImage* borderImage = style()->borderImage().image();
850 return borderImage && borderImage->canRender(*this, style()->effectiveZoom()) && borderImage->isLoaded();
853 bool RenderObject::mustInvalidateFillLayersPaintOnWidthChange(const FillLayer& layer) const
855 // Nobody will use multiple layers without wanting fancy positioning.
859 // Make sure we have a valid image.
860 StyleImage* img = layer.image();
861 if (!img || !img->canRender(*this, style()->effectiveZoom()))
864 if (layer.repeatX() != RepeatFill && layer.repeatX() != NoRepeatFill)
867 if (layer.xPosition().isPercent() && !layer.xPosition().isZero())
870 if (layer.backgroundXOrigin() != LeftEdge)
873 EFillSizeType sizeType = layer.sizeType();
875 if (sizeType == Contain || sizeType == Cover)
878 if (sizeType == SizeLength) {
879 if (layer.sizeLength().width().isPercent() && !layer.sizeLength().width().isZero())
881 if (img->isGeneratedImage() && layer.sizeLength().width().isAuto())
883 } else if (img->usesImageContainerSize()) {
890 bool RenderObject::mustInvalidateFillLayersPaintOnHeightChange(const FillLayer& layer) const
892 // Nobody will use multiple layers without wanting fancy positioning.
896 // Make sure we have a valid image.
897 StyleImage* img = layer.image();
898 if (!img || !img->canRender(*this, style()->effectiveZoom()))
901 if (layer.repeatY() != RepeatFill && layer.repeatY() != NoRepeatFill)
904 if (layer.yPosition().isPercent() && !layer.yPosition().isZero())
907 if (layer.backgroundYOrigin() != TopEdge)
910 EFillSizeType sizeType = layer.sizeType();
912 if (sizeType == Contain || sizeType == Cover)
915 if (sizeType == SizeLength) {
916 if (layer.sizeLength().height().isPercent() && !layer.sizeLength().height().isZero())
918 if (img->isGeneratedImage() && layer.sizeLength().height().isAuto())
920 } else if (img->usesImageContainerSize()) {
927 bool RenderObject::mustInvalidateBackgroundOrBorderPaintOnWidthChange() const
929 if (hasMask() && mustInvalidateFillLayersPaintOnWidthChange(style()->maskLayers()))
932 // If we don't have a background/border/mask, then nothing to do.
933 if (!hasBoxDecorationBackground())
936 if (mustInvalidateFillLayersPaintOnWidthChange(style()->backgroundLayers()))
939 // Our fill layers are ok. Let's check border.
940 if (style()->hasBorder() && canRenderBorderImage())
946 bool RenderObject::mustInvalidateBackgroundOrBorderPaintOnHeightChange() const
948 if (hasMask() && mustInvalidateFillLayersPaintOnHeightChange(style()->maskLayers()))
951 // If we don't have a background/border/mask, then nothing to do.
952 if (!hasBoxDecorationBackground())
955 if (mustInvalidateFillLayersPaintOnHeightChange(style()->backgroundLayers()))
958 // Our fill layers are ok. Let's check border.
959 if (style()->hasBorder() && canRenderBorderImage())
965 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
966 BoxSide side, Color color, EBorderStyle style,
967 int adjacentWidth1, int adjacentWidth2, bool antialias)
971 if (side == BSTop || side == BSBottom) {
979 // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
980 // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
981 if (!thickness || !length)
984 if (style == DOUBLE && thickness < 3)
993 drawDashedOrDottedBoxSide(graphicsContext, x1, y1, x2, y2, side,
994 color, thickness, style, antialias);
997 drawDoubleBoxSide(graphicsContext, x1, y1, x2, y2, length, side, color,
998 thickness, adjacentWidth1, adjacentWidth2, antialias);
1002 drawRidgeOrGrooveBoxSide(graphicsContext, x1, y1, x2, y2, side, color,
1003 style, adjacentWidth1, adjacentWidth2, antialias);
1006 // FIXME: Maybe we should lighten the colors on one side like Firefox.
1007 // https://bugs.webkit.org/show_bug.cgi?id=58608
1008 if (side == BSTop || side == BSLeft)
1009 color = color.dark();
1012 if (style == OUTSET && (side == BSBottom || side == BSRight))
1013 color = color.dark();
1016 drawSolidBoxSide(graphicsContext, x1, y1, x2, y2, side, color, adjacentWidth1, adjacentWidth2, antialias);
1021 void RenderObject::drawDashedOrDottedBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1022 BoxSide side, Color color, int thickness, EBorderStyle style, bool antialias)
1027 bool wasAntialiased = graphicsContext->shouldAntialias();
1028 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1029 graphicsContext->setShouldAntialias(antialias);
1030 graphicsContext->setStrokeColor(color);
1031 graphicsContext->setStrokeThickness(thickness);
1032 graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
1037 graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
1041 graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
1044 graphicsContext->setShouldAntialias(wasAntialiased);
1045 graphicsContext->setStrokeStyle(oldStrokeStyle);
1048 void RenderObject::drawDoubleBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1049 int length, BoxSide side, Color color, int thickness, int adjacentWidth1, int adjacentWidth2, bool antialias)
1051 int thirdOfThickness = (thickness + 1) / 3;
1052 ASSERT(thirdOfThickness);
1054 if (!adjacentWidth1 && !adjacentWidth2) {
1055 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1056 graphicsContext->setStrokeStyle(NoStroke);
1057 graphicsContext->setFillColor(color);
1059 bool wasAntialiased = graphicsContext->shouldAntialias();
1060 graphicsContext->setShouldAntialias(antialias);
1065 graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
1066 graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
1070 // FIXME: Why do we offset the border by 1 in this case but not the other one?
1072 graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
1073 graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
1078 graphicsContext->setShouldAntialias(wasAntialiased);
1079 graphicsContext->setStrokeStyle(oldStrokeStyle);
1083 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
1084 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
1088 drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
1089 y1, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1090 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1091 drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
1092 y2 - thirdOfThickness, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
1093 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1096 drawLineForBoxSide(graphicsContext, x1, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
1097 x1 + thirdOfThickness, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
1098 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1099 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
1100 x2, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
1101 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1104 drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
1105 y1, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1106 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1107 drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
1108 y2 - thirdOfThickness, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
1109 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1112 drawLineForBoxSide(graphicsContext, x1, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0),
1113 x1 + thirdOfThickness, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0),
1114 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1115 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0),
1116 x2, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0),
1117 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1124 void RenderObject::drawRidgeOrGrooveBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1125 BoxSide side, Color color, EBorderStyle style, int adjacentWidth1, int adjacentWidth2, bool antialias)
1129 if (style == GROOVE) {
1137 int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
1138 int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
1142 drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1, 0) / 2, y1, x2 - std::max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1143 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1144 drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(adjacentWidth2 + 1, 0) / 2, y2,
1145 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1148 drawLineForBoxSide(graphicsContext, x1, y1 + std::max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(-adjacentWidth2, 0) / 2,
1149 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1150 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(adjacentWidth2 + 1, 0) / 2,
1151 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1154 drawLineForBoxSide(graphicsContext, x1 + std::max(adjacentWidth1, 0) / 2, y1, x2 - std::max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1155 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1156 drawLineForBoxSide(graphicsContext, x1 + std::max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - std::max(-adjacentWidth2 + 1, 0) / 2, y2,
1157 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1160 drawLineForBoxSide(graphicsContext, x1, y1 + std::max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - std::max(adjacentWidth2, 0) / 2,
1161 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1162 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + std::max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - std::max(-adjacentWidth2 + 1, 0) / 2,
1163 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1168 void RenderObject::drawSolidBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1169 BoxSide side, Color color, int adjacentWidth1, int adjacentWidth2, bool antialias)
1171 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1172 graphicsContext->setStrokeStyle(NoStroke);
1173 graphicsContext->setFillColor(color);
1176 if (!adjacentWidth1 && !adjacentWidth2) {
1177 // Turn off antialiasing to match the behavior of drawConvexPolygon();
1178 // this matters for rects in transformed contexts.
1179 bool wasAntialiased = graphicsContext->shouldAntialias();
1180 graphicsContext->setShouldAntialias(antialias);
1181 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
1182 graphicsContext->setShouldAntialias(wasAntialiased);
1183 graphicsContext->setStrokeStyle(oldStrokeStyle);
1189 quad[0] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y1);
1190 quad[1] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y2);
1191 quad[2] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y2);
1192 quad[3] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y1);
1195 quad[0] = FloatPoint(x1 + std::max(adjacentWidth1, 0), y1);
1196 quad[1] = FloatPoint(x1 + std::max(-adjacentWidth1, 0), y2);
1197 quad[2] = FloatPoint(x2 - std::max(-adjacentWidth2, 0), y2);
1198 quad[3] = FloatPoint(x2 - std::max(adjacentWidth2, 0), y1);
1201 quad[0] = FloatPoint(x1, y1 + std::max(-adjacentWidth1, 0));
1202 quad[1] = FloatPoint(x1, y2 - std::max(-adjacentWidth2, 0));
1203 quad[2] = FloatPoint(x2, y2 - std::max(adjacentWidth2, 0));
1204 quad[3] = FloatPoint(x2, y1 + std::max(adjacentWidth1, 0));
1207 quad[0] = FloatPoint(x1, y1 + std::max(adjacentWidth1, 0));
1208 quad[1] = FloatPoint(x1, y2 - std::max(adjacentWidth2, 0));
1209 quad[2] = FloatPoint(x2, y2 - std::max(-adjacentWidth2, 0));
1210 quad[3] = FloatPoint(x2, y1 + std::max(-adjacentWidth1, 0));
1214 graphicsContext->drawConvexPolygon(4, quad, antialias);
1215 graphicsContext->setStrokeStyle(oldStrokeStyle);
1218 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
1220 Vector<IntRect> focusRingRects;
1221 addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer());
1222 if (style->outlineStyleIsAuto())
1223 paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), resolveColor(style, CSSPropertyOutlineColor));
1225 addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
1228 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
1233 if (!n || !n->isLink() || !n->isElementNode())
1235 const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
1238 KURL url = n->document().completeURL(href);
1241 if (context->supportsURLFragments() && url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, n->document().baseURL())) {
1242 String name = url.fragmentIdentifier();
1243 if (document().findAnchor(name))
1244 context->setURLFragmentForRect(name, pixelSnappedIntRect(rect));
1247 context->setURLForRect(url, pixelSnappedIntRect(rect));
1250 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1255 RenderStyle* styleToUse = outlineStyle();
1256 LayoutUnit outlineWidth = styleToUse->outlineWidth();
1258 int outlineOffset = styleToUse->outlineOffset();
1260 if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1261 if (RenderTheme::theme().shouldDrawDefaultFocusRing(this)) {
1262 // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1263 paintFocusRing(paintInfo, paintRect.location(), styleToUse);
1267 if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1270 IntRect inner = pixelSnappedIntRect(paintRect);
1271 inner.inflate(outlineOffset);
1273 IntRect outer = pixelSnappedIntRect(inner);
1274 outer.inflate(outlineWidth);
1276 // FIXME: This prevents outlines from painting inside the object. See bug 12042
1277 if (outer.isEmpty())
1280 EBorderStyle outlineStyle = styleToUse->outlineStyle();
1281 Color outlineColor = resolveColor(styleToUse, CSSPropertyOutlineColor);
1283 GraphicsContext* graphicsContext = paintInfo.context;
1284 bool useTransparencyLayer = outlineColor.hasAlpha();
1285 if (useTransparencyLayer) {
1286 if (outlineStyle == SOLID) {
1288 path.addRect(outer);
1289 path.addRect(inner);
1290 graphicsContext->setFillRule(RULE_EVENODD);
1291 graphicsContext->setFillColor(outlineColor);
1292 graphicsContext->fillPath(path);
1295 graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1296 outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1299 int leftOuter = outer.x();
1300 int leftInner = inner.x();
1301 int rightOuter = outer.maxX();
1302 int rightInner = inner.maxX();
1303 int topOuter = outer.y();
1304 int topInner = inner.y();
1305 int bottomOuter = outer.maxY();
1306 int bottomInner = inner.maxY();
1308 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1309 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1310 drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1311 drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1313 if (useTransparencyLayer)
1314 graphicsContext->endLayer();
1317 void RenderObject::addChildFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer) const
1319 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling()) {
1320 if (current->isText() || current->isListMarker())
1323 if (current->isBox()) {
1324 RenderBox* box = toRenderBox(current);
1325 if (box->hasLayer()) {
1326 Vector<IntRect> layerFocusRingRects;
1327 box->addFocusRingRects(layerFocusRingRects, LayoutPoint(), box);
1328 for (size_t i = 0; i < layerFocusRingRects.size(); ++i) {
1329 FloatQuad quadInBox = box->localToContainerQuad(FloatRect(layerFocusRingRects[i]), paintContainer);
1330 rects.append(pixelSnappedIntRect(LayoutRect(quadInBox.boundingBox())));
1333 FloatPoint pos(additionalOffset);
1334 pos.move(box->locationOffset()); // FIXME: Snap offsets? crbug.com/350474
1335 box->addFocusRingRects(rects, flooredIntPoint(pos), paintContainer);
1338 current->addFocusRingRects(rects, additionalOffset, paintContainer);
1343 LayoutPoint RenderObject::positionFromPaintInvalidationContainer(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1345 // FIXME: This assert should be re-enabled when we move paint invalidation to after compositing update. crbug.com/360286
1346 // ASSERT(containerForPaintInvalidation() == paintInvalidationContainer);
1348 if (paintInvalidationContainer == this)
1349 return LayoutPoint();
1351 return LayoutPoint(localToContainerPoint(LayoutPoint(), paintInvalidationContainer, 0, 0, paintInvalidationState));
1354 IntRect RenderObject::absoluteBoundingBoxRect() const
1356 Vector<FloatQuad> quads;
1357 absoluteQuads(quads);
1359 size_t n = quads.size();
1363 IntRect result = quads[0].enclosingBoundingBox();
1364 for (size_t i = 1; i < n; ++i)
1365 result.unite(quads[i].enclosingBoundingBox());
1369 IntRect RenderObject::absoluteBoundingBoxRectIgnoringTransforms() const
1371 FloatPoint absPos = localToAbsolute();
1372 Vector<IntRect> rects;
1373 absoluteRects(rects, flooredLayoutPoint(absPos));
1375 size_t n = rects.size();
1379 LayoutRect result = rects[0];
1380 for (size_t i = 1; i < n; ++i)
1381 result.unite(rects[i]);
1382 return pixelSnappedIntRect(result);
1385 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1387 Vector<IntRect> rects;
1388 const RenderLayerModelObject* container = containerForPaintInvalidation();
1389 addFocusRingRects(rects, LayoutPoint(localToContainerPoint(FloatPoint(), container)), container);
1390 size_t count = rects.size();
1391 for (size_t i = 0; i < count; ++i)
1392 quads.append(container->localToAbsoluteQuad(FloatQuad(rects[i])));
1395 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1397 if (!range || !range->startContainer())
1400 range->ownerDocument().updateLayout();
1402 Vector<FloatQuad> quads;
1403 range->textQuads(quads);
1406 for (size_t i = 0; i < quads.size(); ++i)
1407 result.unite(quads[i].boundingBox());
1412 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1415 result.unite(absoluteBoundingBoxRect());
1416 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling())
1417 current->addAbsoluteRectForLayer(result);
1420 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1422 LayoutRect result = absoluteBoundingBoxRect();
1423 topLevelRect = result;
1424 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling())
1425 current->addAbsoluteRectForLayer(result);
1429 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1433 const RenderLayerModelObject* RenderObject::containerForPaintInvalidation() const
1438 return adjustCompositedContainerForSpecialAncestors(enclosingCompositedContainer());
1441 const RenderLayerModelObject* RenderObject::enclosingCompositedContainer() const
1443 RenderLayerModelObject* container = 0;
1444 if (view()->usesCompositing()) {
1445 // FIXME: CompositingState is not necessarily up to date for many callers of this function.
1446 DisableCompositingQueryAsserts disabler;
1448 if (RenderLayer* compositingLayer = enclosingLayer()->enclosingLayerForPaintInvalidation())
1449 container = compositingLayer->renderer();
1454 const RenderLayerModelObject* RenderObject::adjustCompositedContainerForSpecialAncestors(const RenderLayerModelObject* paintInvalidationContainer) const
1457 if (document().view()->hasSoftwareFilters()) {
1458 if (RenderLayer* enclosingFilterLayer = enclosingLayer()->enclosingFilterLayer())
1459 return enclosingFilterLayer->renderer();
1462 // If we have a flow thread, then we need to do individual paint invalidations within the RenderRegions instead.
1463 // Return the flow thread as a paint invalidation container in order to create a chokepoint that allows us to change
1464 // paint invalidation to do individual region paint invalidations.
1465 if (RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock()) {
1466 // If we have already found a paint invalidation container then we will invalidate paints in that container only if it is part of the same
1467 // flow thread. Otherwise we will need to catch the paint invalidation call and send it to the flow thread.
1468 if (!paintInvalidationContainer || paintInvalidationContainer->flowThreadContainingBlock() != parentRenderFlowThread)
1469 paintInvalidationContainer = parentRenderFlowThread;
1471 return paintInvalidationContainer ? paintInvalidationContainer : view();
1474 bool RenderObject::isPaintInvalidationContainer() const
1476 return hasLayer() && toRenderLayerModelObject(this)->layer()->isPaintInvalidationContainer();
1479 template <typename T>
1480 void addJsonObjectForRect(TracedValue* value, const char* name, const T& rect)
1482 value->beginDictionary(name);
1483 value->setDouble("x", rect.x());
1484 value->setDouble("y", rect.y());
1485 value->setDouble("width", rect.width());
1486 value->setDouble("height", rect.height());
1487 value->endDictionary();
1490 static PassRefPtr<TraceEvent::ConvertableToTraceFormat> jsonObjectForPaintInvalidationInfo(const LayoutRect& rect, const String& invalidationReason)
1492 RefPtr<TracedValue> value = TracedValue::create();
1493 addJsonObjectForRect(value.get(), "rect", rect);
1494 value->setString("invalidation_reason", invalidationReason);
1498 LayoutRect RenderObject::computePaintInvalidationRect(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1500 return clippedOverflowRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationState);
1503 void RenderObject::invalidatePaintUsingContainer(const RenderLayerModelObject* paintInvalidationContainer, const LayoutRect& r, InvalidationReason invalidationReason) const
1508 // FIXME: This should be an assert, but editing/selection can trigger this case to invalidate
1509 // the selection. crbug.com/368140.
1513 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "RenderObject::invalidatePaintUsingContainer()",
1514 "object", this->debugName().ascii(),
1515 "info", jsonObjectForPaintInvalidationInfo(r, invalidationReasonToString(invalidationReason)));
1517 // For querying RenderLayer::compositingState()
1518 DisableCompositingQueryAsserts disabler;
1520 if (paintInvalidationContainer->isRenderFlowThread()) {
1521 toRenderFlowThread(paintInvalidationContainer)->repaintRectangleInRegions(r);
1525 if (paintInvalidationContainer->hasFilter() && paintInvalidationContainer->layer()->requiresFullLayerImageForFilters()) {
1526 paintInvalidationContainer->layer()->paintInvalidator().setFilterBackendNeedsRepaintingInRect(r);
1530 RenderView* v = view();
1531 if (paintInvalidationContainer->isRenderView()) {
1532 ASSERT(paintInvalidationContainer == v);
1533 v->invalidatePaintForRectangle(r);
1537 if (v->usesCompositing()) {
1538 ASSERT(paintInvalidationContainer->hasLayer() && (paintInvalidationContainer->layer()->compositingState() == PaintsIntoOwnBacking || paintInvalidationContainer->layer()->compositingState() == PaintsIntoGroupedBacking));
1539 paintInvalidationContainer->layer()->paintInvalidator().setBackingNeedsRepaintInRect(r);
1543 void RenderObject::paintInvalidationForWholeRenderer() const
1548 if (view()->document().printing())
1549 return; // Don't invalidate paints if we're printing.
1551 // FIXME: really, we're in the paint invalidation phase here, and the following queries are legal.
1552 // Until those states are fully fledged, I'll just disable the ASSERTS.
1553 DisableCompositingQueryAsserts disabler;
1554 const RenderLayerModelObject* paintInvalidationContainer = containerForPaintInvalidation();
1556 // FIXME: We should invalidate only previousPaintInvalidationRect, but for now we invalidate both the previous
1557 // and current paint rects to meet the expectations of some callers in some cases (crbug.com/397555):
1558 // - transform style change without a layout - crbug.com/394004;
1559 // - some objects don't save previousPaintInvalidationRect - crbug.com/394133.
1560 LayoutRect paintInvalidationRect = boundsRectForPaintInvalidation(paintInvalidationContainer);
1561 invalidatePaintUsingContainer(paintInvalidationContainer, paintInvalidationRect, InvalidationPaint);
1562 if (paintInvalidationRect != previousPaintInvalidationRect())
1563 invalidatePaintUsingContainer(paintInvalidationContainer, previousPaintInvalidationRect(), InvalidationPaint);
1566 LayoutRect RenderObject::boundsRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1568 if (!paintInvalidationContainer)
1569 return computePaintInvalidationRect(paintInvalidationContainer, paintInvalidationState);
1570 return RenderLayer::computePaintInvalidationRect(this, paintInvalidationContainer->layer(), paintInvalidationState);
1573 void RenderObject::invalidatePaintRectangle(const LayoutRect& r) const
1578 if (view()->document().printing())
1579 return; // Don't invalidate paints if we're printing.
1581 LayoutRect dirtyRect(r);
1583 const RenderLayerModelObject* paintInvalidationContainer = containerForPaintInvalidation();
1584 RenderLayer::mapRectToPaintInvalidationBacking(this, paintInvalidationContainer, dirtyRect);
1585 invalidatePaintUsingContainer(paintInvalidationContainer, dirtyRect, InvalidationPaintRectangle);
1588 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1590 return pixelSnappedIntRect(absoluteClippedOverflowRect());
1593 const char* RenderObject::invalidationReasonToString(InvalidationReason reason) const
1596 case InvalidationNone:
1598 case InvalidationIncremental:
1599 return "incremental";
1600 case InvalidationFull:
1602 case InvalidationBorderFitLines:
1603 return "border fit lines";
1604 case InvalidationBorderBoxChange:
1605 return "border box change";
1606 case InvalidationBoundsChange:
1607 return "bounds change";
1608 case InvalidationLocationChange:
1609 return "location change";
1610 case InvalidationScroll:
1612 case InvalidationSelection:
1614 case InvalidationLayer:
1616 case InvalidationPaint:
1617 return "invalidate paint";
1618 case InvalidationPaintRectangle:
1619 return "invalidate paint rectangle";
1621 ASSERT_NOT_REACHED();
1625 void RenderObject::invalidateTreeIfNeeded(const PaintInvalidationState& paintInvalidationState)
1627 // If we didn't need paint invalidation then our children don't need as well.
1628 // Skip walking down the tree as everything should be fine below us.
1629 if (!shouldCheckForPaintInvalidation(paintInvalidationState))
1632 clearPaintInvalidationState(paintInvalidationState);
1634 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1635 if (!child->isOutOfFlowPositioned())
1636 child->invalidateTreeIfNeeded(paintInvalidationState);
1640 static PassRefPtr<TraceEvent::ConvertableToTraceFormat> jsonObjectForOldAndNewRects(const LayoutRect& oldRect, const LayoutRect& newRect)
1642 RefPtr<TracedValue> value = TracedValue::create();
1643 addJsonObjectForRect(value.get(), "old", oldRect);
1644 addJsonObjectForRect(value.get(), "new", newRect);
1648 InvalidationReason RenderObject::invalidatePaintIfNeeded(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const PaintInvalidationState& paintInvalidationState)
1650 RenderView* v = view();
1651 if (v->document().printing())
1652 return InvalidationNone; // Don't invalidate paints if we're printing.
1654 const LayoutRect& newBounds = previousPaintInvalidationRect();
1655 const LayoutPoint& newLocation = previousPositionFromPaintInvalidationContainer();
1657 // FIXME: PaintInvalidationState should not be required here, but the call to flipForWritingMode
1658 // in mapRectToPaintInvalidationBacking will give us the wrong results with it disabled.
1660 ASSERT(newBounds == boundsRectForPaintInvalidation(&paintInvalidationContainer, &paintInvalidationState));
1662 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "RenderObject::invalidatePaintIfNeeded()",
1663 "object", this->debugName().ascii(),
1664 "info", jsonObjectForOldAndNewRects(oldBounds, newBounds));
1666 InvalidationReason invalidationReason = getPaintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
1668 if (invalidationReason == InvalidationNone)
1669 return invalidationReason;
1671 if (invalidationReason == InvalidationIncremental) {
1672 incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds);
1673 return invalidationReason;
1676 fullyInvalidatePaint(paintInvalidationContainer, invalidationReason, oldBounds, newBounds);
1677 return invalidationReason;
1680 InvalidationReason RenderObject::getPaintInvalidationReason(const RenderLayerModelObject& paintInvalidationContainer,
1681 const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect& newBounds, const LayoutPoint& newLocation)
1683 if (shouldDoFullPaintInvalidation())
1684 return InvalidationFull;
1686 // Presumably a background or a border exists if border-fit:lines was specified.
1687 if (style()->borderFit() == BorderFitLines)
1688 return InvalidationBorderFitLines;
1690 if (compositingState() != PaintsIntoOwnBacking && newLocation != oldLocation)
1691 return InvalidationLocationChange;
1693 // If the bounds are the same then we know that none of the statements below
1694 // can match, so we can early out since we will not need to do any
1696 if (oldBounds == newBounds)
1697 return InvalidationNone;
1699 // If we shifted, we don't know the exact reason so we are conservative and trigger a full invalidation. Shifting could
1700 // be caused by some layout property (left / top) or some in-flow renderer inserted / removed before us in the tree.
1701 if (newBounds.location() != oldBounds.location())
1702 return InvalidationBoundsChange;
1704 // If the size is zero on one of our bounds then we know we're going to have
1705 // to do a full invalidation of either old bounds or new bounds. If we fall
1706 // into the incremental invalidation we'll issue two invalidations instead
1708 if (oldBounds.size().isZero() || newBounds.size().isZero())
1709 return InvalidationBoundsChange;
1711 // This covers the case where we mark containing blocks for layout
1712 // and they change size but don't have anything to paint. This is
1713 // a pretty common case for <body> as we add / remove children
1714 // (and the default background is done by FrameView).
1715 if (skipInvalidationWhenLaidOutChildren() && !mayNeedPaintInvalidation())
1716 return InvalidationNone;
1718 return InvalidationIncremental;
1721 void RenderObject::incrementallyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds)
1723 ASSERT(oldBounds.location() == newBounds.location());
1725 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1727 invalidatePaintUsingContainer(&paintInvalidationContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()), InvalidationIncremental);
1728 else if (deltaRight < 0)
1729 invalidatePaintUsingContainer(&paintInvalidationContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()), InvalidationIncremental);
1731 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1732 if (deltaBottom > 0)
1733 invalidatePaintUsingContainer(&paintInvalidationContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom), InvalidationIncremental);
1734 else if (deltaBottom < 0)
1735 invalidatePaintUsingContainer(&paintInvalidationContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom), InvalidationIncremental);
1738 void RenderObject::fullyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, InvalidationReason invalidationReason, const LayoutRect& oldBounds, const LayoutRect& newBounds)
1740 // Otherwise do full paint invalidation.
1741 invalidatePaintUsingContainer(&paintInvalidationContainer, oldBounds, invalidationReason);
1742 if (newBounds != oldBounds)
1743 invalidatePaintUsingContainer(&paintInvalidationContainer, newBounds, invalidationReason);
1746 void RenderObject::invalidatePaintForOverflow()
1750 void RenderObject::invalidatePaintForOverflowIfNeeded()
1752 if (shouldInvalidateOverflowForPaint())
1753 invalidatePaintForOverflow();
1756 bool RenderObject::checkForPaintInvalidation() const
1758 return !document().view()->needsFullPaintInvalidation() && everHadLayout();
1761 LayoutRect RenderObject::rectWithOutlineForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, LayoutUnit outlineWidth, const PaintInvalidationState* paintInvalidationState) const
1763 LayoutRect r(clippedOverflowRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationState));
1764 r.inflate(outlineWidth);
1768 LayoutRect RenderObject::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject*, const PaintInvalidationState*) const
1770 ASSERT_NOT_REACHED();
1771 return LayoutRect();
1774 void RenderObject::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, ViewportConstrainedPosition, const PaintInvalidationState* paintInvalidationState) const
1776 if (paintInvalidationContainer == this)
1779 if (RenderObject* o = parent()) {
1780 if (o->isRenderBlockFlow()) {
1781 RenderBlock* cb = toRenderBlock(o);
1782 if (cb->hasColumns())
1783 cb->adjustRectForColumns(rect);
1786 if (o->hasOverflowClip()) {
1787 RenderBox* boxParent = toRenderBox(o);
1788 boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1793 // RenderBox must override this method and pass correct ViewportConstrainedPosition for fixed-position.
1794 o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, IsNotFixedPosition, paintInvalidationState);
1798 void RenderObject::computeFloatRectForPaintInvalidation(const RenderLayerModelObject*, FloatRect&, const PaintInvalidationState*) const
1800 ASSERT_NOT_REACHED();
1803 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1809 void RenderObject::showTreeForThis() const
1812 node()->showTreeForThis();
1815 void RenderObject::showRenderTreeForThis() const
1817 showRenderTree(this, 0);
1820 void RenderObject::showLineTreeForThis() const
1822 if (containingBlock())
1823 containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1826 void RenderObject::showRenderObject() const
1828 showRenderObject(0);
1831 void RenderObject::showRenderObject(int printedCharacters) const
1833 printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1836 if (printedCharacters)
1837 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1839 fputc('\t', stderr);
1842 fputc('\n', stderr);
1845 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1847 int printedCharacters = 0;
1848 if (markedObject1 == this && markedLabel1)
1849 printedCharacters += fprintf(stderr, "%s", markedLabel1);
1850 if (markedObject2 == this && markedLabel2)
1851 printedCharacters += fprintf(stderr, "%s", markedLabel2);
1852 for (; printedCharacters < depth * 2; printedCharacters++)
1855 showRenderObject(printedCharacters);
1857 for (const RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
1858 child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1863 bool RenderObject::isSelectable() const
1865 return !isInert() && !(style()->userSelect() == SELECT_NONE && style()->userModify() == READ_ONLY);
1868 Color RenderObject::selectionBackgroundColor() const
1870 if (!isSelectable())
1871 return Color::transparent;
1873 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1874 return resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
1875 return frame()->selection().isFocusedAndActive() ?
1876 RenderTheme::theme().activeSelectionBackgroundColor() :
1877 RenderTheme::theme().inactiveSelectionBackgroundColor();
1880 Color RenderObject::selectionColor(int colorProperty) const
1882 // If the element is unselectable, or we are only painting the selection,
1883 // don't override the foreground color with the selection foreground color.
1884 if (!isSelectable() || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1885 return resolveColor(colorProperty);
1887 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1888 return resolveColor(pseudoStyle.get(), colorProperty);
1889 if (!RenderTheme::theme().supportsSelectionForegroundColors())
1890 return resolveColor(colorProperty);
1891 return frame()->selection().isFocusedAndActive() ?
1892 RenderTheme::theme().activeSelectionForegroundColor() :
1893 RenderTheme::theme().inactiveSelectionForegroundColor();
1896 Color RenderObject::selectionForegroundColor() const
1898 return selectionColor(CSSPropertyWebkitTextFillColor);
1901 Color RenderObject::selectionEmphasisMarkColor() const
1903 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1906 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1908 view()->selectionStartEnd(spos, epos);
1911 void RenderObject::handleDynamicFloatPositionChange()
1913 // We have gone from not affecting the inline status of the parent flow to suddenly
1914 // having an impact. See if there is a mismatch between the parent flow's
1915 // childrenInline() state and our state.
1916 setInline(style()->isDisplayInlineType());
1917 if (isInline() != parent()->childrenInline()) {
1919 toRenderBoxModelObject(parent())->childBecameNonInline(this);
1921 // An anonymous block must be made to wrap this inline.
1922 RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1923 RenderObjectChildList* childlist = parent()->virtualChildren();
1924 childlist->insertChildNode(parent(), block, this);
1925 block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1930 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff) const
1932 if (diff.transformChanged() && isSVG())
1933 diff.setNeedsFullLayout();
1935 // If transform changed, and the layer does not paint into its own separate backing, then we need to invalidate paints.
1936 if (diff.transformChanged()) {
1937 // Text nodes share style with their parents but transforms don't apply to them,
1938 // hence the !isText() check.
1939 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasStyleDeterminedDirectCompositingReasons()))
1940 diff.setNeedsPaintInvalidationLayer();
1943 // If opacity or zIndex changed, and the layer does not paint into its own separate backing, then we need to invalidate paints (also
1944 // ignoring text nodes)
1945 if (diff.opacityChanged() || diff.zIndexChanged()) {
1946 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasStyleDeterminedDirectCompositingReasons()))
1947 diff.setNeedsPaintInvalidationLayer();
1950 // If filter changed, and the layer does not paint into its own separate backing or it paints with filters, then we need to invalidate paints.
1951 if (diff.filterChanged() && hasLayer()) {
1952 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
1953 if (!layer->hasStyleDeterminedDirectCompositingReasons() || layer->paintsWithFilters())
1954 diff.setNeedsPaintInvalidationLayer();
1957 if (diff.textOrColorChanged() && !diff.needsPaintInvalidation()
1958 && hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor())
1959 diff.setNeedsPaintInvalidationObject();
1961 // The answer to layerTypeRequired() for plugins, iframes, and canvas can change without the actual
1962 // style changing, since it depends on whether we decide to composite these elements. When the
1963 // layer status of one of these elements changes, we need to force a layout.
1964 if (!diff.needsFullLayout() && style() && isLayerModelObject()) {
1965 bool requiresLayer = toRenderLayerModelObject(this)->layerTypeRequired() != NoLayer;
1966 if (hasLayer() != requiresLayer)
1967 diff.setNeedsFullLayout();
1970 // If we have no layer(), just treat a PaintInvalidationLayer hint as a normal paint invalidation.
1971 if (diff.needsPaintInvalidationLayer() && !hasLayer()) {
1972 diff.clearNeedsPaintInvalidation();
1973 diff.setNeedsPaintInvalidationObject();
1979 void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
1981 ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER);
1983 // FIXME: We should consider just making all pseudo items use an inherited style.
1985 // Images are special and must inherit the pseudoStyle so the width and height of
1986 // the pseudo element doesn't change the size of the image. In all other cases we
1987 // can just share the style.
1989 // Quotes are also RenderInline, so we need to create an inherited style to avoid
1990 // getting an inline with positioning or an invalid display.
1992 if (isImage() || isQuote()) {
1993 RefPtr<RenderStyle> style = RenderStyle::create();
1994 style->inheritFrom(pseudoStyle.get());
1995 setStyle(style.release());
1999 setStyle(pseudoStyle);
2002 inline bool RenderObject::hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const
2004 if (style()->hasBorder() || style()->hasOutline())
2006 for (const RenderObject* r = slowFirstChild(); r; r = r->nextSibling()) {
2007 if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
2009 if (r->style()->hasOutline() || r->style()->hasBorder())
2015 void RenderObject::markContainingBlocksForOverflowRecalc()
2017 for (RenderBlock* container = containingBlock(); container && !container->childNeedsOverflowRecalcAfterStyleChange(); container = container->containingBlock())
2018 container->setChildNeedsOverflowRecalcAfterStyleChange(true);
2021 void RenderObject::setNeedsOverflowRecalcAfterStyleChange()
2023 bool neededRecalc = needsOverflowRecalcAfterStyleChange();
2024 setSelfNeedsOverflowRecalcAfterStyleChange(true);
2026 markContainingBlocksForOverflowRecalc();
2029 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
2033 if (m_style == style) {
2034 // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
2035 // style sharing is disabled for them. That should ensure that we never hit this code path.
2036 ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
2040 StyleDifference diff;
2042 diff = m_style->visualInvalidationDiff(*style);
2044 diff = adjustStyleDifference(diff);
2046 styleWillChange(diff, *style);
2048 RefPtr<RenderStyle> oldStyle = m_style.release();
2049 setStyleInternal(style);
2051 updateFillImages(oldStyle ? &oldStyle->backgroundLayers() : 0, m_style->backgroundLayers());
2052 updateFillImages(oldStyle ? &oldStyle->maskLayers() : 0, m_style->maskLayers());
2054 updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style->borderImage().image());
2055 updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style->maskBoxImage().image());
2057 updateShapeImage(oldStyle ? oldStyle->shapeOutside() : 0, m_style->shapeOutside());
2059 bool doesNotNeedLayout = !m_parent || isText();
2061 styleDidChange(diff, oldStyle.get());
2063 // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
2064 // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
2065 // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
2066 // in the future as we move renderer changes out of layout and into style changes.
2067 if (doesNotNeedLayout)
2070 // Now that the layer (if any) has been updated, we need to adjust the diff again,
2071 // check whether we should layout now, and decide if we need to invalidate paints.
2072 StyleDifference updatedDiff = adjustStyleDifference(diff);
2074 if (!diff.needsFullLayout()) {
2075 if (updatedDiff.needsFullLayout())
2076 setNeedsLayoutAndPrefWidthsRecalc();
2077 else if (updatedDiff.needsPositionedMovementLayout())
2078 setNeedsPositionedMovementLayout();
2081 if (diff.transformChanged() && !needsLayout()) {
2082 if (RenderBlock* container = containingBlock())
2083 container->setNeedsOverflowRecalcAfterStyleChange();
2086 if (updatedDiff.needsPaintInvalidationLayer())
2087 toRenderLayerModelObject(this)->layer()->setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
2088 else if (diff.needsPaintInvalidationObject() || updatedDiff.needsPaintInvalidationObject())
2089 setShouldDoFullPaintInvalidation(true);
2092 static inline bool rendererHasBackground(const RenderObject* renderer)
2094 return renderer && renderer->hasBackground();
2097 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
2100 // If our z-index changes value or our visibility changes,
2101 // we need to dirty our stacking context's z-order list.
2102 bool visibilityChanged = m_style->visibility() != newStyle.visibility()
2103 || m_style->zIndex() != newStyle.zIndex()
2104 || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
2105 if (visibilityChanged) {
2106 document().setAnnotatedRegionsDirty(true);
2107 if (AXObjectCache* cache = document().existingAXObjectCache())
2108 cache->childrenChanged(parent());
2111 // Keep layer hierarchy visibility bits up to date if visibility changes.
2112 if (m_style->visibility() != newStyle.visibility()) {
2113 // We might not have an enclosing layer yet because we might not be in the tree.
2114 if (RenderLayer* layer = enclosingLayer())
2115 layer->potentiallyDirtyVisibleContentStatus(newStyle.visibility());
2118 if (isFloating() && (m_style->floating() != newStyle.floating()))
2119 // For changes in float styles, we need to conceivably remove ourselves
2120 // from the floating objects list.
2121 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2122 else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
2123 // For changes in positioning styles, we need to conceivably remove ourselves
2124 // from the positioned objects list.
2125 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2127 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
2128 && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
2129 && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
2131 // Clearing these bits is required to avoid leaving stale renderers.
2132 // FIXME: We shouldn't need that hack if our logic was totally correct.
2133 if (diff.needsLayout()) {
2135 clearPositionedState();
2138 s_affectsParentBlock = false;
2141 if (view()->frameView()) {
2142 bool shouldBlitOnFixedBackgroundImage = false;
2143 if (RuntimeEnabledFeatures::fastMobileScrollingEnabled()) {
2144 // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
2145 // when scrolling a page with a fixed background image. As an optimization, assuming there are
2146 // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
2147 // ignore the CSS property "background-attachment: fixed".
2148 shouldBlitOnFixedBackgroundImage = true;
2150 bool newStyleSlowScroll = !shouldBlitOnFixedBackgroundImage && newStyle.hasFixedBackgroundImage();
2151 bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
2153 bool drawsRootBackground = isDocumentElement() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
2154 if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
2155 if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
2156 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
2157 newStyleSlowScroll = false;
2159 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
2160 oldStyleSlowScroll = false;
2164 if (oldStyleSlowScroll != newStyleSlowScroll) {
2165 if (oldStyleSlowScroll)
2166 view()->frameView()->removeSlowRepaintObject();
2167 if (newStyleSlowScroll)
2168 view()->frameView()->addSlowRepaintObject();
2172 // Elements with non-auto touch-action will send a SetTouchAction message
2173 // on touchstart in EventHandler::handleTouchEvent, and so effectively have
2174 // a touchstart handler that must be reported.
2176 // Since a CSS property cannot be applied directly to a text node, a
2177 // handler will have already been added for its parent so ignore it.
2178 TouchAction oldTouchAction = m_style ? m_style->touchAction() : TouchActionAuto;
2179 if (node() && !node()->isTextNode() && (oldTouchAction == TouchActionAuto) != (newStyle.touchAction() == TouchActionAuto)) {
2180 EventHandlerRegistry& registry = document().frameHost()->eventHandlerRegistry();
2181 if (newStyle.touchAction() != TouchActionAuto)
2182 registry.didAddEventHandler(*node(), EventHandlerRegistry::TouchEvent);
2184 registry.didRemoveEventHandler(*node(), EventHandlerRegistry::TouchEvent);
2188 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
2190 ASSERT(a->cursors() != b->cursors());
2191 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
2194 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
2196 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
2199 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
2201 if (s_affectsParentBlock)
2202 handleDynamicFloatPositionChange();
2207 if (diff.needsFullLayout()) {
2208 RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.get());
2210 // If the object already needs layout, then setNeedsLayout won't do
2211 // any work. But if the containing block has changed, then we may need
2212 // to mark the new containing blocks for layout. The change that can
2213 // directly affect the containing block of this object is a change to
2214 // the position style.
2215 if (needsLayout() && oldStyle->position() != m_style->position())
2216 markContainingBlocksForLayout();
2219 if (needsOverflowRecalcAfterStyleChange() && oldStyle->position() != m_style->position())
2220 markContainingBlocksForOverflowRecalc();
2222 if (diff.needsFullLayout())
2223 setNeedsLayoutAndPrefWidthsRecalc();
2224 } else if (diff.needsPositionedMovementLayout())
2225 setNeedsPositionedMovementLayout();
2227 // Don't check for paint invalidation here; we need to wait until the layer has been
2228 // updated by subclasses before we know if we have to invalidate paints (in setStyle()).
2230 if (oldStyle && !areCursorsEqual(oldStyle, style())) {
2231 if (LocalFrame* frame = this->frame())
2232 frame->eventHandler().scheduleCursorUpdate();
2236 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
2238 // FIXME: We could save this call when the change only affected non-inherited properties.
2239 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
2240 if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
2243 if (blockChildrenOnly && !child->isRenderBlock())
2246 if (child->isRenderFullScreen() || child->isRenderFullScreenPlaceholder())
2249 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), child->style()->display());
2250 if (style()->specifiesColumns()) {
2251 if (child->style()->specifiesColumns())
2252 newStyle->inheritColumnPropertiesFrom(style());
2253 if (child->style()->columnSpan())
2254 newStyle->setColumnSpan(ColumnSpanAll);
2257 // Preserve the position style of anonymous block continuations as they can have relative position when
2258 // they contain block descendants of relative positioned inlines.
2259 if (child->isRelPositioned() && toRenderBlock(child)->isAnonymousBlockContinuation())
2260 newStyle->setPosition(child->style()->position());
2262 child->setStyle(newStyle.release());
2266 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer& newLayers)
2268 // Optimize the common case
2269 if (oldLayers && !oldLayers->next() && !newLayers.next() && (oldLayers->image() == newLayers.image()))
2272 // Go through the new layers and addClients first, to avoid removing all clients of an image.
2273 for (const FillLayer* currNew = &newLayers; currNew; currNew = currNew->next()) {
2274 if (currNew->image())
2275 currNew->image()->addClient(this);
2278 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2279 if (currOld->image())
2280 currOld->image()->removeClient(this);
2284 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2286 if (oldImage != newImage) {
2288 oldImage->removeClient(this);
2290 newImage->addClient(this);
2294 void RenderObject::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
2296 if (oldShapeValue || newShapeValue)
2297 updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
2300 LayoutRect RenderObject::viewRect() const
2302 return view()->viewRect();
2305 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2307 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2308 mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2309 transformState.flatten();
2311 return transformState.lastPlanarPoint();
2314 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2316 TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2317 mapAbsoluteToLocalPoint(mode, transformState);
2318 transformState.flatten();
2320 return transformState.lastPlanarPoint();
2323 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2325 TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2326 mapAbsoluteToLocalPoint(mode, transformState);
2327 transformState.flatten();
2328 return transformState.lastPlanarQuad();
2331 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
2333 if (paintInvalidationContainer == this)
2336 RenderObject* o = parent();
2340 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2341 LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2342 if (mode & ApplyContainerFlip && o->isBox()) {
2343 if (o->style()->isFlippedBlocksWritingMode())
2344 transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2345 mode &= ~ApplyContainerFlip;
2348 transformState.move(o->columnOffset(roundedLayoutPoint(transformState.mappedPoint())));
2350 if (o->hasOverflowClip())
2351 transformState.move(-toRenderBox(o)->scrolledContentOffset());
2353 o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed, paintInvalidationState);
2356 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2358 ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
2360 RenderObject* container = parent();
2364 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2366 if (container->hasOverflowClip())
2367 offset = -toRenderBox(container)->scrolledContentOffset();
2369 geometryMap.push(this, offset, hasColumns());
2374 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2376 RenderObject* o = parent();
2378 o->mapAbsoluteToLocalPoint(mode, transformState);
2379 if (o->hasOverflowClip())
2380 transformState.move(toRenderBox(o)->scrolledContentOffset());
2384 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
2386 // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2387 // so check the layer's transform directly.
2388 return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2391 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2393 transform.makeIdentity();
2394 transform.translate(offsetInContainer.width().toFloat(), offsetInContainer.height().toFloat());
2395 RenderLayer* layer = hasLayer() ? toRenderLayerModelObject(this)->layer() : 0;
2396 if (layer && layer->transform())
2397 transform.multiply(layer->currentTransform());
2399 if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2400 // Perpsective on the container affects us, so we have to factor it in here.
2401 ASSERT(containerObject->hasLayer());
2402 FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
2404 TransformationMatrix perspectiveMatrix;
2405 perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2407 transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2408 transform = perspectiveMatrix * transform;
2409 transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2413 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2415 // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2416 // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2417 TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2418 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2419 transformState.flatten();
2421 return transformState.lastPlanarQuad();
2424 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
2426 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2427 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed, paintInvalidationState);
2428 transformState.flatten();
2430 return transformState.lastPlanarPoint();
2433 LayoutSize RenderObject::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2435 ASSERT(o == container());
2437 LayoutSize offset = o->columnOffset(point);
2439 if (o->hasOverflowClip())
2440 offset -= toRenderBox(o)->scrolledContentOffset();
2442 if (offsetDependsOnPoint)
2443 *offsetDependsOnPoint = hasColumns() || o->isRenderFlowThread();
2448 LayoutSize RenderObject::offsetFromAncestorContainer(const RenderObject* container) const
2451 LayoutPoint referencePoint;
2452 const RenderObject* currContainer = this;
2454 const RenderObject* nextContainer = currContainer->container();
2455 ASSERT(nextContainer); // This means we reached the top without finding container.
2458 ASSERT(!currContainer->hasTransform());
2459 LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2460 offset += currentOffset;
2461 referencePoint.move(currentOffset);
2462 currContainer = nextContainer;
2463 } while (currContainer != container);
2468 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2470 if (extraWidthToEndOfLine)
2471 *extraWidthToEndOfLine = 0;
2473 return LayoutRect();
2476 void RenderObject::computeLayerHitTestRects(LayerHitTestRects& layerRects) const
2478 // Figure out what layer our container is in. Any offset (or new layer) for this
2479 // renderer within it's container will be applied in addLayerHitTestRects.
2480 LayoutPoint layerOffset;
2481 const RenderLayer* currentLayer = 0;
2484 RenderObject* container = this->container();
2485 currentLayer = container->enclosingLayer();
2486 if (container && currentLayer->renderer() != container) {
2487 layerOffset.move(container->offsetFromAncestorContainer(currentLayer->renderer()));
2488 // If the layer itself is scrolled, we have to undo the subtraction of its scroll
2489 // offset since we want the offset relative to the scrolling content, not the
2491 if (currentLayer->renderer()->hasOverflowClip())
2492 layerOffset.move(currentLayer->renderBox()->scrolledContentOffset());
2496 this->addLayerHitTestRects(layerRects, currentLayer, layerOffset, LayoutRect());
2499 void RenderObject::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
2501 ASSERT(currentLayer);
2502 ASSERT(currentLayer == this->enclosingLayer());
2504 // Compute the rects for this renderer only and add them to the results.
2505 // Note that we could avoid passing the offset and instead adjust each result, but this
2506 // seems slightly simpler.
2507 Vector<LayoutRect> ownRects;
2508 LayoutRect newContainerRect;
2509 computeSelfHitTestRects(ownRects, layerOffset);
2511 // When we get to have a lot of rects on a layer, the performance cost of tracking those
2512 // rects outweighs the benefit of doing compositor thread hit testing.
2513 // FIXME: This limit needs to be low due to the O(n^2) algorithm in
2514 // WebLayer::setTouchEventHandlerRegion - crbug.com/300282.
2515 const size_t maxRectsPerLayer = 100;
2517 LayerHitTestRects::iterator iter = layerRects.find(currentLayer);
2518 Vector<LayoutRect>* iterValue;
2519 if (iter == layerRects.end())
2520 iterValue = &layerRects.add(currentLayer, Vector<LayoutRect>()).storedValue->value;
2522 iterValue = &iter->value;
2523 for (size_t i = 0; i < ownRects.size(); i++) {
2524 if (!containerRect.contains(ownRects[i])) {
2525 iterValue->append(ownRects[i]);
2526 if (iterValue->size() > maxRectsPerLayer) {
2527 // Just mark the entire layer instead, and switch to walking the layer
2528 // tree instead of the render tree.
2529 layerRects.remove(currentLayer);
2530 currentLayer->addLayerHitTestRects(layerRects);
2533 if (newContainerRect.isEmpty())
2534 newContainerRect = ownRects[i];
2537 if (newContainerRect.isEmpty())
2538 newContainerRect = containerRect;
2540 // If it's possible for children to have rects outside our bounds, then we need to descend into
2541 // the children and compute them.
2542 // Ideally there would be other cases where we could detect that children couldn't have rects
2543 // outside our bounds and prune the tree walk.
2544 // Note that we don't use Region here because Union is O(N) - better to just keep a list of
2545 // partially redundant rectangles. If we find examples where this is expensive, then we could
2546 // rewrite Region to be more efficient. See https://bugs.webkit.org/show_bug.cgi?id=100814.
2547 if (!isRenderView()) {
2548 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling()) {
2549 curr->addLayerHitTestRects(layerRects, currentLayer, layerOffset, newContainerRect);
2554 bool RenderObject::isRooted() const
2556 const RenderObject* object = this;
2557 while (object->parent() && !object->hasLayer())
2558 object = object->parent();
2559 if (object->hasLayer())
2560 return toRenderLayerModelObject(object)->layer()->root()->isRootLayer();
2564 RenderObject* RenderObject::rendererForRootBackground()
2566 ASSERT(isDocumentElement());
2567 if (!hasBackground() && isHTMLHtmlElement(node())) {
2568 // Locate the <body> element using the DOM. This is easier than trying
2569 // to crawl around a render tree with potential :before/:after content and
2570 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
2571 // render object very easily via the DOM.
2572 HTMLElement* body = document().body();
2573 RenderObject* bodyObject = isHTMLBodyElement(body) ? body->renderer() : 0;
2581 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
2583 // Respect the image's orientation if it's being used as a full-page image or it's
2584 // an <img> and the setting to respect it everywhere is set.
2585 return document().isImageDocument()
2586 || (document().settings() && document().settings()->shouldRespectImageOrientation() && isHTMLImageElement(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
2589 bool RenderObject::hasOutlineAnnotation() const
2591 return node() && node()->isLink() && document().printing();
2594 bool RenderObject::hasEntirelyFixedBackground() const
2596 return m_style->hasEntirelyFixedBackground();
2599 RenderObject* RenderObject::container(const RenderLayerModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
2601 if (paintInvalidationContainerSkipped)
2602 *paintInvalidationContainerSkipped = false;
2604 // This method is extremely similar to containingBlock(), but with a few notable
2606 // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2607 // the object is not part of the primary document subtree yet.
2608 // (2) For normal flow elements, it just returns the parent.
2609 // (3) For absolute positioned elements, it will return a relative positioned inline.
2610 // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2611 // the layout of the positioned object. This does mean that computePositionedLogicalWidth and
2612 // computePositionedLogicalHeight have to use container().
2613 RenderObject* o = parent();
2618 EPosition pos = m_style->position();
2619 if (pos == FixedPosition) {
2620 return containerForFixedPosition(paintInvalidationContainer, paintInvalidationContainerSkipped);
2621 } else if (pos == AbsolutePosition) {
2622 // We technically just want our containing block, but
2623 // we may not have one if we're part of an uninstalled
2624 // subtree. We'll climb as high as we can though.
2626 if (o->style()->position() != StaticPosition)
2629 if (o->canContainFixedPositionObjects())
2632 if (paintInvalidationContainerSkipped && o == paintInvalidationContainer)
2633 *paintInvalidationContainerSkipped = true;
2642 bool RenderObject::isSelectionBorder() const
2644 SelectionState st = selectionState();
2645 return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2648 inline void RenderObject::clearLayoutRootIfNeeded() const
2651 if (FrameView* view = frame()->view()) {
2652 if (view->layoutRoot() == this) {
2653 if (!documentBeingDestroyed())
2654 ASSERT_NOT_REACHED();
2655 // This indicates a failure to layout the child, which is why
2656 // the layout root is still set to |this|. Make sure to clear it
2657 // since we are getting destroyed.
2658 view->clearLayoutSubtreeRoot();
2664 void RenderObject::willBeDestroyed()
2666 // Destroy any leftover anonymous children.
2667 RenderObjectChildList* children = virtualChildren();
2669 children->destroyLeftoverChildren();
2671 // If this renderer is being autoscrolled, stop the autoscrolling.
2672 if (LocalFrame* frame = this->frame()) {
2674 frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
2677 // For accessibility management, notify the parent of the imminent change to its child set.
2678 // We do it now, before remove(), while the parent pointer is still available.
2679 if (AXObjectCache* cache = document().existingAXObjectCache())
2680 cache->childrenChanged(this->parent());
2684 // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
2685 // object for this renderer. So we remove the AX render object now, after the renderer is removed.
2686 if (AXObjectCache* cache = document().existingAXObjectCache())
2687 cache->remove(this);
2689 // If this renderer had a parent, remove should have destroyed any counters
2690 // attached to this renderer and marked the affected other counters for
2691 // reevaluation. This apparently redundant check is here for the case when
2692 // this renderer had no parent at the time remove() was called.
2694 if (hasCounterNodeMap())
2695 RenderCounter::destroyCounterNodes(*this);
2697 // Remove the handler if node had touch-action set. Don't call when
2698 // document is being destroyed as all handlers will have been cleared
2699 // previously. Handlers are not added for text nodes so don't try removing
2700 // for one too. Need to check if m_style is null in cases of partial construction.
2701 if (!documentBeingDestroyed() && node() && !node()->isTextNode() && m_style && m_style->touchAction() != TouchActionAuto)
2702 document().frameHost()->eventHandlerRegistry().didRemoveEventHandler(*node(), EventHandlerRegistry::TouchEvent);
2704 setAncestorLineBoxDirty(false);
2706 clearLayoutRootIfNeeded();
2709 void RenderObject::insertedIntoTree()
2711 // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2713 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2714 // and don't have a layer attached to ourselves.
2715 RenderLayer* layer = 0;
2716 if (slowFirstChild() || hasLayer()) {
2717 layer = parent()->enclosingLayer();
2721 // If |this| is visible but this object was not, tell the layer it has some visible content
2722 // that needs to be drawn and layer visibility optimization can't be used
2723 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2725 layer = parent()->enclosingLayer();
2727 layer->dirtyVisibleContentStatus();
2730 if (!isFloating() && parent()->childrenInline())
2731 parent()->dirtyLinesFromChangedChild(this);
2734 void RenderObject::willBeRemovedFromTree()
2736 // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2738 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2739 RenderLayer* layer = 0;
2740 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2741 layer = parent()->enclosingLayer();
2743 layer->dirtyVisibleContentStatus();
2746 // Keep our layer hierarchy updated.
2747 if (slowFirstChild() || hasLayer()) {
2749 layer = parent()->enclosingLayer();
2750 removeLayers(layer);
2753 if (isOutOfFlowPositioned() && parent()->childrenInline())
2754 parent()->dirtyLinesFromChangedChild(this);
2756 removeFromRenderFlowThread();
2758 // Update cached boundaries in SVG renderers if a child is removed.
2759 if (parent()->isSVG())
2760 parent()->setNeedsBoundariesUpdate();
2763 void RenderObject::removeFromRenderFlowThread()
2765 if (flowThreadState() == NotInsideFlowThread)
2768 // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2769 // It's only until later when we actually destroy it and remove all the children from it.
2770 // Currently, that happens for firstLetter elements and list markers.
2771 // Pass in the flow thread so that we don't have to look it up for all the children.
2772 removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
2775 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
2777 if (const RenderObjectChildList* children = virtualChildren()) {
2778 for (RenderObject* child = children->firstChild(); child; child = child->nextSibling())
2779 child->removeFromRenderFlowThreadRecursive(renderFlowThread);
2782 setFlowThreadState(NotInsideFlowThread);
2785 void RenderObject::destroyAndCleanupAnonymousWrappers()
2787 // If the tree is destroyed, there is no need for a clean-up phase.
2788 if (documentBeingDestroyed()) {
2793 RenderObject* destroyRoot = this;
2794 for (RenderObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2795 // Anonymous block continuations are tracked and destroyed elsewhere (see the bottom of RenderBlock::removeChild)
2796 if (destroyRootParent->isRenderBlock() && toRenderBlock(destroyRootParent)->isAnonymousBlockContinuation())
2798 // Render flow threads are tracked by the FlowThreadController, so we can't destroy them here.
2799 // Column spans are tracked elsewhere.
2800 if (destroyRootParent->isRenderFlowThread() || destroyRootParent->isAnonymousColumnSpanBlock())
2803 if (destroyRootParent->slowFirstChild() != this || destroyRootParent->slowLastChild() != this)
2807 destroyRoot->destroy();
2809 // WARNING: |this| is deleted here.
2812 void RenderObject::destroy()
2814 #if ENABLE(ASSERT) && ENABLE(OILPAN)
2815 ASSERT(!m_didCallDestroy);
2816 m_didCallDestroy = true;
2822 void RenderObject::removeShapeImageClient(ShapeValue* shapeValue)
2826 if (StyleImage* shapeImage = shapeValue->image())
2827 shapeImage->removeClient(this);
2830 void RenderObject::postDestroy()
2832 // It seems ugly that this is not in willBeDestroyed().
2834 for (const FillLayer* bgLayer = &m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2835 if (StyleImage* backgroundImage = bgLayer->image())
2836 backgroundImage->removeClient(this);
2839 for (const FillLayer* maskLayer = &m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2840 if (StyleImage* maskImage = maskLayer->image())
2841 maskImage->removeClient(this);
2844 if (StyleImage* borderImage = m_style->borderImage().image())
2845 borderImage->removeClient(this);
2847 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2848 maskBoxImage->removeClient(this);
2850 removeShapeImageClient(m_style->shapeOutside());
2852 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
2858 PositionWithAffinity RenderObject::positionForPoint(const LayoutPoint&)
2860 return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2863 void RenderObject::updateDragState(bool dragOn)
2865 bool valueChanged = (dragOn != isDragging());
2866 setIsDragging(dragOn);
2867 if (valueChanged && node()) {
2868 if (node()->isElementNode() && toElement(node())->childrenOrSiblingsAffectedByDrag())
2869 node()->setNeedsStyleRecalc(SubtreeStyleChange);
2870 else if (style()->affectedByDrag())
2871 node()->setNeedsStyleRecalc(LocalStyleChange);
2873 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
2874 curr->updateDragState(dragOn);
2877 CompositingState RenderObject::compositingState() const
2879 return hasLayer() ? toRenderLayerModelObject(this)->layer()->compositingState() : NotComposited;
2882 CompositingReasons RenderObject::additionalCompositingReasons() const
2884 return CompositingReasonNone;
2887 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2889 bool inside = false;
2890 if (hitTestFilter != HitTestSelf) {
2891 // First test the foreground layer (lines and inlines).
2892 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
2894 // Test floats next.
2896 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2898 // Finally test to see if the mouse is in the background (within a child block's background).
2900 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2903 // See if the mouse is inside us but not any of our descendants
2904 if (hitTestFilter != HitTestDescendants && !inside)
2905 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2910 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2912 if (result.innerNode())
2915 Node* node = this->node();
2917 // If we hit the anonymous renderers inside generated content we should
2918 // actually hit the generated content so walk up to the PseudoElement.
2919 if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2920 for (RenderObject* renderer = parent(); renderer && !node; renderer = renderer->parent())
2921 node = renderer->node();
2925 result.setInnerNode(node);
2926 if (!result.innerNonSharedNode())
2927 result.setInnerNonSharedNode(node);
2928 result.setLocalPoint(point);
2932 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2937 void RenderObject::scheduleRelayout()
2939 if (isRenderView()) {
2940 FrameView* view = toRenderView(this)->frameView();
2942 view->scheduleRelayout();
2945 if (RenderView* renderView = view()) {
2946 if (FrameView* frameView = renderView->frameView())
2947 frameView->scheduleRelayoutOfSubtree(this);
2953 void RenderObject::forceLayout()
2955 setSelfNeedsLayout(true);
2956 setShouldDoFullPaintInvalidation(true);
2960 // FIXME: Does this do anything different than forceLayout given that we don't walk
2961 // the containing block chain. If not, we should change all callers to use forceLayout.
2962 void RenderObject::forceChildLayout()
2964 setNormalChildNeedsLayout(true);
2968 enum StyleCacheState {
2973 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderObject* renderer, RenderStyle* style)
2975 const RenderObject* rendererForFirstLineStyle = renderer;
2976 if (renderer->isBeforeOrAfterContent())
2977 rendererForFirstLineStyle = renderer->parent();
2979 if (rendererForFirstLineStyle->isRenderBlockFlow() || rendererForFirstLineStyle->isRenderButton()) {
2980 if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
2982 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2983 return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == renderer ? style : 0);
2985 } else if (!rendererForFirstLineStyle->isAnonymous() && rendererForFirstLineStyle->isRenderInline()) {
2986 RenderStyle* parentStyle = rendererForFirstLineStyle->parent()->firstLineStyle();
2987 if (parentStyle != rendererForFirstLineStyle->parent()->style()) {
2988 if (type == Cached) {
2989 // A first-line style is in effect. Cache a first-line style for ourselves.
2990 rendererForFirstLineStyle->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2991 return rendererForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2993 return rendererForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
2999 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
3001 if (!document().styleEngine()->usesFirstLineRules())
3006 return firstLineStyleForCachedUncachedType(Uncached, this, style);
3009 RenderStyle* RenderObject::cachedFirstLineStyle() const
3011 ASSERT(document().styleEngine()->usesFirstLineRules());
3013 if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
3016 return m_style.get();
3019 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
3021 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
3024 RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
3028 RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
3030 return style()->addCachedPseudoStyle(result.release());
3034 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
3036 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
3041 parentStyle = style();
3047 Element* element = Traversal<Element>::firstAncestorOrSelf(*node());
3051 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
3052 RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
3053 result->setStyleType(FIRST_LINE_INHERITED);
3054 return result.release();
3057 return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
3060 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyleFromParentOrShadowHost() const
3065 if (ShadowRoot* root = node()->containingShadowRoot()) {
3066 if (root->type() == ShadowRoot::UserAgentShadowRoot) {
3067 if (Element* shadowHost = node()->shadowHost()) {
3068 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
3073 return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
3076 bool RenderObject::hasBlendMode() const
3078 return RuntimeEnabledFeatures::cssCompositingEnabled() && style() && style()->hasBlendMode();
3081 void RenderObject::getTextDecorations(unsigned decorations, AppliedTextDecoration& underline, AppliedTextDecoration& overline, AppliedTextDecoration& linethrough, bool quirksMode, bool firstlineStyle)
3083 RenderObject* curr = this;
3084 RenderStyle* styleToUse = 0;
3085 unsigned currDecs = TextDecorationNone;
3087 TextDecorationStyle resultStyle;
3089 styleToUse = curr->style(firstlineStyle);
3090 currDecs = styleToUse->textDecoration();
3091 currDecs &= decorations;
3092 resultColor = styleToUse->visitedDependentDecorationColor();
3093 resultStyle = styleToUse->textDecorationStyle();
3094 // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
3096 if (currDecs & TextDecorationUnderline) {
3097 decorations &= ~TextDecorationUnderline;
3098 underline.color = resultColor;
3099 underline.style = resultStyle;
3101 if (currDecs & TextDecorationOverline) {
3102 decorations &= ~TextDecorationOverline;
3103 overline.color = resultColor;
3104 overline.style = resultStyle;
3106 if (currDecs & TextDecorationLineThrough) {
3107 decorations &= ~TextDecorationLineThrough;
3108 linethrough.color = resultColor;
3109 linethrough.style = resultStyle;
3112 if (curr->isRubyText())
3114 curr = curr->parent();
3115 if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
3116 curr = toRenderBlock(curr)->continuation();
3117 } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(*curr->node()) && !isHTMLFontElement(*curr->node()))));
3119 // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
3120 if (decorations && curr) {
3121 styleToUse = curr->style(firstlineStyle);
3122 resultColor = styleToUse->visitedDependentDecorationColor();
3123 if (decorations & TextDecorationUnderline) {
3124 underline.color = resultColor;
3125 underline.style = resultStyle;
3127 if (decorations & TextDecorationOverline) {
3128 overline.color = resultColor;
3129 overline.style = resultStyle;
3131 if (decorations & TextDecorationLineThrough) {
3132 linethrough.color = resultColor;
3133 linethrough.style = resultStyle;
3138 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3140 // Convert the style regions to absolute coordinates.
3141 if (style()->visibility() != VISIBLE || !isBox())
3144 if (style()->getDraggableRegionMode() == DraggableRegionNone)
3147 RenderBox* box = toRenderBox(this);
3148 FloatRect localBounds(FloatPoint(), FloatSize(box->width().toFloat(), box->height().toFloat()));
3149 FloatRect absBounds = localToAbsoluteQuad(localBounds).boundingBox();
3151 AnnotatedRegionValue region;
3152 region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
3153 region.bounds = LayoutRect(absBounds);
3154 regions.append(region);
3157 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3159 // RenderTexts don't have their own style, they just use their parent's style,
3160 // so we don't want to include them.
3164 addAnnotatedRegions(regions);
3165 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
3166 curr->collectAnnotatedRegions(regions);
3169 bool RenderObject::willRenderImage(ImageResource*)
3171 // Without visibility we won't render (and therefore don't care about animation).
3172 if (style()->visibility() != VISIBLE)
3175 // We will not render a new image when Active DOM is suspended
3176 if (document().activeDOMObjectsAreSuspended())
3179 // If we're not in a window (i.e., we're dormant from being in a background tab)
3180 // then we don't want to render either.
3181 return document().view()->isVisible();
3184 int RenderObject::caretMinOffset() const
3189 int RenderObject::caretMaxOffset() const
3192 return node() ? std::max(1U, node()->countChildren()) : 1;
3198 int RenderObject::previousOffset(int current) const
3203 int RenderObject::previousOffsetForBackwardDeletion(int current) const
3208 int RenderObject::nextOffset(int current) const
3213 bool RenderObject::isInert() const
3215 const RenderObject* renderer = this;
3216 while (!renderer->node())
3217 renderer = renderer->parent();
3218 return renderer->node()->isInert();
3221 // touch-action applies to all elements with both width AND height properties.
3222 // According to the CSS Box Model Spec (http://dev.w3.org/csswg/css-box/#the-width-and-height-properties)
3223 // width applies to all elements but non-replaced inline elements, table rows, and row groups and
3224 // height applies to all elements but non-replaced inline elements, table columns, and column groups.
3225 bool RenderObject::supportsTouchAction() const
3227 if (isInline() && !isReplaced())
3229 if (isTableRow() || isRenderTableCol())
3235 void RenderObject::imageChanged(ImageResource* image, const IntRect* rect)
3237 imageChanged(static_cast<WrappedImagePtr>(image), rect);
3240 Element* RenderObject::offsetParent() const
3242 if (isDocumentElement() || isBody())
3245 if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
3248 // If A is an area HTML element which has a map HTML element somewhere in the ancestor
3249 // chain return the nearest ancestor map HTML element and stop this algorithm.
3250 // FIXME: Implement!
3252 float effectiveZoom = style()->effectiveZoom();
3254 for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
3255 // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
3257 node = ancestor->node();
3262 if (ancestor->isPositioned())
3265 if (isHTMLBodyElement(*node))
3268 if (!isPositioned() && (isHTMLTableElement(*node) || isHTMLTableCellElement(*node)))
3271 // Webkit specific extension where offsetParent stops at zoom level changes.
3272 if (effectiveZoom != ancestor->style()->effectiveZoom())
3276 return node && node->isElementNode() ? toElement(node) : 0;
3279 PositionWithAffinity RenderObject::createPositionWithAffinity(int offset, EAffinity affinity)
3281 // If this is a non-anonymous renderer in an editable area, then it's simple.
3282 if (Node* node = nonPseudoNode()) {
3283 if (!node->hasEditableStyle()) {
3284 // If it can be found, we prefer a visually equivalent position that is editable.
3285 Position position = createLegacyEditingPosition(node, offset);
3286 Position candidate = position.downstream(CanCrossEditingBoundary);
3287 if (candidate.deprecatedNode()->hasEditableStyle())
3288 return PositionWithAffinity(candidate, affinity);
3289 candidate = position.upstream(CanCrossEditingBoundary);
3290 if (candidate.deprecatedNode()->hasEditableStyle())
3291 return PositionWithAffinity(candidate, affinity);
3293 // FIXME: Eliminate legacy editing positions
3294 return PositionWithAffinity(createLegacyEditingPosition(node, offset), affinity);
3297 // We don't want to cross the boundary between editable and non-editable
3298 // regions of the document, but that is either impossible or at least
3299 // extremely unlikely in any normal case because we stop as soon as we
3300 // find a single non-anonymous renderer.
3302 // Find a nearby non-anonymous renderer.
3303 RenderObject* child = this;
3304 while (RenderObject* parent = child->parent()) {
3305 // Find non-anonymous content after.
3306 for (RenderObject* renderer = child->nextInPreOrder(parent); renderer; renderer = renderer->nextInPreOrder(parent)) {
3307 if (Node* node = renderer->nonPseudoNode())
3308 return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3311 // Find non-anonymous content before.
3312 for (RenderObject* renderer = child->previousInPreOrder(); renderer; renderer = renderer->previousInPreOrder()) {
3313 if (renderer == parent)
3315 if (Node* node = renderer->nonPseudoNode())
3316 return PositionWithAffinity(lastPositionInOrAfterNode(node), DOWNSTREAM);
3319 // Use the parent itself unless it too is anonymous.
3320 if (Node* node = parent->nonPseudoNode())
3321 return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3323 // Repeat at the next level up.
3327 // Everything was anonymous. Give up.
3328 return PositionWithAffinity();
3331 PositionWithAffinity RenderObject::createPositionWithAffinity(const Position& position)
3333 if (position.isNotNull())
3334 return PositionWithAffinity(position);
3337 return createPositionWithAffinity(0, DOWNSTREAM);
3340 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
3342 return SetCursorBasedOnStyle;
3345 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
3350 RenderBlock* containingBlock = this->containingBlock();
3351 return containingBlock ? !containingBlock->needsLayout() : false;
3354 // We only create "generated" child renderers like one for first-letter if:
3355 // - the firstLetterBlock can have children in the DOM and
3356 // - the block doesn't have any special assumption on its text children.
3357 // This correctly prevents form controls from having such renderers.
3358 bool RenderObject::canHaveGeneratedChildren() const
3360 return canHaveChildren();
3363 void RenderObject::setNeedsBoundariesUpdate()
3365 if (RenderObject* renderer = parent())
3366 renderer->setNeedsBoundariesUpdate();
3369 FloatRect RenderObject::objectBoundingBox() const
3371 ASSERT_NOT_REACHED();
3375 FloatRect RenderObject::strokeBoundingBox() const
3377 ASSERT_NOT_REACHED();
3381 // Returns the smallest rectangle enclosing all of the painted content
3382 // respecting clipping, masking, filters, opacity, stroke-width and markers
3383 FloatRect RenderObject::paintInvalidationRectInLocalCoordinates() const
3385 ASSERT_NOT_REACHED();
3389 AffineTransform RenderObject::localTransform() const
3391 static const AffineTransform identity;
3395 const AffineTransform& RenderObject::localToParentTransform() const
3397 static const AffineTransform identity;
3401 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
3403 ASSERT_NOT_REACHED();
3407 bool RenderObject::isRelayoutBoundaryForInspector() const
3409 return objectIsRelayoutBoundary(this);
3412 void RenderObject::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
3414 // paintInvalidationStateIsDirty should be kept in sync with the
3415 // booleans that are cleared below.
3416 ASSERT(paintInvalidationState.forceCheckForPaintInvalidation() || paintInvalidationStateIsDirty());
3417 setShouldDoFullPaintInvalidation(false);
3418 setShouldDoFullPaintInvalidationIfSelfPaintingLayer(false);
3419 setOnlyNeededPositionedMovementLayout(false);
3420 setNeededLayoutBecauseOfChildren(false);
3421 setShouldInvalidateOverflowForPaint(false);
3422 setLayoutDidGetCalled(false);
3423 setMayNeedPaintInvalidation(false);
3426 bool RenderObject::isAllowedToModifyRenderTreeStructure(Document& document)
3428 return DeprecatedDisableModifyRenderTreeStructureAsserts::canModifyRenderTreeStateInAnyState()
3429 || document.lifecycle().stateAllowsRenderTreeMutations();
3432 DeprecatedDisableModifyRenderTreeStructureAsserts::DeprecatedDisableModifyRenderTreeStructureAsserts()
3433 : m_disabler(gModifyRenderTreeStructureAnyState, true)
3437 bool DeprecatedDisableModifyRenderTreeStructureAsserts::canModifyRenderTreeStateInAnyState()
3439 return gModifyRenderTreeStructureAnyState;
3442 } // namespace blink
3446 void showTree(const blink::RenderObject* object)
3449 object->showTreeForThis();
3452 void showLineTree(const blink::RenderObject* object)
3455 object->showLineTreeForThis();
3458 void showRenderTree(const blink::RenderObject* object1)
3460 showRenderTree(object1, 0);
3463 void showRenderTree(const blink::RenderObject* object1, const blink::RenderObject* object2)
3466 const blink::RenderObject* root = object1;
3467 while (root->parent())
3468 root = root->parent();
3469 root->showRenderTreeAndMark(object1, "*", object2, "-", 0);