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