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