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#if ENABLE(COMPOSITED_FIXED_ELEMENTS)
1671            RenderLayer* layer = hasLayer() ? enclosingLayer() : 0;
1672            if (layer && m_style->position() != newStyle->position()
1673                && (m_style->position() == FixedPosition || newStyle->position() == FixedPosition))
1674                layer->dirtyZOrderLists();
1675#endif
1676            bool visibilityChanged = m_style->visibility() != newStyle->visibility()
1677                || m_style->zIndex() != newStyle->zIndex()
1678                || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
1679#if ENABLE(DASHBOARD_SUPPORT)
1680            if (visibilityChanged)
1681                document()->setDashboardRegionsDirty(true);
1682#endif
1683            if (visibilityChanged && AXObjectCache::accessibilityEnabled())
1684                document()->axObjectCache()->childrenChanged(this);
1685
1686            // Keep layer hierarchy visibility bits up to date if visibility changes.
1687            if (m_style->visibility() != newStyle->visibility()) {
1688                if (RenderLayer* l = enclosingLayer()) {
1689                    if (newStyle->visibility() == VISIBLE)
1690                        l->setHasVisibleContent(true);
1691                    else if (l->hasVisibleContent() && (this == l->renderer() || l->renderer()->style()->visibility() != VISIBLE)) {
1692                        l->dirtyVisibleContentStatus();
1693                        if (diff > StyleDifferenceRepaintLayer)
1694                            repaint();
1695                    }
1696                }
1697            }
1698        }
1699
1700        if (m_parent && (diff == StyleDifferenceRepaint || newStyle->outlineSize() < m_style->outlineSize()))
1701            repaint();
1702        if (isFloating() && (m_style->floating() != newStyle->floating()))
1703            // For changes in float styles, we need to conceivably remove ourselves
1704            // from the floating objects list.
1705            toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1706        else if (isPositioned() && (m_style->position() != newStyle->position()))
1707            // For changes in positioning styles, we need to conceivably remove ourselves
1708            // from the positioned objects list.
1709            toRenderBox(this)->removeFloatingOrPositionedChildFromBlockLists();
1710
1711        s_affectsParentBlock = isFloatingOrPositioned() &&
1712            (!newStyle->isFloating() && newStyle->position() != AbsolutePosition && newStyle->position() != FixedPosition)
1713            && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
1714
1715        // reset style flags
1716        if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
1717            m_floating = false;
1718            m_positioned = false;
1719            m_relPositioned = false;
1720        }
1721        m_horizontalWritingMode = true;
1722        m_paintBackground = false;
1723        m_hasOverflowClip = false;
1724        m_hasTransform = false;
1725        m_hasReflection = false;
1726    } else
1727        s_affectsParentBlock = false;
1728
1729    if (view()->frameView()) {
1730        bool shouldBlitOnFixedBackgroundImage = false;
1731#if ENABLE(FAST_MOBILE_SCROLLING)
1732        // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
1733        // when scrolling a page with a fixed background image. As an optimization, assuming there are
1734        // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
1735        // ignore the CSS property "background-attachment: fixed".
1736        shouldBlitOnFixedBackgroundImage = true;
1737#endif
1738
1739        bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
1740        bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
1741        if (oldStyleSlowScroll != newStyleSlowScroll) {
1742            if (oldStyleSlowScroll)
1743                view()->frameView()->removeSlowRepaintObject();
1744            if (newStyleSlowScroll)
1745                view()->frameView()->addSlowRepaintObject();
1746        }
1747    }
1748}
1749
1750static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
1751{
1752    ASSERT(a->cursors() != b->cursors());
1753    return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
1754}
1755
1756static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
1757{
1758    return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
1759}
1760
1761void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1762{
1763    if (s_affectsParentBlock)
1764        handleDynamicFloatPositionChange();
1765
1766    if (!m_parent)
1767        return;
1768
1769    if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1770        RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
1771
1772        // If the object already needs layout, then setNeedsLayout won't do
1773        // any work. But if the containing block has changed, then we may need
1774        // to mark the new containing blocks for layout. The change that can
1775        // directly affect the containing block of this object is a change to
1776        // the position style.
1777        if (m_needsLayout && oldStyle->position() != m_style->position())
1778            markContainingBlocksForLayout();
1779
1780        if (diff == StyleDifferenceLayout)
1781            setNeedsLayoutAndPrefWidthsRecalc();
1782        else
1783            setNeedsSimplifiedNormalFlowLayout();
1784    } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1785        setNeedsPositionedMovementLayout();
1786
1787    // Don't check for repaint here; we need to wait until the layer has been
1788    // updated by subclasses before we know if we have to repaint (in setStyle()).
1789
1790    if (oldStyle && !areCursorsEqual(oldStyle, style())) {
1791        if (Frame* frame = this->frame())
1792            frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
1793    }
1794}
1795
1796void RenderObject::propagateStyleToAnonymousChildren()
1797{
1798    for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1799        if (child->isAnonymous() && !child->isBeforeOrAfterContent()) {
1800            RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyle(style());
1801            if (style()->specifiesColumns()) {
1802                if (child->style()->specifiesColumns())
1803                    newStyle->inheritColumnPropertiesFrom(style());
1804                if (child->style()->columnSpan())
1805                    newStyle->setColumnSpan(true);
1806            }
1807            newStyle->setDisplay(child->style()->display());
1808            child->setStyle(newStyle.release());
1809        }
1810    }
1811}
1812
1813void RenderObject::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
1814{
1815    // Optimize the common case
1816    if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && (oldLayers->image() == newLayers->image()))
1817        return;
1818
1819    // Go through the new layers and addClients first, to avoid removing all clients of an image.
1820    for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
1821        if (currNew->image())
1822            currNew->image()->addClient(this);
1823    }
1824
1825    for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
1826        if (currOld->image())
1827            currOld->image()->removeClient(this);
1828    }
1829}
1830
1831void RenderObject::updateImage(StyleImage* oldImage, StyleImage* newImage)
1832{
1833    if (oldImage != newImage) {
1834        if (oldImage)
1835            oldImage->removeClient(this);
1836        if (newImage)
1837            newImage->addClient(this);
1838    }
1839}
1840
1841IntRect RenderObject::viewRect() const
1842{
1843    return view()->viewRect();
1844}
1845
1846FloatPoint RenderObject::localToAbsolute(const FloatPoint& localPoint, bool fixed, bool useTransforms) const
1847{
1848    TransformState transformState(TransformState::ApplyTransformDirection, localPoint);
1849    mapLocalToContainer(0, fixed, useTransforms, transformState);
1850    transformState.flatten();
1851
1852    return transformState.lastPlanarPoint();
1853}
1854
1855FloatPoint RenderObject::absoluteToLocal(const FloatPoint& containerPoint, bool fixed, bool useTransforms) const
1856{
1857    TransformState transformState(TransformState::UnapplyInverseTransformDirection, containerPoint);
1858    mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1859    transformState.flatten();
1860
1861    return transformState.lastPlanarPoint();
1862}
1863
1864void RenderObject::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState) const
1865{
1866    if (repaintContainer == this)
1867        return;
1868
1869    RenderObject* o = parent();
1870    if (!o)
1871        return;
1872
1873    IntPoint centerPoint = roundedIntPoint(transformState.mappedPoint());
1874    if (o->isBox() && o->style()->isFlippedBlocksWritingMode())
1875        transformState.move(toRenderBox(o)->flipForWritingModeIncludingColumns(roundedIntPoint(transformState.mappedPoint())) - centerPoint);
1876
1877    IntSize columnOffset;
1878    o->adjustForColumns(columnOffset, roundedIntPoint(transformState.mappedPoint()));
1879    if (!columnOffset.isZero())
1880        transformState.move(columnOffset);
1881
1882    if (o->hasOverflowClip())
1883        transformState.move(-toRenderBox(o)->layer()->scrolledContentOffset());
1884
1885    o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState);
1886}
1887
1888void RenderObject::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1889{
1890    RenderObject* o = parent();
1891    if (o) {
1892        o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1893        if (o->hasOverflowClip())
1894            transformState.move(toRenderBox(o)->layer()->scrolledContentOffset());
1895    }
1896}
1897
1898bool RenderObject::shouldUseTransformFromContainer(const RenderObject* containerObject) const
1899{
1900#if ENABLE(3D_RENDERING)
1901    // hasTransform() indicates whether the object has transform, transform-style or perspective. We just care about transform,
1902    // so check the layer's transform directly.
1903    return (hasLayer() && toRenderBoxModelObject(this)->layer()->transform()) || (containerObject && containerObject->style()->hasPerspective());
1904#else
1905    UNUSED_PARAM(containerObject);
1906    return hasTransform();
1907#endif
1908}
1909
1910void RenderObject::getTransformFromContainer(const RenderObject* containerObject, const IntSize& offsetInContainer, TransformationMatrix& transform) const
1911{
1912    transform.makeIdentity();
1913    transform.translate(offsetInContainer.width(), offsetInContainer.height());
1914    RenderLayer* layer;
1915    if (hasLayer() && (layer = toRenderBoxModelObject(this)->layer()) && layer->transform())
1916        transform.multiply(layer->currentTransform());
1917
1918#if ENABLE(3D_RENDERING)
1919    if (containerObject && containerObject->hasLayer() && containerObject->style()->hasPerspective()) {
1920        // Perpsective on the container affects us, so we have to factor it in here.
1921        ASSERT(containerObject->hasLayer());
1922        FloatPoint perspectiveOrigin = toRenderBoxModelObject(containerObject)->layer()->perspectiveOrigin();
1923
1924        TransformationMatrix perspectiveMatrix;
1925        perspectiveMatrix.applyPerspective(containerObject->style()->perspective());
1926
1927        transform.translateRight3d(-perspectiveOrigin.x(), -perspectiveOrigin.y(), 0);
1928        transform = perspectiveMatrix * transform;
1929        transform.translateRight3d(perspectiveOrigin.x(), perspectiveOrigin.y(), 0);
1930    }
1931#else
1932    UNUSED_PARAM(containerObject);
1933#endif
1934}
1935
1936FloatQuad RenderObject::localToContainerQuad(const FloatQuad& localQuad, RenderBoxModelObject* repaintContainer, bool fixed) const
1937{
1938    // Track the point at the center of the quad's bounding box. As mapLocalToContainer() calls offsetFromContainer(),
1939    // it will use that point as the reference point to decide which column's transform to apply in multiple-column blocks.
1940    TransformState transformState(TransformState::ApplyTransformDirection, localQuad.boundingBox().center(), &localQuad);
1941    mapLocalToContainer(repaintContainer, fixed, true, transformState);
1942    transformState.flatten();
1943
1944    return transformState.lastPlanarQuad();
1945}
1946
1947IntSize RenderObject::offsetFromContainer(RenderObject* o, const IntPoint& point) const
1948{
1949    ASSERT(o == container());
1950
1951    IntSize offset;
1952
1953    o->adjustForColumns(offset, point);
1954
1955    if (o->hasOverflowClip())
1956        offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1957
1958    return offset;
1959}
1960
1961IntSize RenderObject::offsetFromAncestorContainer(RenderObject* container) const
1962{
1963    IntSize offset;
1964    IntPoint referencePoint;
1965    const RenderObject* currContainer = this;
1966    do {
1967        RenderObject* nextContainer = currContainer->container();
1968        ASSERT(nextContainer);  // This means we reached the top without finding container.
1969        if (!nextContainer)
1970            break;
1971        ASSERT(!currContainer->hasTransform());
1972        IntSize currentOffset = currContainer->offsetFromContainer(nextContainer, referencePoint);
1973        offset += currentOffset;
1974        referencePoint.move(currentOffset);
1975        currContainer = nextContainer;
1976    } while (currContainer != container);
1977
1978    return offset;
1979}
1980
1981IntRect RenderObject::localCaretRect(InlineBox*, int, int* extraWidthToEndOfLine)
1982{
1983    if (extraWidthToEndOfLine)
1984        *extraWidthToEndOfLine = 0;
1985
1986    return IntRect();
1987}
1988
1989RenderView* RenderObject::view() const
1990{
1991    return toRenderView(document()->renderer());
1992}
1993
1994bool RenderObject::isRooted(RenderView** view)
1995{
1996    RenderObject* o = this;
1997    while (o->parent())
1998        o = o->parent();
1999
2000    if (!o->isRenderView())
2001        return false;
2002
2003    if (view)
2004        *view = toRenderView(o);
2005
2006    return true;
2007}
2008
2009bool RenderObject::hasOutlineAnnotation() const
2010{
2011    return node() && node()->isLink() && document()->printing();
2012}
2013
2014RenderObject* RenderObject::container(RenderBoxModelObject* repaintContainer, bool* repaintContainerSkipped) const
2015{
2016    if (repaintContainerSkipped)
2017        *repaintContainerSkipped = false;
2018
2019    // This method is extremely similar to containingBlock(), but with a few notable
2020    // exceptions.
2021    // (1) It can be used on orphaned subtrees, i.e., it can be called safely even when
2022    // the object is not part of the primary document subtree yet.
2023    // (2) For normal flow elements, it just returns the parent.
2024    // (3) For absolute positioned elements, it will return a relative positioned inline.
2025    // containingBlock() simply skips relpositioned inlines and lets an enclosing block handle
2026    // the layout of the positioned object.  This does mean that computePositionedLogicalWidth and
2027    // computePositionedLogicalHeight have to use container().
2028    RenderObject* o = parent();
2029
2030    if (isText())
2031        return o;
2032
2033    EPosition pos = m_style->position();
2034    if (pos == FixedPosition) {
2035        // container() can be called on an object that is not in the
2036        // tree yet.  We don't call view() since it will assert if it
2037        // can't get back to the canvas.  Instead we just walk as high up
2038        // as we can.  If we're in the tree, we'll get the root.  If we
2039        // aren't we'll get the root of our little subtree (most likely
2040        // we'll just return 0).
2041        // FIXME: The definition of view() has changed to not crawl up the render tree.  It might
2042        // be safe now to use it.
2043        while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
2044            if (repaintContainerSkipped && o == repaintContainer)
2045                *repaintContainerSkipped = true;
2046            o = o->parent();
2047        }
2048    } else if (pos == AbsolutePosition) {
2049        // Same goes here.  We technically just want our containing block, but
2050        // we may not have one if we're part of an uninstalled subtree.  We'll
2051        // climb as high as we can though.
2052        while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
2053            if (repaintContainerSkipped && o == repaintContainer)
2054                *repaintContainerSkipped = true;
2055#if ENABLE(SVG)
2056                if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
2057                    break;
2058#endif
2059            o = o->parent();
2060        }
2061    }
2062
2063    return o;
2064}
2065
2066bool RenderObject::isSelectionBorder() const
2067{
2068    SelectionState st = selectionState();
2069    return st == SelectionStart || st == SelectionEnd || st == SelectionBoth;
2070}
2071
2072void RenderObject::destroy()
2073{
2074    // Destroy any leftover anonymous children.
2075    RenderObjectChildList* children = virtualChildren();
2076    if (children)
2077        children->destroyLeftoverChildren();
2078
2079    // If this renderer is being autoscrolled, stop the autoscroll timer
2080
2081    // FIXME: RenderObject::destroy should not get called with a renderer whose document
2082    // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
2083    // check that the frame is not null.
2084    ASSERT(frame());
2085    if (frame() && frame()->eventHandler()->autoscrollRenderer() == this)
2086        frame()->eventHandler()->stopAutoscrollTimer(true);
2087
2088    if (AXObjectCache::accessibilityEnabled()) {
2089        document()->axObjectCache()->childrenChanged(this->parent());
2090        document()->axObjectCache()->remove(this);
2091    }
2092    animation()->cancelAnimations(this);
2093
2094    // By default no ref-counting. RenderWidget::destroy() doesn't call
2095    // this function because it needs to do ref-counting. If anything
2096    // in this function changes, be sure to fix RenderWidget::destroy() as well.
2097
2098    remove();
2099
2100    // If this renderer had a parent, remove should have destroyed any counters
2101    // attached to this renderer and marked the affected other counters for
2102    // reevaluation. This apparently redundant check is here for the case when
2103    // this renderer had no parent at the time remove() was called.
2104
2105    if (m_hasCounterNodeMap)
2106        RenderCounter::destroyCounterNodes(this);
2107
2108    // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
2109    // be moved into RenderBoxModelObject::destroy.
2110    if (hasLayer()) {
2111        setHasLayer(false);
2112        toRenderBoxModelObject(this)->destroyLayer();
2113    }
2114    arenaDelete(renderArena(), this);
2115}
2116
2117void RenderObject::arenaDelete(RenderArena* arena, void* base)
2118{
2119    if (m_style) {
2120        for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
2121            if (StyleImage* backgroundImage = bgLayer->image())
2122                backgroundImage->removeClient(this);
2123        }
2124
2125        for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2126            if (StyleImage* maskImage = maskLayer->image())
2127                maskImage->removeClient(this);
2128        }
2129
2130        if (StyleImage* borderImage = m_style->borderImage().image())
2131            borderImage->removeClient(this);
2132
2133        if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
2134            maskBoxImage->removeClient(this);
2135    }
2136
2137#ifndef NDEBUG
2138    void* savedBase = baseOfRenderObjectBeingDeleted;
2139    baseOfRenderObjectBeingDeleted = base;
2140#endif
2141    delete this;
2142#ifndef NDEBUG
2143    baseOfRenderObjectBeingDeleted = savedBase;
2144#endif
2145
2146    // Recover the size left there for us by operator delete and free the memory.
2147    arena->free(*(size_t*)base, base);
2148}
2149
2150VisiblePosition RenderObject::positionForCoordinates(int x, int y)
2151{
2152    return positionForPoint(IntPoint(x, y));
2153}
2154
2155VisiblePosition RenderObject::positionForPoint(const IntPoint&)
2156{
2157    return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2158}
2159
2160void RenderObject::updateDragState(bool dragOn)
2161{
2162    bool valueChanged = (dragOn != m_isDragging);
2163    m_isDragging = dragOn;
2164    if (valueChanged && style()->affectedByDragRules() && node())
2165        node()->setNeedsStyleRecalc();
2166    for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2167        curr->updateDragState(dragOn);
2168}
2169
2170bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const IntPoint& point, int tx, int ty, HitTestFilter hitTestFilter)
2171{
2172    bool inside = false;
2173    if (hitTestFilter != HitTestSelf) {
2174        // First test the foreground layer (lines and inlines).
2175        inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestForeground);
2176
2177        // Test floats next.
2178        if (!inside)
2179            inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestFloat);
2180
2181        // Finally test to see if the mouse is in the background (within a child block's background).
2182        if (!inside)
2183            inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestChildBlockBackgrounds);
2184    }
2185
2186    // See if the mouse is inside us but not any of our descendants
2187    if (hitTestFilter != HitTestDescendants && !inside)
2188        inside = nodeAtPoint(request, result, point.x(), point.y(), tx, ty, HitTestBlockBackground);
2189
2190    return inside;
2191}
2192
2193void RenderObject::updateHitTestResult(HitTestResult& result, const IntPoint& point)
2194{
2195    if (result.innerNode())
2196        return;
2197
2198    Node* n = node();
2199    if (n) {
2200        result.setInnerNode(n);
2201        if (!result.innerNonSharedNode())
2202            result.setInnerNonSharedNode(n);
2203        result.setLocalPoint(point);
2204    }
2205}
2206
2207bool RenderObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, int /*x*/, int /*y*/, int /*tx*/, int /*ty*/, HitTestAction)
2208{
2209    return false;
2210}
2211
2212void RenderObject::scheduleRelayout()
2213{
2214    if (isRenderView()) {
2215        FrameView* view = toRenderView(this)->frameView();
2216        if (view)
2217            view->scheduleRelayout();
2218    } else if (parent()) {
2219        FrameView* v = view() ? view()->frameView() : 0;
2220        if (v)
2221            v->scheduleRelayoutOfSubtree(this);
2222    }
2223}
2224
2225void RenderObject::layout()
2226{
2227    ASSERT(needsLayout());
2228    RenderObject* child = firstChild();
2229    while (child) {
2230        child->layoutIfNeeded();
2231        ASSERT(!child->needsLayout());
2232        child = child->nextSibling();
2233    }
2234    setNeedsLayout(false);
2235}
2236
2237PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
2238{
2239    if (!document()->usesFirstLineRules())
2240        return 0;
2241
2242    ASSERT(!isText());
2243
2244    RefPtr<RenderStyle> result;
2245
2246    if (isBlockFlow()) {
2247        if (RenderBlock* firstLineBlock = this->firstLineBlock())
2248            result = firstLineBlock->getUncachedPseudoStyle(FIRST_LINE, style, firstLineBlock == this ? style : 0);
2249    } else if (!isAnonymous() && isRenderInline()) {
2250        RenderStyle* parentStyle = parent()->firstLineStyle();
2251        if (parentStyle != parent()->style())
2252            result = getUncachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle, style);
2253    }
2254
2255    return result.release();
2256}
2257
2258RenderStyle* RenderObject::firstLineStyleSlowCase() const
2259{
2260    ASSERT(document()->usesFirstLineRules());
2261
2262    RenderStyle* style = m_style.get();
2263    const RenderObject* renderer = isText() ? parent() : this;
2264    if (renderer->isBlockFlow()) {
2265        if (RenderBlock* firstLineBlock = renderer->firstLineBlock())
2266            style = firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
2267    } else if (!renderer->isAnonymous() && renderer->isRenderInline()) {
2268        RenderStyle* parentStyle = renderer->parent()->firstLineStyle();
2269        if (parentStyle != renderer->parent()->style()) {
2270            // A first-line style is in effect. Cache a first-line style for ourselves.
2271            renderer->style()->setHasPseudoStyle(FIRST_LINE_INHERITED);
2272            style = renderer->getCachedPseudoStyle(FIRST_LINE_INHERITED, parentStyle);
2273        }
2274    }
2275
2276    return style;
2277}
2278
2279RenderStyle* RenderObject::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
2280{
2281    if (pseudo < FIRST_INTERNAL_PSEUDOID && !style()->hasPseudoStyle(pseudo))
2282        return 0;
2283
2284    RenderStyle* cachedStyle = style()->getCachedPseudoStyle(pseudo);
2285    if (cachedStyle)
2286        return cachedStyle;
2287
2288    RefPtr<RenderStyle> result = getUncachedPseudoStyle(pseudo, parentStyle);
2289    if (result)
2290        return style()->addCachedPseudoStyle(result.release());
2291    return 0;
2292}
2293
2294PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle, RenderStyle* ownStyle) const
2295{
2296    if (pseudo < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style()->hasPseudoStyle(pseudo))
2297        return 0;
2298
2299    if (!parentStyle) {
2300        ASSERT(!ownStyle);
2301        parentStyle = style();
2302    }
2303
2304    Node* n = node();
2305    while (n && !n->isElementNode())
2306        n = n->parentNode();
2307    if (!n)
2308        return 0;
2309
2310    RefPtr<RenderStyle> result;
2311    if (pseudo == FIRST_LINE_INHERITED) {
2312        result = document()->styleSelector()->styleForElement(static_cast<Element*>(n), parentStyle, false);
2313        result->setStyleType(FIRST_LINE_INHERITED);
2314    } else
2315        result = document()->styleSelector()->pseudoStyleForElement(pseudo, static_cast<Element*>(n), parentStyle);
2316    return result.release();
2317}
2318
2319static Color decorationColor(RenderObject* renderer)
2320{
2321    Color result;
2322    if (renderer->style()->textStrokeWidth() > 0) {
2323        // Prefer stroke color if possible but not if it's fully transparent.
2324        result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
2325        if (result.alpha())
2326            return result;
2327    }
2328
2329    result = renderer->style()->visitedDependentColor(CSSPropertyWebkitTextFillColor);
2330    return result;
2331}
2332
2333void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
2334                                           Color& linethrough, bool quirksMode)
2335{
2336    RenderObject* curr = this;
2337    do {
2338        int currDecs = curr->style()->textDecoration();
2339        if (currDecs) {
2340            if (currDecs & UNDERLINE) {
2341                decorations &= ~UNDERLINE;
2342                underline = decorationColor(curr);
2343            }
2344            if (currDecs & OVERLINE) {
2345                decorations &= ~OVERLINE;
2346                overline = decorationColor(curr);
2347            }
2348            if (currDecs & LINE_THROUGH) {
2349                decorations &= ~LINE_THROUGH;
2350                linethrough = decorationColor(curr);
2351            }
2352        }
2353        curr = curr->parent();
2354        if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
2355            curr = toRenderBlock(curr)->continuation();
2356    } while (curr && decorations && (!quirksMode || !curr->node() ||
2357                                     (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
2358
2359    // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
2360    if (decorations && curr) {
2361        if (decorations & UNDERLINE)
2362            underline = decorationColor(curr);
2363        if (decorations & OVERLINE)
2364            overline = decorationColor(curr);
2365        if (decorations & LINE_THROUGH)
2366            linethrough = decorationColor(curr);
2367    }
2368}
2369
2370#if ENABLE(DASHBOARD_SUPPORT)
2371void RenderObject::addDashboardRegions(Vector<DashboardRegionValue>& regions)
2372{
2373    // Convert the style regions to absolute coordinates.
2374    if (style()->visibility() != VISIBLE || !isBox())
2375        return;
2376
2377    RenderBox* box = toRenderBox(this);
2378
2379    const Vector<StyleDashboardRegion>& styleRegions = style()->dashboardRegions();
2380    unsigned i, count = styleRegions.size();
2381    for (i = 0; i < count; i++) {
2382        StyleDashboardRegion styleRegion = styleRegions[i];
2383
2384        int w = box->width();
2385        int h = box->height();
2386
2387        DashboardRegionValue region;
2388        region.label = styleRegion.label;
2389        region.bounds = IntRect(styleRegion.offset.left().value(),
2390                                styleRegion.offset.top().value(),
2391                                w - styleRegion.offset.left().value() - styleRegion.offset.right().value(),
2392                                h - styleRegion.offset.top().value() - styleRegion.offset.bottom().value());
2393        region.type = styleRegion.type;
2394
2395        region.clip = region.bounds;
2396        computeAbsoluteRepaintRect(region.clip);
2397        if (region.clip.height() < 0) {
2398            region.clip.setHeight(0);
2399            region.clip.setWidth(0);
2400        }
2401
2402        FloatPoint absPos = localToAbsolute();
2403        region.bounds.setX(absPos.x() + styleRegion.offset.left().value());
2404        region.bounds.setY(absPos.y() + styleRegion.offset.top().value());
2405
2406        if (frame()) {
2407            float pageScaleFactor = frame()->page()->chrome()->scaleFactor();
2408            if (pageScaleFactor != 1.0f) {
2409                region.bounds.scale(pageScaleFactor);
2410                region.clip.scale(pageScaleFactor);
2411            }
2412        }
2413
2414        regions.append(region);
2415    }
2416}
2417
2418void RenderObject::collectDashboardRegions(Vector<DashboardRegionValue>& regions)
2419{
2420    // RenderTexts don't have their own style, they just use their parent's style,
2421    // so we don't want to include them.
2422    if (isText())
2423        return;
2424
2425    addDashboardRegions(regions);
2426    for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
2427        curr->collectDashboardRegions(regions);
2428}
2429#endif
2430
2431bool RenderObject::willRenderImage(CachedImage*)
2432{
2433    // Without visibility we won't render (and therefore don't care about animation).
2434    if (style()->visibility() != VISIBLE)
2435        return false;
2436
2437    // 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)
2438    // then we don't want to render either.
2439    return !document()->inPageCache() && !document()->view()->isOffscreen();
2440}
2441
2442int RenderObject::maximalOutlineSize(PaintPhase p) const
2443{
2444    if (p != PaintPhaseOutline && p != PaintPhaseSelfOutline && p != PaintPhaseChildOutlines)
2445        return 0;
2446    return toRenderView(document()->renderer())->maximalOutlineSize();
2447}
2448
2449int RenderObject::caretMinOffset() const
2450{
2451    return 0;
2452}
2453
2454int RenderObject::caretMaxOffset() const
2455{
2456    if (isReplaced())
2457        return node() ? max(1U, node()->childNodeCount()) : 1;
2458    if (isHR())
2459        return 1;
2460    return 0;
2461}
2462
2463unsigned RenderObject::caretMaxRenderedOffset() const
2464{
2465    return 0;
2466}
2467
2468int RenderObject::previousOffset(int current) const
2469{
2470    return current - 1;
2471}
2472
2473int RenderObject::previousOffsetForBackwardDeletion(int current) const
2474{
2475    return current - 1;
2476}
2477
2478int RenderObject::nextOffset(int current) const
2479{
2480    return current + 1;
2481}
2482
2483void RenderObject::adjustRectForOutlineAndShadow(IntRect& rect) const
2484{
2485    int outlineSize = outlineStyleForRepaint()->outlineSize();
2486    if (const ShadowData* boxShadow = style()->boxShadow()) {
2487        boxShadow->adjustRectForShadow(rect, outlineSize);
2488        return;
2489    }
2490
2491    rect.inflate(outlineSize);
2492}
2493
2494AnimationController* RenderObject::animation() const
2495{
2496    return frame()->animation();
2497}
2498
2499void RenderObject::imageChanged(CachedImage* image, const IntRect* rect)
2500{
2501    imageChanged(static_cast<WrappedImagePtr>(image), rect);
2502}
2503
2504RenderBoxModelObject* RenderObject::offsetParent() const
2505{
2506    // If any of the following holds true return null and stop this algorithm:
2507    // A is the root element.
2508    // A is the HTML body element.
2509    // The computed value of the position property for element A is fixed.
2510    if (isRoot() || isBody() || (isPositioned() && style()->position() == FixedPosition))
2511        return 0;
2512
2513    // If A is an area HTML element which has a map HTML element somewhere in the ancestor
2514    // chain return the nearest ancestor map HTML element and stop this algorithm.
2515    // FIXME: Implement!
2516
2517    // Return the nearest ancestor element of A for which at least one of the following is
2518    // true and stop this algorithm if such an ancestor is found:
2519    //     * The computed value of the position property is not static.
2520    //     * It is the HTML body element.
2521    //     * The computed value of the position property of A is static and the ancestor
2522    //       is one of the following HTML elements: td, th, or table.
2523    //     * Our own extension: if there is a difference in the effective zoom
2524
2525    bool skipTables = isPositioned() || isRelPositioned();
2526    float currZoom = style()->effectiveZoom();
2527    RenderObject* curr = parent();
2528    while (curr && (!curr->node() || (!curr->isPositioned() && !curr->isRelPositioned() && !curr->isBody()))) {
2529        Node* element = curr->node();
2530        if (!skipTables && element) {
2531            bool isTableElement = element->hasTagName(tableTag) ||
2532                                  element->hasTagName(tdTag) ||
2533                                  element->hasTagName(thTag);
2534
2535#if ENABLE(WML)
2536            if (!isTableElement && element->isWMLElement())
2537                isTableElement = element->hasTagName(WMLNames::tableTag) ||
2538                                 element->hasTagName(WMLNames::tdTag);
2539#endif
2540
2541            if (isTableElement)
2542                break;
2543        }
2544
2545        float newZoom = curr->style()->effectiveZoom();
2546        if (currZoom != newZoom)
2547            break;
2548        currZoom = newZoom;
2549        curr = curr->parent();
2550    }
2551    return curr && curr->isBoxModelObject() ? toRenderBoxModelObject(curr) : 0;
2552}
2553
2554VisiblePosition RenderObject::createVisiblePosition(int offset, EAffinity affinity)
2555{
2556    // If this is a non-anonymous renderer in an editable area, then it's simple.
2557    if (Node* node = this->node()) {
2558        if (!node->rendererIsEditable()) {
2559            // If it can be found, we prefer a visually equivalent position that is editable.
2560            Position position(node, offset);
2561            Position candidate = position.downstream(CanCrossEditingBoundary);
2562            if (candidate.deprecatedNode()->rendererIsEditable())
2563                return VisiblePosition(candidate, affinity);
2564            candidate = position.upstream(CanCrossEditingBoundary);
2565            if (candidate.deprecatedNode()->rendererIsEditable())
2566                return VisiblePosition(candidate, affinity);
2567        }
2568        // FIXME: Eliminate legacy editing positions
2569        return VisiblePosition(Position(node, offset), affinity);
2570    }
2571
2572    // We don't want to cross the boundary between editable and non-editable
2573    // regions of the document, but that is either impossible or at least
2574    // extremely unlikely in any normal case because we stop as soon as we
2575    // find a single non-anonymous renderer.
2576
2577    // Find a nearby non-anonymous renderer.
2578    RenderObject* child = this;
2579    while (RenderObject* parent = child->parent()) {
2580        // Find non-anonymous content after.
2581        RenderObject* renderer = child;
2582        while ((renderer = renderer->nextInPreOrder(parent))) {
2583            if (Node* node = renderer->node())
2584                return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2585        }
2586
2587        // Find non-anonymous content before.
2588        renderer = child;
2589        while ((renderer = renderer->previousInPreOrder())) {
2590            if (renderer == parent)
2591                break;
2592            if (Node* node = renderer->node())
2593                return VisiblePosition(lastPositionInOrAfterNode(node), DOWNSTREAM);
2594        }
2595
2596        // Use the parent itself unless it too is anonymous.
2597        if (Node* node = parent->node())
2598            return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
2599
2600        // Repeat at the next level up.
2601        child = parent;
2602    }
2603
2604    // Everything was anonymous. Give up.
2605    return VisiblePosition();
2606}
2607
2608VisiblePosition RenderObject::createVisiblePosition(const Position& position)
2609{
2610    if (position.isNotNull())
2611        return VisiblePosition(position);
2612
2613    ASSERT(!node());
2614    return createVisiblePosition(0, DOWNSTREAM);
2615}
2616
2617#if ENABLE(SVG)
2618RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
2619{
2620    ASSERT_NOT_REACHED();
2621    return 0;
2622}
2623
2624void RenderObject::setNeedsBoundariesUpdate()
2625{
2626    if (RenderObject* renderer = parent())
2627        renderer->setNeedsBoundariesUpdate();
2628}
2629
2630FloatRect RenderObject::objectBoundingBox() const
2631{
2632    ASSERT_NOT_REACHED();
2633    return FloatRect();
2634}
2635
2636FloatRect RenderObject::strokeBoundingBox() const
2637{
2638    ASSERT_NOT_REACHED();
2639    return FloatRect();
2640}
2641
2642// Returns the smallest rectangle enclosing all of the painted content
2643// respecting clipping, masking, filters, opacity, stroke-width and markers
2644FloatRect RenderObject::repaintRectInLocalCoordinates() const
2645{
2646    ASSERT_NOT_REACHED();
2647    return FloatRect();
2648}
2649
2650AffineTransform RenderObject::localTransform() const
2651{
2652    static const AffineTransform identity;
2653    return identity;
2654}
2655
2656const AffineTransform& RenderObject::localToParentTransform() const
2657{
2658    static const AffineTransform identity;
2659    return identity;
2660}
2661
2662bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint&, HitTestAction)
2663{
2664    ASSERT_NOT_REACHED();
2665    return false;
2666}
2667
2668#endif // ENABLE(SVG)
2669
2670} // namespace WebCore
2671
2672#ifndef NDEBUG
2673
2674void showTree(const WebCore::RenderObject* ro)
2675{
2676    if (ro)
2677        ro->showTreeForThis();
2678}
2679
2680void showRenderTree(const WebCore::RenderObject* object1)
2681{
2682    showRenderTree(object1, 0);
2683}
2684
2685void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2)
2686{
2687    if (object1) {
2688        const WebCore::RenderObject* root = object1;
2689        while (root->parent())
2690            root = root->parent();
2691        root->showRenderTreeAndMark(object1, "*", object2, "-", 0);
2692    }
2693}
2694
2695#endif
2696