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 "RenderObject.h"
30 #include "AXObjectCache.h"
32 #include "ContentData.h"
33 #include "CursorList.h"
34 #include "DashArray.h"
35 #include "EditingBoundary.h"
36 #include "FloatQuad.h"
37 #include "FlowThreadController.h"
39 #include "FrameView.h"
40 #include "GraphicsContext.h"
41 #include "HTMLElement.h"
42 #include "HTMLNames.h"
43 #include "HitTestResult.h"
45 #include "RenderArena.h"
46 #include "RenderCounter.h"
47 #include "RenderDeprecatedFlexibleBox.h"
48 #include "RenderFlexibleBox.h"
49 #include "RenderGeometryMap.h"
50 #include "RenderGrid.h"
51 #include "RenderImage.h"
52 #include "RenderImageResourceStyleImage.h"
53 #include "RenderInline.h"
54 #include "RenderLayer.h"
55 #include "RenderLayerBacking.h"
56 #include "RenderListItem.h"
57 #include "RenderMultiColumnBlock.h"
58 #include "RenderNamedFlowThread.h"
59 #include "RenderRegion.h"
60 #include "RenderRuby.h"
61 #include "RenderRubyText.h"
62 #include "RenderScrollbarPart.h"
63 #include "RenderTableCaption.h"
64 #include "RenderTableCell.h"
65 #include "RenderTableCol.h"
66 #include "RenderTableRow.h"
67 #include "RenderTheme.h"
68 #include "RenderView.h"
70 #include "StyleResolver.h"
71 #include "TransformState.h"
72 #include "WebCoreMemoryInstrumentation.h"
73 #include "htmlediting.h"
76 #include <wtf/RefCountedLeakCounter.h>
77 #include <wtf/UnusedParam.h>
79 #if USE(ACCELERATED_COMPOSITING)
80 #include "RenderLayerCompositor.h"
84 #include "RenderSVGResourceContainer.h"
85 #include "SVGRenderSupport.h"
92 using namespace HTMLNames;
95 static void* baseOfRenderObjectBeingDeleted;
97 RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject, bool isForbidden)
98 : m_renderObject(renderObject)
99 , m_preexistingForbidden(m_renderObject->isSetNeedsLayoutForbidden())
101 m_renderObject->setNeedsLayoutIsForbidden(isForbidden);
104 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
106 m_renderObject->setNeedsLayoutIsForbidden(m_preexistingForbidden);
110 struct SameSizeAsRenderObject {
111 virtual ~SameSizeAsRenderObject() { } // Allocate vtable pointer.
114 unsigned m_debugBitfields : 2;
116 unsigned m_bitfields;
119 COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
121 bool RenderObject::s_affectsParentBlock = false;
123 RenderObjectAncestorLineboxDirtySet* RenderObject::s_ancestorLineboxDirtySet = 0;
125 void* RenderObject::operator new(size_t sz, RenderArena* renderArena)
127 return renderArena->allocate(sz);
130 void RenderObject::operator delete(void* ptr, size_t sz)
132 ASSERT(baseOfRenderObjectBeingDeleted == ptr);
134 // Stash size where destroy can find it.
138 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
140 Document* doc = element->document();
141 RenderArena* arena = doc->renderArena();
143 // Minimal support for content properties replacing an entire element.
144 // Works only if we have exactly one piece of content and it's a URL.
145 // Otherwise acts as if we didn't support this feature.
146 const ContentData* contentData = style->contentData();
147 if (contentData && !contentData->next() && contentData->isImage() && !element->isPseudoElement()) {
148 RenderImage* image = new (arena) RenderImage(element);
149 // RenderImageResourceStyleImage requires a style being present on the image but we don't want to
150 // trigger a style change now as the node is not fully attached. Moving this code to style change
151 // doesn't make sense as it should be run once at renderer creation.
152 image->setStyleInternal(style);
153 if (const StyleImage* styleImage = static_cast<const ImageContentData*>(contentData)->image()) {
154 image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
155 image->setIsGeneratedContent();
157 image->setImageResource(RenderImageResource::create());
158 image->setStyleInternal(0);
162 if (element->hasTagName(rubyTag)) {
163 if (style->display() == INLINE)
164 return new (arena) RenderRubyAsInline(element);
165 else if (style->display() == BLOCK)
166 return new (arena) RenderRubyAsBlock(element);
168 // treat <rt> as ruby text ONLY if it still has its default treatment of block
169 if (element->hasTagName(rtTag) && style->display() == BLOCK)
170 return new (arena) RenderRubyText(element);
171 if (doc->cssRegionsEnabled() && style->isDisplayRegionType() && !style->regionThread().isEmpty() && doc->renderView())
172 return new (arena) RenderRegion(element, 0);
173 switch (style->display()) {
177 return new (arena) RenderInline(element);
182 if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && doc->regionBasedColumnsEnabled())
183 return new (arena) RenderMultiColumnBlock(element);
184 return new (arena) RenderBlock(element);
186 return new (arena) RenderListItem(element);
189 return new (arena) RenderTable(element);
190 case TABLE_ROW_GROUP:
191 case TABLE_HEADER_GROUP:
192 case TABLE_FOOTER_GROUP:
193 return new (arena) RenderTableSection(element);
195 return new (arena) RenderTableRow(element);
196 case TABLE_COLUMN_GROUP:
198 return new (arena) RenderTableCol(element);
200 return new (arena) RenderTableCell(element);
202 return new (arena) RenderTableCaption(element);
205 return new (arena) RenderDeprecatedFlexibleBox(element);
208 return new (arena) RenderFlexibleBox(element);
211 return new (arena) RenderGrid(element);
217 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("RenderObject"));
219 RenderObject::RenderObject(Node* node)
220 : CachedImageClient()
227 , m_hasAXObject(false)
228 , m_setNeedsLayoutForbidden(false)
233 renderObjectCounter.increment();
237 RenderObject::~RenderObject()
240 ASSERT(!m_hasAXObject);
241 renderObjectCounter.decrement();
245 RenderTheme* RenderObject::theme() const
247 ASSERT(document()->page());
249 return document()->page()->theme();
252 bool RenderObject::isDescendantOf(const RenderObject* obj) const
254 for (const RenderObject* r = this; r; r = r->m_parent) {
261 bool RenderObject::isBody() const
263 return node() && node()->hasTagName(bodyTag);
266 bool RenderObject::isHR() const
268 return node() && node()->hasTagName(hrTag);
271 bool RenderObject::isLegend() const
273 return node() && node()->hasTagName(legendTag);
276 bool RenderObject::isHTMLMarquee() const
278 return node() && node()->renderer() == this && node()->hasTagName(marqueeTag);
281 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
283 setFlowThreadState(state);
285 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
286 // If the child is a fragmentation context it already updated the descendants flag accordingly.
287 if (child->isRenderFlowThread())
289 ASSERT(state != child->flowThreadState());
290 child->setFlowThreadStateIncludingDescendants(state);
294 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
296 RenderObjectChildList* children = virtualChildren();
301 bool needsTable = false;
303 if (newChild->isRenderTableCol()) {
304 RenderTableCol* newTableColumn = toRenderTableCol(newChild);
305 bool isColumnInColumnGroup = newTableColumn->isTableColumn() && isRenderTableCol();
306 needsTable = !isTable() && !isColumnInColumnGroup;
307 } else if (newChild->isTableCaption())
308 needsTable = !isTable();
309 else if (newChild->isTableSection())
310 needsTable = !isTable();
311 else if (newChild->isTableRow())
312 needsTable = !isTableSection();
313 else if (newChild->isTableCell())
314 needsTable = !isTableRow();
318 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
319 if (afterChild && afterChild->isAnonymous() && afterChild->isTable() && !afterChild->isBeforeContent())
320 table = toRenderTable(afterChild);
322 table = RenderTable::createAnonymousWithParentRenderer(this);
323 addChild(table, beforeChild);
325 table->addChild(newChild);
327 children->insertChildNode(this, newChild, beforeChild);
329 if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE)
330 toRenderText(newChild)->transformText();
332 // SVG creates renderers for <g display="none">, as SVG requires children of hidden
333 // <g>s to have renderers - at least that's how our implementation works. Consider:
334 // <g display="none"><foreignObject><body style="position: relative">FOO...
335 // - requiresLayer() would return true for the <body>, creating a new RenderLayer
336 // - when the document is painted, both layers are painted. The <body> layer doesn't
337 // know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
338 // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
339 // and stop creating layers at all for these cases - they're not used anyways.
340 if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
341 toRenderLayerModelObject(newChild)->layer()->removeOnlyThisLayer();
344 SVGRenderSupport::childAdded(this, newChild);
348 void RenderObject::removeChild(RenderObject* oldChild)
350 RenderObjectChildList* children = virtualChildren();
355 children->removeChildNode(this, oldChild);
358 RenderObject* RenderObject::nextInPreOrder() const
360 if (RenderObject* o = firstChild())
363 return nextInPreOrderAfterChildren();
366 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
369 if (!(o = nextSibling())) {
371 while (o && !o->nextSibling())
374 o = o->nextSibling();
380 RenderObject* RenderObject::nextInPreOrder(const RenderObject* stayWithin) const
382 if (RenderObject* o = firstChild())
385 return nextInPreOrderAfterChildren(stayWithin);
388 RenderObject* RenderObject::nextInPreOrderAfterChildren(const RenderObject* stayWithin) const
390 if (this == stayWithin)
393 const RenderObject* current = this;
395 while (!(next = current->nextSibling())) {
396 current = current->parent();
397 if (!current || current == stayWithin)
403 RenderObject* RenderObject::previousInPreOrder() const
405 if (RenderObject* o = previousSibling()) {
406 while (o->lastChild())
414 RenderObject* RenderObject::previousInPreOrder(const RenderObject* stayWithin) const
416 if (this == stayWithin)
419 return previousInPreOrder();
422 RenderObject* RenderObject::childAt(unsigned index) const
424 RenderObject* child = firstChild();
425 for (unsigned i = 0; child && i < index; i++)
426 child = child->nextSibling();
430 RenderObject* RenderObject::firstLeafChild() const
432 RenderObject* r = firstChild();
443 RenderObject* RenderObject::lastLeafChild() const
445 RenderObject* r = lastChild();
456 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
457 RenderLayer*& beforeChild)
459 if (obj->hasLayer()) {
460 if (!beforeChild && newObject) {
461 // We need to figure out the layer that follows newObject. We only do
462 // this the first time we find a child layer, and then we update the
463 // pointer values for newObject and beforeChild used by everyone else.
464 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
467 parentLayer->addChild(toRenderLayerModelObject(obj)->layer(), beforeChild);
471 for (RenderObject* curr = obj->firstChild(); curr; curr = curr->nextSibling())
472 addLayers(curr, parentLayer, newObject, beforeChild);
475 void RenderObject::addLayers(RenderLayer* parentLayer)
480 RenderObject* object = this;
481 RenderLayer* beforeChild = 0;
482 WebCore::addLayers(this, parentLayer, object, beforeChild);
485 void RenderObject::removeLayers(RenderLayer* parentLayer)
491 parentLayer->removeChild(toRenderLayerModelObject(this)->layer());
495 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
496 curr->removeLayers(parentLayer);
499 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
505 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
506 ASSERT(oldParent == layer->parent());
508 oldParent->removeChild(layer);
509 newParent->addChild(layer);
513 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
514 curr->moveLayers(oldParent, newParent);
517 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
520 // Error check the parent layer passed in. If it's null, we can't find anything.
524 // Step 1: If our layer is a child of the desired parent, then return our layer.
525 RenderLayer* ourLayer = hasLayer() ? toRenderLayerModelObject(this)->layer() : 0;
526 if (ourLayer && ourLayer->parent() == parentLayer)
529 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
530 // into our siblings trying to find the next layer whose parent is the desired parent.
531 if (!ourLayer || ourLayer == parentLayer) {
532 for (RenderObject* curr = startPoint ? startPoint->nextSibling() : firstChild();
533 curr; curr = curr->nextSibling()) {
534 RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
540 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
542 if (parentLayer == ourLayer)
545 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
546 // follow us to see if we can locate a layer.
547 if (checkParent && parent())
548 return parent()->findNextLayer(parentLayer, this, true);
553 RenderLayer* RenderObject::enclosingLayer() const
555 const RenderObject* curr = this;
557 RenderLayer* layer = curr->hasLayer() ? toRenderLayerModelObject(curr)->layer() : 0;
560 curr = curr->parent();
565 bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
567 RenderLayer* enclosingLayer = this->enclosingLayer();
571 enclosingLayer->scrollRectToVisible(rect, alignX, alignY);
575 RenderBox* RenderObject::enclosingBox() const
577 RenderObject* curr = const_cast<RenderObject*>(this);
580 return toRenderBox(curr);
581 curr = curr->parent();
584 ASSERT_NOT_REACHED();
588 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
590 RenderObject* curr = const_cast<RenderObject*>(this);
592 if (curr->isBoxModelObject())
593 return toRenderBoxModelObject(curr);
594 curr = curr->parent();
597 ASSERT_NOT_REACHED();
601 RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
603 ASSERT(flowThreadState() != NotInsideFlowThread);
605 // See if we have the thread cached because we're in the middle of layout.
606 RenderFlowThread* flowThread = view()->flowThreadController()->currentRenderFlowThread();
610 // Not in the middle of layout so have to find the thread the slow way.
611 RenderObject* curr = const_cast<RenderObject*>(this);
613 if (curr->isRenderFlowThread())
614 return toRenderFlowThread(curr);
615 curr = curr->containingBlock();
620 RenderNamedFlowThread* RenderObject::renderNamedFlowThreadWrapper() const
622 RenderObject* object = const_cast<RenderObject*>(this);
623 while (object && object->isAnonymousBlock() && !object->isRenderNamedFlowThread())
624 object = object->parent();
626 return object && object->isRenderNamedFlowThread() ? toRenderNamedFlowThread(object) : 0;
629 RenderBlock* RenderObject::firstLineBlock() const
634 static inline bool objectIsRelayoutBoundary(const RenderObject* object)
636 // FIXME: In future it may be possible to broaden these conditions in order to improve performance.
637 if (object->isTextControl())
641 if (object->isSVGRoot())
645 if (!object->hasOverflowClip())
648 if (object->style()->width().isIntrinsicOrAuto() || object->style()->height().isIntrinsicOrAuto() || object->style()->height().isPercent())
651 // Table parts can't be relayout roots since the table is responsible for layouting all the parts.
652 if (object->isTablePart())
658 void RenderObject::markContainingBlocksForLayout(bool scheduleRelayout, RenderObject* newRoot)
660 ASSERT(!scheduleRelayout || !newRoot);
661 ASSERT(!isSetNeedsLayoutForbidden());
663 RenderObject* object = container();
664 RenderObject* last = this;
666 bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
670 // FIXME: Remove this once we remove the special cases for counters, quotes and mathml
671 // calling setNeedsLayout during preferred width computation.
672 SetLayoutNeededForbiddenScope layoutForbiddenScope(object, isSetNeedsLayoutForbidden());
674 // Don't mark the outermost object of an unrooted subtree. That object will be
675 // marked when the subtree is added to the document.
676 RenderObject* container = object->container();
677 if (!container && !object->isRenderView())
679 if (!last->isText() && last->style()->hasOutOfFlowPosition()) {
680 bool willSkipRelativelyPositionedInlines = !object->isRenderBlock() || object->isAnonymousBlock();
681 // Skip relatively positioned inlines and anonymous blocks to get to the enclosing RenderBlock.
682 while (object && (!object->isRenderBlock() || object->isAnonymousBlock()))
683 object = object->container();
684 if (!object || object->posChildNeedsLayout())
686 if (willSkipRelativelyPositionedInlines)
687 container = object->container();
688 object->setPosChildNeedsLayout(true);
689 simplifiedNormalFlowLayout = true;
690 ASSERT(!object->isSetNeedsLayoutForbidden());
691 } else if (simplifiedNormalFlowLayout) {
692 if (object->needsSimplifiedNormalFlowLayout())
694 object->setNeedsSimplifiedNormalFlowLayout(true);
695 ASSERT(!object->isSetNeedsLayoutForbidden());
697 if (object->normalChildNeedsLayout())
699 object->setNormalChildNeedsLayout(true);
700 ASSERT(!object->isSetNeedsLayoutForbidden());
703 if (object == newRoot)
707 if (scheduleRelayout && objectIsRelayoutBoundary(last))
712 if (scheduleRelayout)
713 last->scheduleRelayout();
717 void RenderObject::checkBlockPositionedObjectsNeedLayout()
719 ASSERT(!needsLayout());
722 toRenderBlock(this)->checkPositionedObjectsNeedLayout();
726 void RenderObject::setPreferredLogicalWidthsDirty(bool shouldBeDirty, MarkingBehavior markParents)
728 bool alreadyDirty = preferredLogicalWidthsDirty();
729 m_bitfields.setPreferredLogicalWidthsDirty(shouldBeDirty);
730 if (shouldBeDirty && !alreadyDirty && markParents == MarkContainingBlockChain && (isText() || !style()->hasOutOfFlowPosition()))
731 invalidateContainerPreferredLogicalWidths();
734 void RenderObject::invalidateContainerPreferredLogicalWidths()
736 // In order to avoid pathological behavior when inlines are deeply nested, we do include them
737 // in the chain that we mark dirty (even though they're kind of irrelevant).
738 RenderObject* o = isTableCell() ? containingBlock() : container();
739 while (o && !o->preferredLogicalWidthsDirty()) {
740 // Don't invalidate the outermost object of an unrooted subtree. That object will be
741 // invalidated when the subtree is added to the document.
742 RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
743 if (!container && !o->isRenderView())
746 o->m_bitfields.setPreferredLogicalWidthsDirty(true);
747 if (o->style()->hasOutOfFlowPosition())
748 // A positioned object has no effect on the min/max width of its containing block ever.
749 // We can optimize this case and not go up any further.
755 void RenderObject::setLayerNeedsFullRepaint()
758 toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaint);
761 void RenderObject::setLayerNeedsFullRepaintForPositionedMovementLayout()
764 toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
767 RenderBlock* RenderObject::containingBlock() const
769 RenderObject* o = parent();
770 if (!o && isRenderScrollbarPart())
771 o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
772 if (!isText() && m_style->position() == FixedPosition) {
774 if (o->canContainFixedPositionObjects())
778 ASSERT(!o || !o->isAnonymousBlock());
779 } else if (!isText() && m_style->position() == AbsolutePosition) {
781 // For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
782 // to return the inline itself. This allows us to avoid having a positioned objects
783 // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
784 // from this method. The container() method can actually be used to obtain the
786 if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
788 if (o->isRenderView())
790 if (o->hasTransform() && o->isRenderBlock())
793 if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
794 o = o->containingBlock();
798 if (o->isSVGForeignObject()) //foreignObject is the containing block for contents inside it
805 while (o && o->isAnonymousBlock())
806 o = o->containingBlock();
808 while (o && ((o->isInline() && !o->isReplaced()) || !o->isRenderBlock()))
812 if (!o || !o->isRenderBlock())
813 return 0; // This can still happen in case of an orphaned tree
815 return toRenderBlock(o);
818 static bool mustRepaintFillLayers(const RenderObject* renderer, const FillLayer* layer)
820 // Nobody will use multiple layers without wanting fancy positioning.
824 // Make sure we have a valid image.
825 StyleImage* img = layer->image();
826 if (!img || !img->canRender(renderer, renderer->style()->effectiveZoom()))
829 if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
832 EFillSizeType sizeType = layer->sizeType();
834 if (sizeType == Contain || sizeType == Cover)
837 if (sizeType == SizeLength) {
838 if (layer->sizeLength().width().isPercent() || layer->sizeLength().height().isPercent())
840 } else if (img->usesImageContainerSize())
846 bool RenderObject::borderImageIsLoadedAndCanBeRendered() const
848 ASSERT(style()->hasBorder());
850 StyleImage* borderImage = style()->borderImage().image();
851 return borderImage && borderImage->canRender(this, style()->effectiveZoom()) && borderImage->isLoaded();
854 bool RenderObject::mustRepaintBackgroundOrBorder() const
856 if (hasMask() && mustRepaintFillLayers(this, style()->maskLayers()))
859 // If we don't have a background/border/mask, then nothing to do.
860 if (!hasBoxDecorations())
863 if (mustRepaintFillLayers(this, style()->backgroundLayers()))
866 // Our fill layers are ok. Let's check border.
867 if (style()->hasBorder() && borderImageIsLoadedAndCanBeRendered())
873 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
874 BoxSide side, Color color, EBorderStyle style,
875 int adjacentWidth1, int adjacentWidth2, bool antialias)
879 if (side == BSTop || side == BSBottom) {
887 // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
888 // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
889 if (!thickness || !length)
892 if (style == DOUBLE && thickness < 3)
901 graphicsContext->setStrokeColor(color, m_style->colorSpace());
902 graphicsContext->setStrokeThickness(thickness);
903 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
904 graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
907 bool wasAntialiased = graphicsContext->shouldAntialias();
908 graphicsContext->setShouldAntialias(antialias);
913 graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
917 graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
920 graphicsContext->setShouldAntialias(wasAntialiased);
921 graphicsContext->setStrokeStyle(oldStrokeStyle);
926 int thirdOfThickness = (thickness + 1) / 3;
927 ASSERT(thirdOfThickness);
929 if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
930 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
931 graphicsContext->setStrokeStyle(NoStroke);
932 graphicsContext->setFillColor(color, m_style->colorSpace());
934 bool wasAntialiased = graphicsContext->shouldAntialias();
935 graphicsContext->setShouldAntialias(antialias);
940 graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
941 graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
945 // FIXME: Why do we offset the border by 1 in this case but not the other one?
947 graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
948 graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
953 graphicsContext->setShouldAntialias(wasAntialiased);
954 graphicsContext->setStrokeStyle(oldStrokeStyle);
956 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
957 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
961 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
962 y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
963 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
964 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
965 y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
966 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
969 drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
970 x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
971 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
972 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
973 x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
974 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
977 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
978 y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
979 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
980 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
981 y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
982 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
985 drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
986 x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
987 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
988 drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
989 x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
990 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
1002 if (style == GROOVE) {
1010 int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
1011 int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
1015 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1016 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1017 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
1018 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1021 drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
1022 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1023 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
1024 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1027 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1028 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1029 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
1030 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1033 drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
1034 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1035 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
1036 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1042 // FIXME: Maybe we should lighten the colors on one side like Firefox.
1043 // https://bugs.webkit.org/show_bug.cgi?id=58608
1044 if (side == BSTop || side == BSLeft)
1045 color = color.dark();
1048 if (style == OUTSET && (side == BSBottom || side == BSRight))
1049 color = color.dark();
1052 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1053 graphicsContext->setStrokeStyle(NoStroke);
1054 graphicsContext->setFillColor(color, m_style->colorSpace());
1057 if (!adjacentWidth1 && !adjacentWidth2) {
1058 // Turn off antialiasing to match the behavior of drawConvexPolygon();
1059 // this matters for rects in transformed contexts.
1060 bool wasAntialiased = graphicsContext->shouldAntialias();
1061 graphicsContext->setShouldAntialias(antialias);
1062 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
1063 graphicsContext->setShouldAntialias(wasAntialiased);
1064 graphicsContext->setStrokeStyle(oldStrokeStyle);
1070 quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
1071 quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
1072 quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
1073 quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
1076 quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
1077 quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
1078 quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
1079 quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
1082 quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
1083 quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
1084 quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
1085 quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
1088 quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
1089 quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
1090 quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
1091 quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
1095 graphicsContext->drawConvexPolygon(4, quad, antialias);
1096 graphicsContext->setStrokeStyle(oldStrokeStyle);
1102 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
1104 Vector<IntRect> focusRingRects;
1105 addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
1106 if (style->outlineStyleIsAuto())
1107 paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
1109 addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
1112 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
1117 if (!n || !n->isLink() || !n->isElementNode())
1119 const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
1122 context->setURLForRect(n->document()->completeURL(href), pixelSnappedIntRect(rect));
1125 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1130 RenderStyle* styleToUse = style();
1131 LayoutUnit outlineWidth = styleToUse->outlineWidth();
1133 int outlineOffset = styleToUse->outlineOffset();
1135 if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1136 if (!theme()->supportsFocusRing(styleToUse)) {
1137 // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1138 paintFocusRing(paintInfo, paintRect.location(), styleToUse);
1142 if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1145 IntRect inner = pixelSnappedIntRect(paintRect);
1146 inner.inflate(outlineOffset);
1148 IntRect outer = pixelSnappedIntRect(inner);
1149 outer.inflate(outlineWidth);
1151 // FIXME: This prevents outlines from painting inside the object. See bug 12042
1152 if (outer.isEmpty())
1155 EBorderStyle outlineStyle = styleToUse->outlineStyle();
1156 Color outlineColor = styleToUse->visitedDependentColor(CSSPropertyOutlineColor);
1158 GraphicsContext* graphicsContext = paintInfo.context;
1159 bool useTransparencyLayer = outlineColor.hasAlpha();
1160 if (useTransparencyLayer) {
1161 if (outlineStyle == SOLID) {
1163 path.addRect(outer);
1164 path.addRect(inner);
1165 graphicsContext->setFillRule(RULE_EVENODD);
1166 graphicsContext->setFillColor(outlineColor, styleToUse->colorSpace());
1167 graphicsContext->fillPath(path);
1170 graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1171 outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1174 int leftOuter = outer.x();
1175 int leftInner = inner.x();
1176 int rightOuter = outer.maxX();
1177 int rightInner = inner.maxX();
1178 int topOuter = outer.y();
1179 int topInner = inner.y();
1180 int bottomOuter = outer.maxY();
1181 int bottomInner = inner.maxY();
1183 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1184 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1185 drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1186 drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1188 if (useTransparencyLayer)
1189 graphicsContext->endTransparencyLayer();
1192 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms) const
1194 if (useTransforms) {
1195 Vector<FloatQuad> quads;
1196 absoluteQuads(quads);
1198 size_t n = quads.size();
1202 IntRect result = quads[0].enclosingBoundingBox();
1203 for (size_t i = 1; i < n; ++i)
1204 result.unite(quads[i].enclosingBoundingBox());
1208 FloatPoint absPos = localToAbsolute();
1209 Vector<IntRect> rects;
1210 absoluteRects(rects, flooredLayoutPoint(absPos));
1212 size_t n = rects.size();
1216 LayoutRect result = rects[0];
1217 for (size_t i = 1; i < n; ++i)
1218 result.unite(rects[i]);
1219 return pixelSnappedIntRect(result);
1222 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1224 Vector<IntRect> rects;
1225 // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1226 // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1227 // implicitly assumes that. This doesn't work correctly with transformed
1229 FloatPoint absolutePoint = localToAbsolute();
1230 addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
1231 size_t count = rects.size();
1232 for (size_t i = 0; i < count; ++i) {
1233 IntRect rect = rects[i];
1234 rect.move(-absolutePoint.x(), -absolutePoint.y());
1235 quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1239 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1241 if (!range || !range->startContainer())
1244 if (range->ownerDocument())
1245 range->ownerDocument()->updateLayout();
1247 Vector<FloatQuad> quads;
1248 range->textQuads(quads);
1251 for (size_t i = 0; i < quads.size(); ++i)
1252 result.unite(quads[i].boundingBox());
1257 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1260 result.unite(absoluteBoundingBoxRectIgnoringTransforms());
1261 for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1262 current->addAbsoluteRectForLayer(result);
1265 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1267 LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
1268 topLevelRect = result;
1269 for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1270 current->addAbsoluteRectForLayer(result);
1274 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1278 RenderLayerModelObject* RenderObject::containerForRepaint() const
1280 RenderView* v = view();
1284 RenderLayerModelObject* repaintContainer = 0;
1286 #if USE(ACCELERATED_COMPOSITING)
1287 if (v->usesCompositing()) {
1288 if (RenderLayer* parentLayer = enclosingLayer()) {
1289 RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
1291 repaintContainer = compLayer->renderer();
1296 #if ENABLE(CSS_FILTERS)
1297 if (document()->view()->hasSoftwareFilters()) {
1298 if (RenderLayer* parentLayer = enclosingLayer()) {
1299 RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
1300 if (enclosingFilterLayer)
1301 return enclosingFilterLayer->renderer();
1306 // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1307 // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1308 // repainting to do individual region repaints.
1309 RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
1310 if (parentRenderFlowThread) {
1311 // The ancestor document will do the reparenting when the repaint propagates further up.
1312 // We're just a seamless child document, and we don't need to do the hacking.
1313 if (parentRenderFlowThread && parentRenderFlowThread->document() != document())
1314 return repaintContainer;
1315 // If we have already found a repaint container then we will repaint into that container only if it is part of the same
1316 // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
1317 RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : 0;
1318 if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
1319 repaintContainer = parentRenderFlowThread;
1321 return repaintContainer;
1324 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const IntRect& r, bool immediate) const
1326 if (!repaintContainer) {
1327 view()->repaintViewRectangle(r, immediate);
1331 if (repaintContainer->isRenderFlowThread()) {
1332 toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r, immediate);
1336 #if ENABLE(CSS_FILTERS)
1337 if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
1338 repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r, immediate);
1343 #if USE(ACCELERATED_COMPOSITING)
1344 RenderView* v = view();
1345 if (repaintContainer->isRenderView()) {
1346 ASSERT(repaintContainer == v);
1347 bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
1348 if (!viewHasCompositedLayer || v->layer()->backing()->paintsIntoWindow()) {
1349 LayoutRect repaintRectangle = r;
1350 if (viewHasCompositedLayer && v->layer()->transform())
1351 repaintRectangle = enclosingIntRect(v->layer()->transform()->mapRect(r));
1352 v->repaintViewRectangle(repaintRectangle, immediate);
1357 if (v->usesCompositing()) {
1358 ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1359 repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
1362 if (repaintContainer->isRenderView())
1363 toRenderView(repaintContainer)->repaintViewRectangle(r, immediate);
1367 void RenderObject::repaint(bool immediate) const
1369 // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1371 if (!isRooted(&view))
1374 if (view->printing())
1375 return; // Don't repaint if we're printing.
1377 RenderLayerModelObject* repaintContainer = containerForRepaint();
1378 repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)), immediate);
1381 void RenderObject::repaintRectangle(const LayoutRect& r, bool immediate) const
1383 // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1385 if (!isRooted(&view))
1388 if (view->printing())
1389 return; // Don't repaint if we're printing.
1391 LayoutRect dirtyRect(r);
1393 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1394 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1395 dirtyRect.move(view->layoutDelta());
1397 RenderLayerModelObject* repaintContainer = containerForRepaint();
1398 computeRectForRepaint(repaintContainer, dirtyRect);
1399 repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(dirtyRect), immediate);
1402 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1404 return pixelSnappedIntRect(absoluteClippedOverflowRect());
1407 bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1409 RenderView* v = view();
1411 return false; // Don't repaint if we're printing.
1413 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1414 // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1415 LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1416 LayoutRect newOutlineBox;
1418 bool fullRepaint = selfNeedsLayout();
1419 // Presumably a background or a border exists if border-fit:lines was specified.
1420 if (!fullRepaint && style()->borderFit() == BorderFitLines)
1423 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1424 // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1425 newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1426 if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder() && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1430 if (!repaintContainer)
1431 repaintContainer = v;
1434 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds));
1435 if (newBounds != oldBounds)
1436 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds));
1440 if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1443 LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1445 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1446 else if (deltaLeft < 0)
1447 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1449 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1451 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1452 else if (deltaRight < 0)
1453 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1455 LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1457 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1458 else if (deltaTop < 0)
1459 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1461 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1462 if (deltaBottom > 0)
1463 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1464 else if (deltaBottom < 0)
1465 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1467 if (newOutlineBox == oldOutlineBox)
1470 // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1471 // two rectangles (but typically only one).
1472 RenderStyle* outlineStyle = outlineStyleForRepaint();
1473 LayoutUnit outlineWidth = outlineStyle->outlineSize();
1474 LayoutBoxExtent insetShadowExtent = style()->getBoxShadowInsetExtent();
1475 LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1477 LayoutUnit shadowLeft;
1478 LayoutUnit shadowRight;
1479 style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1480 int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1481 LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : LayoutUnit();
1482 LayoutUnit minInsetRightShadowExtent = min<LayoutUnit>(-insetShadowExtent.right(), min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1483 LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth, v), valueForLength(style()->borderBottomRightRadius().width(), boxWidth, v)));
1484 LayoutUnit decorationsWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
1485 LayoutRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1487 width + decorationsWidth,
1488 max(newOutlineBox.height(), oldOutlineBox.height()));
1489 LayoutUnit right = min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1490 if (rightRect.x() < right) {
1491 rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1492 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(rightRect));
1495 LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1497 LayoutUnit shadowTop;
1498 LayoutUnit shadowBottom;
1499 style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1500 int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1501 LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : LayoutUnit();
1502 LayoutUnit minInsetBottomShadowExtent = min<LayoutUnit>(-insetShadowExtent.bottom(), min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1503 LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight, v), valueForLength(style()->borderBottomRightRadius().height(), boxHeight, v)));
1504 LayoutUnit decorationsHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
1505 LayoutRect bottomRect(newOutlineBox.x(),
1506 min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1507 max(newOutlineBox.width(), oldOutlineBox.width()),
1508 height + decorationsHeight);
1509 LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
1510 if (bottomRect.y() < bottom) {
1511 bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1512 repaintUsingContainer(repaintContainer, pixelSnappedIntRect(bottomRect));
1518 bool RenderObject::checkForRepaintDuringLayout() const
1520 return !document()->view()->needsFullRepaint() && !hasLayer() && everHadLayout();
1523 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
1525 LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
1526 r.inflate(outlineWidth);
1530 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
1532 ASSERT_NOT_REACHED();
1533 return LayoutRect();
1536 void RenderObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1538 if (repaintContainer == this)
1541 if (RenderObject* o = parent()) {
1542 if (o->isBlockFlow()) {
1543 RenderBlock* cb = toRenderBlock(o);
1544 if (cb->hasColumns())
1545 cb->adjustRectForColumns(rect);
1548 if (o->hasOverflowClip()) {
1549 RenderBox* boxParent = toRenderBox(o);
1550 boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1555 o->computeRectForRepaint(repaintContainer, rect, fixed);
1559 void RenderObject::computeFloatRectForRepaint(const RenderLayerModelObject*, FloatRect&, bool) const
1561 ASSERT_NOT_REACHED();
1564 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1570 void RenderObject::showTreeForThis() const
1573 node()->showTreeForThis();
1576 void RenderObject::showRenderTreeForThis() const
1578 showRenderTree(this, 0);
1581 void RenderObject::showLineTreeForThis() const
1583 if (containingBlock())
1584 containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1587 void RenderObject::showRenderObject() const
1589 showRenderObject(0);
1592 void RenderObject::showRenderObject(int printedCharacters) const
1594 // As this function is intended to be used when debugging, the
1595 // this pointer may be 0.
1597 fputs("(null)\n", stderr);
1601 printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1604 if (printedCharacters)
1605 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1607 fputc('\t', stderr);
1610 fputc('\n', stderr);
1613 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1615 int printedCharacters = 0;
1616 if (markedObject1 == this && markedLabel1)
1617 printedCharacters += fprintf(stderr, "%s", markedLabel1);
1618 if (markedObject2 == this && markedLabel2)
1619 printedCharacters += fprintf(stderr, "%s", markedLabel2);
1620 for (; printedCharacters < depth * 2; printedCharacters++)
1623 showRenderObject(printedCharacters);
1627 for (const RenderObject* child = firstChild(); child; child = child->nextSibling())
1628 child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1633 Color RenderObject::selectionBackgroundColor() const
1636 if (style()->userSelect() != SELECT_NONE) {
1637 RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1638 if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1639 color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1641 color = frame()->selection()->isFocusedAndActive() ?
1642 theme()->activeSelectionBackgroundColor() :
1643 theme()->inactiveSelectionBackgroundColor();
1649 Color RenderObject::selectionColor(int colorProperty) const
1652 // If the element is unselectable, or we are only painting the selection,
1653 // don't override the foreground color with the selection foreground color.
1654 if (style()->userSelect() == SELECT_NONE
1655 || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1658 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
1659 color = pseudoStyle->visitedDependentColor(colorProperty);
1660 if (!color.isValid())
1661 color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1663 color = frame()->selection()->isFocusedAndActive() ?
1664 theme()->activeSelectionForegroundColor() :
1665 theme()->inactiveSelectionForegroundColor();
1670 Color RenderObject::selectionForegroundColor() const
1672 return selectionColor(CSSPropertyWebkitTextFillColor);
1675 Color RenderObject::selectionEmphasisMarkColor() const
1677 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1680 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1682 view()->selectionStartEnd(spos, epos);
1685 void RenderObject::handleDynamicFloatPositionChange()
1687 // We have gone from not affecting the inline status of the parent flow to suddenly
1688 // having an impact. See if there is a mismatch between the parent flow's
1689 // childrenInline() state and our state.
1690 setInline(style()->isDisplayInlineType());
1691 if (isInline() != parent()->childrenInline()) {
1693 toRenderBoxModelObject(parent())->childBecameNonInline(this);
1695 // An anonymous block must be made to wrap this inline.
1696 RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1697 RenderObjectChildList* childlist = parent()->virtualChildren();
1698 childlist->insertChildNode(parent(), block, this);
1699 block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1704 void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
1706 if (!isText() && style)
1707 setStyle(animation()->updateAnimations(this, style.get()));
1712 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1714 #if USE(ACCELERATED_COMPOSITING)
1715 // If transform changed, and we are not composited, need to do a layout.
1716 if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1717 // Text nodes share style with their parents but transforms don't apply to them,
1718 // hence the !isText() check.
1719 // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
1720 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited())) {
1721 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
1722 // then we actually need SimplifiedLayoutAndPositionedMovement.
1724 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
1725 else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
1726 diff = StyleDifferenceSimplifiedLayout;
1727 else if (diff < StyleDifferenceSimplifiedLayout)
1728 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
1729 } else if (diff < StyleDifferenceRecompositeLayer)
1730 diff = StyleDifferenceRecompositeLayer;
1733 // If opacity changed, and we are not composited, need to repaint (also
1734 // ignoring text nodes)
1735 if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
1736 if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited()))
1737 diff = StyleDifferenceRepaintLayer;
1738 else if (diff < StyleDifferenceRecompositeLayer)
1739 diff = StyleDifferenceRecompositeLayer;
1742 #if ENABLE(CSS_FILTERS)
1743 if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
1744 RenderLayer* layer = toRenderLayerModelObject(this)->layer();
1745 if (!layer->isComposited() || layer->paintsWithFilters())
1746 diff = StyleDifferenceRepaintLayer;
1747 else if (diff < StyleDifferenceRecompositeLayer)
1748 diff = StyleDifferenceRecompositeLayer;
1752 // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
1753 // style changing, since it depends on whether we decide to composite these elements. When the
1754 // layer status of one of these elements changes, we need to force a layout.
1755 if (diff == StyleDifferenceEqual && style() && isLayerModelObject()) {
1756 if (hasLayer() != toRenderLayerModelObject(this)->requiresLayer())
1757 diff = StyleDifferenceLayout;
1760 UNUSED_PARAM(contextSensitiveProperties);
1763 // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
1764 if (diff == StyleDifferenceRepaintLayer && !hasLayer())
1765 diff = StyleDifferenceRepaint;
1770 void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
1772 ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER);
1774 // Images are special and must inherit the pseudoStyle so the width and height of
1775 // the pseudo element doesn't change the size of the image. In all other cases we
1776 // can just share the style.
1778 RefPtr<RenderStyle> style = RenderStyle::create();
1779 style->inheritFrom(pseudoStyle.get());
1780 setStyle(style.release());
1784 setStyle(pseudoStyle);
1787 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
1789 if (m_style == style) {
1790 #if USE(ACCELERATED_COMPOSITING)
1791 // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
1792 // style sharing is disabled for them. That should ensure that we never hit this code path.
1793 ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
1798 StyleDifference diff = StyleDifferenceEqual;
1799 unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
1801 diff = m_style->diff(style.get(), contextSensitiveProperties);
1803 diff = adjustStyleDifference(diff, contextSensitiveProperties);
1805 styleWillChange(diff, style.get());
1807 RefPtr<RenderStyle> oldStyle = m_style.release();
1808 setStyleInternal(style);
1810 updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
1811 updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
1813 updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
1814 updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
1816 // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
1817 // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
1818 if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
1819 toRenderView(document()->renderer())->setMaximalOutlineSize(m_style->outlineSize());
1821 bool doesNotNeedLayout = !m_parent || isText();
1823 styleDidChange(diff, oldStyle.get());
1825 // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
1826 // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
1827 // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
1828 // in the future as we move renderer changes out of layout and into style changes.
1829 if (doesNotNeedLayout)
1832 // Now that the layer (if any) has been updated, we need to adjust the diff again,
1833 // check whether we should layout now, and decide if we need to repaint.
1834 StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
1836 if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
1837 if (updatedDiff == StyleDifferenceLayout)
1838 setNeedsLayoutAndPrefWidthsRecalc();
1839 else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
1840 setNeedsPositionedMovementLayout();
1841 else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1842 setNeedsPositionedMovementLayout();
1843 setNeedsSimplifiedNormalFlowLayout();
1844 } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
1845 setNeedsSimplifiedNormalFlowLayout();
1848 if (updatedDiff == StyleDifferenceRepaintLayer || updatedDiff == StyleDifferenceRepaint) {
1849 // Do a repaint with the new style now, e.g., for example if we go from
1850 // not having an outline to having an outline.
1855 static inline bool rendererHasBackground(const RenderObject* renderer)
1857 return renderer && renderer->hasBackground();
1860 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1863 // If our z-index changes value or our visibility changes,
1864 // we need to dirty our stacking context's z-order list.
1866 bool visibilityChanged = m_style->visibility() != newStyle->visibility()
1867 || m_style->zIndex() != newStyle->zIndex()
1868 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1869 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
1870 if (visibilityChanged)
1871 document()->setAnnotatedRegionsDirty(true);
1873 if (visibilityChanged) {
1874 if (AXObjectCache* cache = document()->existingAXObjectCache())
1875 cache->childrenChanged(parent());
1878 // Keep layer hierarchy visibility bits up to date if visibility changes.
1879 if (m_style->visibility() != newStyle->visibility()) {
1880 if (RenderLayer* l = enclosingLayer()) {
1881 if (newStyle->visibility() == VISIBLE)
1882 l->setHasVisibleContent();
1883 else if (l->hasVisibleContent() && (this == l->renderer() || l->renderer()->style()->visibility() != VISIBLE)) {
1884 l->dirtyVisibleContentStatus();
1885 if (diff > StyleDifferenceRepaintLayer)
1892 if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
1894 if (isFloating() && (m_style->floating() != newStyle->floating()))
1895 // For changes in float styles, we need to conceivably remove ourselves
1896 // from the floating objects list.
1897 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1898 else if (isOutOfFlowPositioned() && (m_style->position() != newStyle->position()))
1899 // For changes in positioning styles, we need to conceivably remove ourselves
1900 // from the positioned objects list.
1901 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1903 s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
1904 && (!newStyle->isFloating() && !newStyle->hasOutOfFlowPosition())
1905 && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
1907 // reset style flags
1908 if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
1910 clearPositionedState();
1912 setHorizontalWritingMode(true);
1913 setHasBoxDecorations(false);
1914 setHasOverflowClip(false);
1915 setHasTransform(false);
1916 setHasReflection(false);
1918 s_affectsParentBlock = false;
1920 if (view()->frameView()) {
1921 bool shouldBlitOnFixedBackgroundImage = false;
1922 #if ENABLE(FAST_MOBILE_SCROLLING)
1923 // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
1924 // when scrolling a page with a fixed background image. As an optimization, assuming there are
1925 // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
1926 // ignore the CSS property "background-attachment: fixed".
1928 if (view()->frameView()->delegatesScrolling())
1930 shouldBlitOnFixedBackgroundImage = true;
1933 bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
1934 bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
1936 #if USE(ACCELERATED_COMPOSITING)
1937 bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document()->documentElement()->renderer()));
1938 if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
1939 if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
1940 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
1941 newStyleSlowScroll = false;
1943 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
1944 oldStyleSlowScroll = false;
1948 if (oldStyleSlowScroll != newStyleSlowScroll) {
1949 if (oldStyleSlowScroll)
1950 view()->frameView()->removeSlowRepaintObject();
1951 if (newStyleSlowScroll)
1952 view()->frameView()->addSlowRepaintObject();
1957 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
1959 ASSERT(a->cursors() != b->cursors());
1960 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1963 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
1965 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1968 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1970 if (s_affectsParentBlock)
1971 handleDynamicFloatPositionChange();
1974 SVGRenderSupport::styleChanged(this);
1980 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1981 RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
1983 // If the object already needs layout, then setNeedsLayout won't do
1984 // any work. But if the containing block has changed, then we may need
1985 // to mark the new containing blocks for layout. The change that can
1986 // directly affect the containing block of this object is a change to
1987 // the position style.
1988 if (needsLayout() && oldStyle->position() != m_style->position())
1989 markContainingBlocksForLayout();
1991 if (diff == StyleDifferenceLayout)
1992 setNeedsLayoutAndPrefWidthsRecalc();
1994 setNeedsSimplifiedNormalFlowLayout();
1995 } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1996 setNeedsPositionedMovementLayout();
1997 setNeedsSimplifiedNormalFlowLayout();
1998 } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1999 setNeedsPositionedMovementLayout();
2001 // Don't check for repaint here; we need to wait until the layer has been
2002 // updated by subclasses before we know if we have to repaint (in setStyle()).
2004 if (oldStyle && !areCursorsEqual(oldStyle, style())) {
2005 if (Frame* frame = this->frame())
2006 frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
2010 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
2012 // FIXME: We could save this call when the change only affected non-inherited properties.
2013 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
2014 if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
2017 if (blockChildrenOnly && !child->isRenderBlock())
2020 #if ENABLE(FULLSCREEN_API)
2021 if (child->isRenderFullScreen() || child->isRenderFullScreenPlaceholder())
2025 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), child->style()->display());
2026 if (style()->specifiesColumns()) {
2027 if (child->style()->specifiesColumns())
2028 newStyle->inheritColumnPropertiesFrom(style());
2029 if (child->style()->columnSpan())
2030 newStyle->setColumnSpan(ColumnSpanAll);
2033 // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
2034 // they contain block descendants of relative or sticky positioned inlines.
2035 if (child->isInFlowPositioned() && toRenderBlock(child)->isAnonymousBlockContinuation())
2036 newStyle->setPosition(child->style()->position());
2038 child->setStyle(newStyle.release());
2042 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
2044 // Optimize the common case
2045 if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
2048 // Go through the new layers and addClients first, to avoid removing all clients of an image.
2049 for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
2050 if (currNew->image())
2051 currNew->image()->addClient(this);
2054 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2055 if (currOld->image())
2056 currOld->image()->removeClient(this);
2060 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2062 if (oldImage != newImage) {
2064 oldImage->removeClient(this);
2066 newImage->addClient(this);
2070 LayoutRect RenderObject::viewRect() const
2072 return view()->viewRect();
2075 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2077 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2078 mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2079 transformState.flatten();
2081 return transformState.lastPlanarPoint();
2084 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2086 TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2087 mapAbsoluteToLocalPoint(mode, transformState);
2088 transformState.flatten();
2090 return transformState.lastPlanarPoint();
2093 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2095 TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2096 mapAbsoluteToLocalPoint(mode, transformState);
2097 transformState.flatten();
2098 return transformState.lastPlanarQuad();
2101 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
2103 if (repaintContainer == this)
2106 RenderObject* o = parent();
2110 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2111 LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2112 if (mode & ApplyContainerFlip && o->isBox()) {
2113 if (o->style()->isFlippedBlocksWritingMode())
2114 transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2115 mode &= ~ApplyContainerFlip;
2118 LayoutSize columnOffset;
2119 o->adjustForColumns(columnOffset, roundedLayoutPoint(transformState.mappedPoint()));
2120 if (!columnOffset.isZero())
2121 transformState.move(columnOffset);
2123 if (o->hasOverflowClip())
2124 transformState.move(-toRenderBox(o)->scrolledContentOffset());
2126 o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2129 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2131 ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
2133 RenderObject* container = parent();
2137 // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2139 if (container->hasOverflowClip())
2140 offset = -toRenderBox(container)->scrolledContentOffset();
2142 geometryMap.push(this, offset, hasColumns());
2147 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2149 RenderObject* o = parent();
2151 o->mapAbsoluteToLocalPoint(mode, transformState);
2152 if (o->hasOverflowClip())
2153 transformState.move(toRenderBox(o)->scrolledContentOffset());
2157 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
2159 #if ENABLE(3D_RENDERING)
2160 // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2161 // so check the layer's transform directly.
2162 return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2164 UNUSED_PARAM(containerObject);
2165 return hasTransform();
2169 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2171 transform.makeIdentity();
2172 transform.translate(offsetInContainer.width(), offsetInContainer.height());
2174 if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
2175 transform.multiply(layer->currentTransform());
2177 #if ENABLE(3D_RENDERING)
2178 if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2179 // Perpsective on the container affects us, so we have to factor it in here.
2180 ASSERT(containerObject->hasLayer());
2181 FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
2183 TransformationMatrix perspectiveMatrix;
2184 perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2186 transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2187 transform = perspectiveMatrix * transform;
2188 transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2191 UNUSED_PARAM(containerObject);
2195 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2197 // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2198 // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2199 TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2200 mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2201 transformState.flatten();
2203 return transformState.lastPlanarQuad();
2206 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2208 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2209 mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2210 transformState.flatten();
2212 return transformState.lastPlanarPoint();
2215 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2217 ASSERT(o == container());
2221 o->adjustForColumns(offset, point);
2223 if (o->hasOverflowClip())
2224 offset -= toRenderBox(o)->scrolledContentOffset();
2226 if (offsetDependsOnPoint)
2227 *offsetDependsOnPoint = hasColumns();
2232 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
2235 LayoutPoint referencePoint;
2236 const RenderObject* currContainer = this;
2238 RenderObject* nextContainer = currContainer->container();
2239 ASSERT(nextContainer); // This means we reached the top without finding container.
2242 ASSERT(!currContainer->hasTransform());
2243 LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2244 offset += currentOffset;
2245 referencePoint.move(currentOffset);
2246 currContainer = nextContainer;
2247 } while (currContainer != container);
2252 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2254 if (extraWidthToEndOfLine)
2255 *extraWidthToEndOfLine = 0;
2257 return LayoutRect();
2260 bool RenderObject::isRooted(RenderView** view) const
2262 const RenderObject* o = this;
2266 if (!o->isRenderView())
2270 *view = const_cast<RenderView*>(toRenderView(o));
2275 RenderObject* RenderObject::rendererForRootBackground()
2278 if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
2279 // Locate the <body> element using the DOM. This is easier than trying
2280 // to crawl around a render tree with potential :before/:after content and
2281 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
2282 // render object very easily via the DOM.
2283 HTMLElement* body = document()->body();
2284 RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
2292 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
2294 // Respect the image's orientation if it's being used as a full-page image or it's
2295 // an <img> and the setting to respect it everywhere is set.
2297 #if USE(CG) || PLATFORM(CHROMIUM) || USE(CAIRO) || PLATFORM(BLACKBERRY)
2298 // This can only be enabled for ports which honor the orientation flag in their drawing code.
2299 document()->isImageDocument() ||
2301 (document()->settings() && document()->settings()->shouldRespectImageOrientation() && node() && node()->hasTagName(HTMLNames::imgTag)) ? RespectImageOrientation : DoNotRespectImageOrientation;
2304 bool RenderObject::hasOutlineAnnotation() const
2306 return node() && node()->isLink() && document()->printing();
2309 bool RenderObject::hasEntirelyFixedBackground() const
2311 return m_style->hasEntirelyFixedBackground();
2314 RenderObject* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
2316 if (repaintContainerSkipped)
2317 *repaintContainerSkipped = false;
2319 // This method is extremely similar to containingBlock(), but with a few notable
2321 // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2322 // the object is not part of the primary document subtree yet.
2323 // (2) For normal flow elements, it just returns the parent.
2324 // (3) For absolute positioned elements, it will return a relative positioned inline.
2325 // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2326 // the layout of the positioned object. This does mean that computePositionedLogicalWidth and
2327 // computePositionedLogicalHeight have to use container().
2328 RenderObject* o = parent();
2333 EPosition pos = m_style->position();
2334 if (pos == FixedPosition) {
2335 // container() can be called on an object that is not in the
2336 // tree yet. We don't call view() since it will assert if it
2337 // can't get back to the canvas. Instead we just walk as high up
2338 // as we can. If we're in the tree, we'll get the root. If we
2339 // aren't we'll get the root of our little subtree (most likely
2340 // we'll just return 0).
2341 // FIXME: The definition of view() has changed to not crawl up the render tree. It might
2342 // be safe now to use it.
2343 while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
2345 // foreignObject is the containing block for its contents.
2346 if (o->isSVGForeignObject())
2349 // The render flow thread is the top most containing block
2350 // for the fixed positioned elements.
2351 if (o->isOutOfFlowRenderFlowThread())
2354 if (repaintContainerSkipped && o == repaintContainer)
2355 *repaintContainerSkipped = true;
2359 } else if (pos == AbsolutePosition) {
2360 // Same goes here. We technically just want our containing block, but
2361 // we may not have one if we're part of an uninstalled subtree. We'll
2362 // climb as high as we can though.
2363 while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
2365 if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
2368 if (repaintContainerSkipped && o == repaintContainer)
2369 *repaintContainerSkipped = true;
2378 bool RenderObject::isSelectionBorder() const
2380 SelectionState st = selectionState();
2381 return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2384 inline void RenderObject::clearLayoutRootIfNeeded() const
2386 if (!documentBeingDestroyed() && frame()) {
2387 if (FrameView* view = frame()->view()) {
2388 if (view->layoutRoot() == this) {
2389 ASSERT_NOT_REACHED();
2390 // This indicates a failure to layout the child, which is why
2391 // the layout root is still set to |this|. Make sure to clear it
2392 // since we are getting destroyed.
2393 view->clearLayoutRoot();
2399 void RenderObject::willBeDestroyed()
2401 // Destroy any leftover anonymous children.
2402 RenderObjectChildList* children = virtualChildren();
2404 children->destroyLeftoverChildren();
2406 // If this renderer is being autoscrolled, stop the autoscroll timer
2408 // FIXME: RenderObject::destroy should not get called with a renderer whose document
2409 // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
2410 // check that the frame is not null.
2412 if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
2413 frame()->eventHandler()->stopAutoscrollTimer(true);
2415 animation()->cancelAnimations(this);
2417 // For accessibility management, notify the parent of the imminent change to its child set.
2418 // We do it now, before remove(), while the parent pointer is still available.
2419 if (AXObjectCache* cache = document()->existingAXObjectCache())
2420 cache->childrenChanged(this->parent());
2424 // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
2425 // object for this renderer. So we remove the AX render object now, after the renderer is removed.
2426 if (AXObjectCache* cache = document()->existingAXObjectCache())
2427 cache->remove(this);
2430 if (!documentBeingDestroyed() && view() && view()->hasRenderNamedFlowThreads()) {
2431 // After remove, the object and the associated information should not be in any flow thread.
2432 const RenderNamedFlowThreadList* flowThreadList = view()->flowThreadController()->renderNamedFlowThreadList();
2433 for (RenderNamedFlowThreadList::const_iterator iter = flowThreadList->begin(); iter != flowThreadList->end(); ++iter) {
2434 const RenderNamedFlowThread* renderFlowThread = *iter;
2435 ASSERT(!renderFlowThread->hasChild(this));
2436 ASSERT(!renderFlowThread->hasChildInfo(this));
2441 // If this renderer had a parent, remove should have destroyed any counters
2442 // attached to this renderer and marked the affected other counters for
2443 // reevaluation. This apparently redundant check is here for the case when
2444 // this renderer had no parent at the time remove() was called.
2446 if (hasCounterNodeMap())
2447 RenderCounter::destroyCounterNodes(this);
2449 // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
2450 // be moved into RenderBoxModelObject::destroy.
2453 toRenderLayerModelObject(this)->destroyLayer();
2456 setAncestorLineBoxDirty(false);
2458 clearLayoutRootIfNeeded();
2461 void RenderObject::insertedIntoTree()
2463 // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2465 // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2466 // and don't have a layer attached to ourselves.
2467 RenderLayer* layer = 0;
2468 if (firstChild() || hasLayer()) {
2469 layer = parent()->enclosingLayer();
2473 // If |this| is visible but this object was not, tell the layer it has some visible content
2474 // that needs to be drawn and layer visibility optimization can't be used
2475 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2477 layer = parent()->enclosingLayer();
2479 layer->setHasVisibleContent();
2482 if (!isFloating() && parent()->childrenInline())
2483 parent()->dirtyLinesFromChangedChild(this);
2485 if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
2486 containerFlowThread->addFlowChild(this);
2489 void RenderObject::willBeRemovedFromTree()
2491 // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2493 // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2494 RenderLayer* layer = 0;
2495 if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2496 if ((layer = parent()->enclosingLayer()))
2497 layer->dirtyVisibleContentStatus();
2500 // Keep our layer hierarchy updated.
2501 if (firstChild() || hasLayer()) {
2503 layer = parent()->enclosingLayer();
2504 removeLayers(layer);
2507 if (isOutOfFlowPositioned() && parent()->childrenInline())
2508 parent()->dirtyLinesFromChangedChild(this);
2510 removeFromRenderFlowThread();
2512 if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
2513 containerFlowThread->removeFlowChild(this);
2516 // Update cached boundaries in SVG renderers, if a child is removed.
2517 parent()->setNeedsBoundariesUpdate();
2521 void RenderObject::removeFromRenderFlowThread()
2523 if (flowThreadState() == NotInsideFlowThread)
2526 // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2527 // It's only until later when we actually destroy it and remove all the children from it.
2528 // Currently, that happens for firstLetter elements and list markers.
2529 // Pass in the flow thread so that we don't have to look it up for all the children.
2530 removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
2533 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
2535 if (const RenderObjectChildList* children = virtualChildren()) {
2536 for (RenderObject* child = children->firstChild(); child; child = child->nextSibling())
2537 child->removeFromRenderFlowThreadRecursive(renderFlowThread);
2540 RenderFlowThread* localFlowThread = renderFlowThread;
2541 if (flowThreadState() == InsideInFlowThread)
2542 localFlowThread = flowThreadContainingBlock(); // We have to ask. We can't just assume we are in the same flow thread.
2543 if (localFlowThread)
2544 localFlowThread->removeFlowChildInfo(this);
2545 setFlowThreadState(NotInsideFlowThread);
2548 void RenderObject::destroyAndCleanupAnonymousWrappers()
2550 // If the tree is destroyed, there is no need for a clean-up phase.
2551 if (documentBeingDestroyed()) {
2556 RenderObject* destroyRoot = this;
2557 for (RenderObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2558 // Currently we only remove anonymous cells' wrapper but we should remove all unneeded
2559 // wrappers. See http://webkit.org/b/52123 as an example where this is needed.
2560 if (!destroyRootParent->isTableCell())
2563 if (destroyRootParent->firstChild() != this || destroyRootParent->lastChild() != this)
2567 destroyRoot->destroy();
2569 // WARNING: |this| is deleted here.
2572 void RenderObject::destroy()
2575 arenaDelete(renderArena(), this);
2578 void RenderObject::arenaDelete(RenderArena* arena, void* base)
2581 for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2582 if (StyleImage* backgroundImage = bgLayer->image())
2583 backgroundImage->removeClient(this);
2586 for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2587 if (StyleImage* maskImage = maskLayer->image())
2588 maskImage->removeClient(this);
2591 if (StyleImage* borderImage = m_style->borderImage().image())
2592 borderImage->removeClient(this);
2594 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2595 maskBoxImage->removeClient(this);
2599 void* savedBase = baseOfRenderObjectBeingDeleted;
2600 baseOfRenderObjectBeingDeleted = base;
2604 baseOfRenderObjectBeingDeleted = savedBase;
2607 // Recover the size left there for us by operator delete and free the memory.
2608 arena->free(*(size_t*)base, base);
2611 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&)
2613 return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2616 void RenderObject::updateDragState(bool dragOn)
2618 bool valueChanged = (dragOn != isDragging());
2619 setIsDragging(dragOn);
2620 if (valueChanged && node() && (style()->affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())))
2621 node()->setNeedsStyleRecalc();
2622 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2623 curr->updateDragState(dragOn);
2626 bool RenderObject::isComposited() const
2628 return hasLayer() && toRenderLayerModelObject(this)->layer()->isComposited();
2631 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2633 bool inside = false;
2634 if (hitTestFilter != HitTestSelf) {
2635 // First test the foreground layer (lines and inlines).
2636 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
2638 // Test floats next.
2640 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2642 // Finally test to see if the mouse is in the background (within a child block's background).
2644 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2647 // See if the mouse is inside us but not any of our descendants
2648 if (hitTestFilter != HitTestDescendants && !inside)
2649 inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2654 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2656 if (result.innerNode())
2659 Node* node = this->node();
2661 // If we hit the anonymous renderers inside generated content we should
2662 // actually hit the generated content so walk up to the PseudoElement.
2663 if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2664 for (RenderObject* renderer = parent(); renderer && !node; renderer = renderer->parent())
2665 node = renderer->node();
2669 result.setInnerNode(node);
2670 if (!result.innerNonSharedNode())
2671 result.setInnerNonSharedNode(node);
2672 result.setLocalPoint(point);
2676 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2681 void RenderObject::scheduleRelayout()
2683 if (isRenderView()) {
2684 FrameView* view = toRenderView(this)->frameView();
2686 view->scheduleRelayout();
2689 if (RenderView* renderView = view()) {
2690 if (FrameView* frameView = renderView->frameView())
2691 frameView->scheduleRelayoutOfSubtree(this);
2697 void RenderObject::layout()
2699 StackStats::LayoutCheckPoint layoutCheckPoint;
2700 ASSERT(needsLayout());
2701 RenderObject* child = firstChild();
2703 child->layoutIfNeeded();
2704 ASSERT(!child->needsLayout());
2705 child = child->nextSibling();
2707 setNeedsLayout(false);
2710 enum StyleCacheState {
2715 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderObject* renderer, RenderStyle* style)
2717 const RenderObject* rendererForFirstLineStyle = renderer;
2718 if (renderer->isBeforeOrAfterContent())
2719 rendererForFirstLineStyle = renderer->parent();
2721 if (rendererForFirstLineStyle->isBlockFlow()) {
2722 if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
2724 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2725 return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == renderer ? style : 0);
2727 } else if (!rendererForFirstLineStyle->isAnonymous() && rendererForFirstLineStyle->isRenderInline()) {
2728 RenderStyle* parentStyle = rendererForFirstLineStyle->parent()->firstLineStyle();
2729 if (parentStyle != rendererForFirstLineStyle->parent()->style()) {
2730 if (type == Cached) {
2731 // A first-line style is in effect. Cache a first-line style for ourselves.
2732 rendererForFirstLineStyle->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2733 return rendererForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2735 return rendererForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
2741 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2743 if (!document()->styleSheetCollection()->usesFirstLineRules())
2748 return firstLineStyleForCachedUncachedType(Uncached, this, style);
2751 RenderStyle* RenderObject::cachedFirstLineStyle() const
2753 ASSERT(document()->styleSheetCollection()->usesFirstLineRules());
2755 if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
2758 return m_style.get();
2761 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2763 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2766 RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2770 RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2772 return style()->addCachedPseudoStyle(result.release());
2776 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2778 if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
2783 parentStyle = style();
2786 // FIXME: This "find nearest element parent" should be a helper function.
2788 while (n && !n->isElementNode())
2789 n = n->parentNode();
2792 Element* element = toElement(n);
2794 if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2795 RefPtr<RenderStyle> result = document()->styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing);
2796 result->setStyleType(FIRST_LINE_INHERITED);
2797 return result.release();
2800 return document()->styleResolver()->pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2803 static Color decorationColor(RenderStyle* style)
2806 #if ENABLE(CSS3_TEXT)
2807 // Check for text decoration color first.
2808 result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
2809 if (result.isValid())
2812 if (style->textStrokeWidth() > 0) {
2813 // Prefer stroke color if possible but not if it's fully transparent.
2814 result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2819 result = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2823 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2824 Color& linethrough, bool quirksMode, bool firstlineStyle)
2826 RenderObject* curr = this;
2827 RenderStyle* styleToUse = 0;
2828 ETextDecoration currDecs = TDNONE;
2831 styleToUse = curr->style(firstlineStyle);
2832 currDecs = styleToUse->textDecoration();
2833 resultColor = decorationColor(styleToUse);
2834 // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2836 if (currDecs & UNDERLINE) {
2837 decorations &= ~UNDERLINE;
2838 underline = resultColor;
2840 if (currDecs & OVERLINE) {
2841 decorations &= ~OVERLINE;
2842 overline = resultColor;
2844 if (currDecs & LINE_THROUGH) {
2845 decorations &= ~LINE_THROUGH;
2846 linethrough = resultColor;
2849 if (curr->isRubyText())
2851 curr = curr->parent();
2852 if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2853 curr = toRenderBlock(curr)->continuation();
2854 } while (curr && decorations && (!quirksMode || !curr->node() ||
2855 (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
2857 // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2858 if (decorations && curr) {
2859 styleToUse = curr->style(firstlineStyle);
2860 resultColor = decorationColor(styleToUse);
2861 if (decorations & UNDERLINE)
2862 underline = resultColor;
2863 if (decorations & OVERLINE)
2864 overline = resultColor;
2865 if (decorations & LINE_THROUGH)
2866 linethrough = resultColor;
2870 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2871 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2873 // Convert the style regions to absolute coordinates.
2874 if (style()->visibility() != VISIBLE || !isBox())
2877 RenderBox* box = toRenderBox(this);
2878 FloatPoint absPos = localToAbsolute();
2880 #if ENABLE(DASHBOARD_SUPPORT)
2881 const Vector<StyleDashboardRegion>& styleRegions = style()->dashboardRegions();
2882 unsigned i, count = styleRegions.size();
2883 for (i = 0; i < count; i++) {
2884 StyleDashboardRegion styleRegion = styleRegions[i];
2886 LayoutUnit w = box->width();
2887 LayoutUnit h = box->height();
2889 AnnotatedRegionValue region;
2890 region.label = styleRegion.label;
2891 region.bounds = LayoutRect(styleRegion.offset.left().value(),
2892 styleRegion.offset.top().value(),
2893 w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2894 h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2895 region.type = styleRegion.type;
2897 region.clip = region.bounds;
2898 computeAbsoluteRepaintRect(region.clip);
2899 if (region.clip.height() < 0) {
2900 region.clip.setHeight(0);
2901 region.clip.setWidth(0);
2904 region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2905 region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2907 regions.append(region);
2909 #else // ENABLE(DRAGGABLE_REGION)
2910 if (style()->getDraggableRegionMode() == DraggableRegionNone)
2912 AnnotatedRegionValue region;
2913 region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
2914 region.bounds = LayoutRect(absPos.x(), absPos.y(), box->width(), box->height());
2915 regions.append(region);
2919 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2921 // RenderTexts don't have their own style, they just use their parent's style,
2922 // so we don't want to include them.
2926 addAnnotatedRegions(regions);
2927 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2928 curr->collectAnnotatedRegions(regions);
2932 bool RenderObject::willRenderImage(CachedImage*)
2934 // Without visibility we won't render (and therefore don't care about animation).
2935 if (style()->visibility() != VISIBLE)
2938 // We will not render a new image when Active DOM is suspended
2939 if (document()->activeDOMObjectsAreSuspended())
2942 // If we're not in a window (i.e., we're dormant from being put in the b/f cache or in a background tab)
2943 // then we don't want to render either.
2944 return !document()->inPageCache() && !document()->view()->isOffscreen();
2947 int RenderObject::maximalOutlineSize(PaintPhase p) const
2949 if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2951 return view()->maximalOutlineSize();
2954 int RenderObject::caretMinOffset() const
2959 int RenderObject::caretMaxOffset() const
2962 return node() ? max(1U, node()->childNodeCount()) : 1;
2968 int RenderObject::previousOffset(int current) const
2973 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2978 int RenderObject::nextOffset(int current) const
2983 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
2985 int outlineSize = outlineStyleForRepaint()->outlineSize();
2986 if (const ShadowData* boxShadow = style()->boxShadow()) {
2987 boxShadow->adjustRectForShadow(rect, outlineSize);
2991 rect.inflate(outlineSize);
2994 AnimationController* RenderObject::animation() const
2996 return frame()->animation();
2999 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
3001 imageChanged(static_cast<WrappedImagePtr>(image), rect);
3004 Element* RenderObject::offsetParent() const
3006 if (isRoot() || isBody())
3009 if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
3012 // If A is an area HTML element which has a map HTML element somewhere in the ancestor
3013 // chain return the nearest ancestor map HTML element and stop this algorithm.
3014 // FIXME: Implement!
3016 // FIXME: Figure out the right behavior for elements inside a flow thread.
3017 // https://bugs.webkit.org/show_bug.cgi?id=113276
3019 float effectiveZoom = style()->effectiveZoom();
3021 for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
3022 node = ancestor->node();
3024 // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
3029 if (ancestor->isPositioned())
3032 if (node->hasTagName(HTMLNames::bodyTag))
3035 if (!isPositioned() && (node->hasTagName(tableTag) || node->hasTagName(tdTag) || node->hasTagName(thTag)))
3038 // Webkit specific extension where offsetParent stops at zoom level changes.
3039 if (effectiveZoom != ancestor->style()->effectiveZoom())
3043 return node && node->isElementNode() ? toElement(node) : 0;
3046 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity)
3048 // If this is a non-anonymous renderer in an editable area, then it's simple.
3049 if (Node* node = nonPseudoNode()) {
3050 if (!node->rendererIsEditable()) {
3051 // If it can be found, we prefer a visually equivalent position that is editable.
3052 Position position = createLegacyEditingPosition(node, offset);
3053 Position candidate = position.downstream(CanCrossEditingBoundary);
3054 if (candidate.deprecatedNode()->rendererIsEditable())
3055 return VisiblePosition(candidate, affinity);
3056 candidate = position.upstream(CanCrossEditingBoundary);
3057 if (candidate.deprecatedNode()->rendererIsEditable())
3058 return VisiblePosition(candidate, affinity);
3060 // FIXME: Eliminate legacy editing positions
3061 return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
3064 // We don't want to cross the boundary between editable and non-editable
3065 // regions of the document, but that is either impossible or at least
3066 // extremely unlikely in any normal case because we stop as soon as we
3067 // find a single non-anonymous renderer.
3069 // Find a nearby non-anonymous renderer.
3070 RenderObject* child = this;
3071 while (RenderObject* parent = child->parent()) {
3072 // Find non-anonymous content after.
3073 RenderObject* renderer = child;
3074 while ((renderer = renderer->nextInPreOrder(parent))) {
3075 if (Node* node = renderer->nonPseudoNode())
3076 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3079 // Find non-anonymous content before.
3081 while ((renderer = renderer->previousInPreOrder())) {
3082 if (renderer == parent)
3084 if (Node* node = renderer->nonPseudoNode())
3085 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
3088 // Use the parent itself unless it too is anonymous.
3089 if (Node* node = parent->nonPseudoNode())
3090 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3092 // Repeat at the next level up.
3096 // Everything was anonymous. Give up.
3097 return VisiblePosition();
3100 VisiblePosition RenderObject::createVisiblePosition(const Position& position)
3102 if (position.isNotNull())
3103 return VisiblePosition(position);
3106 return createVisiblePosition(0, DOWNSTREAM);
3109 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
3111 return SetCursorBasedOnStyle;
3114 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
3119 RenderBlock* containingBlock = this->containingBlock();
3120 return containingBlock ? !containingBlock->needsLayout() : true;
3123 // We only create "generated" child renderers like one for first-letter if:
3124 // - the firstLetterBlock can have children in the DOM and
3125 // - the block doesn't have any special assumption on its text children.
3126 // This correctly prevents form controls from having such renderers.
3127 bool RenderObject::canHaveGeneratedChildren() const
3129 return canHaveChildren();
3132 bool RenderObject::canBeReplacedWithInlineRunIn() const
3137 void RenderObject::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3139 MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Rendering);
3140 info.addMember(m_style, "style");
3141 info.addWeakPointer(m_node);
3142 info.addWeakPointer(m_parent);
3143 info.addWeakPointer(m_previous);
3144 info.addWeakPointer(m_next);
3146 info.setCustomAllocation(true);
3151 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
3153 ASSERT_NOT_REACHED();
3157 void RenderObject::setNeedsBoundariesUpdate()
3159 if (RenderObject* renderer = parent())
3160 renderer->setNeedsBoundariesUpdate();
3163 FloatRect RenderObject::objectBoundingBox() const
3165 ASSERT_NOT_REACHED();
3169 FloatRect RenderObject::strokeBoundingBox() const
3171 ASSERT_NOT_REACHED();
3175 // Returns the smallest rectangle enclosing all of the painted content
3176 // respecting clipping, masking, filters, opacity, stroke-width and markers
3177 FloatRect RenderObject::repaintRectInLocalCoordinates() const
3179 ASSERT_NOT_REACHED();
3183 AffineTransform RenderObject::localTransform() const
3185 static const AffineTransform identity;
3189 const AffineTransform& RenderObject::localToParentTransform() const
3191 static const AffineTransform identity;
3195 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
3197 ASSERT_NOT_REACHED();
3201 #endif // ENABLE(SVG)
3203 } // namespace WebCore
3207 void showTree(const WebCore::RenderObject* object)
3210 object->showTreeForThis();
3213 void showLineTree(const WebCore::RenderObject* object)
3216 object->showLineTreeForThis();
3219 void showRenderTree(const WebCore::RenderObject* object1)
3221 showRenderTree(object1, 0);
3224 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
3227 const WebCore::RenderObject* root = object1;
3228 while (root->parent())
3229 root = root->parent();
3230 root->showRenderTreeAndMark(object1, "*", object2, "-", 0);