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