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