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/animation/ActiveAnimations.h"
33 #include "core/css/resolver/StyleResolver.h"
34 #include "core/dom/ElementTraversal.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/FrameView.h"
42 #include "core/frame/LocalFrame.h"
43 #include "core/html/HTMLAnchorElement.h"
44 #include "core/html/HTMLElement.h"
45 #include "core/html/HTMLHtmlElement.h"
46 #include "core/html/HTMLTableCellElement.h"
47 #include "core/html/HTMLTableElement.h"
48 #include "core/page/AutoscrollController.h"
49 #include "core/page/EventHandler.h"
50 #include "core/page/Page.h"
51 #include "core/frame/Settings.h"
52 #include "core/frame/UseCounter.h"
53 #include "core/rendering/FlowThreadController.h"
54 #include "core/rendering/HitTestResult.h"
55 #include "core/rendering/RenderCounter.h"
56 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
57 #include "core/rendering/RenderFlexibleBox.h"
58 #include "core/rendering/RenderFlowThread.h"
59 #include "core/rendering/RenderGeometryMap.h"
60 #include "core/rendering/RenderGrid.h"
61 #include "core/rendering/RenderImage.h"
62 #include "core/rendering/RenderImageResourceStyleImage.h"
63 #include "core/rendering/RenderInline.h"
64 #include "core/rendering/RenderLayer.h"
65 #include "core/rendering/RenderListItem.h"
66 #include "core/rendering/RenderMarquee.h"
67 #include "core/rendering/RenderScrollbarPart.h"
68 #include "core/rendering/RenderTableCaption.h"
69 #include "core/rendering/RenderTableCell.h"
70 #include "core/rendering/RenderTableCol.h"
71 #include "core/rendering/RenderTableRow.h"
72 #include "core/rendering/RenderTheme.h"
73 #include "core/rendering/RenderView.h"
74 #include "core/rendering/compositing/CompositedLayerMapping.h"
75 #include "core/rendering/compositing/RenderLayerCompositor.h"
76 #include "core/rendering/style/ContentData.h"
77 #include "core/rendering/style/ShadowList.h"
78 #include "platform/JSONValues.h"
79 #include "platform/Partitions.h"
80 #include "platform/RuntimeEnabledFeatures.h"
81 #include "platform/TraceEvent.h"
82 #include "platform/TracedValue.h"
83 #include "platform/geometry/TransformState.h"
84 #include "platform/graphics/GraphicsContext.h"
85 #include "wtf/RefCountedLeakCounter.h"
86 #include "wtf/text/StringBuilder.h"
87 #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_bitfields;
127 unsigned m_bitfields2;
128 LayoutRect rect; // Stores the previous paint invalidation rect.
129 LayoutPoint position; // Stores the previous position from the paint invalidation container.
132 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
134 bool RenderObject::s_affectsParentBlock = false;
136 void* RenderObject::operator new(size_t sz)
138 ASSERT(isMainThread());
139 return partitionAlloc(Partitions::getRenderingPartition(), sz);
142 void RenderObject::operator delete(void* ptr)
144 ASSERT(isMainThread());
148 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
150 ASSERT(isAllowedToModifyRenderTreeStructure(element->document()));
152 // Minimal support for content properties replacing an entire element.
153 // Works only if we have exactly one piece of content and it's a URL.
154 // Otherwise acts as if we didn't support this feature.
155 const ContentData* contentData = style->contentData();
156 if (contentData && !contentData->next() && contentData->isImage() && !element->isPseudoElement()) {
157 RenderImage* image = new RenderImage(element);
158 // RenderImageResourceStyleImage requires a style being present on the image but we don't want to
159 // trigger a style change now as the node is not fully attached. Moving this code to style change
160 // doesn't make sense as it should be run once at renderer creation.
161 image->setStyleInternal(style);
162 if (const StyleImage* styleImage = static_cast<const ImageContentData*>(contentData)->image()) {
163 image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
164 image->setIsGeneratedContent();
166 image->setImageResource(RenderImageResource::create());
167 image->setStyleInternal(nullptr);
171 switch (style->display()) {
175 return new RenderInline(element);
178 return new RenderBlockFlow(element);
180 return new RenderListItem(element);
183 return new RenderTable(element);
184 case TABLE_ROW_GROUP:
185 case TABLE_HEADER_GROUP:
186 case TABLE_FOOTER_GROUP:
187 return new RenderTableSection(element);
189 return new RenderTableRow(element);
190 case TABLE_COLUMN_GROUP:
192 return new RenderTableCol(element);
194 return new RenderTableCell(element);
196 return new RenderTableCaption(element);
199 return new RenderDeprecatedFlexibleBox(element);
202 return new RenderFlexibleBox(element);
205 return new RenderGrid(element);
211 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
213 RenderObject::RenderObject(Node* node)
214 : ImageResourceClient()
221 , m_hasAXObject(false)
222 , m_setNeedsLayoutForbidden(false)
227 renderObjectCounter.increment();
231 RenderObject::~RenderObject()
233 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
235 ASSERT(!m_hasAXObject);
236 renderObjectCounter.decrement();
240 String RenderObject::debugName() const
243 name.append(renderName());
245 if (Node* node = this->node()) {
247 name.append(node->debugName());
250 return name.toString();
253 bool RenderObject::isDescendantOf(const RenderObject* obj) const
255 for (const RenderObject* r = this; r; r = r->m_parent) {
262 bool RenderObject::isHR() const
264 return isHTMLHRElement(node());
267 bool RenderObject::isLegend() const
269 return isHTMLLegendElement(node());
272 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
274 for (RenderObject *object = this; object; object = object->nextInPreOrder(this)) {
275 // If object is a fragmentation context it already updated the descendants flag accordingly.
276 if (object->isRenderFlowThread())
278 ASSERT(state != object->flowThreadState());
279 object->setFlowThreadState(state);
283 bool RenderObject::requiresAnonymousTableWrappers(const RenderObject* newChild) const
285 // Check should agree with:
286 // CSS 2.1 Tables: 17.2.1 Anonymous table objects
287 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
288 if (newChild->isRenderTableCol()) {
289 const RenderTableCol* newTableColumn = toRenderTableCol(newChild);
290 bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isRenderTableCol();
291 return !isTable() && !isColumnInColumnGroup;
292 } else if (newChild->isTableCaption())
294 else if (newChild->isTableSection())
296 else if (newChild->isTableRow())
297 return !isTableSection();
298 else if (newChild->isTableCell())
299 return !isTableRow();
303 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
305 ASSERT(isAllowedToModifyRenderTreeStructure(document()));
307 RenderObjectChildList* children = virtualChildren();
312 if (requiresAnonymousTableWrappers(newChild)) {
313 // Generate an anonymous table or reuse existing one from previous child
314 // Per: 17.2.1 Anonymous table objects 3. Generate missing parents
315 // http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes
317 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
318 if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent())
319 table = toRenderTable(afterChild);
321 table = RenderTable::createAnonymousWithParentRenderer(this);
322 addChild(table, beforeChild);
324 table->addChild(newChild);
326 children->insertChildNode(this, newChild, beforeChild);
328 if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE)
329 toRenderText(newChild)->transformText();
331 // SVG creates renderers for <g display="none">, as SVG requires children of hidden
332 // <g>s to have renderers - at least that's how our implementation works. Consider:
333 // <g display="none"><foreignObject><body style="position: relative">FOO...
334 // - layerTypeRequired() would return true for the <body>, creating a new RenderLayer
335 // - when the document is painted, both layers are painted. The <body> layer doesn't
336 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
337 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
338 // and stop creating layers at all for these cases - they're not used anyways.
339 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
340 toRenderLayerModelObject(newChild)->layer()->removeOnlyThisLayer();
343 void RenderObject::removeChild(RenderObject* oldChild)
345 ASSERT(isAllowedToModifyRenderTreeStructure(document()));
347 RenderObjectChildList* children = virtualChildren();
352 children->removeChildNode(this, oldChild);
355 RenderObject* RenderObject::nextInPreOrder() const
357 if (RenderObject* o = slowFirstChild())
360 return nextInPreOrderAfterChildren();
363 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
366 if (!(o = nextSibling())) {
368 while (o && !o->nextSibling())
371 o = o->nextSibling();
377 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
379 if (RenderObject* o = slowFirstChild())
382 return nextInPreOrderAfterChildren(stayWithin);
385 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
387 if (this == stayWithin)
390 const RenderObject* current = this;
392 while (!(next = current->nextSibling())) {
393 current = current->parent();
394 if (!current || current == stayWithin)
400 RenderObject* RenderObject::previousInPreOrder() const
402 if (RenderObject* o = previousSibling()) {
403 while (RenderObject* lastChild = o->slowLastChild())
411 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
413 if (this == stayWithin)
416 return previousInPreOrder();
419 RenderObject* RenderObject::childAt(unsigned index) const
421 RenderObject* child = slowFirstChild();
422 for (unsigned i = 0; child && i < index; i++)
423 child = child->nextSibling();
427 RenderObject* RenderObject::lastLeafChild() const
429 RenderObject* r = slowLastChild();
432 n = r->slowLastChild();
440 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
441 RenderLayer*& beforeChild)
443 if (obj->hasLayer()) {
444 if (!beforeChild && newObject) {
445 // We need to figure out the layer that follows newObject. We only do
446 // this the first time we find a child layer, and then we update the
447 // pointer values for newObject and beforeChild used by everyone else.
448 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
451 parentLayer->addChild(toRenderLayerModelObject(obj)->layer(), beforeChild);
455 for (RenderObject* curr = obj->slowFirstChild(); curr; curr = curr->nextSibling())
456 addLayers(curr, parentLayer, newObject, beforeChild);
459 void RenderObject::addLayers(RenderLayer* parentLayer)
464 RenderObject* object = this;
465 RenderLayer* beforeChild = 0;
466 WebCore::addLayers(this, parentLayer, object, beforeChild);
469 void RenderObject::removeLayers(RenderLayer* parentLayer)
475 parentLayer->removeChild(toRenderLayerModelObject(this)->layer());
479 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
480 curr->removeLayers(parentLayer);
483 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
489 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
490 ASSERT(oldParent == layer->parent());
492 oldParent->removeChild(layer);
493 newParent->addChild(layer);
497 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
498 curr->moveLayers(oldParent, newParent);
501 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
504 // Error check the parent layer passed in. If it's null, we can't find anything.
508 // Step 1: If our layer is a child of the desired parent, then return our layer.
509 RenderLayer* ourLayer = hasLayer() ? toRenderLayerModelObject(this)->layer() : 0;
510 if (ourLayer && ourLayer->parent() == parentLayer)
513 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
514 // into our siblings trying to find the next layer whose parent is the desired parent.
515 if (!ourLayer || ourLayer == parentLayer) {
516 for (RenderObject* curr = startPoint ? startPoint->nextSibling() : slowFirstChild();
517 curr; curr = curr->nextSibling()) {
518 RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
524 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
526 if (parentLayer == ourLayer)
529 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
530 // follow us to see if we can locate a layer.
531 if (checkParent && parent())
532 return parent()->findNextLayer(parentLayer, this, true);
537 RenderLayer* RenderObject::enclosingLayer() const
539 for (const RenderObject* current = this; current; current = current->parent()) {
540 if (current->hasLayer())
541 return toRenderLayerModelObject(current)->layer();
543 // FIXME: We should remove the one caller that triggers this case and make
544 // this function return a reference.
545 ASSERT(!m_parent && !isRenderView());
549 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
551 RenderBox* enclosingBox = this->enclosingBox();
555 enclosingBox->scrollRectToVisible(rect, alignX, alignY);
559 RenderBox* RenderObject::enclosingBox() const
561 RenderObject* curr = const_cast<RenderObject*>(this);
564 return toRenderBox(curr);
565 curr = curr->parent();
568 ASSERT_NOT_REACHED();
572 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
574 RenderObject* curr = const_cast<RenderObject*>(this);
576 if (curr->isBoxModelObject())
577 return toRenderBoxModelObject(curr);
578 curr = curr->parent();
581 ASSERT_NOT_REACHED();
585 RenderBox* RenderObject::enclosingScrollableBox() const
587 for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
588 if (!ancestor->isBox())
591 RenderBox* ancestorBox = toRenderBox(ancestor);
592 if (ancestorBox->canBeScrolledAndHasScrollableArea())
599 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
601 ASSERT(flowThreadState() != NotInsideFlowThread);
603 // See if we have the thread cached because we're in the middle of layout.
604 RenderFlowThread* flowThread = view()->flowThreadController()->currentRenderFlowThread();
608 // Not in the middle of layout so have to find the thread the slow way.
609 RenderObject* curr = const_cast<RenderObject*>(this);
611 if (curr->isRenderFlowThread())
612 return toRenderFlowThread(curr);
613 curr = curr->containingBlock();
618 RenderBlock* RenderObject::firstLineBlock() const
623 static inline bool objectIsRelayoutBoundary(const RenderObject* object)
625 // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
626 if (object->isTextControl())
629 if (object->isSVGRoot())
632 if (!object->hasOverflowClip())
635 if (object->style()->width().isIntrinsicOrAuto() || object->style()->height().isIntrinsicOrAuto() || object->style()->height().isPercent())
638 // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
639 if (object->isTablePart())
645 void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot, SubtreeLayoutScope* layouter)
647 ASSERT(!scheduleRelayout || !newRoot);
648 ASSERT(!isSetNeedsLayoutForbidden());
649 ASSERT(!layouter || this != layouter->root());
651 RenderObject* object = container();
652 RenderObject* last = this;
654 bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
657 if (object->selfNeedsLayout())
660 // Don't mark the outermost object of an unrooted subtree. That object will be
661 // marked when the subtree is added to the document.
662 RenderObject* container = object->container();
663 if (!container && !object->isRenderView())
665 if (!last->isText() && last->style()->hasOutOfFlowPosition()) {
666 bool willSkipRelativelyPositionedInlines = !object->isRenderBlock() || object->isAnonymousBlock();
667 // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
668 while (object && (!object->isRenderBlock() || object->isAnonymousBlock()))
669 object = object->container();
670 if (!object || object->posChildNeedsLayout())
672 if (willSkipRelativelyPositionedInlines)
673 container = object->container();
674 object->setPosChildNeedsLayout(true);
675 simplifiedNormalFlowLayout = true;
676 ASSERT(!object->isSetNeedsLayoutForbidden());
677 } else if (simplifiedNormalFlowLayout) {
678 if (object->needsSimplifiedNormalFlowLayout())
680 object->setNeedsSimplifiedNormalFlowLayout(true);
681 ASSERT(!object->isSetNeedsLayoutForbidden());
683 if (object->normalChildNeedsLayout())
685 object->setNormalChildNeedsLayout(true);
686 ASSERT(!object->isSetNeedsLayoutForbidden());
690 layouter->addRendererToLayout(object);
691 if (object == layouter->root())
695 if (object == newRoot)
699 if (scheduleRelayout && objectIsRelayoutBoundary(last))
704 if (scheduleRelayout)
705 last->scheduleRelayout();
709 void RenderObject::checkBlockPositionedObjectsNeedLayout()
711 ASSERT(!needsLayout());
714 toRenderBlock(this)->checkPositionedObjectsNeedLayout();
718 void RenderObject::setPreferredLogicalWidthsDirty(MarkingBehavior markParents)
720 m_bitfields.setPreferredLogicalWidthsDirty(true);
721 if (markParents == MarkContainingBlockChain && (isText() || !style()->hasOutOfFlowPosition()))
722 invalidateContainerPreferredLogicalWidths();
725 void RenderObject::clearPreferredLogicalWidthsDirty()
727 m_bitfields.setPreferredLogicalWidthsDirty(false);
730 void RenderObject::invalidateContainerPreferredLogicalWidths()
732 // In order to avoid pathological behavior when inlines are deeply nested, we do include them
733 // in the chain that we mark dirty (even though they're kind of irrelevant).
734 RenderObject* o = isTableCell() ? containingBlock() : container();
735 while (o && !o->preferredLogicalWidthsDirty()) {
736 // Don't invalidate the outermost object of an unrooted subtree. That object will be
737 // invalidated when the subtree is added to the document.
738 RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
739 if (!container && !o->isRenderView())
742 o->m_bitfields.setPreferredLogicalWidthsDirty(true);
743 if (o->style()->hasOutOfFlowPosition())
744 // A positioned object has no effect on the min/max width of its containing block ever.
745 // We can optimize this case and not go up any further.
751 void RenderObject::setLayerNeedsFullPaintInvalidationForPositionedMovementLayout()
754 toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
757 RenderBlock* RenderObject::containerForFixedPosition(const RenderLayerModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
759 ASSERT(!paintInvalidationContainerSkipped || !*paintInvalidationContainerSkipped);
761 ASSERT(style()->position() == FixedPosition);
763 RenderObject* ancestor = parent();
764 for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
765 if (paintInvalidationContainerSkipped && ancestor == paintInvalidationContainer)
766 *paintInvalidationContainerSkipped = true;
769 ASSERT(!ancestor || !ancestor->isAnonymousBlock());
770 return toRenderBlock(ancestor);
773 RenderBlock* RenderObject::containingBlock() const
775 RenderObject* o = parent();
776 if (!o && isRenderScrollbarPart())
777 o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
778 if (!isText() && m_style->position() == FixedPosition) {
779 return containerForFixedPosition();
780 } else if (!isText() && m_style->position() == AbsolutePosition) {
782 // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
783 // to return the inline itself. This allows us to avoid having a positioned objects
784 // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
785 // from this method. The container() method can actually be used to obtain the
787 if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
790 if (o->canContainFixedPositionObjects())
793 if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
794 o = o->containingBlock();
801 if (o && !o->isRenderBlock())
802 o = o->containingBlock();
804 while (o && o->isAnonymousBlock())
805 o = o->containingBlock();
807 while (o && ((o->isInline() && !o->isReplaced()) || !o->isRenderBlock()))
811 if (!o || !o->isRenderBlock())
812 return 0; // This can still happen in case of an orphaned tree
814 return toRenderBlock(o);
817 RenderObject* RenderObject::clippingContainer() const
819 RenderObject* container = const_cast<RenderObject*>(this);
821 if (container->style()->position() == FixedPosition) {
822 for (container = container->parent(); container && !container->canContainFixedPositionObjects(); container = container->parent()) {
823 // CSS clip applies to fixed position elements even for ancestors that are not what the
824 // fixed element is positioned with respect to.
825 if (container->hasClip())
829 container = container->containingBlock();
834 if (container->hasClipOrOverflowClip())
840 bool RenderObject::canRenderBorderImage() const
842 ASSERT(style()->hasBorder());
844 StyleImage* borderImage = style()->borderImage().image();
845 return borderImage && borderImage->canRender(*this, style()->effectiveZoom()) && borderImage->isLoaded();
848 bool RenderObject::mustInvalidateFillLayersPaintOnWidthChange(const FillLayer& layer) const
850 // Nobody will use multiple layers without wanting fancy positioning.
854 // Make sure we have a valid image.
855 StyleImage* img = layer.image();
856 if (!img || !img->canRender(*this, style()->effectiveZoom()))
859 if (layer.repeatX() != RepeatFill && layer.repeatX() != NoRepeatFill)
862 if (layer.xPosition().isPercent() && !layer.xPosition().isZero())
865 if (layer.backgroundXOrigin() != LeftEdge)
868 EFillSizeType sizeType = layer.sizeType();
870 if (sizeType == Contain || sizeType == Cover)
873 if (sizeType == SizeLength) {
874 if (layer.sizeLength().width().isPercent() && !layer.sizeLength().width().isZero())
876 if (img->isGeneratedImage() && layer.sizeLength().width().isAuto())
878 } else if (img->usesImageContainerSize()) {
885 bool RenderObject::mustInvalidateFillLayersPaintOnHeightChange(const FillLayer& layer) const
887 // Nobody will use multiple layers without wanting fancy positioning.
891 // Make sure we have a valid image.
892 StyleImage* img = layer.image();
893 if (!img || !img->canRender(*this, style()->effectiveZoom()))
896 if (layer.repeatY() != RepeatFill && layer.repeatY() != NoRepeatFill)
899 if (layer.yPosition().isPercent() && !layer.yPosition().isZero())
902 if (layer.backgroundYOrigin() != TopEdge)
905 EFillSizeType sizeType = layer.sizeType();
907 if (sizeType == Contain || sizeType == Cover)
910 if (sizeType == SizeLength) {
911 if (layer.sizeLength().height().isPercent() && !layer.sizeLength().height().isZero())
913 if (img->isGeneratedImage() && layer.sizeLength().height().isAuto())
915 } else if (img->usesImageContainerSize()) {
922 bool RenderObject::mustInvalidateBackgroundOrBorderPaintOnWidthChange() const
924 if (hasMask() && mustInvalidateFillLayersPaintOnWidthChange(*style()->maskLayers()))
927 // If we don't have a background/border/mask, then nothing to do.
928 if (!hasBoxDecorations())
931 if (mustInvalidateFillLayersPaintOnWidthChange(*style()->backgroundLayers()))
934 // Our fill layers are ok. Let's check border.
935 if (style()->hasBorder() && canRenderBorderImage())
941 bool RenderObject::mustInvalidateBackgroundOrBorderPaintOnHeightChange() const
943 if (hasMask() && mustInvalidateFillLayersPaintOnHeightChange(*style()->maskLayers()))
946 // If we don't have a background/border/mask, then nothing to do.
947 if (!hasBoxDecorations())
950 if (mustInvalidateFillLayersPaintOnHeightChange(*style()->backgroundLayers()))
953 // Our fill layers are ok. Let's check border.
954 if (style()->hasBorder() && canRenderBorderImage())
960 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
961 BoxSide side, Color color, EBorderStyle style,
962 int adjacentWidth1, int adjacentWidth2, bool antialias)
966 if (side == BSTop || side == BSBottom) {
974 // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
975 // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
976 if (!thickness || !length)
979 if (style == DOUBLE && thickness < 3)
988 drawDashedOrDottedBoxSide(graphicsContext, x1, y1, x2, y2, side,
989 color, thickness, style, antialias);
992 drawDoubleBoxSide(graphicsContext, x1, y1, x2, y2, length, side, color,
993 thickness, adjacentWidth1, adjacentWidth2, antialias);
997 drawRidgeOrGrooveBoxSide(graphicsContext, x1, y1, x2, y2, side, color,
998 style, adjacentWidth1, adjacentWidth2, antialias);
1001 // FIXME: Maybe we should lighten the colors on one side like Firefox.
1002 // https://bugs.webkit.org/show_bug.cgi?id=58608
1003 if (side == BSTop || side == BSLeft)
1004 color = color.dark();
1007 if (style == OUTSET && (side == BSBottom || side == BSRight))
1008 color = color.dark();
1011 drawSolidBoxSide(graphicsContext, x1, y1, x2, y2, side, color, adjacentWidth1, adjacentWidth2, antialias);
1016 void RenderObject::drawDashedOrDottedBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1017 BoxSide side, Color color, int thickness, EBorderStyle style, bool antialias)
1022 bool wasAntialiased = graphicsContext->shouldAntialias();
1023 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1024 graphicsContext->setShouldAntialias(antialias);
1025 graphicsContext->setStrokeColor(color);
1026 graphicsContext->setStrokeThickness(thickness);
1027 graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
1032 graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
1036 graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
1039 graphicsContext->setShouldAntialias(wasAntialiased);
1040 graphicsContext->setStrokeStyle(oldStrokeStyle);
1043 void RenderObject::drawDoubleBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1044 int length, BoxSide side, Color color, int thickness, int adjacentWidth1, int adjacentWidth2, bool antialias)
1046 int thirdOfThickness = (thickness + 1) / 3;
1047 ASSERT(thirdOfThickness);
1049 if (!adjacentWidth1 && !adjacentWidth2) {
1050 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1051 graphicsContext->setStrokeStyle(NoStroke);
1052 graphicsContext->setFillColor(color);
1054 bool wasAntialiased = graphicsContext->shouldAntialias();
1055 graphicsContext->setShouldAntialias(antialias);
1060 graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
1061 graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
1065 // FIXME: Why do we offset the border by 1 in this case but not the other one?
1067 graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
1068 graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
1073 graphicsContext->setShouldAntialias(wasAntialiased);
1074 graphicsContext->setStrokeStyle(oldStrokeStyle);
1078 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
1079 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
1083 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1084 y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1085 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1086 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1087 y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
1088 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1091 drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1092 x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
1093 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1094 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1095 x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
1096 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1099 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1100 y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
1101 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1102 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1103 y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
1104 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1107 drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
1108 x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
1109 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1110 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
1111 x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
1112 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1119 void RenderObject::drawRidgeOrGrooveBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1120 BoxSide side, Color color, EBorderStyle style, int adjacentWidth1, int adjacentWidth2, bool antialias)
1124 if (style == GROOVE) {
1132 int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
1133 int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
1137 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1138 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1139 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
1140 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1143 drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
1144 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1145 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
1146 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1149 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1150 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1151 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
1152 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1155 drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
1156 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1157 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
1158 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1163 void RenderObject::drawSolidBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
1164 BoxSide side, Color color, int adjacentWidth1, int adjacentWidth2, bool antialias)
1166 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1167 graphicsContext->setStrokeStyle(NoStroke);
1168 graphicsContext->setFillColor(color);
1171 if (!adjacentWidth1 && !adjacentWidth2) {
1172 // Turn off antialiasing to match the behavior of drawConvexPolygon();
1173 // this matters for rects in transformed contexts.
1174 bool wasAntialiased = graphicsContext->shouldAntialias();
1175 graphicsContext->setShouldAntialias(antialias);
1176 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
1177 graphicsContext->setShouldAntialias(wasAntialiased);
1178 graphicsContext->setStrokeStyle(oldStrokeStyle);
1184 quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
1185 quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
1186 quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
1187 quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
1190 quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
1191 quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
1192 quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
1193 quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
1196 quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
1197 quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
1198 quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
1199 quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
1202 quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
1203 quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
1204 quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
1205 quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
1209 graphicsContext->drawConvexPolygon(4, quad, antialias);
1210 graphicsContext->setStrokeStyle(oldStrokeStyle);
1213 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
1215 Vector<IntRect> focusRingRects;
1216 addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer());
1217 if (style->outlineStyleIsAuto())
1218 paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), resolveColor(style, CSSPropertyOutlineColor));
1220 addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
1223 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
1228 if (!n || !n->isLink() || !n->isElementNode())
1230 const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
1233 KURL url = n->document().completeURL(href);
1236 if (context->supportsURLFragments() && url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, n->document().baseURL())) {
1237 String name = url.fragmentIdentifier();
1238 if (document().findAnchor(name))
1239 context->setURLFragmentForRect(name, pixelSnappedIntRect(rect));
1242 context->setURLForRect(url, pixelSnappedIntRect(rect));
1245 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1250 RenderStyle* styleToUse = style();
1251 LayoutUnit outlineWidth = styleToUse->outlineWidth();
1253 int outlineOffset = styleToUse->outlineOffset();
1255 if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1256 if (RenderTheme::theme().shouldDrawDefaultFocusRing(this)) {
1257 // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1258 paintFocusRing(paintInfo, paintRect.location(), styleToUse);
1262 if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1265 IntRect inner = pixelSnappedIntRect(paintRect);
1266 inner.inflate(outlineOffset);
1268 IntRect outer = pixelSnappedIntRect(inner);
1269 outer.inflate(outlineWidth);
1271 // FIXME: This prevents outlines from painting inside the object. See bug 12042
1272 if (outer.isEmpty())
1275 EBorderStyle outlineStyle = styleToUse->outlineStyle();
1276 Color outlineColor = resolveColor(styleToUse, CSSPropertyOutlineColor);
1278 GraphicsContext* graphicsContext = paintInfo.context;
1279 bool useTransparencyLayer = outlineColor.hasAlpha();
1280 if (useTransparencyLayer) {
1281 if (outlineStyle == SOLID) {
1283 path.addRect(outer);
1284 path.addRect(inner);
1285 graphicsContext->setFillRule(RULE_EVENODD);
1286 graphicsContext->setFillColor(outlineColor);
1287 graphicsContext->fillPath(path);
1290 graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1291 outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1294 int leftOuter = outer.x();
1295 int leftInner = inner.x();
1296 int rightOuter = outer.maxX();
1297 int rightInner = inner.maxX();
1298 int topOuter = outer.y();
1299 int topInner = inner.y();
1300 int bottomOuter = outer.maxY();
1301 int bottomInner = inner.maxY();
1303 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1304 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1305 drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1306 drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1308 if (useTransparencyLayer)
1309 graphicsContext->endLayer();
1312 void RenderObject::addChildFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer)
1314 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling()) {
1315 if (current->isText() || current->isListMarker())
1318 if (current->isBox()) {
1319 RenderBox* box = toRenderBox(current);
1320 if (box->hasLayer()) {
1321 Vector<IntRect> layerFocusRingRects;
1322 box->addFocusRingRects(layerFocusRingRects, LayoutPoint(), box);
1323 for (size_t i = 0; i < layerFocusRingRects.size(); ++i) {
1324 FloatQuad quadInBox = box->localToContainerQuad(FloatRect(layerFocusRingRects[i]), paintContainer);
1325 rects.append(pixelSnappedIntRect(LayoutRect(quadInBox.boundingBox())));
1328 FloatPoint pos(additionalOffset);
1329 pos.move(box->locationOffset()); // FIXME: Snap offsets? crbug.com/350474
1330 box->addFocusRingRects(rects, flooredIntPoint(pos), paintContainer);
1333 current->addFocusRingRects(rects, additionalOffset, paintContainer);
1338 // FIXME: In repaint-after-layout, we should be able to change the logic to remove the need for this function. See crbug.com/368416.
1339 LayoutPoint RenderObject::positionFromPaintInvalidationContainer(const RenderLayerModelObject* paintInvalidationContainer) const
1341 // FIXME: This assert should be re-enabled when we move paint invalidation to after compositing update. crbug.com/360286
1342 // ASSERT(containerForPaintInvalidation() == paintInvalidationContainer);
1344 LayoutPoint offset = isBox() ? toRenderBox(this)->location() : LayoutPoint();
1345 if (paintInvalidationContainer == this)
1348 return roundedIntPoint(localToContainerPoint(offset, paintInvalidationContainer));
1351 IntRect RenderObject::absoluteBoundingBoxRect() const
1353 Vector<FloatQuad> quads;
1354 absoluteQuads(quads);
1356 size_t n = quads.size();
1360 IntRect result = quads[0].enclosingBoundingBox();
1361 for (size_t i = 1; i < n; ++i)
1362 result.unite(quads[i].enclosingBoundingBox());
1366 IntRect RenderObject::absoluteBoundingBoxRectIgnoringTransforms() const
1368 FloatPoint absPos = localToAbsolute();
1369 Vector<IntRect> rects;
1370 absoluteRects(rects, flooredLayoutPoint(absPos));
1372 size_t n = rects.size();
1376 LayoutRect result = rects[0];
1377 for (size_t i = 1; i < n; ++i)
1378 result.unite(rects[i]);
1379 return pixelSnappedIntRect(result);
1382 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1384 Vector<IntRect> rects;
1385 const RenderLayerModelObject* container = containerForPaintInvalidation();
1386 addFocusRingRects(rects, LayoutPoint(localToContainerPoint(FloatPoint(), container)), container);
1387 size_t count = rects.size();
1388 for (size_t i = 0; i < count; ++i)
1389 quads.append(container->localToAbsoluteQuad(FloatQuad(rects[i])));
1392 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1394 if (!range || !range->startContainer())
1397 range->ownerDocument().updateLayout();
1399 Vector<FloatQuad> quads;
1400 range->textQuads(quads);
1403 for (size_t i = 0; i < quads.size(); ++i)
1404 result.unite(quads[i].boundingBox());
1409 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1412 result.unite(absoluteBoundingBoxRect());
1413 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling())
1414 current->addAbsoluteRectForLayer(result);
1417 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1419 LayoutRect result = absoluteBoundingBoxRect();
1420 topLevelRect = result;
1421 for (RenderObject* current = slowFirstChild(); current; current = current->nextSibling())
1422 current->addAbsoluteRectForLayer(result);
1426 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1430 const RenderLayerModelObject* RenderObject::containerForPaintInvalidation() const
1435 return adjustCompositedContainerForSpecialAncestors(enclosingCompositedContainer());
1438 const RenderLayerModelObject* RenderObject::enclosingCompositedContainer() const
1440 RenderLayerModelObject* container = 0;
1441 if (view()->usesCompositing()) {
1442 // FIXME: CompositingState is not necessarily up to date for many callers of this function.
1443 DisableCompositingQueryAsserts disabler;
1445 if (RenderLayer* compositingLayer = enclosingLayer()->enclosingCompositingLayerForRepaint())
1446 container = compositingLayer->renderer();
1451 const RenderLayerModelObject* RenderObject::adjustCompositedContainerForSpecialAncestors(const RenderLayerModelObject* paintInvalidationContainer) const
1454 if (document().view()->hasSoftwareFilters()) {
1455 if (RenderLayer* enclosingFilterLayer = enclosingLayer()->enclosingFilterLayer())
1456 return enclosingFilterLayer->renderer();
1459 // If we have a flow thread, then we need to do individual paint invalidations within the RenderRegions instead.
1460 // Return the flow thread as a paint invalidation container in order to create a chokepoint that allows us to change
1461 // paint invalidation to do individual region paint invalidations.
1462 if (RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock()) {
1463 // 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
1464 // flow thread. Otherwise we will need to catch the paint invalidation call and send it to the flow thread.
1465 if (!paintInvalidationContainer || paintInvalidationContainer->flowThreadContainingBlock() != parentRenderFlowThread)
1466 paintInvalidationContainer = parentRenderFlowThread;
1468 return paintInvalidationContainer ? paintInvalidationContainer : view();
1471 bool RenderObject::isPaintInvalidationContainer() const
1473 return hasLayer() && toRenderLayerModelObject(this)->layer()->isRepaintContainer();
1476 template<typename T> PassRefPtr<JSONValue> jsonObjectForRect(const T& rect)
1478 RefPtr<JSONObject> object = JSONObject::create();
1479 object->setNumber("x", rect.x());
1480 object->setNumber("y", rect.y());
1481 object->setNumber("width", rect.width());
1482 object->setNumber("height", rect.height());
1483 return object.release();
1486 static PassRefPtr<JSONValue> jsonObjectForPaintInvalidationInfo(const IntRect& rect, const String& invalidationReason)
1488 RefPtr<JSONObject> object = JSONObject::create();
1489 object->setValue("rect", jsonObjectForRect(rect));
1490 object->setString("invalidation_reason", invalidationReason);
1491 return object.release();
1494 LayoutRect RenderObject::computePaintInvalidationRect(const RenderLayerModelObject* paintInvalidationContainer) const
1496 return clippedOverflowRectForPaintInvalidation(paintInvalidationContainer);
1499 void RenderObject::invalidatePaintUsingContainer(const RenderLayerModelObject* paintInvalidationContainer, const IntRect& r, InvalidationReason invalidationReason) const
1504 // FIXME: This should be an assert, but editing/selection can trigger this case to invalidate
1505 // the selection. crbug.com/368140.
1509 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "RenderObject::invalidatePaintUsingContainer()",
1510 "object", this->debugName().ascii(),
1511 "info", TracedValue::fromJSONValue(jsonObjectForPaintInvalidationInfo(r, invalidationReasonToString(invalidationReason))));
1513 // For querying RenderLayer::compositingState()
1514 DisableCompositingQueryAsserts disabler;
1516 if (paintInvalidationContainer->isRenderFlowThread()) {
1517 toRenderFlowThread(paintInvalidationContainer)->repaintRectangleInRegions(r);
1521 if (paintInvalidationContainer->hasFilter() && paintInvalidationContainer->layer()->requiresFullLayerImageForFilters()) {
1522 paintInvalidationContainer->layer()->repainter().setFilterBackendNeedsRepaintingInRect(r);
1526 RenderView* v = view();
1527 if (paintInvalidationContainer->isRenderView()) {
1528 ASSERT(paintInvalidationContainer == v);
1529 v->repaintViewRectangle(r);
1533 if (v->usesCompositing()) {
1534 ASSERT(paintInvalidationContainer->hasLayer() && (paintInvalidationContainer->layer()->compositingState() == PaintsIntoOwnBacking || paintInvalidationContainer->layer()->compositingState() == PaintsIntoGroupedBacking));
1535 paintInvalidationContainer->layer()->repainter().setBackingNeedsRepaintInRect(r);
1539 void RenderObject::paintInvalidationForWholeRenderer() const
1544 if (view()->document().printing())
1545 return; // Don't invalidate paints if we're printing.
1547 // FIXME: really, we're in the paint invalidation phase here, and the following queries are legal.
1548 // Until those states are fully fledged, I'll just disable the ASSERTS.
1549 DisableCompositingQueryAsserts disabler;
1550 const RenderLayerModelObject* paintInvalidationContainer = containerForPaintInvalidation();
1551 LayoutRect paintInvalidationRect = boundsRectForPaintInvalidation(paintInvalidationContainer);
1552 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(paintInvalidationRect), InvalidationPaint);
1555 LayoutRect RenderObject::boundsRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const
1557 if (!paintInvalidationContainer)
1558 return computePaintInvalidationRect(paintInvalidationContainer);
1559 return RenderLayer::computeRepaintRect(this, paintInvalidationContainer->layer());
1562 void RenderObject::invalidatePaintRectangle(const LayoutRect& r) const
1567 if (view()->document().printing())
1568 return; // Don't invalidate paints if we're printing.
1570 LayoutRect dirtyRect(r);
1572 if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
1573 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1574 // paint invalidation containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1575 dirtyRect.move(view()->layoutDelta());
1578 const RenderLayerModelObject* paintInvalidationContainer = containerForPaintInvalidation();
1579 RenderLayer::mapRectToRepaintBacking(this, paintInvalidationContainer, dirtyRect);
1580 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(dirtyRect), InvalidationPaintRectangle);
1583 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1585 return pixelSnappedIntRect(absoluteClippedOverflowRect());
1588 const char* RenderObject::invalidationReasonToString(InvalidationReason reason) const
1591 case InvalidationIncremental:
1592 return "incremental";
1593 case InvalidationSelfLayout:
1594 return "self layout";
1595 case InvalidationBorderFitLines:
1596 return "border fit lines";
1597 case InvalidationBorderRadius:
1598 return "border radius";
1599 case InvalidationBoundsChangeWithBackground:
1600 return "bounds change with background";
1601 case InvalidationBoundsChange:
1602 return "bounds change";
1603 case InvalidationLocationChange:
1604 return "location change";
1605 case InvalidationScroll:
1607 case InvalidationSelection:
1609 case InvalidationLayer:
1611 case InvalidationPaint:
1612 return "invalidate paint";
1613 case InvalidationPaintRectangle:
1614 return "invalidate paint rectangle";
1616 ASSERT_NOT_REACHED();
1620 void RenderObject::invalidateTreeAfterLayout(const RenderLayerModelObject& paintInvalidationContainer)
1622 // If we didn't need paint invalidation then our children don't need as well.
1623 // Skip walking down the tree as everything should be fine below us.
1624 if (!shouldCheckForPaintInvalidationAfterLayout())
1627 clearPaintInvalidationState();
1629 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1630 if (!child->isOutOfFlowPositioned())
1631 child->invalidateTreeAfterLayout(paintInvalidationContainer);
1635 static PassRefPtr<JSONValue> jsonObjectForOldAndNewRects(const LayoutRect& oldRect, const LayoutRect& newRect)
1637 RefPtr<JSONObject> object = JSONObject::create();
1639 object->setValue("old", jsonObjectForRect(oldRect));
1640 object->setValue("new", jsonObjectForRect(newRect));
1641 return object.release();
1644 bool RenderObject::invalidatePaintAfterLayoutIfNeeded(const RenderLayerModelObject* paintInvalidationContainer, bool wasSelfLayout,
1645 const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect* newBoundsPtr, const LayoutPoint* newLocationPtr)
1647 RenderView* v = view();
1648 if (v->document().printing())
1649 return false; // Don't invalidate paints if we're printing.
1651 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1652 // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForPaintInvalidation(paintInvalidationContainer));
1653 LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : computePaintInvalidationRect();
1654 LayoutPoint newLocation = newLocationPtr ? (*newLocationPtr) : RenderLayer::positionFromPaintInvalidationContainer(this, paintInvalidationContainer);
1656 // FIXME: This should use a ConvertableToTraceFormat when they are available in Blink.
1657 TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "RenderObject::invalidatePaintAfterLayoutIfNeeded()",
1658 "object", this->debugName().ascii(),
1659 "info", TracedValue::fromJSONValue(jsonObjectForOldAndNewRects(oldBounds, newBounds)));
1661 InvalidationReason invalidationReason = wasSelfLayout ? InvalidationSelfLayout : InvalidationIncremental;
1663 // Presumably a background or a border exists if border-fit:lines was specified.
1664 if (invalidationReason == InvalidationIncremental && style()->borderFit() == BorderFitLines)
1665 invalidationReason = InvalidationBorderFitLines;
1667 if (invalidationReason == InvalidationIncremental && style()->hasBorderRadius()) {
1668 // If a border-radius exists and width/height is smaller than
1669 // radius width/height, we cannot use delta-paint-invalidation.
1670 RoundedRect oldRoundedRect = style()->getRoundedBorderFor(oldBounds);
1671 RoundedRect newRoundedRect = style()->getRoundedBorderFor(newBounds);
1672 if (oldRoundedRect.radii() != newRoundedRect.radii())
1673 invalidationReason = InvalidationBorderRadius;
1676 if (invalidationReason == InvalidationIncremental && compositingState() != PaintsIntoOwnBacking && newLocation != oldLocation)
1677 invalidationReason = InvalidationLocationChange;
1679 // If the bounds are the same then we know that none of the statements below
1680 // can match, so we can early out since we will not need to do any
1682 if (invalidationReason == InvalidationIncremental && oldBounds == newBounds)
1685 if (invalidationReason == InvalidationIncremental) {
1686 if (oldBounds.width() != newBounds.width() && mustInvalidateBackgroundOrBorderPaintOnWidthChange())
1687 invalidationReason = InvalidationBoundsChangeWithBackground;
1688 else if (oldBounds.height() != newBounds.height() && mustInvalidateBackgroundOrBorderPaintOnHeightChange())
1689 invalidationReason = InvalidationBoundsChangeWithBackground;
1692 // If we shifted, we don't know the exact reason so we are conservative and trigger a full invalidation. Shifting could
1693 // be caused by some layout property (left / top) or some in-flow renderer inserted / removed before us in the tree.
1694 if (invalidationReason == InvalidationIncremental && newBounds.location() != oldBounds.location())
1695 invalidationReason = InvalidationBoundsChange;
1697 // If the size is zero on one of our bounds then we know we're going to have
1698 // to do a full invalidation of either old bounds or new bounds. If we fall
1699 // into the incremental invalidation we'll issue two invalidations instead
1701 if (invalidationReason == InvalidationIncremental && (oldBounds.size().isZero() || newBounds.size().isZero()))
1702 invalidationReason = InvalidationBoundsChange;
1704 ASSERT(paintInvalidationContainer);
1706 if (invalidationReason != InvalidationIncremental) {
1707 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(oldBounds), invalidationReason);
1708 if (newBounds != oldBounds)
1709 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(newBounds), invalidationReason);
1713 LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1715 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()), invalidationReason);
1716 else if (deltaLeft < 0)
1717 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()), invalidationReason);
1719 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1721 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()), invalidationReason);
1722 else if (deltaRight < 0)
1723 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()), invalidationReason);
1725 LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1727 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop), invalidationReason);
1728 else if (deltaTop < 0)
1729 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop), invalidationReason);
1731 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1732 if (deltaBottom > 0)
1733 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom), invalidationReason);
1734 else if (deltaBottom < 0)
1735 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom), invalidationReason);
1737 // FIXME: This is a limitation of our visual overflow being a single rectangle.
1738 if (!style()->boxShadow() && !style()->hasBorderImageOutsets() && !style()->hasOutline())
1741 // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1742 // two rectangles (but typically only one).
1743 RenderStyle* outlineStyle = outlineStyleForPaintInvalidation();
1744 LayoutUnit outlineWidth = outlineStyle->outlineSize();
1745 LayoutBoxExtent insetShadowExtent = style()->getBoxShadowInsetExtent();
1746 LayoutUnit width = absoluteValue(newBounds.width() - oldBounds.width());
1748 LayoutUnit shadowLeft;
1749 LayoutUnit shadowRight;
1750 style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1751 int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1752 LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : LayoutUnit();
1753 LayoutUnit minInsetRightShadowExtent = min<LayoutUnit>(-insetShadowExtent.right(), min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1754 LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth), valueForLength(style()->borderBottomRightRadius().width(), boxWidth)));
1755 LayoutUnit decorationsLeftWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowLeft);
1756 LayoutUnit decorationsRightWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
1757 LayoutRect rightRect(newBounds.x() + min(newBounds.width(), oldBounds.width()) - decorationsLeftWidth,
1759 width + decorationsLeftWidth + decorationsRightWidth,
1760 max(newBounds.height(), oldBounds.height()));
1761 LayoutUnit right = min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1762 if (rightRect.x() < right) {
1763 rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1764 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(rightRect), invalidationReason);
1767 LayoutUnit height = absoluteValue(newBounds.height() - oldBounds.height());
1769 LayoutUnit shadowTop;
1770 LayoutUnit shadowBottom;
1771 style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1772 int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1773 LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : LayoutUnit();
1774 LayoutUnit minInsetBottomShadowExtent = min<LayoutUnit>(-insetShadowExtent.bottom(), min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1775 LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight), valueForLength(style()->borderBottomRightRadius().height(), boxHeight)));
1776 LayoutUnit decorationsTopHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowTop);
1777 LayoutUnit decorationsBottomHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
1778 LayoutRect bottomRect(newBounds.x(),
1779 min(newBounds.maxY(), oldBounds.maxY()) - decorationsTopHeight,
1780 max(newBounds.width(), oldBounds.width()),
1781 height + decorationsTopHeight + decorationsBottomHeight);
1782 LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
1783 if (bottomRect.y() < bottom) {
1784 bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1785 invalidatePaintUsingContainer(paintInvalidationContainer, pixelSnappedIntRect(bottomRect), invalidationReason);
1791 void RenderObject::invalidatePaintForOverflow()
1795 void RenderObject::invalidatePaintForOverflowIfNeeded()
1797 if (shouldInvalidateOverflowForPaint())
1798 invalidatePaintForOverflow();
1801 bool RenderObject::checkForPaintInvalidation() const
1803 return !document().view()->needsFullPaintInvalidation() && everHadLayout();
1806 bool RenderObject::checkForPaintInvalidationDuringLayout() const
1808 return !RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && checkForPaintInvalidation();
1811 LayoutRect RenderObject::rectWithOutlineForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, LayoutUnit outlineWidth) const
1813 LayoutRect r(clippedOverflowRectForPaintInvalidation(paintInvalidationContainer));
1814 r.inflate(outlineWidth);
1818 LayoutRect RenderObject::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject*) const
1820 ASSERT_NOT_REACHED();
1821 return LayoutRect();
1824 void RenderObject::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, bool fixed) const
1826 if (paintInvalidationContainer == this)
1829 if (RenderObject* o = parent()) {
1830 if (o->isRenderBlockFlow()) {
1831 RenderBlock* cb = toRenderBlock(o);
1832 if (cb->hasColumns())
1833 cb->adjustRectForColumns(rect);
1836 if (o->hasOverflowClip()) {
1837 RenderBox* boxParent = toRenderBox(o);
1838 boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1843 o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, fixed);
1847 void RenderObject::computeFloatRectForPaintInvalidation(const RenderLayerModelObject*, FloatRect&, bool) const
1849 ASSERT_NOT_REACHED();
1852 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1858 void RenderObject::showTreeForThis() const
1861 node()->showTreeForThis();
1864 void RenderObject::showRenderTreeForThis() const
1866 showRenderTree(this, 0);
1869 void RenderObject::showLineTreeForThis() const
1871 if (containingBlock())
1872 containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1875 void RenderObject::showRenderObject() const
1877 showRenderObject(0);
1880 void RenderObject::showRenderObject(int printedCharacters) const
1882 // As this function is intended to be used when debugging, the
1883 // this pointer may be 0.
1885 fputs("(null)\n", stderr);
1889 printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1892 if (printedCharacters)
1893 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1895 fputc('\t', stderr);
1898 fputc('\n', stderr);
1901 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1903 int printedCharacters = 0;
1904 if (markedObject1 == this && markedLabel1)
1905 printedCharacters += fprintf(stderr, "%s", markedLabel1);
1906 if (markedObject2 == this && markedLabel2)
1907 printedCharacters += fprintf(stderr, "%s", markedLabel2);
1908 for (; printedCharacters < depth * 2; printedCharacters++)
1911 showRenderObject(printedCharacters);
1915 for (const RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
1916 child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1921 bool RenderObject::isSelectable() const
1923 return !isInert() && !(style()->userSelect() == SELECT_NONE && style()->userModify() == READ_ONLY);
1926 Color RenderObject::selectionBackgroundColor() const
1928 if (!isSelectable())
1929 return Color::transparent;
1931 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1932 return resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
1933 return frame()->selection().isFocusedAndActive() ?
1934 RenderTheme::theme().activeSelectionBackgroundColor() :
1935 RenderTheme::theme().inactiveSelectionBackgroundColor();
1938 Color RenderObject::selectionColor(int colorProperty) const
1940 // If the element is unselectable, or we are only painting the selection,
1941 // don't override the foreground color with the selection foreground color.
1942 if (!isSelectable() || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1943 return resolveColor(colorProperty);
1945 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyleFromParentOrShadowHost())
1946 return resolveColor(pseudoStyle.get(), colorProperty);
1947 if (!RenderTheme::theme().supportsSelectionForegroundColors())
1948 return resolveColor(colorProperty);
1949 return frame()->selection().isFocusedAndActive() ?
1950 RenderTheme::theme().activeSelectionForegroundColor() :
1951 RenderTheme::theme().inactiveSelectionForegroundColor();
1954 Color RenderObject::selectionForegroundColor() const
1956 return selectionColor(CSSPropertyWebkitTextFillColor);
1959 Color RenderObject::selectionEmphasisMarkColor() const
1961 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1964 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1966 view()->selectionStartEnd(spos, epos);
1969 void RenderObject::handleDynamicFloatPositionChange()
1971 // We have gone from not affecting the inline status of the parent flow to suddenly
1972 // having an impact. See if there is a mismatch between the parent flow's
1973 // childrenInline() state and our state.
1974 setInline(style()->isDisplayInlineType());
1975 if (isInline() != parent()->childrenInline()) {
1977 toRenderBoxModelObject(parent())->childBecameNonInline(this);
1979 // An anonymous block must be made to wrap this inline.
1980 RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1981 RenderObjectChildList* childlist = parent()->virtualChildren();
1982 childlist->insertChildNode(parent(), block, this);
1983 block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1988 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1990 if (contextSensitiveProperties & ContextSensitivePropertyTransform && isSVG())
1991 diff.setNeedsFullLayout();
1993 // If transform changed, and the layer does not paint into its own separate backing, then we need to invalidate paints.
1994 if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1995 // Text nodes share style with their parents but transforms don't apply to them,
1996 // hence the !isText() check.
1997 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->styleDeterminedCompositingReasons()))
1998 diff.setNeedsRepaintLayer();
2000 diff.setNeedsRecompositeLayer();
2003 // If opacity or zIndex changed, and the layer does not paint into its own separate backing, then we need to invalidate paints (also
2004 // ignoring text nodes)
2005 if (contextSensitiveProperties & (ContextSensitivePropertyOpacity | ContextSensitivePropertyZIndex)) {
2006 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->styleDeterminedCompositingReasons()))
2007 diff.setNeedsRepaintLayer();
2009 diff.setNeedsRecompositeLayer();
2012 // 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.
2013 if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
2014 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
2015 if (!layer->styleDeterminedCompositingReasons() || layer->paintsWithFilters())
2016 diff.setNeedsRepaintLayer();
2018 diff.setNeedsRecompositeLayer();
2021 if ((contextSensitiveProperties & ContextSensitivePropertyTextOrColor) && !diff.needsRepaint()
2022 && hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor())
2023 diff.setNeedsRepaintObject();
2025 // The answer to layerTypeRequired() for plugins, iframes, and canvas can change without the actual
2026 // style changing, since it depends on whether we decide to composite these elements. When the
2027 // layer status of one of these elements changes, we need to force a layout.
2028 if (!diff.needsFullLayout() && style() && isLayerModelObject()) {
2029 bool requiresLayer = toRenderLayerModelObject(this)->layerTypeRequired() != NoLayer;
2030 if (hasLayer() != requiresLayer)
2031 diff.setNeedsFullLayout();
2034 // If we have no layer(), just treat a RepaintLayer hint as a normal paint invalidation.
2035 if (diff.needsRepaintLayer() && !hasLayer()) {
2036 diff.clearNeedsRepaint();
2037 diff.setNeedsRepaintObject();
2043 void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
2045 ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER);
2047 // FIXME: We should consider just making all pseudo items use an inherited style.
2049 // Images are special and must inherit the pseudoStyle so the width and height of
2050 // the pseudo element doesn't change the size of the image. In all other cases we
2051 // can just share the style.
2053 // Quotes are also RenderInline, so we need to create an inherited style to avoid
2054 // getting an inline with positioning or an invalid display.
2056 if (isImage() || isQuote()) {
2057 RefPtr<RenderStyle> style = RenderStyle::create();
2058 style->inheritFrom(pseudoStyle.get());
2059 setStyle(style.release());
2063 setStyle(pseudoStyle);
2066 inline bool RenderObject::hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const
2068 if (style()->hasBorder() || style()->hasOutline())
2070 for (const RenderObject* r = slowFirstChild(); r; r = r->nextSibling()) {
2071 if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
2073 if (r->style()->hasOutline() || r->style()->hasBorder())
2079 void RenderObject::markContainingBlocksForOverflowRecalc()
2081 for (RenderBlock* container = containingBlock(); container && !container->childNeedsOverflowRecalcAfterStyleChange(); container = container->containingBlock())
2082 container->setChildNeedsOverflowRecalcAfterStyleChange(true);
2085 void RenderObject::setNeedsOverflowRecalcAfterStyleChange()
2087 bool neededRecalc = needsOverflowRecalcAfterStyleChange();
2088 setSelfNeedsOverflowRecalcAfterStyleChange(true);
2090 markContainingBlocksForOverflowRecalc();
2093 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
2097 if (m_style == style) {
2098 // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
2099 // style sharing is disabled for them. That should ensure that we never hit this code path.
2100 ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
2104 StyleDifference diff;
2105 unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
2107 diff = m_style->visualInvalidationDiff(*style, contextSensitiveProperties);
2109 diff = adjustStyleDifference(diff, contextSensitiveProperties);
2111 styleWillChange(diff, *style);
2113 RefPtr<RenderStyle> oldStyle = m_style.release();
2114 setStyleInternal(style);
2116 updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
2117 updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
2119 updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
2120 updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
2122 updateShapeImage(oldStyle ? oldStyle->shapeOutside() : 0, m_style ? m_style->shapeOutside() : 0);
2124 bool doesNotNeedLayout = !m_parent || isText();
2126 styleDidChange(diff, oldStyle.get());
2128 // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
2129 // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
2130 // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
2131 // in the future as we move renderer changes out of layout and into style changes.
2132 if (doesNotNeedLayout)
2135 // Now that the layer (if any) has been updated, we need to adjust the diff again,
2136 // check whether we should layout now, and decide if we need to invalidate paints.
2137 StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
2139 if (!diff.needsFullLayout()) {
2140 if (updatedDiff.needsFullLayout())
2141 setNeedsLayoutAndPrefWidthsRecalc();
2142 else if (updatedDiff.needsPositionedMovementLayout())
2143 setNeedsPositionedMovementLayout();
2146 if (contextSensitiveProperties & ContextSensitivePropertyTransform && !needsLayout()) {
2147 if (RenderBlock* container = containingBlock())
2148 container->setNeedsOverflowRecalcAfterStyleChange();
2151 if (updatedDiff.needsRepaint()) {
2152 // Invalidate paints with the new style, e.g., for example if we go from not having
2153 // an outline to having an outline.
2154 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && needsLayout())
2155 setShouldDoFullPaintInvalidationAfterLayout(true);
2156 else if (!selfNeedsLayout())
2157 paintInvalidationForWholeRenderer();
2161 static inline bool rendererHasBackground(const RenderObject* renderer)
2163 return renderer && renderer->hasBackground();
2166 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
2169 // If our z-index changes value or our visibility changes,
2170 // we need to dirty our stacking context's z-order list.
2171 bool visibilityChanged = m_style->visibility() != newStyle.visibility()
2172 || m_style->zIndex() != newStyle.zIndex()
2173 || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
2174 if (visibilityChanged) {
2175 document().setAnnotatedRegionsDirty(true);
2176 if (AXObjectCache* cache = document().existingAXObjectCache())
2177 cache->childrenChanged(parent());
2180 // Keep layer hierarchy visibility bits up to date if visibility changes.
2181 if (m_style->visibility() != newStyle.visibility()) {
2182 // We might not have an enclosing layer yet because we might not be in the tree.
2183 if (RenderLayer* layer = enclosingLayer()) {
2184 if (newStyle.visibility() == VISIBLE) {
2185 layer->setHasVisibleContent();
2186 } else if (layer->hasVisibleContent() && (this == layer->renderer() || layer->renderer()->style()->visibility() != VISIBLE)) {
2187 layer->dirtyVisibleContentStatus();
2188 if (diff.needsLayout())
2189 paintInvalidationForWholeRenderer();
2194 if (m_parent && diff.needsRepaintObject()) {
2195 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && (diff.needsLayout() || needsLayout()))
2196 setShouldDoFullPaintInvalidationAfterLayout(true);
2197 else if (!diff.needsFullLayout() && !selfNeedsLayout())
2198 paintInvalidationForWholeRenderer();
2201 if (isFloating() && (m_style->floating() != newStyle.floating()))
2202 // For changes in float styles, we need to conceivably remove ourselves
2203 // from the floating objects list.
2204 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2205 else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
2206 // For changes in positioning styles, we need to conceivably remove ourselves
2207 // from the positioned objects list.
2208 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
2210 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
2211 && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
2212 && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
2214 // Clearing these bits is required to avoid leaving stale renderers.
2215 // FIXME: We shouldn't need that hack if our logic was totally correct.
2216 if (diff.needsLayout()) {
2218 clearPositionedState();
2221 s_affectsParentBlock = false;
2224 if (view()->frameView()) {
2225 bool shouldBlitOnFixedBackgroundImage = false;
2226 if (RuntimeEnabledFeatures::fastMobileScrollingEnabled()) {
2227 // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
2228 // when scrolling a page with a fixed background image. As an optimization, assuming there are
2229 // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
2230 // ignore the CSS property "background-attachment: fixed".
2231 shouldBlitOnFixedBackgroundImage = true;
2233 bool newStyleSlowScroll = !shouldBlitOnFixedBackgroundImage && newStyle.hasFixedBackgroundImage();
2234 bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
2236 bool drawsRootBackground = isDocumentElement() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
2237 if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
2238 if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
2239 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
2240 newStyleSlowScroll = false;
2242 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
2243 oldStyleSlowScroll = false;
2247 if (oldStyleSlowScroll != newStyleSlowScroll) {
2248 if (oldStyleSlowScroll)
2249 view()->frameView()->removeSlowRepaintObject();
2250 if (newStyleSlowScroll)
2251 view()->frameView()->addSlowRepaintObject();
2255 // Elements with non-auto touch-action will send a SetTouchAction message
2256 // on touchstart in EventHandler::handleTouchEvent, and so effectively have
2257 // a touchstart handler that must be reported.
2259 // Since a CSS property cannot be applied directly to a text node, a
2260 // handler will have already been added for its parent so ignore it.
2261 TouchAction oldTouchAction = m_style ? m_style->touchAction() : TouchActionAuto;
2262 if (node() && !node()->isTextNode() && (oldTouchAction == TouchActionAuto) != (newStyle.touchAction() == TouchActionAuto)) {
2263 if (newStyle.touchAction() != TouchActionAuto)
2264 document().didAddTouchEventHandler(node());
2266 document().didRemoveTouchEventHandler(node());
2270 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
2272 ASSERT(a->cursors() != b->cursors());
2273 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
2276 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
2278 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
2281 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
2283 if (s_affectsParentBlock)
2284 handleDynamicFloatPositionChange();
2289 if (diff.needsFullLayout()) {
2290 RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.get());
2292 // If the object already needs layout, then setNeedsLayout won't do
2293 // any work. But if the containing block has changed, then we may need
2294 // to mark the new containing blocks for layout. The change that can
2295 // directly affect the containing block of this object is a change to
2296 // the position style.
2297 if (needsLayout() && oldStyle->position() != m_style->position())
2298 markContainingBlocksForLayout();
2301 if (needsOverflowRecalcAfterStyleChange() && oldStyle->position() != m_style->position())
2302 markContainingBlocksForOverflowRecalc();
2304 if (diff.needsFullLayout())
2305 setNeedsLayoutAndPrefWidthsRecalc();
2306 } else if (diff.needsPositionedMovementLayout())
2307 setNeedsPositionedMovementLayout();
2309 // Don't check for paint invalidation here; we need to wait until the layer has been
2310 // updated by subclasses before we know if we have to invalidate paints (in setStyle()).
2312 if (oldStyle && !areCursorsEqual(oldStyle, style())) {
2313 if (LocalFrame* frame = this->frame())
2314 frame->eventHandler().scheduleCursorUpdate();
2318 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
2320 // FIXME: We could save this call when the change only affected non-inherited properties.
2321 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
2322 if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
2325 if (blockChildrenOnly && !child->isRenderBlock())
2328 if (child->isRenderFullScreen() || child->isRenderFullScreenPlaceholder())
2331 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), child->style()->display());
2332 if (style()->specifiesColumns()) {
2333 if (child->style()->specifiesColumns())
2334 newStyle->inheritColumnPropertiesFrom(style());
2335 if (child->style()->columnSpan())
2336 newStyle->setColumnSpan(ColumnSpanAll);
2339 // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
2340 // they contain block descendants of relative or sticky positioned inlines.
2341 if (child->isInFlowPositioned() && toRenderBlock(child)->isAnonymousBlockContinuation())
2342 newStyle->setPosition(child->style()->position());
2344 child->setStyle(newStyle.release());
2348 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
2350 // Optimize the common case
2351 if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
2354 // Go through the new layers and addClients first, to avoid removing all clients of an image.
2355 for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
2356 if (currNew->image())
2357 currNew->image()->addClient(this);
2360 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2361 if (currOld->image())
2362 currOld->image()->removeClient(this);
2366 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2368 if (oldImage != newImage) {
2370 oldImage->removeClient(this);
2372 newImage->addClient(this);
2376 void RenderObject::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
2378 if (oldShapeValue || newShapeValue)
2379 updateImage(oldShapeValue ? oldShapeValue->image() : 0, newShapeValue ? newShapeValue->image() : 0);
2382 LayoutRect RenderObject::viewRect() const
2384 return view()->viewRect();
2387 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2389 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2390 mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2391 transformState.flatten();
2393 return transformState.lastPlanarPoint();
2396 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2398 TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2399 mapAbsoluteToLocalPoint(mode, transformState);
2400 transformState.flatten();
2402 return transformState.lastPlanarPoint();
2405 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2407 TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2408 mapAbsoluteToLocalPoint(mode, transformState);
2409 transformState.flatten();
2410 return transformState.lastPlanarQuad();
2413 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
2415 if (paintInvalidationContainer == this)
2418 RenderObject* o = parent();
2422 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2423 LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2424 if (mode & ApplyContainerFlip && o->isBox()) {
2425 if (o->style()->isFlippedBlocksWritingMode())
2426 transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2427 mode &= ~ApplyContainerFlip;
2430 transformState.move(o->columnOffset(roundedLayoutPoint(transformState.mappedPoint())));
2432 if (o->hasOverflowClip())
2433 transformState.move(-toRenderBox(o)->scrolledContentOffset());
2435 o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed);
2438 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2440 ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
2442 RenderObject* container = parent();
2446 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2448 if (container->hasOverflowClip())
2449 offset = -toRenderBox(container)->scrolledContentOffset();
2451 geometryMap.push(this, offset, hasColumns());
2456 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2458 RenderObject* o = parent();
2460 o->mapAbsoluteToLocalPoint(mode, transformState);
2461 if (o->hasOverflowClip())
2462 transformState.move(toRenderBox(o)->scrolledContentOffset());
2466 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
2468 // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2469 // so check the layer's transform directly.
2470 return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2473 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2475 transform.makeIdentity();
2476 transform.translate(offsetInContainer.width().toFloat(), offsetInContainer.height().toFloat());
2478 if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
2479 transform.multiply(layer->currentTransform());
2481 if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2482 // Perpsective on the container affects us, so we have to factor it in here.
2483 ASSERT(containerObject->hasLayer());
2484 FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
2486 TransformationMatrix perspectiveMatrix;
2487 perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2489 transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2490 transform = perspectiveMatrix * transform;
2491 transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2495 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2497 // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2498 // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2499 TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2500 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2501 transformState.flatten();
2503 return transformState.lastPlanarQuad();
2506 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* paintInvalidationContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2508 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2509 mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2510 transformState.flatten();
2512 return transformState.lastPlanarPoint();
2515 LayoutSize RenderObject::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2517 ASSERT(o == container());
2519 LayoutSize offset = o->columnOffset(point);
2521 if (o->hasOverflowClip())
2522 offset -= toRenderBox(o)->scrolledContentOffset();
2524 if (offsetDependsOnPoint)
2525 *offsetDependsOnPoint = hasColumns() || o->isRenderFlowThread();
2530 LayoutSize RenderObject::offsetFromAncestorContainer(const RenderObject* container) const
2533 LayoutPoint referencePoint;
2534 const RenderObject* currContainer = this;
2536 const RenderObject* nextContainer = currContainer->container();
2537 ASSERT(nextContainer); // This means we reached the top without finding container.
2540 ASSERT(!currContainer->hasTransform());
2541 LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2542 offset += currentOffset;
2543 referencePoint.move(currentOffset);
2544 currContainer = nextContainer;
2545 } while (currContainer != container);
2550 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2552 if (extraWidthToEndOfLine)
2553 *extraWidthToEndOfLine = 0;
2555 return LayoutRect();
2558 void RenderObject::computeLayerHitTestRects(LayerHitTestRects& layerRects) const
2560 // Figure out what layer our container is in. Any offset (or new layer) for this
2561 // renderer within it's container will be applied in addLayerHitTestRects.
2562 LayoutPoint layerOffset;
2563 const RenderLayer* currentLayer = 0;
2566 RenderObject* container = this->container();
2567 currentLayer = container->enclosingLayer();
2568 if (container && currentLayer->renderer() != container) {
2569 layerOffset.move(container->offsetFromAncestorContainer(currentLayer->renderer()));
2570 // If the layer itself is scrolled, we have to undo the subtraction of its scroll
2571 // offset since we want the offset relative to the scrolling content, not the
2573 if (currentLayer->renderer()->hasOverflowClip())
2574 layerOffset.move(currentLayer->renderBox()->scrolledContentOffset());
2578 this->addLayerHitTestRects(layerRects, currentLayer, layerOffset, LayoutRect());
2581 void RenderObject::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
2583 ASSERT(currentLayer);
2584 ASSERT(currentLayer == this->enclosingLayer());
2586 // Compute the rects for this renderer only and add them to the results.
2587 // Note that we could avoid passing the offset and instead adjust each result, but this
2588 // seems slightly simpler.
2589 Vector<LayoutRect> ownRects;
2590 LayoutRect newContainerRect;
2591 computeSelfHitTestRects(ownRects, layerOffset);
2593 // When we get to have a lot of rects on a layer, the performance cost of tracking those
2594 // rects outweighs the benefit of doing compositor thread hit testing.
2595 // FIXME: This limit needs to be low due to the O(n^2) algorithm in
2596 // WebLayer::setTouchEventHandlerRegion - crbug.com/300282.
2597 const size_t maxRectsPerLayer = 100;
2599 LayerHitTestRects::iterator iter = layerRects.find(currentLayer);
2600 Vector<WebCore::LayoutRect>* iterValue;
2601 if (iter == layerRects.end())
2602 iterValue = &layerRects.add(currentLayer, Vector<LayoutRect>()).storedValue->value;
2604 iterValue = &iter->value;
2605 for (size_t i = 0; i < ownRects.size(); i++) {
2606 if (!containerRect.contains(ownRects[i])) {
2607 iterValue->append(ownRects[i]);
2608 if (iterValue->size() > maxRectsPerLayer) {
2609 // Just mark the entire layer instead, and switch to walking the layer
2610 // tree instead of the render tree.
2611 layerRects.remove(currentLayer);
2612 currentLayer->addLayerHitTestRects(layerRects);
2615 if (newContainerRect.isEmpty())
2616 newContainerRect = ownRects[i];
2619 if (newContainerRect.isEmpty())
2620 newContainerRect = containerRect;
2622 // If it's possible for children to have rects outside our bounds, then we need to descend into
2623 // the children and compute them.
2624 // Ideally there would be other cases where we could detect that children couldn't have rects
2625 // outside our bounds and prune the tree walk.
2626 // Note that we don't use Region here because Union is O(N) - better to just keep a list of
2627 // partially redundant rectangles. If we find examples where this is expensive, then we could
2628 // rewrite Region to be more efficient. See https://bugs.webkit.org/show_bug.cgi?id=100814.
2629 if (!isRenderView()) {
2630 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling()) {
2631 curr->addLayerHitTestRects(layerRects, currentLayer, layerOffset, newContainerRect);
2636 bool RenderObject::isRooted() const
2638 const RenderObject* object = this;
2639 while (object->parent() && !object->hasLayer())
2640 object = object->parent();
2641 if (object->hasLayer())
2642 return toRenderLayerModelObject(object)->layer()->root()->isRootLayer();
2646 RenderObject* RenderObject::rendererForRootBackground()
2648 ASSERT(isDocumentElement());
2649 if (!hasBackground() && isHTMLHtmlElement(node())) {
2650 // Locate the <body> element using the DOM. This is easier than trying
2651 // to crawl around a render tree with potential :before/:after content and
2652 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
2653 // render object very easily via the DOM.
2654 HTMLElement* body = document().body();
2655 RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
2663 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
2665 // Respect the image's orientation if it's being used as a full-page image or it's
2666 // an <img> and the setting to respect it everywhere is set.
2667 return document().isImageDocument()
2668 || (document().settings() && document().settings()->shouldRespectImageOrientation() && isHTMLImageElement(node())) ? RespectImageOrientation : DoNotRespectImageOrientation;
2671 bool RenderObject::hasOutlineAnnotation() const
2673 return node() && node()->isLink() && document().printing();
2676 bool RenderObject::hasEntirelyFixedBackground() const
2678 return m_style->hasEntirelyFixedBackground();
2681 RenderObject* RenderObject::container(const RenderLayerModelObject* paintInvalidationContainer, bool* paintInvalidationContainerSkipped) const
2683 if (paintInvalidationContainerSkipped)
2684 *paintInvalidationContainerSkipped = false;
2686 // This method is extremely similar to containingBlock(), but with a few notable
2688 // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2689 // the object is not part of the primary document subtree yet.
2690 // (2) For normal flow elements, it just returns the parent.
2691 // (3) For absolute positioned elements, it will return a relative positioned inline.
2692 // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2693 // the layout of the positioned object. This does mean that computePositionedLogicalWidth and
2694 // computePositionedLogicalHeight have to use container().
2695 RenderObject* o = parent();
2700 EPosition pos = m_style->position();
2701 if (pos == FixedPosition) {
2702 return containerForFixedPosition(paintInvalidationContainer, paintInvalidationContainerSkipped);
2703 } else if (pos == AbsolutePosition) {
2704 // We technically just want our containing block, but
2705 // we may not have one if we're part of an uninstalled
2706 // subtree. We'll climb as high as we can though.
2708 if (o->style()->position() != StaticPosition)
2711 if (o->canContainFixedPositionObjects())
2714 if (paintInvalidationContainerSkipped && o == paintInvalidationContainer)
2715 *paintInvalidationContainerSkipped = true;
2724 bool RenderObject::isSelectionBorder() const
2726 SelectionState st = selectionState();
2727 return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2730 inline void RenderObject::clearLayoutRootIfNeeded() const
2733 if (FrameView* view = frame()->view()) {
2734 if (view->layoutRoot() == this) {
2735 if (!documentBeingDestroyed())
2736 ASSERT_NOT_REACHED();
2737 // This indicates a failure to layout the child, which is why
2738 // the layout root is still set to |this|. Make sure to clear it
2739 // since we are getting destroyed.
2740 view->clearLayoutSubtreeRoot();
2746 void RenderObject::willBeDestroyed()
2748 // Destroy any leftover anonymous children.
2749 RenderObjectChildList* children = virtualChildren();
2751 children->destroyLeftoverChildren();
2753 // If this renderer is being autoscrolled, stop the autoscrolling.
2754 if (LocalFrame* frame = this->frame()) {
2756 frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
2759 // For accessibility management, notify the parent of the imminent change to its child set.
2760 // We do it now, before remove(), while the parent pointer is still available.
2761 if (AXObjectCache* cache = document().existingAXObjectCache())
2762 cache->childrenChanged(this->parent());
2766 // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
2767 // object for this renderer. So we remove the AX render object now, after the renderer is removed.
2768 if (AXObjectCache* cache = document().existingAXObjectCache())
2769 cache->remove(this);
2771 // If this renderer had a parent, remove should have destroyed any counters
2772 // attached to this renderer and marked the affected other counters for
2773 // reevaluation. This apparently redundant check is here for the case when
2774 // this renderer had no parent at the time remove() was called.
2776 if (hasCounterNodeMap())
2777 RenderCounter::destroyCounterNodes(*this);
2779 // Remove the handler if node had touch-action set. Don't call when
2780 // document is being destroyed as all handlers will have been cleared
2781 // previously. Handlers are not added for text nodes so don't try removing
2782 // for one too. Need to check if m_style is null in cases of partial construction.
2783 if (!documentBeingDestroyed() && node() && !node()->isTextNode() && m_style && m_style->touchAction() != TouchActionAuto)
2784 document().didRemoveTouchEventHandler(node());
2786 setAncestorLineBoxDirty(false);
2788 clearLayoutRootIfNeeded();
2791 void RenderObject::insertedIntoTree()
2793 // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2795 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2796 // and don't have a layer attached to ourselves.
2797 RenderLayer* layer = 0;
2798 if (slowFirstChild() || hasLayer()) {
2799 layer = parent()->enclosingLayer();
2803 // If |this| is visible but this object was not, tell the layer it has some visible content
2804 // that needs to be drawn and layer visibility optimization can't be used
2805 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2807 layer = parent()->enclosingLayer();
2809 layer->setHasVisibleContent();
2812 if (!isFloating() && parent()->childrenInline())
2813 parent()->dirtyLinesFromChangedChild(this);
2816 void RenderObject::willBeRemovedFromTree()
2818 // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2820 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2821 RenderLayer* layer = 0;
2822 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2823 layer = parent()->enclosingLayer();
2825 layer->dirtyVisibleContentStatus();
2828 // Keep our layer hierarchy updated.
2829 if (slowFirstChild() || hasLayer()) {
2831 layer = parent()->enclosingLayer();
2832 removeLayers(layer);
2835 if (isOutOfFlowPositioned() && parent()->childrenInline())
2836 parent()->dirtyLinesFromChangedChild(this);
2838 removeFromRenderFlowThread();
2840 // Update cached boundaries in SVG renderers if a child is removed.
2841 if (parent()->isSVG())
2842 parent()->setNeedsBoundariesUpdate();
2845 void RenderObject::removeFromRenderFlowThread()
2847 if (flowThreadState() == NotInsideFlowThread)
2850 // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2851 // It's only until later when we actually destroy it and remove all the children from it.
2852 // Currently, that happens for firstLetter elements and list markers.
2853 // Pass in the flow thread so that we don't have to look it up for all the children.
2854 removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
2857 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
2859 if (const RenderObjectChildList* children = virtualChildren()) {
2860 for (RenderObject* child = children->firstChild(); child; child = child->nextSibling())
2861 child->removeFromRenderFlowThreadRecursive(renderFlowThread);
2864 setFlowThreadState(NotInsideFlowThread);
2867 void RenderObject::destroyAndCleanupAnonymousWrappers()
2869 // If the tree is destroyed, there is no need for a clean-up phase.
2870 if (documentBeingDestroyed()) {
2875 RenderObject* destroyRoot = this;
2876 for (RenderObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2877 // Anonymous block continuations are tracked and destroyed elsewhere (see the bottom of RenderBlock::removeChild)
2878 if (destroyRootParent->isRenderBlock() && toRenderBlock(destroyRootParent)->isAnonymousBlockContinuation())
2880 // Render flow threads are tracked by the FlowThreadController, so we can't destroy them here.
2881 // Column spans are tracked elsewhere.
2882 if (destroyRootParent->isRenderFlowThread() || destroyRootParent->isAnonymousColumnSpanBlock())
2885 if (destroyRootParent->slowFirstChild() != this || destroyRootParent->slowLastChild() != this)
2889 destroyRoot->destroy();
2891 // WARNING: |this| is deleted here.
2894 void RenderObject::destroy()
2900 void RenderObject::removeShapeImageClient(ShapeValue* shapeValue)
2904 if (StyleImage* shapeImage = shapeValue->image())
2905 shapeImage->removeClient(this);
2908 void RenderObject::postDestroy()
2910 // It seems ugly that this is not in willBeDestroyed().
2912 for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2913 if (StyleImage* backgroundImage = bgLayer->image())
2914 backgroundImage->removeClient(this);
2917 for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2918 if (StyleImage* maskImage = maskLayer->image())
2919 maskImage->removeClient(this);
2922 if (StyleImage* borderImage = m_style->borderImage().image())
2923 borderImage->removeClient(this);
2925 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2926 maskBoxImage->removeClient(this);
2928 removeShapeImageClient(m_style->shapeOutside());
2934 PositionWithAffinity RenderObject::positionForPoint(const LayoutPoint&)
2936 return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2939 void RenderObject::updateDragState(bool dragOn)
2941 bool valueChanged = (dragOn != isDragging());
2942 setIsDragging(dragOn);
2943 if (valueChanged && node()) {
2944 if (node()->isElementNode() && toElement(node())->childrenOrSiblingsAffectedByDrag())
2945 node()->setNeedsStyleRecalc(SubtreeStyleChange);
2946 else if (style()->affectedByDrag())
2947 node()->setNeedsStyleRecalc(LocalStyleChange);
2949 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
2950 curr->updateDragState(dragOn);
2953 CompositingState RenderObject::compositingState() const
2955 return hasLayer() ? toRenderLayerModelObject(this)->layer()->compositingState() : NotComposited;
2958 CompositingReasons RenderObject::additionalCompositingReasons(CompositingTriggerFlags) const
2960 return CompositingReasonNone;
2963 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2965 bool inside = false;
2966 if (hitTestFilter != HitTestSelf) {
2967 // First test the foreground layer (lines and inlines).
2968 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
2970 // Test floats next.
2972 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2974 // Finally test to see if the mouse is in the background (within a child block's background).
2976 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2979 // See if the mouse is inside us but not any of our descendants
2980 if (hitTestFilter != HitTestDescendants && !inside)
2981 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2986 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2988 if (result.innerNode())
2991 Node* node = this->node();
2993 // If we hit the anonymous renderers inside generated content we should
2994 // actually hit the generated content so walk up to the PseudoElement.
2995 if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2996 for (RenderObject* renderer = parent(); renderer && !node; renderer = renderer->parent())
2997 node = renderer->node();
3001 result.setInnerNode(node);
3002 if (!result.innerNonSharedNode())
3003 result.setInnerNonSharedNode(node);
3004 result.setLocalPoint(point);
3008 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
3013 void RenderObject::scheduleRelayout()
3015 if (isRenderView()) {
3016 FrameView* view = toRenderView(this)->frameView();
3018 view->scheduleRelayout();
3021 if (RenderView* renderView = view()) {
3022 if (FrameView* frameView = renderView->frameView())
3023 frameView->scheduleRelayoutOfSubtree(this);
3029 void RenderObject::forceLayout()
3031 setSelfNeedsLayout(true);
3032 setShouldDoFullPaintInvalidationAfterLayout(true);
3036 // FIXME: Does this do anything different than forceLayout given that we don't walk
3037 // the containing block chain. If not, we should change all callers to use forceLayout.
3038 void RenderObject::forceChildLayout()
3040 setNormalChildNeedsLayout(true);
3044 enum StyleCacheState {
3049 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderObject* renderer, RenderStyle* style)
3051 const RenderObject* rendererForFirstLineStyle = renderer;
3052 if (renderer->isBeforeOrAfterContent())
3053 rendererForFirstLineStyle = renderer->parent();
3055 if (rendererForFirstLineStyle->isRenderBlockFlow() || rendererForFirstLineStyle->isRenderButton()) {
3056 if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
3058 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
3059 return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == renderer ? style : 0);
3061 } else if (!rendererForFirstLineStyle->isAnonymous() && rendererForFirstLineStyle->isRenderInline()) {
3062 RenderStyle* parentStyle = rendererForFirstLineStyle->parent()->firstLineStyle();
3063 if (parentStyle != rendererForFirstLineStyle->parent()->style()) {
3064 if (type == Cached) {
3065 // A first-line style is in effect. Cache a first-line style for ourselves.
3066 rendererForFirstLineStyle->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
3067 return rendererForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
3069 return rendererForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
3075 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
3077 if (!document().styleEngine()->usesFirstLineRules())
3082 return firstLineStyleForCachedUncachedType(Uncached, this, style);
3085 RenderStyle* RenderObject::cachedFirstLineStyle() const
3087 ASSERT(document().styleEngine()->usesFirstLineRules());
3089 if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
3092 return m_style.get();
3095 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
3097 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
3100 RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
3104 RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
3106 return style()->addCachedPseudoStyle(result.release());
3110 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
3112 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
3117 parentStyle = style();
3123 Element* element = Traversal<Element>::firstAncestorOrSelf(*node());
3127 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
3128 RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
3129 result->setStyleType(FIRST_LINE_INHERITED);
3130 return result.release();
3133 return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
3136 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyleFromParentOrShadowHost() const
3141 if (ShadowRoot* root = node()->containingShadowRoot()) {
3142 if (root->type() == ShadowRoot::UserAgentShadowRoot) {
3143 if (Element* shadowHost = node()->shadowHost()) {
3144 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
3149 return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
3152 bool RenderObject::hasBlendMode() const
3154 return RuntimeEnabledFeatures::cssCompositingEnabled() && style() && style()->hasBlendMode();
3157 void RenderObject::getTextDecorations(unsigned decorations, AppliedTextDecoration& underline, AppliedTextDecoration& overline, AppliedTextDecoration& linethrough, bool quirksMode, bool firstlineStyle)
3159 RenderObject* curr = this;
3160 RenderStyle* styleToUse = 0;
3161 unsigned currDecs = TextDecorationNone;
3163 TextDecorationStyle resultStyle;
3165 styleToUse = curr->style(firstlineStyle);
3166 currDecs = styleToUse->textDecoration();
3167 currDecs &= decorations;
3168 resultColor = styleToUse->visitedDependentDecorationColor();
3169 resultStyle = styleToUse->textDecorationStyle();
3170 // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
3172 if (currDecs & TextDecorationUnderline) {
3173 decorations &= ~TextDecorationUnderline;
3174 underline.color = resultColor;
3175 underline.style = resultStyle;
3177 if (currDecs & TextDecorationOverline) {
3178 decorations &= ~TextDecorationOverline;
3179 overline.color = resultColor;
3180 overline.style = resultStyle;
3182 if (currDecs & TextDecorationLineThrough) {
3183 decorations &= ~TextDecorationLineThrough;
3184 linethrough.color = resultColor;
3185 linethrough.style = resultStyle;
3188 if (curr->isRubyText())
3190 curr = curr->parent();
3191 if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
3192 curr = toRenderBlock(curr)->continuation();
3193 } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(*curr->node()) && !isHTMLFontElement(*curr->node()))));
3195 // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
3196 if (decorations && curr) {
3197 styleToUse = curr->style(firstlineStyle);
3198 resultColor = styleToUse->visitedDependentDecorationColor();
3199 if (decorations & TextDecorationUnderline) {
3200 underline.color = resultColor;
3201 underline.style = resultStyle;
3203 if (decorations & TextDecorationOverline) {
3204 overline.color = resultColor;
3205 overline.style = resultStyle;
3207 if (decorations & TextDecorationLineThrough) {
3208 linethrough.color = resultColor;
3209 linethrough.style = resultStyle;
3214 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3216 // Convert the style regions to absolute coordinates.
3217 if (style()->visibility() != VISIBLE || !isBox())
3220 if (style()->getDraggableRegionMode() == DraggableRegionNone)
3223 RenderBox* box = toRenderBox(this);
3224 FloatRect localBounds(FloatPoint(), FloatSize(box->width().toFloat(), box->height().toFloat()));
3225 FloatRect absBounds = localToAbsoluteQuad(localBounds).boundingBox();
3227 AnnotatedRegionValue region;
3228 region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
3229 region.bounds = LayoutRect(absBounds);
3230 regions.append(region);
3233 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
3235 // RenderTexts don't have their own style, they just use their parent's style,
3236 // so we don't want to include them.
3240 addAnnotatedRegions(regions);
3241 for (RenderObject* curr = slowFirstChild(); curr; curr = curr->nextSibling())
3242 curr->collectAnnotatedRegions(regions);
3245 bool RenderObject::willRenderImage(ImageResource*)
3247 // Without visibility we won't render (and therefore don't care about animation).
3248 if (style()->visibility() != VISIBLE)
3251 // We will not render a new image when Active DOM is suspended
3252 if (document().activeDOMObjectsAreSuspended())
3255 // If we're not in a window (i.e., we're dormant from being in a background tab)
3256 // then we don't want to render either.
3257 return document().view()->isVisible();
3260 int RenderObject::caretMinOffset() const
3265 int RenderObject::caretMaxOffset() const
3268 return node() ? max(1U, node()->countChildren()) : 1;
3274 int RenderObject::previousOffset(int current) const
3279 int RenderObject::previousOffsetForBackwardDeletion(int current) const
3284 int RenderObject::nextOffset(int current) const
3289 bool RenderObject::isInert() const
3291 const RenderObject* renderer = this;
3292 while (!renderer->node())
3293 renderer = renderer->parent();
3294 return renderer->node()->isInert();
3297 // touch-action applies to all elements with both width AND height properties.
3298 // According to the CSS Box Model Spec (http://dev.w3.org/csswg/css-box/#the-width-and-height-properties)
3299 // width applies to all elements but non-replaced inline elements, table rows, and row groups and
3300 // height applies to all elements but non-replaced inline elements, table columns, and column groups.
3301 bool RenderObject::supportsTouchAction() const
3303 if (isInline() && !isReplaced())
3305 if (isTableRow() || isRenderTableCol())
3311 void RenderObject::imageChanged(ImageResource* image, const IntRect* rect)
3313 imageChanged(static_cast<WrappedImagePtr>(image), rect);
3316 Element* RenderObject::offsetParent() const
3318 if (isDocumentElement() || isBody())
3321 if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
3324 // If A is an area HTML element which has a map HTML element somewhere in the ancestor
3325 // chain return the nearest ancestor map HTML element and stop this algorithm.
3326 // FIXME: Implement!
3328 float effectiveZoom = style()->effectiveZoom();
3330 for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
3331 // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
3333 node = ancestor->node();
3338 if (ancestor->isPositioned())
3341 if (isHTMLBodyElement(*node))
3344 if (!isPositioned() && (isHTMLTableElement(*node) || isHTMLTableCellElement(*node)))
3347 // Webkit specific extension where offsetParent stops at zoom level changes.
3348 if (effectiveZoom != ancestor->style()->effectiveZoom())
3352 return node && node->isElementNode() ? toElement(node) : 0;
3355 PositionWithAffinity RenderObject::createPositionWithAffinity(int offset, EAffinity affinity)
3357 // If this is a non-anonymous renderer in an editable area, then it's simple.
3358 if (Node* node = nonPseudoNode()) {
3359 if (!node->rendererIsEditable()) {
3360 // If it can be found, we prefer a visually equivalent position that is editable.
3361 Position position = createLegacyEditingPosition(node, offset);
3362 Position candidate = position.downstream(CanCrossEditingBoundary);
3363 if (candidate.deprecatedNode()->rendererIsEditable())
3364 return PositionWithAffinity(candidate, affinity);
3365 candidate = position.upstream(CanCrossEditingBoundary);
3366 if (candidate.deprecatedNode()->rendererIsEditable())
3367 return PositionWithAffinity(candidate, affinity);
3369 // FIXME: Eliminate legacy editing positions
3370 return PositionWithAffinity(createLegacyEditingPosition(node, offset), affinity);
3373 // We don't want to cross the boundary between editable and non-editable
3374 // regions of the document, but that is either impossible or at least
3375 // extremely unlikely in any normal case because we stop as soon as we
3376 // find a single non-anonymous renderer.
3378 // Find a nearby non-anonymous renderer.
3379 RenderObject* child = this;
3380 while (RenderObject* parent = child->parent()) {
3381 // Find non-anonymous content after.
3382 RenderObject* renderer = child;
3383 while ((renderer = renderer->nextInPreOrder(parent))) {
3384 if (Node* node = renderer->nonPseudoNode())
3385 return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3388 // Find non-anonymous content before.
3390 while ((renderer = renderer->previousInPreOrder())) {
3391 if (renderer == parent)
3393 if (Node* node = renderer->nonPseudoNode())
3394 return PositionWithAffinity(lastPositionInOrAfterNode(node), DOWNSTREAM);
3397 // Use the parent itself unless it too is anonymous.
3398 if (Node* node = parent->nonPseudoNode())
3399 return PositionWithAffinity(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3401 // Repeat at the next level up.
3405 // Everything was anonymous. Give up.
3406 return PositionWithAffinity();
3409 PositionWithAffinity RenderObject::createPositionWithAffinity(const Position& position)
3411 if (position.isNotNull())
3412 return PositionWithAffinity(position);
3415 return createPositionWithAffinity(0, DOWNSTREAM);
3418 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
3420 return SetCursorBasedOnStyle;
3423 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
3428 RenderBlock* containingBlock = this->containingBlock();
3429 return containingBlock ? !containingBlock->needsLayout() : true;
3432 // We only create "generated" child renderers like one for first-letter if:
3433 // - the firstLetterBlock can have children in the DOM and
3434 // - the block doesn't have any special assumption on its text children.
3435 // This correctly prevents form controls from having such renderers.
3436 bool RenderObject::canHaveGeneratedChildren() const
3438 return canHaveChildren();
3441 void RenderObject::setNeedsBoundariesUpdate()
3443 if (RenderObject* renderer = parent())
3444 renderer->setNeedsBoundariesUpdate();
3447 FloatRect RenderObject::objectBoundingBox() const
3449 ASSERT_NOT_REACHED();
3453 FloatRect RenderObject::strokeBoundingBox() const
3455 ASSERT_NOT_REACHED();
3459 // Returns the smallest rectangle enclosing all of the painted content
3460 // respecting clipping, masking, filters, opacity, stroke-width and markers
3461 FloatRect RenderObject::paintInvalidationRectInLocalCoordinates() const
3463 ASSERT_NOT_REACHED();
3467 AffineTransform RenderObject::localTransform() const
3469 static const AffineTransform identity;
3473 const AffineTransform& RenderObject::localToParentTransform() const
3475 static const AffineTransform identity;
3479 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
3481 ASSERT_NOT_REACHED();
3485 bool RenderObject::isRelayoutBoundaryForInspector() const
3487 return objectIsRelayoutBoundary(this);
3490 void RenderObject::clearPaintInvalidationState()
3492 setShouldDoFullPaintInvalidationAfterLayout(false);
3493 setShouldDoFullPaintInvalidationIfSelfPaintingLayer(false);
3494 setOnlyNeededPositionedMovementLayout(false);
3495 setShouldInvalidateOverflowForPaint(false);
3496 setLayoutDidGetCalled(false);
3497 setMayNeedPaintInvalidation(false);
3500 bool RenderObject::isAllowedToModifyRenderTreeStructure(Document& document)
3502 return DeprecatedDisableModifyRenderTreeStructureAsserts::canModifyRenderTreeStateInAnyState()
3503 || document.lifecycle().stateAllowsRenderTreeMutations();
3506 DeprecatedDisableModifyRenderTreeStructureAsserts::DeprecatedDisableModifyRenderTreeStructureAsserts()
3507 : m_disabler(gModifyRenderTreeStructureAnyState, true)
3511 bool DeprecatedDisableModifyRenderTreeStructureAsserts::canModifyRenderTreeStateInAnyState()
3513 return gModifyRenderTreeStructureAnyState;
3516 } // namespace WebCore
3520 void showTree(const WebCore::RenderObject* object)
3523 object->showTreeForThis();
3526 void showLineTree(const WebCore::RenderObject* object)
3529 object->showLineTreeForThis();
3532 void showRenderTree(const WebCore::RenderObject* object1)
3534 showRenderTree(object1, 0);
3537 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
3540 const WebCore::RenderObject* root = object1;
3541 while (root->parent())
3542 root = root->parent();
3543 root->showRenderTreeAndMark(object1, "*", object2, "-", 0);