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