[BlackBerry] WebOverlay: fix access to m_client
[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     EFillSizeType sizeType = layer->sizeType();
833
834     if (sizeType == Contain || sizeType == Cover)
835         return true;
836     
837     if (sizeType == SizeLength) {
838         if (layer->sizeLength().width().isPercent() || layer->sizeLength().height().isPercent())
839             return true;
840     } else if (img->usesImageContainerSize())
841         return true;
842
843     return false;
844 }
845
846 bool RenderObject::borderImageIsLoadedAndCanBeRendered() const
847 {
848     ASSERT(style()->hasBorder());
849
850     StyleImage* borderImage = style()->borderImage().image();
851     return borderImage && borderImage->canRender(this, style()->effectiveZoom()) && borderImage->isLoaded();
852 }
853
854 bool RenderObject::mustRepaintBackgroundOrBorder() const
855 {
856     if (hasMask() && mustRepaintFillLayers(this, style()->maskLayers()))
857         return true;
858
859     // If we don't have a background/border/mask, then nothing to do.
860     if (!hasBoxDecorations())
861         return false;
862
863     if (mustRepaintFillLayers(this, style()->backgroundLayers()))
864         return true;
865      
866     // Our fill layers are ok.  Let's check border.
867     if (style()->hasBorder() && borderImageIsLoadedAndCanBeRendered())
868         return true;
869
870     return false;
871 }
872
873 void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
874                                       BoxSide side, Color color, EBorderStyle style,
875                                       int adjacentWidth1, int adjacentWidth2, bool antialias)
876 {
877     int thickness;
878     int length;
879     if (side == BSTop || side == BSBottom) {
880         thickness = y2 - y1;
881         length = x2 - x1;
882     } else {
883         thickness = x2 - x1;
884         length = y2 - y1;
885     }
886
887     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
888     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
889     if (!thickness || !length)
890         return;
891
892     if (style == DOUBLE && thickness < 3)
893         style = SOLID;
894
895     switch (style) {
896         case BNONE:
897         case BHIDDEN:
898             return;
899         case DOTTED:
900         case DASHED: {
901             graphicsContext->setStrokeColor(color, m_style->colorSpace());
902             graphicsContext->setStrokeThickness(thickness);
903             StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
904             graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
905
906             if (thickness > 0) {
907                 bool wasAntialiased = graphicsContext->shouldAntialias();
908                 graphicsContext->setShouldAntialias(antialias);
909
910                 switch (side) {
911                     case BSBottom:
912                     case BSTop:
913                         graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
914                         break;
915                     case BSRight:
916                     case BSLeft:
917                         graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
918                         break;
919                 }
920                 graphicsContext->setShouldAntialias(wasAntialiased);
921                 graphicsContext->setStrokeStyle(oldStrokeStyle);
922             }
923             break;
924         }
925         case DOUBLE: {
926             int thirdOfThickness = (thickness + 1) / 3;
927             ASSERT(thirdOfThickness);
928
929             if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
930                 StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
931                 graphicsContext->setStrokeStyle(NoStroke);
932                 graphicsContext->setFillColor(color, m_style->colorSpace());
933                 
934                 bool wasAntialiased = graphicsContext->shouldAntialias();
935                 graphicsContext->setShouldAntialias(antialias);
936
937                 switch (side) {
938                     case BSTop:
939                     case BSBottom:
940                         graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
941                         graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
942                         break;
943                     case BSLeft:
944                     case BSRight:
945                         // FIXME: Why do we offset the border by 1 in this case but not the other one?
946                         if (length > 1) {
947                             graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
948                             graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
949                         }
950                         break;
951                 }
952
953                 graphicsContext->setShouldAntialias(wasAntialiased);
954                 graphicsContext->setStrokeStyle(oldStrokeStyle);
955             } else {
956                 int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
957                 int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
958
959                 switch (side) {
960                     case BSTop:
961                         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
962                                    y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
963                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
964                         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
965                                    y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
966                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
967                         break;
968                     case BSLeft:
969                         drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
970                                    x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
971                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
972                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
973                                    x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
974                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
975                         break;
976                     case BSBottom:
977                         drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
978                                    y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
979                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
980                         drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
981                                    y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
982                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
983                         break;
984                     case BSRight:
985                         drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
986                                    x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
987                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
988                         drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
989                                    x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
990                                    side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
991                         break;
992                     default:
993                         break;
994                 }
995             }
996             break;
997         }
998         case RIDGE:
999         case GROOVE: {
1000             EBorderStyle s1;
1001             EBorderStyle s2;
1002             if (style == GROOVE) {
1003                 s1 = INSET;
1004                 s2 = OUTSET;
1005             } else {
1006                 s1 = OUTSET;
1007                 s2 = INSET;
1008             }
1009
1010             int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
1011             int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
1012
1013             switch (side) {
1014                 case BSTop:
1015                     drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1016                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1017                     drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
1018                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1019                     break;
1020                 case BSLeft:
1021                     drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
1022                                side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
1023                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
1024                                side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1025                     break;
1026                 case BSBottom:
1027                     drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
1028                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1029                     drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
1030                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1031                     break;
1032                 case BSRight:
1033                     drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
1034                                side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
1035                     drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
1036                                side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
1037                     break;
1038             }
1039             break;
1040         }
1041         case INSET:
1042             // FIXME: Maybe we should lighten the colors on one side like Firefox.
1043             // https://bugs.webkit.org/show_bug.cgi?id=58608
1044             if (side == BSTop || side == BSLeft)
1045                 color = color.dark();
1046             // fall through
1047         case OUTSET:
1048             if (style == OUTSET && (side == BSBottom || side == BSRight))
1049                 color = color.dark();
1050             // fall through
1051         case SOLID: {
1052             StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
1053             graphicsContext->setStrokeStyle(NoStroke);
1054             graphicsContext->setFillColor(color, m_style->colorSpace());
1055             ASSERT(x2 >= x1);
1056             ASSERT(y2 >= y1);
1057             if (!adjacentWidth1 && !adjacentWidth2) {
1058                 // Turn off antialiasing to match the behavior of drawConvexPolygon();
1059                 // this matters for rects in transformed contexts.
1060                 bool wasAntialiased = graphicsContext->shouldAntialias();
1061                 graphicsContext->setShouldAntialias(antialias);
1062                 graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
1063                 graphicsContext->setShouldAntialias(wasAntialiased);
1064                 graphicsContext->setStrokeStyle(oldStrokeStyle);
1065                 return;
1066             }
1067             FloatPoint quad[4];
1068             switch (side) {
1069                 case BSTop:
1070                     quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
1071                     quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
1072                     quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
1073                     quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
1074                     break;
1075                 case BSBottom:
1076                     quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
1077                     quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
1078                     quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
1079                     quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
1080                     break;
1081                 case BSLeft:
1082                     quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
1083                     quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
1084                     quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
1085                     quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
1086                     break;
1087                 case BSRight:
1088                     quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
1089                     quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
1090                     quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
1091                     quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
1092                     break;
1093             }
1094
1095             graphicsContext->drawConvexPolygon(4, quad, antialias);
1096             graphicsContext->setStrokeStyle(oldStrokeStyle);
1097             break;
1098         }
1099     }
1100 }
1101
1102 void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
1103 {
1104     Vector<IntRect> focusRingRects;
1105     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
1106     if (style->outlineStyleIsAuto())
1107         paintInfo.context->drawFocusRing(focusRingRects, style->outlineWidth(), style->outlineOffset(), style->visitedDependentColor(CSSPropertyOutlineColor));
1108     else
1109         addPDFURLRect(paintInfo.context, unionRect(focusRingRects));
1110 }
1111
1112 void RenderObject::addPDFURLRect(GraphicsContext* context, const LayoutRect& rect)
1113 {
1114     if (rect.isEmpty())
1115         return;
1116     Node* n = node();
1117     if (!n || !n->isLink() || !n->isElementNode())
1118         return;
1119     const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
1120     if (href.isNull())
1121         return;
1122     context->setURLForRect(n->document()->completeURL(href), pixelSnappedIntRect(rect));
1123 }
1124
1125 void RenderObject::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1126 {
1127     if (!hasOutline())
1128         return;
1129
1130     RenderStyle* styleToUse = style();
1131     LayoutUnit outlineWidth = styleToUse->outlineWidth();
1132
1133     int outlineOffset = styleToUse->outlineOffset();
1134
1135     if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
1136         if (!theme()->supportsFocusRing(styleToUse)) {
1137             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
1138             paintFocusRing(paintInfo, paintRect.location(), styleToUse);
1139         }
1140     }
1141
1142     if (styleToUse->outlineStyleIsAuto() || styleToUse->outlineStyle() == BNONE)
1143         return;
1144
1145     IntRect inner = pixelSnappedIntRect(paintRect);
1146     inner.inflate(outlineOffset);
1147
1148     IntRect outer = pixelSnappedIntRect(inner);
1149     outer.inflate(outlineWidth);
1150
1151     // FIXME: This prevents outlines from painting inside the object. See bug 12042
1152     if (outer.isEmpty())
1153         return;
1154
1155     EBorderStyle outlineStyle = styleToUse->outlineStyle();
1156     Color outlineColor = styleToUse->visitedDependentColor(CSSPropertyOutlineColor);
1157
1158     GraphicsContext* graphicsContext = paintInfo.context;
1159     bool useTransparencyLayer = outlineColor.hasAlpha();
1160     if (useTransparencyLayer) {
1161         if (outlineStyle == SOLID) {
1162             Path path;
1163             path.addRect(outer);
1164             path.addRect(inner);
1165             graphicsContext->setFillRule(RULE_EVENODD);
1166             graphicsContext->setFillColor(outlineColor, styleToUse->colorSpace());
1167             graphicsContext->fillPath(path);
1168             return;
1169         }
1170         graphicsContext->beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
1171         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
1172     }
1173
1174     int leftOuter = outer.x();
1175     int leftInner = inner.x();
1176     int rightOuter = outer.maxX();
1177     int rightInner = inner.maxX();
1178     int topOuter = outer.y();
1179     int topInner = inner.y();
1180     int bottomOuter = outer.maxY();
1181     int bottomInner = inner.maxY();
1182     
1183     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, leftInner, bottomOuter, BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1184     drawLineForBoxSide(graphicsContext, leftOuter, topOuter, rightOuter, topInner, BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1185     drawLineForBoxSide(graphicsContext, rightInner, topOuter, rightOuter, bottomOuter, BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1186     drawLineForBoxSide(graphicsContext, leftOuter, bottomInner, rightOuter, bottomOuter, BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1187
1188     if (useTransparencyLayer)
1189         graphicsContext->endTransparencyLayer();
1190 }
1191
1192 IntRect RenderObject::absoluteBoundingBoxRect(bool useTransforms) const
1193 {
1194     if (useTransforms) {
1195         Vector<FloatQuad> quads;
1196         absoluteQuads(quads);
1197
1198         size_t n = quads.size();
1199         if (!n)
1200             return IntRect();
1201     
1202         IntRect result = quads[0].enclosingBoundingBox();
1203         for (size_t i = 1; i < n; ++i)
1204             result.unite(quads[i].enclosingBoundingBox());
1205         return result;
1206     }
1207
1208     FloatPoint absPos = localToAbsolute();
1209     Vector<IntRect> rects;
1210     absoluteRects(rects, flooredLayoutPoint(absPos));
1211
1212     size_t n = rects.size();
1213     if (!n)
1214         return IntRect();
1215
1216     LayoutRect result = rects[0];
1217     for (size_t i = 1; i < n; ++i)
1218         result.unite(rects[i]);
1219     return pixelSnappedIntRect(result);
1220 }
1221
1222 void RenderObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads)
1223 {
1224     Vector<IntRect> rects;
1225     // FIXME: addFocusRingRects() needs to be passed this transform-unaware
1226     // localToAbsolute() offset here because RenderInline::addFocusRingRects()
1227     // implicitly assumes that. This doesn't work correctly with transformed
1228     // descendants.
1229     FloatPoint absolutePoint = localToAbsolute();
1230     addFocusRingRects(rects, flooredLayoutPoint(absolutePoint));
1231     size_t count = rects.size();
1232     for (size_t i = 0; i < count; ++i) {
1233         IntRect rect = rects[i];
1234         rect.move(-absolutePoint.x(), -absolutePoint.y());
1235         quads.append(localToAbsoluteQuad(FloatQuad(rect)));
1236     }
1237 }
1238
1239 FloatRect RenderObject::absoluteBoundingBoxRectForRange(const Range* range)
1240 {
1241     if (!range || !range->startContainer())
1242         return FloatRect();
1243
1244     if (range->ownerDocument())
1245         range->ownerDocument()->updateLayout();
1246
1247     Vector<FloatQuad> quads;
1248     range->textQuads(quads);
1249
1250     FloatRect result;
1251     for (size_t i = 0; i < quads.size(); ++i)
1252         result.unite(quads[i].boundingBox());
1253
1254     return result;
1255 }
1256
1257 void RenderObject::addAbsoluteRectForLayer(LayoutRect& result)
1258 {
1259     if (hasLayer())
1260         result.unite(absoluteBoundingBoxRectIgnoringTransforms());
1261     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1262         current->addAbsoluteRectForLayer(result);
1263 }
1264
1265 LayoutRect RenderObject::paintingRootRect(LayoutRect& topLevelRect)
1266 {
1267     LayoutRect result = absoluteBoundingBoxRectIgnoringTransforms();
1268     topLevelRect = result;
1269     for (RenderObject* current = firstChild(); current; current = current->nextSibling())
1270         current->addAbsoluteRectForLayer(result);
1271     return result;
1272 }
1273
1274 void RenderObject::paint(PaintInfo&, const LayoutPoint&)
1275 {
1276 }
1277
1278 RenderLayerModelObject* RenderObject::containerForRepaint() const
1279 {
1280     RenderView* v = view();
1281     if (!v)
1282         return 0;
1283     
1284     RenderLayerModelObject* repaintContainer = 0;
1285
1286 #if USE(ACCELERATED_COMPOSITING)
1287     if (v->usesCompositing()) {
1288         if (RenderLayer* parentLayer = enclosingLayer()) {
1289             RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
1290             if (compLayer)
1291                 repaintContainer = compLayer->renderer();
1292         }
1293     }
1294 #endif
1295     
1296 #if ENABLE(CSS_FILTERS)
1297     if (document()->view()->hasSoftwareFilters()) {
1298         if (RenderLayer* parentLayer = enclosingLayer()) {
1299             RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
1300             if (enclosingFilterLayer)
1301                 return enclosingFilterLayer->renderer();
1302         }
1303     }
1304 #endif
1305
1306     // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead.
1307     // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change
1308     // repainting to do individual region repaints.
1309     RenderFlowThread* parentRenderFlowThread = flowThreadContainingBlock();
1310     if (parentRenderFlowThread) {
1311         // The ancestor document will do the reparenting when the repaint propagates further up.
1312         // We're just a seamless child document, and we don't need to do the hacking.
1313         if (parentRenderFlowThread && parentRenderFlowThread->document() != document())
1314             return repaintContainer;
1315         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
1316         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
1317         RenderFlowThread* repaintContainerFlowThread = repaintContainer ? repaintContainer->flowThreadContainingBlock() : 0;
1318         if (!repaintContainerFlowThread || repaintContainerFlowThread != parentRenderFlowThread)
1319             repaintContainer = parentRenderFlowThread;
1320     }
1321     return repaintContainer;
1322 }
1323
1324 void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintContainer, const IntRect& r, bool immediate) const
1325 {
1326     if (!repaintContainer) {
1327         view()->repaintViewRectangle(r, immediate);
1328         return;
1329     }
1330
1331     if (repaintContainer->isRenderFlowThread()) {
1332         toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r, immediate);
1333         return;
1334     }
1335
1336 #if ENABLE(CSS_FILTERS)
1337     if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
1338         repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r, immediate);
1339         return;
1340     }
1341 #endif
1342
1343 #if USE(ACCELERATED_COMPOSITING)
1344     RenderView* v = view();
1345     if (repaintContainer->isRenderView()) {
1346         ASSERT(repaintContainer == v);
1347         bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
1348         if (!viewHasCompositedLayer || v->layer()->backing()->paintsIntoWindow()) {
1349             LayoutRect repaintRectangle = r;
1350             if (viewHasCompositedLayer &&  v->layer()->transform())
1351                 repaintRectangle = enclosingIntRect(v->layer()->transform()->mapRect(r));
1352             v->repaintViewRectangle(repaintRectangle, immediate);
1353             return;
1354         }
1355     }
1356     
1357     if (v->usesCompositing()) {
1358         ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
1359         repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
1360     }
1361 #else
1362     if (repaintContainer->isRenderView())
1363         toRenderView(repaintContainer)->repaintViewRectangle(r, immediate);
1364 #endif
1365 }
1366
1367 void RenderObject::repaint(bool immediate) const
1368 {
1369     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1370     RenderView* view;
1371     if (!isRooted(&view))
1372         return;
1373
1374     if (view->printing())
1375         return; // Don't repaint if we're printing.
1376
1377     RenderLayerModelObject* repaintContainer = containerForRepaint();
1378     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)), immediate);
1379 }
1380
1381 void RenderObject::repaintRectangle(const LayoutRect& r, bool immediate) const
1382 {
1383     // Don't repaint if we're unrooted (note that view() still returns the view when unrooted)
1384     RenderView* view;
1385     if (!isRooted(&view))
1386         return;
1387
1388     if (view->printing())
1389         return; // Don't repaint if we're printing.
1390
1391     LayoutRect dirtyRect(r);
1392
1393     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1394     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1395     dirtyRect.move(view->layoutDelta());
1396
1397     RenderLayerModelObject* repaintContainer = containerForRepaint();
1398     computeRectForRepaint(repaintContainer, dirtyRect);
1399     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(dirtyRect), immediate);
1400 }
1401
1402 IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
1403 {
1404     return pixelSnappedIntRect(absoluteClippedOverflowRect());
1405 }
1406
1407 bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1408 {
1409     RenderView* v = view();
1410     if (v->printing())
1411         return false; // Don't repaint if we're printing.
1412
1413     // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
1414     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1415     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1416     LayoutRect newOutlineBox;
1417
1418     bool fullRepaint = selfNeedsLayout();
1419     // Presumably a background or a border exists if border-fit:lines was specified.
1420     if (!fullRepaint && style()->borderFit() == BorderFitLines)
1421         fullRepaint = true;
1422     if (!fullRepaint) {
1423         // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
1424         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1425         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1426         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder() && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1427             fullRepaint = true;
1428     }
1429
1430     if (!repaintContainer)
1431         repaintContainer = v;
1432
1433     if (fullRepaint) {
1434         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds));
1435         if (newBounds != oldBounds)
1436             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds));
1437         return true;
1438     }
1439
1440     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1441         return false;
1442
1443     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1444     if (deltaLeft > 0)
1445         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1446     else if (deltaLeft < 0)
1447         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1448
1449     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1450     if (deltaRight > 0)
1451         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1452     else if (deltaRight < 0)
1453         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1454
1455     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1456     if (deltaTop > 0)
1457         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1458     else if (deltaTop < 0)
1459         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1460
1461     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1462     if (deltaBottom > 0)
1463         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1464     else if (deltaBottom < 0)
1465         repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1466
1467     if (newOutlineBox == oldOutlineBox)
1468         return false;
1469
1470     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1471     // two rectangles (but typically only one).
1472     RenderStyle* outlineStyle = outlineStyleForRepaint();
1473     LayoutUnit outlineWidth = outlineStyle->outlineSize();
1474     LayoutBoxExtent insetShadowExtent = style()->getBoxShadowInsetExtent();
1475     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1476     if (width) {
1477         LayoutUnit shadowLeft;
1478         LayoutUnit shadowRight;
1479         style()->getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1480         int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
1481         LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : LayoutUnit();
1482         LayoutUnit minInsetRightShadowExtent = min<LayoutUnit>(-insetShadowExtent.right(), min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1483         LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth, v), valueForLength(style()->borderBottomRightRadius().width(), boxWidth, v)));
1484         LayoutUnit decorationsWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
1485         LayoutRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1486             newOutlineBox.y(),
1487             width + decorationsWidth,
1488             max(newOutlineBox.height(), oldOutlineBox.height()));
1489         LayoutUnit right = min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1490         if (rightRect.x() < right) {
1491             rightRect.setWidth(min(rightRect.width(), right - rightRect.x()));
1492             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(rightRect));
1493         }
1494     }
1495     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1496     if (height) {
1497         LayoutUnit shadowTop;
1498         LayoutUnit shadowBottom;
1499         style()->getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1500         int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
1501         LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : LayoutUnit();
1502         LayoutUnit minInsetBottomShadowExtent = min<LayoutUnit>(-insetShadowExtent.bottom(), min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1503         LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight, v), valueForLength(style()->borderBottomRightRadius().height(), boxHeight, v)));
1504         LayoutUnit decorationsHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
1505         LayoutRect bottomRect(newOutlineBox.x(),
1506             min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1507             max(newOutlineBox.width(), oldOutlineBox.width()),
1508             height + decorationsHeight);
1509         LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
1510         if (bottomRect.y() < bottom) {
1511             bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
1512             repaintUsingContainer(repaintContainer, pixelSnappedIntRect(bottomRect));
1513         }
1514     }
1515     return false;
1516 }
1517
1518 bool RenderObject::checkForRepaintDuringLayout() const
1519 {
1520     return !document()->view()->needsFullRepaint() && !hasLayer() && everHadLayout();
1521 }
1522
1523 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
1524 {
1525     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
1526     r.inflate(outlineWidth);
1527     return r;
1528 }
1529
1530 LayoutRect RenderObject::clippedOverflowRectForRepaint(const RenderLayerModelObject*) const
1531 {
1532     ASSERT_NOT_REACHED();
1533     return LayoutRect();
1534 }
1535
1536 void RenderObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1537 {
1538     if (repaintContainer == this)
1539         return;
1540
1541     if (RenderObject* o = parent()) {
1542         if (o->isBlockFlow()) {
1543             RenderBlock* cb = toRenderBlock(o);
1544             if (cb->hasColumns())
1545                 cb->adjustRectForColumns(rect);
1546         }
1547
1548         if (o->hasOverflowClip()) {
1549             RenderBox* boxParent = toRenderBox(o);
1550             boxParent->applyCachedClipAndScrollOffsetForRepaint(rect);
1551             if (rect.isEmpty())
1552                 return;
1553         }
1554
1555         o->computeRectForRepaint(repaintContainer, rect, fixed);
1556     }
1557 }
1558
1559 void RenderObject::computeFloatRectForRepaint(const RenderLayerModelObject*, FloatRect&, bool) const
1560 {
1561     ASSERT_NOT_REACHED();
1562 }
1563
1564 void RenderObject::dirtyLinesFromChangedChild(RenderObject*)
1565 {
1566 }
1567
1568 #ifndef NDEBUG
1569
1570 void RenderObject::showTreeForThis() const
1571 {
1572     if (node())
1573         node()->showTreeForThis();
1574 }
1575
1576 void RenderObject::showRenderTreeForThis() const
1577 {
1578     showRenderTree(this, 0);
1579 }
1580
1581 void RenderObject::showLineTreeForThis() const
1582 {
1583     if (containingBlock())
1584         containingBlock()->showLineTreeAndMark(0, 0, 0, 0, this);
1585 }
1586
1587 void RenderObject::showRenderObject() const
1588 {
1589     showRenderObject(0);
1590 }
1591
1592 void RenderObject::showRenderObject(int printedCharacters) const
1593 {
1594     // As this function is intended to be used when debugging, the
1595     // this pointer may be 0.
1596     if (!this) {
1597         fputs("(null)\n", stderr);
1598         return;
1599     }
1600
1601     printedCharacters += fprintf(stderr, "%s %p", renderName(), this);
1602
1603     if (node()) {
1604         if (printedCharacters)
1605             for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1606                 fputc(' ', stderr);
1607         fputc('\t', stderr);
1608         node()->showNode();
1609     } else
1610         fputc('\n', stderr);
1611 }
1612
1613 void RenderObject::showRenderTreeAndMark(const RenderObject* markedObject1, const char* markedLabel1, const RenderObject* markedObject2, const char* markedLabel2, int depth) const
1614 {
1615     int printedCharacters = 0;
1616     if (markedObject1 == this && markedLabel1)
1617         printedCharacters += fprintf(stderr, "%s", markedLabel1);
1618     if (markedObject2 == this && markedLabel2)
1619         printedCharacters += fprintf(stderr, "%s", markedLabel2);
1620     for (; printedCharacters < depth * 2; printedCharacters++)
1621         fputc(' ', stderr);
1622
1623     showRenderObject(printedCharacters);
1624     if (!this)
1625         return;
1626
1627     for (const RenderObject* child = firstChild(); child; child = child->nextSibling())
1628         child->showRenderTreeAndMark(markedObject1, markedLabel1, markedObject2, markedLabel2, depth + 1);
1629 }
1630
1631 #endif // NDEBUG
1632
1633 Color RenderObject::selectionBackgroundColor() const
1634 {
1635     Color color;
1636     if (style()->userSelect() != SELECT_NONE) {
1637         RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1638         if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1639             color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1640         else
1641             color = frame()->selection()->isFocusedAndActive() ?
1642                     theme()->activeSelectionBackgroundColor() :
1643                     theme()->inactiveSelectionBackgroundColor();
1644     }
1645
1646     return color;
1647 }
1648
1649 Color RenderObject::selectionColor(int colorProperty) const
1650 {
1651     Color color;
1652     // If the element is unselectable, or we are only painting the selection,
1653     // don't override the foreground color with the selection foreground color.
1654     if (style()->userSelect() == SELECT_NONE
1655         || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
1656         return color;
1657
1658     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
1659         color = pseudoStyle->visitedDependentColor(colorProperty);
1660         if (!color.isValid())
1661             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1662     } else
1663         color = frame()->selection()->isFocusedAndActive() ?
1664                 theme()->activeSelectionForegroundColor() :
1665                 theme()->inactiveSelectionForegroundColor();
1666
1667     return color;
1668 }
1669
1670 Color RenderObject::selectionForegroundColor() const
1671 {
1672     return selectionColor(CSSPropertyWebkitTextFillColor);
1673 }
1674
1675 Color RenderObject::selectionEmphasisMarkColor() const
1676 {
1677     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1678 }
1679
1680 void RenderObject::selectionStartEnd(int& spos, int& epos) const
1681 {
1682     view()->selectionStartEnd(spos, epos);
1683 }
1684
1685 void RenderObject::handleDynamicFloatPositionChange()
1686 {
1687     // We have gone from not affecting the inline status of the parent flow to suddenly
1688     // having an impact.  See if there is a mismatch between the parent flow's
1689     // childrenInline() state and our state.
1690     setInline(style()->isDisplayInlineType());
1691     if (isInline() != parent()->childrenInline()) {
1692         if (!isInline())
1693             toRenderBoxModelObject(parent())->childBecameNonInline(this);
1694         else {
1695             // An anonymous block must be made to wrap this inline.
1696             RenderBlock* block = toRenderBlock(parent())->createAnonymousBlock();
1697             RenderObjectChildList* childlist = parent()->virtualChildren();
1698             childlist->insertChildNode(parent(), block, this);
1699             block->children()->appendChildNode(block, childlist->removeChildNode(parent(), this));
1700         }
1701     }
1702 }
1703
1704 void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
1705 {
1706     if (!isText() && style)
1707         setStyle(animation()->updateAnimations(this, style.get()));
1708     else
1709         setStyle(style);
1710 }
1711
1712 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
1713 {
1714 #if USE(ACCELERATED_COMPOSITING)
1715     // If transform changed, and we are not composited, need to do a layout.
1716     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
1717         // Text nodes share style with their parents but transforms don't apply to them,
1718         // hence the !isText() check.
1719         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
1720         if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited())) {
1721             // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
1722             // then we actually need SimplifiedLayoutAndPositionedMovement.
1723             if (!hasLayer())
1724                 diff = StyleDifferenceLayout; // FIXME: Do this for now since SimplifiedLayout cannot handle updating floating objects lists.
1725             else if (diff < StyleDifferenceLayoutPositionedMovementOnly)
1726                 diff = StyleDifferenceSimplifiedLayout;
1727             else if (diff < StyleDifferenceSimplifiedLayout)
1728                 diff = StyleDifferenceSimplifiedLayoutAndPositionedMovement;
1729         } else if (diff < StyleDifferenceRecompositeLayer)
1730             diff = StyleDifferenceRecompositeLayer;
1731     }
1732
1733     // If opacity changed, and we are not composited, need to repaint (also
1734     // ignoring text nodes)
1735     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
1736         if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited()))
1737             diff = StyleDifferenceRepaintLayer;
1738         else if (diff < StyleDifferenceRecompositeLayer)
1739             diff = StyleDifferenceRecompositeLayer;
1740     }
1741     
1742 #if ENABLE(CSS_FILTERS)
1743     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
1744         RenderLayer* layer = toRenderLayerModelObject(this)->layer();
1745         if (!layer->isComposited() || layer->paintsWithFilters())
1746             diff = StyleDifferenceRepaintLayer;
1747         else if (diff < StyleDifferenceRecompositeLayer)
1748             diff = StyleDifferenceRecompositeLayer;
1749     }
1750 #endif
1751     
1752     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
1753     // style changing, since it depends on whether we decide to composite these elements. When the
1754     // layer status of one of these elements changes, we need to force a layout.
1755     if (diff == StyleDifferenceEqual && style() && isLayerModelObject()) {
1756         if (hasLayer() != toRenderLayerModelObject(this)->requiresLayer())
1757             diff = StyleDifferenceLayout;
1758     }
1759 #else
1760     UNUSED_PARAM(contextSensitiveProperties);
1761 #endif
1762
1763     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
1764     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
1765         diff = StyleDifferenceRepaint;
1766
1767     return diff;
1768 }
1769
1770 void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
1771 {
1772     ASSERT(pseudoStyle->styleType() == BEFORE || pseudoStyle->styleType() == AFTER);
1773
1774     // Images are special and must inherit the pseudoStyle so the width and height of
1775     // the pseudo element doesn't change the size of the image. In all other cases we
1776     // can just share the style.
1777     if (isImage()) {
1778         RefPtr<RenderStyle> style = RenderStyle::create();
1779         style->inheritFrom(pseudoStyle.get());
1780         setStyle(style.release());
1781         return;
1782     }
1783
1784     setStyle(pseudoStyle);
1785 }
1786
1787 void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
1788 {
1789     if (m_style == style) {
1790 #if USE(ACCELERATED_COMPOSITING)
1791         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
1792         // style sharing is disabled for them. That should ensure that we never hit this code path.
1793         ASSERT(!isRenderIFrame() && !isEmbeddedObject() && !isCanvas());
1794 #endif
1795         return;
1796     }
1797
1798     StyleDifference diff = StyleDifferenceEqual;
1799     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
1800     if (m_style)
1801         diff = m_style->diff(style.get(), contextSensitiveProperties);
1802
1803     diff = adjustStyleDifference(diff, contextSensitiveProperties);
1804
1805     styleWillChange(diff, style.get());
1806     
1807     RefPtr<RenderStyle> oldStyle = m_style.release();
1808     setStyleInternal(style);
1809
1810     updateFillImages(oldStyle ? oldStyle->backgroundLayers() : 0, m_style ? m_style->backgroundLayers() : 0);
1811     updateFillImages(oldStyle ? oldStyle->maskLayers() : 0, m_style ? m_style->maskLayers() : 0);
1812
1813     updateImage(oldStyle ? oldStyle->borderImage().image() : 0, m_style ? m_style->borderImage().image() : 0);
1814     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
1815
1816     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
1817     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
1818     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
1819         toRenderView(document()->renderer())->setMaximalOutlineSize(m_style->outlineSize());
1820
1821     bool doesNotNeedLayout = !m_parent || isText();
1822
1823     styleDidChange(diff, oldStyle.get());
1824
1825     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
1826     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
1827     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
1828     // in the future as we move renderer changes out of layout and into style changes.
1829     if (doesNotNeedLayout)
1830         return;
1831
1832     // Now that the layer (if any) has been updated, we need to adjust the diff again,
1833     // check whether we should layout now, and decide if we need to repaint.
1834     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
1835     
1836     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
1837         if (updatedDiff == StyleDifferenceLayout)
1838             setNeedsLayoutAndPrefWidthsRecalc();
1839         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
1840             setNeedsPositionedMovementLayout();
1841         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1842             setNeedsPositionedMovementLayout();
1843             setNeedsSimplifiedNormalFlowLayout();
1844         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
1845             setNeedsSimplifiedNormalFlowLayout();
1846     }
1847     
1848     if (updatedDiff == StyleDifferenceRepaintLayer || updatedDiff == StyleDifferenceRepaint) {
1849         // Do a repaint with the new style now, e.g., for example if we go from
1850         // not having an outline to having an outline.
1851         repaint();
1852     }
1853 }
1854
1855 static inline bool rendererHasBackground(const RenderObject* renderer)
1856 {
1857     return renderer && renderer->hasBackground();
1858 }
1859
1860 void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1861 {
1862     if (m_style) {
1863         // If our z-index changes value or our visibility changes,
1864         // we need to dirty our stacking context's z-order list.
1865         if (newStyle) {
1866             bool visibilityChanged = m_style->visibility() != newStyle->visibility() 
1867                 || m_style->zIndex() != newStyle->zIndex() 
1868                 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1869 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
1870             if (visibilityChanged)
1871                 document()->setAnnotatedRegionsDirty(true);
1872 #endif
1873             if (visibilityChanged) {
1874                 if (AXObjectCache* cache = document()->existingAXObjectCache())
1875                     cache->childrenChanged(parent());
1876             }
1877
1878             // Keep layer hierarchy visibility bits up to date if visibility changes.
1879             if (m_style->visibility() != newStyle->visibility()) {
1880                 if (RenderLayer* l = enclosingLayer()) {
1881                     if (newStyle->visibility() == VISIBLE)
1882                         l->setHasVisibleContent();
1883                     else if (l->hasVisibleContent() && (this == l->renderer() || l->renderer()->style()->visibility() != VISIBLE)) {
1884                         l->dirtyVisibleContentStatus();
1885                         if (diff > StyleDifferenceRepaintLayer)
1886                             repaint();
1887                     }
1888                 }
1889             }
1890         }
1891
1892         if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
1893             repaint();
1894         if (isFloating() && (m_style->floating() != newStyle->floating()))
1895             // For changes in float styles, we need to conceivably remove ourselves
1896             // from the floating objects list.
1897             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1898         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle->position()))
1899             // For changes in positioning styles, we need to conceivably remove ourselves
1900             // from the positioned objects list.
1901             toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1902
1903         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
1904             && (!newStyle->isFloating() && !newStyle->hasOutOfFlowPosition())
1905             && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
1906
1907         // reset style flags
1908         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
1909             setFloating(false);
1910             clearPositionedState();
1911         }
1912         setHorizontalWritingMode(true);
1913         setHasBoxDecorations(false);
1914         setHasOverflowClip(false);
1915         setHasTransform(false);
1916         setHasReflection(false);
1917     } else
1918         s_affectsParentBlock = false;
1919
1920     if (view()->frameView()) {
1921         bool shouldBlitOnFixedBackgroundImage = false;
1922 #if ENABLE(FAST_MOBILE_SCROLLING)
1923         // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
1924         // when scrolling a page with a fixed background image. As an optimization, assuming there are
1925         // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
1926         // ignore the CSS property "background-attachment: fixed".
1927 #if PLATFORM(QT)
1928         if (view()->frameView()->delegatesScrolling())
1929 #endif
1930             shouldBlitOnFixedBackgroundImage = true;
1931 #endif
1932
1933         bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
1934         bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
1935
1936 #if USE(ACCELERATED_COMPOSITING)
1937         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document()->documentElement()->renderer()));
1938         if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
1939             if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
1940                 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
1941                     newStyleSlowScroll = false;
1942
1943                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
1944                     oldStyleSlowScroll = false;
1945             }
1946         }
1947 #endif
1948         if (oldStyleSlowScroll != newStyleSlowScroll) {
1949             if (oldStyleSlowScroll)
1950                 view()->frameView()->removeSlowRepaintObject();
1951             if (newStyleSlowScroll)
1952                 view()->frameView()->addSlowRepaintObject();
1953         }
1954     }
1955 }
1956
1957 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
1958 {
1959     ASSERT(a->cursors() != b->cursors());
1960     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1961 }
1962
1963 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
1964 {
1965     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1966 }
1967
1968 void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1969 {
1970     if (s_affectsParentBlock)
1971         handleDynamicFloatPositionChange();
1972
1973 #if ENABLE(SVG)
1974     SVGRenderSupport::styleChanged(this);
1975 #endif
1976
1977     if (!m_parent)
1978         return;
1979     
1980     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1981         RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
1982
1983         // If the object already needs layout, then setNeedsLayout won't do
1984         // any work. But if the containing block has changed, then we may need
1985         // to mark the new containing blocks for layout. The change that can
1986         // directly affect the containing block of this object is a change to
1987         // the position style.
1988         if (needsLayout() && oldStyle->position() != m_style->position())
1989             markContainingBlocksForLayout();
1990
1991         if (diff == StyleDifferenceLayout)
1992             setNeedsLayoutAndPrefWidthsRecalc();
1993         else
1994             setNeedsSimplifiedNormalFlowLayout();
1995     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1996         setNeedsPositionedMovementLayout();
1997         setNeedsSimplifiedNormalFlowLayout();
1998     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1999         setNeedsPositionedMovementLayout();
2000
2001     // Don't check for repaint here; we need to wait until the layer has been
2002     // updated by subclasses before we know if we have to repaint (in setStyle()).
2003
2004     if (oldStyle && !areCursorsEqual(oldStyle, style())) {
2005         if (Frame* frame = this->frame())
2006             frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
2007     }
2008 }
2009
2010 void RenderObject::propagateStyleToAnonymousChildren(bool blockChildrenOnly)
2011 {
2012     // FIXME: We could save this call when the change only affected non-inherited properties.
2013     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
2014         if (!child->isAnonymous() || child->style()->styleType() != NOPSEUDO)
2015             continue;
2016
2017         if (blockChildrenOnly && !child->isRenderBlock())
2018             continue;
2019
2020 #if ENABLE(FULLSCREEN_API)
2021         if (child->isRenderFullScreen() || child->isRenderFullScreenPlaceholder())
2022             continue;
2023 #endif
2024
2025         RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), child->style()->display());
2026         if (style()->specifiesColumns()) {
2027             if (child->style()->specifiesColumns())
2028                 newStyle->inheritColumnPropertiesFrom(style());
2029             if (child->style()->columnSpan())
2030                 newStyle->setColumnSpan(ColumnSpanAll);
2031         }
2032
2033         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
2034         // they contain block descendants of relative or sticky positioned inlines.
2035         if (child->isInFlowPositioned() && toRenderBlock(child)->isAnonymousBlockContinuation())
2036             newStyle->setPosition(child->style()->position());
2037
2038         child->setStyle(newStyle.release());
2039     }
2040 }
2041
2042 void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
2043 {
2044     // Optimize the common case
2045     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
2046         return;
2047     
2048     // Go through the new layers and addClients first, to avoid removing all clients of an image.
2049     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
2050         if (currNew->image())
2051             currNew->image()->addClient(this);
2052     }
2053
2054     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
2055         if (currOld->image())
2056             currOld->image()->removeClient(this);
2057     }
2058 }
2059
2060 void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
2061 {
2062     if (oldImage != newImage) {
2063         if (oldImage)
2064             oldImage->removeClient(this);
2065         if (newImage)
2066             newImage->addClient(this);
2067     }
2068 }
2069
2070 LayoutRect RenderObject::viewRect() const
2071 {
2072     return view()->viewRect();
2073 }
2074
2075 FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, MapCoordinatesFlags mode) const
2076 {
2077     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2078     mapLocalToContainer(0, transformState, mode | ApplyContainerFlip);
2079     transformState.flatten();
2080     
2081     return transformState.lastPlanarPoint();
2082 }
2083
2084 FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, MapCoordinatesFlags mode) const
2085 {
2086     TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
2087     mapAbsoluteToLocalPoint(mode, transformState);
2088     transformState.flatten();
2089     
2090     return transformState.lastPlanarPoint();
2091 }
2092
2093 FloatQuad RenderObject::absoluteToLocalQuad(const FloatQuad& quad, MapCoordinatesFlags mode) const
2094 {
2095     TransformState transformState(TransformState::UnapplyInverseTransformDirection, quad.boundingBox().center(), quad);
2096     mapAbsoluteToLocalPoint(mode, transformState);
2097     transformState.flatten();
2098     return transformState.lastPlanarQuad();
2099 }
2100
2101 void RenderObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
2102 {
2103     if (repaintContainer == this)
2104         return;
2105
2106     RenderObject* o = parent();
2107     if (!o)
2108         return;
2109
2110     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2111     LayoutPoint centerPoint = roundedLayoutPoint(transformState.mappedPoint());
2112     if (mode & ApplyContainerFlip && o->isBox()) {
2113         if (o->style()->isFlippedBlocksWritingMode())
2114             transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedLayoutPoint(transformState.mappedPoint())) - centerPoint);
2115         mode &= ~ApplyContainerFlip;
2116     }
2117
2118     LayoutSize columnOffset;
2119     o->adjustForColumns(columnOffset, roundedLayoutPoint(transformState.mappedPoint()));
2120     if (!columnOffset.isZero())
2121         transformState.move(columnOffset);
2122
2123     if (o->hasOverflowClip())
2124         transformState.move(-toRenderBox(o)->scrolledContentOffset());
2125
2126     o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
2127 }
2128
2129 const RenderObject* RenderObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2130 {
2131     ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != this);
2132
2133     RenderObject* container = parent();
2134     if (!container)
2135         return 0;
2136
2137     // FIXME: this should call offsetFromContainer to share code, but I'm not sure it's ever called.
2138     LayoutSize offset;
2139     if (container->hasOverflowClip())
2140         offset = -toRenderBox(container)->scrolledContentOffset();
2141
2142     geometryMap.push(this, offset, hasColumns());
2143     
2144     return container;
2145 }
2146
2147 void RenderObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2148 {
2149     RenderObject* o = parent();
2150     if (o) {
2151         o->mapAbsoluteToLocalPoint(mode, transformState);
2152         if (o->hasOverflowClip())
2153             transformState.move(toRenderBox(o)->scrolledContentOffset());
2154     }
2155 }
2156
2157 bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
2158 {
2159 #if ENABLE(3D_RENDERING)
2160     // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
2161     // so check the layer's transform directly.
2162     return (hasLayer() && toRenderLayerModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
2163 #else
2164     UNUSED_PARAM(containerObject);
2165     return hasTransform();
2166 #endif
2167 }
2168
2169 void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const LayoutSize& offsetInContainer, TransformationMatrix& transform) const
2170 {
2171     transform.makeIdentity();
2172     transform.translate(offsetInContainer.width(), offsetInContainer.height());
2173     RenderLayer* layer;
2174     if (hasLayer() && (layer = toRenderLayerModelObject(this)->layer()) && layer->transform())
2175         transform.multiply(layer->currentTransform());
2176     
2177 #if ENABLE(3D_RENDERING)
2178     if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
2179         // Perpsective on the container affects us, so we have to factor it in here.
2180         ASSERT(containerObject->hasLayer());
2181         FloatPoint perspectiveOrigin = toRenderLayerModelObject(containerObject)->layer()->perspectiveOrigin();
2182
2183         TransformationMatrix perspectiveMatrix;
2184         perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
2185         
2186         transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
2187         transform = perspectiveMatrix * transform;
2188         transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
2189     }
2190 #else
2191     UNUSED_PARAM(containerObject);
2192 #endif
2193 }
2194
2195 FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2196 {
2197     // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
2198     // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
2199     TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), localQuad);
2200     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2201     transformState.flatten();
2202     
2203     return transformState.lastPlanarQuad();
2204 }
2205
2206 FloatPoint RenderObject::localToContainerPoint(const FloatPoint& localPoint, const RenderLayerModelObject* repaintContainer, MapCoordinatesFlags mode, bool* wasFixed) const
2207 {
2208     TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
2209     mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip | UseTransforms, wasFixed);
2210     transformState.flatten();
2211
2212     return transformState.lastPlanarPoint();
2213 }
2214
2215 LayoutSize RenderObject::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
2216 {
2217     ASSERT(o == container());
2218
2219     LayoutSize offset;
2220
2221     o->adjustForColumns(offset, point);
2222
2223     if (o->hasOverflowClip())
2224         offset -= toRenderBox(o)->scrolledContentOffset();
2225
2226     if (offsetDependsOnPoint)
2227         *offsetDependsOnPoint = hasColumns();
2228
2229     return offset;
2230 }
2231
2232 LayoutSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
2233 {
2234     LayoutSize offset;
2235     LayoutPoint referencePoint;
2236     const RenderObject* currContainer = this;
2237     do {
2238         RenderObject* nextContainer = currContainer->container();
2239         ASSERT(nextContainer);  // This means we reached the top without finding container.
2240         if (!nextContainer)
2241             break;
2242         ASSERT(!currContainer->hasTransform());
2243         LayoutSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
2244         offset += currentOffset;
2245         referencePoint.move(currentOffset);
2246         currContainer = nextContainer;
2247     } while (currContainer != container);
2248
2249     return offset;
2250 }
2251
2252 LayoutRect RenderObject::localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine)
2253 {
2254     if (extraWidthToEndOfLine)
2255         *extraWidthToEndOfLine = 0;
2256
2257     return LayoutRect();
2258 }
2259
2260 bool RenderObject::isRooted(RenderView** view) const
2261 {
2262     const RenderObject* o = this;
2263     while (o->parent())
2264         o = o->parent();
2265
2266     if (!o->isRenderView())
2267         return false;
2268
2269     if (view)
2270         *view = const_cast<RenderView*>(toRenderView(o));
2271
2272     return true;
2273 }
2274
2275 RenderObject* RenderObject::rendererForRootBackground()
2276 {
2277     ASSERT(isRoot());
2278     if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
2279         // Locate the <body> element using the DOM. This is easier than trying
2280         // to crawl around a render tree with potential :before/:after content and
2281         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
2282         // render object very easily via the DOM.
2283         HTMLElement* body = document()->body();
2284         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
2285         if (bodyObject)
2286             return bodyObject;
2287     }
2288     
2289     return this;
2290 }
2291
2292 RespectImageOrientationEnum RenderObject::shouldRespectImageOrientation() const
2293 {
2294     // Respect the image's orientation if it's being used as a full-page image or it's
2295     // an <img> and the setting to respect it everywhere is set.
2296     return
2297 #if USE(CG) || PLATFORM(CHROMIUM) || USE(CAIRO) || PLATFORM(BLACKBERRY)
2298         // This can only be enabled for ports which honor the orientation flag in their drawing code.
2299         document()->isImageDocument() ||
2300 #endif
2301         (document()->settings() && document()->settings()->shouldRespectImageOrientation() && node() && node()->hasTagName(HTMLNames::imgTag)) ? RespectImageOrientation : DoNotRespectImageOrientation;
2302 }
2303
2304 bool RenderObject::hasOutlineAnnotation() const
2305 {
2306     return node() && node()->isLink() && document()->printing();
2307 }
2308
2309 bool RenderObject::hasEntirelyFixedBackground() const
2310 {
2311     return m_style->hasEntirelyFixedBackground();
2312 }
2313
2314 RenderObject* RenderObject::container(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
2315 {
2316     if (repaintContainerSkipped)
2317         *repaintContainerSkipped = false;
2318
2319     // This method is extremely similar to containingBlock(), but with a few notable
2320     // exceptions.
2321     // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2322     // the object is not part of the primary document subtree yet.
2323     // (2) For normal flow elements, it just returns the parent.
2324     // (3) For absolute positioned elements, it will return a relative positioned inline.
2325     // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2326     // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
2327     // computePositionedLogicalHeight have to use container().
2328     RenderObject* o = parent();
2329
2330     if (isText())
2331         return o;
2332
2333     EPosition pos = m_style->position();
2334     if (pos == FixedPosition) {
2335         // container() can be called on an object that is not in the
2336         // tree yet.  We don't call view() since it will assert if it
2337         // can't get back to the canvas.  Instead we just walk as high up
2338         // as we can.  If we're in the tree, we'll get the root.  If we
2339         // aren't we'll get the root of our little subtree (most likely
2340         // we'll just return 0).
2341         // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
2342         // be safe now to use it.
2343         while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
2344 #if ENABLE(SVG)
2345             // foreignObject is the containing block for its contents.
2346             if (o->isSVGForeignObject())
2347                 break;
2348 #endif
2349             // The render flow thread is the top most containing block
2350             // for the fixed positioned elements.
2351             if (o->isOutOfFlowRenderFlowThread())
2352                 break;
2353
2354             if (repaintContainerSkipped && o == repaintContainer)
2355                 *repaintContainerSkipped = true;
2356
2357             o = o->parent();
2358         }
2359     } else if (pos == AbsolutePosition) {
2360         // Same goes here.  We technically just want our containing block, but
2361         // we may not have one if we're part of an uninstalled subtree.  We'll
2362         // climb as high as we can though.
2363         while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
2364 #if ENABLE(SVG)
2365             if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
2366                 break;
2367 #endif
2368             if (repaintContainerSkipped && o == repaintContainer)
2369                 *repaintContainerSkipped = true;
2370
2371             o = o->parent();
2372         }
2373     }
2374
2375     return o;
2376 }
2377
2378 bool RenderObject::isSelectionBorder() const
2379 {
2380     SelectionState st = selectionState();
2381     return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2382 }
2383
2384 inline void RenderObject::clearLayoutRootIfNeeded() const
2385 {
2386     if (!documentBeingDestroyed() && frame()) {
2387         if (FrameView* view = frame()->view()) {
2388             if (view->layoutRoot() == this) {
2389                 ASSERT_NOT_REACHED();
2390                 // This indicates a failure to layout the child, which is why
2391                 // the layout root is still set to |this|. Make sure to clear it
2392                 // since we are getting destroyed.
2393                 view->clearLayoutRoot();
2394             }
2395         }
2396     }
2397 }
2398
2399 void RenderObject::willBeDestroyed()
2400 {
2401     // Destroy any leftover anonymous children.
2402     RenderObjectChildList* children = virtualChildren();
2403     if (children)
2404         children->destroyLeftoverChildren();
2405
2406     // If this renderer is being autoscrolled, stop the autoscroll timer
2407     
2408     // FIXME: RenderObject::destroy should not get called with a renderer whose document
2409     // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
2410     // check that the frame is not null.
2411     ASSERT(frame());
2412     if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
2413         frame()->eventHandler()->stopAutoscrollTimer(true);
2414
2415     animation()->cancelAnimations(this);
2416
2417     // For accessibility management, notify the parent of the imminent change to its child set.
2418     // We do it now, before remove(), while the parent pointer is still available.
2419     if (AXObjectCache* cache = document()->existingAXObjectCache())
2420         cache->childrenChanged(this->parent());
2421
2422     remove();
2423
2424     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
2425     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
2426     if (AXObjectCache* cache = document()->existingAXObjectCache())
2427         cache->remove(this);
2428
2429 #ifndef NDEBUG
2430     if (!documentBeingDestroyed() && view() && view()->hasRenderNamedFlowThreads()) {
2431         // After remove, the object and the associated information should not be in any flow thread.
2432         const RenderNamedFlowThreadList* flowThreadList = view()->flowThreadController()->renderNamedFlowThreadList();
2433         for (RenderNamedFlowThreadList::const_iterator iter = flowThreadList->begin(); iter != flowThreadList->end(); ++iter) {
2434             const RenderNamedFlowThread* renderFlowThread = *iter;
2435             ASSERT(!renderFlowThread->hasChild(this));
2436             ASSERT(!renderFlowThread->hasChildInfo(this));
2437         }
2438     }
2439 #endif
2440
2441     // If this renderer had a parent, remove should have destroyed any counters
2442     // attached to this renderer and marked the affected other counters for
2443     // reevaluation. This apparently redundant check is here for the case when
2444     // this renderer had no parent at the time remove() was called.
2445
2446     if (hasCounterNodeMap())
2447         RenderCounter::destroyCounterNodes(this);
2448
2449     // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
2450     // be moved into RenderBoxModelObject::destroy.
2451     if (hasLayer()) {
2452         setHasLayer(false);
2453         toRenderLayerModelObject(this)->destroyLayer();
2454     }
2455
2456     setAncestorLineBoxDirty(false);
2457
2458     clearLayoutRootIfNeeded();
2459 }
2460
2461 void RenderObject::insertedIntoTree()
2462 {
2463     // FIXME: We should ASSERT(isRooted()) here but generated content makes some out-of-order insertion.
2464
2465     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
2466     // and don't have a layer attached to ourselves.
2467     RenderLayer* layer = 0;
2468     if (firstChild() || hasLayer()) {
2469         layer = parent()->enclosingLayer();
2470         addLayers(layer);
2471     }
2472
2473     // If |this| is visible but this object was not, tell the layer it has some visible content
2474     // that needs to be drawn and layer visibility optimization can't be used
2475     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2476         if (!layer)
2477             layer = parent()->enclosingLayer();
2478         if (layer)
2479             layer->setHasVisibleContent();
2480     }
2481
2482     if (!isFloating() && parent()->childrenInline())
2483         parent()->dirtyLinesFromChangedChild(this);
2484
2485     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
2486         containerFlowThread->addFlowChild(this);
2487 }
2488
2489 void RenderObject::willBeRemovedFromTree()
2490 {
2491     // FIXME: We should ASSERT(isRooted()) but we have some out-of-order removals which would need to be fixed first.
2492
2493     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
2494     RenderLayer* layer = 0;
2495     if (parent()->style()->visibility() != VISIBLE && style()->visibility() == VISIBLE && !hasLayer()) {
2496         if ((layer = parent()->enclosingLayer()))
2497             layer->dirtyVisibleContentStatus();
2498     }
2499
2500     // Keep our layer hierarchy updated.
2501     if (firstChild() || hasLayer()) {
2502         if (!layer)
2503             layer = parent()->enclosingLayer();
2504         removeLayers(layer);
2505     }
2506
2507     if (isOutOfFlowPositioned() && parent()->childrenInline())
2508         parent()->dirtyLinesFromChangedChild(this);
2509
2510     removeFromRenderFlowThread();
2511
2512     if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
2513         containerFlowThread->removeFlowChild(this);
2514
2515 #if ENABLE(SVG)
2516     // Update cached boundaries in SVG renderers, if a child is removed.
2517     parent()->setNeedsBoundariesUpdate();
2518 #endif
2519 }
2520
2521 void RenderObject::removeFromRenderFlowThread()
2522 {
2523     if (flowThreadState() == NotInsideFlowThread)
2524         return;
2525     
2526     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2527     // It's only until later when we actually destroy it and remove all the children from it. 
2528     // Currently, that happens for firstLetter elements and list markers.
2529     // Pass in the flow thread so that we don't have to look it up for all the children.
2530     removeFromRenderFlowThreadRecursive(flowThreadContainingBlock());
2531 }
2532
2533 void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread)
2534 {
2535     if (const RenderObjectChildList* children = virtualChildren()) {
2536         for (RenderObject* child = children->firstChild(); child; child = child->nextSibling())
2537             child->removeFromRenderFlowThreadRecursive(renderFlowThread);
2538     }
2539     
2540     RenderFlowThread* localFlowThread = renderFlowThread;
2541     if (flowThreadState() == InsideInFlowThread)
2542         localFlowThread = flowThreadContainingBlock(); // We have to ask. We can't just assume we are in the same flow thread.
2543     if (localFlowThread)
2544         localFlowThread->removeFlowChildInfo(this);
2545     setFlowThreadState(NotInsideFlowThread);
2546 }
2547
2548 void RenderObject::destroyAndCleanupAnonymousWrappers()
2549 {
2550     // If the tree is destroyed, there is no need for a clean-up phase.
2551     if (documentBeingDestroyed()) {
2552         destroy();
2553         return;
2554     }
2555
2556     RenderObject* destroyRoot = this;
2557     for (RenderObject* destroyRootParent = destroyRoot->parent(); destroyRootParent && destroyRootParent->isAnonymous(); destroyRoot = destroyRootParent, destroyRootParent = destroyRootParent->parent()) {
2558         // Currently we only remove anonymous cells' wrapper but we should remove all unneeded
2559         // wrappers. See http://webkit.org/b/52123 as an example where this is needed.
2560         if (!destroyRootParent->isTableCell())
2561             break;
2562
2563         if (destroyRootParent->firstChild() != this || destroyRootParent->lastChild() != this)
2564             break;
2565     }
2566
2567     destroyRoot->destroy();
2568
2569     // WARNING: |this| is deleted here.
2570 }
2571
2572 void RenderObject::destroy()
2573 {
2574     willBeDestroyed();
2575     arenaDelete(renderArena(), this);
2576 }
2577
2578 void RenderObject::arenaDelete(RenderArena* arena, void* base)
2579 {
2580     if (m_style) {
2581         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2582             if (StyleImage* backgroundImage = bgLayer->image())
2583                 backgroundImage->removeClient(this);
2584         }
2585
2586         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2587             if (StyleImage* maskImage = maskLayer->image())
2588                 maskImage->removeClient(this);
2589         }
2590
2591         if (StyleImage* borderImage = m_style->borderImage().image())
2592             borderImage->removeClient(this);
2593
2594         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2595             maskBoxImage->removeClient(this);
2596     }
2597
2598 #ifndef NDEBUG
2599     void* savedBase = baseOfRenderObjectBeingDeleted;
2600     baseOfRenderObjectBeingDeleted = base;
2601 #endif
2602     delete this;
2603 #ifndef NDEBUG
2604     baseOfRenderObjectBeingDeleted = savedBase;
2605 #endif
2606
2607     // Recover the size left there for us by operator delete and free the memory.
2608     arena->free(*(size_t*)base, base);
2609 }
2610
2611 VisiblePosition RenderObject::positionForPoint(const LayoutPoint&)
2612 {
2613     return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2614 }
2615
2616 void RenderObject::updateDragState(bool dragOn)
2617 {
2618     bool valueChanged = (dragOn != isDragging());
2619     setIsDragging(dragOn);
2620     if (valueChanged && node() && (style()->affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())))
2621         node()->setNeedsStyleRecalc();
2622     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2623         curr->updateDragState(dragOn);
2624 }
2625
2626 bool RenderObject::isComposited() const
2627 {
2628     return hasLayer() && toRenderLayerModelObject(this)->layer()->isComposited();
2629 }
2630
2631 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
2632 {
2633     bool inside = false;
2634     if (hitTestFilter != HitTestSelf) {
2635         // First test the foreground layer (lines and inlines).
2636         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestForeground);
2637
2638         // Test floats next.
2639         if (!inside)
2640             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestFloat);
2641
2642         // Finally test to see if the mouse is in the background (within a child block's background).
2643         if (!inside)
2644             inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestChildBlockBackgrounds);
2645     }
2646
2647     // See if the mouse is inside us but not any of our descendants
2648     if (hitTestFilter != HitTestDescendants && !inside)
2649         inside = nodeAtPoint(request, result, locationInContainer, accumulatedOffset, HitTestBlockBackground);
2650
2651     return inside;
2652 }
2653
2654 void RenderObject::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
2655 {
2656     if (result.innerNode())
2657         return;
2658
2659     Node* node = this->node();
2660
2661     // If we hit the anonymous renderers inside generated content we should
2662     // actually hit the generated content so walk up to the PseudoElement.
2663     if (!node && parent() && parent()->isBeforeOrAfterContent()) {
2664         for (RenderObject* renderer = parent(); renderer && !node; renderer = renderer->parent())
2665             node = renderer->node();
2666     }
2667
2668     if (node) {
2669         result.setInnerNode(node);
2670         if (!result.innerNonSharedNode())
2671             result.setInnerNonSharedNode(node);
2672         result.setLocalPoint(point);
2673     }
2674 }
2675
2676 bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& /*locationInContainer*/, const LayoutPoint& /*accumulatedOffset*/, HitTestAction)
2677 {
2678     return false;
2679 }
2680
2681 void RenderObject::scheduleRelayout()
2682 {
2683     if (isRenderView()) {
2684         FrameView* view = toRenderView(this)->frameView();
2685         if (view)
2686             view->scheduleRelayout();
2687     } else {
2688         if (isRooted()) {
2689             if (RenderView* renderView = view()) {
2690                 if (FrameView* frameView = renderView->frameView())
2691                     frameView->scheduleRelayoutOfSubtree(this);
2692             }
2693         }
2694     }
2695 }
2696
2697 void RenderObject::layout()
2698 {
2699     StackStats::LayoutCheckPoint layoutCheckPoint;
2700     ASSERT(needsLayout());
2701     RenderObject* child = firstChild();
2702     while (child) {
2703         child->layoutIfNeeded();
2704         ASSERT(!child->needsLayout());
2705         child = child->nextSibling();
2706     }
2707     setNeedsLayout(false);
2708 }
2709
2710 enum StyleCacheState {
2711     Cached,
2712     Uncached
2713 };
2714
2715 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderObject* renderer, RenderStyle* style)
2716 {
2717     const RenderObject* rendererForFirstLineStyle = renderer;
2718     if (renderer->isBeforeOrAfterContent())
2719         rendererForFirstLineStyle = renderer->parent();
2720
2721     if (rendererForFirstLineStyle->isBlockFlow()) {
2722         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
2723             if (type == Cached)
2724                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2725             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == renderer ? style : 0);
2726         }
2727     } else if (!rendererForFirstLineStyle->isAnonymous() && rendererForFirstLineStyle->isRenderInline()) {
2728         RenderStyle* parentStyle = rendererForFirstLineStyle->parent()->firstLineStyle();
2729         if (parentStyle != rendererForFirstLineStyle->parent()->style()) {
2730             if (type == Cached) {
2731                 // A first-line style is in effect. Cache a first-line style for ourselves.
2732                 rendererForFirstLineStyle->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2733                 return rendererForFirstLineStyle->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2734             }
2735             return rendererForFirstLineStyle->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), parentStyle, style);
2736         }
2737     }
2738     return 0;
2739 }
2740
2741 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2742 {
2743     if (!document()->styleSheetCollection()->usesFirstLineRules())
2744         return 0;
2745
2746     ASSERT(!isText());
2747
2748     return firstLineStyleForCachedUncachedType(Uncached, this, style);
2749 }
2750
2751 RenderStyle* RenderObject::cachedFirstLineStyle() const
2752 {
2753     ASSERT(document()->styleSheetCollection()->usesFirstLineRules());
2754
2755     if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
2756         return style.get();
2757
2758     return m_style.get();
2759 }
2760
2761 RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2762 {
2763     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2764         return 0;
2765
2766     RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2767     if (cachedStyle)
2768         return cachedStyle;
2769     
2770     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
2771     if (result)
2772         return style()->addCachedPseudoStyle(result.release());
2773     return 0;
2774 }
2775
2776 PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2777 {
2778     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudoStyleRequest.pseudoId))
2779         return 0;
2780     
2781     if (!parentStyle) {
2782         ASSERT(!ownStyle);
2783         parentStyle = style();
2784     }
2785
2786     // FIXME: This "find nearest element parent" should be a helper function.
2787     Node* n = node();
2788     while (n && !n->isElementNode())
2789         n = n->parentNode();
2790     if (!n)
2791         return 0;
2792     Element* element = toElement(n);
2793
2794     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
2795         RefPtr<RenderStyle> result = document()->styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing);
2796         result->setStyleType(FIRST_LINE_INHERITED);
2797         return result.release();
2798     }
2799
2800     return document()->styleResolver()->pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
2801 }
2802
2803 static Color decorationColor(RenderStyle* style)
2804 {
2805     Color result;
2806 #if ENABLE(CSS3_TEXT)
2807     // Check for text decoration color first.
2808     result = style->visitedDependentColor(CSSPropertyWebkitTextDecorationColor);
2809     if (result.isValid())
2810         return result;
2811 #endif // CSS3_TEXT
2812     if (style->textStrokeWidth() > 0) {
2813         // Prefer stroke color if possible but not if it's fully transparent.
2814         result = style->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2815         if (result.alpha())
2816             return result;
2817     }
2818     
2819     result = style->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2820     return result;
2821 }
2822
2823 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2824                                            Color& linethrough, bool quirksMode, bool firstlineStyle)
2825 {
2826     RenderObject* curr = this;
2827     RenderStyle* styleToUse = 0;
2828     ETextDecoration currDecs = TDNONE;
2829     Color resultColor;
2830     do {
2831         styleToUse = curr->style(firstlineStyle);
2832         currDecs = styleToUse->textDecoration();
2833         resultColor = decorationColor(styleToUse);
2834         // Parameter 'decorations' is cast as an int to enable the bitwise operations below.
2835         if (currDecs) {
2836             if (currDecs & UNDERLINE) {
2837                 decorations &= ~UNDERLINE;
2838                 underline = resultColor;
2839             }
2840             if (currDecs & OVERLINE) {
2841                 decorations &= ~OVERLINE;
2842                 overline = resultColor;
2843             }
2844             if (currDecs & LINE_THROUGH) {
2845                 decorations &= ~LINE_THROUGH;
2846                 linethrough = resultColor;
2847             }
2848         }
2849         if (curr->isRubyText())
2850             return;
2851         curr = curr->parent();
2852         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2853             curr = toRenderBlock(curr)->continuation();
2854     } while (curr && decorations && (!quirksMode || !curr->node() ||
2855                                      (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
2856
2857     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2858     if (decorations && curr) {
2859         styleToUse = curr->style(firstlineStyle);
2860         resultColor = decorationColor(styleToUse);
2861         if (decorations & UNDERLINE)
2862             underline = resultColor;
2863         if (decorations & OVERLINE)
2864             overline = resultColor;
2865         if (decorations & LINE_THROUGH)
2866             linethrough = resultColor;
2867     }
2868 }
2869
2870 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2871 void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2872 {
2873     // Convert the style regions to absolute coordinates.
2874     if (style()->visibility() != VISIBLE || !isBox())
2875         return;
2876     
2877     RenderBox* box = toRenderBox(this);
2878     FloatPoint absPos = localToAbsolute();
2879
2880 #if ENABLE(DASHBOARD_SUPPORT)
2881     const Vector<StyleDashboardRegion>& styleRegions = style()->dashboardRegions();
2882     unsigned i, count = styleRegions.size();
2883     for (i = 0; i < count; i++) {
2884         StyleDashboardRegion styleRegion = styleRegions[i];
2885
2886         LayoutUnit w = box->width();
2887         LayoutUnit h = box->height();
2888
2889         AnnotatedRegionValue region;
2890         region.label = styleRegion.label;
2891         region.bounds = LayoutRect(styleRegion.offset.left().value(),
2892                                    styleRegion.offset.top().value(),
2893                                    w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2894                                    h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2895         region.type = styleRegion.type;
2896
2897         region.clip = region.bounds;
2898         computeAbsoluteRepaintRect(region.clip);
2899         if (region.clip.height() < 0) {
2900             region.clip.setHeight(0);
2901             region.clip.setWidth(0);
2902         }
2903
2904         region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2905         region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2906
2907         regions.append(region);
2908     }
2909 #else // ENABLE(DRAGGABLE_REGION)
2910     if (style()->getDraggableRegionMode() == DraggableRegionNone)
2911         return;
2912     AnnotatedRegionValue region;
2913     region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
2914     region.bounds = LayoutRect(absPos.x(), absPos.y(), box->width(), box->height());
2915     regions.append(region);
2916 #endif
2917 }
2918
2919 void RenderObject::collectAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
2920 {
2921     // RenderTexts don't have their own style, they just use their parent's style,
2922     // so we don't want to include them.
2923     if (isText())
2924         return;
2925
2926     addAnnotatedRegions(regions);
2927     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2928         curr->collectAnnotatedRegions(regions);
2929 }
2930 #endif
2931
2932 bool RenderObject::willRenderImage(CachedImage*)
2933 {
2934     // Without visibility we won't render (and therefore don't care about animation).
2935     if (style()->visibility() != VISIBLE)
2936         return false;
2937
2938     // We will not render a new image when Active DOM is suspended
2939     if (document()->activeDOMObjectsAreSuspended())
2940         return false;
2941
2942     // 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)
2943     // then we don't want to render either.
2944     return !document()->inPageCache() && !document()->view()->isOffscreen();
2945 }
2946
2947 int RenderObject::maximalOutlineSize(PaintPhase p) const
2948 {
2949     if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2950         return 0;
2951     return view()->maximalOutlineSize();
2952 }
2953
2954 int RenderObject::caretMinOffset() const
2955 {
2956     return 0;
2957 }
2958
2959 int RenderObject::caretMaxOffset() const
2960 {
2961     if (isReplaced())
2962         return node() ? max(1U, node()->childNodeCount()) : 1;
2963     if (isHR())
2964         return 1;
2965     return 0;
2966 }
2967
2968 int RenderObject::previousOffset(int current) const
2969 {
2970     return current - 1;
2971 }
2972
2973 int RenderObject::previousOffsetForBackwardDeletion(int current) const
2974 {
2975     return current - 1;
2976 }
2977
2978 int RenderObject::nextOffset(int current) const
2979 {
2980     return current + 1;
2981 }
2982
2983 void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
2984 {
2985     int outlineSize = outlineStyleForRepaint()->outlineSize();
2986     if (const ShadowData* boxShadow = style()->boxShadow()) {
2987         boxShadow->adjustRectForShadow(rect, outlineSize);
2988         return;
2989     }
2990
2991     rect.inflate(outlineSize);
2992 }
2993
2994 AnimationController* RenderObject::animation() const
2995 {
2996     return frame()->animation();
2997 }
2998
2999 void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
3000 {
3001     imageChanged(static_cast<WrappedImagePtr>(image), rect);
3002 }
3003
3004 Element* RenderObject::offsetParent() const
3005 {
3006     if (isRoot() || isBody())
3007         return 0;
3008
3009     if (isOutOfFlowPositioned() && style()->position() == FixedPosition)
3010         return 0;
3011
3012     // If A is an area HTML element which has a map HTML element somewhere in the ancestor
3013     // chain return the nearest ancestor map HTML element and stop this algorithm.
3014     // FIXME: Implement!
3015
3016     // FIXME: Figure out the right behavior for elements inside a flow thread.
3017     // https://bugs.webkit.org/show_bug.cgi?id=113276
3018
3019     float effectiveZoom = style()->effectiveZoom();
3020     Node* node = 0;
3021     for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
3022         node = ancestor->node();
3023
3024         // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
3025
3026         if (!node)
3027             continue;
3028
3029         if (ancestor->isPositioned())
3030             break;
3031
3032         if (node->hasTagName(HTMLNames::bodyTag))
3033             break;
3034
3035         if (!isPositioned() && (node->hasTagName(tableTag) || node->hasTagName(tdTag) || node->hasTagName(thTag)))
3036             break;
3037
3038         // Webkit specific extension where offsetParent stops at zoom level changes.
3039         if (effectiveZoom != ancestor->style()->effectiveZoom())
3040             break;
3041     }
3042
3043     return node && node->isElementNode() ? toElement(node) : 0;
3044 }
3045
3046 VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity)
3047 {
3048     // If this is a non-anonymous renderer in an editable area, then it's simple.
3049     if (Node* node = nonPseudoNode()) {
3050         if (!node->rendererIsEditable()) {
3051             // If it can be found, we prefer a visually equivalent position that is editable. 
3052             Position position = createLegacyEditingPosition(node, offset);
3053             Position candidate = position.downstream(CanCrossEditingBoundary);
3054             if (candidate.deprecatedNode()->rendererIsEditable())
3055                 return VisiblePosition(candidate, affinity);
3056             candidate = position.upstream(CanCrossEditingBoundary);
3057             if (candidate.deprecatedNode()->rendererIsEditable())
3058                 return VisiblePosition(candidate, affinity);
3059         }
3060         // FIXME: Eliminate legacy editing positions
3061         return VisiblePosition(createLegacyEditingPosition(node, offset), affinity);
3062     }
3063
3064     // We don't want to cross the boundary between editable and non-editable
3065     // regions of the document, but that is either impossible or at least
3066     // extremely unlikely in any normal case because we stop as soon as we
3067     // find a single non-anonymous renderer.
3068
3069     // Find a nearby non-anonymous renderer.
3070     RenderObject* child = this;
3071     while (RenderObject* parent = child->parent()) {
3072         // Find non-anonymous content after.
3073         RenderObject* renderer = child;
3074         while ((renderer = renderer->nextInPreOrder(parent))) {
3075             if (Node* node = renderer->nonPseudoNode())
3076                 return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3077         }
3078
3079         // Find non-anonymous content before.
3080         renderer = child;
3081         while ((renderer = renderer->previousInPreOrder())) {
3082             if (renderer == parent)
3083                 break;
3084             if (Node* node = renderer->nonPseudoNode())
3085                 return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
3086         }
3087
3088         // Use the parent itself unless it too is anonymous.
3089         if (Node* node = parent->nonPseudoNode())
3090             return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
3091
3092         // Repeat at the next level up.
3093         child = parent;
3094     }
3095
3096     // Everything was anonymous. Give up.
3097     return VisiblePosition();
3098 }
3099
3100 VisiblePosition RenderObject::createVisiblePosition(const Position& position)
3101 {
3102     if (position.isNotNull())
3103         return VisiblePosition(position);
3104
3105     ASSERT(!node());
3106     return createVisiblePosition(0, DOWNSTREAM);
3107 }
3108
3109 CursorDirective RenderObject::getCursor(const LayoutPoint&, Cursor&) const
3110 {
3111     return SetCursorBasedOnStyle;
3112 }
3113
3114 bool RenderObject::canUpdateSelectionOnRootLineBoxes()
3115 {
3116     if (needsLayout())
3117         return false;
3118
3119     RenderBlock* containingBlock = this->containingBlock();
3120     return containingBlock ? !containingBlock->needsLayout() : true;
3121 }
3122
3123 // We only create "generated" child renderers like one for first-letter if:
3124 // - the firstLetterBlock can have children in the DOM and
3125 // - the block doesn't have any special assumption on its text children.
3126 // This correctly prevents form controls from having such renderers.
3127 bool RenderObject::canHaveGeneratedChildren() const
3128 {
3129     return canHaveChildren();
3130 }
3131
3132 bool RenderObject::canBeReplacedWithInlineRunIn() const
3133 {
3134     return true;
3135 }
3136
3137 void RenderObject::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3138 {
3139     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Rendering);
3140     info.addMember(m_style, "style");
3141     info.addWeakPointer(m_node);
3142     info.addWeakPointer(m_parent);
3143     info.addWeakPointer(m_previous);
3144     info.addWeakPointer(m_next);
3145
3146     info.setCustomAllocation(true);
3147 }
3148
3149 #if ENABLE(SVG)
3150
3151 RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
3152 {
3153     ASSERT_NOT_REACHED();
3154     return 0;
3155 }
3156
3157 void RenderObject::setNeedsBoundariesUpdate()
3158 {
3159     if (RenderObject* renderer = parent())
3160         renderer->setNeedsBoundariesUpdate();
3161 }
3162
3163 FloatRect RenderObject::objectBoundingBox() const
3164 {
3165     ASSERT_NOT_REACHED();
3166     return FloatRect();
3167 }
3168
3169 FloatRect RenderObject::strokeBoundingBox() const
3170 {
3171     ASSERT_NOT_REACHED();
3172     return FloatRect();
3173 }
3174
3175 // Returns the smallest rectangle enclosing all of the painted content
3176 // respecting clipping, masking, filters, opacity, stroke-width and markers
3177 FloatRect RenderObject::repaintRectInLocalCoordinates() const
3178 {
3179     ASSERT_NOT_REACHED();
3180     return FloatRect();
3181 }
3182
3183 AffineTransform RenderObject::localTransform() const
3184 {
3185     static const AffineTransform identity;
3186     return identity;
3187 }
3188
3189 const AffineTransform& RenderObject::localToParentTransform() const
3190 {
3191     static const AffineTransform identity;
3192     return identity;
3193 }
3194
3195 bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
3196 {
3197     ASSERT_NOT_REACHED();
3198     return false;
3199 }
3200
3201 #endif // ENABLE(SVG)
3202
3203 } // namespace WebCore
3204
3205 #ifndef NDEBUG
3206
3207 void showTree(const WebCore::RenderObject* object)
3208 {
3209     if (object)
3210         object->showTreeForThis();
3211 }
3212
3213 void showLineTree(const WebCore::RenderObject* object)
3214 {
3215     if (object)
3216         object->showLineTreeForThis();
3217 }
3218
3219 void showRenderTree(const WebCore::RenderObject* object1)
3220 {
3221     showRenderTree(object1, 0);
3222 }
3223
3224 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
3225 {
3226     if (object1) {
3227         const WebCore::RenderObject* root = object1;
3228         while (root->parent())
3229             root = root->parent();
3230         root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
3231     }
3232 }
3233
3234 #endif