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