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