f079d8b05a16d1b018ff97f74c7dd0b290fda608
[WebKit.git] / Source / WebCore / rendering / RenderBoxModelObject.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7  * Copyright (C) 2010 Google Inc. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  *
24  */
25
26 #include "config.h"
27 #include "RenderBoxModelObject.h"
28
29 #include "FilterOperations.h"
30 #include "GraphicsContext.h"
31 #include "HTMLFrameOwnerElement.h"
32 #include "HTMLNames.h"
33 #include "ImageBuffer.h"
34 #include "Page.h"
35 #include "Path.h"
36 #include "RenderBlock.h"
37 #include "RenderInline.h"
38 #include "RenderLayer.h"
39 #include "RenderView.h"
40 #include "Settings.h"
41 #include "TransformState.h"
42 #include <wtf/CurrentTime.h>
43
44 #if USE(ACCELERATED_COMPOSITING)
45 #include "RenderLayerBacking.h"
46 #include "RenderLayerCompositor.h"
47 #endif
48
49 using namespace std;
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 bool RenderBoxModelObject::s_wasFloating = false;
56 bool RenderBoxModelObject::s_hadLayer = false;
57 bool RenderBoxModelObject::s_hadTransform = false;
58 bool RenderBoxModelObject::s_layerWasSelfPainting = false;
59
60 static const double cInterpolationCutoff = 800. * 800.;
61 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
62
63 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
64 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
65
66 // The HashMap for storing continuation pointers.
67 // An inline can be split with blocks occuring in between the inline content.
68 // When this occurs we need a pointer to the next object. We can basically be
69 // split into a sequence of inlines and blocks. The continuation will either be
70 // an anonymous block (that houses other blocks) or it will be an inline flow.
71 // <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
72 // its continuation but the <b> will just have an inline as its continuation.
73 typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
74 static ContinuationMap* continuationMap = 0;
75
76 // This HashMap is similar to the continuation map, but connects first-letter
77 // renderers to their remaining text fragments.
78 typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
79 static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
80
81 class ImageQualityController {
82     WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
83 public:
84     ImageQualityController();
85     bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
86     void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
87     void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
88     void objectDestroyed(RenderBoxModelObject*);
89     bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
90
91 private:
92     void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
93     void restartTimer();
94
95     ObjectLayerSizeMap m_objectLayerSizeMap;
96     Timer<ImageQualityController> m_timer;
97     bool m_animatedResizeIsActive;
98 };
99
100 ImageQualityController::ImageQualityController()
101     : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
102     , m_animatedResizeIsActive(false)
103 {
104 }
105
106 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
107 {
108     if (innerMap) {
109         innerMap->remove(layer);
110         if (innerMap->isEmpty())
111             objectDestroyed(object);
112     }
113 }
114     
115 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
116 {
117     if (innerMap)
118         innerMap->set(layer, size);
119     else {
120         LayerSizeMap newInnerMap;
121         newInnerMap.set(layer, size);
122         m_objectLayerSizeMap.set(object, newInnerMap);
123     }
124 }
125     
126 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
127 {
128     m_objectLayerSizeMap.remove(object);
129     if (m_objectLayerSizeMap.isEmpty()) {
130         m_animatedResizeIsActive = false;
131         m_timer.stop();
132     }
133 }
134
135 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
136 {
137     if (m_animatedResizeIsActive) {
138         m_animatedResizeIsActive = false;
139         for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it)
140             it->first->repaint();
141     }
142 }
143
144 void ImageQualityController::restartTimer()
145 {
146     m_timer.startOneShot(cLowQualityTimeThreshold);
147 }
148
149 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
150 {
151     // If the image is not a bitmap image, then none of this is relevant and we just paint at high
152     // quality.
153     if (!image || !image->isBitmapImage() || context->paintingDisabled())
154         return false;
155
156     if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
157         return true;
158     
159     // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
160     // is actually being scaled.
161     IntSize imageSize(image->width(), image->height());
162
163     // Look ourselves up in the hashtables.
164     ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
165     LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->second : 0;
166     LayoutSize oldSize;
167     bool isFirstResize = true;
168     if (innerMap) {
169         LayerSizeMap::iterator j = innerMap->find(layer);
170         if (j != innerMap->end()) {
171             isFirstResize = false;
172             oldSize = j->second;
173         }
174     }
175
176     const AffineTransform& currentTransform = context->getCTM();
177     bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
178     if (!contextIsScaled && size == imageSize) {
179         // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
180         removeLayer(object, innerMap, layer);
181         return false;
182     }
183
184     // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
185     if (object->document()->page()->inLowQualityImageInterpolationMode()) {
186         double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
187         if (totalPixels > cInterpolationCutoff)
188             return true;
189     }
190
191     // If an animated resize is active, paint in low quality and kick the timer ahead.
192     if (m_animatedResizeIsActive) {
193         set(object, innerMap, layer, size);
194         restartTimer();
195         return true;
196     }
197     // If this is the first time resizing this image, or its size is the
198     // same as the last resize, draw at high res, but record the paint
199     // size and set the timer.
200     if (isFirstResize || oldSize == size) {
201         restartTimer();
202         set(object, innerMap, layer, size);
203         return false;
204     }
205     // If the timer is no longer active, draw at high quality and don't
206     // set the timer.
207     if (!m_timer.isActive()) {
208         removeLayer(object, innerMap, layer);
209         return false;
210     }
211     // This object has been resized to two different sizes while the timer
212     // is active, so draw at low quality, set the flag for animated resizes and
213     // the object to the list for high quality redraw.
214     set(object, innerMap, layer, size);
215     m_animatedResizeIsActive = true;
216     restartTimer();
217     return true;
218 }
219
220 static ImageQualityController* gImageQualityController = 0;
221
222 static ImageQualityController* imageQualityController()
223 {
224     if (!gImageQualityController)
225         gImageQualityController = new ImageQualityController;
226
227     return gImageQualityController;
228 }
229
230 void RenderBoxModelObject::setSelectionState(SelectionState state)
231 {
232     if (state == SelectionInside && selectionState() != SelectionNone)
233         return;
234
235     if ((state == SelectionStart && selectionState() == SelectionEnd)
236         || (state == SelectionEnd && selectionState() == SelectionStart))
237         RenderObject::setSelectionState(SelectionBoth);
238     else
239         RenderObject::setSelectionState(state);
240
241     // FIXME: We should consider whether it is OK propagating to ancestor RenderInlines.
242     // This is a workaround for http://webkit.org/b/32123
243     // The containing block can be null in case of an orphaned tree.
244     RenderBlock* containingBlock = this->containingBlock();
245     if (containingBlock && !containingBlock->isRenderView())
246         containingBlock->setSelectionState(state);
247 }
248
249 #if USE(ACCELERATED_COMPOSITING)
250 void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
251 {
252     if (!hasLayer())
253         return;
254
255     layer()->contentChanged(changeType);
256 }
257
258 bool RenderBoxModelObject::hasAcceleratedCompositing() const
259 {
260     return view()->compositor()->hasAcceleratedCompositing();
261 }
262
263 bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
264 {
265     ASSERT(hasLayer());
266     ASSERT(isComposited());
267     return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
268 }
269
270 void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
271 {
272     ASSERT(hasLayer());
273     ASSERT(isComposited());
274     layer()->backing()->transitionPaused(timeOffset, propertyId);
275 }
276
277 void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
278 {
279     ASSERT(hasLayer());
280     ASSERT(isComposited());
281     layer()->backing()->transitionFinished(propertyId);
282 }
283
284 bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes)
285 {
286     ASSERT(hasLayer());
287     ASSERT(isComposited());
288     return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
289 }
290
291 void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
292 {
293     ASSERT(hasLayer());
294     ASSERT(isComposited());
295     layer()->backing()->animationPaused(timeOffset, name);
296 }
297
298 void RenderBoxModelObject::animationFinished(const String& name)
299 {
300     ASSERT(hasLayer());
301     ASSERT(isComposited());
302     layer()->backing()->animationFinished(name);
303 }
304
305 void RenderBoxModelObject::suspendAnimations(double time)
306 {
307     ASSERT(hasLayer());
308     ASSERT(isComposited());
309     layer()->backing()->suspendAnimations(time);
310 }
311 #endif
312
313 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
314 {
315     return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
316 }
317
318 RenderBoxModelObject::RenderBoxModelObject(Node* node)
319     : RenderObject(node)
320     , m_layer(0)
321 {
322 }
323
324 RenderBoxModelObject::~RenderBoxModelObject()
325 {
326     // Our layer should have been destroyed and cleared by now
327     ASSERT(!hasLayer());
328     ASSERT(!m_layer);
329     if (gImageQualityController) {
330         gImageQualityController->objectDestroyed(this);
331         if (gImageQualityController->isEmpty()) {
332             delete gImageQualityController;
333             gImageQualityController = 0;
334         }
335     }
336 }
337
338 void RenderBoxModelObject::destroyLayer()
339 {
340     ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
341     ASSERT(m_layer);
342     m_layer->destroy(renderArena());
343     m_layer = 0;
344 }
345
346 void RenderBoxModelObject::willBeDestroyed()
347 {
348     // This must be done before we destroy the RenderObject.
349     if (m_layer)
350         m_layer->clearClipRects();
351
352     // A continuation of this RenderObject should be destroyed at subclasses.
353     ASSERT(!continuation());
354
355     // If this is a first-letter object with a remaining text fragment then the
356     // entry needs to be cleared from the map.
357     if (firstLetterRemainingText())
358         setFirstLetterRemainingText(0);
359
360     // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
361     RenderObject::willBeDestroyed();
362 }
363
364 bool RenderBoxModelObject::hasSelfPaintingLayer() const
365 {
366     return m_layer && m_layer->isSelfPaintingLayer();
367 }
368
369 void RenderBoxModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
370 {
371     s_wasFloating = isFloating();
372     s_hadLayer = hasLayer();
373     s_hadTransform = hasTransform();
374     if (s_hadLayer)
375         s_layerWasSelfPainting = layer()->isSelfPaintingLayer();
376
377     // If our z-index changes value or our visibility changes,
378     // we need to dirty our stacking context's z-order list.
379     RenderStyle* oldStyle = style();
380     if (oldStyle && newStyle) {
381         if (parent()) {
382             // Do a repaint with the old style first, e.g., for example if we go from
383             // having an outline to not having an outline.
384             if (diff == StyleDifferenceRepaintLayer) {
385                 layer()->repaintIncludingDescendants();
386                 if (!(oldStyle->clip() == newStyle->clip()))
387                     layer()->clearClipRectsIncludingDescendants();
388             } else if (diff == StyleDifferenceRepaint || newStyle->outlineSize() < oldStyle->outlineSize())
389                 repaint();
390         }
391         
392         if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
393             // When a layout hint happens, we go ahead and do a repaint of the layer, since the layer could
394             // end up being destroyed.
395             if (hasLayer()) {
396                 if (oldStyle->position() != newStyle->position()
397                     || oldStyle->zIndex() != newStyle->zIndex()
398                     || oldStyle->hasAutoZIndex() != newStyle->hasAutoZIndex()
399                     || !(oldStyle->clip() == newStyle->clip())
400                     || oldStyle->hasClip() != newStyle->hasClip()
401                     || oldStyle->opacity() != newStyle->opacity()
402                     || oldStyle->transform() != newStyle->transform()
403 #if ENABLE(CSS_FILTERS)
404                     || oldStyle->filter() != newStyle->filter()
405 #endif
406                     )
407                 layer()->repaintIncludingDescendants();
408             } else if (newStyle->hasTransform() || newStyle->opacity() < 1 || newStyle->hasFilter()) {
409                 // If we don't have a layer yet, but we are going to get one because of transform or opacity,
410                 //  then we need to repaint the old position of the object.
411                 repaint();
412             }
413         }
414
415         if (hasLayer()
416             && (oldStyle->hasAutoZIndex() != newStyle->hasAutoZIndex()
417                 || oldStyle->zIndex() != newStyle->zIndex()
418                 || oldStyle->visibility() != newStyle->visibility())) {
419             layer()->dirtyStackingContextZOrderLists();
420             if (oldStyle->hasAutoZIndex() != newStyle->hasAutoZIndex() || oldStyle->visibility() != newStyle->visibility())
421                 layer()->dirtyZOrderLists();
422         }
423     }
424
425     RenderObject::styleWillChange(diff, newStyle);
426 }
427
428 void RenderBoxModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
429 {
430     RenderObject::styleDidChange(diff, oldStyle);
431     updateBoxModelInfoFromStyle();
432     
433     if (requiresLayer()) {
434         if (!layer() && layerCreationAllowedForSubtree()) {
435             if (s_wasFloating && isFloating())
436                 setChildNeedsLayout(true);
437             m_layer = new (renderArena()) RenderLayer(this);
438             setHasLayer(true);
439             m_layer->insertOnlyThisLayer();
440             if (parent() && !needsLayout() && containingBlock()) {
441                 m_layer->setRepaintStatus(NeedsFullRepaint);
442                 // There is only one layer to update, it is not worth using |cachedOffset| since
443                 // we are not sure the value will be used.
444                 m_layer->updateLayerPositions(0);
445             }
446         }
447     } else if (layer() && layer()->parent()) {
448         setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
449         setHasReflection(false);
450         m_layer->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
451         if (s_wasFloating && isFloating())
452             setChildNeedsLayout(true);
453         if (s_hadTransform)
454             setNeedsLayoutAndPrefWidthsRecalc();
455     }
456
457     if (layer()) {
458         layer()->styleChanged(diff, oldStyle);
459         if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
460             setChildNeedsLayout(true);
461     }
462 }
463
464 void RenderBoxModelObject::updateBoxModelInfoFromStyle()
465 {
466     // Set the appropriate bits for a box model object.  Since all bits are cleared in styleWillChange,
467     // we only check for bits that could possibly be set to true.
468     RenderStyle* styleToUse = style();
469     setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
470     setInline(styleToUse->isDisplayInlineType());
471     setRelPositioned(styleToUse->position() == RelativePosition);
472     setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
473 }
474
475 enum RelPosAxis { RelPosX, RelPosY };
476
477 static LayoutUnit accumulateRelativePositionOffsets(const RenderObject* child, RelPosAxis axis)
478 {
479     if (!child->isAnonymousBlock() || !child->isRelPositioned())
480         return 0;
481     LayoutUnit offset = ZERO_LAYOUT_UNIT;
482     RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
483     while (p && p->isRenderInline()) {
484         if (p->isRelPositioned())
485             offset += (axis == RelPosX) ? toRenderInline(p)->relativePositionOffsetX() : toRenderInline(p)->relativePositionOffsetY();
486         p = p->parent();
487     }
488     return offset;
489 }
490
491 LayoutUnit RenderBoxModelObject::relativePositionOffsetX() const
492 {
493     LayoutUnit offset = accumulateRelativePositionOffsets(this, RelPosX);
494
495     // Objects that shrink to avoid floats normally use available line width when computing containing block width.  However
496     // in the case of relative positioning using percentages, we can't do this.  The offset should always be resolved using the
497     // available width of the containing block.  Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
498     // call availableWidth on our containing block.
499     if (!style()->left().isAuto()) {
500         RenderBlock* cb = containingBlock();
501         if (!style()->right().isAuto() && !cb->style()->isLeftToRightDirection())
502             return -valueForLength(style()->right(), cb->availableWidth(), view());
503         return offset + valueForLength(style()->left(), cb->availableWidth(), view());
504     }
505     if (!style()->right().isAuto()) {
506         RenderBlock* cb = containingBlock();
507         return offset + -valueForLength(style()->right(), cb->availableWidth(), view());
508     }
509     return offset;
510 }
511
512 LayoutUnit RenderBoxModelObject::relativePositionOffsetY() const
513 {
514     LayoutUnit offset = accumulateRelativePositionOffsets(this, RelPosY);
515     
516     RenderBlock* containingBlock = this->containingBlock();
517     // If the containing block of a relatively positioned element does not
518     // specify a height, a percentage top or bottom offset should be resolved as
519     // auto. An exception to this is if the containing block has the WinIE quirk
520     // where <html> and <body> assume the size of the viewport. In this case,
521     // calculate the percent offset based on this height.
522     // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
523     if (!style()->top().isAuto()
524         && (!containingBlock->style()->height().isAuto()
525             || !style()->top().isPercent()
526             || containingBlock->stretchesToViewport()))
527         return offset + valueForLength(style()->top(), containingBlock->availableHeight(), view());
528
529     if (!style()->bottom().isAuto()
530         && (!containingBlock->style()->height().isAuto()
531             || !style()->bottom().isPercent()
532             || containingBlock->stretchesToViewport()))
533         return offset + -valueForLength(style()->bottom(), containingBlock->availableHeight(), view());
534
535     return offset;
536 }
537
538 LayoutPoint RenderBoxModelObject::offsetTopLeft(const LayoutPoint& startPoint) const
539 {
540     // If the element is the HTML body element or does not have an associated box
541     // return 0 and stop this algorithm.
542     if (isBody())
543         return LayoutPoint();
544     
545     LayoutPoint referencePoint = startPoint;
546     referencePoint.move(parent()->offsetForColumns(referencePoint));
547     
548     // If the offsetParent of the element is null, or is the HTML body element,
549     // return the distance between the canvas origin and the left border edge 
550     // of the element and stop this algorithm.
551     if (const RenderBoxModelObject* offsetParent = this->offsetParent()) {
552         if (offsetParent->isBox() && !offsetParent->isBody())
553             referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop());
554         if (!isPositioned()) {
555             if (isRelPositioned())
556                 referencePoint.move(relativePositionOffset());
557             const RenderObject* curr = parent();
558             while (curr != offsetParent) {
559                 // FIXME: What are we supposed to do inside SVG content?
560                 if (curr->isBox() && !curr->isTableRow())
561                     referencePoint.moveBy(toRenderBox(curr)->topLeftLocation());
562                 referencePoint.move(curr->parent()->offsetForColumns(referencePoint));
563                 curr = curr->parent();
564             }
565             if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isRelPositioned() && !offsetParent->isPositioned())
566                 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
567         }
568     }
569
570     return referencePoint;
571 }
572
573 LayoutUnit RenderBoxModelObject::offsetLeft() const
574 {
575     // Note that RenderInline and RenderBox override this to pass a different
576     // startPoint to offsetTopLeft.
577     return offsetTopLeft(LayoutPoint()).x();
578 }
579
580 LayoutUnit RenderBoxModelObject::offsetTop() const
581 {
582     // Note that RenderInline and RenderBox override this to pass a different
583     // startPoint to offsetTopLeft.
584     return offsetTopLeft(LayoutPoint()).y();
585 }
586
587 int RenderBoxModelObject::pixelSnappedOffsetWidth() const
588 {
589     return snapSizeToPixel(offsetWidth(), offsetLeft());
590 }
591
592 int RenderBoxModelObject::pixelSnappedOffsetHeight() const
593 {
594     return snapSizeToPixel(offsetHeight(), offsetTop());
595 }
596
597 LayoutUnit RenderBoxModelObject::computedCSSPaddingTop() const
598 {
599     LayoutUnit w = ZERO_LAYOUT_UNIT;
600     RenderView* renderView = 0;
601     Length padding = style()->paddingTop();
602     if (padding.isPercent())
603         w = containingBlock()->availableLogicalWidth();
604     else if (padding.isViewportPercentage())
605         renderView = view();
606     return minimumValueForLength(padding, w, renderView);
607 }
608
609 LayoutUnit RenderBoxModelObject::computedCSSPaddingBottom() const
610 {
611     LayoutUnit w = ZERO_LAYOUT_UNIT;
612     RenderView* renderView = 0;
613     Length padding = style()->paddingBottom();
614     if (padding.isPercent())
615         w = containingBlock()->availableLogicalWidth();
616     else if (padding.isViewportPercentage())
617         renderView = view();
618     return minimumValueForLength(padding, w, renderView);
619 }
620
621 LayoutUnit RenderBoxModelObject::computedCSSPaddingLeft() const
622 {
623     LayoutUnit w = ZERO_LAYOUT_UNIT;
624     RenderView* renderView = 0;
625     Length padding = style()->paddingLeft();
626     if (padding.isPercent())
627         w = containingBlock()->availableLogicalWidth();
628     else if (padding.isViewportPercentage())
629         renderView = view();
630     return minimumValueForLength(padding, w, renderView);
631 }
632
633 LayoutUnit RenderBoxModelObject::computedCSSPaddingRight() const
634 {
635     LayoutUnit w = ZERO_LAYOUT_UNIT;
636     RenderView* renderView = 0;
637     Length padding = style()->paddingRight();
638     if (padding.isPercent())
639         w = containingBlock()->availableLogicalWidth();
640     else if (padding.isViewportPercentage())
641         renderView = view();
642     return minimumValueForLength(padding, w, renderView);
643 }
644
645 LayoutUnit RenderBoxModelObject::computedCSSPaddingBefore() const
646 {
647     LayoutUnit w = ZERO_LAYOUT_UNIT;
648     RenderView* renderView = 0;
649     Length padding = style()->paddingBefore();
650     if (padding.isPercent())
651         w = containingBlock()->availableLogicalWidth();
652     else if (padding.isViewportPercentage())
653         renderView = view();
654     return minimumValueForLength(padding, w, renderView);
655 }
656
657 LayoutUnit RenderBoxModelObject::computedCSSPaddingAfter() const
658 {
659     LayoutUnit w = ZERO_LAYOUT_UNIT;
660     RenderView* renderView = 0;
661     Length padding = style()->paddingAfter();
662     if (padding.isPercent())
663         w = containingBlock()->availableLogicalWidth();
664     else if (padding.isViewportPercentage())
665         renderView = view();
666     return minimumValueForLength(padding, w, renderView);
667 }
668
669 LayoutUnit RenderBoxModelObject::computedCSSPaddingStart() const
670 {
671     LayoutUnit w = ZERO_LAYOUT_UNIT;
672     RenderView* renderView = 0;
673     Length padding = style()->paddingStart();
674     if (padding.isPercent())
675         w = containingBlock()->availableLogicalWidth();
676     else if (padding.isViewportPercentage())
677         renderView = view();
678     return minimumValueForLength(padding, w, renderView);
679 }
680
681 LayoutUnit RenderBoxModelObject::computedCSSPaddingEnd() const
682 {
683     LayoutUnit w = ZERO_LAYOUT_UNIT;
684     RenderView* renderView = 0;
685     Length padding = style()->paddingEnd();
686     if (padding.isPercent())
687         w = containingBlock()->availableLogicalWidth();
688     else if (padding.isViewportPercentage())
689         renderView = view();
690     return minimumValueForLength(padding, w, renderView);
691 }
692
693 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
694     bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
695 {
696     RenderView* renderView = view();
697     RoundedRect border = style()->getRoundedBorderFor(borderRect, renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
698     if (box && (box->nextLineBox() || box->prevLineBox())) {
699         RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
700         border.setRadii(segmentBorder.radii());
701     }
702
703     return border;
704 }
705
706 static LayoutRect backgroundRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance)
707 {
708     if (bleedAvoidance != BackgroundBleedShrinkBackground)
709         return borderRect;
710
711     // We shrink the rectangle by one pixel on each side because the bleed is one pixel maximum.
712     AffineTransform transform = context->getCTM();
713     LayoutRect adjustedRect = borderRect;
714     adjustedRect.inflateX(-static_cast<LayoutUnit>(ceil(1 / transform.xScale())));
715     adjustedRect.inflateY(-static_cast<LayoutUnit>(ceil(1 / transform.yScale())));
716     return adjustedRect;
717 }
718
719 static void applyBoxShadowForBackground(GraphicsContext* context, RenderStyle* style)
720 {
721     const ShadowData* boxShadow = style->boxShadow();
722     while (boxShadow->style() != Normal)
723         boxShadow = boxShadow->next();
724
725     FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
726     if (!boxShadow->isWebkitBoxShadow())
727         context->setShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), style->colorSpace());
728     else
729         context->setLegacyShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), style->colorSpace());
730 }
731
732 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
733     BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
734 {
735     GraphicsContext* context = paintInfo.context;
736     if (context->paintingDisabled() || rect.isEmpty())
737         return;
738
739     bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
740     bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
741
742     bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
743     bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
744     bool isBorderFill = bgLayer->clip() == BorderFillBox;
745     bool isRoot = this->isRoot();
746
747     Color bgColor = color;
748     StyleImage* bgImage = bgLayer->image();
749     bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style()->effectiveZoom());
750     
751     bool forceBackgroundToWhite = false;
752     if (document()->printing()) {
753         if (style()->printColorAdjust() == PrintColorAdjustEconomy)
754             forceBackgroundToWhite = true;
755         if (document()->settings() && document()->settings()->shouldPrintBackgrounds())
756             forceBackgroundToWhite = false;
757     }
758
759     // When printing backgrounds is disabled or using economy mode,
760     // change existing background colors and images to a solid white background.
761     // If there's no bg color or image, leave it untouched to avoid affecting transparency.
762     // We don't try to avoid loading the background images, because this style flag is only set
763     // when printing, and at that point we've already loaded the background images anyway. (To avoid
764     // loading the background images we'd have to do this check when applying styles rather than
765     // while rendering.)
766     if (forceBackgroundToWhite) {
767         // Note that we can't reuse this variable below because the bgColor might be changed
768         bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha() > 0;
769         if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
770             bgColor = Color::white;
771             shouldPaintBackgroundImage = false;
772         }
773     }
774
775     bool colorVisible = bgColor.isValid() && bgColor.alpha() > 0;
776     
777     // Fast path for drawing simple color backgrounds.
778     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
779         if (!colorVisible)
780             return;
781
782         bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
783         GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
784         if (boxShadowShouldBeAppliedToBackground)
785             applyBoxShadowForBackground(context, style());
786
787         if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
788             RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
789             context->fillRoundedRect(border, bgColor, style()->colorSpace());
790         } else
791             context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
792         
793         return;
794     }
795
796     bool clipToBorderRadius = hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer;
797     GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
798     if (clipToBorderRadius) {
799         RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
800         context->addRoundedRectClip(border);
801     }
802     
803     int bLeft = includeLeftEdge ? borderLeft() : 0;
804     int bRight = includeRightEdge ? borderRight() : 0;
805     LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : ZERO_LAYOUT_UNIT;
806     LayoutUnit pRight = includeRightEdge ? paddingRight() : ZERO_LAYOUT_UNIT;
807
808     GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
809     LayoutRect scrolledPaintRect = rect;
810     if (clippedWithLocalScrolling) {
811         // Clip to the overflow area.
812         RenderBox* thisBox = toRenderBox(this);
813         context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
814         
815         // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
816         IntSize offset = thisBox->scrolledContentOffset();
817         scrolledPaintRect.move(-offset);
818         scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
819         scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
820     }
821     
822     GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
823     OwnPtr<ImageBuffer> maskImage;
824     IntRect maskRect;
825
826     if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
827         // Clip to the padding or content boxes as necessary.
828         bool includePadding = bgLayer->clip() == ContentFillBox;
829         LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : ZERO_LAYOUT_UNIT),
830                                    scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : ZERO_LAYOUT_UNIT),
831                                    scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : ZERO_LAYOUT_UNIT),
832                                    scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : ZERO_LAYOUT_UNIT));
833         backgroundClipStateSaver.save();
834         context->clip(clipRect);
835     } else if (bgLayer->clip() == TextFillBox) {
836         // We have to draw our text into a mask that can then be used to clip background drawing.
837         // First figure out how big the mask has to be.  It should be no bigger than what we need
838         // to actually render, so we should intersect the dirty rect with the border box of the background.
839         maskRect = pixelSnappedIntRect(rect);
840         maskRect.intersect(paintInfo.rect);
841
842         // Now create the mask.
843         maskImage = context->createCompatibleBuffer(maskRect.size());
844         if (!maskImage)
845             return;
846
847         GraphicsContext* maskImageContext = maskImage->context();
848         maskImageContext->translate(-maskRect.x(), -maskRect.y());
849
850         // Now add the text to the clip.  We do this by painting using a special paint phase that signals to
851         // InlineTextBoxes that they should just add their contents to the clip.
852         PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, true, 0, paintInfo.renderRegion, 0);
853         if (box) {
854             RootInlineBox* root = box->root();
855             box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
856         } else {
857             LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
858             paint(info, scrolledPaintRect.location() - localOffset);
859         }
860
861         // The mask has been created.  Now we just need to clip to it.
862         backgroundClipStateSaver.save();
863         context->clip(maskRect);
864         context->beginTransparencyLayer(1);
865     }
866
867     // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
868     // no background in the child document should show the parent's background.
869     bool isOpaqueRoot = false;
870     if (isRoot) {
871         isOpaqueRoot = true;
872         if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
873             Element* ownerElement = document()->ownerElement();
874             if (ownerElement) {
875                 if (!ownerElement->hasTagName(frameTag)) {
876                     // Locate the <body> element using the DOM.  This is easier than trying
877                     // to crawl around a render tree with potential :before/:after content and
878                     // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
879                     // render object very easily via the DOM.
880                     HTMLElement* body = document()->body();
881                     if (body) {
882                         // Can't scroll a frameset document anyway.
883                         isOpaqueRoot = body->hasLocalName(framesetTag);
884                     }
885 #if ENABLE(SVG)
886                     else {
887                         // SVG documents and XML documents with SVG root nodes are transparent.
888                         isOpaqueRoot = !document()->hasSVGRootNode();
889                     }
890 #endif
891                 }
892             } else
893                 isOpaqueRoot = !view()->frameView()->isTransparent();
894         }
895         view()->frameView()->setContentIsOpaque(isOpaqueRoot);
896     }
897
898     // Paint the color first underneath all images.
899     if (!bgLayer->next()) {
900         IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect));
901         bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
902         if (!boxShadowShouldBeAppliedToBackground)
903             backgroundRect.intersect(paintInfo.rect);
904
905         // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
906         Color baseColor;
907         bool shouldClearBackground = false;
908         if (isOpaqueRoot) {
909             baseColor = view()->frameView()->baseBackgroundColor();
910             if (!baseColor.alpha())
911                 shouldClearBackground = true;
912         }
913
914         GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
915         if (boxShadowShouldBeAppliedToBackground)
916             applyBoxShadowForBackground(context, style());
917
918         if (baseColor.alpha()) {
919             if (bgColor.alpha())
920                 baseColor = baseColor.blend(bgColor);
921
922             context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
923         } else if (bgColor.alpha()) {
924             CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
925             context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
926         } else if (shouldClearBackground)
927             context->clearRect(backgroundRect);
928     }
929
930     // no progressive loading of the background image
931     if (shouldPaintBackgroundImage) {
932         BackgroundImageGeometry geometry;
933         calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry);
934         geometry.clip(paintInfo.rect);
935         if (!geometry.destRect().isEmpty()) {
936             CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
937             RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
938             RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
939             bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
940             context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(), 
941                 compositeOp, useLowQualityScaling);
942         }
943     }
944
945     if (bgLayer->clip() == TextFillBox) {
946         context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn);
947         context->endTransparencyLayer();
948     }
949 }
950
951 static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
952 {
953     return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
954 }
955
956 static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
957 {
958     return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
959 }
960
961 static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
962 {
963     if (intrinsicRatio.isEmpty()) {
964         if (useWidth)
965             return IntSize(useWidth, size.height());
966         return IntSize(size.width(), useHeight);
967     }
968
969     if (useWidth)
970         return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
971     return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
972 }
973
974 static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& intrinsicRatio)
975 {
976     // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
977     // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
978
979     int solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
980     int solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
981     if (solutionWidth <= size.width()) {
982         if (solutionHeight <= size.height()) {
983             // If both solutions fit, choose the one covering the larger area.
984             int areaOne = solutionWidth * size.height();
985             int areaTwo = size.width() * solutionHeight;
986             if (areaOne < areaTwo)
987                 return IntSize(size.width(), solutionHeight);
988             return IntSize(solutionWidth, size.height());
989         }
990
991         // Only the first solution fits.
992         return IntSize(solutionWidth, size.height());
993     }
994
995     // Only the second solution fits, assert that.
996     ASSERT(solutionHeight <= size.height());
997     return IntSize(size.width(), solutionHeight);
998 }
999
1000 IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize) const
1001 {
1002     // A generated image without a fixed size, will always return the container size as intrinsic size.
1003     if (image->isGeneratedImage() && image->usesImageContainerSize())
1004         return IntSize(positioningAreaSize.width(), positioningAreaSize.height());
1005
1006     Length intrinsicWidth;
1007     Length intrinsicHeight;
1008     FloatSize intrinsicRatio;
1009     image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
1010
1011     // Intrinsic dimensions expressed as percentages must be resolved relative to the dimensions of the rectangle
1012     // that establishes the coordinate system for the 'background-position' property. 
1013     
1014     // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
1015     if (intrinsicWidth.isPercent() && intrinsicHeight.isPercent() && intrinsicRatio.isEmpty()) {
1016         // Resolve width/height percentages against positioningAreaSize, only if no intrinsic ratio is provided.
1017         int resolvedWidth = static_cast<int>(round(positioningAreaSize.width() * intrinsicWidth.percent() / 100));
1018         int resolvedHeight = static_cast<int>(round(positioningAreaSize.height() * intrinsicHeight.percent() / 100));
1019         return IntSize(resolvedWidth, resolvedHeight);
1020     }
1021
1022     IntSize resolvedSize(intrinsicWidth.isFixed() ? intrinsicWidth.value() : 0, intrinsicHeight.isFixed() ? intrinsicHeight.value() : 0);
1023     IntSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
1024     resolvedSize.scale(style()->effectiveZoom());
1025     resolvedSize.clampToMinimumSize(minimumSize);
1026
1027     if (!resolvedSize.isEmpty())
1028         return resolvedSize;
1029
1030     // If the image has one of either an intrinsic width or an intrinsic height:
1031     // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
1032     // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
1033     //   establishes the coordinate system for the 'background-position' property.
1034     if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
1035         return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, intrinsicRatio, resolvedSize.width(), resolvedSize.height());
1036
1037     // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
1038     // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
1039     // establishes the coordinate system for the 'background-position' property.
1040     if (!intrinsicRatio.isEmpty())
1041         return resolveAgainstIntrinsicRatio(positioningAreaSize, intrinsicRatio);
1042
1043     // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
1044     // establishes the coordinate system for the 'background-position' property.
1045     return positioningAreaSize;
1046 }
1047
1048 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, const IntSize& positioningAreaSize) const
1049 {
1050     StyleImage* image = fillLayer->image();
1051     EFillSizeType type = fillLayer->size().type;
1052
1053     IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize);
1054     imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
1055     RenderView* renderView = view();
1056     switch (type) {
1057         case SizeLength: {
1058             int w = positioningAreaSize.width();
1059             int h = positioningAreaSize.height();
1060
1061             Length layerWidth = fillLayer->size().size.width();
1062             Length layerHeight = fillLayer->size().size.height();
1063
1064             if (layerWidth.isFixed())
1065                 w = layerWidth.value();
1066             else if (layerWidth.isPercent() || layerHeight.isViewportPercentage())
1067                 w = valueForLength(layerWidth, positioningAreaSize.width(), renderView);
1068             
1069             if (layerHeight.isFixed())
1070                 h = layerHeight.value();
1071             else if (layerHeight.isPercent() || layerHeight.isViewportPercentage())
1072                 h = valueForLength(layerHeight, positioningAreaSize.height(), renderView);
1073             
1074             // If one of the values is auto we have to use the appropriate
1075             // scale to maintain our aspect ratio.
1076             if (layerWidth.isAuto() && !layerHeight.isAuto()) {
1077                 if (imageIntrinsicSize.height())
1078                     w = imageIntrinsicSize.width() * h / imageIntrinsicSize.height();        
1079             } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
1080                 if (imageIntrinsicSize.width())
1081                     h = imageIntrinsicSize.height() * w / imageIntrinsicSize.width();
1082             } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
1083                 // If both width and height are auto, use the image's intrinsic size.
1084                 w = imageIntrinsicSize.width();
1085                 h = imageIntrinsicSize.height();
1086             }
1087             
1088             return IntSize(max(1, w), max(1, h));
1089         }
1090         case SizeNone: {
1091             // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1092             if (!imageIntrinsicSize.isEmpty())
1093                 return imageIntrinsicSize;
1094
1095             // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
1096             type = Contain;
1097         }
1098         case Contain:
1099         case Cover: {
1100             float horizontalScaleFactor = imageIntrinsicSize.width()
1101                 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
1102             float verticalScaleFactor = imageIntrinsicSize.height()
1103                 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
1104             float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
1105             return IntSize(max(1, static_cast<int>(imageIntrinsicSize.width() * scaleFactor)), max(1, static_cast<int>(imageIntrinsicSize.height() * scaleFactor)));
1106        }
1107     }
1108
1109     ASSERT_NOT_REACHED();
1110     return IntSize();
1111 }
1112
1113 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
1114 {
1115     m_destRect.move(max(xOffset, 0), 0);
1116     m_phase.setX(-min(xOffset, 0));
1117     m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
1118 }
1119 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
1120 {
1121     m_destRect.move(0, max(yOffset, 0));
1122     m_phase.setY(-min(yOffset, 0));
1123     m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
1124 }
1125
1126 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const IntPoint& attachmentPoint)
1127 {
1128     IntPoint alignedPoint = attachmentPoint;
1129     m_phase.move(max(alignedPoint.x() - m_destRect.x(), 0), max(alignedPoint.y() - m_destRect.y(), 0));
1130 }
1131
1132 void RenderBoxModelObject::BackgroundImageGeometry::clip(const IntRect& clipRect)
1133 {
1134     m_destRect.intersect(clipRect);
1135 }
1136
1137 IntPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
1138 {
1139     IntPoint phase = m_phase;
1140     phase += m_destRect.location() - m_destOrigin;
1141     return phase;
1142 }
1143
1144 void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const LayoutRect& paintRect, 
1145                                                             BackgroundImageGeometry& geometry)
1146 {
1147     LayoutUnit left = 0;
1148     LayoutUnit top = 0;
1149     IntSize positioningAreaSize;
1150     IntRect snappedPaintRect = pixelSnappedIntRect(paintRect);
1151
1152     // Determine the background positioning area and set destRect to the background painting area.
1153     // destRect will be adjusted later if the background is non-repeating.
1154     bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
1155
1156 #if ENABLE(FAST_MOBILE_SCROLLING)
1157     if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
1158         // As a side effect of an optimization to blit on scroll, we do not honor the CSS
1159         // property "background-attachment: fixed" because it may result in rendering
1160         // artifacts. Note, these artifacts only appear if we are blitting on scroll of
1161         // a page that has fixed background images.
1162         fixedAttachment = false;
1163     }
1164 #endif
1165
1166     if (!fixedAttachment) {
1167         geometry.setDestRect(snappedPaintRect);
1168
1169         LayoutUnit right = 0;
1170         LayoutUnit bottom = 0;
1171         // Scroll and Local.
1172         if (fillLayer->origin() != BorderFillBox) {
1173             left = borderLeft();
1174             right = borderRight();
1175             top = borderTop();
1176             bottom = borderBottom();
1177             if (fillLayer->origin() == ContentFillBox) {
1178                 left += paddingLeft();
1179                 right += paddingRight();
1180                 top += paddingTop();
1181                 bottom += paddingBottom();
1182             }
1183         }
1184
1185         // The background of the box generated by the root element covers the entire canvas including
1186         // its margins. Since those were added in already, we have to factor them out when computing
1187         // the background positioning area.
1188         if (isRoot()) {
1189             positioningAreaSize = IntSize(snapSizeToPixel(toRenderBox(this)->width() - left - right, toRenderBox(this)->x()),
1190                                           snapSizeToPixel(toRenderBox(this)->height() - top - bottom, toRenderBox(this)->y()));
1191             left += marginLeft();
1192             top += marginTop();
1193         } else
1194             positioningAreaSize = IntSize(snapSizeToPixel(paintRect.width() - left - right, paintRect.x()),
1195                                           snapSizeToPixel(paintRect.height() - top - bottom, paintRect.y()));
1196     } else {
1197         geometry.setDestRect(pixelSnappedIntRect(viewRect()));
1198         positioningAreaSize = geometry.destRect().size();
1199     }
1200
1201     IntSize fillTileSize = calculateFillTileSize(fillLayer, positioningAreaSize);
1202     fillLayer->image()->setContainerSizeForRenderer(this, fillTileSize, style()->effectiveZoom());
1203     geometry.setTileSize(fillTileSize);
1204
1205     EFillRepeat backgroundRepeatX = fillLayer->repeatX();
1206     EFillRepeat backgroundRepeatY = fillLayer->repeatY();
1207     RenderView* renderView = view();
1208
1209     LayoutUnit xPosition = minimumValueForLength(fillLayer->xPosition(), positioningAreaSize.width() - geometry.tileSize().width(), renderView, true);
1210     if (backgroundRepeatX == RepeatFill)
1211         geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(xPosition + left) % geometry.tileSize().width() : 0);
1212     else
1213         geometry.setNoRepeatX(xPosition + left);
1214
1215     LayoutUnit yPosition = minimumValueForLength(fillLayer->yPosition(), positioningAreaSize.height() - geometry.tileSize().height(), renderView, true);
1216     if (backgroundRepeatY == RepeatFill)
1217         geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(yPosition + top) % geometry.tileSize().height() : 0);
1218     else 
1219         geometry.setNoRepeatY(yPosition + top);
1220
1221     if (fixedAttachment)
1222         geometry.useFixedAttachment(snappedPaintRect.location());
1223
1224     geometry.clip(snappedPaintRect);
1225     geometry.setDestOrigin(geometry.destRect().location());
1226 }
1227
1228 static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
1229 {
1230     if (borderSlice.isRelative())
1231         return borderSlice.value() * borderSide;
1232     if (borderSlice.isAuto())
1233         return imageSide;
1234     return valueForLength(borderSlice, boxExtent, renderView);
1235 }
1236
1237 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
1238                                                const NinePieceImage& ninePieceImage, CompositeOperator op)
1239 {
1240     StyleImage* styleImage = ninePieceImage.image();
1241     if (!styleImage)
1242         return false;
1243
1244     if (!styleImage->isLoaded())
1245         return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1246
1247     if (!styleImage->canRender(this, style->effectiveZoom()))
1248         return false;
1249
1250     // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
1251     // doesn't have any understanding of the zoom that is in effect on the tile.
1252     LayoutUnit topOutset;
1253     LayoutUnit rightOutset;
1254     LayoutUnit bottomOutset;
1255     LayoutUnit leftOutset;
1256     style->getImageOutsets(ninePieceImage, topOutset, rightOutset, bottomOutset, leftOutset);
1257
1258     LayoutUnit topWithOutset = rect.y() - topOutset;
1259     LayoutUnit bottomWithOutset = rect.maxY() + bottomOutset;
1260     LayoutUnit leftWithOutset = rect.x() - leftOutset;
1261     LayoutUnit rightWithOutset = rect.maxX() + rightOutset;
1262     IntRect borderImageRect = pixelSnappedIntRect(leftWithOutset, topWithOutset, rightWithOutset - leftWithOutset, bottomWithOutset - topWithOutset);
1263
1264     IntSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size());
1265
1266     // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1267     styleImage->setContainerSizeForRenderer(this, imageSize, style->effectiveZoom());
1268
1269     int imageWidth = imageSize.width() / style->effectiveZoom();
1270     int imageHeight = imageSize.height() / style->effectiveZoom();
1271     RenderView* renderView = view();
1272
1273     float imageScaleFactor = styleImage->imageScaleFactor();
1274     int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight, renderView)) * imageScaleFactor;
1275     int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth, renderView)) * imageScaleFactor;
1276     int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight, renderView)) * imageScaleFactor;
1277     int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth, renderView)) * imageScaleFactor;
1278
1279     ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1280     ENinePieceImageRule vRule = ninePieceImage.verticalRule();
1281
1282     LayoutUnit topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height(), renderView);
1283     LayoutUnit rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
1284     LayoutUnit bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
1285     LayoutUnit leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
1286     
1287     // Reduce the widths if they're too large.
1288     // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
1289     // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
1290     // multiplying them by f.
1291     LayoutUnit borderSideWidth = max<LayoutUnit>(1, leftWidth + rightWidth);
1292     LayoutUnit borderSideHeight = max<LayoutUnit>(1, topWidth + bottomWidth);
1293     float borderSideScaleFactor = min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight);
1294     if (borderSideScaleFactor < 1) {
1295         topWidth *= borderSideScaleFactor;
1296         rightWidth *= borderSideScaleFactor;
1297         bottomWidth *= borderSideScaleFactor;
1298         leftWidth *= borderSideScaleFactor;
1299     }
1300
1301     bool drawLeft = leftSlice > 0 && leftWidth > 0;
1302     bool drawTop = topSlice > 0 && topWidth > 0;
1303     bool drawRight = rightSlice > 0 && rightWidth > 0;
1304     bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
1305     bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0
1306                       && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
1307
1308     RefPtr<Image> image = styleImage->image(this, imageSize);
1309     ColorSpace colorSpace = style->colorSpace();
1310     
1311     float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1312     float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1313     
1314     float sourceWidth = imageWidth - leftSlice - rightSlice;
1315     float sourceHeight = imageHeight - topSlice - bottomSlice;
1316     
1317     float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
1318     float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
1319     float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
1320     float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
1321     
1322     if (drawLeft) {
1323         // Paint the top and bottom left corners.
1324
1325         // The top left corner rect is (tx, ty, leftWidth, topWidth)
1326         // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
1327         if (drawTop)
1328             graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.location(), LayoutSize(leftWidth, topWidth)),
1329                                        LayoutRect(0, 0, leftSlice, topSlice), op);
1330
1331         // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1332         // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1333         if (drawBottom)
1334             graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1335                                        LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
1336
1337         // Paint the left edge.
1338         // Have to scale and tile into the border rect.
1339         if (sourceHeight > 0)
1340             graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
1341                                             destinationHeight),
1342                                             IntRect(0, topSlice, leftSlice, sourceHeight),
1343                                             FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
1344     }
1345
1346     if (drawRight) {
1347         // Paint the top and bottom right corners
1348         // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1349         // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1350         if (drawTop)
1351             graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1352                                        LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
1353
1354         // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1355         // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1356         if (drawBottom)
1357             graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1358                                        LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1359
1360         // Paint the right edge.
1361         if (sourceHeight > 0)
1362             graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1363                                             destinationHeight),
1364                                             IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1365                                             FloatSize(rightSideScale, rightSideScale),
1366                                             Image::StretchTile, (Image::TileRule)vRule, op);
1367     }
1368
1369     // Paint the top edge.
1370     if (drawTop && sourceWidth > 0)
1371         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
1372                                         IntRect(leftSlice, 0, sourceWidth, topSlice),
1373                                         FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
1374
1375     // Paint the bottom edge.
1376     if (drawBottom && sourceWidth > 0)
1377         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
1378                                         destinationWidth, bottomWidth),
1379                                         IntRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
1380                                         FloatSize(bottomSideScale, bottomSideScale),
1381                                         (Image::TileRule)hRule, Image::StretchTile, op);
1382
1383     // Paint the middle.
1384     if (drawMiddle) {
1385         FloatSize middleScaleFactor(1, 1);
1386         if (drawTop)
1387             middleScaleFactor.setWidth(topSideScale);
1388         else if (drawBottom)
1389             middleScaleFactor.setWidth(bottomSideScale);
1390         if (drawLeft)
1391             middleScaleFactor.setHeight(leftSideScale);
1392         else if (drawRight)
1393             middleScaleFactor.setHeight(rightSideScale);
1394             
1395         // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
1396         // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
1397         // The middle however can have "stretch" specified in one axis but not the other, so we have to
1398         // correct the scale here.
1399         if (hRule == StretchImageRule)
1400             middleScaleFactor.setWidth(destinationWidth / sourceWidth);
1401             
1402         if (vRule == StretchImageRule)
1403             middleScaleFactor.setHeight(destinationHeight / sourceHeight);
1404         
1405         graphicsContext->drawTiledImage(image.get(), colorSpace,
1406             IntRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
1407             IntRect(leftSlice, topSlice, sourceWidth, sourceHeight),
1408             middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1409     }
1410
1411     return true;
1412 }
1413
1414 class BorderEdge {
1415 public:
1416     BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1417         : width(edgeWidth)
1418         , color(edgeColor)
1419         , style(edgeStyle)
1420         , isTransparent(edgeIsTransparent)
1421         , isPresent(edgeIsPresent)
1422     {
1423         if (style == DOUBLE && edgeWidth < 3)
1424             style = SOLID;
1425     }
1426     
1427     BorderEdge()
1428         : width(0)
1429         , style(BHIDDEN)
1430         , isTransparent(false)
1431         , isPresent(false)
1432     {
1433     }
1434     
1435     bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1436     bool shouldRender() const { return isPresent && hasVisibleColorAndStyle(); }
1437     bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1438     bool obscuresBackgroundEdge(float scale) const
1439     {
1440         if (!isPresent || isTransparent || width < (2 * scale) || color.hasAlpha() || style == BHIDDEN)
1441             return false;
1442
1443         if (style == DOTTED || style == DASHED)
1444             return false;
1445
1446         if (style == DOUBLE)
1447             return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1448
1449         return true;
1450     }
1451     bool obscuresBackground() const
1452     {
1453         if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1454             return false;
1455
1456         if (style == DOTTED || style == DASHED || style == DOUBLE)
1457             return false;
1458
1459         return true;
1460     }
1461
1462     int usedWidth() const { return isPresent ? width : 0; }
1463     
1464     void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1465     {
1466         int fullWidth = usedWidth();
1467         outerWidth = fullWidth / 3;
1468         innerWidth = fullWidth * 2 / 3;
1469
1470         // We need certain integer rounding results
1471         if (fullWidth % 3 == 2)
1472             outerWidth += 1;
1473
1474         if (fullWidth % 3 == 1)
1475             innerWidth += 1;
1476     }
1477     
1478     int width;
1479     Color color;
1480     EBorderStyle style;
1481     bool isTransparent;
1482     bool isPresent;
1483 };
1484
1485 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1486 {
1487     LayoutRect boundingRect = border.rect();
1488     if (clipRect.contains(boundingRect))
1489         return false;
1490
1491     RoundedRect::Radii radii = border.radii();
1492
1493     LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1494     if (clipRect.intersects(topLeftRect))
1495         return false;
1496
1497     LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1498     topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1499     if (clipRect.intersects(topRightRect))
1500         return false;
1501
1502     LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1503     bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1504     if (clipRect.intersects(bottomLeftRect))
1505         return false;
1506
1507     LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1508     bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1509     bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1510     if (clipRect.intersects(bottomRightRect))
1511         return false;
1512
1513     return true;
1514 }
1515
1516 #if HAVE(PATH_BASED_BORDER_RADIUS_DRAWING)
1517 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1518 {
1519     return !firstRadius.isZero() || !secondRadius.isZero();
1520 }
1521
1522 enum BorderEdgeFlag {
1523     TopBorderEdge = 1 << BSTop,
1524     RightBorderEdge = 1 << BSRight,
1525     BottomBorderEdge = 1 << BSBottom,
1526     LeftBorderEdge = 1 << BSLeft,
1527     AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1528 };
1529
1530 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1531 {
1532     return static_cast<BorderEdgeFlag>(1 << side);
1533 }
1534
1535 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1536 {
1537     return flags & edgeFlagForSide(side);
1538 }
1539
1540 static inline bool includesAdjacentEdges(BorderEdgeFlags flags)
1541 {
1542     return (flags & (TopBorderEdge | RightBorderEdge)) == (TopBorderEdge | RightBorderEdge)
1543         || (flags & (RightBorderEdge | BottomBorderEdge)) == (RightBorderEdge | BottomBorderEdge)
1544         || (flags & (BottomBorderEdge | LeftBorderEdge)) == (BottomBorderEdge | LeftBorderEdge)
1545         || (flags & (LeftBorderEdge | TopBorderEdge)) == (LeftBorderEdge | TopBorderEdge);
1546 }
1547
1548 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1549 {
1550     return firstEdge.color == secondEdge.color;
1551 }
1552
1553 inline bool styleRequiresClipPolygon(EBorderStyle style)
1554 {
1555     return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1556 }
1557
1558 static bool borderStyleFillsBorderArea(EBorderStyle style)
1559 {
1560     return !(style == DOTTED || style == DASHED || style == DOUBLE);
1561 }
1562
1563 static bool borderStyleHasInnerDetail(EBorderStyle style)
1564 {
1565     return style == GROOVE || style == RIDGE || style == DOUBLE;
1566 }
1567
1568 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1569 {
1570     return style == DOTTED || style == DASHED;
1571 }
1572
1573 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1574 // INSET darkens the top and left (and maybe lightens the bottom and right)
1575 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1576 {
1577     // These styles match at the top/left and bottom/right.
1578     if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1579         const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1580         const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1581
1582         BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1583         return flags == topRightFlags || flags == bottomLeftFlags;
1584     }
1585     return false;
1586 }
1587
1588 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1589 {
1590     if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1591         return false;
1592
1593     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1594         return false;
1595
1596     return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1597 }
1598
1599
1600 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1601 {
1602     if (!edges[side].color.hasAlpha())
1603         return false;
1604
1605     if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1606         return false;
1607
1608     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1609         return true;
1610
1611     return borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1612 }
1613
1614 // This assumes that we draw in order: top, bottom, left, right.
1615 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1616 {
1617     switch (side) {
1618     case BSTop:
1619     case BSBottom:
1620         if (edges[adjacentSide].presentButInvisible())
1621             return false;
1622
1623         if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1624             return false;
1625         
1626         if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1627             return false;
1628
1629         return true;
1630
1631     case BSLeft:
1632     case BSRight:
1633         // These draw last, so are never overdrawn.
1634         return false;
1635     }
1636     return false;
1637 }
1638
1639 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1640 {
1641     if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1642         return true;
1643
1644     if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1645         return true;
1646
1647     if (style != adjacentStyle)
1648         return true;
1649
1650     return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1651 }
1652
1653 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1654 {
1655     if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1656         return false;
1657
1658     if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1659         return false;
1660
1661     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1662         return true;
1663
1664     if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1665         return true;
1666     
1667     return false;
1668 }
1669
1670 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1671     const IntRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1672     BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1673 {
1674     const BorderEdge& edgeToRender = edges[side];
1675     const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1676     const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1677
1678     bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1679     bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1680     
1681     bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1682     bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1683
1684     const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1685
1686     if (path) {
1687         GraphicsContextStateSaver stateSaver(*graphicsContext);
1688         if (innerBorder.isRenderable())
1689             clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1690         else
1691             clipBorderSideForComplexInnerPath(graphicsContext, outerBorder, innerBorder, side, edges);
1692         float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1693         drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1694             colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1695     } else {
1696         bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1697         bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1;
1698         bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2;
1699         bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2;
1700         
1701         GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1702         if (shouldClip) {
1703             bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1);
1704             bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2);
1705             clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2);
1706             // Since we clipped, no need to draw with a mitre.
1707             mitreAdjacentSide1 = false;
1708             mitreAdjacentSide2 = false;
1709         }
1710         
1711         drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1712                 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1713     }
1714 }
1715
1716 static IntRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1717 {
1718     IntRect sideRect = outerBorder.rect();
1719     int width = edges[side].width;
1720
1721     if (side == BSTop)
1722         sideRect.setHeight(width);
1723     else if (side == BSBottom)
1724         sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1725     else if (side == BSLeft)
1726         sideRect.setWidth(width);
1727     else
1728         sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1729
1730     return sideRect;
1731 }
1732
1733 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1734                                             const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1735                                             bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1736 {
1737     bool renderRadii = outerBorder.isRounded();
1738
1739     Path roundedPath;
1740     if (renderRadii)
1741         roundedPath.addRoundedRect(outerBorder);
1742     
1743     if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1744         IntRect sideRect = outerBorder.rect();
1745         sideRect.setHeight(edges[BSTop].width);
1746
1747         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1748         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1749     }
1750
1751     if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1752         IntRect sideRect = outerBorder.rect();
1753         sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width);
1754
1755         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1756         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1757     }
1758
1759     if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1760         IntRect sideRect = outerBorder.rect();
1761         sideRect.setWidth(edges[BSLeft].width);
1762
1763         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1764         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1765     }
1766
1767     if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1768         IntRect sideRect = outerBorder.rect();
1769         sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width);
1770
1771         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1772         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1773     }
1774 }
1775
1776 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1777                                                        const BorderEdge edges[], BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1778 {
1779     BorderEdgeFlags edgesToDraw = AllBorderEdges;
1780     while (edgesToDraw) {
1781         // Find undrawn edges sharing a color.
1782         Color commonColor;
1783         
1784         BorderEdgeFlags commonColorEdgeSet = 0;
1785         for (int i = BSTop; i <= BSLeft; ++i) {
1786             BoxSide currSide = static_cast<BoxSide>(i);
1787             if (!includesEdge(edgesToDraw, currSide))
1788                 continue;
1789
1790             bool includeEdge;
1791             if (!commonColorEdgeSet) {
1792                 commonColor = edges[currSide].color;
1793                 includeEdge = true;
1794             } else
1795                 includeEdge = edges[currSide].color == commonColor;
1796
1797             if (includeEdge)
1798                 commonColorEdgeSet |= edgeFlagForSide(currSide);
1799         }
1800
1801         bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && commonColor.hasAlpha();
1802         if (useTransparencyLayer) {
1803             graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1804             commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1805         }
1806
1807         paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1808             
1809         if (useTransparencyLayer)
1810             graphicsContext->endTransparencyLayer();
1811         
1812         edgesToDraw &= ~commonColorEdgeSet;
1813     }
1814 }
1815
1816 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1817                                        BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1818 {
1819     GraphicsContext* graphicsContext = info.context;
1820     // border-image is not affected by border-radius.
1821     if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1822         return;
1823
1824     if (graphicsContext->paintingDisabled())
1825         return;
1826
1827     BorderEdge edges[4];
1828     getBorderEdgeInfo(edges, style, includeLogicalLeftEdge, includeLogicalRightEdge);
1829     RoundedRect outerBorder = style->getRoundedBorderFor(rect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
1830     RoundedRect innerBorder = style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1831
1832     bool haveAlphaColor = false;
1833     bool haveAllSolidEdges = true;
1834     bool haveAllDoubleEdges = true;
1835     int numEdgesVisible = 4;
1836     bool allEdgesShareColor = true;
1837     int firstVisibleEdge = -1;
1838
1839     for (int i = BSTop; i <= BSLeft; ++i) {
1840         const BorderEdge& currEdge = edges[i];
1841         if (currEdge.presentButInvisible()) {
1842             --numEdgesVisible;
1843             allEdgesShareColor = false;
1844             continue;
1845         }
1846         
1847         if (!currEdge.width) {
1848             --numEdgesVisible;
1849             continue;
1850         }
1851
1852         if (firstVisibleEdge == -1)
1853             firstVisibleEdge = i;
1854         else if (currEdge.color != edges[firstVisibleEdge].color)
1855             allEdgesShareColor = false;
1856
1857         if (currEdge.color.hasAlpha())
1858             haveAlphaColor = true;
1859         
1860         if (currEdge.style != SOLID)
1861             haveAllSolidEdges = false;
1862
1863         if (currEdge.style != DOUBLE)
1864             haveAllDoubleEdges = false;
1865     }
1866
1867     // If no corner intersects the clip region, we can pretend outerBorder is
1868     // rectangular to improve performance.
1869     if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
1870         outerBorder.setRadii(RoundedRect::Radii());
1871
1872     // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1873     if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) {
1874         // Fast path for drawing all solid edges and all unrounded double edges
1875         if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
1876             && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
1877             Path path;
1878             
1879             if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1880                 path.addRoundedRect(outerBorder);
1881             else
1882                 path.addRect(outerBorder.rect());
1883
1884             if (haveAllDoubleEdges) {
1885                 IntRect innerThirdRect = outerBorder.rect();
1886                 IntRect outerThirdRect = outerBorder.rect();
1887                 for (int side = BSTop; side <= BSLeft; ++side) {
1888                     int outerWidth;
1889                     int innerWidth;
1890                     edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
1891
1892                     if (side == BSTop) {
1893                         innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth);
1894                         outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth);
1895                     } else if (side == BSBottom) {
1896                         innerThirdRect.setHeight(innerThirdRect.height() - innerWidth);
1897                         outerThirdRect.setHeight(outerThirdRect.height() - outerWidth);
1898                     } else if (side == BSLeft) {
1899                         innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth);
1900                         outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth);
1901                     } else {
1902                         innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
1903                         outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
1904                     }
1905                 }
1906
1907                 RoundedRect outerThird = outerBorder;
1908                 RoundedRect innerThird = innerBorder;
1909                 innerThird.setRect(innerThirdRect);
1910                 outerThird.setRect(outerThirdRect);
1911
1912                 if (outerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1913                     path.addRoundedRect(outerThird);
1914                 else
1915                     path.addRect(outerThird.rect());
1916
1917                 if (innerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1918                     path.addRoundedRect(innerThird);
1919                 else
1920                     path.addRect(innerThird.rect());
1921             }
1922
1923             if (innerBorder.isRounded())
1924                 path.addRoundedRect(innerBorder);
1925             else
1926                 path.addRect(innerBorder.rect());
1927             
1928             graphicsContext->setFillRule(RULE_EVENODD);
1929             graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1930             graphicsContext->fillPath(path);
1931             return;
1932         } 
1933         // Avoid creating transparent layers
1934         if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
1935             Path path;
1936
1937             for (int i = BSTop; i <= BSLeft; ++i) {
1938                 const BorderEdge& currEdge = edges[i];
1939                 if (currEdge.shouldRender()) {
1940                     IntRect sideRect = calculateSideRect(outerBorder, edges, i);
1941                     path.addRect(sideRect);
1942                 }
1943             }
1944
1945             graphicsContext->setFillRule(RULE_NONZERO);
1946             graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1947             graphicsContext->fillPath(path);
1948             return;
1949         }
1950     }
1951
1952     bool clipToOuterBorder = outerBorder.isRounded();
1953     GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
1954     if (clipToOuterBorder) {
1955         // Clip to the inner and outer radii rects.
1956         if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1957             graphicsContext->addRoundedRectClip(outerBorder);
1958         // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1959         // The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
1960         if (innerBorder.isRenderable())
1961             graphicsContext->clipOutRoundedRect(innerBorder);
1962     }
1963
1964     // If only one edge visible antialiasing doesn't create seams
1965     bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1;
1966     if (haveAlphaColor)
1967         paintTranslucentBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1968     else
1969         paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, AllBorderEdges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1970 }
1971
1972 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
1973                                     float thickness, float drawThickness, BoxSide side, const RenderStyle* style, 
1974                                     Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1975 {
1976     if (thickness <= 0)
1977         return;
1978
1979     if (borderStyle == DOUBLE && thickness < 3)
1980         borderStyle = SOLID;
1981
1982     switch (borderStyle) {
1983     case BNONE:
1984     case BHIDDEN:
1985         return;
1986     case DOTTED:
1987     case DASHED: {
1988         graphicsContext->setStrokeColor(color, style->colorSpace());
1989
1990         // The stroke is doubled here because the provided path is the 
1991         // outside edge of the border so half the stroke is clipped off. 
1992         // The extra multiplier is so that the clipping mask can antialias
1993         // the edges to prevent jaggies.
1994         graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
1995         graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1996
1997         // If the number of dashes that fit in the path is odd and non-integral then we
1998         // will have an awkwardly-sized dash at the end of the path. To try to avoid that
1999         // here, we simply make the whitespace dashes ever so slightly bigger.
2000         // FIXME: This could be even better if we tried to manipulate the dash offset
2001         // and possibly the gapLength to get the corners dash-symmetrical.
2002         float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
2003         float gapLength = dashLength;
2004         float numberOfDashes = borderPath.length() / dashLength;
2005         // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
2006         // FIXME: should do this test per side.
2007         if (numberOfDashes >= 4) {
2008             bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
2009             bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
2010             if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
2011                 float numberOfGaps = numberOfDashes / 2;
2012                 gapLength += (dashLength  / numberOfGaps);
2013             }
2014
2015             DashArray lineDash;
2016             lineDash.append(dashLength);
2017             lineDash.append(gapLength);
2018             graphicsContext->setLineDash(lineDash, dashLength);
2019         }
2020         
2021         // FIXME: stroking the border path causes issues with tight corners:
2022         // https://bugs.webkit.org/show_bug.cgi?id=58711
2023         // Also, to get the best appearance we should stroke a path between the two borders.
2024         graphicsContext->strokePath(borderPath);
2025         return;
2026     }
2027     case DOUBLE: {
2028         // Get the inner border rects for both the outer border line and the inner border line
2029         int outerBorderTopWidth;
2030         int innerBorderTopWidth;
2031         edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
2032
2033         int outerBorderRightWidth;
2034         int innerBorderRightWidth;
2035         edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
2036
2037         int outerBorderBottomWidth;
2038         int innerBorderBottomWidth;
2039         edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
2040
2041         int outerBorderLeftWidth;
2042         int innerBorderLeftWidth;
2043         edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
2044
2045         // Draw inner border line
2046         {
2047             GraphicsContextStateSaver stateSaver(*graphicsContext);
2048             RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
2049                 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
2050                 includeLogicalLeftEdge, includeLogicalRightEdge);
2051             
2052             graphicsContext->addRoundedRectClip(innerClip);
2053             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2054         }
2055
2056         // Draw outer border line
2057         {
2058             GraphicsContextStateSaver stateSaver(*graphicsContext);
2059             LayoutRect outerRect = borderRect;
2060             if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
2061                 outerRect.inflate(1);
2062                 ++outerBorderTopWidth;
2063                 ++outerBorderBottomWidth;
2064                 ++outerBorderLeftWidth;
2065                 ++outerBorderRightWidth;
2066             }
2067                 
2068             RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
2069                 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
2070                 includeLogicalLeftEdge, includeLogicalRightEdge);
2071             graphicsContext->clipOutRoundedRect(outerClip);
2072             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2073         }
2074         return;
2075     }
2076     case RIDGE:
2077     case GROOVE:
2078     {
2079         EBorderStyle s1;
2080         EBorderStyle s2;
2081         if (borderStyle == GROOVE) {
2082             s1 = INSET;
2083             s2 = OUTSET;
2084         } else {
2085             s1 = OUTSET;
2086             s2 = INSET;
2087         }
2088         
2089         // Paint full border
2090         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2091
2092         // Paint inner only
2093         GraphicsContextStateSaver stateSaver(*graphicsContext);
2094         LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
2095         LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
2096         LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
2097         LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
2098
2099         RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
2100             topWidth, bottomWidth, leftWidth, rightWidth,
2101             includeLogicalLeftEdge, includeLogicalRightEdge);
2102
2103         graphicsContext->addRoundedRectClip(clipRect);
2104         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2105         return;
2106     }
2107     case INSET:
2108         if (side == BSTop || side == BSLeft)
2109             color = color.dark();
2110         break;
2111     case OUTSET:
2112         if (side == BSBottom || side == BSRight)
2113             color = color.dark();
2114         break;
2115     default:
2116         break;
2117     }
2118
2119     graphicsContext->setStrokeStyle(NoStroke);
2120     graphicsContext->setFillColor(color, style->colorSpace());
2121     graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
2122 }
2123 #else
2124 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const IntRect& rect, const RenderStyle* style,
2125                                        BackgroundBleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2126 {
2127     GraphicsContext* graphicsContext = info.context;
2128     // FIXME: This old version of paintBorder should be removed when all ports implement 
2129     // GraphicsContext::clipConvexPolygon()!! This should happen soon.
2130     if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
2131         return;
2132
2133     const Color& topColor = style->visitedDependentColor(CSSPropertyBorderTopColor);
2134     const Color& bottomColor = style->visitedDependentColor(CSSPropertyBorderBottomColor);
2135     const Color& leftColor = style->visitedDependentColor(CSSPropertyBorderLeftColor);
2136     const Color& rightColor = style->visitedDependentColor(CSSPropertyBorderRightColor);
2137
2138     bool topTransparent = style->borderTopIsTransparent();
2139     bool bottomTransparent = style->borderBottomIsTransparent();
2140     bool rightTransparent = style->borderRightIsTransparent();
2141     bool leftTransparent = style->borderLeftIsTransparent();
2142
2143     EBorderStyle topStyle = style->borderTopStyle();
2144     EBorderStyle bottomStyle = style->borderBottomStyle();
2145     EBorderStyle leftStyle = style->borderLeftStyle();
2146     EBorderStyle rightStyle = style->borderRightStyle();
2147
2148     bool horizontal = style->isHorizontalWritingMode();
2149     bool renderTop = topStyle > BHIDDEN && !topTransparent && (horizontal || includeLogicalLeftEdge);
2150     bool renderLeft = leftStyle > BHIDDEN && !leftTransparent && (!horizontal || includeLogicalLeftEdge);
2151     bool renderRight = rightStyle > BHIDDEN && !rightTransparent && (!horizontal || includeLogicalRightEdge);
2152     bool renderBottom = bottomStyle > BHIDDEN && !bottomTransparent && (horizontal || includeLogicalRightEdge);
2153
2154
2155     RoundedRect border(rect);
2156     
2157     GraphicsContextStateSaver stateSaver(*graphicsContext, false);
2158     if (style->hasBorderRadius()) {
2159         border.includeLogicalEdges(style->getRoundedBorderFor(border.rect(), view()).radii(),
2160                                    horizontal, includeLogicalLeftEdge, includeLogicalRightEdge);
2161         if (border.isRounded()) {
2162             stateSaver.save();
2163             graphicsContext->addRoundedRectClip(border);
2164         }
2165     }
2166
2167     int firstAngleStart, secondAngleStart, firstAngleSpan, secondAngleSpan;
2168     float thickness;
2169     bool renderRadii = border.isRounded();
2170     bool upperLeftBorderStylesMatch = renderLeft && (topStyle == leftStyle) && (topColor == leftColor);
2171     bool upperRightBorderStylesMatch = renderRight && (topStyle == rightStyle) && (topColor == rightColor) && (topStyle != OUTSET) && (topStyle != RIDGE) && (topStyle != INSET) && (topStyle != GROOVE);
2172     bool lowerLeftBorderStylesMatch = renderLeft && (bottomStyle == leftStyle) && (bottomColor == leftColor) && (bottomStyle != OUTSET) && (bottomStyle != RIDGE) && (bottomStyle != INSET) && (bottomStyle != GROOVE);
2173     bool lowerRightBorderStylesMatch = renderRight && (bottomStyle == rightStyle) && (bottomColor == rightColor);
2174
2175     if (renderTop) {
2176         bool ignoreLeft = (renderRadii && border.radii().topLeft().width() > 0)
2177             || (topColor == leftColor && topTransparent == leftTransparent && topStyle >= OUTSET
2178                 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
2179         
2180         bool ignoreRight = (renderRadii && border.radii().topRight().width() > 0)
2181             || (topColor == rightColor && topTransparent == rightTransparent && topStyle >= OUTSET
2182                 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
2183
2184         int x = rect.x();
2185         int x2 = rect.maxX();
2186         if (renderRadii) {
2187             x += border.radii().topLeft().width();
2188             x2 -= border.radii().topRight().width();
2189         }
2190
2191         drawLineForBoxSide(graphicsContext, x, rect.y(), x2, rect.y() + style->borderTopWidth(), BSTop, topColor, topStyle,
2192                    ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
2193
2194         if (renderRadii) {
2195             int leftY = rect.y();
2196
2197             // We make the arc double thick and let the clip rect take care of clipping the extra off.
2198             // We're doing this because it doesn't seem possible to match the curve of the clip exactly
2199             // with the arc-drawing function.
2200             thickness = style->borderTopWidth() * 2;
2201
2202             if (border.radii().topLeft().width()) {
2203                 int leftX = rect.x();
2204                 // The inner clip clips inside the arc. This is especially important for 1px borders.
2205                 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
2206                     && (style->borderTopWidth() < border.radii().topLeft().height())
2207                     && (topStyle != DOUBLE || style->borderTopWidth() > 6);
2208                 
2209                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
2210                 if (applyLeftInnerClip)
2211                     graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
2212                                                              style->borderTopWidth());
2213
2214                 firstAngleStart = 90;
2215                 firstAngleSpan = upperLeftBorderStylesMatch ? 90 : 45;
2216
2217                 // Draw upper left arc
2218                 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
2219                               BSTop, topColor, topStyle, true);
2220             }
2221
2222             if (border.radii().topRight().width()) {
2223                 int rightX = rect.maxX() - border.radii().topRight().width() * 2;
2224                 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
2225                     && (style->borderTopWidth() < border.radii().topRight().height())
2226                     && (topStyle != DOUBLE || style->borderTopWidth() > 6);
2227
2228                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
2229                 if (applyRightInnerClip)
2230                     graphicsContext->addInnerRoundedRectClip(IntRect(rightX, leftY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
2231                                                              style->borderTopWidth());
2232
2233                 if (upperRightBorderStylesMatch) {
2234                     secondAngleStart = 0;
2235                     secondAngleSpan = 90;
2236                 } else {
2237                     secondAngleStart = 45;
2238                     secondAngleSpan = 45;
2239                 }
2240
2241                 // Draw upper right arc
2242                 drawArcForBoxSide(graphicsContext, rightX, leftY, thickness, border.radii().topRight(), secondAngleStart, secondAngleSpan,
2243                               BSTop, topColor, topStyle, false);
2244             }
2245         }
2246     }
2247
2248     if (renderBottom) {
2249         bool ignoreLeft = (renderRadii && border.radii().bottomLeft().width() > 0)
2250             || (bottomColor == leftColor && bottomTransparent == leftTransparent && bottomStyle >= OUTSET
2251                 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
2252
2253         bool ignoreRight = (renderRadii && border.radii().bottomRight().width() > 0)
2254             || (bottomColor == rightColor && bottomTransparent == rightTransparent && bottomStyle >= OUTSET
2255                 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
2256
2257         int x = rect.x();
2258         int x2 = rect.maxX();
2259         if (renderRadii) {
2260             x += border.radii().bottomLeft().width();
2261             x2 -= border.radii().bottomRight().width();
2262         }
2263
2264         drawLineForBoxSide(graphicsContext, x, rect.maxY() - style->borderBottomWidth(), x2, rect.maxY(), BSBottom, bottomColor, bottomStyle,
2265                    ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
2266
2267         if (renderRadii) {
2268             thickness = style->borderBottomWidth() * 2;
2269
2270             if (border.radii().bottomLeft().width()) {
2271                 int leftX = rect.x();
2272                 int leftY = rect.maxY() - border.radii().bottomLeft().height() * 2;
2273                 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
2274                     && (style->borderBottomWidth() < border.radii().bottomLeft().height())
2275                     && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
2276
2277                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
2278                 if (applyLeftInnerClip)
2279                     graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
2280                                                              style->borderBottomWidth());
2281
2282                 if (lowerLeftBorderStylesMatch) {
2283                     firstAngleStart = 180;
2284                     firstAngleSpan = 90;
2285                 } else {
2286                     firstAngleStart = 225;
2287                     firstAngleSpan = 45;
2288                 }
2289
2290                 // Draw lower left arc
2291                 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().bottomLeft(), firstAngleStart, firstAngleSpan,
2292                               BSBottom, bottomColor, bottomStyle, true);
2293             }
2294
2295             if (border.radii().bottomRight().width()) {
2296                 int rightY = rect.maxY() - border.radii().bottomRight().height() * 2;
2297                 int rightX = rect.maxX() - border.radii().bottomRight().width() * 2;
2298                 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
2299                     && (style->borderBottomWidth() < border.radii().bottomRight().height())
2300                     && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
2301
2302                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
2303                 if (applyRightInnerClip)
2304                     graphicsContext->addInnerRoundedRectClip(IntRect(rightX, rightY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
2305                                                              style->borderBottomWidth());
2306
2307                 secondAngleStart = 270;
2308                 secondAngleSpan = lowerRightBorderStylesMatch ? 90 : 45;
2309
2310                 // Draw lower right arc
2311                 drawArcForBoxSide(graphicsContext, rightX, rightY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
2312                               BSBottom, bottomColor, bottomStyle, false);
2313             }
2314         }
2315     }
2316
2317     if (renderLeft) {
2318         bool ignoreTop = (renderRadii && border.radii().topLeft().height() > 0)
2319             || (topColor == leftColor && topTransparent == leftTransparent && leftStyle >= OUTSET
2320                 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
2321
2322         bool ignoreBottom = (renderRadii && border.radii().bottomLeft().height() > 0)
2323             || (bottomColor == leftColor && bottomTransparent == leftTransparent && leftStyle >= OUTSET
2324                 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
2325
2326         int y = rect.y();
2327         int y2 = rect.maxY();
2328         if (renderRadii) {
2329             y += border.radii().topLeft().height();
2330             y2 -= border.radii().bottomLeft().height();
2331         }
2332
2333         drawLineForBoxSide(graphicsContext, rect.x(), y, rect.x() + style->borderLeftWidth(), y2, BSLeft, leftColor, leftStyle,
2334                    ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
2335
2336         if (renderRadii && (!upperLeftBorderStylesMatch || !lowerLeftBorderStylesMatch)) {
2337             int topX = rect.x();
2338             thickness = style->borderLeftWidth() * 2;
2339
2340             if (!upperLeftBorderStylesMatch && border.radii().topLeft().width()) {
2341                 int topY = rect.y();
2342                 bool applyTopInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
2343                     && (style->borderTopWidth() < border.radii().topLeft().height())
2344                     && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
2345
2346                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
2347                 if (applyTopInnerClip)
2348                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
2349                                                              style->borderLeftWidth());
2350
2351                 firstAngleStart = 135;
2352                 firstAngleSpan = 45;
2353
2354                 // Draw top left arc
2355                 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
2356                               BSLeft, leftColor, leftStyle, true);
2357             }
2358
2359             if (!lowerLeftBorderStylesMatch && border.radii().bottomLeft().width()) {
2360                 int bottomY = rect.maxY() - border.radii().bottomLeft().height() * 2;
2361                 bool applyBottomInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
2362                     && (style->borderBottomWidth() < border.radii().bottomLeft().height())
2363                     && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
2364
2365                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
2366                 if (applyBottomInnerClip)
2367                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, bottomY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
2368                                                              style->borderLeftWidth());
2369
2370                 secondAngleStart = 180;
2371                 secondAngleSpan = 45;
2372
2373                 // Draw bottom left arc
2374                 drawArcForBoxSide(graphicsContext, topX, bottomY, thickness, border.radii().bottomLeft(), secondAngleStart, secondAngleSpan,
2375                               BSLeft, leftColor, leftStyle, false);
2376             }
2377         }
2378     }
2379
2380     if (renderRight) {
2381         bool ignoreTop = (renderRadii && border.radii().topRight().height() > 0)
2382             || ((topColor == rightColor) && (topTransparent == rightTransparent)
2383                 && (rightStyle >= DOTTED || rightStyle == INSET)
2384                 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
2385
2386         bool ignoreBottom = (renderRadii && border.radii().bottomRight().height() > 0)
2387             || ((bottomColor == rightColor) && (bottomTransparent == rightTransparent)
2388                 && (rightStyle >= DOTTED || rightStyle == INSET)
2389                 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
2390
2391         int y = rect.y();
2392         int y2 = rect.maxY();
2393         if (renderRadii) {
2394             y += border.radii().topRight().height();
2395             y2 -= border.radii().bottomRight().height();
2396         }
2397
2398         drawLineForBoxSide(graphicsContext, rect.maxX() - style->borderRightWidth(), y, rect.maxX(), y2, BSRight, rightColor, rightStyle,
2399                    ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
2400
2401         if (renderRadii && (!upperRightBorderStylesMatch || !lowerRightBorderStylesMatch)) {
2402             thickness = style->borderRightWidth() * 2;
2403
2404             if (!upperRightBorderStylesMatch && border.radii().topRight().width()) {
2405                 int topX = rect.maxX() - border.radii().topRight().width() * 2;
2406                 int topY = rect.y();
2407                 bool applyTopInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
2408                     && (style->borderTopWidth() < border.radii().topRight().height())
2409                     && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
2410
2411                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
2412                 if (applyTopInnerClip)
2413                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
2414                                                              style->borderRightWidth());
2415
2416                 firstAngleStart = 0;
2417                 firstAngleSpan = 45;
2418
2419                 // Draw top right arc
2420                 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topRight(), firstAngleStart, firstAngleSpan,
2421                               BSRight, rightColor, rightStyle, true);
2422             }
2423
2424             if (!lowerRightBorderStylesMatch && border.radii().bottomRight().width()) {
2425                 int bottomX = rect.maxX() - border.radii().bottomRight().width() * 2;
2426                 int bottomY = rect.maxY() - border.radii().bottomRight().height() * 2;
2427                 bool applyBottomInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
2428                     && (style->borderBottomWidth() < border.radii().bottomRight().height())
2429                     && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
2430
2431                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
2432                 if (applyBottomInnerClip)
2433                     graphicsContext->addInnerRoundedRectClip(IntRect(bottomX, bottomY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
2434                                                              style->borderRightWidth());
2435
2436                 secondAngleStart = 315;
2437                 secondAngleSpan = 45;
2438
2439                 // Draw bottom right arc
2440                 drawArcForBoxSide(graphicsContext, bottomX, bottomY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
2441                               BSRight, rightColor, rightStyle, false);
2442             }
2443         }
2444     }
2445 }
2446 #endif
2447
2448 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
2449 {
2450     // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2451     // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2452     // Note that if findIntersection fails, it will leave result untouched.
2453     if (fabs(outerCorner.x() - innerCorner.x()) > fabs(outerCorner.y() - innerCorner.y()))
2454         findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2455     else
2456         findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2457 }
2458
2459 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2460                                                  BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2461 {
2462     FloatPoint quad[4];
2463
2464     const LayoutRect& outerRect = outerBorder.rect();
2465     const LayoutRect& innerRect = innerBorder.rect();
2466
2467     FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2468
2469     // For each side, create a quad that encompasses all parts of that side that may draw,
2470     // including areas inside the innerBorder.
2471     //
2472     //         0----------------3
2473     //       0  \              /  0
2474     //       |\  1----------- 2  /|
2475     //       | 1                1 |   
2476     //       | |                | |
2477     //       | |                | |  
2478     //       | 2                2 |  
2479     //       |/  1------------2  \| 
2480     //       3  /              \  3   
2481     //         0----------------3
2482     //
2483     switch (side) {
2484     case BSTop:
2485         quad[0] = outerRect.minXMinYCorner();
2486         quad[1] = innerRect.minXMinYCorner();
2487         quad[2] = innerRect.maxXMinYCorner();
2488         quad[3] = outerRect.maxXMinYCorner();
2489
2490         if (!innerBorder.radii().topLeft().isZero())
2491             findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2492
2493         if (!innerBorder.radii().topRight().isZero())
2494             findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2495         break;
2496
2497     case BSLeft:
2498         quad[0] = outerRect.minXMinYCorner();
2499         quad[1] = innerRect.minXMinYCorner();
2500         quad[2] = innerRect.minXMaxYCorner();
2501         quad[3] = outerRect.minXMaxYCorner();
2502
2503         if (!innerBorder.radii().topLeft().isZero())
2504             findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2505
2506         if (!innerBorder.radii().bottomLeft().isZero())
2507             findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2508         break;
2509
2510     case BSBottom:
2511         quad[0] = outerRect.minXMaxYCorner();
2512         quad[1] = innerRect.minXMaxYCorner();
2513         quad[2] = innerRect.maxXMaxYCorner();
2514         quad[3] = outerRect.maxXMaxYCorner();
2515
2516         if (!innerBorder.radii().bottomLeft().isZero())
2517             findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2518
2519         if (!innerBorder.radii().bottomRight().isZero())
2520             findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2521         break;
2522
2523     case BSRight:
2524         quad[0] = outerRect.maxXMinYCorner();
2525         quad[1] = innerRect.maxXMinYCorner();
2526         quad[2] = innerRect.maxXMaxYCorner();
2527         quad[3] = outerRect.maxXMaxYCorner();
2528
2529         if (!innerBorder.radii().topRight().isZero())
2530             findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2531
2532         if (!innerBorder.radii().bottomRight().isZero())
2533             findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2534         break;
2535     }
2536
2537     // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2538     // if neither side matches, anti-alias the clip.
2539     if (firstEdgeMatches == secondEdgeMatches) {
2540         graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2541         return;
2542     }
2543
2544     // Square off the end which shouldn't be affected by antialiasing, and clip.
2545     FloatPoint firstQuad[4];
2546     firstQuad[0] = quad[0];
2547     firstQuad[1] = quad[1];
2548     firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2549         : FloatPoint(quad[2].x(), quad[3].y());
2550     firstQuad[3] = quad[3];
2551     graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2552
2553     FloatPoint secondQuad[4];
2554     secondQuad[0] = quad[0];
2555     secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2556         : FloatPoint(quad[1].x(), quad[0].y());
2557     secondQuad[2] = quad[2];
2558     secondQuad[3] = quad[3];
2559     // Antialiasing affects the second side.
2560     graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2561 }
2562
2563 static IntRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
2564 {
2565     IntRect sideRect = outerBorder.rect();
2566     int width;
2567
2568     switch (side) {
2569     case BSTop:
2570         width = sideRect.height() - edges[BSBottom].width;
2571         sideRect.setHeight(width);
2572         break;
2573     case BSBottom:
2574         width = sideRect.height() - edges[BSTop].width;
2575         sideRect.shiftYEdgeTo(sideRect.maxY() - width);
2576         break;
2577     case BSLeft:
2578         width = sideRect.width() - edges[BSRight].width;
2579         sideRect.setWidth(width);
2580         break;
2581     case BSRight:
2582         width = sideRect.width() - edges[BSLeft].width;
2583         sideRect.shiftXEdgeTo(sideRect.maxX() - width);
2584         break;
2585     }
2586
2587     return sideRect;
2588 }
2589
2590 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
2591 {
2592     // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
2593     // This function relies on the fact we only get radii not contained within each edge if one of the radii
2594     // for an edge is zero, so we can shift the arc towards the zero radius corner.
2595     RoundedRect::Radii newRadii = innerBorder.radii();
2596     IntRect newRect = innerBorder.rect();
2597
2598     float overshoot;
2599     float maxRadii;
2600
2601     switch (side) {
2602     case BSTop:
2603         overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
2604         if (overshoot > 0) {
2605             ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width()));
2606             newRect.setWidth(newRect.width() + overshoot);
2607             if (!newRadii.topLeft().width())
2608                 newRect.move(-overshoot, 0);
2609         }
2610         newRadii.setBottomLeft(IntSize(0, 0));
2611         newRadii.setBottomRight(IntSize(0, 0));
2612         maxRadii = max(newRadii.topLeft().height(), newRadii.topRight().height());
2613         if (maxRadii > newRect.height())
2614             newRect.setHeight(maxRadii);
2615         break;
2616
2617     case BSBottom:
2618         overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
2619         if (overshoot > 0) {
2620             ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width()));
2621             newRect.setWidth(newRect.width() + overshoot);
2622             if (!newRadii.bottomLeft().width())
2623                 newRect.move(-overshoot, 0);
2624         }
2625         newRadii.setTopLeft(IntSize(0, 0));
2626         newRadii.setTopRight(IntSize(0, 0));
2627         maxRadii = max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
2628         if (maxRadii > newRect.height()) {
2629             newRect.move(0, newRect.height() - maxRadii);
2630             newRect.setHeight(maxRadii);
2631         }
2632         break;
2633
2634     case BSLeft:
2635         overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
2636         if (overshoot > 0) {
2637             ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height()));
2638             newRect.setHeight(newRect.height() + overshoot);
2639             if (!newRadii.topLeft().height())
2640                 newRect.move(0, -overshoot);
2641         }
2642         newRadii.setTopRight(IntSize(0, 0));
2643         newRadii.setBottomRight(IntSize(0, 0));
2644         maxRadii = max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
2645         if (maxRadii > newRect.width())
2646             newRect.setWidth(maxRadii);
2647         break;
2648
2649     case BSRight:
2650         overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
2651         if (overshoot > 0) {
2652             ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height()));
2653             newRect.setHeight(newRect.height() + overshoot);
2654             if (!newRadii.topRight().height())
2655                 newRect.move(0, -overshoot);
2656         }
2657         newRadii.setTopLeft(IntSize(0, 0));
2658         newRadii.setBottomLeft(IntSize(0, 0));
2659         maxRadii = max(newRadii.topRight().width(), newRadii.bottomRight().width());
2660         if (maxRadii > newRect.width()) {
2661             newRect.move(newRect.width() - maxRadii, 0);
2662             newRect.setWidth(maxRadii);
2663         }
2664         break;
2665     }
2666
2667     return RoundedRect(newRect, newRadii);
2668 }
2669
2670 void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2671     BoxSide side, const class BorderEdge edges[])
2672 {
2673     graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
2674     graphicsContext->clipOutRoundedRect(calculateAdjustedInnerBorder(innerBorder, side));
2675 }
2676
2677 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2678 {
2679     bool horizontal = style->isHorizontalWritingMode();
2680
2681     edges[BSTop] = BorderEdge(style->borderTopWidth(),
2682         style->visitedDependentColor(CSSPropertyBorderTopColor),
2683         style->borderTopStyle(),
2684         style->borderTopIsTransparent(),
2685         horizontal || includeLogicalLeftEdge);
2686
2687     edges[BSRight] = BorderEdge(style->borderRightWidth(),
2688         style->visitedDependentColor(CSSPropertyBorderRightColor),
2689         style->borderRightStyle(),
2690         style->borderRightIsTransparent(),
2691         !horizontal || includeLogicalRightEdge);
2692
2693     edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2694         style->visitedDependentColor(CSSPropertyBorderBottomColor),
2695         style->borderBottomStyle(),
2696         style->borderBottomIsTransparent(),
2697         horizontal || includeLogicalRightEdge);
2698
2699     edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2700         style->visitedDependentColor(CSSPropertyBorderLeftColor),
2701         style->borderLeftStyle(),
2702         style->borderLeftIsTransparent(),
2703         !horizontal || includeLogicalLeftEdge);
2704 }
2705
2706 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2707 {
2708     BorderEdge edges[4];
2709     getBorderEdgeInfo(edges, style());
2710
2711     for (int i = BSTop; i <= BSLeft; ++i) {
2712         const BorderEdge& currEdge = edges[i];
2713         // FIXME: for vertical text
2714         float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2715         if (!currEdge.obscuresBackgroundEdge(axisScale))
2716             return false;
2717     }
2718
2719     return true;
2720 }
2721
2722 bool RenderBoxModelObject::borderObscuresBackground() const
2723 {
2724     if (!style()->hasBorder())
2725         return false;
2726
2727     // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2728     if (style()->borderImage().image())
2729         return false;
2730
2731     BorderEdge edges[4];
2732     getBorderEdgeInfo(edges, style());
2733
2734     for (int i = BSTop; i <= BSLeft; ++i) {
2735         const BorderEdge& currEdge = edges[i];
2736         if (!currEdge.obscuresBackground())
2737             return false;
2738     }
2739
2740     return true;
2741 }
2742
2743 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2744 {
2745     if (bleedAvoidance != BackgroundBleedNone)
2746         return false;
2747
2748     if (style()->hasAppearance())
2749         return false;
2750
2751     bool hasOneNormalBoxShadow = false;
2752     for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
2753         if (currentShadow->style() != Normal)
2754             continue;
2755
2756         if (hasOneNormalBoxShadow)
2757             return false;
2758         hasOneNormalBoxShadow = true;
2759
2760         if (currentShadow->spread())
2761             return false;
2762     }
2763
2764     if (!hasOneNormalBoxShadow)
2765         return false;
2766
2767     Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
2768     if (!backgroundColor.isValid() || backgroundColor.alpha() < 255)
2769         return false;
2770
2771     const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
2772     for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next())
2773         lastBackgroundLayer = next;
2774
2775     if (lastBackgroundLayer->clip() != BorderFillBox)
2776         return false;
2777
2778     if (lastBackgroundLayer->image() && style()->hasBorderRadius())
2779         return false;
2780
2781     if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2782         return false;
2783
2784     if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2785         return false;
2786
2787     return true;
2788 }
2789
2790 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
2791 {
2792     IntRect bounds(holeRect);
2793     
2794     bounds.inflate(shadowBlur);
2795
2796     if (shadowSpread < 0)
2797         bounds.inflate(-shadowSpread);
2798     
2799     IntRect offsetBounds = bounds;
2800     offsetBounds.move(-shadowOffset);
2801     return unionRect(bounds, offsetBounds);
2802 }
2803
2804 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2805 {
2806     // FIXME: Deal with border-image.  Would be great to use border-image as a mask.
2807     GraphicsContext* context = info.context;
2808     if (context->paintingDisabled() || !s->boxShadow())
2809         return;
2810
2811     RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2812                                                    : s->getRoundedBorderFor(paintRect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
2813
2814     bool hasBorderRadius = s->hasBorderRadius();
2815     bool isHorizontal = s->isHorizontalWritingMode();
2816     
2817     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2818     for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2819         if (shadow->style() != shadowStyle)
2820             continue;
2821
2822         IntSize shadowOffset(shadow->x(), shadow->y());
2823         int shadowBlur = shadow->blur();
2824         int shadowSpread = shadow->spread();
2825         
2826         if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
2827             continue;
2828         
2829         const Color& shadowColor = shadow->color();
2830
2831         if (shadow->style() == Normal) {
2832             RoundedRect fillRect = border;
2833             fillRect.inflate(shadowSpread);
2834             if (fillRect.isEmpty())
2835                 continue;
2836
2837             IntRect shadowRect(border.rect());
2838             shadowRect.inflate(shadowBlur + shadowSpread);
2839             shadowRect.move(shadowOffset);
2840
2841             GraphicsContextStateSaver stateSaver(*context);
2842             context->clip(shadowRect);
2843
2844             // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2845             // bleed in (due to antialiasing) if the context is transformed.
2846             IntSize extraOffset(paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowBlur + 2 * shadowSpread + 1, 0);
2847             shadowOffset -= extraOffset;
2848             fillRect.move(extraOffset);
2849
2850             if (shadow->isWebkitBoxShadow())
2851                 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2852             else
2853                 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2854
2855             if (hasBorderRadius) {
2856                 RoundedRect rectToClipOut = border;
2857
2858                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2859                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2860                 // corners. Those are avoided by insetting the clipping path by one pixel.
2861                 if (hasOpaqueBackground) {
2862                     rectToClipOut.inflateWithRadii(-1);
2863                 }
2864
2865                 if (!rectToClipOut.isEmpty())
2866                     context->clipOutRoundedRect(rectToClipOut);
2867
2868                 RoundedRect influenceRect(shadowRect, border.radii());
2869                 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
2870                 if (allCornersClippedOut(influenceRect, info.rect))
2871                     context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2872                 else {
2873                     fillRect.expandRadii(shadowSpread);
2874                     context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2875                 }
2876             } else {
2877                 IntRect rectToClipOut = border.rect();
2878
2879                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2880                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2881                 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2882                 // by one pixel.
2883                 if (hasOpaqueBackground) {
2884                     // FIXME: The function to decide on the policy based on the transform should be a named function.
2885                     // FIXME: It's not clear if this check is right. What about integral scale factors?
2886                     AffineTransform transform = context->getCTM();
2887                     if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
2888                         rectToClipOut.inflate(-1);
2889                 }
2890
2891                 if (!rectToClipOut.isEmpty())
2892                     context->clipOut(rectToClipOut);
2893                 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2894             }
2895         } else {
2896             // Inset shadow.
2897             IntRect holeRect(border.rect());
2898             holeRect.inflate(-shadowSpread);
2899
2900             if (holeRect.isEmpty()) {
2901                 if (hasBorderRadius)
2902                     context->fillRoundedRect(border, shadowColor, s->colorSpace());
2903                 else
2904                     context->fillRect(border.rect(), shadowColor, s->colorSpace());
2905                 continue;
2906             }
2907
2908             if (!includeLogicalLeftEdge) {
2909                 if (isHorizontal) {
2910                     holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
2911                     holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
2912                 } else {
2913                     holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
2914                     holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
2915                 }
2916             }
2917             if (!includeLogicalRightEdge) {
2918                 if (isHorizontal)
2919                     holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
2920                 else
2921                     holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
2922             }
2923
2924             Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2925
2926             IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
2927             RoundedRect roundedHole(holeRect, border.radii());
2928
2929             GraphicsContextStateSaver stateSaver(*context);
2930             if (hasBorderRadius) {
2931                 Path path;
2932                 path.addRoundedRect(border);
2933                 context->clip(path);
2934                 roundedHole.shrinkRadii(shadowSpread);
2935             } else
2936                 context->clip(border.rect());
2937
2938             IntSize extraOffset(2 * paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowBlur - 2 * shadowSpread + 1, 0);
2939             context->translate(extraOffset.width(), extraOffset.height());
2940             shadowOffset -= extraOffset;
2941
2942             if (shadow->isWebkitBoxShadow())
2943                 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2944             else
2945                 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2946
2947             context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2948         }
2949     }
2950 }
2951
2952 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2953 {
2954     return containingBlock()->availableLogicalWidth();
2955 }
2956
2957 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2958 {
2959     if (!continuationMap)
2960         return 0;
2961     return continuationMap->get(this);
2962 }
2963
2964 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2965 {
2966     if (continuation) {
2967         if (!continuationMap)
2968             continuationMap = new ContinuationMap;
2969         continuationMap->set(this, continuation);
2970     } else {
2971         if (continuationMap)
2972             continuationMap->remove(this);
2973     }
2974 }
2975
2976 RenderObject* RenderBoxModelObject::firstLetterRemainingText() const
2977 {
2978     if (!firstLetterRemainingTextMap)
2979         return 0;
2980     return firstLetterRemainingTextMap->get(this);
2981 }
2982
2983 void RenderBoxModelObject::setFirstLetterRemainingText(RenderObject* remainingText)
2984 {
2985     if (remainingText) {
2986         if (!firstLetterRemainingTextMap)
2987             firstLetterRemainingTextMap = new FirstLetterRemainingTextMap;
2988         firstLetterRemainingTextMap->set(this, remainingText);
2989     } else if (firstLetterRemainingTextMap)
2990         firstLetterRemainingTextMap->remove(this);
2991 }
2992
2993 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context)
2994 {
2995     // FIXME: We may want to not antialias when scaled by an integral value,
2996     // and we may want to antialias when translated by a non-integral value.
2997     return !context->getCTM().isIdentityOrTranslationOrFlipped();
2998 }
2999
3000 void RenderBoxModelObject::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
3001 {
3002     // We don't expect absoluteToLocal() to be called during layout (yet)
3003     ASSERT(!view() || !view()->layoutStateEnabled());
3004
3005     RenderObject* o = container();
3006     if (!o)
3007         return;
3008
3009     o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
3010
3011     LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
3012
3013     if (!style()->isPositioned() && o->hasColumns()) {
3014         RenderBlock* block = static_cast<RenderBlock*>(o);
3015         LayoutPoint point(roundedLayoutPoint(transformState.mappedPoint()));
3016         point -= containerOffset;
3017         block->adjustForColumnRect(containerOffset, point);
3018     }
3019
3020     bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
3021     if (useTransforms && shouldUseTransformFromContainer(o)) {
3022         TransformationMatrix t;
3023         getTransformFromContainer(o, containerOffset, t);
3024         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
3025     } else
3026         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
3027 }
3028
3029 } // namespace WebCore