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