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