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