Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* class that manages rules for positioning floats */
#include "nsFloatManager.h"
#include <algorithm>
#include <initializer_list>
#include "gfxContext.h"
#include "mozilla/PresShell.h"
#include "mozilla/ReflowInput.h"
#include "mozilla/ShapeUtils.h"
#include "nsBlockFrame.h"
#include "nsDeviceContext.h"
#include "nsError.h"
#include "nsIFrame.h"
#include "nsIFrameInlines.h"
#include "nsImageRenderer.h"
using namespace mozilla;
using namespace mozilla::image;
using namespace mozilla::gfx;
int32_t nsFloatManager::sCachedFloatManagerCount = 0;
void* nsFloatManager::sCachedFloatManagers[NS_FLOAT_MANAGER_CACHE_SIZE];
/////////////////////////////////////////////////////////////////////////////
// nsFloatManager
nsFloatManager::nsFloatManager(PresShell* aPresShell, WritingMode aWM)
:
#ifdef DEBUG
mWritingMode(aWM),
#endif
mLineLeft(0),
mBlockStart(0),
mFloatDamage(aPresShell),
mPushedLeftFloatPastBreak(false),
mPushedRightFloatPastBreak(false),
mSplitLeftFloatAcrossBreak(false),
mSplitRightFloatAcrossBreak(false) {
MOZ_COUNT_CTOR(nsFloatManager);
}
nsFloatManager::~nsFloatManager() { MOZ_COUNT_DTOR(nsFloatManager); }
// static
void* nsFloatManager::operator new(size_t aSize) noexcept(true) {
if (sCachedFloatManagerCount > 0) {
// We have cached unused instances of this class, return a cached
// instance in stead of always creating a new one.
return sCachedFloatManagers[--sCachedFloatManagerCount];
}
// The cache is empty, this means we have to create a new instance using
// the global |operator new|.
return moz_xmalloc(aSize);
}
void nsFloatManager::operator delete(void* aPtr, size_t aSize) {
if (!aPtr) {
return;
}
// This float manager is no longer used, if there's still room in
// the cache we'll cache this float manager, unless the layout
// module was already shut down.
if (sCachedFloatManagerCount < NS_FLOAT_MANAGER_CACHE_SIZE &&
sCachedFloatManagerCount >= 0) {
// There's still space in the cache for more instances, put this
// instance in the cache in stead of deleting it.
sCachedFloatManagers[sCachedFloatManagerCount++] = aPtr;
return;
}
// The cache is full, or the layout module has been shut down,
// delete this float manager.
free(aPtr);
}
/* static */
void nsFloatManager::Shutdown() {
// The layout module is being shut down, clean up the cache and
// disable further caching.
int32_t i;
for (i = 0; i < sCachedFloatManagerCount; i++) {
void* floatManager = sCachedFloatManagers[i];
if (floatManager) {
free(floatManager);
}
}
// Disable further caching.
sCachedFloatManagerCount = -1;
}
#define CHECK_BLOCK_AND_LINE_DIR(aWM) \
NS_ASSERTION((aWM).GetBlockDir() == mWritingMode.GetBlockDir() && \
(aWM).IsLineInverted() == mWritingMode.IsLineInverted(), \
"incompatible writing modes")
nsFlowAreaRect nsFloatManager::GetFlowArea(
WritingMode aCBWM, WritingMode aWM, nscoord aBCoord, nscoord aBSize,
BandInfoType aBandInfoType, ShapeType aShapeType, LogicalRect aContentArea,
SavedState* aState, const nsSize& aContainerSize) const {
CHECK_BLOCK_AND_LINE_DIR(aWM);
NS_ASSERTION(aBSize >= 0, "unexpected max block size");
NS_ASSERTION(aContentArea.ISize(aWM) >= 0,
"unexpected content area inline size");
nscoord blockStart = aBCoord + mBlockStart;
if (blockStart < nscoord_MIN) {
NS_WARNING("bad value");
blockStart = nscoord_MIN;
}
// Determine the last float that we should consider.
uint32_t floatCount;
if (aState) {
// Use the provided state.
floatCount = aState->mFloatInfoCount;
MOZ_ASSERT(floatCount <= mFloats.Length(), "bad state");
} else {
// Use our current state.
floatCount = mFloats.Length();
}
// If there are no floats at all, or we're below the last one, return
// quickly.
if (floatCount == 0 || (mFloats[floatCount - 1].mLeftBEnd <= blockStart &&
mFloats[floatCount - 1].mRightBEnd <= blockStart)) {
return nsFlowAreaRect(aWM, aContentArea.IStart(aWM), aBCoord,
aContentArea.ISize(aWM), aBSize,
nsFlowAreaRectFlags::NoFlags);
}
nscoord blockEnd;
if (aBSize == nscoord_MAX) {
// This warning (and the two below) are possible to hit on pages
// with really large objects.
NS_WARNING_ASSERTION(aBandInfoType == BandInfoType::BandFromPoint,
"bad height");
blockEnd = nscoord_MAX;
} else {
blockEnd = blockStart + aBSize;
if (blockEnd < blockStart || blockEnd > nscoord_MAX) {
NS_WARNING("bad value");
blockEnd = nscoord_MAX;
}
}
nscoord lineLeft = mLineLeft + aContentArea.LineLeft(aWM, aContainerSize);
nscoord lineRight = mLineLeft + aContentArea.LineRight(aWM, aContainerSize);
if (lineRight < lineLeft) {
NS_WARNING("bad value");
lineRight = lineLeft;
}
// Walk backwards through the floats until we either hit the front of
// the list or we're above |blockStart|.
bool haveFloats = false;
bool mayWiden = false;
for (uint32_t i = floatCount; i > 0; --i) {
const FloatInfo& fi = mFloats[i - 1];
if (fi.mLeftBEnd <= blockStart && fi.mRightBEnd <= blockStart) {
// There aren't any more floats that could intersect this band.
break;
}
if (fi.IsEmpty(aShapeType)) {
// Ignore empty float areas.
continue;
}
nscoord floatBStart = fi.BStart(aShapeType);
nscoord floatBEnd = fi.BEnd(aShapeType);
if (blockStart < floatBStart &&
aBandInfoType == BandInfoType::BandFromPoint) {
// This float is below our band. Shrink our band's height if needed.
if (floatBStart < blockEnd) {
blockEnd = floatBStart;
}
}
// If blockStart == blockEnd (which happens only with WidthWithinHeight),
// we include floats that begin at our 0-height vertical area. We
// need to do this to satisfy the invariant that a
// WidthWithinHeight call is at least as narrow on both sides as a
// BandFromPoint call beginning at its blockStart.
else if (blockStart < floatBEnd &&
(floatBStart < blockEnd ||
(floatBStart == blockEnd && blockStart == blockEnd))) {
// This float is in our band.
// Shrink our band's width if needed.
UsedFloat floatStyle = fi.mFrame->StyleDisplay()->UsedFloat(aCBWM);
// When aBandInfoType is BandFromPoint, we're only intended to
// consider a point along the y axis rather than a band.
const nscoord bandBlockEnd =
aBandInfoType == BandInfoType::BandFromPoint ? blockStart : blockEnd;
if (floatStyle == UsedFloat::Left) {
// A left float
nscoord lineRightEdge =
fi.LineRight(aShapeType, blockStart, bandBlockEnd);
if (lineRightEdge > lineLeft) {
lineLeft = lineRightEdge;
// Only set haveFloats to true if the float is inside our
// containing block. This matches the spec for what some
// callers want and disagrees for other callers, so we should
// probably provide better information at some point.
haveFloats = true;
// Our area may widen in the block direction if this float may
// narrow in the block direction.
mayWiden = mayWiden || fi.MayNarrowInBlockDirection(aShapeType);
}
} else {
// A right float
nscoord lineLeftEdge =
fi.LineLeft(aShapeType, blockStart, bandBlockEnd);
if (lineLeftEdge < lineRight) {
lineRight = lineLeftEdge;
// See above.
haveFloats = true;
mayWiden = mayWiden || fi.MayNarrowInBlockDirection(aShapeType);
}
}
// Shrink our band's height if needed.
if (floatBEnd < blockEnd &&
aBandInfoType == BandInfoType::BandFromPoint) {
blockEnd = floatBEnd;
}
}
}
nscoord blockSize =
(blockEnd == nscoord_MAX) ? nscoord_MAX : (blockEnd - blockStart);
// convert back from LineLeft/Right to IStart
nscoord inlineStart =
aWM.IsBidiLTR()
? lineLeft - mLineLeft
: mLineLeft - lineRight + LogicalSize(aWM, aContainerSize).ISize(aWM);
nsFlowAreaRectFlags flags =
(haveFloats ? nsFlowAreaRectFlags::HasFloats
: nsFlowAreaRectFlags::NoFlags) |
(mayWiden ? nsFlowAreaRectFlags::MayWiden : nsFlowAreaRectFlags::NoFlags);
// Some callers clamp the inline size of nsFlowAreaRect to be nonnegative
// "for compatibility with nsSpaceManager". So, we set a flag here to record
// the fact that the ISize is actually negative, so that downstream code can
// realize that there's no place here where we could put a float-avoiding
// block (even one with ISize of 0).
if (lineRight - lineLeft < 0) {
flags |= nsFlowAreaRectFlags::ISizeIsActuallyNegative;
}
return nsFlowAreaRect(aWM, inlineStart, blockStart - mBlockStart,
lineRight - lineLeft, blockSize, flags);
}
void nsFloatManager::AddFloat(nsIFrame* aFloatFrame,
const LogicalRect& aMarginRect, WritingMode aWM,
const nsSize& aContainerSize) {
CHECK_BLOCK_AND_LINE_DIR(aWM);
NS_ASSERTION(aMarginRect.ISize(aWM) >= 0, "negative inline size!");
NS_ASSERTION(aMarginRect.BSize(aWM) >= 0, "negative block size!");
FloatInfo info(aFloatFrame, mLineLeft, mBlockStart, aMarginRect, aWM,
aContainerSize);
// Set mLeftBEnd and mRightBEnd.
if (HasAnyFloats()) {
FloatInfo& tail = mFloats[mFloats.Length() - 1];
info.mLeftBEnd = tail.mLeftBEnd;
info.mRightBEnd = tail.mRightBEnd;
} else {
info.mLeftBEnd = nscoord_MIN;
info.mRightBEnd = nscoord_MIN;
}
WritingMode cbWM = aFloatFrame->GetParent()->GetWritingMode();
UsedFloat floatStyle = aFloatFrame->StyleDisplay()->UsedFloat(cbWM);
MOZ_ASSERT(floatStyle == UsedFloat::Left || floatStyle == UsedFloat::Right,
"Unexpected float style!");
nscoord& sideBEnd =
floatStyle == UsedFloat::Left ? info.mLeftBEnd : info.mRightBEnd;
nscoord thisBEnd = info.BEnd();
if (thisBEnd > sideBEnd) {
sideBEnd = thisBEnd;
}
mFloats.AppendElement(std::move(info));
}
// static
LogicalRect nsFloatManager::CalculateRegionFor(WritingMode aWM,
nsIFrame* aFloat,
const LogicalMargin& aMargin,
const nsSize& aContainerSize) {
// We consider relatively positioned frames at their original position.
LogicalRect region(aWM,
nsRect(aFloat->GetNormalPosition(), aFloat->GetSize()),
aContainerSize);
// Float region includes its margin
region.Inflate(aWM, aMargin);
// Don't store rectangles with negative margin-box width or height in
// the float manager; it can't deal with them.
if (region.ISize(aWM) < 0) {
// Preserve the right margin-edge for left floats and the left
// margin-edge for right floats
const nsStyleDisplay* display = aFloat->StyleDisplay();
WritingMode cbWM = aFloat->GetParent()->GetWritingMode();
UsedFloat floatStyle = display->UsedFloat(cbWM);
if ((UsedFloat::Left == floatStyle) == aWM.IsBidiLTR()) {
region.IStart(aWM) = region.IEnd(aWM);
}
region.ISize(aWM) = 0;
}
if (region.BSize(aWM) < 0) {
region.BSize(aWM) = 0;
}
return region;
}
NS_DECLARE_FRAME_PROPERTY_DELETABLE(FloatRegionProperty, nsMargin)
LogicalRect nsFloatManager::GetRegionFor(WritingMode aWM, nsIFrame* aFloat,
const nsSize& aContainerSize) {
LogicalRect region = aFloat->GetLogicalRect(aWM, aContainerSize);
void* storedRegion = aFloat->GetProperty(FloatRegionProperty());
if (storedRegion) {
nsMargin margin = *static_cast<nsMargin*>(storedRegion);
region.Inflate(aWM, LogicalMargin(aWM, margin));
}
return region;
}
void nsFloatManager::StoreRegionFor(WritingMode aWM, nsIFrame* aFloat,
const LogicalRect& aRegion,
const nsSize& aContainerSize) {
nsRect region = aRegion.GetPhysicalRect(aWM, aContainerSize);
nsRect rect = aFloat->GetRect();
if (region.IsEqualEdges(rect)) {
aFloat->RemoveProperty(FloatRegionProperty());
} else {
nsMargin* storedMargin = aFloat->GetProperty(FloatRegionProperty());
if (!storedMargin) {
storedMargin = new nsMargin();
aFloat->SetProperty(FloatRegionProperty(), storedMargin);
}
*storedMargin = region - rect;
}
}
nsresult nsFloatManager::RemoveTrailingRegions(nsIFrame* aFrameList) {
if (!aFrameList) {
return NS_OK;
}
// This could be a good bit simpler if we could guarantee that the
// floats given were at the end of our list, so we could just search
// for the head of aFrameList. (But we can't;
// layout/reftests/bugs/421710-1.html crashes.)
nsTHashSet<nsIFrame*> frameSet(1);
for (nsIFrame* f = aFrameList; f; f = f->GetNextSibling()) {
frameSet.Insert(f);
}
uint32_t newLength = mFloats.Length();
while (newLength > 0) {
if (!frameSet.Contains(mFloats[newLength - 1].mFrame)) {
break;
}
--newLength;
}
mFloats.TruncateLength(newLength);
#ifdef DEBUG
for (uint32_t i = 0; i < mFloats.Length(); ++i) {
NS_ASSERTION(
!frameSet.Contains(mFloats[i].mFrame),
"Frame region deletion was requested but we couldn't delete it");
}
#endif
return NS_OK;
}
void nsFloatManager::PushState(SavedState* aState) {
MOZ_ASSERT(aState, "Need a place to save state");
// This is a cheap push implementation, which
// only saves the (x,y) and last frame in the mFrameInfoMap
// which is enough info to get us back to where we should be
// when pop is called.
//
// This push/pop mechanism is used to undo any
// floats that were added during the unconstrained reflow
// in nsBlockReflowContext::DoReflowBlock(). (See bug 96736)
//
// It should also be noted that the state for mFloatDamage is
// intentionally not saved or restored in PushState() and PopState(),
// since that could lead to bugs where damage is missed/dropped when
// we move from position A to B (during the intermediate incremental
// reflow mentioned above) and then from B to C during the subsequent
// reflow. In the typical case A and C will be the same, but not always.
// Allowing mFloatDamage to accumulate the damage incurred during both
// reflows ensures that nothing gets missed.
aState->mLineLeft = mLineLeft;
aState->mBlockStart = mBlockStart;
aState->mPushedLeftFloatPastBreak = mPushedLeftFloatPastBreak;
aState->mPushedRightFloatPastBreak = mPushedRightFloatPastBreak;
aState->mSplitLeftFloatAcrossBreak = mSplitLeftFloatAcrossBreak;
aState->mSplitRightFloatAcrossBreak = mSplitRightFloatAcrossBreak;
aState->mFloatInfoCount = mFloats.Length();
}
void nsFloatManager::PopState(SavedState* aState) {
MOZ_ASSERT(aState, "No state to restore?");
mLineLeft = aState->mLineLeft;
mBlockStart = aState->mBlockStart;
mPushedLeftFloatPastBreak = aState->mPushedLeftFloatPastBreak;
mPushedRightFloatPastBreak = aState->mPushedRightFloatPastBreak;
mSplitLeftFloatAcrossBreak = aState->mSplitLeftFloatAcrossBreak;
mSplitRightFloatAcrossBreak = aState->mSplitRightFloatAcrossBreak;
NS_ASSERTION(aState->mFloatInfoCount <= mFloats.Length(),
"somebody misused PushState/PopState");
mFloats.TruncateLength(aState->mFloatInfoCount);
}
nscoord nsFloatManager::LowestFloatBStart() const {
if (mPushedLeftFloatPastBreak || mPushedRightFloatPastBreak) {
return nscoord_MAX;
}
if (!HasAnyFloats()) {
return nscoord_MIN;
}
return mFloats[mFloats.Length() - 1].BStart() - mBlockStart;
}
#ifdef DEBUG_FRAME_DUMP
void DebugListFloatManager(const nsFloatManager* aFloatManager) {
aFloatManager->List(stdout);
}
nsresult nsFloatManager::List(FILE* out) const {
if (!HasAnyFloats()) {
return NS_OK;
}
for (uint32_t i = 0; i < mFloats.Length(); ++i) {
const FloatInfo& fi = mFloats[i];
fprintf_stderr(out,
"Float %u: frame=%p rect={%d,%d,%d,%d} BEnd={l:%d, r:%d}\n",
i, static_cast<void*>(fi.mFrame), fi.LineLeft(), fi.BStart(),
fi.ISize(), fi.BSize(), fi.mLeftBEnd, fi.mRightBEnd);
}
return NS_OK;
}
#endif
nscoord nsFloatManager::ClearFloats(nscoord aBCoord,
UsedClear aClearType) const {
if (!HasAnyFloats()) {
return aBCoord;
}
nscoord blockEnd = aBCoord + mBlockStart;
const FloatInfo& tail = mFloats[mFloats.Length() - 1];
switch (aClearType) {
case UsedClear::Both:
blockEnd = std::max(blockEnd, tail.mLeftBEnd);
blockEnd = std::max(blockEnd, tail.mRightBEnd);
break;
case UsedClear::Left:
blockEnd = std::max(blockEnd, tail.mLeftBEnd);
break;
case UsedClear::Right:
blockEnd = std::max(blockEnd, tail.mRightBEnd);
break;
case UsedClear::None:
// Do nothing
break;
}
blockEnd -= mBlockStart;
return blockEnd;
}
bool nsFloatManager::ClearContinues(UsedClear aClearType) const {
return ((mPushedLeftFloatPastBreak || mSplitLeftFloatAcrossBreak) &&
(aClearType == UsedClear::Both || aClearType == UsedClear::Left)) ||
((mPushedRightFloatPastBreak || mSplitRightFloatAcrossBreak) &&
(aClearType == UsedClear::Both || aClearType == UsedClear::Right));
}
/////////////////////////////////////////////////////////////////////////////
// ShapeInfo is an abstract class for implementing all the shapes in CSS
// Shapes Module. A subclass needs to override all the methods to adjust
// the flow area with respect to its shape.
//
class nsFloatManager::ShapeInfo {
public:
virtual ~ShapeInfo() = default;
virtual nscoord LineLeft(const nscoord aBStart,
const nscoord aBEnd) const = 0;
virtual nscoord LineRight(const nscoord aBStart,
const nscoord aBEnd) const = 0;
virtual nscoord BStart() const = 0;
virtual nscoord BEnd() const = 0;
virtual bool IsEmpty() const = 0;
// Does this shape possibly get inline narrower in the BStart() to BEnd()
// span when proceeding in the block direction? This is false for unrounded
// rectangles that span all the way to BEnd(), but could be true for other
// shapes. Note that we don't care if the BEnd() falls short of the margin
// rect -- the ShapeInfo can only affect float behavior in the span between
// BStart() and BEnd().
virtual bool MayNarrowInBlockDirection() const = 0;
// Translate the current origin by the specified offsets.
virtual void Translate(nscoord aLineLeft, nscoord aBlockStart) = 0;
static LogicalRect ComputeShapeBoxRect(StyleShapeBox, nsIFrame* const aFrame,
const LogicalRect& aMarginRect,
WritingMode aWM);
// Convert the LogicalRect to the special logical coordinate space used
// in float manager.
static nsRect ConvertToFloatLogical(const LogicalRect& aRect, WritingMode aWM,
const nsSize& aContainerSize) {
return nsRect(aRect.LineLeft(aWM, aContainerSize), aRect.BStart(aWM),
aRect.ISize(aWM), aRect.BSize(aWM));
}
static UniquePtr<ShapeInfo> CreateShapeBox(nsIFrame* const aFrame,
nscoord aShapeMargin,
const LogicalRect& aShapeBoxRect,
WritingMode aWM,
const nsSize& aContainerSize);
static UniquePtr<ShapeInfo> CreateBasicShape(
const StyleBasicShape& aBasicShape, nscoord aShapeMargin,
nsIFrame* const aFrame, const LogicalRect& aShapeBoxRect,
const LogicalRect& aMarginRect, WritingMode aWM,
const nsSize& aContainerSize);
static UniquePtr<ShapeInfo> CreateInset(const StyleBasicShape& aBasicShape,
nscoord aShapeMargin,
nsIFrame* aFrame,
const LogicalRect& aShapeBoxRect,
WritingMode aWM,
const nsSize& aContainerSize);
static UniquePtr<ShapeInfo> CreateCircleOrEllipse(
const StyleBasicShape& aBasicShape, nscoord aShapeMargin,
nsIFrame* const aFrame, const LogicalRect& aShapeBoxRect, WritingMode aWM,
const nsSize& aContainerSize);
static UniquePtr<ShapeInfo> CreatePolygon(const StyleBasicShape& aBasicShape,
nscoord aShapeMargin,
nsIFrame* const aFrame,
const LogicalRect& aShapeBoxRect,
const LogicalRect& aMarginRect,
WritingMode aWM,
const nsSize& aContainerSize);
static UniquePtr<ShapeInfo> CreateImageShape(const StyleImage& aShapeImage,
float aShapeImageThreshold,
nscoord aShapeMargin,
nsIFrame* const aFrame,
const LogicalRect& aMarginRect,
WritingMode aWM,
const nsSize& aContainerSize);
protected:
// Compute the minimum line-axis difference between the bounding shape
// box and its rounded corner within the given band (block-axis region).
// This is used as a helper function to compute the LineRight() and
// LineLeft(). See the picture in the implementation for an example.
// RadiusL and RadiusB stand for radius on the line-axis and block-axis.
//
// Returns radius-x diff on the line-axis, or 0 if there's no rounded
// corner within the given band.
static nscoord ComputeEllipseLineInterceptDiff(
const nscoord aShapeBoxBStart, const nscoord aShapeBoxBEnd,
const nscoord aBStartCornerRadiusL, const nscoord aBStartCornerRadiusB,
const nscoord aBEndCornerRadiusL, const nscoord aBEndCornerRadiusB,
const nscoord aBandBStart, const nscoord aBandBEnd);
static nscoord XInterceptAtY(const nscoord aY, const nscoord aRadiusX,
const nscoord aRadiusY);
// Convert the physical point to the special logical coordinate space
// used in float manager.
static nsPoint ConvertToFloatLogical(const nsPoint& aPoint, WritingMode aWM,
const nsSize& aContainerSize);
// Convert the half corner radii (nscoord[8]) to the special logical
// coordinate space used in float manager.
static UniquePtr<nscoord[]> ConvertToFloatLogical(const nscoord aRadii[8],
WritingMode aWM);
// Some ShapeInfo subclasses may define their float areas in intervals.
// Each interval is a rectangle that is one device pixel deep in the block
// axis. The values are stored as block edges in the y coordinates,
// and inline edges as the x coordinates. Interval arrays should be sorted
// on increasing y values. This function uses a binary search to find the
// first interval that contains aTargetY. If no such interval exists, this
// function returns aIntervals.Length().
static size_t MinIntervalIndexContainingY(const nsTArray<nsRect>& aIntervals,
const nscoord aTargetY);
// This interval function is designed to handle the arguments to ::LineLeft()
// and LineRight() and interpret them for the supplied aIntervals.
static nscoord LineEdge(const nsTArray<nsRect>& aIntervals,
const nscoord aBStart, const nscoord aBEnd,
bool aIsLineLeft);
// These types, constants, and functions are useful for ShapeInfos that
// allocate a distance field. Efficient distance field calculations use
// integer values that are 5X the Euclidean distance. MAX_MARGIN_5X is the
// largest possible margin that we can calculate (in 5X integer dev pixels),
// given these constraints.
typedef uint16_t dfType;
static const dfType MAX_CHAMFER_VALUE;
static const dfType MAX_MARGIN;
static const dfType MAX_MARGIN_5X;
// This function returns a typed, overflow-safe value of aShapeMargin in
// 5X integer dev pixels.
static dfType CalcUsedShapeMargin5X(nscoord aShapeMargin,
int32_t aAppUnitsPerDevPixel);
};
const nsFloatManager::ShapeInfo::dfType
nsFloatManager::ShapeInfo::MAX_CHAMFER_VALUE = 11;
const nsFloatManager::ShapeInfo::dfType nsFloatManager::ShapeInfo::MAX_MARGIN =
(std::numeric_limits<dfType>::max() - MAX_CHAMFER_VALUE) / 5;
const nsFloatManager::ShapeInfo::dfType
nsFloatManager::ShapeInfo::MAX_MARGIN_5X = MAX_MARGIN * 5;
/////////////////////////////////////////////////////////////////////////////
// EllipseShapeInfo
//
// Implements shape-outside: circle() and shape-outside: ellipse().
//
class nsFloatManager::EllipseShapeInfo final
: public nsFloatManager::ShapeInfo {
public:
// Construct the float area using math to calculate the shape boundary.
// This is the fast path and should be used when shape-margin is negligible,
// or when the two values of aRadii are roughly equal. Those two conditions
// are defined by ShapeMarginIsNegligible() and RadiiAreRoughlyEqual(). In
// those cases, we can conveniently represent the entire float area using
// an ellipse.
EllipseShapeInfo(const nsPoint& aCenter, const nsSize& aRadii,
nscoord aShapeMargin);
// Construct the float area using rasterization to calculate the shape
// boundary. This constructor accounts for the fact that applying
// 'shape-margin' to an ellipse produces a shape that is not mathematically
// representable as an ellipse.
EllipseShapeInfo(const nsPoint& aCenter, const nsSize& aRadii,
nscoord aShapeMargin, int32_t aAppUnitsPerDevPixel);
static bool ShapeMarginIsNegligible(nscoord aShapeMargin) {
// For now, only return true for a shape-margin of 0. In the future, if
// we want to enable use of the fast-path constructor more often, this
// limit could be increased;
static const nscoord SHAPE_MARGIN_NEGLIGIBLE_MAX(0);
return aShapeMargin <= SHAPE_MARGIN_NEGLIGIBLE_MAX;
}
static bool RadiiAreRoughlyEqual(const nsSize& aRadii) {
// For now, only return true when we are exactly equal. In the future, if
// we want to enable use of the fast-path constructor more often, this
// could be generalized to allow radii that are in some close proportion
// to each other.
return aRadii.width == aRadii.height;
}
nscoord LineEdge(const nscoord aBStart, const nscoord aBEnd,
bool aLeft) const;
nscoord LineLeft(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord LineRight(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord BStart() const override {
return mCenter.y - mRadii.height - mShapeMargin;
}
nscoord BEnd() const override {
return mCenter.y + mRadii.height + mShapeMargin;
}
bool IsEmpty() const override {
// An EllipseShapeInfo is never empty, because an ellipse or circle with
// a zero radius acts like a point, and an ellipse with one zero radius
// acts like a line.
return false;
}
bool MayNarrowInBlockDirection() const override { return true; }
void Translate(nscoord aLineLeft, nscoord aBlockStart) override {
mCenter.MoveBy(aLineLeft, aBlockStart);
for (nsRect& interval : mIntervals) {
interval.MoveBy(aLineLeft, aBlockStart);
}
}
private:
// The position of the center of the ellipse. The coordinate space is the
// same as FloatInfo::mRect.
nsPoint mCenter;
// The radii of the ellipse in app units. The width and height represent
// the line-axis and block-axis radii of the ellipse.
nsSize mRadii;
// The shape-margin of the ellipse in app units. If this value is greater
// than zero, then we calculate the bounds of the ellipse + margin using
// numerical methods and store the values in mIntervals.
nscoord mShapeMargin;
// An interval is slice of the float area defined by this EllipseShapeInfo.
// Each interval is a rectangle that is one pixel deep in the block
// axis. The values are stored as block edges in the y coordinates,
// and inline edges as the x coordinates.
// The intervals are stored in ascending order on y.
nsTArray<nsRect> mIntervals;
};
nsFloatManager::EllipseShapeInfo::EllipseShapeInfo(const nsPoint& aCenter,
const nsSize& aRadii,
nscoord aShapeMargin)
: mCenter(aCenter),
mRadii(aRadii),
mShapeMargin(
0) // We intentionally ignore the value of aShapeMargin here.
{
MOZ_ASSERT(
RadiiAreRoughlyEqual(aRadii) || ShapeMarginIsNegligible(aShapeMargin),
"This constructor should only be called when margin is "
"negligible or radii are roughly equal.");
// We add aShapeMargin into the radii, and we earlier stored a mShapeMargin
// of zero.
mRadii.width += aShapeMargin;
mRadii.height += aShapeMargin;
}
nsFloatManager::EllipseShapeInfo::EllipseShapeInfo(const nsPoint& aCenter,
const nsSize& aRadii,
nscoord aShapeMargin,
int32_t aAppUnitsPerDevPixel)
: mCenter(aCenter), mRadii(aRadii), mShapeMargin(aShapeMargin) {
if (RadiiAreRoughlyEqual(aRadii) || ShapeMarginIsNegligible(aShapeMargin)) {
// Mimic the behavior of the simple constructor, by adding aShapeMargin
// into the radii, and then storing mShapeMargin of zero.
mRadii.width += mShapeMargin;
mRadii.height += mShapeMargin;
mShapeMargin = 0;
return;
}
// We have to calculate a distance field from the ellipse edge, then build
// intervals based on pixels with less than aShapeMargin distance to an
// edge pixel.
// mCenter and mRadii have already been translated into logical coordinates.
// x = inline, y = block. Due to symmetry, we only need to calculate the
// distance field for one quadrant of the ellipse. We choose the positive-x,
// positive-y quadrant (the lower right quadrant in horizontal-tb writing
// mode). We choose this quadrant because it allows us to traverse our
// distance field in memory order, which is more cache efficient.
// When we apply these intervals in LineLeft() and LineRight(), we
// account for block ranges that hit other quadrants, or hit multiple
// quadrants.
// Given this setup, computing the distance field is a one-pass O(n)
// operation that runs from block top-to-bottom, inline left-to-right. We
// use a chamfer 5-7-11 5x5 matrix to compute minimum distance to an edge
// pixel. This integer math computation is reasonably close to the true
// Euclidean distance. The distances will be approximately 5x the true
// distance, quantized in integer units. The 5x is factored away in the
// comparison which builds the intervals.
dfType usedMargin5X =
CalcUsedShapeMargin5X(aShapeMargin, aAppUnitsPerDevPixel);
// Calculate the bounds of one quadrant of the ellipse, in integer device
// pixels. These bounds are equal to the rectangle defined by the radii,
// plus the shape-margin value in both dimensions.
const LayoutDeviceIntSize bounds =
LayoutDevicePixel::FromAppUnitsRounded(mRadii, aAppUnitsPerDevPixel) +
LayoutDeviceIntSize(usedMargin5X / 5, usedMargin5X / 5);
// Since our distance field is computed with a 5x5 neighborhood, but only
// looks in the negative block and negative inline directions, it is
// effectively a 3x3 neighborhood. We need to expand our distance field
// outwards by a further 2 pixels in both axes (on the minimum block edge
// and the minimum inline edge). We call this edge area the expanded region.
static const uint32_t iExpand = 2;
static const uint32_t bExpand = 2;
// Clamp the size of our distance field sizes to prevent multiplication
// overflow.
static const uint32_t DF_SIDE_MAX =
floor(sqrt((double)(std::numeric_limits<int32_t>::max())));
const uint32_t iSize = std::min(bounds.width + iExpand, DF_SIDE_MAX);
const uint32_t bSize = std::min(bounds.height + bExpand, DF_SIDE_MAX);
auto df = MakeUniqueFallible<dfType[]>(iSize * bSize);
if (!df) {
// Without a distance field, we can't reason about the float area.
return;
}
// Single pass setting distance field, in positive block direction, three
// cases:
// 1) Expanded region pixel: set to MAX_MARGIN_5X.
// 2) Pixel within the ellipse: set to 0.
// 3) Other pixel: set to minimum neighborhood distance value, computed
// with 5-7-11 chamfer.
for (uint32_t b = 0; b < bSize; ++b) {
bool bIsInExpandedRegion(b < bExpand);
nscoord bInAppUnits = (b - bExpand) * aAppUnitsPerDevPixel;
bool bIsMoreThanEllipseBEnd(bInAppUnits > mRadii.height);
// Find the i intercept of the ellipse edge for this block row, and
// adjust it to compensate for the expansion of the inline dimension.
// If we're in the expanded region, or if we're using a b that's more
// than the bEnd of the ellipse, the intercept is nscoord_MIN.
// We have one other special case to consider: when the ellipse has no
// height. In that case we treat the bInAppUnits == 0 case as
// intercepting at the width of the ellipse. All other cases solve
// the intersection mathematically.
const int32_t iIntercept =
(bIsInExpandedRegion || bIsMoreThanEllipseBEnd)
? nscoord_MIN
: iExpand + NSAppUnitsToIntPixels(
(!!mRadii.height || bInAppUnits)
? XInterceptAtY(bInAppUnits, mRadii.width,
mRadii.height)
: mRadii.width,
aAppUnitsPerDevPixel);
// Set iMax in preparation for this block row.
int32_t iMax = iIntercept;
for (uint32_t i = 0; i < iSize; ++i) {
const uint32_t index = i + b * iSize;
MOZ_ASSERT(index < (iSize * bSize),
"Our distance field index should be in-bounds.");
// Handle our three cases, in order.
if (i < iExpand || bIsInExpandedRegion) {
// Case 1: Expanded reqion pixel.
df[index] = MAX_MARGIN_5X;
} else if ((int32_t)i <= iIntercept) {
// Case 2: Pixel within the ellipse, or just outside the edge of it.
// Having a positive height indicates that there's an area we can
// be inside of.
df[index] = (!!mRadii.height) ? 0 : 5;
} else {
// Case 3: Other pixel.
// Backward-looking neighborhood distance from target pixel X
// with chamfer 5-7-11 looks like:
//
// +--+--+--+
// | |11| |
// +--+--+--+
// |11| 7| 5|
// +--+--+--+
// | | 5| X|
// +--+--+--+
//
// X should be set to the minimum of the values of all of the numbered
// neighbors summed with the value in that chamfer cell.
MOZ_ASSERT(index - iSize - 2 < (iSize * bSize) &&
index - (iSize * 2) - 1 < (iSize * bSize),
"Our distance field most extreme indices should be "
"in-bounds.");
// clang-format off
df[index] = std::min<dfType>(df[index - 1] + 5,
std::min<dfType>(df[index - iSize] + 5,
std::min<dfType>(df[index - iSize - 1] + 7,
std::min<dfType>(df[index - iSize - 2] + 11,
df[index - (iSize * 2) - 1] + 11))));
// clang-format on
// Check the df value and see if it's less than or equal to the
// usedMargin5X value.
if (df[index] <= usedMargin5X) {
MOZ_ASSERT(iMax < (int32_t)i);
iMax = i;
} else {
// Since we're computing the bottom-right quadrant, there's no way
// for a later i value in this row to be within the usedMargin5X
// value. Likewise, every row beyond us will encounter this
// condition with an i value less than or equal to our i value now.
// Since our chamfer only looks upward and leftward, we can stop
// calculating for the rest of the row, because the distance field
// values there will never be looked at in a later row's chamfer
// calculation.
break;
}
}
}
// It's very likely, though not guaranteed that we will find an pixel
// within the shape-margin distance for each block row. This may not
// always be true due to rounding errors.
if (iMax > nscoord_MIN) {
// Origin for this interval is at the center of the ellipse, adjusted
// in the positive block direction by bInAppUnits.
nsPoint origin(aCenter.x, aCenter.y + bInAppUnits);
// Size is an inline iMax plus 1 (to account for the whole pixel) dev
// pixels, by 1 block dev pixel. We convert this to app units.
nsSize size((iMax - iExpand + 1) * aAppUnitsPerDevPixel,
aAppUnitsPerDevPixel);
mIntervals.AppendElement(nsRect(origin, size));
}
}
}
nscoord nsFloatManager::EllipseShapeInfo::LineEdge(const nscoord aBStart,
const nscoord aBEnd,
bool aIsLineLeft) const {
// If no mShapeMargin, just compute the edge using math.
if (mShapeMargin == 0) {
nscoord lineDiff = ComputeEllipseLineInterceptDiff(
BStart(), BEnd(), mRadii.width, mRadii.height, mRadii.width,
mRadii.height, aBStart, aBEnd);
return mCenter.x + (aIsLineLeft ? (-mRadii.width + lineDiff)
: (mRadii.width - lineDiff));
}
// We are checking against our intervals. Make sure we have some.
if (mIntervals.IsEmpty()) {
NS_WARNING("With mShapeMargin > 0, we can't proceed without intervals.");
return aIsLineLeft ? nscoord_MAX : nscoord_MIN;
}
// Map aBStart and aBEnd into our intervals. Our intervals are calculated
// for the lower-right quadrant (in terms of horizontal-tb writing mode).
// If aBStart and aBEnd span the center of the ellipse, then we know we
// are at the maximum displacement from the center.
bool bStartIsAboveCenter = (aBStart < mCenter.y);
bool bEndIsBelowOrAtCenter = (aBEnd >= mCenter.y);
if (bStartIsAboveCenter && bEndIsBelowOrAtCenter) {
return mCenter.x + (aIsLineLeft ? (-mRadii.width - mShapeMargin)
: (mRadii.width + mShapeMargin));
}
// aBStart and aBEnd don't span the center. Since the intervals are
// strictly wider approaching the center (the start of the mIntervals
// array), we only need to find the interval at the block value closest to
// the center. We find the min of aBStart, aBEnd, and their reflections --
// whichever two of them are within the lower-right quadrant. When we
// reflect from the upper-right quadrant to the lower-right, we have to
// subtract 1 from the reflection, to account that block values are always
// addressed from the leading block edge.
// The key example is when we check with aBStart == aBEnd at the top of the
// intervals. That block line would be considered contained in the
// intervals (though it has no height), but its reflection would not be
// within the intervals unless we subtract 1.
nscoord bSmallestWithinIntervals = std::min(
bStartIsAboveCenter ? aBStart + (mCenter.y - aBStart) * 2 - 1 : aBStart,
bEndIsBelowOrAtCenter ? aBEnd : aBEnd + (mCenter.y - aBEnd) * 2 - 1);
MOZ_ASSERT(bSmallestWithinIntervals >= mCenter.y &&
bSmallestWithinIntervals < BEnd(),
"We should have a block value within the float area.");
size_t index =
MinIntervalIndexContainingY(mIntervals, bSmallestWithinIntervals);
if (index >= mIntervals.Length()) {
// This indicates that our intervals don't cover the block value
// bSmallestWithinIntervals. This can happen when rounding error in the
// distance field calculation resulted in the last block pixel row not
// contributing to the float area. As long as we're within one block pixel
// past the last interval, this is an expected outcome.
#ifdef DEBUG
nscoord onePixelPastLastInterval =
mIntervals[mIntervals.Length() - 1].YMost() +
mIntervals[mIntervals.Length() - 1].Height();
NS_WARNING_ASSERTION(bSmallestWithinIntervals < onePixelPastLastInterval,
"We should have found a matching interval for this "
"block value.");
#endif
return aIsLineLeft ? nscoord_MAX : nscoord_MIN;
}
// The interval is storing the line right value. If aIsLineLeft is true,
// return the line right value reflected about the center. Since this is
// an inline measurement, it's just checking the distance to an edge, and
// not a collision with a specific pixel. For that reason, we don't need
// to subtract 1 from the reflection, as we did with the block reflection.
nscoord iLineRight = mIntervals[index].XMost();
return aIsLineLeft ? iLineRight - (iLineRight - mCenter.x) * 2 : iLineRight;
}
nscoord nsFloatManager::EllipseShapeInfo::LineLeft(const nscoord aBStart,
const nscoord aBEnd) const {
return LineEdge(aBStart, aBEnd, true);
}
nscoord nsFloatManager::EllipseShapeInfo::LineRight(const nscoord aBStart,
const nscoord aBEnd) const {
return LineEdge(aBStart, aBEnd, false);
}
/////////////////////////////////////////////////////////////////////////////
// RoundedBoxShapeInfo
//
// Implements shape-outside: <shape-box> and shape-outside: inset().
//
class nsFloatManager::RoundedBoxShapeInfo final
: public nsFloatManager::ShapeInfo {
public:
RoundedBoxShapeInfo(const nsRect& aRect, UniquePtr<nscoord[]> aRadii)
: mRect(aRect), mRadii(std::move(aRadii)), mShapeMargin(0) {}
RoundedBoxShapeInfo(const nsRect& aRect, UniquePtr<nscoord[]> aRadii,
nscoord aShapeMargin, int32_t aAppUnitsPerDevPixel);
nscoord LineLeft(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord LineRight(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord BStart() const override { return mRect.y; }
nscoord BEnd() const override { return mRect.YMost(); }
bool IsEmpty() const override {
// A RoundedBoxShapeInfo is never empty, because if it is collapsed to
// zero area, it acts like a point. If it is collapsed further, to become
// inside-out, it acts like a rect in the same shape as the inside-out
// rect.
return false;
}
bool MayNarrowInBlockDirection() const override {
// Only possible to narrow if there are non-null mRadii.
return !!mRadii;
}
void Translate(nscoord aLineLeft, nscoord aBlockStart) override {
mRect.MoveBy(aLineLeft, aBlockStart);
if (mShapeMargin > 0) {
MOZ_ASSERT(mLogicalTopLeftCorner && mLogicalTopRightCorner &&
mLogicalBottomLeftCorner && mLogicalBottomRightCorner,
"If we have positive shape-margin, we should have corners.");
mLogicalTopLeftCorner->Translate(aLineLeft, aBlockStart);
mLogicalTopRightCorner->Translate(aLineLeft, aBlockStart);
mLogicalBottomLeftCorner->Translate(aLineLeft, aBlockStart);
mLogicalBottomRightCorner->Translate(aLineLeft, aBlockStart);
}
}
static bool EachCornerHasBalancedRadii(const nscoord* aRadii) {
return (aRadii[eCornerTopLeftX] == aRadii[eCornerTopLeftY] &&
aRadii[eCornerTopRightX] == aRadii[eCornerTopRightY] &&
aRadii[eCornerBottomLeftX] == aRadii[eCornerBottomLeftY] &&
aRadii[eCornerBottomRightX] == aRadii[eCornerBottomRightY]);
}
private:
// The rect of the rounded box shape in the float manager's coordinate
// space.
nsRect mRect;
// The half corner radii of the reference box. It's an nscoord[8] array
// in the float manager's coordinate space. If there are no radii, it's
// nullptr.
const UniquePtr<nscoord[]> mRadii;
// A shape-margin value extends the boundaries of the float area. When our
// first constructor is used, it is for the creation of rounded boxes that
// can ignore shape-margin -- either because it was specified as zero or
// because the box shape and radii can be inflated to account for it. When
// our second constructor is used, we store the shape-margin value here.
const nscoord mShapeMargin;
// If our second constructor is called (which implies mShapeMargin > 0),
// we will construct EllipseShapeInfo objects for each corner. We use the
// float logical naming here, where LogicalTopLeftCorner means the BStart
// LineLeft corner, and similarly for the other corners.
UniquePtr<EllipseShapeInfo> mLogicalTopLeftCorner;
UniquePtr<EllipseShapeInfo> mLogicalTopRightCorner;
UniquePtr<EllipseShapeInfo> mLogicalBottomLeftCorner;
UniquePtr<EllipseShapeInfo> mLogicalBottomRightCorner;
};
nsFloatManager::RoundedBoxShapeInfo::RoundedBoxShapeInfo(
const nsRect& aRect, UniquePtr<nscoord[]> aRadii, nscoord aShapeMargin,
int32_t aAppUnitsPerDevPixel)
: mRect(aRect), mRadii(std::move(aRadii)), mShapeMargin(aShapeMargin) {
MOZ_ASSERT(mShapeMargin > 0 && !EachCornerHasBalancedRadii(mRadii.get()),
"Slow constructor should only be used for for shape-margin > 0 "
"and radii with elliptical corners.");
// Before we inflate mRect by mShapeMargin, construct each of our corners.
// If we do it in this order, it's a bit simpler to calculate the center
// of each of the corners.
mLogicalTopLeftCorner = MakeUnique<EllipseShapeInfo>(
nsPoint(mRect.X() + mRadii[eCornerTopLeftX],
mRect.Y() + mRadii[eCornerTopLeftY]),
nsSize(mRadii[eCornerTopLeftX], mRadii[eCornerTopLeftY]), mShapeMargin,
aAppUnitsPerDevPixel);
mLogicalTopRightCorner = MakeUnique<EllipseShapeInfo>(
nsPoint(mRect.XMost() - mRadii[eCornerTopRightX],
mRect.Y() + mRadii[eCornerTopRightY]),
nsSize(mRadii[eCornerTopRightX], mRadii[eCornerTopRightY]), mShapeMargin,
aAppUnitsPerDevPixel);
mLogicalBottomLeftCorner = MakeUnique<EllipseShapeInfo>(
nsPoint(mRect.X() + mRadii[eCornerBottomLeftX],
mRect.YMost() - mRadii[eCornerBottomLeftY]),
nsSize(mRadii[eCornerBottomLeftX], mRadii[eCornerBottomLeftY]),
mShapeMargin, aAppUnitsPerDevPixel);
mLogicalBottomRightCorner = MakeUnique<EllipseShapeInfo>(
nsPoint(mRect.XMost() - mRadii[eCornerBottomRightX],
mRect.YMost() - mRadii[eCornerBottomRightY]),
nsSize(mRadii[eCornerBottomRightX], mRadii[eCornerBottomRightY]),
mShapeMargin, aAppUnitsPerDevPixel);
// Now we inflate our mRect by mShapeMargin.
mRect.Inflate(mShapeMargin);
}
nscoord nsFloatManager::RoundedBoxShapeInfo::LineLeft(
const nscoord aBStart, const nscoord aBEnd) const {
if (mShapeMargin == 0) {
if (!mRadii) {
return mRect.x;
}
nscoord lineLeftDiff = ComputeEllipseLineInterceptDiff(
mRect.y, mRect.YMost(), mRadii[eCornerTopLeftX],
mRadii[eCornerTopLeftY], mRadii[eCornerBottomLeftX],
mRadii[eCornerBottomLeftY], aBStart, aBEnd);
return mRect.x + lineLeftDiff;
}
MOZ_ASSERT(mLogicalTopLeftCorner && mLogicalBottomLeftCorner,
"If we have positive shape-margin, we should have corners.");
// Determine if aBEnd is within our top corner.
if (aBEnd < mLogicalTopLeftCorner->BEnd()) {
return mLogicalTopLeftCorner->LineLeft(aBStart, aBEnd);
}
// Determine if aBStart is within our bottom corner.
if (aBStart >= mLogicalBottomLeftCorner->BStart()) {
return mLogicalBottomLeftCorner->LineLeft(aBStart, aBEnd);
}
// Either aBStart or aBEnd or both are within the flat part of our left
// edge. Because we've already inflated our mRect to encompass our
// mShapeMargin, we can just return the edge.
return mRect.X();
}
nscoord nsFloatManager::RoundedBoxShapeInfo::LineRight(
const nscoord aBStart, const nscoord aBEnd) const {
if (mShapeMargin == 0) {
if (!mRadii) {
return mRect.XMost();
}
nscoord lineRightDiff = ComputeEllipseLineInterceptDiff(
mRect.y, mRect.YMost(), mRadii[eCornerTopRightX],
mRadii[eCornerTopRightY], mRadii[eCornerBottomRightX],
mRadii[eCornerBottomRightY], aBStart, aBEnd);
return mRect.XMost() - lineRightDiff;
}
MOZ_ASSERT(mLogicalTopRightCorner && mLogicalBottomRightCorner,
"If we have positive shape-margin, we should have corners.");
// Determine if aBEnd is within our top corner.
if (aBEnd < mLogicalTopRightCorner->BEnd()) {
return mLogicalTopRightCorner->LineRight(aBStart, aBEnd);
}
// Determine if aBStart is within our bottom corner.
if (aBStart >= mLogicalBottomRightCorner->BStart()) {
return mLogicalBottomRightCorner->LineRight(aBStart, aBEnd);
}
// Either aBStart or aBEnd or both are within the flat part of our right
// edge. Because we've already inflated our mRect to encompass our
// mShapeMargin, we can just return the edge.
return mRect.XMost();
}
/////////////////////////////////////////////////////////////////////////////
// PolygonShapeInfo
//
// Implements shape-outside: polygon().
//
class nsFloatManager::PolygonShapeInfo final
: public nsFloatManager::ShapeInfo {
public:
explicit PolygonShapeInfo(nsTArray<nsPoint>&& aVertices);
PolygonShapeInfo(nsTArray<nsPoint>&& aVertices, nscoord aShapeMargin,
int32_t aAppUnitsPerDevPixel, const nsRect& aMarginRect);
nscoord LineLeft(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord LineRight(const nscoord aBStart, const nscoord aBEnd) const override;
nscoord BStart() const override { return mBStart; }
nscoord BEnd() const override { return mBEnd; }
bool IsEmpty() const override {
// A PolygonShapeInfo is never empty, because the parser prevents us from
// creating a shape with no vertices. If we only have 1 vertex, the
// shape acts like a point. With 2 non-coincident vertices, the shape
// acts like a line.
return false;
}
bool MayNarrowInBlockDirection() const override { return true; }
void Translate(nscoord aLineLeft, nscoord aBlockStart) override;
private:
// Helper method for determining the mBStart and mBEnd based on the
// vertices' y extent.
void ComputeExtent();
// Helper method for implementing LineLeft() and LineRight().
nscoord ComputeLineIntercept(
const nscoord aBStart, const nscoord aBEnd,
nscoord (*aCompareOp)(std::initializer_list<nscoord>),
const nscoord aLineInterceptInitialValue) const;
// Given a horizontal line y, and two points p1 and p2 forming a line
// segment L. Solve x for the intersection of y and L. This method
// assumes y and L do intersect, and L is *not* horizontal.
static nscoord XInterceptAtY(const nscoord aY, const nsPoint& aP1,
const nsPoint& aP2);
// The vertices of the polygon in the float manager's coordinate space.
nsTArray<nsPoint> mVertices;
// An interval is slice of the float area defined by this PolygonShapeInfo.
// These are only generated and used in float area calculations for
// shape-margin > 0. Each interval is a rectangle that is one device pixel
// deep in the block axis. The values are stored as block edges in the y
// coordinates, and inline edges as the x coordinates.
// The intervals are stored in ascending order on y.
nsTArray<nsRect> mIntervals;
// Computed block start and block end value of the polygon shape. These
// initial values are set to correct values in ComputeExtent(), which is
// called from all constructors. Afterwards, mBStart is guaranteed to be
// less than or equal to mBEnd.
nscoord mBStart = nscoord_MAX;
nscoord mBEnd = nscoord_MIN;
};
nsFloatManager::PolygonShapeInfo::PolygonShapeInfo(
nsTArray<nsPoint>&& aVertices)
: mVertices(std::move(aVertices)) {
ComputeExtent();
}
nsFloatManager::PolygonShapeInfo::PolygonShapeInfo(
nsTArray<nsPoint>&& aVertices, nscoord aShapeMargin,
int32_t aAppUnitsPerDevPixel, const nsRect& aMarginRect)
: mVertices(std::move(aVertices)) {