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