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