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