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