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