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