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