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