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