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"
31 #include "CSSStyleSelector.h"
33 #include "ContentData.h"
34 #include "CursorList.h"
35 #include "DashArray.h"
36 #include "EditingBoundary.h"
37 #include "FloatQuad.h"
39 #include "FrameView.h"
40 #include "GraphicsContext.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
44 #include "RenderArena.h"
45 #include "RenderCounter.h"
46 #include "RenderDeprecatedFlexibleBox.h"
47 #include "RenderFlexibleBox.h"
48 #include "RenderFlowThread.h"
49 #include "RenderImage.h"
50 #include "RenderImageResourceStyleImage.h"
51 #include "RenderInline.h"
52 #include "RenderLayer.h"
53 #include "RenderListItem.h"
54 #include "RenderRegion.h"
55 #include "RenderRuby.h"
56 #include "RenderRubyText.h"
57 #include "RenderTableCell.h"
58 #include "RenderTableCol.h"
59 #include "RenderTableRow.h"
60 #include "RenderTheme.h"
61 #include "RenderView.h"
62 #include "TransformState.h"
63 #include "htmlediting.h"
66 #include <wtf/RefCountedLeakCounter.h>
67 #include <wtf/UnusedParam.h>
69 #if USE(ACCELERATED_COMPOSITING)
70 #include "RenderLayerCompositor.h"
74 #include "RenderSVGResourceContainer.h"
75 #include "SVGRenderSupport.h"
82 using namespace HTMLNames;
85 static void* baseOfRenderObjectBeingDeleted;
88 bool RenderObject::s_affectsParentBlock = false;
90 void* RenderObject::operator new(size_t sz, RenderArena* renderArena) throw()
92 return renderArena->allocate(sz);
95 void RenderObject::operator delete(void* ptr, size_t sz)
97 ASSERT(baseOfRenderObjectBeingDeleted == ptr);
99 // Stash size where destroy can find it.
103 RenderObject* RenderObject::createObject(Node* node, RenderStyle* style)
105 Document* doc = node->document();
106 RenderArena* arena = doc->renderArena();
108 // Minimal support for content properties replacing an entire element.
109 // Works only if we have exactly one piece of content and it's a URL.
110 // Otherwise acts as if we didn't support this feature.
111 const ContentData* contentData = style->contentData();
112 if (contentData && !contentData->next() && contentData->isImage() && doc != node) {
113 RenderImage* image = new (arena) RenderImage(node);
114 image->setStyle(style);
115 if (const StyleImage* styleImage = static_cast<const ImageContentData*>(contentData)->image())
116 image->setImageResource(RenderImageResourceStyleImage::create(const_cast<StyleImage*>(styleImage)));
118 image->setImageResource(RenderImageResource::create());
122 if (node->hasTagName(rubyTag)) {
123 if (style->display() == INLINE)
124 return new (arena) RenderRubyAsInline(node);
125 else if (style->display() == BLOCK)
126 return new (arena) RenderRubyAsBlock(node);
128 // treat <rt> as ruby text ONLY if it still has its default treatment of block
129 if (node->hasTagName(rtTag) && style->display() == BLOCK)
130 return new (arena) RenderRubyText(node);
132 switch (style->display()) {
136 return new (arena) RenderInline(node);
141 // Only non-replaced block elements can become a region.
142 if (!style->regionThread().isEmpty() && doc->renderView())
143 return new (arena) RenderRegion(node, doc->renderView()->renderFlowThreadWithName(style->regionThread()));
144 return new (arena) RenderBlock(node);
146 return new (arena) RenderListItem(node);
149 return new (arena) RenderTable(node);
150 case TABLE_ROW_GROUP:
151 case TABLE_HEADER_GROUP:
152 case TABLE_FOOTER_GROUP:
153 return new (arena) RenderTableSection(node);
155 return new (arena) RenderTableRow(node);
156 case TABLE_COLUMN_GROUP:
158 return new (arena) RenderTableCol(node);
160 return new (arena) RenderTableCell(node);
163 // As per the section 17.1 of the spec WAP-239-WCSS-20011026-a.pdf,
164 // the marquee box inherits and extends the characteristics of the
165 // principal block box ([CSS2] section 9.2.1).
168 return new (arena) RenderBlock(node);
171 return new (arena) RenderDeprecatedFlexibleBox(node);
172 #if ENABLE(CSS3_FLEXBOX)
175 return new (arena) RenderFlexibleBox(node);
183 static WTF::RefCountedLeakCounter renderObjectCounter("RenderObject");
186 RenderObject::RenderObject(Node* node)
187 : CachedResourceClient()
194 , m_hasAXObject(false)
195 , m_setNeedsLayoutForbidden(false)
197 , m_needsLayout(false)
198 , m_needsPositionedMovementLayout(false)
199 , m_normalChildNeedsLayout(false)
200 , m_posChildNeedsLayout(false)
201 , m_needsSimplifiedNormalFlowLayout(false)
202 , m_preferredLogicalWidthsDirty(false)
204 , m_positioned(false)
205 , m_relPositioned(false)
206 , m_paintBackground(false)
207 , m_isAnonymous(node == node->document())
212 , m_horizontalWritingMode(true)
213 , m_isDragging(false)
215 , m_hasOverflowClip(false)
216 , m_hasTransform(false)
217 , m_hasReflection(false)
218 , m_hasCounterNodeMap(false)
219 , m_everHadLayout(false)
220 , m_childrenInline(false)
221 , m_marginBeforeQuirk(false)
222 , m_marginAfterQuirk(false)
223 , m_hasMarkupTruncation(false)
224 , m_selectionState(SelectionNone)
225 , m_hasColumns(false)
228 renderObjectCounter.increment();
233 RenderObject::~RenderObject()
235 ASSERT(!node() || documentBeingDestroyed() || !frame()->view() || frame()->view()->layoutRoot() != this);
237 ASSERT(!m_hasAXObject);
238 renderObjectCounter.decrement();
242 RenderTheme* RenderObject::theme() const
244 ASSERT(document()->page());
246 return document()->page()->theme();
249 bool RenderObject::isDescendantOf(const RenderObject* obj) const
251 for (const RenderObject* r = this; r; r = r->m_parent) {
258 bool RenderObject::isBody() const
260 return node() && node()->hasTagName(bodyTag);
263 bool RenderObject::isHR() const
265 return node() && node()->hasTagName(hrTag);
268 bool RenderObject::isLegend() const
270 return node() && node()->hasTagName(legendTag);
273 bool RenderObject::isHTMLMarquee() const
275 return node() && node()->renderer() == this && node()->hasTagName(marqueeTag);
278 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
280 RenderObjectChildList* children = virtualChildren();
285 bool needsTable = false;
287 if (newChild->isTableCol() && newChild->style()->display() == TABLE_COLUMN_GROUP)
288 needsTable = !isTable();
289 else if (newChild->isRenderBlock() && newChild->style()->display() == TABLE_CAPTION)
290 needsTable = !isTable();
291 else if (newChild->isTableSection())
292 needsTable = !isTable();
293 else if (newChild->isTableRow())
294 needsTable = !isTableSection();
295 else if (newChild->isTableCell()) {
296 needsTable = !isTableRow();
297 // I'm not 100% sure this is the best way to fix this, but without this
298 // change we recurse infinitely when trying to render the CSS2 test page:
299 // http://www.bath.ac.uk/%7Epy8ieh/internet/eviltests/htmlbodyheadrendering2.html.
300 // See Radar 2925291.
301 if (needsTable && isTableCell() && !children->firstChild() && !newChild->isTableCell())
307 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
308 if (afterChild && afterChild->isAnonymous() && afterChild->isTable())
309 table = toRenderTable(afterChild);
311 table = new (renderArena()) RenderTable(document() /* is anonymous */);
312 RefPtr<RenderStyle> newStyle = RenderStyle::create();
313 newStyle->inheritFrom(style());
314 newStyle->setDisplay(TABLE);
315 table->setStyle(newStyle.release());
316 addChild(table, beforeChild);
318 table->addChild(newChild);
321 children->insertChildNode(this, newChild, beforeChild);
323 if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE) {
324 RefPtr<StringImpl> textToTransform = toRenderText(newChild)->originalText();
326 toRenderText(newChild)->setText(textToTransform.release(), true);
330 void RenderObject::removeChild(RenderObject* oldChild)
332 RenderObjectChildList* children = virtualChildren();
337 // We do this here instead of in removeChildNode, since the only extremely low-level uses of remove/appendChildNode
338 // cannot affect the positioned object list, and the floating object list is irrelevant (since the list gets cleared on
340 if (oldChild->isFloatingOrPositioned())
341 toRenderBox(oldChild)->removeFloatingOrPositionedChildFromBlockLists();
343 children->removeChildNode(this, oldChild);
346 RenderObject* RenderObject::nextInPreOrder() const
348 if (RenderObject* o = firstChild())
351 return nextInPreOrderAfterChildren();
354 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
357 if (!(o = nextSibling())) {
359 while (o && !o->nextSibling())
362 o = o->nextSibling();
368 RenderObject* RenderObject::nextInPreOrder(RenderObject* stayWithin) const
370 if (RenderObject* o = firstChild())
373 return nextInPreOrderAfterChildren(stayWithin);
376 RenderObject* RenderObject::nextInPreOrderAfterChildren(RenderObject* stayWithin) const
378 if (this == stayWithin)
381 const RenderObject* current = this;
383 while (!(next = current->nextSibling())) {
384 current = current->parent();
385 if (!current || current == stayWithin)
391 RenderObject* RenderObject::previousInPreOrder() const
393 if (RenderObject* o = previousSibling()) {
394 while (o->lastChild())
402 RenderObject* RenderObject::childAt(unsigned index) const
404 RenderObject* child = firstChild();
405 for (unsigned i = 0; child && i < index; i++)
406 child = child->nextSibling();
410 RenderObject* RenderObject::firstLeafChild() const
412 RenderObject* r = firstChild();
423 RenderObject* RenderObject::lastLeafChild() const
425 RenderObject* r = lastChild();
436 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
437 RenderLayer*& beforeChild)
439 if (obj->hasLayer()) {
440 if (!beforeChild && newObject) {
441 // We need to figure out the layer that follows newObject. We only do
442 // this the first time we find a child layer, and then we update the
443 // pointer values for newObject and beforeChild used by everyone else.
444 beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
447 parentLayer->addChild(toRenderBoxModelObject(obj)->layer(), beforeChild);
451 for (RenderObject* curr = obj->firstChild(); curr; curr = curr->nextSibling())
452 addLayers(curr, parentLayer, newObject, beforeChild);
455 void RenderObject::addLayers(RenderLayer* parentLayer)
460 RenderObject* object = this;
461 RenderLayer* beforeChild = 0;
462 WebCore::addLayers(this, parentLayer, object, beforeChild);
465 void RenderObject::removeLayers(RenderLayer* parentLayer)
471 parentLayer->removeChild(toRenderBoxModelObject(this)->layer());
475 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
476 curr->removeLayers(parentLayer);
479 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
485 RenderLayer* layer = toRenderBoxModelObject(this)->layer();
486 ASSERT(oldParent == layer->parent());
488 oldParent->removeChild(layer);
489 newParent->addChild(layer);
493 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
494 curr->moveLayers(oldParent, newParent);
497 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
500 // Error check the parent layer passed in. If it's null, we can't find anything.
504 // Step 1: If our layer is a child of the desired parent, then return our layer.
505 RenderLayer* ourLayer = hasLayer() ? toRenderBoxModelObject(this)->layer() : 0;
506 if (ourLayer && ourLayer->parent() == parentLayer)
509 // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
510 // into our siblings trying to find the next layer whose parent is the desired parent.
511 if (!ourLayer || ourLayer == parentLayer) {
512 for (RenderObject* curr = startPoint ? startPoint->nextSibling() : firstChild();
513 curr; curr = curr->nextSibling()) {
514 RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
520 // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
522 if (parentLayer == ourLayer)
525 // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
526 // follow us to see if we can locate a layer.
527 if (checkParent && parent())
528 return parent()->findNextLayer(parentLayer, this, true);
533 RenderLayer* RenderObject::enclosingLayer() const
535 const RenderObject* curr = this;
537 RenderLayer* layer = curr->hasLayer() ? toRenderBoxModelObject(curr)->layer() : 0;
540 curr = curr->parent();
545 RenderBox* RenderObject::enclosingBox() const
547 RenderObject* curr = const_cast<RenderObject*>(this);
550 return toRenderBox(curr);
551 curr = curr->parent();
554 ASSERT_NOT_REACHED();
558 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
560 RenderObject* curr = const_cast<RenderObject*>(this);
562 if (curr->isBoxModelObject())
563 return toRenderBoxModelObject(curr);
564 curr = curr->parent();
567 ASSERT_NOT_REACHED();
571 RenderFlowThread* RenderObject::enclosingRenderFlowThread() const
573 RenderObject* curr = const_cast<RenderObject*>(this);
575 if (curr->isRenderFlowThread())
576 return toRenderFlowThread(curr);
577 curr = curr->parent();
582 RenderBlock* RenderObject::firstLineBlock() const
587 void RenderObject::setPreferredLogicalWidthsDirty(bool b, bool markParents)
589 bool alreadyDirty = m_preferredLogicalWidthsDirty;
590 m_preferredLogicalWidthsDirty = b;
591 if (b && !alreadyDirty && markParents && (isText() || (style()->position() != FixedPosition && style()->position() != AbsolutePosition)))
592 invalidateContainerPreferredLogicalWidths();
595 void RenderObject::invalidateContainerPreferredLogicalWidths()
597 // In order to avoid pathological behavior when inlines are deeply nested, we do include them
598 // in the chain that we mark dirty (even though they're kind of irrelevant).
599 RenderObject* o = isTableCell() ? containingBlock() : container();
600 while (o && !o->m_preferredLogicalWidthsDirty) {
601 // Don't invalidate the outermost object of an unrooted subtree. That object will be
602 // invalidated when the subtree is added to the document.
603 RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
604 if (!container && !o->isRenderView())
607 o->m_preferredLogicalWidthsDirty = true;
608 if (o->style()->position() == FixedPosition || o->style()->position() == AbsolutePosition)
609 // A positioned object has no effect on the min/max width of its containing block ever.
610 // We can optimize this case and not go up any further.
616 void RenderObject::setLayerNeedsFullRepaint()
619 toRenderBoxModelObject(this)->layer()->setNeedsFullRepaint(true);
622 RenderBlock* RenderObject::containingBlock() const
624 ASSERT(!isTableCell());
625 ASSERT(!isRenderView());
627 RenderObject* o = parent();
628 if (!isText() && m_style->position() == FixedPosition) {
629 while (o && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock()))
631 } else if (!isText() && m_style->position() == AbsolutePosition) {
632 while (o && (o->style()->position() == StaticPosition || (o->isInline() && !o->isReplaced())) && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
633 // For relpositioned inlines, we return the nearest enclosing block. We don't try
634 // to return the inline itself. This allows us to avoid having a positioned objects
635 // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
636 // from this method. The container() method can actually be used to obtain the
638 if (o->style()->position() == RelativePosition && o->isInline() && !o->isReplaced())
639 return o->containingBlock();
641 if (o->isSVGForeignObject()) //foreignObject is the containing block for contents inside it
648 while (o && ((o->isInline() && !o->isReplaced()) || o->isTableRow() || o->isTableSection()
649 || o->isTableCol() || o->isFrameSet() || o->isMedia()
651 || o->isSVGContainer() || o->isSVGRoot()
657 if (!o || !o->isRenderBlock())
658 return 0; // This can still happen in case of an orphaned tree
660 return toRenderBlock(o);
663 static bool mustRepaintFillLayers(const RenderObject* renderer, const FillLayer* layer)
665 // Nobody will use multiple layers without wanting fancy positioning.
669 // Make sure we have a valid image.
670 StyleImage* img = layer->image();
671 if (!img || !img->canRender(renderer->style()->effectiveZoom()))
674 if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
677 if (layer->size().type == SizeLength) {
678 if (layer->size().size.width().isPercent() || layer->size().size.height().isPercent())
680 } else if (layer->size().type == Contain || layer->size().type == Cover || img->usesImageContainerSize())
686 bool RenderObject::borderImageIsLoadedAndCanBeRendered() const
688 ASSERT(style()->hasBorder());
690 StyleImage* borderImage = style()->borderImage().image();
691 return borderImage && borderImage->canRender(style()->effectiveZoom()) && borderImage->isLoaded();
694 bool RenderObject::mustRepaintBackgroundOrBorder() const
696 if (hasMask() && mustRepaintFillLayers(this, style()->maskLayers()))
699 // If we don't have a background/border/mask, then nothing to do.
700 if (!hasBoxDecorations())
703 if (mustRepaintFillLayers(this, style()->backgroundLayers()))
706 // Our fill layers are ok. Let's check border.
707 if (style()->hasBorder() && borderImageIsLoadedAndCanBeRendered())
713 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
714 BoxSide side, Color color, EBorderStyle style,
715 int adjacentWidth1, int adjacentWidth2, bool antialias)
717 int width = (side == BSTop || side == BSBottom ? y2 - y1 : x2 - x1);
719 if (style == DOUBLE && width < 3)
728 graphicsContext->setStrokeColor(color, m_style->colorSpace());
729 graphicsContext->setStrokeThickness(width);
730 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
731 graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
734 bool wasAntialiased = graphicsContext->shouldAntialias();
735 graphicsContext->setShouldAntialias(antialias);
740 graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
744 graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
747 graphicsContext->setShouldAntialias(wasAntialiased);
748 graphicsContext->setStrokeStyle(oldStrokeStyle);
753 int third = (width + 1) / 3;
755 if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
756 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
757 graphicsContext->setStrokeStyle(NoStroke);
758 graphicsContext->setFillColor(color, m_style->colorSpace());
760 bool wasAntialiased = graphicsContext->shouldAntialias();
761 graphicsContext->setShouldAntialias(antialias);
766 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, third));
767 graphicsContext->drawRect(IntRect(x1, y2 - third, x2 - x1, third));
770 graphicsContext->drawRect(IntRect(x1, y1 + 1, third, y2 - y1 - 1));
771 graphicsContext->drawRect(IntRect(x2 - third, y1 + 1, third, y2 - y1 - 1));
774 graphicsContext->drawRect(IntRect(x1, y1 + 1, third, y2 - y1 - 1));
775 graphicsContext->drawRect(IntRect(x2 - third, y1 + 1, third, y2 - y1 - 1));
779 graphicsContext->setShouldAntialias(wasAntialiased);
780 graphicsContext->setStrokeStyle(oldStrokeStyle);
782 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
783 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
787 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
788 y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + third,
789 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
790 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
791 y2 - third, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
792 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
795 drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
796 x1 + third, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
797 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
798 drawLineForBoxSide(graphicsContext, x2 - third, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
799 x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
800 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
803 drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
804 y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + third,
805 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
806 drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
807 y2 - third, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
808 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
811 drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
812 x1 + third, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
813 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
814 drawLineForBoxSide(graphicsContext, x2 - third, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
815 x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
816 side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
828 if (style == GROOVE) {
836 int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
837 int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
841 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
842 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
843 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
844 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
847 drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
848 side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
849 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
850 side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
853 drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
854 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
855 drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
856 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
859 drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
860 side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
861 drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
862 side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
868 // FIXME: Maybe we should lighten the colors on one side like Firefox.
869 // https://bugs.webkit.org/show_bug.cgi?id=58608
870 if (side == BSTop || side == BSLeft)
871 color = color.dark();
874 if (style == OUTSET && (side == BSBottom || side == BSRight))
875 color = color.dark();
878 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
879 graphicsContext->setStrokeStyle(NoStroke);
880 graphicsContext->setFillColor(color, m_style->colorSpace());
883 if (!adjacentWidth1 && !adjacentWidth2) {
884 // Turn off antialiasing to match the behavior of drawConvexPolygon();
885 // this matters for rects in transformed contexts.
886 bool wasAntialiased = graphicsContext->shouldAntialias();
887 graphicsContext->setShouldAntialias(antialias);
888 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
889 graphicsContext->setShouldAntialias(wasAntialiased);
890 graphicsContext->setStrokeStyle(oldStrokeStyle);
896 quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
897 quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
898 quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
899 quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
902 quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
903 quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
904 quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
905 quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
908 quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
909 quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
910 quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
911 quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
914 quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
915 quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
916 quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
917 quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
921 graphicsContext->drawConvexPolygon(4, quad, antialias);
922 graphicsContext->setStrokeStyle(oldStrokeStyle);
928 #if !HAVE(PATH_BASED_BORDER_RADIUS_DRAWING)
929 void RenderObject::drawArcForBoxSide(GraphicsContext* graphicsContext, int x, int y, float thickness, const IntSize& radius,
930 int angleStart, int angleSpan, BoxSide s, Color color,
931 EBorderStyle style, bool firstCorner)
933 // FIXME: This function should be removed when all ports implement GraphicsContext::clipConvexPolygon()!!
934 // At that time, everyone can use RenderObject::drawBoxSideFromPath() instead. This should happen soon.
935 if ((style == DOUBLE && thickness / 2 < 3) || ((style == RIDGE || style == GROOVE) && thickness / 2 < 2))
944 graphicsContext->setStrokeColor(color, m_style->colorSpace());
945 graphicsContext->setStrokeStyle(style == DOTTED ? DottedStroke : DashedStroke);
946 graphicsContext->setStrokeThickness(thickness);
947 graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
950 float third = thickness / 3.0f;
951 float innerThird = (thickness + 1.0f) / 6.0f;
952 int shiftForInner = static_cast<int>(innerThird * 2.5f);
955 int outerHeight = radius.height() * 2;
956 int innerX = x + shiftForInner;
957 int innerY = y + shiftForInner;
958 int innerWidth = (radius.width() - shiftForInner) * 2;
959 int innerHeight = (radius.height() - shiftForInner) * 2;
960 if (innerThird > 1 && (s == BSTop || (firstCorner && (s == BSLeft || s == BSRight)))) {
965 graphicsContext->setStrokeStyle(SolidStroke);
966 graphicsContext->setStrokeColor(color, m_style->colorSpace());
967 graphicsContext->setStrokeThickness(third);
968 graphicsContext->strokeArc(IntRect(x, outerY, radius.width() * 2, outerHeight), angleStart, angleSpan);
969 graphicsContext->setStrokeThickness(innerThird > 2 ? innerThird - 1 : innerThird);
970 graphicsContext->strokeArc(IntRect(innerX, innerY, innerWidth, innerHeight), angleStart, angleSpan);
976 if ((style == RIDGE && (s == BSTop || s == BSLeft)) ||
977 (style == GROOVE && (s == BSBottom || s == BSRight)))
981 color = color.dark();
984 graphicsContext->setStrokeStyle(SolidStroke);
985 graphicsContext->setStrokeColor(color, m_style->colorSpace());
986 graphicsContext->setStrokeThickness(thickness);
987 graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
989 float halfThickness = (thickness + 1.0f) / 4.0f;
990 int shiftForInner = static_cast<int>(halfThickness * 1.5f);
991 graphicsContext->setStrokeColor(c2, m_style->colorSpace());
992 graphicsContext->setStrokeThickness(halfThickness > 2 ? halfThickness - 1 : halfThickness);
993 graphicsContext->strokeArc(IntRect(x + shiftForInner, y + shiftForInner, (radius.width() - shiftForInner) * 2,
994 (radius.height() - shiftForInner) * 2), angleStart, angleSpan);
998 if (s == BSTop || s == BSLeft)
999 color = color.dark();
1001 if (style == OUTSET && (s == BSBottom || s == BSRight))
1002 color = color.dark();
1004 graphicsContext->setStrokeStyle(SolidStroke);
1005 graphicsContext->setStrokeColor(color, m_style->colorSpace());
1006 graphicsContext->setStrokeThickness(thickness);
1007 graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
1013 void RenderObject::paintFocusRing(GraphicsContext* context, const LayoutPoint& paintOffset, RenderStyle* style)
1015 Vector<LayoutRect> focusRingRects;
1016 addFocusRingRects(focusRingRects, paintOffset);
1017 if (style->outlineStyleIsAuto())
1018 context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
1020 addPDFURLRect(context, unionRect(focusRingRects));
1023 void RenderObject::addPDFURLRect(GraphicsContext* context, const IntRect& rect)
1028 if (!n || !n->isLink() || !n->isElementNode())
1030 const AtomicString& href = static_cast<Element*>(n)->getAttribute(hrefAttr);
1033 context->setURLForRect(n->document()->completeURL(href), rect);
1036 void RenderObject::paintOutline(GraphicsContext* graphicsContext, const LayoutRect& paintRect)
1041 RenderStyle* styleToUse = style();
1042 LayoutUnit outlineWidth = styleToUse->outlineWidth();
1043 EBorderStyle outlineStyle = styleToUse->outlineStyle();
1045 Color outlineColor = styleToUse->visitedDependentColor(CSSPropertyOutlineColor);
1047 LayoutUnit offset = styleToUse->outlineOffset();
1049 if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1050 if (!theme()->supportsFocusRing(styleToUse)) {
1051 // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1052 paintFocusRing(graphicsContext, paintRect.location(), styleToUse);
1056 if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1059 LayoutRect adjustedPaintRec = paintRect;
1060 adjustedPaintRec.inflate(offset);
1062 if (adjustedPaintRec.isEmpty())
1065 bool useTransparencyLayer = outlineColor.hasAlpha();
1066 if (useTransparencyLayer) {
1067 graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1068 outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1071 LayoutUnit leftOuter = adjustedPaintRec.x() - outlineWidth;
1072 LayoutUnit leftInner = adjustedPaintRec.x();
1073 LayoutUnit rightOuter = adjustedPaintRec.maxX() + outlineWidth;
1074 LayoutUnit rightInner = adjustedPaintRec.maxX();
1075 LayoutUnit topOuter = adjustedPaintRec.y() - outlineWidth;
1076 LayoutUnit topInner = adjustedPaintRec.y();
1077 LayoutUnit bottomOuter = adjustedPaintRec.maxY() + outlineWidth;
1078 LayoutUnit bottomInner = adjustedPaintRec.maxY();
1080 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1081 drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1082 drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1083 drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1085 if (useTransparencyLayer)
1086 graphicsContext->endTransparencyLayer();
1089 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms)
1091 if (useTransforms) {
1092 Vector<FloatQuad> quads;
1093 absoluteQuads(quads);
1095 size_t n = quads.size();
1099 IntRect result = quads[0].enclosingBoundingBox();
1100 for (size_t i = 1; i < n; ++i)
1101 result.unite(quads[i].enclosingBoundingBox());
1105 FloatPoint absPos = localToAbsolute();
1106 Vector<IntRect> rects;
1107 absoluteRects(rects, flooredLayoutPoint(absPos));
1109 size_t n = rects.size();
1113 IntRect result = rects[0];
1114 for (size_t i = 1; i < n; ++i)
1115 result.unite(rects[i]);
1119 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1121 Vector<IntRect> rects;
1122 // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1123 // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1124 // implicitly assumes that. This doesn't work correctly with transformed
1126 FloatPoint absolutePoint = localToAbsolute();
1127 addFocusRingRects(rects, flooredIntPoint(absolutePoint));
1128 size_t count = rects.size();
1129 for (size_t i = 0; i < count; ++i) {
1130 IntRect rect = rects[i];
1131 rect.move(-absolutePoint.x(), -absolutePoint.y());
1132 quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1136 void RenderObject::addAbsoluteRectForLayer(IntRect& result)
1139 result.unite(absoluteBoundingBoxRect());
1140 for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1141 current->addAbsoluteRectForLayer(result);
1144 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1146 LayoutRect result = absoluteBoundingBoxRect();
1147 topLevelRect = result;
1148 for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1149 current->addAbsoluteRectForLayer(result);
1153 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1157 RenderBoxModelObject* RenderObject::containerForRepaint() const
1159 RenderView* v = view();
1163 RenderBoxModelObject* repaintContainer = 0;
1165 #if USE(ACCELERATED_COMPOSITING)
1166 if (v->usesCompositing()) {
1167 RenderLayer* compLayer = enclosingLayer()->enclosingCompositingLayer();
1169 repaintContainer = compLayer->renderer();
1173 // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1174 // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1175 // repainting to do individual region repaints.
1176 // FIXME: Composited layers inside a flow thread will bypass this mechanism and will malfunction. It's not
1177 // clear how to address this problem for composited descendants of a RenderFlowThread.
1178 if (!repaintContainer && v->hasRenderFlowThreads())
1179 repaintContainer = enclosingRenderFlowThread();
1180 return repaintContainer;
1183 void RenderObject::repaintUsingContainer(RenderBoxModelObject* repaintContainer, const LayoutRect& r, bool immediate)
1185 if (!repaintContainer) {
1186 view()->repaintViewRectangle(r, immediate);
1190 if (repaintContainer->isRenderFlowThread())
1191 return toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r, immediate);
1193 #if USE(ACCELERATED_COMPOSITING)
1194 RenderView* v = view();
1195 if (repaintContainer->isRenderView()) {
1196 ASSERT(repaintContainer == v);
1197 bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
1198 if (!viewHasCompositedLayer || v->layer()->backing()->paintingGoesToWindow()) {
1199 LayoutRect repaintRectangle = r;
1200 if (viewHasCompositedLayer && v->layer()->transform())
1201 repaintRectangle = v->layer()->transform()->mapRect(r);
1202 v->repaintViewRectangle(repaintRectangle, immediate);
1207 if (v->usesCompositing()) {
1208 ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1209 repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
1212 if (repaintContainer->isRenderView())
1213 toRenderView(repaintContainer)->repaintViewRectangle(r, immediate);
1217 void RenderObject::repaint(bool immediate)
1219 // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1221 if (!isRooted(&view))
1224 if (view->printing())
1225 return; // Don't repaint if we're printing.
1227 RenderBoxModelObject* repaintContainer = containerForRepaint();
1228 repaintUsingContainer(repaintContainer ? repaintContainer : view, clippedOverflowRectForRepaint(repaintContainer), immediate);
1231 void RenderObject::repaintRectangle(const LayoutRect& r, bool immediate)
1233 // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1235 if (!isRooted(&view))
1238 if (view->printing())
1239 return; // Don't repaint if we're printing.
1241 LayoutRect dirtyRect(r);
1243 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1244 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1245 dirtyRect.move(view->layoutDelta());
1247 RenderBoxModelObject* repaintContainer = containerForRepaint();
1248 computeRectForRepaint(repaintContainer, dirtyRect);
1249 repaintUsingContainer(repaintContainer ? repaintContainer : view, dirtyRect, immediate);
1252 bool RenderObject::repaintAfterLayoutIfNeeded(RenderBoxModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1254 RenderView* v = view();
1256 return false; // Don't repaint if we're printing.
1258 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1259 // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1260 LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1261 LayoutRect newOutlineBox;
1263 bool fullRepaint = selfNeedsLayout();
1264 // Presumably a background or a border exists if border-fit:lines was specified.
1265 if (!fullRepaint && style()->borderFit() == BorderFitLines)
1268 // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1269 // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1270 newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1271 if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder() && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1275 if (!repaintContainer)
1276 repaintContainer = v;
1279 repaintUsingContainer(repaintContainer, oldBounds);
1280 if (newBounds != oldBounds)
1281 repaintUsingContainer(repaintContainer, newBounds);
1285 if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1288 LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1290 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1291 else if (deltaLeft < 0)
1292 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1294 LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1296 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1297 else if (deltaRight < 0)
1298 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1300 LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1302 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1303 else if (deltaTop < 0)
1304 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1306 LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1307 if (deltaBottom > 0)
1308 repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1309 else if (deltaBottom < 0)
1310 repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1312 if (newOutlineBox == oldOutlineBox)
1315 // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1316 // two rectangles (but typically only one).
1317 RenderStyle* outlineStyle = outlineStyleForRepaint();
1318 LayoutUnit ow = outlineStyle->outlineSize();
1319 LayoutUnit width = abs(newOutlineBox.width() - oldOutlineBox.width());
1321 LayoutUnit shadowLeft;
1322 LayoutUnit shadowRight;
1323 style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1325 LayoutUnit borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1326 LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : 0;
1327 LayoutUnit borderWidth = max(-outlineStyle->outlineOffset(), max(borderRight, max(style()->borderTopRightRadius().width().calcValue(boxWidth), style()->borderBottomRightRadius().width().calcValue(boxWidth)))) + max(ow, shadowRight);
1328 LayoutRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - borderWidth,
1330 width + borderWidth,
1331 max(newOutlineBox.height(), oldOutlineBox.height()));
1332 LayoutUnit right = min(newBounds.maxX(), oldBounds.maxX());
1333 if (rightRect.x() < right) {
1334 rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1335 repaintUsingContainer(repaintContainer, rightRect);
1338 LayoutUnit height = abs(newOutlineBox.height() - oldOutlineBox.height());
1340 LayoutUnit shadowTop;
1341 LayoutUnit shadowBottom;
1342 style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1344 LayoutUnit borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1345 LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : 0;
1346 LayoutUnit borderHeight = max(-outlineStyle->outlineOffset(), max(borderBottom, max(style()->borderBottomLeftRadius().height().calcValue(boxHeight), style()->borderBottomRightRadius().height().calcValue(boxHeight)))) + max(ow, shadowBottom);
1347 LayoutRect bottomRect(newOutlineBox.x(),
1348 min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - borderHeight,
1349 max(newOutlineBox.width(), oldOutlineBox.width()),
1350 height + borderHeight);
1351 LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
1352 if (bottomRect.y() < bottom) {
1353 bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1354 repaintUsingContainer(repaintContainer, bottomRect);
1360 void RenderObject::repaintDuringLayoutIfMoved(const LayoutRect&)
1364 void RenderObject::repaintOverhangingFloats(bool)
1368 bool RenderObject::checkForRepaintDuringLayout() const
1370 // FIXME: <https://bugs.webkit.org/show_bug.cgi?id=20885> It is probably safe to also require
1371 // m_everHadLayout. Currently, only RenderBlock::layoutBlock() adds this condition. See also
1372 // <https://bugs.webkit.org/show_bug.cgi?id=15129>.
1373 return !document()->view()->needsFullRepaint() && !hasLayer();
1376 IntRect RenderObject::rectWithOutlineForRepaint(RenderBoxModelObject* repaintContainer, int outlineWidth) const
1378 IntRect r(clippedOverflowRectForRepaint(repaintContainer));
1379 r.inflate(outlineWidth);
1383 IntRect RenderObject::clippedOverflowRectForRepaint(RenderBoxModelObject*) const
1385 ASSERT_NOT_REACHED();
1389 void RenderObject::computeRectForRepaint(RenderBoxModelObject* repaintContainer, IntRect& rect, bool fixed) const
1391 if (repaintContainer == this)
1394 if (RenderObject* o = parent()) {
1395 if (o->isBlockFlow()) {
1396 RenderBlock* cb = toRenderBlock(o);
1397 if (cb->hasColumns())
1398 cb->adjustRectForColumns(rect);
1401 if (o->hasOverflowClip()) {
1402 // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1403 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1404 // anyway if its size does change.
1405 RenderBox* boxParent = toRenderBox(o);
1407 IntRect repaintRect(rect);
1408 repaintRect.move(-boxParent->layer()->scrolledContentOffset()); // For overflow:auto/scroll/hidden.
1410 IntRect boxRect(IntPoint(), boxParent->layer()->size());
1411 rect = intersection(repaintRect, boxRect);
1416 o->computeRectForRepaint(repaintContainer, rect, fixed);
1420 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1426 void RenderObject::showTreeForThis() const
1429 node()->showTreeForThis();
1432 void RenderObject::showRenderTreeForThis() const
1434 showRenderTree(this, 0);
1437 void RenderObject::showLineTreeForThis() const
1439 if (containingBlock())
1440 containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1443 void RenderObject::showRenderObject() const
1445 showRenderObject(0);
1448 void RenderObject::showRenderObject(int printedCharacters) const
1450 // As this function is intended to be used when debugging, the
1451 // this pointer may be 0.
1453 fputs("(null)\n", stderr);
1457 printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1460 if (printedCharacters)
1461 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1463 fputc('\t', stderr);
1466 fputc('\n', stderr);
1469 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1471 int printedCharacters = 0;
1472 if (markedObject1 == this && markedLabel1)
1473 printedCharacters += fprintf(stderr, "%s", markedLabel1);
1474 if (markedObject2 == this && markedLabel2)
1475 printedCharacters += fprintf(stderr, "%s", markedLabel2);
1476 for (; printedCharacters < depth * 2; printedCharacters++)
1479 showRenderObject(printedCharacters);
1483 for (const RenderObject* child = firstChild(); child; child = child->nextSibling())
1484 child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1489 Color RenderObject::selectionBackgroundColor() const
1492 if (style()->userSelect() != SELECT_NONE) {
1493 RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(SELECTION);
1494 if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1495 color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1497 color = frame()->selection()->isFocusedAndActive() ?
1498 theme()->activeSelectionBackgroundColor() :
1499 theme()->inactiveSelectionBackgroundColor();
1505 Color RenderObject::selectionColor(int colorProperty) const
1508 // If the element is unselectable, or we are only painting the selection,
1509 // don't override the foreground color with the selection foreground color.
1510 if (style()->userSelect() == SELECT_NONE
1511 || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1514 if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(SELECTION)) {
1515 color = pseudoStyle->visitedDependentColor(colorProperty);
1516 if (!color.isValid())
1517 color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1519 color = frame()->selection()->isFocusedAndActive() ?
1520 theme()->activeSelectionForegroundColor() :
1521 theme()->inactiveSelectionForegroundColor();
1526 Color RenderObject::selectionForegroundColor() const
1528 return selectionColor(CSSPropertyWebkitTextFillColor);
1531 Color RenderObject::selectionEmphasisMarkColor() const
1533 return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1536 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1538 view()->selectionStartEnd(spos, epos);
1541 void RenderObject::handleDynamicFloatPositionChange()
1543 // We have gone from not affecting the inline status of the parent flow to suddenly
1544 // having an impact. See if there is a mismatch between the parent flow's
1545 // childrenInline() state and our state.
1546 setInline(style()->isDisplayInlineType());
1547 if (isInline() != parent()->childrenInline()) {
1549 toRenderBoxModelObject(parent())->childBecameNonInline(this);
1551 // An anonymous block must be made to wrap this inline.
1552 RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1553 RenderObjectChildList* childlist = parent()->virtualChildren();
1554 childlist->insertChildNode(parent(), block, this);
1555 block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1560 void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
1562 if (!isText() && style)
1563 setStyle(animation()->updateAnimations(this, style.get()));
1568 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1570 #if USE(ACCELERATED_COMPOSITING)
1571 // If transform changed, and we are not composited, need to do a layout.
1572 if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1573 // Text nodes share style with their parents but transforms don't apply to them,
1574 // hence the !isText() check.
1575 // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
1576 if (!isText() && (!hasLayer() || !toRenderBoxModelObject(this)->layer()->isComposited())) {
1577 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
1578 // then we actually need SimplifiedLayoutAndPositionedMovement.
1580 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
1581 else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
1582 diff = StyleDifferenceSimplifiedLayout;
1583 else if (diff < StyleDifferenceSimplifiedLayout)
1584 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
1585 } else if (diff < StyleDifferenceRecompositeLayer)
1586 diff = StyleDifferenceRecompositeLayer;
1589 // If opacity changed, and we are not composited, need to repaint (also
1590 // ignoring text nodes)
1591 if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
1592 if (!isText() && (!hasLayer() || !toRenderBoxModelObject(this)->layer()->isComposited()))
1593 diff = StyleDifferenceRepaintLayer;
1594 else if (diff < StyleDifferenceRecompositeLayer)
1595 diff = StyleDifferenceRecompositeLayer;
1598 // The answer to requiresLayer() for plugins and iframes can change outside of the style system,
1599 // since it depends on whether we decide to composite these elements. When the layer status of
1600 // one of these elements changes, we need to force a layout.
1601 if (diff == StyleDifferenceEqual && style() && isBoxModelObject()) {
1602 if (hasLayer() != toRenderBoxModelObject(this)->requiresLayer())
1603 diff = StyleDifferenceLayout;
1606 UNUSED_PARAM(contextSensitiveProperties);
1609 // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
1610 if (diff == StyleDifferenceRepaintLayer && !hasLayer())
1611 diff = StyleDifferenceRepaint;
1616 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
1618 if (m_style == style) {
1619 #if USE(ACCELERATED_COMPOSITING)
1620 // We need to run through adjustStyleDifference() for iframes and plugins, so
1621 // style sharing is disabled for them. That should ensure that we never hit this code path.
1622 ASSERT(!isRenderIFrame() && !isEmbeddedObject() &&!isApplet());
1627 StyleDifference diff = StyleDifferenceEqual;
1628 unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
1630 diff = m_style->diff(style.get(), contextSensitiveProperties);
1632 diff = adjustStyleDifference(diff, contextSensitiveProperties);
1634 styleWillChange(diff, style.get());
1636 RefPtr<RenderStyle> oldStyle = m_style.release();
1639 updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
1640 updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
1642 updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
1643 updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
1645 // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
1646 // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
1647 if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
1648 toRenderView(document()->renderer())->setMaximalOutlineSize(m_style->outlineSize());
1650 styleDidChange(diff, oldStyle.get());
1652 if (!m_parent || isText())
1655 // Now that the layer (if any) has been updated, we need to adjust the diff again,
1656 // check whether we should layout now, and decide if we need to repaint.
1657 StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
1659 if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
1660 if (updatedDiff == StyleDifferenceLayout)
1661 setNeedsLayoutAndPrefWidthsRecalc();
1662 else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
1663 setNeedsPositionedMovementLayout();
1664 else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1665 setNeedsPositionedMovementLayout();
1666 setNeedsSimplifiedNormalFlowLayout();
1667 } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
1668 setNeedsSimplifiedNormalFlowLayout();
1671 if (updatedDiff == StyleDifferenceRepaintLayer || updatedDiff == StyleDifferenceRepaint) {
1672 // Do a repaint with the new style now, e.g., for example if we go from
1673 // not having an outline to having an outline.
1678 void RenderObject::setStyleInternal(PassRefPtr<RenderStyle> style)
1683 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1686 // If our z-index changes value or our visibility changes,
1687 // we need to dirty our stacking context's z-order list.
1689 bool visibilityChanged = m_style->visibility() != newStyle->visibility()
1690 || m_style->zIndex() != newStyle->zIndex()
1691 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1692 #if ENABLE(DASHBOARD_SUPPORT)
1693 if (visibilityChanged)
1694 document()->setDashboardRegionsDirty(true);
1696 if (visibilityChanged && AXObjectCache::accessibilityEnabled())
1697 document()->axObjectCache()->childrenChanged(this);
1699 // Keep layer hierarchy visibility bits up to date if visibility changes.
1700 if (m_style->visibility() != newStyle->visibility()) {
1701 if (RenderLayer* l = enclosingLayer()) {
1702 if (newStyle->visibility() == VISIBLE)
1703 l->setHasVisibleContent(true);
1704 else if (l->hasVisibleContent() && (this == l->renderer() || l->renderer()->style()->visibility() != VISIBLE)) {
1705 l->dirtyVisibleContentStatus();
1706 if (diff > StyleDifferenceRepaintLayer)
1713 if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
1715 if (isFloating() && (m_style->floating() != newStyle->floating()))
1716 // For changes in float styles, we need to conceivably remove ourselves
1717 // from the floating objects list.
1718 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1719 else if (isPositioned() && (m_style->position() != newStyle->position()))
1720 // For changes in positioning styles, we need to conceivably remove ourselves
1721 // from the positioned objects list.
1722 toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1724 s_affectsParentBlock = isFloatingOrPositioned() &&
1725 (!newStyle->isFloating() && newStyle->position() != AbsolutePosition && newStyle->position() != FixedPosition)
1726 && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
1728 // reset style flags
1729 if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
1731 m_positioned = false;
1732 m_relPositioned = false;
1734 m_horizontalWritingMode = true;
1735 m_paintBackground = false;
1736 m_hasOverflowClip = false;
1737 m_hasTransform = false;
1738 m_hasReflection = false;
1740 s_affectsParentBlock = false;
1742 if (view()->frameView()) {
1743 bool shouldBlitOnFixedBackgroundImage = false;
1744 #if ENABLE(FAST_MOBILE_SCROLLING)
1745 // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
1746 // when scrolling a page with a fixed background image. As an optimization, assuming there are
1747 // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
1748 // ignore the CSS property "background-attachment: fixed".
1749 shouldBlitOnFixedBackgroundImage = true;
1752 bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
1753 bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
1754 if (oldStyleSlowScroll != newStyleSlowScroll) {
1755 if (oldStyleSlowScroll)
1756 view()->frameView()->removeSlowRepaintObject();
1757 if (newStyleSlowScroll)
1758 view()->frameView()->addSlowRepaintObject();
1763 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
1765 ASSERT(a->cursors() != b->cursors());
1766 return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1769 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
1771 return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1774 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1776 if (s_affectsParentBlock)
1777 handleDynamicFloatPositionChange();
1782 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1783 RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
1785 // If the object already needs layout, then setNeedsLayout won't do
1786 // any work. But if the containing block has changed, then we may need
1787 // to mark the new containing blocks for layout. The change that can
1788 // directly affect the containing block of this object is a change to
1789 // the position style.
1790 if (m_needsLayout && oldStyle->position() != m_style->position())
1791 markContainingBlocksForLayout();
1793 if (diff == StyleDifferenceLayout)
1794 setNeedsLayoutAndPrefWidthsRecalc();
1796 setNeedsSimplifiedNormalFlowLayout();
1797 } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1798 setNeedsPositionedMovementLayout();
1799 setNeedsSimplifiedNormalFlowLayout();
1800 } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1801 setNeedsPositionedMovementLayout();
1803 // Don't check for repaint here; we need to wait until the layer has been
1804 // updated by subclasses before we know if we have to repaint (in setStyle()).
1806 if (oldStyle && !areCursorsEqual(oldStyle, style())) {
1807 if (Frame* frame = this->frame())
1808 frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
1812 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
1814 // FIXME: We could save this call when the change only affected non-inherited properties.
1815 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1816 if (blockChildrenOnly ? child->isAnonymousBlock() : child->isAnonymous() && !child->isBeforeOrAfterContent()) {
1817 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyle(style());
1818 if (style()->specifiesColumns()) {
1819 if (child->style()->specifiesColumns())
1820 newStyle->inheritColumnPropertiesFrom(style());
1821 if (child->style()->columnSpan())
1822 newStyle->setColumnSpan(true);
1824 newStyle->setDisplay(blockChildrenOnly ? BLOCK : child->style()->display());
1825 child->setStyle(newStyle.release());
1830 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
1832 // Optimize the common case
1833 if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
1836 // Go through the new layers and addClients first, to avoid removing all clients of an image.
1837 for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
1838 if (currNew->image())
1839 currNew->image()->addClient(this);
1842 for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
1843 if (currOld->image())
1844 currOld->image()->removeClient(this);
1848 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
1850 if (oldImage != newImage) {
1852 oldImage->removeClient(this);
1854 newImage->addClient(this);
1858 IntRect RenderObject::viewRect() const
1860 return view()->viewRect();
1863 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, bool fixed, bool useTransforms) const
1865 TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1866 mapLocalToContainer(0, fixed, useTransforms, transformState);
1867 transformState.flatten();
1869 return transformState.lastPlanarPoint();
1872 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, bool fixed, bool useTransforms) const
1874 TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1875 mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1876 transformState.flatten();
1878 return transformState.lastPlanarPoint();
1881 void RenderObject::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
1883 if (repaintContainer == this)
1886 RenderObject* o = parent();
1890 IntPoint centerPoint = roundedIntPoint(transformState.mappedPoint());
1891 if (o->isBox() && o->style()->isFlippedBlocksWritingMode())
1892 transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedIntPoint(transformState.mappedPoint())) - centerPoint);
1894 IntSize columnOffset;
1895 o->adjustForColumns(columnOffset, roundedIntPoint(transformState.mappedPoint()));
1896 if (!columnOffset.isZero())
1897 transformState.move(columnOffset);
1899 if (o->hasOverflowClip())
1900 transformState.move(-toRenderBox(o)->layer()->scrolledContentOffset());
1902 o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
1905 void RenderObject::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1907 RenderObject* o = parent();
1909 o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1910 if (o->hasOverflowClip())
1911 transformState.move(toRenderBox(o)->layer()->scrolledContentOffset());
1915 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1917 #if ENABLE(3D_RENDERING)
1918 // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
1919 // so check the layer's transform directly.
1920 return (hasLayer() && toRenderBoxModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
1922 UNUSED_PARAM(containerObject);
1923 return hasTransform();
1927 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
1929 transform.makeIdentity();
1930 transform.translate(offsetInContainer.width(), offsetInContainer.height());
1932 if (hasLayer() && (layer = toRenderBoxModelObject(this)->layer()) && layer->transform())
1933 transform.multiply(layer->currentTransform());
1935 #if ENABLE(3D_RENDERING)
1936 if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
1937 // Perpsective on the container affects us, so we have to factor it in here.
1938 ASSERT(containerObject->hasLayer());
1939 FloatPoint perspectiveOrigin = toRenderBoxModelObject(containerObject)->layer()->perspectiveOrigin();
1941 TransformationMatrix perspectiveMatrix;
1942 perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
1944 transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1945 transform = perspectiveMatrix * transform;
1946 transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1949 UNUSED_PARAM(containerObject);
1953 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, RenderBoxModelObject* repaintContainer, bool fixed, bool* wasFixed) const
1955 // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1956 // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1957 TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
1958 mapLocalToContainer(repaintContainer, fixed, true, transformState, wasFixed);
1959 transformState.flatten();
1961 return transformState.lastPlanarQuad();
1964 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point) const
1966 ASSERT(o == container());
1970 o->adjustForColumns(offset, point);
1972 if (o->hasOverflowClip())
1973 offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1978 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
1981 LayoutPoint referencePoint;
1982 const RenderObject* currContainer = this;
1984 RenderObject* nextContainer = currContainer->container();
1985 ASSERT(nextContainer); // This means we reached the top without finding container.
1988 ASSERT(!currContainer->hasTransform());
1989 LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
1990 offset += currentOffset;
1991 referencePoint.move(currentOffset);
1992 currContainer = nextContainer;
1993 } while (currContainer != container);
1998 IntRect RenderObject::localCaretRect(InlineBox*, int, int* extraWidthToEndOfLine)
2000 if (extraWidthToEndOfLine)
2001 *extraWidthToEndOfLine = 0;
2006 RenderView* RenderObject::view() const
2008 return toRenderView(document()->renderer());
2011 bool RenderObject::isRooted(RenderView** view)
2013 RenderObject* o = this;
2017 if (!o->isRenderView())
2021 *view = toRenderView(o);
2026 bool RenderObject::hasOutlineAnnotation() const
2028 return node() && node()->isLink() && document()->printing();
2031 RenderObject* RenderObject::container(RenderBoxModelObject* repaintContainer, bool* repaintContainerSkipped) const
2033 if (repaintContainerSkipped)
2034 *repaintContainerSkipped = false;
2036 // This method is extremely similar to containingBlock(), but with a few notable
2038 // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2039 // the object is not part of the primary document subtree yet.
2040 // (2) For normal flow elements, it just returns the parent.
2041 // (3) For absolute positioned elements, it will return a relative positioned inline.
2042 // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2043 // the layout of the positioned object. This does mean that computePositionedLogicalWidth and
2044 // computePositionedLogicalHeight have to use container().
2045 RenderObject* o = parent();
2050 EPosition pos = m_style->position();
2051 if (pos == FixedPosition) {
2052 // container() can be called on an object that is not in the
2053 // tree yet. We don't call view() since it will assert if it
2054 // can't get back to the canvas. Instead we just walk as high up
2055 // as we can. If we're in the tree, we'll get the root. If we
2056 // aren't we'll get the root of our little subtree (most likely
2057 // we'll just return 0).
2058 // FIXME: The definition of view() has changed to not crawl up the render tree. It might
2059 // be safe now to use it.
2060 while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
2061 if (repaintContainerSkipped && o == repaintContainer)
2062 *repaintContainerSkipped = true;
2065 } else if (pos == AbsolutePosition) {
2066 // Same goes here. We technically just want our containing block, but
2067 // we may not have one if we're part of an uninstalled subtree. We'll
2068 // climb as high as we can though.
2069 while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
2070 if (repaintContainerSkipped && o == repaintContainer)
2071 *repaintContainerSkipped = true;
2079 bool RenderObject::isSelectionBorder() const
2081 SelectionState st = selectionState();
2082 return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2085 void RenderObject::willBeDestroyed()
2087 // Destroy any leftover anonymous children.
2088 RenderObjectChildList* children = virtualChildren();
2090 children->destroyLeftoverChildren();
2092 // If this renderer is being autoscrolled, stop the autoscroll timer
2094 // FIXME: RenderObject::destroy should not get called with a renderer whose document
2095 // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
2096 // check that the frame is not null.
2098 if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
2099 frame()->eventHandler()->stopAutoscrollTimer(true);
2101 if (AXObjectCache::accessibilityEnabled()) {
2102 document()->axObjectCache()->childrenChanged(this->parent());
2103 document()->axObjectCache()->remove(this);
2105 animation()->cancelAnimations(this);
2109 // If this renderer had a parent, remove should have destroyed any counters
2110 // attached to this renderer and marked the affected other counters for
2111 // reevaluation. This apparently redundant check is here for the case when
2112 // this renderer had no parent at the time remove() was called.
2114 if (m_hasCounterNodeMap)
2115 RenderCounter::destroyCounterNodes(this);
2117 // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
2118 // be moved into RenderBoxModelObject::destroy.
2121 toRenderBoxModelObject(this)->destroyLayer();
2125 void RenderObject::destroy()
2128 arenaDelete(renderArena(), this);
2131 void RenderObject::arenaDelete(RenderArena* arena, void* base)
2134 for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2135 if (StyleImage* backgroundImage = bgLayer->image())
2136 backgroundImage->removeClient(this);
2139 for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2140 if (StyleImage* maskImage = maskLayer->image())
2141 maskImage->removeClient(this);
2144 if (StyleImage* borderImage = m_style->borderImage().image())
2145 borderImage->removeClient(this);
2147 if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2148 maskBoxImage->removeClient(this);
2152 void* savedBase = baseOfRenderObjectBeingDeleted;
2153 baseOfRenderObjectBeingDeleted = base;
2157 baseOfRenderObjectBeingDeleted = savedBase;
2160 // Recover the size left there for us by operator delete and free the memory.
2161 arena->free(*(size_t*)base, base);
2164 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&)
2166 return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2169 void RenderObject::updateDragState(bool dragOn)
2171 bool valueChanged = (dragOn != m_isDragging);
2172 m_isDragging = dragOn;
2173 if (valueChanged && style()->affectedByDragRules() && node())
2174 node()->setNeedsStyleRecalc();
2175 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2176 curr->updateDragState(dragOn);
2179 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2181 bool inside = false;
2182 if (hitTestFilter != HitTestSelf) {
2183 // First test the foreground layer (lines and inlines).
2184 inside = nodeAtPoint(request, result, pointInContainer, accumulatedOffset, HitTestForeground);
2186 // Test floats next.
2188 inside = nodeAtPoint(request, result, pointInContainer, accumulatedOffset, HitTestFloat);
2190 // Finally test to see if the mouse is in the background (within a child block's background).
2192 inside = nodeAtPoint(request, result, pointInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2195 // See if the mouse is inside us but not any of our descendants
2196 if (hitTestFilter != HitTestDescendants && !inside)
2197 inside = nodeAtPoint(request, result, pointInContainer, accumulatedOffset, HitTestBlockBackground);
2202 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2204 if (result.innerNode())
2209 result.setInnerNode(n);
2210 if (!result.innerNonSharedNode())
2211 result.setInnerNonSharedNode(n);
2212 result.setLocalPoint(point);
2216 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const LayoutPoint& /*pointInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2221 void RenderObject::scheduleRelayout()
2223 if (isRenderView()) {
2224 FrameView* view = toRenderView(this)->frameView();
2226 view->scheduleRelayout();
2227 } else if (parent()) {
2228 FrameView* v = view() ? view()->frameView() : 0;
2230 v->scheduleRelayoutOfSubtree(this);
2234 void RenderObject::layout()
2236 ASSERT(needsLayout());
2237 RenderObject* child = firstChild();
2239 child->layoutIfNeeded();
2240 ASSERT(!child->needsLayout());
2241 child = child->nextSibling();
2243 setNeedsLayout(false);
2246 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2248 if (!document()->usesFirstLineRules())
2253 RefPtr<RenderStyle> result;
2255 if (isBlockFlow()) {
2256 if (RenderBlock* firstLineBlock = this->firstLineBlock())
2257 result = firstLineBlock->getUncachedPseudoStyle(FIRST_LINE, style, firstLineBlock == this ? style : 0);
2258 } else if (!isAnonymous() && isRenderInline()) {
2259 RenderStyle* parentStyle = parent()->firstLineStyle();
2260 if (parentStyle != parent()->style())
2261 result = getUncachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle, style);
2264 return result.release();
2267 RenderStyle* RenderObject::firstLineStyleSlowCase() const
2269 ASSERT(document()->usesFirstLineRules());
2271 RenderStyle* style = m_style.get();
2272 const RenderObject* renderer = isText() ? parent() : this;
2273 if (renderer->isBlockFlow()) {
2274 if (RenderBlock* firstLineBlock = renderer->firstLineBlock())
2275 style = firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2276 } else if (!renderer->isAnonymous() && renderer->isRenderInline()) {
2277 RenderStyle* parentStyle = renderer->parent()->firstLineStyle();
2278 if (parentStyle != renderer->parent()->style()) {
2279 // A first-line style is in effect. Cache a first-line style for ourselves.
2280 renderer->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2281 style = renderer->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2288 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2290 if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2293 RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2297 RefPtr<RenderStyle> result = getUncachedPseudoStyle(pseudo, parentStyle);
2299 return style()->addCachedPseudoStyle(result.release());
2303 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2305 if (pseudo < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudo))
2310 parentStyle = style();
2314 while (n && !n->isElementNode())
2315 n = n->parentNode();
2319 RefPtr<RenderStyle> result;
2320 if (pseudo == FIRST_LINE_INHERITED) {
2321 result = document()->styleSelector()->styleForElement(static_cast<Element*>(n), parentStyle, false);
2322 result->setStyleType(FIRST_LINE_INHERITED);
2324 result = document()->styleSelector()->pseudoStyleForElement(pseudo, static_cast<Element*>(n), parentStyle);
2325 return result.release();
2328 static Color decorationColor(RenderObject* renderer)
2331 if (renderer->style()->textStrokeWidth() > 0) {
2332 // Prefer stroke color if possible but not if it's fully transparent.
2333 result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2338 result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2342 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2343 Color& linethrough, bool quirksMode)
2345 RenderObject* curr = this;
2347 int currDecs = curr->style()->textDecoration();
2349 if (currDecs & UNDERLINE) {
2350 decorations &= ~UNDERLINE;
2351 underline = decorationColor(curr);
2353 if (currDecs & OVERLINE) {
2354 decorations &= ~OVERLINE;
2355 overline = decorationColor(curr);
2357 if (currDecs & LINE_THROUGH) {
2358 decorations &= ~LINE_THROUGH;
2359 linethrough = decorationColor(curr);
2362 curr = curr->parent();
2363 if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2364 curr = toRenderBlock(curr)->continuation();
2365 } while (curr && decorations && (!quirksMode || !curr->node() ||
2366 (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
2368 // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2369 if (decorations && curr) {
2370 if (decorations & UNDERLINE)
2371 underline = decorationColor(curr);
2372 if (decorations & OVERLINE)
2373 overline = decorationColor(curr);
2374 if (decorations & LINE_THROUGH)
2375 linethrough = decorationColor(curr);
2379 #if ENABLE(DASHBOARD_SUPPORT)
2380 void RenderObject::addDashboardRegions(Vector<DashboardRegionValue>& regions)
2382 // Convert the style regions to absolute coordinates.
2383 if (style()->visibility() != VISIBLE || !isBox())
2386 RenderBox* box = toRenderBox(this);
2388 const Vector<StyleDashboardRegion>& styleRegions = style()->dashboardRegions();
2389 unsigned i, count = styleRegions.size();
2390 for (i = 0; i < count; i++) {
2391 StyleDashboardRegion styleRegion = styleRegions[i];
2393 int w = box->width();
2394 int h = box->height();
2396 DashboardRegionValue region;
2397 region.label = styleRegion.label;
2398 region.bounds = IntRect(styleRegion.offset.left().value(),
2399 styleRegion.offset.top().value(),
2400 w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2401 h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2402 region.type = styleRegion.type;
2404 region.clip = region.bounds;
2405 computeAbsoluteRepaintRect(region.clip);
2406 if (region.clip.height() < 0) {
2407 region.clip.setHeight(0);
2408 region.clip.setWidth(0);
2411 FloatPoint absPos = localToAbsolute();
2412 region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2413 region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2416 float deviceScaleFactor = frame()->page()->deviceScaleFactor();
2417 if (deviceScaleFactor != 1.0f) {
2418 region.bounds.scale(deviceScaleFactor);
2419 region.clip.scale(deviceScaleFactor);
2423 regions.append(region);
2427 void RenderObject::collectDashboardRegions(Vector<DashboardRegionValue>& regions)
2429 // RenderTexts don't have their own style, they just use their parent's style,
2430 // so we don't want to include them.
2434 addDashboardRegions(regions);
2435 for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2436 curr->collectDashboardRegions(regions);
2440 bool RenderObject::willRenderImage(CachedImage*)
2442 // Without visibility we won't render (and therefore don't care about animation).
2443 if (style()->visibility() != VISIBLE)
2446 // 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)
2447 // then we don't want to render either.
2448 return !document()->inPageCache() && !document()->view()->isOffscreen();
2451 int RenderObject::maximalOutlineSize(PaintPhase p) const
2453 if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2455 return toRenderView(document()->renderer())->maximalOutlineSize();
2458 int RenderObject::caretMinOffset() const
2463 int RenderObject::caretMaxOffset() const
2466 return node() ? max(1U, node()->childNodeCount()) : 1;
2472 unsigned RenderObject::caretMaxRenderedOffset() const
2477 int RenderObject::previousOffset(int current) const
2482 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2487 int RenderObject::nextOffset(int current) const
2492 void RenderObject::adjustRectForOutlineAndShadow(IntRect& rect) const
2494 int outlineSize = outlineStyleForRepaint()->outlineSize();
2495 if (const ShadowData* boxShadow = style()->boxShadow()) {
2496 boxShadow->adjustRectForShadow(rect, outlineSize);
2500 rect.inflate(outlineSize);
2503 AnimationController* RenderObject::animation() const
2505 return frame()->animation();
2508 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
2510 imageChanged(static_cast<WrappedImagePtr>(image), rect);
2513 RenderBoxModelObject* RenderObject::offsetParent() const
2515 // If any of the following holds true return null and stop this algorithm:
2516 // A is the root element.
2517 // A is the HTML body element.
2518 // The computed value of the position property for element A is fixed.
2519 if (isRoot() || isBody() || (isPositioned() && style()->position() == FixedPosition))
2522 // If A is an area HTML element which has a map HTML element somewhere in the ancestor
2523 // chain return the nearest ancestor map HTML element and stop this algorithm.
2524 // FIXME: Implement!
2526 // Return the nearest ancestor element of A for which at least one of the following is
2527 // true and stop this algorithm if such an ancestor is found:
2528 // * The computed value of the position property is not static.
2529 // * It is the HTML body element.
2530 // * The computed value of the position property of A is static and the ancestor
2531 // is one of the following HTML elements: td, th, or table.
2532 // * Our own extension: if there is a difference in the effective zoom
2534 bool skipTables = isPositioned() || isRelPositioned();
2535 float currZoom = style()->effectiveZoom();
2536 RenderObject* curr = parent();
2537 while (curr && (!curr->node() || (!curr->isPositioned() && !curr->isRelPositioned() && !curr->isBody()))) {
2538 Node* element = curr->node();
2539 if (!skipTables && element && (element->hasTagName(tableTag) || element->hasTagName(tdTag) || element->hasTagName(thTag)))
2542 float newZoom = curr->style()->effectiveZoom();
2543 if (currZoom != newZoom)
2546 curr = curr->parent();
2548 return curr && curr->isBoxModelObject() ? toRenderBoxModelObject(curr) : 0;
2551 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity)
2553 // If this is a non-anonymous renderer in an editable area, then it's simple.
2554 if (Node* node = this->node()) {
2555 if (!node->rendererIsEditable()) {
2556 // If it can be found, we prefer a visually equivalent position that is editable.
2557 Position position = createLegacyEditingPosition(node, offset);
2558 Position candidate = position.downstream(CanCrossEditingBoundary);
2559 if (candidate.deprecatedNode()->rendererIsEditable())
2560 return VisiblePosition(candidate, affinity);
2561 candidate = position.upstream(CanCrossEditingBoundary);
2562 if (candidate.deprecatedNode()->rendererIsEditable())
2563 return VisiblePosition(candidate, affinity);
2565 // FIXME: Eliminate legacy editing positions
2566 return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
2569 // We don't want to cross the boundary between editable and non-editable
2570 // regions of the document, but that is either impossible or at least
2571 // extremely unlikely in any normal case because we stop as soon as we
2572 // find a single non-anonymous renderer.
2574 // Find a nearby non-anonymous renderer.
2575 RenderObject* child = this;
2576 while (RenderObject* parent = child->parent()) {
2577 // Find non-anonymous content after.
2578 RenderObject* renderer = child;
2579 while ((renderer = renderer->nextInPreOrder(parent))) {
2580 if (Node* node = renderer->node())
2581 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2584 // Find non-anonymous content before.
2586 while ((renderer = renderer->previousInPreOrder())) {
2587 if (renderer == parent)
2589 if (Node* node = renderer->node())
2590 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
2593 // Use the parent itself unless it too is anonymous.
2594 if (Node* node = parent->node())
2595 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2597 // Repeat at the next level up.
2601 // Everything was anonymous. Give up.
2602 return VisiblePosition();
2605 VisiblePosition RenderObject::createVisiblePosition(const Position& position)
2607 if (position.isNotNull())
2608 return VisiblePosition(position);
2611 return createVisiblePosition(0, DOWNSTREAM);
2615 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
2617 ASSERT_NOT_REACHED();
2621 void RenderObject::setNeedsBoundariesUpdate()
2623 if (RenderObject* renderer = parent())
2624 renderer->setNeedsBoundariesUpdate();
2627 FloatRect RenderObject::objectBoundingBox() const
2629 ASSERT_NOT_REACHED();
2633 FloatRect RenderObject::strokeBoundingBox() const
2635 ASSERT_NOT_REACHED();
2639 // Returns the smallest rectangle enclosing all of the painted content
2640 // respecting clipping, masking, filters, opacity, stroke-width and markers
2641 FloatRect RenderObject::repaintRectInLocalCoordinates() const
2643 ASSERT_NOT_REACHED();
2647 AffineTransform RenderObject::localTransform() const
2649 static const AffineTransform identity;
2653 const AffineTransform& RenderObject::localToParentTransform() const
2655 static const AffineTransform identity;
2659 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2661 ASSERT_NOT_REACHED();
2665 #endif // ENABLE(SVG)
2667 } // namespace WebCore
2671 void showTree(const WebCore::RenderObject* object)
2674 object->showTreeForThis();
2677 void showLineTree(const WebCore::RenderObject* object)
2680 object->showLineTreeForThis();
2683 void showRenderTree(const WebCore::RenderObject* object1)
2685 showRenderTree(object1, 0);
2688 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
2691 const WebCore::RenderObject* root = object1;
2692 while (root->parent())
2693 root = root->parent();
2694 root->showRenderTreeAndMark(object1, "*", object2, "-", 0);