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