1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2000 Dirk Mueller (mueller@kde.org)
5  *           (C) 2004 Allan Sandfeld Jensen (kde@carewolf.com)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
7  * Copyright (C) 2009 Google Inc. All rights reserved.
8  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  *
25  */
26 
27 #include "config.h"
28 #include "RenderObject.h"
29 
30 #include "AXObjectCache.h"
31 #include "CSSStyleSelector.h"
32 #include "Chrome.h"
33 #include "ContentData.h"
34 #include "CursorList.h"
35 #include "DashArray.h"
36 #include "EditingBoundary.h"
37 #include "FloatQuad.h"
38 #include "Frame.h"
39 #include "FrameView.h"
40 #include "GraphicsContext.h"
41 #include "HTMLNames.h"
42 #include "HitTestResult.h"
43 #include "Page.h"
44 #include "RenderArena.h"
45 #include "RenderCounter.h"
46 #include "RenderFlexibleBox.h"
47 #include "RenderImage.h"
48 #include "RenderImageResourceStyleImage.h"
49 #include "RenderInline.h"
50 #include "RenderLayer.h"
51 #include "RenderListItem.h"
52 #include "RenderRuby.h"
53 #include "RenderRubyText.h"
54 #include "RenderTableCell.h"
55 #include "RenderTableCol.h"
56 #include "RenderTableRow.h"
57 #include "RenderTheme.h"
58 #include "RenderView.h"
59 #include "TransformState.h"
60 #include "htmlediting.h"
61 #include <algorithm>
62 #include <stdio.h>
63 #include <wtf/RefCountedLeakCounter.h>
64 #include <wtf/UnusedParam.h>
65 
66 #if USE(ACCELERATED_COMPOSITING)
67 #include "RenderLayerCompositor.h"
68 #endif
69 
70 #if ENABLE(SVG)
71 #include "RenderSVGResourceContainer.h"
72 #include "SVGRenderSupport.h"
73 #endif
74 
75 using namespace std;
76 
77 namespace WebCore {
78 
79 using namespace HTMLNames;
80 
81 #ifndef NDEBUG
82 static void* baseOfRenderObjectBeingDeleted;
83 #endif
84 
85 bool RenderObject::s_affectsParentBlock = false;
86 
operator new(size_t sz,RenderArena * renderArena)87 void* RenderObject::operator new(size_t sz, RenderArena* renderArena) throw()
88 {
89     return renderArena->allocate(sz);
90 }
91 
operator delete(void * ptr,size_t sz)92 void RenderObject::operator delete(void* ptr, size_t sz)
93 {
94     ASSERT(baseOfRenderObjectBeingDeleted == ptr);
95 
96     // Stash size where destroy can find it.
97     *(size_t *)ptr = sz;
98 }
99 
createObject(Node * node,RenderStyle * style)100 RenderObject* RenderObject::createObject(Node* node, RenderStyle* style)
101 {
102     Document* doc = node->document();
103     RenderArena* arena = doc->renderArena();
104 
105     // Minimal support for content properties replacing an entire element.
106     // Works only if we have exactly one piece of content and it's a URL.
107     // Otherwise acts as if we didn't support this feature.
108     const ContentData* contentData = style->contentData();
109     if (contentData && !contentData->next() && contentData->isImage() && doc != node) {
110         RenderImage* image = new (arena) RenderImage(node);
111         image->setStyle(style);
112         if (StyleImage* styleImage = contentData->image())
113             image->setImageResource(RenderImageResourceStyleImage::create(styleImage));
114         else
115             image->setImageResource(RenderImageResource::create());
116         return image;
117     }
118 
119     if (node->hasTagName(rubyTag)) {
120         if (style->display() == INLINE)
121             return new (arena) RenderRubyAsInline(node);
122         else if (style->display() == BLOCK)
123             return new (arena) RenderRubyAsBlock(node);
124     }
125     // treat <rt> as ruby text ONLY if it still has its default treatment of block
126     if (node->hasTagName(rtTag) && style->display() == BLOCK)
127         return new (arena) RenderRubyText(node);
128 
129     switch (style->display()) {
130         case NONE:
131             return 0;
132         case INLINE:
133             return new (arena) RenderInline(node);
134         case BLOCK:
135         case INLINE_BLOCK:
136         case RUN_IN:
137         case COMPACT:
138             return new (arena) RenderBlock(node);
139         case LIST_ITEM:
140             return new (arena) RenderListItem(node);
141         case TABLE:
142         case INLINE_TABLE:
143             return new (arena) RenderTable(node);
144         case TABLE_ROW_GROUP:
145         case TABLE_HEADER_GROUP:
146         case TABLE_FOOTER_GROUP:
147             return new (arena) RenderTableSection(node);
148         case TABLE_ROW:
149             return new (arena) RenderTableRow(node);
150         case TABLE_COLUMN_GROUP:
151         case TABLE_COLUMN:
152             return new (arena) RenderTableCol(node);
153         case TABLE_CELL:
154             return new (arena) RenderTableCell(node);
155         case TABLE_CAPTION:
156 #if ENABLE(WCSS)
157         // As per the section 17.1 of the spec WAP-239-WCSS-20011026-a.pdf,
158         // the marquee box inherits and extends the characteristics of the
159         // principal block box ([CSS2] section 9.2.1).
160         case WAP_MARQUEE:
161 #endif
162             return new (arena) RenderBlock(node);
163         case BOX:
164         case INLINE_BOX:
165             return new (arena) RenderFlexibleBox(node);
166     }
167 
168     return 0;
169 }
170 
171 #ifndef NDEBUG
172 static WTF::RefCountedLeakCounter renderObjectCounter("RenderObject");
173 #endif
174 
RenderObject(Node * node)175 RenderObject::RenderObject(Node* node)
176     : CachedResourceClient()
177     , m_style(0)
178     , m_node(node)
179     , m_parent(0)
180     , m_previous(0)
181     , m_next(0)
182 #ifndef NDEBUG
183     , m_hasAXObject(false)
184     , m_setNeedsLayoutForbidden(false)
185 #endif
186     , m_needsLayout(false)
187     , m_needsPositionedMovementLayout(false)
188     , m_normalChildNeedsLayout(false)
189     , m_posChildNeedsLayout(false)
190     , m_needsSimplifiedNormalFlowLayout(false)
191     , m_preferredLogicalWidthsDirty(false)
192     , m_floating(false)
193     , m_positioned(false)
194     , m_relPositioned(false)
195     , m_paintBackground(false)
196     , m_isAnonymous(node == node->document())
197     , m_isText(false)
198     , m_isBox(false)
199     , m_inline(true)
200     , m_replaced(false)
201     , m_horizontalWritingMode(true)
202     , m_isDragging(false)
203     , m_hasLayer(false)
204     , m_hasOverflowClip(false)
205     , m_hasTransform(false)
206     , m_hasReflection(false)
207     , m_hasOverrideSize(false)
208     , m_hasCounterNodeMap(false)
209     , m_everHadLayout(false)
210     , m_childrenInline(false)
211     , m_marginBeforeQuirk(false)
212     , m_marginAfterQuirk(false)
213     , m_hasMarkupTruncation(false)
214     , m_selectionState(SelectionNone)
215     , m_hasColumns(false)
216 {
217 #ifndef NDEBUG
218     renderObjectCounter.increment();
219 #endif
220     ASSERT(node);
221 }
222 
~RenderObject()223 RenderObject::~RenderObject()
224 {
225     ASSERT(!node() || documentBeingDestroyed() || !frame()->view() || frame()->view()->layoutRoot() != this);
226 #ifndef NDEBUG
227     ASSERT(!m_hasAXObject);
228     renderObjectCounter.decrement();
229 #endif
230 }
231 
theme() const232 RenderTheme* RenderObject::theme() const
233 {
234     ASSERT(document()->page());
235 
236     return document()->page()->theme();
237 }
238 
isDescendantOf(const RenderObject * obj) const239 bool RenderObject::isDescendantOf(const RenderObject* obj) const
240 {
241     for (const RenderObject* r = this; r; r = r->m_parent) {
242         if (r == obj)
243             return true;
244     }
245     return false;
246 }
247 
isBody() const248 bool RenderObject::isBody() const
249 {
250     return node() && node()->hasTagName(bodyTag);
251 }
252 
isHR() const253 bool RenderObject::isHR() const
254 {
255     return node() && node()->hasTagName(hrTag);
256 }
257 
isLegend() const258 bool RenderObject::isLegend() const
259 {
260     return node() && node()->hasTagName(legendTag);
261 }
262 
isHTMLMarquee() const263 bool RenderObject::isHTMLMarquee() const
264 {
265     return node() && node()->renderer() == this && node()->hasTagName(marqueeTag);
266 }
267 
addChild(RenderObject * newChild,RenderObject * beforeChild)268 void RenderObject::addChild(RenderObject* newChild, RenderObject* beforeChild)
269 {
270     RenderObjectChildList* children = virtualChildren();
271     ASSERT(children);
272     if (!children)
273         return;
274 
275     bool needsTable = false;
276 
277     if (newChild->isTableCol() && newChild->style()->display() == TABLE_COLUMN_GROUP)
278         needsTable = !isTable();
279     else if (newChild->isRenderBlock() && newChild->style()->display() == TABLE_CAPTION)
280         needsTable = !isTable();
281     else if (newChild->isTableSection())
282         needsTable = !isTable();
283     else if (newChild->isTableRow())
284         needsTable = !isTableSection();
285     else if (newChild->isTableCell()) {
286         needsTable = !isTableRow();
287         // I'm not 100% sure this is the best way to fix this, but without this
288         // change we recurse infinitely when trying to render the CSS2 test page:
289         // http://www.bath.ac.uk/%7Epy8ieh/internet/eviltests/htmlbodyheadrendering2.html.
290         // See Radar 2925291.
291         if (needsTable && isTableCell() && !children->firstChild() && !newChild->isTableCell())
292             needsTable = false;
293     }
294 
295     if (needsTable) {
296         RenderTable* table;
297         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : children->lastChild();
298         if (afterChild && afterChild->isAnonymous() && afterChild->isTable())
299             table = toRenderTable(afterChild);
300         else {
301             table = new (renderArena()) RenderTable(document() /* is anonymous */);
302             RefPtr<RenderStyle> newStyle = RenderStyle::create();
303             newStyle->inheritFrom(style());
304             newStyle->setDisplay(TABLE);
305             table->setStyle(newStyle.release());
306             addChild(table, beforeChild);
307         }
308         table->addChild(newChild);
309     } else {
310         // Just add it...
311         children->insertChildNode(this, newChild, beforeChild);
312     }
313     if (newChild->isText() && newChild->style()->textTransform() == CAPITALIZE) {
314         RefPtr<StringImpl> textToTransform = toRenderText(newChild)->originalText();
315         if (textToTransform)
316             toRenderText(newChild)->setText(textToTransform.release(), true);
317     }
318 }
319 
removeChild(RenderObject * oldChild)320 void RenderObject::removeChild(RenderObject* oldChild)
321 {
322     RenderObjectChildList* children = virtualChildren();
323     ASSERT(children);
324     if (!children)
325         return;
326 
327     // We do this here instead of in removeChildNode, since the only extremely low-level uses of remove/appendChildNode
328     // cannot affect the positioned object list, and the floating object list is irrelevant (since the list gets cleared on
329     // layout anyway).
330     if (oldChild->isFloatingOrPositioned())
331         toRenderBox(oldChild)->removeFloatingOrPositionedChildFromBlockLists();
332 
333     children->removeChildNode(this, oldChild);
334 }
335 
nextInPreOrder() const336 RenderObject* RenderObject::nextInPreOrder() const
337 {
338     if (RenderObject* o = firstChild())
339         return o;
340 
341     return nextInPreOrderAfterChildren();
342 }
343 
nextInPreOrderAfterChildren() const344 RenderObject* RenderObject::nextInPreOrderAfterChildren() const
345 {
346     RenderObject* o;
347     if (!(o = nextSibling())) {
348         o = parent();
349         while (o && !o->nextSibling())
350             o = o->parent();
351         if (o)
352             o = o->nextSibling();
353     }
354 
355     return o;
356 }
357 
nextInPreOrder(RenderObject * stayWithin) const358 RenderObject* RenderObject::nextInPreOrder(RenderObject* stayWithin) const
359 {
360     if (RenderObject* o = firstChild())
361         return o;
362 
363     return nextInPreOrderAfterChildren(stayWithin);
364 }
365 
nextInPreOrderAfterChildren(RenderObject * stayWithin) const366 RenderObject* RenderObject::nextInPreOrderAfterChildren(RenderObject* stayWithin) const
367 {
368     if (this == stayWithin)
369         return 0;
370 
371     const RenderObject* current = this;
372     RenderObject* next;
373     while (!(next = current->nextSibling())) {
374         current = current->parent();
375         if (!current || current == stayWithin)
376             return 0;
377     }
378     return next;
379 }
380 
previousInPreOrder() const381 RenderObject* RenderObject::previousInPreOrder() const
382 {
383     if (RenderObject* o = previousSibling()) {
384         while (o->lastChild())
385             o = o->lastChild();
386         return o;
387     }
388 
389     return parent();
390 }
391 
childAt(unsigned index) const392 RenderObject* RenderObject::childAt(unsigned index) const
393 {
394     RenderObject* child = firstChild();
395     for (unsigned i = 0; child && i < index; i++)
396         child = child->nextSibling();
397     return child;
398 }
399 
firstLeafChild() const400 RenderObject* RenderObject::firstLeafChild() const
401 {
402     RenderObject* r = firstChild();
403     while (r) {
404         RenderObject* n = 0;
405         n = r->firstChild();
406         if (!n)
407             break;
408         r = n;
409     }
410     return r;
411 }
412 
lastLeafChild() const413 RenderObject* RenderObject::lastLeafChild() const
414 {
415     RenderObject* r = lastChild();
416     while (r) {
417         RenderObject* n = 0;
418         n = r->lastChild();
419         if (!n)
420             break;
421         r = n;
422     }
423     return r;
424 }
425 
addLayers(RenderObject * obj,RenderLayer * parentLayer,RenderObject * & newObject,RenderLayer * & beforeChild)426 static void addLayers(RenderObject* obj, RenderLayer* parentLayer, RenderObject*& newObject,
427                       RenderLayer*& beforeChild)
428 {
429     if (obj->hasLayer()) {
430         if (!beforeChild && newObject) {
431             // We need to figure out the layer that follows newObject.  We only do
432             // this the first time we find a child layer, and then we update the
433             // pointer values for newObject and beforeChild used by everyone else.
434             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
435             newObject = 0;
436         }
437         parentLayer->addChild(toRenderBoxModelObject(obj)->layer(), beforeChild);
438         return;
439     }
440 
441     for (RenderObject* curr = obj->firstChild(); curr; curr = curr->nextSibling())
442         addLayers(curr, parentLayer, newObject, beforeChild);
443 }
444 
addLayers(RenderLayer * parentLayer,RenderObject * newObject)445 void RenderObject::addLayers(RenderLayer* parentLayer, RenderObject* newObject)
446 {
447     if (!parentLayer)
448         return;
449 
450     RenderObject* object = newObject;
451     RenderLayer* beforeChild = 0;
452     WebCore::addLayers(this, parentLayer, object, beforeChild);
453 }
454 
removeLayers(RenderLayer * parentLayer)455 void RenderObject::removeLayers(RenderLayer* parentLayer)
456 {
457     if (!parentLayer)
458         return;
459 
460     if (hasLayer()) {
461         parentLayer->removeChild(toRenderBoxModelObject(this)->layer());
462         return;
463     }
464 
465     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
466         curr->removeLayers(parentLayer);
467 }
468 
moveLayers(RenderLayer * oldParent,RenderLayer * newParent)469 void RenderObject::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
470 {
471     if (!newParent)
472         return;
473 
474     if (hasLayer()) {
475         RenderLayer* layer = toRenderBoxModelObject(this)->layer();
476         ASSERT(oldParent == layer->parent());
477         if (oldParent)
478             oldParent->removeChild(layer);
479         newParent->addChild(layer);
480         return;
481     }
482 
483     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
484         curr->moveLayers(oldParent, newParent);
485 }
486 
findNextLayer(RenderLayer * parentLayer,RenderObject * startPoint,bool checkParent)487 RenderLayer* RenderObject::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint,
488                                          bool checkParent)
489 {
490     // Error check the parent layer passed in.  If it's null, we can't find anything.
491     if (!parentLayer)
492         return 0;
493 
494     // Step 1: If our layer is a child of the desired parent, then return our layer.
495     RenderLayer* ourLayer = hasLayer() ? toRenderBoxModelObject(this)->layer() : 0;
496     if (ourLayer && ourLayer->parent() == parentLayer)
497         return ourLayer;
498 
499     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
500     // into our siblings trying to find the next layer whose parent is the desired parent.
501     if (!ourLayer || ourLayer == parentLayer) {
502         for (RenderObject* curr = startPoint ? startPoint->nextSibling() : firstChild();
503              curr; curr = curr->nextSibling()) {
504             RenderLayer* nextLayer = curr->findNextLayer(parentLayer, 0, false);
505             if (nextLayer)
506                 return nextLayer;
507         }
508     }
509 
510     // Step 3: If our layer is the desired parent layer, then we're finished.  We didn't
511     // find anything.
512     if (parentLayer == ourLayer)
513         return 0;
514 
515     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
516     // follow us to see if we can locate a layer.
517     if (checkParent && parent())
518         return parent()->findNextLayer(parentLayer, this, true);
519 
520     return 0;
521 }
522 
enclosingLayer() const523 RenderLayer* RenderObject::enclosingLayer() const
524 {
525     const RenderObject* curr = this;
526     while (curr) {
527         RenderLayer* layer = curr->hasLayer() ? toRenderBoxModelObject(curr)->layer() : 0;
528         if (layer)
529             return layer;
530         curr = curr->parent();
531     }
532     return 0;
533 }
534 
enclosingBox() const535 RenderBox* RenderObject::enclosingBox() const
536 {
537     RenderObject* curr = const_cast<RenderObject*>(this);
538     while (curr) {
539         if (curr->isBox())
540             return toRenderBox(curr);
541         curr = curr->parent();
542     }
543 
544     ASSERT_NOT_REACHED();
545     return 0;
546 }
547 
enclosingBoxModelObject() const548 RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
549 {
550     RenderObject* curr = const_cast<RenderObject*>(this);
551     while (curr) {
552         if (curr->isBoxModelObject())
553             return toRenderBoxModelObject(curr);
554         curr = curr->parent();
555     }
556 
557     ASSERT_NOT_REACHED();
558     return 0;
559 }
560 
firstLineBlock() const561 RenderBlock* RenderObject::firstLineBlock() const
562 {
563     return 0;
564 }
565 
setPreferredLogicalWidthsDirty(bool b,bool markParents)566 void RenderObject::setPreferredLogicalWidthsDirty(bool b, bool markParents)
567 {
568     bool alreadyDirty = m_preferredLogicalWidthsDirty;
569     m_preferredLogicalWidthsDirty = b;
570     if (b && !alreadyDirty && markParents && (isText() || (style()->position() != FixedPosition && style()->position() != AbsolutePosition)))
571         invalidateContainerPreferredLogicalWidths();
572 }
573 
invalidateContainerPreferredLogicalWidths()574 void RenderObject::invalidateContainerPreferredLogicalWidths()
575 {
576     // In order to avoid pathological behavior when inlines are deeply nested, we do include them
577     // in the chain that we mark dirty (even though they're kind of irrelevant).
578     RenderObject* o = isTableCell() ? containingBlock() : container();
579     while (o && !o->m_preferredLogicalWidthsDirty) {
580         // Don't invalidate the outermost object of an unrooted subtree. That object will be
581         // invalidated when the subtree is added to the document.
582         RenderObject* container = o->isTableCell() ? o->containingBlock() : o->container();
583         if (!container && !o->isRenderView())
584             break;
585 
586         o->m_preferredLogicalWidthsDirty = true;
587         if (o->style()->position() == FixedPosition || o->style()->position() == AbsolutePosition)
588             // A positioned object has no effect on the min/max width of its containing block ever.
589             // We can optimize this case and not go up any further.
590             break;
591         o = container;
592     }
593 }
594 
setLayerNeedsFullRepaint()595 void RenderObject::setLayerNeedsFullRepaint()
596 {
597     ASSERT(hasLayer());
598     toRenderBoxModelObject(this)->layer()->setNeedsFullRepaint(true);
599 }
600 
containingBlock() const601 RenderBlock* RenderObject::containingBlock() const
602 {
603     if (isTableCell()) {
604         const RenderTableCell* cell = toRenderTableCell(this);
605         if (parent() && cell->section())
606             return cell->table();
607         return 0;
608     }
609 
610     if (isRenderView())
611         return const_cast<RenderView*>(toRenderView(this));
612 
613     RenderObject* o = parent();
614     if (!isText() && m_style->position() == FixedPosition) {
615         while (o && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock()))
616             o = o->parent();
617     } else if (!isText() && m_style->position() == AbsolutePosition) {
618         while (o && (o->style()->position() == StaticPosition || (o->isInline() && !o->isReplaced())) && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
619             // For relpositioned inlines, we return the nearest enclosing block.  We don't try
620             // to return the inline itself.  This allows us to avoid having a positioned objects
621             // list in all RenderInlines and lets us return a strongly-typed RenderBlock* result
622             // from this method.  The container() method can actually be used to obtain the
623             // inline directly.
624             if (o->style()->position() == RelativePosition && o->isInline() && !o->isReplaced())
625                 return o->containingBlock();
626 #if ENABLE(SVG)
627             if (o->isSVGForeignObject()) //foreignObject is the containing block for contents inside it
628                 break;
629 #endif
630 
631             o = o->parent();
632         }
633     } else {
634         while (o && ((o->isInline() && !o->isReplaced()) || o->isTableRow() || o->isTableSection()
635                      || o->isTableCol() || o->isFrameSet() || o->isMedia()
636 #if ENABLE(SVG)
637                      || o->isSVGContainer() || o->isSVGRoot()
638 #endif
639                      ))
640             o = o->parent();
641     }
642 
643     if (!o || !o->isRenderBlock())
644         return 0; // This can still happen in case of an orphaned tree
645 
646     return toRenderBlock(o);
647 }
648 
mustRepaintFillLayers(const RenderObject * renderer,const FillLayer * layer)649 static bool mustRepaintFillLayers(const RenderObject* renderer, const FillLayer* layer)
650 {
651     // Nobody will use multiple layers without wanting fancy positioning.
652     if (layer->next())
653         return true;
654 
655     // Make sure we have a valid image.
656     StyleImage* img = layer->image();
657     if (!img || !img->canRender(renderer->style()->effectiveZoom()))
658         return false;
659 
660     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
661         return true;
662 
663     if (layer->size().type == SizeLength) {
664         if (layer->size().size.width().isPercent() || layer->size().size.height().isPercent())
665             return true;
666     } else if (layer->size().type == Contain || layer->size().type == Cover || img->usesImageContainerSize())
667         return true;
668 
669     return false;
670 }
671 
borderImageIsLoadedAndCanBeRendered() const672 bool RenderObject::borderImageIsLoadedAndCanBeRendered() const
673 {
674     ASSERT(style()->hasBorder());
675 
676     StyleImage* borderImage = style()->borderImage().image();
677     return borderImage && borderImage->canRender(style()->effectiveZoom()) && borderImage->isLoaded();
678 }
679 
mustRepaintBackgroundOrBorder() const680 bool RenderObject::mustRepaintBackgroundOrBorder() const
681 {
682     if (hasMask() && mustRepaintFillLayers(this, style()->maskLayers()))
683         return true;
684 
685     // If we don't have a background/border/mask, then nothing to do.
686     if (!hasBoxDecorations())
687         return false;
688 
689     if (mustRepaintFillLayers(this, style()->backgroundLayers()))
690         return true;
691 
692     // Our fill layers are ok.  Let's check border.
693     if (style()->hasBorder() && borderImageIsLoadedAndCanBeRendered())
694         return true;
695 
696     return false;
697 }
698 
drawLineForBoxSide(GraphicsContext * graphicsContext,int x1,int y1,int x2,int y2,BoxSide side,Color color,EBorderStyle style,int adjacentWidth1,int adjacentWidth2,bool antialias)699 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
700                                       BoxSide side, Color color, EBorderStyle style,
701                                       int adjacentWidth1, int adjacentWidth2, bool antialias)
702 {
703     int width = (side == BSTop || side == BSBottom ? y2 - y1 : x2 - x1);
704 
705     if (style == DOUBLE && width < 3)
706         style = SOLID;
707 
708     switch (style) {
709         case BNONE:
710         case BHIDDEN:
711             return;
712         case DOTTED:
713         case DASHED:
714             graphicsContext->setStrokeColor(color, m_style->colorSpace());
715             graphicsContext->setStrokeThickness(width);
716             graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
717 
718             if (width > 0) {
719                 bool wasAntialiased = graphicsContext->shouldAntialias();
720                 graphicsContext->setShouldAntialias(antialias);
721 
722                 switch (side) {
723                     case BSBottom:
724                     case BSTop:
725                         graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
726                         break;
727                     case BSRight:
728                     case BSLeft:
729                         graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
730                         break;
731                 }
732                 graphicsContext->setShouldAntialias(wasAntialiased);
733             }
734             break;
735         case DOUBLE: {
736             int third = (width + 1) / 3;
737 
738             if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
739                 graphicsContext->setStrokeStyle(NoStroke);
740                 graphicsContext->setFillColor(color, m_style->colorSpace());
741 
742                 bool wasAntialiased = graphicsContext->shouldAntialias();
743                 graphicsContext->setShouldAntialias(antialias);
744 
745                 switch (side) {
746                     case BSTop:
747                     case BSBottom:
748                         graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, third));
749                         graphicsContext->drawRect(IntRect(x1, y2 - third, x2 - x1, third));
750                         break;
751                     case BSLeft:
752                         graphicsContext->drawRect(IntRect(x1, y1 + 1, third, y2 - y1 - 1));
753                         graphicsContext->drawRect(IntRect(x2 - third, y1 + 1, third, y2 - y1 - 1));
754                         break;
755                     case BSRight:
756                         graphicsContext->drawRect(IntRect(x1, y1 + 1, third, y2 - y1 - 1));
757                         graphicsContext->drawRect(IntRect(x2 - third, y1 + 1, third, y2 - y1 - 1));
758                         break;
759                 }
760 
761                 graphicsContext->setShouldAntialias(wasAntialiased);
762             } else {
763                 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
764                 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
765 
766                 switch (side) {
767                     case BSTop:
768                         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
769                                    y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + third,
770                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
771                         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
772                                    y2 - third, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
773                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
774                         break;
775                     case BSLeft:
776                         drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
777                                    x1 + third, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
778                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
779                         drawLineForBoxSide(graphicsContext, x2 - third, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
780                                    x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
781                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
782                         break;
783                     case BSBottom:
784                         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
785                                    y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + third,
786                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
787                         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
788                                    y2 - third, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
789                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
790                         break;
791                     case BSRight:
792                         drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
793                                    x1 + third, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
794                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
795                         drawLineForBoxSide(graphicsContext, x2 - third, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
796                                    x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
797                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
798                         break;
799                     default:
800                         break;
801                 }
802             }
803             break;
804         }
805         case RIDGE:
806         case GROOVE: {
807             EBorderStyle s1;
808             EBorderStyle s2;
809             if (style == GROOVE) {
810                 s1 = INSET;
811                 s2 = OUTSET;
812             } else {
813                 s1 = OUTSET;
814                 s2 = INSET;
815             }
816 
817             int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
818             int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
819 
820             switch (side) {
821                 case BSTop:
822                     drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
823                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
824                     drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
825                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
826                     break;
827                 case BSLeft:
828                     drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
829                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
830                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
831                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
832                     break;
833                 case BSBottom:
834                     drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
835                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
836                     drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
837                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
838                     break;
839                 case BSRight:
840                     drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
841                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
842                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
843                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
844                     break;
845             }
846             break;
847         }
848         case INSET:
849             // FIXME: Maybe we should lighten the colors on one side like Firefox.
850             // https://bugs.webkit.org/show_bug.cgi?id=58608
851             if (side == BSTop || side == BSLeft)
852                 color = color.dark();
853             // fall through
854         case OUTSET:
855             if (style == OUTSET && (side == BSBottom || side == BSRight))
856                 color = color.dark();
857             // fall through
858         case SOLID: {
859             graphicsContext->setStrokeStyle(NoStroke);
860             graphicsContext->setFillColor(color, m_style->colorSpace());
861             ASSERT(x2 >= x1);
862             ASSERT(y2 >= y1);
863             if (!adjacentWidth1 && !adjacentWidth2) {
864                 // Turn off antialiasing to match the behavior of drawConvexPolygon();
865                 // this matters for rects in transformed contexts.
866                 bool wasAntialiased = graphicsContext->shouldAntialias();
867                 graphicsContext->setShouldAntialias(antialias);
868                 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
869                 graphicsContext->setShouldAntialias(wasAntialiased);
870                 return;
871             }
872             FloatPoint quad[4];
873             switch (side) {
874                 case BSTop:
875                     quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
876                     quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
877                     quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
878                     quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
879                     break;
880                 case BSBottom:
881                     quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
882                     quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
883                     quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
884                     quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
885                     break;
886                 case BSLeft:
887                     quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
888                     quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
889                     quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
890                     quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
891                     break;
892                 case BSRight:
893                     quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
894                     quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
895                     quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
896                     quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
897                     break;
898             }
899 
900             graphicsContext->drawConvexPolygon(4, quad, antialias);
901             break;
902         }
903     }
904 }
905 
borderInnerRect(const IntRect & borderRect,unsigned short topWidth,unsigned short bottomWidth,unsigned short leftWidth,unsigned short rightWidth) const906 IntRect RenderObject::borderInnerRect(const IntRect& borderRect, unsigned short topWidth, unsigned short bottomWidth, unsigned short leftWidth, unsigned short rightWidth) const
907 {
908     return IntRect(
909             borderRect.x() + leftWidth,
910             borderRect.y() + topWidth,
911             borderRect.width() - leftWidth - rightWidth,
912             borderRect.height() - topWidth - bottomWidth);
913 }
914 
915 #if !HAVE(PATH_BASED_BORDER_RADIUS_DRAWING)
drawArcForBoxSide(GraphicsContext * graphicsContext,int x,int y,float thickness,const IntSize & radius,int angleStart,int angleSpan,BoxSide s,Color color,EBorderStyle style,bool firstCorner)916 void RenderObject::drawArcForBoxSide(GraphicsContext* graphicsContext, int x, int y, float thickness, const IntSize& radius,
917                                      int angleStart, int angleSpan, BoxSide s, Color color,
918                                      EBorderStyle style, bool firstCorner)
919 {
920     // FIXME: This function should be removed when all ports implement GraphicsContext::clipConvexPolygon()!!
921     // At that time, everyone can use RenderObject::drawBoxSideFromPath() instead. This should happen soon.
922     if ((style == DOUBLE && thickness / 2 < 3) || ((style == RIDGE || style == GROOVE) && thickness / 2 < 2))
923         style = SOLID;
924 
925     switch (style) {
926         case BNONE:
927         case BHIDDEN:
928             return;
929         case DOTTED:
930         case DASHED:
931             graphicsContext->setStrokeColor(color, m_style->colorSpace());
932             graphicsContext->setStrokeStyle(style == DOTTED ? DottedStroke : DashedStroke);
933             graphicsContext->setStrokeThickness(thickness);
934             graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
935             break;
936         case DOUBLE: {
937             float third = thickness / 3.0f;
938             float innerThird = (thickness + 1.0f) / 6.0f;
939             int shiftForInner = static_cast<int>(innerThird * 2.5f);
940 
941             int outerY = y;
942             int outerHeight = radius.height() * 2;
943             int innerX = x + shiftForInner;
944             int innerY = y + shiftForInner;
945             int innerWidth = (radius.width() - shiftForInner) * 2;
946             int innerHeight = (radius.height() - shiftForInner) * 2;
947             if (innerThird > 1 && (s == BSTop || (firstCorner && (s == BSLeft || s == BSRight)))) {
948                 outerHeight += 2;
949                 innerHeight += 2;
950             }
951 
952             graphicsContext->setStrokeStyle(SolidStroke);
953             graphicsContext->setStrokeColor(color, m_style->colorSpace());
954             graphicsContext->setStrokeThickness(third);
955             graphicsContext->strokeArc(IntRect(x, outerY, radius.width() * 2, outerHeight), angleStart, angleSpan);
956             graphicsContext->setStrokeThickness(innerThird > 2 ? innerThird - 1 : innerThird);
957             graphicsContext->strokeArc(IntRect(innerX, innerY, innerWidth, innerHeight), angleStart, angleSpan);
958             break;
959         }
960         case GROOVE:
961         case RIDGE: {
962             Color c2;
963             if ((style == RIDGE && (s == BSTop || s == BSLeft)) ||
964                     (style == GROOVE && (s == BSBottom || s == BSRight)))
965                 c2 = color.dark();
966             else {
967                 c2 = color;
968                 color = color.dark();
969             }
970 
971             graphicsContext->setStrokeStyle(SolidStroke);
972             graphicsContext->setStrokeColor(color, m_style->colorSpace());
973             graphicsContext->setStrokeThickness(thickness);
974             graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
975 
976             float halfThickness = (thickness + 1.0f) / 4.0f;
977             int shiftForInner = static_cast<int>(halfThickness * 1.5f);
978             graphicsContext->setStrokeColor(c2, m_style->colorSpace());
979             graphicsContext->setStrokeThickness(halfThickness > 2 ? halfThickness - 1 : halfThickness);
980             graphicsContext->strokeArc(IntRect(x + shiftForInner, y + shiftForInner, (radius.width() - shiftForInner) * 2,
981                                        (radius.height() - shiftForInner) * 2), angleStart, angleSpan);
982             break;
983         }
984         case INSET:
985             if (s == BSTop || s == BSLeft)
986                 color = color.dark();
987         case OUTSET:
988             if (style == OUTSET && (s == BSBottom || s == BSRight))
989                 color = color.dark();
990         case SOLID:
991             graphicsContext->setStrokeStyle(SolidStroke);
992             graphicsContext->setStrokeColor(color, m_style->colorSpace());
993             graphicsContext->setStrokeThickness(thickness);
994             graphicsContext->strokeArc(IntRect(x, y, radius.width() * 2, radius.height() * 2), angleStart, angleSpan);
995             break;
996     }
997 }
998 #endif
999 
paintFocusRing(GraphicsContext * context,int tx,int ty,RenderStyle * style)1000 void RenderObject::paintFocusRing(GraphicsContext* context, int tx, int ty, RenderStyle* style)
1001 {
1002     Vector<IntRect> focusRingRects;
1003     addFocusRingRects(focusRingRects, tx, ty);
1004     if (style->outlineStyleIsAuto())
1005         context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
1006     else
1007         addPDFURLRect(context, unionRect(focusRingRects));
1008 }
1009 
addPDFURLRect(GraphicsContext * context,const IntRect & rect)1010 void RenderObject::addPDFURLRect(GraphicsContext* context, const IntRect& rect)
1011 {
1012     if (rect.isEmpty())
1013         return;
1014     Node* n = node();
1015     if (!n || !n->isLink() || !n->isElementNode())
1016         return;
1017     const AtomicString& href = static_cast<Element*>(n)->getAttribute(hrefAttr);
1018     if (href.isNull())
1019         return;
1020     context->setURLForRect(n->document()->completeURL(href), rect);
1021 }
1022 
paintOutline(GraphicsContext * graphicsContext,int tx,int ty,int w,int h)1023 void RenderObject::paintOutline(GraphicsContext* graphicsContext, int tx, int ty, int w, int h)
1024 {
1025     if (!hasOutline())
1026         return;
1027 
1028     RenderStyle* styleToUse = style();
1029     int outlineWidth = styleToUse->outlineWidth();
1030     EBorderStyle outlineStyle = styleToUse->outlineStyle();
1031 
1032     Color outlineColor = styleToUse->visitedDependentColor(CSSPropertyOutlineColor);
1033 
1034     int offset = styleToUse->outlineOffset();
1035 
1036     if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1037         if (!theme()->supportsFocusRing(styleToUse)) {
1038             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1039             paintFocusRing(graphicsContext, tx, ty, styleToUse);
1040         }
1041     }
1042 
1043     if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1044         return;
1045 
1046     tx -= offset;
1047     ty -= offset;
1048     w += 2 * offset;
1049     h += 2 * offset;
1050 
1051     if (h < 0 || w < 0)
1052         return;
1053 
1054     int leftOuter = tx - outlineWidth;
1055     int leftInner = tx;
1056     int rightOuter = tx + w + outlineWidth;
1057     int rightInner = tx + w;
1058     int topOuter = ty - outlineWidth;
1059     int topInner = ty;
1060     int bottomOuter = ty + h + outlineWidth;
1061     int bottomInner = ty + h;
1062 
1063     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1064     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1065     drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1066     drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1067 }
1068 
absoluteBoundingBoxRect(bool useTransforms)1069 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms)
1070 {
1071     if (useTransforms) {
1072         Vector<FloatQuad> quads;
1073         absoluteQuads(quads);
1074 
1075         size_t n = quads.size();
1076         if (!n)
1077             return IntRect();
1078 
1079         IntRect result = quads[0].enclosingBoundingBox();
1080         for (size_t i = 1; i < n; ++i)
1081             result.unite(quads[i].enclosingBoundingBox());
1082         return result;
1083     }
1084 
1085     FloatPoint absPos = localToAbsolute();
1086     Vector<IntRect> rects;
1087     absoluteRects(rects, absPos.x(), absPos.y());
1088 
1089     size_t n = rects.size();
1090     if (!n)
1091         return IntRect();
1092 
1093     IntRect result = rects[0];
1094     for (size_t i = 1; i < n; ++i)
1095         result.unite(rects[i]);
1096     return result;
1097 }
1098 
absoluteFocusRingQuads(Vector<FloatQuad> & quads)1099 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1100 {
1101     Vector<IntRect> rects;
1102     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1103     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1104     // implicitly assumes that. This doesn't work correctly with transformed
1105     // descendants.
1106     FloatPoint absolutePoint = localToAbsolute();
1107     addFocusRingRects(rects, absolutePoint.x(), absolutePoint.y());
1108     size_t count = rects.size();
1109     for (size_t i = 0; i < count; ++i) {
1110         IntRect rect = rects[i];
1111         rect.move(-absolutePoint.x(), -absolutePoint.y());
1112         quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1113     }
1114 }
1115 
addAbsoluteRectForLayer(IntRect & result)1116 void RenderObject::addAbsoluteRectForLayer(IntRect& result)
1117 {
1118     if (hasLayer())
1119         result.unite(absoluteBoundingBoxRect());
1120     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1121         current->addAbsoluteRectForLayer(result);
1122 }
1123 
paintingRootRect(IntRect & topLevelRect)1124 IntRect RenderObject::paintingRootRect(IntRect& topLevelRect)
1125 {
1126     IntRect result = absoluteBoundingBoxRect();
1127     topLevelRect = result;
1128     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1129         current->addAbsoluteRectForLayer(result);
1130     return result;
1131 }
1132 
paint(PaintInfo &,int,int)1133 void RenderObject::paint(PaintInfo& /*paintInfo*/, int /*tx*/, int /*ty*/)
1134 {
1135 }
1136 
containerForRepaint() const1137 RenderBoxModelObject* RenderObject::containerForRepaint() const
1138 {
1139 #if USE(ACCELERATED_COMPOSITING)
1140     if (RenderView* v = view()) {
1141         if (v->usesCompositing()) {
1142             RenderLayer* compLayer = enclosingLayer()->enclosingCompositingLayer();
1143             return compLayer ? compLayer->renderer() : 0;
1144         }
1145     }
1146 #endif
1147     // Do root-relative repaint.
1148     return 0;
1149 }
1150 
repaintUsingContainer(RenderBoxModelObject * repaintContainer,const IntRect & r,bool immediate)1151 void RenderObject::repaintUsingContainer(RenderBoxModelObject* repaintContainer, const IntRect& r, bool immediate)
1152 {
1153     if (!repaintContainer) {
1154         view()->repaintViewRectangle(r, immediate);
1155         return;
1156     }
1157 
1158 #if USE(ACCELERATED_COMPOSITING)
1159     RenderView* v = view();
1160     if (repaintContainer->isRenderView()) {
1161         ASSERT(repaintContainer == v);
1162         bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
1163         if (!viewHasCompositedLayer || v->layer()->backing()->paintingGoesToWindow()) {
1164             IntRect repaintRectangle = r;
1165             if (viewHasCompositedLayer &&  v->layer()->transform())
1166                 repaintRectangle = v->layer()->transform()->mapRect(r);
1167             v->repaintViewRectangle(repaintRectangle, immediate);
1168             return;
1169         }
1170     }
1171 
1172     if (v->usesCompositing()) {
1173         ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1174         repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
1175     }
1176 #else
1177     if (repaintContainer->isRenderView())
1178         toRenderView(repaintContainer)->repaintViewRectangle(r, immediate);
1179 #endif
1180 }
1181 
repaint(bool immediate)1182 void RenderObject::repaint(bool immediate)
1183 {
1184     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1185     RenderView* view;
1186     if (!isRooted(&view))
1187         return;
1188 
1189     if (view->printing())
1190         return; // Don't repaint if we're printing.
1191 
1192     RenderBoxModelObject* repaintContainer = containerForRepaint();
1193     repaintUsingContainer(repaintContainer ? repaintContainer : view, clippedOverflowRectForRepaint(repaintContainer), immediate);
1194 }
1195 
repaintRectangle(const IntRect & r,bool immediate)1196 void RenderObject::repaintRectangle(const IntRect& r, bool immediate)
1197 {
1198     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1199     RenderView* view;
1200     if (!isRooted(&view))
1201         return;
1202 
1203     if (view->printing())
1204         return; // Don't repaint if we're printing.
1205 
1206     IntRect dirtyRect(r);
1207 
1208     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1209     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1210     dirtyRect.move(view->layoutDelta());
1211 
1212     RenderBoxModelObject* repaintContainer = containerForRepaint();
1213     computeRectForRepaint(repaintContainer, dirtyRect);
1214     repaintUsingContainer(repaintContainer ? repaintContainer : view, dirtyRect, immediate);
1215 }
1216 
repaintAfterLayoutIfNeeded(RenderBoxModelObject * repaintContainer,const IntRect & oldBounds,const IntRect & oldOutlineBox,const IntRect * newBoundsPtr,const IntRect * newOutlineBoxRectPtr)1217 bool RenderObject::repaintAfterLayoutIfNeeded(RenderBoxModelObject* repaintContainer, const IntRect& oldBounds, const IntRect& oldOutlineBox, const IntRect* newBoundsPtr, const IntRect* newOutlineBoxRectPtr)
1218 {
1219     RenderView* v = view();
1220     if (v->printing())
1221         return false; // Don't repaint if we're printing.
1222 
1223     // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
1224     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1225     IntRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1226     IntRect newOutlineBox;
1227 
1228     bool fullRepaint = selfNeedsLayout();
1229     // Presumably a background or a border exists if border-fit:lines was specified.
1230     if (!fullRepaint && style()->borderFit() == BorderFitLines)
1231         fullRepaint = true;
1232     if (!fullRepaint) {
1233         // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
1234         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1235         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1236         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder() && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1237             fullRepaint = true;
1238     }
1239 
1240     if (!repaintContainer)
1241         repaintContainer = v;
1242 
1243     if (fullRepaint) {
1244         repaintUsingContainer(repaintContainer, oldBounds);
1245         if (newBounds != oldBounds)
1246             repaintUsingContainer(repaintContainer, newBounds);
1247         return true;
1248     }
1249 
1250     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1251         return false;
1252 
1253     int deltaLeft = newBounds.x() - oldBounds.x();
1254     if (deltaLeft > 0)
1255         repaintUsingContainer(repaintContainer, IntRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1256     else if (deltaLeft < 0)
1257         repaintUsingContainer(repaintContainer, IntRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1258 
1259     int deltaRight = newBounds.maxX() - oldBounds.maxX();
1260     if (deltaRight > 0)
1261         repaintUsingContainer(repaintContainer, IntRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1262     else if (deltaRight < 0)
1263         repaintUsingContainer(repaintContainer, IntRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1264 
1265     int deltaTop = newBounds.y() - oldBounds.y();
1266     if (deltaTop > 0)
1267         repaintUsingContainer(repaintContainer, IntRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1268     else if (deltaTop < 0)
1269         repaintUsingContainer(repaintContainer, IntRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1270 
1271     int deltaBottom = newBounds.maxY() - oldBounds.maxY();
1272     if (deltaBottom > 0)
1273         repaintUsingContainer(repaintContainer, IntRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1274     else if (deltaBottom < 0)
1275         repaintUsingContainer(repaintContainer, IntRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1276 
1277     if (newOutlineBox == oldOutlineBox)
1278         return false;
1279 
1280     // We didn't move, but we did change size.  Invalidate the delta, which will consist of possibly
1281     // two rectangles (but typically only one).
1282     RenderStyle* outlineStyle = outlineStyleForRepaint();
1283     int ow = outlineStyle->outlineSize();
1284     int width = abs(newOutlineBox.width() - oldOutlineBox.width());
1285     if (width) {
1286         int shadowLeft;
1287         int shadowRight;
1288         style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1289 
1290         int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1291         int boxWidth = isBox() ? toRenderBox(this)->width() : 0;
1292         int borderWidth = max(-outlineStyle->outlineOffset(), max(borderRight, max(style()->borderTopRightRadius().width().calcValue(boxWidth), style()->borderBottomRightRadius().width().calcValue(boxWidth)))) + max(ow, shadowRight);
1293         IntRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - borderWidth,
1294             newOutlineBox.y(),
1295             width + borderWidth,
1296             max(newOutlineBox.height(), oldOutlineBox.height()));
1297         int right = min(newBounds.maxX(), oldBounds.maxX());
1298         if (rightRect.x() < right) {
1299             rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1300             repaintUsingContainer(repaintContainer, rightRect);
1301         }
1302     }
1303     int height = abs(newOutlineBox.height() - oldOutlineBox.height());
1304     if (height) {
1305         int shadowTop;
1306         int shadowBottom;
1307         style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1308 
1309         int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1310         int boxHeight = isBox() ? toRenderBox(this)->height() : 0;
1311         int borderHeight = max(-outlineStyle->outlineOffset(), max(borderBottom, max(style()->borderBottomLeftRadius().height().calcValue(boxHeight), style()->borderBottomRightRadius().height().calcValue(boxHeight)))) + max(ow, shadowBottom);
1312         IntRect bottomRect(newOutlineBox.x(),
1313             min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - borderHeight,
1314             max(newOutlineBox.width(), oldOutlineBox.width()),
1315             height + borderHeight);
1316         int bottom = min(newBounds.maxY(), oldBounds.maxY());
1317         if (bottomRect.y() < bottom) {
1318             bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1319             repaintUsingContainer(repaintContainer, bottomRect);
1320         }
1321     }
1322     return false;
1323 }
1324 
repaintDuringLayoutIfMoved(const IntRect &)1325 void RenderObject::repaintDuringLayoutIfMoved(const IntRect&)
1326 {
1327 }
1328 
repaintOverhangingFloats(bool)1329 void RenderObject::repaintOverhangingFloats(bool)
1330 {
1331 }
1332 
checkForRepaintDuringLayout() const1333 bool RenderObject::checkForRepaintDuringLayout() const
1334 {
1335     // FIXME: <https://bugs.webkit.org/show_bug.cgi?id=20885> It is probably safe to also require
1336     // m_everHadLayout. Currently, only RenderBlock::layoutBlock() adds this condition. See also
1337     // <https://bugs.webkit.org/show_bug.cgi?id=15129>.
1338     return !document()->view()->needsFullRepaint() && !hasLayer();
1339 }
1340 
rectWithOutlineForRepaint(RenderBoxModelObject * repaintContainer,int outlineWidth)1341 IntRect RenderObject::rectWithOutlineForRepaint(RenderBoxModelObject* repaintContainer, int outlineWidth)
1342 {
1343     IntRect r(clippedOverflowRectForRepaint(repaintContainer));
1344     r.inflate(outlineWidth);
1345     return r;
1346 }
1347 
clippedOverflowRectForRepaint(RenderBoxModelObject *)1348 IntRect RenderObject::clippedOverflowRectForRepaint(RenderBoxModelObject*)
1349 {
1350     ASSERT_NOT_REACHED();
1351     return IntRect();
1352 }
1353 
computeRectForRepaint(RenderBoxModelObject * repaintContainer,IntRect & rect,bool fixed)1354 void RenderObject::computeRectForRepaint(RenderBoxModelObject* repaintContainer, IntRect& rect, bool fixed)
1355 {
1356     if (repaintContainer == this)
1357         return;
1358 
1359     if (RenderObject* o = parent()) {
1360         if (o->isBlockFlow()) {
1361             RenderBlock* cb = toRenderBlock(o);
1362             if (cb->hasColumns())
1363                 cb->adjustRectForColumns(rect);
1364         }
1365 
1366         if (o->hasOverflowClip()) {
1367             // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1368             // layer's size instead.  Even if the layer's size is wrong, the layer itself will repaint
1369             // anyway if its size does change.
1370             RenderBox* boxParent = toRenderBox(o);
1371 
1372             IntRect repaintRect(rect);
1373             repaintRect.move(-boxParent->layer()->scrolledContentOffset()); // For overflow:auto/scroll/hidden.
1374 
1375             IntRect boxRect(0, 0, boxParent->layer()->width(), boxParent->layer()->height());
1376             rect = intersection(repaintRect, boxRect);
1377             if (rect.isEmpty())
1378                 return;
1379         }
1380 
1381         o->computeRectForRepaint(repaintContainer, rect, fixed);
1382     }
1383 }
1384 
dirtyLinesFromChangedChild(RenderObject *)1385 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1386 {
1387 }
1388 
1389 #ifndef NDEBUG
1390 
showTreeForThis() const1391 void RenderObject::showTreeForThis() const
1392 {
1393     if (node())
1394         node()->showTreeForThis();
1395 }
1396 
showRenderTreeForThis() const1397 void RenderObject::showRenderTreeForThis() const
1398 {
1399     showRenderTree(this, 0);
1400 }
1401 
showLineTreeForThis() const1402 void RenderObject::showLineTreeForThis() const
1403 {
1404     if (containingBlock())
1405         containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1406 }
1407 
showRenderObject() const1408 void RenderObject::showRenderObject() const
1409 {
1410     showRenderObject(0);
1411 }
1412 
showRenderObject(int printedCharacters) const1413 void RenderObject::showRenderObject(int printedCharacters) const
1414 {
1415     // As this function is intended to be used when debugging, the
1416     // this pointer may be 0.
1417     if (!this) {
1418         fputs("(null)\n", stderr);
1419         return;
1420     }
1421 
1422     printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1423 
1424     if (node()) {
1425         if (printedCharacters)
1426             for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1427                 fputc(' ', stderr);
1428         fputc('\t', stderr);
1429         node()->showNode();
1430     } else
1431         fputc('\n', stderr);
1432 }
1433 
showRenderTreeAndMark(const RenderObject * markedObject1,const char * markedLabel1,const RenderObject * markedObject2,const char * markedLabel2,int depth) const1434 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1435 {
1436     int printedCharacters = 0;
1437     if (markedObject1 == this && markedLabel1)
1438         printedCharacters += fprintf(stderr, "%s", markedLabel1);
1439     if (markedObject2 == this && markedLabel2)
1440         printedCharacters += fprintf(stderr, "%s", markedLabel2);
1441     for (; printedCharacters < depth * 2; printedCharacters++)
1442         fputc(' ', stderr);
1443 
1444     showRenderObject(printedCharacters);
1445     if (!this)
1446         return;
1447 
1448     for (const RenderObject* child = firstChild(); child; child = child->nextSibling())
1449         child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1450 }
1451 
1452 #endif // NDEBUG
1453 
selectionBackgroundColor() const1454 Color RenderObject::selectionBackgroundColor() const
1455 {
1456     Color color;
1457     if (style()->userSelect() != SELECT_NONE) {
1458         RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(SELECTION);
1459         if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1460             color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1461         else
1462             color = frame()->selection()->isFocusedAndActive() ?
1463                     theme()->activeSelectionBackgroundColor() :
1464                     theme()->inactiveSelectionBackgroundColor();
1465     }
1466 
1467     return color;
1468 }
1469 
selectionColor(int colorProperty) const1470 Color RenderObject::selectionColor(int colorProperty) const
1471 {
1472     Color color;
1473     // If the element is unselectable, or we are only painting the selection,
1474     // don't override the foreground color with the selection foreground color.
1475     if (style()->userSelect() == SELECT_NONE
1476         || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1477         return color;
1478 
1479     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(SELECTION)) {
1480         color = pseudoStyle->visitedDependentColor(colorProperty);
1481         if (!color.isValid())
1482             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1483     } else
1484         color = frame()->selection()->isFocusedAndActive() ?
1485                 theme()->activeSelectionForegroundColor() :
1486                 theme()->inactiveSelectionForegroundColor();
1487 
1488     return color;
1489 }
1490 
selectionForegroundColor() const1491 Color RenderObject::selectionForegroundColor() const
1492 {
1493     return selectionColor(CSSPropertyWebkitTextFillColor);
1494 }
1495 
selectionEmphasisMarkColor() const1496 Color RenderObject::selectionEmphasisMarkColor() const
1497 {
1498     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1499 }
1500 
1501 #if ENABLE(DRAG_SUPPORT)
draggableNode(bool dhtmlOK,bool uaOK,int x,int y,bool & dhtmlWillDrag) const1502 Node* RenderObject::draggableNode(bool dhtmlOK, bool uaOK, int x, int y, bool& dhtmlWillDrag) const
1503 {
1504     if (!dhtmlOK && !uaOK)
1505         return 0;
1506 
1507     for (const RenderObject* curr = this; curr; curr = curr->parent()) {
1508         Node* elt = curr->node();
1509         if (elt && elt->nodeType() == Node::TEXT_NODE) {
1510             // Since there's no way for the author to address the -webkit-user-drag style for a text node,
1511             // we use our own judgement.
1512             if (uaOK && view()->frameView()->frame()->eventHandler()->shouldDragAutoNode(curr->node(), IntPoint(x, y))) {
1513                 dhtmlWillDrag = false;
1514                 return curr->node();
1515             }
1516             if (elt->canStartSelection())
1517                 // In this case we have a click in the unselected portion of text.  If this text is
1518                 // selectable, we want to start the selection process instead of looking for a parent
1519                 // to try to drag.
1520                 return 0;
1521         } else {
1522             EUserDrag dragMode = curr->style()->userDrag();
1523             if (dhtmlOK && dragMode == DRAG_ELEMENT) {
1524                 dhtmlWillDrag = true;
1525                 return curr->node();
1526             }
1527             if (uaOK && dragMode == DRAG_AUTO
1528                     && view()->frameView()->frame()->eventHandler()->shouldDragAutoNode(curr->node(), IntPoint(x, y))) {
1529                 dhtmlWillDrag = false;
1530                 return curr->node();
1531             }
1532         }
1533     }
1534     return 0;
1535 }
1536 #endif // ENABLE(DRAG_SUPPORT)
1537 
selectionStartEnd(int & spos,int & epos) const1538 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1539 {
1540     view()->selectionStartEnd(spos, epos);
1541 }
1542 
handleDynamicFloatPositionChange()1543 void RenderObject::handleDynamicFloatPositionChange()
1544 {
1545     // We have gone from not affecting the inline status of the parent flow to suddenly
1546     // having an impact.  See if there is a mismatch between the parent flow's
1547     // childrenInline() state and our state.
1548     setInline(style()->isDisplayInlineType());
1549     if (isInline() != parent()->childrenInline()) {
1550         if (!isInline())
1551             toRenderBoxModelObject(parent())->childBecameNonInline(this);
1552         else {
1553             // An anonymous block must be made to wrap this inline.
1554             RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1555             RenderObjectChildList* childlist = parent()->virtualChildren();
1556             childlist->insertChildNode(parent(), block, this);
1557             block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1558         }
1559     }
1560 }
1561 
setAnimatableStyle(PassRefPtr<RenderStyle> style)1562 void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
1563 {
1564     if (!isText() && style)
1565         setStyle(animation()->updateAnimations(this, style.get()));
1566     else
1567         setStyle(style);
1568 }
1569 
adjustStyleDifference(StyleDifference diff,unsigned contextSensitiveProperties) const1570 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1571 {
1572 #if USE(ACCELERATED_COMPOSITING)
1573     // If transform changed, and we are not composited, need to do a layout.
1574     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1575         // Text nodes share style with their parents but transforms don't apply to them,
1576         // hence the !isText() check.
1577         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
1578         if (!isText() && (!hasLayer() || !toRenderBoxModelObject(this)->layer()->isComposited())) {
1579             // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
1580             // then we actually need SimplifiedLayoutAndPositionedMovement.
1581             if (!hasLayer())
1582                 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
1583             else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
1584                 diff = StyleDifferenceSimplifiedLayout;
1585             else if (diff < StyleDifferenceSimplifiedLayout)
1586                 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
1587         } else if (diff < StyleDifferenceRecompositeLayer)
1588             diff = StyleDifferenceRecompositeLayer;
1589     }
1590 
1591     // If opacity changed, and we are not composited, need to repaint (also
1592     // ignoring text nodes)
1593     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
1594         if (!isText() && (!hasLayer() || !toRenderBoxModelObject(this)->layer()->isComposited()))
1595             diff = StyleDifferenceRepaintLayer;
1596         else if (diff < StyleDifferenceRecompositeLayer)
1597             diff = StyleDifferenceRecompositeLayer;
1598     }
1599 
1600     // The answer to requiresLayer() for plugins and iframes can change outside of the style system,
1601     // since it depends on whether we decide to composite these elements. When the layer status of
1602     // one of these elements changes, we need to force a layout.
1603     if (diff == StyleDifferenceEqual && style() && isBoxModelObject()) {
1604         if (hasLayer() != toRenderBoxModelObject(this)->requiresLayer())
1605             diff = StyleDifferenceLayout;
1606     }
1607 #else
1608     UNUSED_PARAM(contextSensitiveProperties);
1609 #endif
1610 
1611     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
1612     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
1613         diff = StyleDifferenceRepaint;
1614 
1615     return diff;
1616 }
1617 
setStyle(PassRefPtr<RenderStyle> style)1618 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
1619 {
1620     if (m_style == style) {
1621 #if USE(ACCELERATED_COMPOSITING)
1622         // We need to run through adjustStyleDifference() for iframes and plugins, so
1623         // style sharing is disabled for them. That should ensure that we never hit this code path.
1624         ASSERT(!isRenderIFrame() && !isEmbeddedObject() &&!isApplet());
1625 #endif
1626         return;
1627     }
1628 
1629     StyleDifference diff = StyleDifferenceEqual;
1630     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
1631     if (m_style)
1632         diff = m_style->diff(style.get(), contextSensitiveProperties);
1633 
1634     diff = adjustStyleDifference(diff, contextSensitiveProperties);
1635 
1636     styleWillChange(diff, style.get());
1637 
1638     RefPtr<RenderStyle> oldStyle = m_style.release();
1639     m_style = style;
1640 
1641     updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
1642     updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
1643 
1644     updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
1645     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
1646 
1647     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
1648     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
1649     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
1650         toRenderView(document()->renderer())->setMaximalOutlineSize(m_style->outlineSize());
1651 
1652     styleDidChange(diff, oldStyle.get());
1653 
1654     if (!m_parent || isText())
1655         return;
1656 
1657     // Now that the layer (if any) has been updated, we need to adjust the diff again,
1658     // check whether we should layout now, and decide if we need to repaint.
1659     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
1660 
1661     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
1662         if (updatedDiff == StyleDifferenceLayout)
1663             setNeedsLayoutAndPrefWidthsRecalc();
1664         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
1665             setNeedsPositionedMovementLayout();
1666         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1667             setNeedsPositionedMovementLayout();
1668             setNeedsSimplifiedNormalFlowLayout();
1669         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
1670             setNeedsSimplifiedNormalFlowLayout();
1671     }
1672 
1673     if (updatedDiff == StyleDifferenceRepaintLayer || updatedDiff == StyleDifferenceRepaint) {
1674         // Do a repaint with the new style now, e.g., for example if we go from
1675         // not having an outline to having an outline.
1676         repaint();
1677     }
1678 }
1679 
setStyleInternal(PassRefPtr<RenderStyle> style)1680 void RenderObject::setStyleInternal(PassRefPtr<RenderStyle> style)
1681 {
1682     m_style = style;
1683 }
1684 
styleWillChange(StyleDifference diff,const RenderStyle * newStyle)1685 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1686 {
1687     if (m_style) {
1688         // If our z-index changes value or our visibility changes,
1689         // we need to dirty our stacking context's z-order list.
1690         if (newStyle) {
1691             bool visibilityChanged = m_style->visibility() != newStyle->visibility()
1692                 || m_style->zIndex() != newStyle->zIndex()
1693                 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1694 #if ENABLE(DASHBOARD_SUPPORT)
1695             if (visibilityChanged)
1696                 document()->setDashboardRegionsDirty(true);
1697 #endif
1698             if (visibilityChanged && AXObjectCache::accessibilityEnabled())
1699                 document()->axObjectCache()->childrenChanged(this);
1700 
1701             // Keep layer hierarchy visibility bits up to date if visibility changes.
1702             if (m_style->visibility() != newStyle->visibility()) {
1703                 if (RenderLayer* l = enclosingLayer()) {
1704                     if (newStyle->visibility() == VISIBLE)
1705                         l->setHasVisibleContent(true);
1706                     else if (l->hasVisibleContent() && (this == l->renderer() || l->renderer()->style()->visibility() != VISIBLE)) {
1707                         l->dirtyVisibleContentStatus();
1708                         if (diff > StyleDifferenceRepaintLayer)
1709                             repaint();
1710                     }
1711                 }
1712             }
1713         }
1714 
1715         if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
1716             repaint();
1717         if (isFloating() && (m_style->floating() != newStyle->floating()))
1718             // For changes in float styles, we need to conceivably remove ourselves
1719             // from the floating objects list.
1720             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1721         else if (isPositioned() && (m_style->position() != newStyle->position()))
1722             // For changes in positioning styles, we need to conceivably remove ourselves
1723             // from the positioned objects list.
1724             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1725 
1726         s_affectsParentBlock = isFloatingOrPositioned() &&
1727             (!newStyle->isFloating() && newStyle->position() != AbsolutePosition && newStyle->position() != FixedPosition)
1728             && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
1729 
1730         // reset style flags
1731         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
1732             m_floating = false;
1733             m_positioned = false;
1734             m_relPositioned = false;
1735         }
1736         m_horizontalWritingMode = true;
1737         m_paintBackground = false;
1738         m_hasOverflowClip = false;
1739         m_hasTransform = false;
1740         m_hasReflection = false;
1741     } else
1742         s_affectsParentBlock = false;
1743 
1744     if (view()->frameView()) {
1745         bool shouldBlitOnFixedBackgroundImage = false;
1746 #if ENABLE(FAST_MOBILE_SCROLLING)
1747         // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
1748         // when scrolling a page with a fixed background image. As an optimization, assuming there are
1749         // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
1750         // ignore the CSS property "background-attachment: fixed".
1751         shouldBlitOnFixedBackgroundImage = true;
1752 #endif
1753 
1754         bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
1755         bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
1756         if (oldStyleSlowScroll != newStyleSlowScroll) {
1757             if (oldStyleSlowScroll)
1758                 view()->frameView()->removeSlowRepaintObject();
1759             if (newStyleSlowScroll)
1760                 view()->frameView()->addSlowRepaintObject();
1761         }
1762     }
1763 }
1764 
areNonIdenticalCursorListsEqual(const RenderStyle * a,const RenderStyle * b)1765 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
1766 {
1767     ASSERT(a->cursors() != b->cursors());
1768     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1769 }
1770 
areCursorsEqual(const RenderStyle * a,const RenderStyle * b)1771 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
1772 {
1773     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1774 }
1775 
styleDidChange(StyleDifference diff,const RenderStyle * oldStyle)1776 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1777 {
1778     if (s_affectsParentBlock)
1779         handleDynamicFloatPositionChange();
1780 
1781     if (!m_parent)
1782         return;
1783 
1784     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1785         RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
1786 
1787         // If the object already needs layout, then setNeedsLayout won't do
1788         // any work. But if the containing block has changed, then we may need
1789         // to mark the new containing blocks for layout. The change that can
1790         // directly affect the containing block of this object is a change to
1791         // the position style.
1792         if (m_needsLayout && oldStyle->position() != m_style->position())
1793             markContainingBlocksForLayout();
1794 
1795         if (diff == StyleDifferenceLayout)
1796             setNeedsLayoutAndPrefWidthsRecalc();
1797         else
1798             setNeedsSimplifiedNormalFlowLayout();
1799     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1800         setNeedsPositionedMovementLayout();
1801         setNeedsSimplifiedNormalFlowLayout();
1802     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1803         setNeedsPositionedMovementLayout();
1804 
1805     // Don't check for repaint here; we need to wait until the layer has been
1806     // updated by subclasses before we know if we have to repaint (in setStyle()).
1807 
1808     if (oldStyle && !areCursorsEqual(oldStyle, style())) {
1809         if (Frame* frame = this->frame())
1810             frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
1811     }
1812 }
1813 
propagateStyleToAnonymousChildren(bool blockChildrenOnly)1814 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
1815 {
1816     // FIXME: We could save this call when the change only affected non-inherited properties.
1817     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1818         if (blockChildrenOnly ? child->isAnonymousBlock() : child->isAnonymous() && !child->isBeforeOrAfterContent()) {
1819             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyle(style());
1820             if (style()->specifiesColumns()) {
1821                 if (child->style()->specifiesColumns())
1822                     newStyle->inheritColumnPropertiesFrom(style());
1823                 if (child->style()->columnSpan())
1824                     newStyle->setColumnSpan(true);
1825             }
1826             newStyle->setDisplay(blockChildrenOnly ? BLOCK : child->style()->display());
1827             child->setStyle(newStyle.release());
1828         }
1829     }
1830 }
1831 
updateFillImages(const FillLayer * oldLayers,const FillLayer * newLayers)1832 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
1833 {
1834     // Optimize the common case
1835     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
1836         return;
1837 
1838     // Go through the new layers and addClients first, to avoid removing all clients of an image.
1839     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
1840         if (currNew->image())
1841             currNew->image()->addClient(this);
1842     }
1843 
1844     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
1845         if (currOld->image())
1846             currOld->image()->removeClient(this);
1847     }
1848 }
1849 
updateImage(StyleImage * oldImage,StyleImage * newImage)1850 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
1851 {
1852     if (oldImage != newImage) {
1853         if (oldImage)
1854             oldImage->removeClient(this);
1855         if (newImage)
1856             newImage->addClient(this);
1857     }
1858 }
1859 
viewRect() const1860 IntRect RenderObject::viewRect() const
1861 {
1862     return view()->viewRect();
1863 }
1864 
localToAbsolute(const FloatPoint & localPoint,bool fixed,bool useTransforms) const1865 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, bool fixed, bool useTransforms) const
1866 {
1867     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1868     mapLocalToContainer(0, fixed, useTransforms, transformState);
1869     transformState.flatten();
1870 
1871     return transformState.lastPlanarPoint();
1872 }
1873 
absoluteToLocal(const FloatPoint & containerPoint,bool fixed,bool useTransforms) const1874 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, bool fixed, bool useTransforms) const
1875 {
1876     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1877     mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1878     transformState.flatten();
1879 
1880     return transformState.lastPlanarPoint();
1881 }
1882 
mapLocalToContainer(RenderBoxModelObject * repaintContainer,bool fixed,bool useTransforms,TransformState & transformState) const1883 void RenderObject::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState) const
1884 {
1885     if (repaintContainer == this)
1886         return;
1887 
1888     RenderObject* o = parent();
1889     if (!o)
1890         return;
1891 
1892     IntPoint centerPoint = roundedIntPoint(transformState.mappedPoint());
1893     if (o->isBox() && o->style()->isFlippedBlocksWritingMode())
1894         transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedIntPoint(transformState.mappedPoint())) - centerPoint);
1895 
1896     IntSize columnOffset;
1897     o->adjustForColumns(columnOffset, roundedIntPoint(transformState.mappedPoint()));
1898     if (!columnOffset.isZero())
1899         transformState.move(columnOffset);
1900 
1901     if (o->hasOverflowClip())
1902         transformState.move(-toRenderBox(o)->layer()->scrolledContentOffset());
1903 
1904     o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState);
1905 }
1906 
mapAbsoluteToLocalPoint(bool fixed,bool useTransforms,TransformState & transformState) const1907 void RenderObject::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1908 {
1909     RenderObject* o = parent();
1910     if (o) {
1911         o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1912         if (o->hasOverflowClip())
1913             transformState.move(toRenderBox(o)->layer()->scrolledContentOffset());
1914     }
1915 }
1916 
shouldUseTransformFromContainer(const RenderObject * containerObject) const1917 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1918 {
1919 #if ENABLE(3D_RENDERING)
1920     // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
1921     // so check the layer's transform directly.
1922     return (hasLayer() && toRenderBoxModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
1923 #else
1924     UNUSED_PARAM(containerObject);
1925     return hasTransform();
1926 #endif
1927 }
1928 
getTransformFromContainer(const RenderObject * containerObject,const IntSize & offsetInContainer,TransformationMatrix & transform) const1929 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const IntSize& offsetInContainer, TransformationMatrix& transform) const
1930 {
1931     transform.makeIdentity();
1932     transform.translate(offsetInContainer.width(), offsetInContainer.height());
1933     RenderLayer* layer;
1934     if (hasLayer() && (layer = toRenderBoxModelObject(this)->layer()) && layer->transform())
1935         transform.multiply(layer->currentTransform());
1936 
1937 #if ENABLE(3D_RENDERING)
1938     if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
1939         // Perpsective on the container affects us, so we have to factor it in here.
1940         ASSERT(containerObject->hasLayer());
1941         FloatPoint perspectiveOrigin = toRenderBoxModelObject(containerObject)->layer()->perspectiveOrigin();
1942 
1943         TransformationMatrix perspectiveMatrix;
1944         perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
1945 
1946         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1947         transform = perspectiveMatrix * transform;
1948         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1949     }
1950 #else
1951     UNUSED_PARAM(containerObject);
1952 #endif
1953 }
1954 
localToContainerQuad(const FloatQuad & localQuad,RenderBoxModelObject * repaintContainer,bool fixed) const1955 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, RenderBoxModelObject* repaintContainer, bool fixed) const
1956 {
1957     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1958     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1959     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), &localQuad);
1960     mapLocalToContainer(repaintContainer, fixed, true, transformState);
1961     transformState.flatten();
1962 
1963     return transformState.lastPlanarQuad();
1964 }
1965 
offsetFromContainer(RenderObject * o,const IntPoint & point) const1966 IntSize RenderObject::offsetFromContainer(RenderObject* o, const IntPoint& point) const
1967 {
1968     ASSERT(o == container());
1969 
1970     IntSize offset;
1971 
1972     o->adjustForColumns(offset, point);
1973 
1974     if (o->hasOverflowClip())
1975         offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1976 
1977     return offset;
1978 }
1979 
offsetFromAncestorContainer(RenderObject * container) const1980 IntSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
1981 {
1982     IntSize offset;
1983     IntPoint referencePoint;
1984     const RenderObject* currContainer = this;
1985     do {
1986         RenderObject* nextContainer = currContainer->container();
1987         ASSERT(nextContainer);  // This means we reached the top without finding container.
1988         if (!nextContainer)
1989             break;
1990         ASSERT(!currContainer->hasTransform());
1991         IntSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
1992         offset += currentOffset;
1993         referencePoint.move(currentOffset);
1994         currContainer = nextContainer;
1995     } while (currContainer != container);
1996 
1997     return offset;
1998 }
1999 
localCaretRect(InlineBox *,int,int * extraWidthToEndOfLine)2000 IntRect RenderObject::localCaretRect(InlineBox*, int, int* extraWidthToEndOfLine)
2001 {
2002     if (extraWidthToEndOfLine)
2003         *extraWidthToEndOfLine = 0;
2004 
2005     return IntRect();
2006 }
2007 
view() const2008 RenderView* RenderObject::view() const
2009 {
2010     return toRenderView(document()->renderer());
2011 }
2012 
isRooted(RenderView ** view)2013 bool RenderObject::isRooted(RenderView** view)
2014 {
2015     RenderObject* o = this;
2016     while (o->parent())
2017         o = o->parent();
2018 
2019     if (!o->isRenderView())
2020         return false;
2021 
2022     if (view)
2023         *view = toRenderView(o);
2024 
2025     return true;
2026 }
2027 
hasOutlineAnnotation() const2028 bool RenderObject::hasOutlineAnnotation() const
2029 {
2030     return node() && node()->isLink() && document()->printing();
2031 }
2032 
container(RenderBoxModelObject * repaintContainer,bool * repaintContainerSkipped) const2033 RenderObject* RenderObject::container(RenderBoxModelObject* repaintContainer, bool* repaintContainerSkipped) const
2034 {
2035     if (repaintContainerSkipped)
2036         *repaintContainerSkipped = false;
2037 
2038     // This method is extremely similar to containingBlock(), but with a few notable
2039     // exceptions.
2040     // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2041     // the object is not part of the primary document subtree yet.
2042     // (2) For normal flow elements, it just returns the parent.
2043     // (3) For absolute positioned elements, it will return a relative positioned inline.
2044     // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2045     // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
2046     // computePositionedLogicalHeight have to use container().
2047     RenderObject* o = parent();
2048 
2049     if (isText())
2050         return o;
2051 
2052     EPosition pos = m_style->position();
2053     if (pos == FixedPosition) {
2054         // container() can be called on an object that is not in the
2055         // tree yet.  We don't call view() since it will assert if it
2056         // can't get back to the canvas.  Instead we just walk as high up
2057         // as we can.  If we're in the tree, we'll get the root.  If we
2058         // aren't we'll get the root of our little subtree (most likely
2059         // we'll just return 0).
2060         // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
2061         // be safe now to use it.
2062         while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
2063             if (repaintContainerSkipped && o == repaintContainer)
2064                 *repaintContainerSkipped = true;
2065             o = o->parent();
2066         }
2067     } else if (pos == AbsolutePosition) {
2068         // Same goes here.  We technically just want our containing block, but
2069         // we may not have one if we're part of an uninstalled subtree.  We'll
2070         // climb as high as we can though.
2071         while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
2072             if (repaintContainerSkipped && o == repaintContainer)
2073                 *repaintContainerSkipped = true;
2074             o = o->parent();
2075         }
2076     }
2077 
2078     return o;
2079 }
2080 
isSelectionBorder() const2081 bool RenderObject::isSelectionBorder() const
2082 {
2083     SelectionState st = selectionState();
2084     return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2085 }
2086 
destroy()2087 void RenderObject::destroy()
2088 {
2089     // Destroy any leftover anonymous children.
2090     RenderObjectChildList* children = virtualChildren();
2091     if (children)
2092         children->destroyLeftoverChildren();
2093 
2094     // If this renderer is being autoscrolled, stop the autoscroll timer
2095 
2096     // FIXME: RenderObject::destroy should not get called with a renderer whose document
2097     // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
2098     // check that the frame is not null.
2099     ASSERT(frame());
2100     if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
2101         frame()->eventHandler()->stopAutoscrollTimer(true);
2102 
2103     if (AXObjectCache::accessibilityEnabled()) {
2104         document()->axObjectCache()->childrenChanged(this->parent());
2105         document()->axObjectCache()->remove(this);
2106     }
2107     animation()->cancelAnimations(this);
2108 
2109     // By default no ref-counting. RenderWidget::destroy() doesn't call
2110     // this function because it needs to do ref-counting. If anything
2111     // in this function changes, be sure to fix RenderWidget::destroy() as well.
2112 
2113     remove();
2114 
2115     // If this renderer had a parent, remove should have destroyed any counters
2116     // attached to this renderer and marked the affected other counters for
2117     // reevaluation. This apparently redundant check is here for the case when
2118     // this renderer had no parent at the time remove() was called.
2119 
2120     if (m_hasCounterNodeMap)
2121         RenderCounter::destroyCounterNodes(this);
2122 
2123     // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
2124     // be moved into RenderBoxModelObject::destroy.
2125     if (hasLayer()) {
2126         setHasLayer(false);
2127         toRenderBoxModelObject(this)->destroyLayer();
2128     }
2129     arenaDelete(renderArena(), this);
2130 }
2131 
arenaDelete(RenderArena * arena,void * base)2132 void RenderObject::arenaDelete(RenderArena* arena, void* base)
2133 {
2134     if (m_style) {
2135         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2136             if (StyleImage* backgroundImage = bgLayer->image())
2137                 backgroundImage->removeClient(this);
2138         }
2139 
2140         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2141             if (StyleImage* maskImage = maskLayer->image())
2142                 maskImage->removeClient(this);
2143         }
2144 
2145         if (StyleImage* borderImage = m_style->borderImage().image())
2146             borderImage->removeClient(this);
2147 
2148         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2149             maskBoxImage->removeClient(this);
2150     }
2151 
2152 #ifndef NDEBUG
2153     void* savedBase = baseOfRenderObjectBeingDeleted;
2154     baseOfRenderObjectBeingDeleted = base;
2155 #endif
2156     delete this;
2157 #ifndef NDEBUG
2158     baseOfRenderObjectBeingDeleted = savedBase;
2159 #endif
2160 
2161     // Recover the size left there for us by operator delete and free the memory.
2162     arena->free(*(size_t*)base, base);
2163 }
2164 
positionForCoordinates(int x,int y)2165 VisiblePosition RenderObject::positionForCoordinates(int x, int y)
2166 {
2167     return positionForPoint(IntPoint(x, y));
2168 }
2169 
positionForPoint(const IntPoint &)2170 VisiblePosition RenderObject::positionForPoint(const IntPoint&)
2171 {
2172     return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2173 }
2174 
updateDragState(bool dragOn)2175 void RenderObject::updateDragState(bool dragOn)
2176 {
2177     bool valueChanged = (dragOn != m_isDragging);
2178     m_isDragging = dragOn;
2179     if (valueChanged && style()->affectedByDragRules() && node())
2180         node()->setNeedsStyleRecalc();
2181     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2182         curr->updateDragState(dragOn);
2183 }
2184 
hitTest(const HitTestRequest & request,HitTestResult & result,const IntPoint & point,int tx,int ty,HitTestFilter hitTestFilter)2185 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const IntPoint& point, int tx, int ty, HitTestFilter hitTestFilter)
2186 {
2187     bool inside = false;
2188     if (hitTestFilter != HitTestSelf) {
2189         // First test the foreground layer (lines and inlines).
2190         inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestForeground);
2191 
2192         // Test floats next.
2193         if (!inside)
2194             inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestFloat);
2195 
2196         // Finally test to see if the mouse is in the background (within a child block's background).
2197         if (!inside)
2198             inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestChildBlockBackgrounds);
2199     }
2200 
2201     // See if the mouse is inside us but not any of our descendants
2202     if (hitTestFilter != HitTestDescendants && !inside)
2203         inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestBlockBackground);
2204 
2205     return inside;
2206 }
2207 
updateHitTestResult(HitTestResult & result,const IntPoint & point)2208 void RenderObject::updateHitTestResult(HitTestResult& result, const IntPoint& point)
2209 {
2210     if (result.innerNode())
2211         return;
2212 
2213     Node* n = node();
2214     if (n) {
2215         result.setInnerNode(n);
2216         if (!result.innerNonSharedNode())
2217             result.setInnerNonSharedNode(n);
2218         result.setLocalPoint(point);
2219     }
2220 }
2221 
nodeAtPoint(const HitTestRequest &,HitTestResult &,int,int,int,int,HitTestAction)2222 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, int /*x*/, int /*y*/, int /*tx*/, int /*ty*/, HitTestAction)
2223 {
2224     return false;
2225 }
2226 
scheduleRelayout()2227 void RenderObject::scheduleRelayout()
2228 {
2229     if (isRenderView()) {
2230         FrameView* view = toRenderView(this)->frameView();
2231         if (view)
2232             view->scheduleRelayout();
2233     } else if (parent()) {
2234         FrameView* v = view() ? view()->frameView() : 0;
2235         if (v)
2236             v->scheduleRelayoutOfSubtree(this);
2237     }
2238 }
2239 
layout()2240 void RenderObject::layout()
2241 {
2242     ASSERT(needsLayout());
2243     RenderObject* child = firstChild();
2244     while (child) {
2245         child->layoutIfNeeded();
2246         ASSERT(!child->needsLayout());
2247         child = child->nextSibling();
2248     }
2249     setNeedsLayout(false);
2250 }
2251 
uncachedFirstLineStyle(RenderStyle * style) const2252 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2253 {
2254     if (!document()->usesFirstLineRules())
2255         return 0;
2256 
2257     ASSERT(!isText());
2258 
2259     RefPtr<RenderStyle> result;
2260 
2261     if (isBlockFlow()) {
2262         if (RenderBlock* firstLineBlock = this->firstLineBlock())
2263             result = firstLineBlock->getUncachedPseudoStyle(FIRST_LINE, style, firstLineBlock == this ? style : 0);
2264     } else if (!isAnonymous() && isRenderInline()) {
2265         RenderStyle* parentStyle = parent()->firstLineStyle();
2266         if (parentStyle != parent()->style())
2267             result = getUncachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle, style);
2268     }
2269 
2270     return result.release();
2271 }
2272 
firstLineStyleSlowCase() const2273 RenderStyle* RenderObject::firstLineStyleSlowCase() const
2274 {
2275     ASSERT(document()->usesFirstLineRules());
2276 
2277     RenderStyle* style = m_style.get();
2278     const RenderObject* renderer = isText() ? parent() : this;
2279     if (renderer->isBlockFlow()) {
2280         if (RenderBlock* firstLineBlock = renderer->firstLineBlock())
2281             style = firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2282     } else if (!renderer->isAnonymous() && renderer->isRenderInline()) {
2283         RenderStyle* parentStyle = renderer->parent()->firstLineStyle();
2284         if (parentStyle != renderer->parent()->style()) {
2285             // A first-line style is in effect. Cache a first-line style for ourselves.
2286             renderer->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2287             style = renderer->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2288         }
2289     }
2290 
2291     return style;
2292 }
2293 
getCachedPseudoStyle(PseudoId pseudo,RenderStyle * parentStyle) const2294 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2295 {
2296     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2297         return 0;
2298 
2299     RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2300     if (cachedStyle)
2301         return cachedStyle;
2302 
2303     RefPtr<RenderStyle> result = getUncachedPseudoStyle(pseudo, parentStyle);
2304     if (result)
2305         return style()->addCachedPseudoStyle(result.release());
2306     return 0;
2307 }
2308 
getUncachedPseudoStyle(PseudoId pseudo,RenderStyle * parentStyle,RenderStyle * ownStyle) const2309 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2310 {
2311     if (pseudo < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudo))
2312         return 0;
2313 
2314     if (!parentStyle) {
2315         ASSERT(!ownStyle);
2316         parentStyle = style();
2317     }
2318 
2319     Node* n = node();
2320     while (n && !n->isElementNode())
2321         n = n->parentNode();
2322     if (!n)
2323         return 0;
2324 
2325     RefPtr<RenderStyle> result;
2326     if (pseudo == FIRST_LINE_INHERITED) {
2327         result = document()->styleSelector()->styleForElement(static_cast<Element*>(n), parentStyle, false);
2328         result->setStyleType(FIRST_LINE_INHERITED);
2329     } else
2330         result = document()->styleSelector()->pseudoStyleForElement(pseudo, static_cast<Element*>(n), parentStyle);
2331     return result.release();
2332 }
2333 
decorationColor(RenderObject * renderer)2334 static Color decorationColor(RenderObject* renderer)
2335 {
2336     Color result;
2337     if (renderer->style()->textStrokeWidth() > 0) {
2338         // Prefer stroke color if possible but not if it's fully transparent.
2339         result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2340         if (result.alpha())
2341             return result;
2342     }
2343 
2344     result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2345     return result;
2346 }
2347 
getTextDecorationColors(int decorations,Color & underline,Color & overline,Color & linethrough,bool quirksMode)2348 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2349                                            Color& linethrough, bool quirksMode)
2350 {
2351     RenderObject* curr = this;
2352     do {
2353         int currDecs = curr->style()->textDecoration();
2354         if (currDecs) {
2355             if (currDecs & UNDERLINE) {
2356                 decorations &= ~UNDERLINE;
2357                 underline = decorationColor(curr);
2358             }
2359             if (currDecs & OVERLINE) {
2360                 decorations &= ~OVERLINE;
2361                 overline = decorationColor(curr);
2362             }
2363             if (currDecs & LINE_THROUGH) {
2364                 decorations &= ~LINE_THROUGH;
2365                 linethrough = decorationColor(curr);
2366             }
2367         }
2368         curr = curr->parent();
2369         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2370             curr = toRenderBlock(curr)->continuation();
2371     } while (curr && decorations && (!quirksMode || !curr->node() ||
2372                                      (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
2373 
2374     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2375     if (decorations && curr) {
2376         if (decorations & UNDERLINE)
2377             underline = decorationColor(curr);
2378         if (decorations & OVERLINE)
2379             overline = decorationColor(curr);
2380         if (decorations & LINE_THROUGH)
2381             linethrough = decorationColor(curr);
2382     }
2383 }
2384 
2385 #if ENABLE(DASHBOARD_SUPPORT)
addDashboardRegions(Vector<DashboardRegionValue> & regions)2386 void RenderObject::addDashboardRegions(Vector<DashboardRegionValue>& regions)
2387 {
2388     // Convert the style regions to absolute coordinates.
2389     if (style()->visibility() != VISIBLE || !isBox())
2390         return;
2391 
2392     RenderBox* box = toRenderBox(this);
2393 
2394     const Vector<StyleDashboardRegion>& styleRegions = style()->dashboardRegions();
2395     unsigned i, count = styleRegions.size();
2396     for (i = 0; i < count; i++) {
2397         StyleDashboardRegion styleRegion = styleRegions[i];
2398 
2399         int w = box->width();
2400         int h = box->height();
2401 
2402         DashboardRegionValue region;
2403         region.label = styleRegion.label;
2404         region.bounds = IntRect(styleRegion.offset.left().value(),
2405                                 styleRegion.offset.top().value(),
2406                                 w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2407                                 h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2408         region.type = styleRegion.type;
2409 
2410         region.clip = region.bounds;
2411         computeAbsoluteRepaintRect(region.clip);
2412         if (region.clip.height() < 0) {
2413             region.clip.setHeight(0);
2414             region.clip.setWidth(0);
2415         }
2416 
2417         FloatPoint absPos = localToAbsolute();
2418         region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2419         region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2420 
2421         if (frame()) {
2422             float pageScaleFactor = frame()->page()->chrome()->scaleFactor();
2423             if (pageScaleFactor != 1.0f) {
2424                 region.bounds.scale(pageScaleFactor);
2425                 region.clip.scale(pageScaleFactor);
2426             }
2427         }
2428 
2429         regions.append(region);
2430     }
2431 }
2432 
collectDashboardRegions(Vector<DashboardRegionValue> & regions)2433 void RenderObject::collectDashboardRegions(Vector<DashboardRegionValue>& regions)
2434 {
2435     // RenderTexts don't have their own style, they just use their parent's style,
2436     // so we don't want to include them.
2437     if (isText())
2438         return;
2439 
2440     addDashboardRegions(regions);
2441     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2442         curr->collectDashboardRegions(regions);
2443 }
2444 #endif
2445 
willRenderImage(CachedImage *)2446 bool RenderObject::willRenderImage(CachedImage*)
2447 {
2448     // Without visibility we won't render (and therefore don't care about animation).
2449     if (style()->visibility() != VISIBLE)
2450         return false;
2451 
2452     // 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)
2453     // then we don't want to render either.
2454     return !document()->inPageCache() && !document()->view()->isOffscreen();
2455 }
2456 
maximalOutlineSize(PaintPhase p) const2457 int RenderObject::maximalOutlineSize(PaintPhase p) const
2458 {
2459     if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2460         return 0;
2461     return toRenderView(document()->renderer())->maximalOutlineSize();
2462 }
2463 
caretMinOffset() const2464 int RenderObject::caretMinOffset() const
2465 {
2466     return 0;
2467 }
2468 
caretMaxOffset() const2469 int RenderObject::caretMaxOffset() const
2470 {
2471     if (isReplaced())
2472         return node() ? max(1U, node()->childNodeCount()) : 1;
2473     if (isHR())
2474         return 1;
2475     return 0;
2476 }
2477 
caretMaxRenderedOffset() const2478 unsigned RenderObject::caretMaxRenderedOffset() const
2479 {
2480     return 0;
2481 }
2482 
previousOffset(int current) const2483 int RenderObject::previousOffset(int current) const
2484 {
2485     return current - 1;
2486 }
2487 
previousOffsetForBackwardDeletion(int current) const2488 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2489 {
2490     return current - 1;
2491 }
2492 
nextOffset(int current) const2493 int RenderObject::nextOffset(int current) const
2494 {
2495     return current + 1;
2496 }
2497 
adjustRectForOutlineAndShadow(IntRect & rect) const2498 void RenderObject::adjustRectForOutlineAndShadow(IntRect& rect) const
2499 {
2500     int outlineSize = outlineStyleForRepaint()->outlineSize();
2501     if (const ShadowData* boxShadow = style()->boxShadow()) {
2502         boxShadow->adjustRectForShadow(rect, outlineSize);
2503         return;
2504     }
2505 
2506     rect.inflate(outlineSize);
2507 }
2508 
animation() const2509 AnimationController* RenderObject::animation() const
2510 {
2511     return frame()->animation();
2512 }
2513 
imageChanged(CachedImage * image,const IntRect * rect)2514 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
2515 {
2516     imageChanged(static_cast<WrappedImagePtr>(image), rect);
2517 }
2518 
offsetParent() const2519 RenderBoxModelObject* RenderObject::offsetParent() const
2520 {
2521     // If any of the following holds true return null and stop this algorithm:
2522     // A is the root element.
2523     // A is the HTML body element.
2524     // The computed value of the position property for element A is fixed.
2525     if (isRoot() || isBody() || (isPositioned() && style()->position() == FixedPosition))
2526         return 0;
2527 
2528     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
2529     // chain return the nearest ancestor map HTML element and stop this algorithm.
2530     // FIXME: Implement!
2531 
2532     // Return the nearest ancestor element of A for which at least one of the following is
2533     // true and stop this algorithm if such an ancestor is found:
2534     //     * The computed value of the position property is not static.
2535     //     * It is the HTML body element.
2536     //     * The computed value of the position property of A is static and the ancestor
2537     //       is one of the following HTML elements: td, th, or table.
2538     //     * Our own extension: if there is a difference in the effective zoom
2539 
2540     bool skipTables = isPositioned() || isRelPositioned();
2541     float currZoom = style()->effectiveZoom();
2542     RenderObject* curr = parent();
2543     while (curr && (!curr->node() || (!curr->isPositioned() && !curr->isRelPositioned() && !curr->isBody()))) {
2544         Node* element = curr->node();
2545         if (!skipTables && element && (element->hasTagName(tableTag) || element->hasTagName(tdTag) || element->hasTagName(thTag)))
2546             break;
2547 
2548         float newZoom = curr->style()->effectiveZoom();
2549         if (currZoom != newZoom)
2550             break;
2551         currZoom = newZoom;
2552         curr = curr->parent();
2553     }
2554     return curr && curr->isBoxModelObject() ? toRenderBoxModelObject(curr) : 0;
2555 }
2556 
createVisiblePosition(int offset,EAffinity affinity)2557 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity)
2558 {
2559     // If this is a non-anonymous renderer in an editable area, then it's simple.
2560     if (Node* node = this->node()) {
2561         if (!node->rendererIsEditable()) {
2562             // If it can be found, we prefer a visually equivalent position that is editable.
2563             Position position(node, offset);
2564             Position candidate = position.downstream(CanCrossEditingBoundary);
2565             if (candidate.deprecatedNode()->rendererIsEditable())
2566                 return VisiblePosition(candidate, affinity);
2567             candidate = position.upstream(CanCrossEditingBoundary);
2568             if (candidate.deprecatedNode()->rendererIsEditable())
2569                 return VisiblePosition(candidate, affinity);
2570         }
2571         // FIXME: Eliminate legacy editing positions
2572         return VisiblePosition(Position(node, offset), affinity);
2573     }
2574 
2575     // We don't want to cross the boundary between editable and non-editable
2576     // regions of the document, but that is either impossible or at least
2577     // extremely unlikely in any normal case because we stop as soon as we
2578     // find a single non-anonymous renderer.
2579 
2580     // Find a nearby non-anonymous renderer.
2581     RenderObject* child = this;
2582     while (RenderObject* parent = child->parent()) {
2583         // Find non-anonymous content after.
2584         RenderObject* renderer = child;
2585         while ((renderer = renderer->nextInPreOrder(parent))) {
2586             if (Node* node = renderer->node())
2587                 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2588         }
2589 
2590         // Find non-anonymous content before.
2591         renderer = child;
2592         while ((renderer = renderer->previousInPreOrder())) {
2593             if (renderer == parent)
2594                 break;
2595             if (Node* node = renderer->node())
2596                 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
2597         }
2598 
2599         // Use the parent itself unless it too is anonymous.
2600         if (Node* node = parent->node())
2601             return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2602 
2603         // Repeat at the next level up.
2604         child = parent;
2605     }
2606 
2607     // Everything was anonymous. Give up.
2608     return VisiblePosition();
2609 }
2610 
createVisiblePosition(const Position & position)2611 VisiblePosition RenderObject::createVisiblePosition(const Position& position)
2612 {
2613     if (position.isNotNull())
2614         return VisiblePosition(position);
2615 
2616     ASSERT(!node());
2617     return createVisiblePosition(0, DOWNSTREAM);
2618 }
2619 
2620 #if ENABLE(SVG)
toRenderSVGResourceContainer()2621 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
2622 {
2623     ASSERT_NOT_REACHED();
2624     return 0;
2625 }
2626 
setNeedsBoundariesUpdate()2627 void RenderObject::setNeedsBoundariesUpdate()
2628 {
2629     if (RenderObject* renderer = parent())
2630         renderer->setNeedsBoundariesUpdate();
2631 }
2632 
objectBoundingBox() const2633 FloatRect RenderObject::objectBoundingBox() const
2634 {
2635     ASSERT_NOT_REACHED();
2636     return FloatRect();
2637 }
2638 
strokeBoundingBox() const2639 FloatRect RenderObject::strokeBoundingBox() const
2640 {
2641     ASSERT_NOT_REACHED();
2642     return FloatRect();
2643 }
2644 
2645 // Returns the smallest rectangle enclosing all of the painted content
2646 // respecting clipping, masking, filters, opacity, stroke-width and markers
repaintRectInLocalCoordinates() const2647 FloatRect RenderObject::repaintRectInLocalCoordinates() const
2648 {
2649     ASSERT_NOT_REACHED();
2650     return FloatRect();
2651 }
2652 
localTransform() const2653 AffineTransform RenderObject::localTransform() const
2654 {
2655     static const AffineTransform identity;
2656     return identity;
2657 }
2658 
localToParentTransform() const2659 const AffineTransform& RenderObject::localToParentTransform() const
2660 {
2661     static const AffineTransform identity;
2662     return identity;
2663 }
2664 
nodeAtFloatPoint(const HitTestRequest &,HitTestResult &,const FloatPoint &,HitTestAction)2665 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2666 {
2667     ASSERT_NOT_REACHED();
2668     return false;
2669 }
2670 
2671 #endif // ENABLE(SVG)
2672 
2673 } // namespace WebCore
2674 
2675 #ifndef NDEBUG
2676 
showTree(const WebCore::RenderObject * object)2677 void showTree(const WebCore::RenderObject* object)
2678 {
2679     if (object)
2680         object->showTreeForThis();
2681 }
2682 
showLineTree(const WebCore::RenderObject * object)2683 void showLineTree(const WebCore::RenderObject* object)
2684 {
2685     if (object)
2686         object->showLineTreeForThis();
2687 }
2688 
showRenderTree(const WebCore::RenderObject * object1)2689 void showRenderTree(const WebCore::RenderObject* object1)
2690 {
2691     showRenderTree(object1, 0);
2692 }
2693 
showRenderTree(const WebCore::RenderObject * object1,const WebCore::RenderObject * object2)2694 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
2695 {
2696     if (object1) {
2697         const WebCore::RenderObject* root = object1;
2698         while (root->parent())
2699             root = root->parent();
2700         root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
2701     }
2702 }
2703 
2704 #endif
2705