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