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