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