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