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