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