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