Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=4 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/. */
#include "gfxTextRun.h"
#include "gfxGlyphExtents.h"
#include "gfxHarfBuzzShaper.h"
#include "gfxPlatformFontList.h"
#include "gfxUserFontSet.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/PathHelpers.h"
#include "mozilla/Sprintf.h"
#include "gfxContext.h"
#include "gfxFontConstants.h"
#include "gfxFontMissingGlyphs.h"
#include "gfxScriptItemizer.h"
#include "nsUnicodeProperties.h"
#include "nsStyleConsts.h"
#include "nsStyleUtil.h"
#include "mozilla/Likely.h"
#include "gfx2DGlue.h"
#include "mozilla/gfx/Logging.h" // for gfxCriticalError
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "SharedFontList-impl.h"
#include "TextDrawTarget.h"
#include <unicode/unorm2.h>
#ifdef XP_WIN
# include "gfxWindowsPlatform.h"
#endif
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;
using mozilla::services::GetObserverService;
static const char16_t kEllipsisChar[] = {0x2026, 0x0};
static const char16_t kASCIIPeriodsChar[] = {'.', '.', '.', 0x0};
#ifdef DEBUG_roc
# define DEBUG_TEXT_RUN_STORAGE_METRICS
#endif
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
extern uint32_t gTextRunStorageHighWaterMark;
extern uint32_t gTextRunStorage;
extern uint32_t gFontCount;
extern uint32_t gGlyphExtentsCount;
extern uint32_t gGlyphExtentsWidthsTotalSize;
extern uint32_t gGlyphExtentsSetupEagerSimple;
extern uint32_t gGlyphExtentsSetupEagerTight;
extern uint32_t gGlyphExtentsSetupLazyTight;
extern uint32_t gGlyphExtentsSetupFallBackToTight;
#endif
bool gfxTextRun::GlyphRunIterator::NextRun() {
int32_t glyphRunCount;
if (mTextRun->mHasGlyphRunArray) {
glyphRunCount = mTextRun->mGlyphRunArray.Length();
if (mNextIndex >= glyphRunCount || mNextIndex < 0) {
return false;
}
mGlyphRun = &mTextRun->mGlyphRunArray[mNextIndex];
} else {
if (mNextIndex != 0 || !mTextRun->mSingleGlyphRun.mFont) {
return false;
}
glyphRunCount = 1;
mGlyphRun = &mTextRun->mSingleGlyphRun;
}
if (mGlyphRun->mCharacterOffset >= mEndOffset) {
return false;
}
uint32_t glyphRunEndOffset =
mNextIndex + 1 < (int32_t)glyphRunCount
? mTextRun->mGlyphRunArray[mNextIndex + 1].mCharacterOffset
: mTextRun->GetLength();
if (glyphRunEndOffset <= mStartOffset) {
return false;
}
mStringEnd = std::min(mEndOffset, glyphRunEndOffset);
mStringStart = std::max(mStartOffset, mGlyphRun->mCharacterOffset);
mNextIndex += mDirection;
return true;
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
static void AccountStorageForTextRun(gfxTextRun* aTextRun, int32_t aSign) {
// Ignores detailed glyphs... we don't know when those have been constructed
// Also ignores gfxSkipChars dynamic storage (which won't be anything
// for preformatted text)
// Also ignores GlyphRun array, again because it hasn't been constructed
// by the time this gets called. If there's only one glyphrun that's stored
// directly in the textrun anyway so no additional overhead.
uint32_t length = aTextRun->GetLength();
int32_t bytes = length * sizeof(gfxTextRun::CompressedGlyph);
bytes += sizeof(gfxTextRun);
gTextRunStorage += bytes * aSign;
gTextRunStorageHighWaterMark =
std::max(gTextRunStorageHighWaterMark, gTextRunStorage);
}
#endif
static bool NeedsGlyphExtents(gfxTextRun* aTextRun) {
if (aTextRun->GetFlags() & gfx::ShapedTextFlags::TEXT_NEED_BOUNDING_BOX)
return true;
uint32_t numRuns;
const gfxTextRun::GlyphRun* glyphRuns = aTextRun->GetGlyphRuns(&numRuns);
for (uint32_t i = 0; i < numRuns; ++i) {
if (glyphRuns[i].mFont->GetFontEntry()->IsUserFont()) return true;
}
return false;
}
// Helper for textRun creation to preallocate storage for glyph records;
// this function returns a pointer to the newly-allocated glyph storage.
// Returns nullptr if allocation fails.
void* gfxTextRun::AllocateStorageForTextRun(size_t aSize, uint32_t aLength) {
// Allocate the storage we need, returning nullptr on failure rather than
// throwing an exception (because web content can create huge runs).
void* storage = malloc(aSize + aLength * sizeof(CompressedGlyph));
if (!storage) {
NS_WARNING("failed to allocate storage for text run!");
return nullptr;
}
// Initialize the glyph storage (beyond aSize) to zero
memset(reinterpret_cast<char*>(storage) + aSize, 0,
aLength * sizeof(CompressedGlyph));
return storage;
}
already_AddRefed<gfxTextRun> gfxTextRun::Create(
const gfxTextRunFactory::Parameters* aParams, uint32_t aLength,
gfxFontGroup* aFontGroup, gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2) {
void* storage = AllocateStorageForTextRun(sizeof(gfxTextRun), aLength);
if (!storage) {
return nullptr;
}
RefPtr<gfxTextRun> result =
new (storage) gfxTextRun(aParams, aLength, aFontGroup, aFlags, aFlags2);
return result.forget();
}
gfxTextRun::gfxTextRun(const gfxTextRunFactory::Parameters* aParams,
uint32_t aLength, gfxFontGroup* aFontGroup,
gfx::ShapedTextFlags aFlags,
nsTextFrameUtils::Flags aFlags2)
: gfxShapedText(aLength, aFlags, aParams->mAppUnitsPerDevUnit),
mSingleGlyphRun(),
mUserData(aParams->mUserData),
mFontGroup(aFontGroup),
mFlags2(aFlags2),
mReleasedFontGroup(false),
mReleasedFontGroupSkippedDrawing(false),
mHasGlyphRunArray(false),
mShapingState(eShapingState_Normal) {
NS_ASSERTION(mAppUnitsPerDevUnit > 0, "Invalid app unit scale");
NS_ADDREF(mFontGroup);
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = aFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunConst++;
}
#endif
mCharacterGlyphs = reinterpret_cast<CompressedGlyph*>(this + 1);
if (aParams->mSkipChars) {
mSkipChars.TakeFrom(aParams->mSkipChars);
}
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, 1);
#endif
mDontSkipDrawing =
!!(aFlags2 & nsTextFrameUtils::Flags::DontSkipDrawingForPendingUserFonts);
}
gfxTextRun::~gfxTextRun() {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
AccountStorageForTextRun(this, -1);
#endif
#ifdef DEBUG
// Make it easy to detect a dead text run
mFlags = ~gfx::ShapedTextFlags();
mFlags2 = ~nsTextFrameUtils::Flags();
#endif
if (mHasGlyphRunArray) {
mGlyphRunArray.~nsTArray<GlyphRun>();
} else {
mSingleGlyphRun.mFont = nullptr;
}
// The cached ellipsis textrun (if any) in a fontgroup will have already
// been told to release its reference to the group, so we mustn't do that
// again here.
if (!mReleasedFontGroup) {
#ifndef RELEASE_OR_BETA
gfxTextPerfMetrics* tp = mFontGroup->GetTextPerfMetrics();
if (tp) {
tp->current.textrunDestr++;
}
#endif
NS_RELEASE(mFontGroup);
}
}
void gfxTextRun::ReleaseFontGroup() {
NS_ASSERTION(!mReleasedFontGroup, "doubly released!");
// After dropping our reference to the font group, we'll no longer be able
// to get up-to-date results for ShouldSkipDrawing(). Store the current
// value in mReleasedFontGroupSkippedDrawing.
//
// (It doesn't actually matter that we can't get up-to-date results for
// ShouldSkipDrawing(), since the only text runs that we call
// ReleaseFontGroup() for are ellipsis text runs, and we ask the font
// group for a new ellipsis text run each time we want to draw one,
// and ensure that the cached one is cleared in ClearCachedData() when
// font loading status changes.)
mReleasedFontGroupSkippedDrawing = mFontGroup->ShouldSkipDrawing();
NS_RELEASE(mFontGroup);
mReleasedFontGroup = true;
}
bool gfxTextRun::SetPotentialLineBreaks(Range aRange,
const uint8_t* aBreakBefore) {
NS_ASSERTION(aRange.end <= GetLength(), "Overflow");
uint32_t changed = 0;
CompressedGlyph* cg = mCharacterGlyphs + aRange.start;
const CompressedGlyph* const end = cg + aRange.Length();
while (cg < end) {
uint8_t canBreak = *aBreakBefore++;
if (canBreak && !cg->IsClusterStart()) {
// XXX If we replace the line-breaker with one based more closely
// on UAX#14 (e.g. using ICU), this may not be needed any more.
// Avoid possible breaks inside a cluster, EXCEPT when the previous
// character was a space (compare UAX#14 rules LB9, LB10).
if (cg == mCharacterGlyphs || !(cg - 1)->CharIsSpace()) {
canBreak = CompressedGlyph::FLAG_BREAK_TYPE_NONE;
}
}
changed |= cg->SetCanBreakBefore(canBreak);
++cg;
}
return changed != 0;
}
gfxTextRun::LigatureData gfxTextRun::ComputeLigatureData(
Range aPartRange, PropertyProvider* aProvider) const {
NS_ASSERTION(aPartRange.start < aPartRange.end,
"Computing ligature data for empty range");
NS_ASSERTION(aPartRange.end <= GetLength(), "Character length overflow");
LigatureData result;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
uint32_t i;
for (i = aPartRange.start; !charGlyphs[i].IsLigatureGroupStart(); --i) {
NS_ASSERTION(i > 0, "Ligature at the start of the run??");
}
result.mRange.start = i;
for (i = aPartRange.start + 1;
i < GetLength() && !charGlyphs[i].IsLigatureGroupStart(); ++i) {
}
result.mRange.end = i;
int32_t ligatureWidth = GetAdvanceForGlyphs(result.mRange);
// Count the number of started clusters we have seen
uint32_t totalClusterCount = 0;
uint32_t partClusterIndex = 0;
uint32_t partClusterCount = 0;
for (i = result.mRange.start; i < result.mRange.end; ++i) {
// Treat the first character of the ligature as the start of a
// cluster for our purposes of allocating ligature width to its
// characters.
if (i == result.mRange.start || charGlyphs[i].IsClusterStart()) {
++totalClusterCount;
if (i < aPartRange.start) {
++partClusterIndex;
} else if (i < aPartRange.end) {
++partClusterCount;
}
}
}
NS_ASSERTION(totalClusterCount > 0, "Ligature involving no clusters??");
result.mPartAdvance = partClusterIndex * (ligatureWidth / totalClusterCount);
result.mPartWidth = partClusterCount * (ligatureWidth / totalClusterCount);
// Any rounding errors are apportioned to the final part of the ligature,
// so that measuring all parts of a ligature and summing them is equal to
// the ligature width.
if (aPartRange.end == result.mRange.end) {
gfxFloat allParts = totalClusterCount * (ligatureWidth / totalClusterCount);
result.mPartWidth += ligatureWidth - allParts;
}
if (partClusterCount == 0) {
// nothing to draw
result.mClipBeforePart = result.mClipAfterPart = true;
} else {
// Determine whether we should clip before or after this part when
// drawing its slice of the ligature.
// We need to clip before the part if any cluster is drawn before
// this part.
result.mClipBeforePart = partClusterIndex > 0;
// We need to clip after the part if any cluster is drawn after
// this part.
result.mClipAfterPart =
partClusterIndex + partClusterCount < totalClusterCount;
}
if (aProvider && (mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
gfxFont::Spacing spacing;
if (aPartRange.start == result.mRange.start) {
aProvider->GetSpacing(Range(aPartRange.start, aPartRange.start + 1),
&spacing);
result.mPartWidth += spacing.mBefore;
}
if (aPartRange.end == result.mRange.end) {
aProvider->GetSpacing(Range(aPartRange.end - 1, aPartRange.end),
&spacing);
result.mPartWidth += spacing.mAfter;
}
}
return result;
}
gfxFloat gfxTextRun::ComputePartialLigatureWidth(
Range aPartRange, PropertyProvider* aProvider) const {
if (aPartRange.start >= aPartRange.end) return 0;
LigatureData data = ComputeLigatureData(aPartRange, aProvider);
return data.mPartWidth;
}
int32_t gfxTextRun::GetAdvanceForGlyphs(Range aRange) const {
int32_t advance = 0;
for (auto i = aRange.start; i < aRange.end; ++i) {
advance += GetAdvanceForGlyph(i);
}
return advance;
}
static void GetAdjustedSpacing(
const gfxTextRun* aTextRun, gfxTextRun::Range aRange,
gfxTextRun::PropertyProvider* aProvider,
gfxTextRun::PropertyProvider::Spacing* aSpacing) {
if (aRange.start >= aRange.end) return;
aProvider->GetSpacing(aRange, aSpacing);
#ifdef DEBUG
// Check to see if we have spacing inside ligatures
const gfxTextRun::CompressedGlyph* charGlyphs =
aTextRun->GetCharacterGlyphs();
uint32_t i;
for (i = aRange.start; i < aRange.end; ++i) {
if (!charGlyphs[i].IsLigatureGroupStart()) {
NS_ASSERTION(i == aRange.start || aSpacing[i - aRange.start].mBefore == 0,
"Before-spacing inside a ligature!");
NS_ASSERTION(
i - 1 <= aRange.start || aSpacing[i - 1 - aRange.start].mAfter == 0,
"After-spacing inside a ligature!");
}
}
#endif
}
bool gfxTextRun::GetAdjustedSpacingArray(
Range aRange, PropertyProvider* aProvider, Range aSpacingRange,
nsTArray<PropertyProvider::Spacing>* aSpacing) const {
if (!aProvider || !(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
return false;
}
if (!aSpacing->AppendElements(aRange.Length(), fallible)) {
return false;
}
auto spacingOffset = aSpacingRange.start - aRange.start;
memset(aSpacing->Elements(), 0, sizeof(gfxFont::Spacing) * spacingOffset);
GetAdjustedSpacing(this, aSpacingRange, aProvider,
aSpacing->Elements() + spacingOffset);
memset(aSpacing->Elements() + aSpacingRange.end - aRange.start, 0,
sizeof(gfxFont::Spacing) * (aRange.end - aSpacingRange.end));
return true;
}
void gfxTextRun::ShrinkToLigatureBoundaries(Range* aRange) const {
if (aRange->start >= aRange->end) return;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
while (aRange->start < aRange->end &&
!charGlyphs[aRange->start].IsLigatureGroupStart()) {
++aRange->start;
}
if (aRange->end < GetLength()) {
while (aRange->end > aRange->start &&
!charGlyphs[aRange->end].IsLigatureGroupStart()) {
--aRange->end;
}
}
}
void gfxTextRun::DrawGlyphs(gfxFont* aFont, Range aRange, gfx::Point* aPt,
PropertyProvider* aProvider, Range aSpacingRange,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
aParams.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
aFont->Draw(this, aRange.start, aRange.end, aPt, aParams, aOrientation);
}
static void ClipPartialLigature(const gfxTextRun* aTextRun, gfxFloat* aStart,
gfxFloat* aEnd, gfxFloat aOrigin,
gfxTextRun::LigatureData* aLigature) {
if (aLigature->mClipBeforePart) {
if (aTextRun->IsRightToLeft()) {
*aEnd = std::min(*aEnd, aOrigin);
} else {
*aStart = std::max(*aStart, aOrigin);
}
}
if (aLigature->mClipAfterPart) {
gfxFloat endEdge =
aOrigin + aTextRun->GetDirection() * aLigature->mPartWidth;
if (aTextRun->IsRightToLeft()) {
*aStart = std::max(*aStart, endEdge);
} else {
*aEnd = std::min(*aEnd, endEdge);
}
}
}
void gfxTextRun::DrawPartialLigature(gfxFont* aFont, Range aRange,
gfx::Point* aPt,
PropertyProvider* aProvider,
TextRunDrawParams& aParams,
gfx::ShapedTextFlags aOrientation) const {
if (aRange.start >= aRange.end) {
return;
}
// Draw partial ligature. We hack this by clipping the ligature.
LigatureData data = ComputeLigatureData(aRange, aProvider);
gfxRect clipExtents = aParams.context->GetClipExtents();
gfxFloat start, end;
if (aParams.isVerticalRun) {
start = clipExtents.Y() * mAppUnitsPerDevUnit;
end = clipExtents.YMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->y, &data);
} else {
start = clipExtents.X() * mAppUnitsPerDevUnit;
end = clipExtents.XMost() * mAppUnitsPerDevUnit;
ClipPartialLigature(this, &start, &end, aPt->x, &data);
}
{
// use division here to ensure that when the rect is aligned on multiples
// of mAppUnitsPerDevUnit, we clip to true device unit boundaries.
// Also, make sure we snap the rectangle to device pixels.
Rect clipRect =
aParams.isVerticalRun
? Rect(clipExtents.X(), start / mAppUnitsPerDevUnit,
clipExtents.Width(), (end - start) / mAppUnitsPerDevUnit)
: Rect(start / mAppUnitsPerDevUnit, clipExtents.Y(),
(end - start) / mAppUnitsPerDevUnit, clipExtents.Height());
MaybeSnapToDevicePixels(clipRect, *aParams.dt, true);
aParams.context->Clip(clipRect);
}
gfx::Point pt;
if (aParams.isVerticalRun) {
pt = Point(aPt->x, aPt->y - aParams.direction * data.mPartAdvance);
} else {
pt = Point(aPt->x - aParams.direction * data.mPartAdvance, aPt->y);
}
DrawGlyphs(aFont, data.mRange, &pt, aProvider, aRange, aParams, aOrientation);
aParams.context->PopClip();
if (aParams.isVerticalRun) {
aPt->y += aParams.direction * data.mPartWidth;
} else {
aPt->x += aParams.direction * data.mPartWidth;
}
}
// Returns true if the font has synthetic bolding enabled,
// or is a color font (COLR/SVG/sbix/CBDT), false otherwise. This is used to
// check whether the text run needs to be explicitly composited in order to
// support opacity.
static bool HasSyntheticBoldOrColor(gfxFont* aFont) {
if (aFont->IsSyntheticBold()) {
return true;
}
gfxFontEntry* fe = aFont->GetFontEntry();
if (fe->TryGetSVGData(aFont) || fe->TryGetColorGlyphs()) {
return true;
}
#if defined(XP_MACOSX) // sbix fonts only supported via Core Text
if (fe->HasFontTable(TRUETYPE_TAG('s', 'b', 'i', 'x'))) {
return true;
}
#endif
return false;
}
// helper class for double-buffering drawing with non-opaque color
struct MOZ_STACK_CLASS BufferAlphaColor {
explicit BufferAlphaColor(gfxContext* aContext) : mContext(aContext) {}
~BufferAlphaColor() = default;
void PushSolidColor(const gfxRect& aBounds, const DeviceColor& aAlphaColor,
uint32_t appsPerDevUnit) {
mContext->Save();
mContext->SnappedClip(gfxRect(
aBounds.X() / appsPerDevUnit, aBounds.Y() / appsPerDevUnit,
aBounds.Width() / appsPerDevUnit, aBounds.Height() / appsPerDevUnit));
mContext->SetDeviceColor(
DeviceColor(aAlphaColor.r, aAlphaColor.g, aAlphaColor.b));
mContext->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, aAlphaColor.a);
}
void PopAlpha() {
// pop the text, using the color alpha as the opacity
mContext->PopGroupAndBlend();
mContext->Restore();
}
gfxContext* mContext;
};
void gfxTextRun::Draw(const Range aRange, const gfx::Point aPt,
const DrawParams& aParams) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH ||
!(aParams.drawMode & DrawMode::GLYPH_PATH),
"GLYPH_PATH cannot be used with GLYPH_FILL, GLYPH_STROKE or "
"GLYPH_STROKE_UNDERNEATH");
NS_ASSERTION(aParams.drawMode == DrawMode::GLYPH_PATH || !aParams.callbacks,
"callback must not be specified unless using GLYPH_PATH");
bool skipDrawing =
!mDontSkipDrawing && (mFontGroup ? mFontGroup->ShouldSkipDrawing()
: mReleasedFontGroupSkippedDrawing);
if (aParams.drawMode & DrawMode::GLYPH_FILL) {
DeviceColor currentColor;
if (aParams.context->GetDeviceColor(currentColor) && currentColor.a == 0 &&
!aParams.context->GetTextDrawer()) {
skipDrawing = true;
}
}
gfxFloat direction = GetDirection();
if (skipDrawing) {
// We don't need to draw anything;
// but if the caller wants advance width, we need to compute it here
if (aParams.advanceWidth) {
gfxTextRun::Metrics metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
*aParams.advanceWidth = metrics.mAdvanceWidth * direction;
}
// return without drawing
return;
}
// synthetic bolding draws glyphs twice ==> colors with opacity won't draw
// correctly unless first drawn without alpha
BufferAlphaColor syntheticBoldBuffer(aParams.context);
DeviceColor currentColor;
bool mayNeedBuffering =
aParams.drawMode & DrawMode::GLYPH_FILL &&
aParams.context->HasNonOpaqueNonTransparentColor(currentColor) &&
!aParams.context->GetTextDrawer();
// If we need to double-buffer, we'll need to measure the text first to
// get the bounds of the area of interest. Ideally we'd do that just for
// the specific glyph run(s) that need buffering, but because of bug
// 1612610 we currently use the extent of the entire range even when
// just buffering a subrange. So we'll measure the full range once and
// keep the metrics on hand for any subsequent subranges.
gfxTextRun::Metrics metrics;
bool gotMetrics = false;
// Set up parameters that will be constant across all glyph runs we need
// to draw, regardless of the font used.
TextRunDrawParams params;
params.context = aParams.context;
params.devPerApp = 1.0 / double(GetAppUnitsPerDevUnit());
params.isVerticalRun = IsVertical();
params.isRTL = IsRightToLeft();
params.direction = direction;
params.strokeOpts = aParams.strokeOpts;
params.textStrokeColor = aParams.textStrokeColor;
params.textStrokePattern = aParams.textStrokePattern;
params.drawOpts = aParams.drawOpts;
params.drawMode = aParams.drawMode;
params.callbacks = aParams.callbacks;
params.runContextPaint = aParams.contextPaint;
params.paintSVGGlyphs =
!aParams.callbacks || aParams.callbacks->mShouldPaintSVGGlyphs;
params.dt = aParams.context->GetDrawTarget();
GlyphRunIterator iter(this, aRange);
gfxFloat advance = 0.0;
gfx::Point pt = aPt;
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
Range runRange(iter.GetStringStart(), iter.GetStringEnd());
bool needToRestore = false;
if (mayNeedBuffering && HasSyntheticBoldOrColor(font)) {
needToRestore = true;
if (!gotMetrics) {
// Measure text; use the bounding box to determine the area we need
// to buffer. We measure the entire range, rather than just the glyph
// run that we're actually handling, because of bug 1612610: if the
// bounding box passed to PushSolidColor does not intersect the
// drawTarget's current clip, the skia backend fails to clip properly.
// This means we may use a larger buffer than actually needed, but is
// otherwise harmless.
metrics =
MeasureText(aRange, gfxFont::LOOSE_INK_EXTENTS,
aParams.context->GetDrawTarget(), aParams.provider);
if (IsRightToLeft()) {
metrics.mBoundingBox.MoveBy(
gfxPoint(aPt.x - metrics.mAdvanceWidth, aPt.y));
} else {
metrics.mBoundingBox.MoveBy(gfxPoint(aPt.x, aPt.y));
}
gotMetrics = true;
}
syntheticBoldBuffer.PushSolidColor(metrics.mBoundingBox, currentColor,
GetAppUnitsPerDevUnit());
}
Range ligatureRange(runRange);
ShrinkToLigatureBoundaries(&ligatureRange);
bool drawPartial =
(aParams.drawMode & (DrawMode::GLYPH_FILL | DrawMode::GLYPH_STROKE)) ||
(aParams.drawMode == DrawMode::GLYPH_PATH && aParams.callbacks);
gfx::Point origPt = pt;
if (drawPartial) {
DrawPartialLigature(font, Range(runRange.start, ligatureRange.start), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
DrawGlyphs(font, ligatureRange, &pt, aParams.provider, ligatureRange,
params, iter.GetGlyphRun()->mOrientation);
if (drawPartial) {
DrawPartialLigature(font, Range(ligatureRange.end, runRange.end), &pt,
aParams.provider, params,
iter.GetGlyphRun()->mOrientation);
}
if (params.isVerticalRun) {
advance += (pt.y - origPt.y) * params.direction;
} else {
advance += (pt.x - origPt.x) * params.direction;
}
// composite result when synthetic bolding used
if (needToRestore) {
syntheticBoldBuffer.PopAlpha();
}
}
if (aParams.advanceWidth) {
*aParams.advanceWidth = advance;
}
}
// This method is mostly parallel to Draw().
void gfxTextRun::DrawEmphasisMarks(gfxContext* aContext, gfxTextRun* aMark,
gfxFloat aMarkAdvance, gfx::Point aPt,
Range aRange,
PropertyProvider* aProvider) const {
MOZ_ASSERT(aRange.end <= GetLength());
EmphasisMarkDrawParams params;
params.context = aContext;
params.mark = aMark;
params.advance = aMarkAdvance;
params.direction = GetDirection();
params.isVertical = IsVertical();
float& inlineCoord = params.isVertical ? aPt.y : aPt.x;
float direction = params.direction;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
inlineCoord +=
direction * ComputePartialLigatureWidth(
Range(start, ligatureRange.start), aProvider);
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing = GetAdjustedSpacingArray(ligatureRange, aProvider,
ligatureRange, &spacingBuffer);
params.spacing = haveSpacing ? spacingBuffer.Elements() : nullptr;
font->DrawEmphasisMarks(this, &aPt, ligatureRange.start,
ligatureRange.Length(), params);
inlineCoord += direction * ComputePartialLigatureWidth(
Range(ligatureRange.end, end), aProvider);
}
}
void gfxTextRun::AccumulateMetricsForRun(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
Range aSpacingRange, gfx::ShapedTextFlags aOrientation,
Metrics* aMetrics) const {
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
bool haveSpacing =
GetAdjustedSpacingArray(aRange, aProvider, aSpacingRange, &spacingBuffer);
Metrics metrics = aFont->Measure(
this, aRange.start, aRange.end, aBoundingBoxType, aRefDrawTarget,
haveSpacing ? spacingBuffer.Elements() : nullptr, aOrientation);
aMetrics->CombineWith(metrics, IsRightToLeft());
}
void gfxTextRun::AccumulatePartialLigatureMetrics(
gfxFont* aFont, Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider,
gfx::ShapedTextFlags aOrientation, Metrics* aMetrics) const {
if (aRange.start >= aRange.end) return;
// Measure partial ligature. We hack this by clipping the metrics in the
// same way we clip the drawing.
LigatureData data = ComputeLigatureData(aRange, aProvider);
// First measure the complete ligature
Metrics metrics;
AccumulateMetricsForRun(aFont, data.mRange, aBoundingBoxType, aRefDrawTarget,
aProvider, aRange, aOrientation, &metrics);
// Clip the bounding box to the ligature part
gfxFloat bboxLeft = metrics.mBoundingBox.X();
gfxFloat bboxRight = metrics.mBoundingBox.XMost();
// Where we are going to start "drawing" relative to our left baseline origin
gfxFloat origin =
IsRightToLeft() ? metrics.mAdvanceWidth - data.mPartAdvance : 0;
ClipPartialLigature(this, &bboxLeft, &bboxRight, origin, &data);
metrics.mBoundingBox.SetBoxX(bboxLeft, bboxRight);
// mBoundingBox is now relative to the left baseline origin for the entire
// ligature. Shift it left.
metrics.mBoundingBox.MoveByX(
-(IsRightToLeft()
? metrics.mAdvanceWidth - (data.mPartAdvance + data.mPartWidth)
: data.mPartAdvance));
metrics.mAdvanceWidth = data.mPartWidth;
aMetrics->CombineWith(metrics, IsRightToLeft());
}
gfxTextRun::Metrics gfxTextRun::MeasureText(
Range aRange, gfxFont::BoundingBoxType aBoundingBoxType,
DrawTarget* aRefDrawTarget, PropertyProvider* aProvider) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
Metrics accumulatedMetrics;
GlyphRunIterator iter(this, aRange);
while (iter.NextRun()) {
gfxFont* font = iter.GetGlyphRun()->mFont;
uint32_t start = iter.GetStringStart();
uint32_t end = iter.GetStringEnd();
Range ligatureRange(start, end);
ShrinkToLigatureBoundaries(&ligatureRange);
AccumulatePartialLigatureMetrics(
font, Range(start, ligatureRange.start), aBoundingBoxType,
aRefDrawTarget, aProvider, iter.GetGlyphRun()->mOrientation,
&accumulatedMetrics);
// XXX This sucks. We have to get glyph extents just so we can detect
// glyphs outside the font box, even when aBoundingBoxType is LOOSE,
// even though in almost all cases we could get correct results just
// by getting some ascent/descent from the font and using our stored
// advance widths.
AccumulateMetricsForRun(
font, ligatureRange, aBoundingBoxType, aRefDrawTarget, aProvider,
ligatureRange, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
AccumulatePartialLigatureMetrics(
font, Range(ligatureRange.end, end), aBoundingBoxType, aRefDrawTarget,
aProvider, iter.GetGlyphRun()->mOrientation, &accumulatedMetrics);
}
return accumulatedMetrics;
}
#define MEASUREMENT_BUFFER_SIZE 100
void gfxTextRun::ClassifyAutoHyphenations(uint32_t aStart, Range aRange,
nsTArray<HyphenType>& aHyphenBuffer,
HyphenationState* aWordState) {
MOZ_ASSERT(
aRange.end - aStart <= aHyphenBuffer.Length() && aRange.start >= aStart,
"Range out of bounds");
MOZ_ASSERT(aWordState->mostRecentBoundary >= aStart,
"Unexpected aMostRecentWordBoundary!!");
uint32_t start =
std::min<uint32_t>(aRange.start, aWordState->mostRecentBoundary);
for (uint32_t i = start; i < aRange.end; ++i) {
if (aHyphenBuffer[i - aStart] == HyphenType::Explicit &&
!aWordState->hasExplicitHyphen) {
aWordState->hasExplicitHyphen = true;
}
if (!aWordState->hasManualHyphen &&
(aHyphenBuffer[i - aStart] == HyphenType::Soft ||
aHyphenBuffer[i - aStart] == HyphenType::Explicit)) {
aWordState->hasManualHyphen = true;
// This is the first manual hyphen in the current word. We can only
// know if the current word has a manual hyphen until now. So, we need
// to run a sub loop to update the auto hyphens between the start of
// the current word and this manual hyphen.
if (aWordState->hasAutoHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j < i; j++) {
if (aHyphenBuffer[j - aStart] ==
HyphenType::AutoWithoutManualInSameWord) {
aHyphenBuffer[j - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
}
}
if (aHyphenBuffer[i - aStart] == HyphenType::AutoWithoutManualInSameWord) {
if (!aWordState->hasAutoHyphen) {
aWordState->hasAutoHyphen = true;
}
if (aWordState->hasManualHyphen) {
aHyphenBuffer[i - aStart] = HyphenType::AutoWithManualInSameWord;
}
}
// If we're at the word boundary, clear/reset couple states.
if (mCharacterGlyphs[i].CharIsSpace() || mCharacterGlyphs[i].CharIsTab() ||
mCharacterGlyphs[i].CharIsNewline() ||
// Since we will not have a boundary in the end of the string, let's
// call the end of the string a special case for word boundary.
i == GetLength() - 1) {
// We can only get to know whether we should raise/clear an explicit
// manual hyphen until we get to the end of a word, because this depends
// on whether there exists at least one auto hyphen in the same word.
if (!aWordState->hasAutoHyphen && aWordState->hasExplicitHyphen) {
for (uint32_t j = aWordState->mostRecentBoundary; j <= i; j++) {
if (aHyphenBuffer[j - aStart] == HyphenType::Explicit) {
aHyphenBuffer[j - aStart] = HyphenType::None;
}
}
}
aWordState->mostRecentBoundary = i;
aWordState->hasManualHyphen = false;
aWordState->hasAutoHyphen = false;
aWordState->hasExplicitHyphen = false;
}
}
}
uint32_t gfxTextRun::BreakAndMeasureText(
uint32_t aStart, uint32_t aMaxLength, bool aLineBreakBefore,
gfxFloat aWidth, PropertyProvider* aProvider, SuppressBreak aSuppressBreak,
gfxFloat* aTrimWhitespace, bool aWhitespaceCanHang, Metrics* aMetrics,
gfxFont::BoundingBoxType aBoundingBoxType, DrawTarget* aRefDrawTarget,
bool* aUsedHyphenation, uint32_t* aLastBreak, bool aCanWordWrap,
bool aCanWhitespaceWrap, gfxBreakPriority* aBreakPriority) {
aMaxLength = std::min(aMaxLength, GetLength() - aStart);
NS_ASSERTION(aStart + aMaxLength <= GetLength(), "Substring out of range");
Range bufferRange(
aStart, aStart + std::min<uint32_t>(aMaxLength, MEASUREMENT_BUFFER_SIZE));
PropertyProvider::Spacing spacingBuffer[MEASUREMENT_BUFFER_SIZE];
bool haveSpacing =
aProvider && !!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING);
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
AutoTArray<HyphenType, 4096> hyphenBuffer;
HyphenationState wordState;
wordState.mostRecentBoundary = aStart;
bool haveHyphenation =
aProvider &&
(aProvider->GetHyphensOption() == StyleHyphens::Auto ||
(aProvider->GetHyphensOption() == StyleHyphens::Manual &&
!!(mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_HYPHEN_BREAKS)));
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(bufferRange, hyphenBuffer.Elements());
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer, &wordState);
}
} else {
haveHyphenation = false;
}
}
gfxFloat width = 0;
gfxFloat advance = 0;
// The number of space characters that can be trimmed or hang at a soft-wrap
uint32_t trimmableChars = 0;
// The amount of space removed by ignoring trimmableChars
gfxFloat trimmableAdvance = 0;
int32_t lastBreak = -1;
int32_t lastBreakTrimmableChars = -1;
gfxFloat lastBreakTrimmableAdvance = -1;
// Cache the last candidate break
int32_t lastCandidateBreak = -1;
int32_t lastCandidateBreakTrimmableChars = -1;
gfxFloat lastCandidateBreakTrimmableAdvance = -1;
bool lastCandidateBreakUsedHyphenation = false;
gfxBreakPriority lastCandidateBreakPriority = gfxBreakPriority::eNoBreak;
bool aborted = false;
uint32_t end = aStart + aMaxLength;
bool lastBreakUsedHyphenation = false;
Range ligatureRange(aStart, end);
ShrinkToLigatureBoundaries(&ligatureRange);
// We may need to move `i` backwards in the following loop, and re-scan
// part of the textrun; we'll use `rescanLimit` so we can tell when that
// is happening: if `i < rescanLimit` then we're rescanning.
uint32_t rescanLimit = aStart;
for (uint32_t i = aStart; i < end; ++i) {
if (i >= bufferRange.end) {
// Fetch more spacing and hyphenation data
uint32_t oldHyphenBufferLength = hyphenBuffer.Length();
bufferRange.start = i;
bufferRange.end =
std::min(aStart + aMaxLength, i + MEASUREMENT_BUFFER_SIZE);
// For spacing, we always overwrite the old data with the newly
// fetched one. However, for hyphenation, hyphenation data sometimes
// depends on the context in every word (if "hyphens: auto" is set).
// To ensure we get enough information between neighboring buffers,
// we grow the hyphenBuffer instead of overwrite it.
// NOTE that this means bufferRange does not correspond to the
// entire hyphenBuffer, but only to the most recently added portion.
// Therefore, we need to add the old length to hyphenBuffer.Elements()
// when getting more data.
if (haveSpacing) {
GetAdjustedSpacing(this, bufferRange, aProvider, spacingBuffer);
}
if (haveHyphenation) {
if (hyphenBuffer.AppendElements(bufferRange.Length(), fallible)) {
aProvider->GetHyphenationBreaks(
bufferRange, hyphenBuffer.Elements() + oldHyphenBufferLength);
if (aProvider->GetHyphensOption() == StyleHyphens::Auto) {
uint32_t prevMostRecentWordBoundary = wordState.mostRecentBoundary;
ClassifyAutoHyphenations(aStart, bufferRange, hyphenBuffer,
&wordState);
// If the buffer boundary is in the middle of a word,
// we need to go back to the start of the current word.
// So, we can correct the wrong candidates that we set
// in the previous runs of the loop.
if (prevMostRecentWordBoundary < oldHyphenBufferLength) {
rescanLimit = i;
i = prevMostRecentWordBoundary - 1;
continue;
}
}
} else {
haveHyphenation = false;
}
}
}
// There can't be a word-wrap break opportunity at the beginning of the
// line: if the width is too small for even one character to fit, it
// could be the first and last break opportunity on the line, and that
// would trigger an infinite loop.
if (aSuppressBreak != eSuppressAllBreaks &&
(aSuppressBreak != eSuppressInitialBreak || i > aStart)) {
bool atNaturalBreak = mCharacterGlyphs[i].CanBreakBefore() == 1;
// atHyphenationBreak indicates we're at a "soft" hyphen, where an extra
// hyphen glyph will need to be painted. It is NOT set for breaks at an
// explicit hyphen present in the text.
bool atHyphenationBreak = !atNaturalBreak && haveHyphenation &&
hyphenBuffer[i - aStart] > HyphenType::Explicit;
bool atAutoHyphenWithManualHyphenInSameWord =
atHyphenationBreak &&
hyphenBuffer[i - aStart] == HyphenType::AutoWithManualInSameWord;
bool atBreak = atNaturalBreak || atHyphenationBreak;
bool wordWrapping = aCanWordWrap &&
mCharacterGlyphs[i].IsClusterStart() &&
*aBreakPriority <= gfxBreakPriority::eWordWrapBreak;
bool whitespaceWrapping = false;
if (i > aStart) {
// The spec says the breaking opportunity is *after* whitespace.
auto const& g = mCharacterGlyphs[i - 1];
whitespaceWrapping =
aCanWhitespaceWrap &&
(g.CharIsSpace() || g.CharIsTab() || g.CharIsNewline());
}
if (atBreak || wordWrapping || whitespaceWrapping) {
gfxFloat hyphenatedAdvance = advance;
if (atHyphenationBreak) {
hyphenatedAdvance += aProvider->GetHyphenWidth();
}
if (lastBreak < 0 ||
width + hyphenatedAdvance - trimmableAdvance <= aWidth) {
// We can break here.
lastBreak = i;
lastBreakTrimmableChars = trimmableChars;
lastBreakTrimmableAdvance = trimmableAdvance;
lastBreakUsedHyphenation = atHyphenationBreak;
*aBreakPriority = (atBreak || whitespaceWrapping)
? gfxBreakPriority::eNormalBreak
: gfxBreakPriority::eWordWrapBreak;
}
width += advance;
advance = 0;
if (width - trimmableAdvance > aWidth) {
// No more text fits. Abort
aborted = true;
break;
}
// There are various kinds of break opportunities:
// 1. word wrap break,
// 2. natural break,
// 3. manual hyphenation break,
// 4. auto hyphenation break without any manual hyphenation
// in the same word,
// 5. auto hyphenation break with another manual hyphenation
// in the same word.
// Allow all of them except the last one to be a candidate.
// So, we can ensure that we don't use an automatic
// hyphenation opportunity within a word that contains another
// manual hyphenation, unless it is the only choice.
if (wordWrapping || !atAutoHyphenWithManualHyphenInSameWord) {
lastCandidateBreak = lastBreak;
lastCandidateBreakTrimmableChars = lastBreakTrimmableChars;
lastCandidateBreakTrimmableAdvance = lastBreakTrimmableAdvance;
lastCandidateBreakUsedHyphenation = lastBreakUsedHyphenation;
lastCandidateBreakPriority = *aBreakPriority;
}
}
}
// If we're re-scanning part of a word (to re-process potential
// hyphenation types) then we don't want to accumulate widths again
// for the characters that were already added to `advance`.
if (i < rescanLimit) {
continue;
}
gfxFloat charAdvance;
if (i >= ligatureRange.start && i < ligatureRange.end) {
charAdvance = GetAdvanceForGlyphs(Range(i, i + 1));
if (haveSpacing) {
PropertyProvider::Spacing* space =
&spacingBuffer[i - bufferRange.start];
charAdvance += space->mBefore + space->mAfter;
}
} else {
charAdvance = ComputePartialLigatureWidth(Range(i, i + 1), aProvider);
}
advance += charAdvance;
if (aTrimWhitespace || aWhitespaceCanHang) {
if (mCharacterGlyphs[i].CharIsSpace()) {
++trimmableChars;
trimmableAdvance += charAdvance;
} else {
trimmableAdvance = 0;
trimmableChars = 0;
}
}
}
if (!aborted) {
width += advance;
}
// There are three possibilities:
// 1) all the text fit (width <= aWidth)
// 2) some of the text fit up to a break opportunity (width > aWidth &&
// lastBreak >= 0)
// 3) none of the text fits before a break opportunity (width > aWidth &&
// lastBreak < 0)
uint32_t charsFit;
bool usedHyphenation = false;
if (width - trimmableAdvance <= aWidth) {
charsFit = aMaxLength;
} else if (lastBreak >= 0) {
if (lastCandidateBreak >= 0 && lastCandidateBreak != lastBreak) {
lastBreak = lastCandidateBreak;
lastBreakTrimmableChars = lastCandidateBreakTrimmableChars;
lastBreakTrimmableAdvance = lastCandidateBreakTrimmableAdvance;
lastBreakUsedHyphenation = lastCandidateBreakUsedHyphenation;
*aBreakPriority = lastCandidateBreakPriority;
}
charsFit = lastBreak - aStart;
trimmableChars = lastBreakTrimmableChars;
trimmableAdvance = lastBreakTrimmableAdvance;
usedHyphenation = lastBreakUsedHyphenation;
} else {
charsFit = aMaxLength;
}
if (aMetrics) {
auto fitEnd = aStart + charsFit;
// Initially, measure everything, so that our bounding box includes
// any trimmable or hanging whitespace.
*aMetrics = MeasureText(Range(aStart, fitEnd), aBoundingBoxType,
aRefDrawTarget, aProvider);
if (aTrimWhitespace || aWhitespaceCanHang) {
// Measure trailing whitespace that is to be trimmed/hung.
Metrics trimOrHangMetrics =
MeasureText(Range(fitEnd - trimmableChars, fitEnd), aBoundingBoxType,
aRefDrawTarget, aProvider);
if (aTrimWhitespace) {
aMetrics->mAdvanceWidth -= trimOrHangMetrics.mAdvanceWidth;
} else if (aMetrics->mAdvanceWidth > aWidth) {
// Restrict width of hanging whitespace so it doesn't overflow.
aMetrics->mAdvanceWidth = std::max(
aWidth, aMetrics->mAdvanceWidth - trimOrHangMetrics.mAdvanceWidth);
}
}
}
if (aTrimWhitespace) {
*aTrimWhitespace = trimmableAdvance;
}
if (aUsedHyphenation) {
*aUsedHyphenation = usedHyphenation;
}
if (aLastBreak && charsFit == aMaxLength) {
if (lastBreak < 0) {
*aLastBreak = UINT32_MAX;
} else {
*aLastBreak = lastBreak - aStart;
}
}
return charsFit;
}
gfxFloat gfxTextRun::GetAdvanceWidth(
Range aRange, PropertyProvider* aProvider,
PropertyProvider::Spacing* aSpacing) const {
NS_ASSERTION(aRange.end <= GetLength(), "Substring out of range");
Range ligatureRange = aRange;
ShrinkToLigatureBoundaries(&ligatureRange);
gfxFloat result = ComputePartialLigatureWidth(
Range(aRange.start, ligatureRange.start), aProvider) +
ComputePartialLigatureWidth(
Range(ligatureRange.end, aRange.end), aProvider);
if (aSpacing) {
aSpacing->mBefore = aSpacing->mAfter = 0;
}
// Account for all remaining spacing here. This is more efficient than
// processing it along with the glyphs.
if (aProvider && (mFlags & gfx::ShapedTextFlags::TEXT_ENABLE_SPACING)) {
uint32_t i;
AutoTArray<PropertyProvider::Spacing, 200> spacingBuffer;
if (spacingBuffer.AppendElements(aRange.Length(), fallible)) {
GetAdjustedSpacing(this, ligatureRange, aProvider,
spacingBuffer.Elements());
for (i = 0; i < ligatureRange.Length(); ++i) {
PropertyProvider::Spacing* space = &spacingBuffer[i];
result += space->mBefore + space->mAfter;
}
if (aSpacing) {
aSpacing->mBefore = spacingBuffer[0].mBefore;
aSpacing->mAfter = spacingBuffer.LastElement().mAfter;
}
}
}
return result + GetAdvanceForGlyphs(ligatureRange);
}
gfxFloat gfxTextRun::GetMinAdvanceWidth(Range aRange) {
MOZ_ASSERT(aRange.end <= GetLength(), "Substring out of range");
Range ligatureRange = aRange;
ShrinkToLigatureBoundaries(&ligatureRange);
gfxFloat result =
std::max(ComputePartialLigatureWidth(
Range(aRange.start, ligatureRange.start), nullptr),
ComputePartialLigatureWidth(Range(ligatureRange.end, aRange.end),
nullptr));
// Compute min advance width by assuming each grapheme cluster takes its own
// line.
gfxFloat clusterAdvance = 0;
for (uint32_t i = ligatureRange.start; i < ligatureRange.end; ++i) {
if (mCharacterGlyphs[i].CharIsSpace()) {
// Skip space char to prevent its advance width contributing to the
// result. That is, don't consider a space can be in its own line.
continue;
}
clusterAdvance += GetAdvanceForGlyph(i);
if (i + 1 == ligatureRange.end || IsClusterStart(i + 1)) {
result = std::max(result, clusterAdvance);
clusterAdvance = 0;
}
}
return result;
}
bool gfxTextRun::SetLineBreaks(Range aRange, bool aLineBreakBefore,
bool aLineBreakAfter,
gfxFloat* aAdvanceWidthDelta) {
// Do nothing because our shaping does not currently take linebreaks into
// account. There is no change in advance width.
if (aAdvanceWidthDelta) {
*aAdvanceWidthDelta = 0;
}
return false;
}
uint32_t gfxTextRun::FindFirstGlyphRunContaining(uint32_t aOffset) const {
NS_ASSERTION(aOffset <= GetLength(), "Bad offset looking for glyphrun");
NS_ASSERTION(GetLength() == 0 ||
(!mHasGlyphRunArray && mSingleGlyphRun.mFont) ||
(mHasGlyphRunArray && mGlyphRunArray.Length() > 0),
"non-empty text but no glyph runs present!");
if (!mHasGlyphRunArray) {
return 0;
}
if (aOffset == GetLength()) {
return mGlyphRunArray.Length();
}
uint32_t start = 0;
uint32_t end = mGlyphRunArray.Length();
while (end - start > 1) {
uint32_t mid = (start + end) / 2;
if (mGlyphRunArray[mid].mCharacterOffset <= aOffset) {
start = mid;
} else {
end = mid;
}
}
NS_ASSERTION(mGlyphRunArray[start].mCharacterOffset <= aOffset,
"Hmm, something went wrong, aOffset should have been found");
return start;
}
void gfxTextRun::AddGlyphRun(gfxFont* aFont, FontMatchType aMatchType,
uint32_t aUTF16Offset, bool aForceNewRun,
gfx::ShapedTextFlags aOrientation, bool aIsCJK) {
NS_ASSERTION(aFont, "adding glyph run for null font!");
NS_ASSERTION(aOrientation != gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED,
"mixed orientation should have been resolved");
if (!aFont) {
return;
}
if (!mHasGlyphRunArray) {
// We don't currently have an array.
if (!mSingleGlyphRun.mFont) {
// This is the first glyph run: just store it directly.
mSingleGlyphRun.SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
mSingleGlyphRun.mCharacterOffset = aUTF16Offset;
return;
}
}
uint32_t numGlyphRuns = mHasGlyphRunArray ? mGlyphRunArray.Length() : 1;
if (!aForceNewRun && numGlyphRuns > 0) {
GlyphRun* lastGlyphRun = mHasGlyphRunArray
? &mGlyphRunArray[numGlyphRuns - 1]
: &mSingleGlyphRun;
NS_ASSERTION(lastGlyphRun->mCharacterOffset <= aUTF16Offset,
"Glyph runs out of order (and run not forced)");
// Don't append a run if the font is already the one we want
if (lastGlyphRun->Matches(aFont, aOrientation, aIsCJK, aMatchType)) {
return;
}
// If the offset has not changed, avoid leaving a zero-length run
// by overwriting the last entry instead of appending...
if (lastGlyphRun->mCharacterOffset == aUTF16Offset) {
// ...except that if the run before the last entry had the same
// font as the new one wants, merge with it instead of creating
// adjacent runs with the same font
if (numGlyphRuns > 1 && mGlyphRunArray[numGlyphRuns - 2].Matches(
aFont, aOrientation, aIsCJK, aMatchType)) {
mGlyphRunArray.TruncateLength(numGlyphRuns - 1);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
return;
}
lastGlyphRun->SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
return;
}
}
NS_ASSERTION(
aForceNewRun || numGlyphRuns > 0 || aUTF16Offset == 0,
"First run doesn't cover the first character (and run not forced)?");
if (!mHasGlyphRunArray) {
ConvertToGlyphRunArray();
}
GlyphRun* glyphRun = mGlyphRunArray.AppendElement();
glyphRun->SetProperties(aFont, aOrientation, aIsCJK, aMatchType);
glyphRun->mCharacterOffset = aUTF16Offset;
}
void gfxTextRun::SortGlyphRuns() {
if (!mHasGlyphRunArray) {
return;
}
// We should never have an empty or one-element array here; if there's only
// one glyphrun, it should be stored directly in the textrun without using
// an array at all.
MOZ_ASSERT(mGlyphRunArray.Length() > 1);
AutoTArray<GlyphRun, 16> runs(std::move(mGlyphRunArray));
GlyphRunOffsetComparator comp;
runs.Sort(comp);
// Now copy back, coalescing adjacent glyph runs that have the same
// properties.
mGlyphRunArray.Clear();
GlyphRun* prevRun = nullptr;
for (auto& run : runs) {
// A GlyphRun with the same font and orientation as the previous can
// just be skipped; the last GlyphRun will cover its character range.
MOZ_ASSERT(run.mFont != nullptr);
if (!prevRun || !prevRun->Matches(run.mFont, run.mOrientation, run.mIsCJK,
run.mMatchType)) {
// If two font runs have the same character offset, Sort() will have
// randomized their order!
MOZ_ASSERT(prevRun == nullptr ||
prevRun->mCharacterOffset < run.mCharacterOffset,
"Two fonts for the same run, glyph indices unreliable");
prevRun = mGlyphRunArray.AppendElement(std::move(run));
}
}
MOZ_ASSERT(mGlyphRunArray.Length() > 0);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
}
// Note that SanitizeGlyphRuns scans all glyph runs in the textrun;
// therefore we only call it once, at the end of textrun construction,
// NOT incrementally as each glyph run is added (bug 680402).
void gfxTextRun::SanitizeGlyphRuns() {
if (!mHasGlyphRunArray) {
return;
}
MOZ_ASSERT(mGlyphRunArray.Length() > 1);
// If any glyph run starts with ligature-continuation characters, we need to
// advance it to the first "real" character to avoid drawing partial ligature
// glyphs from wrong font (seen with U+FEFF in reftest 474417-1, as Core Text
// eliminates the glyph, which makes it appear as if a ligature has been
// formed)
int32_t i, lastRunIndex = mGlyphRunArray.Length() - 1;
const CompressedGlyph* charGlyphs = mCharacterGlyphs;
for (i = lastRunIndex; i >= 0; --i) {
GlyphRun& run = mGlyphRunArray[i];
while (charGlyphs[run.mCharacterOffset].IsLigatureContinuation() &&
run.mCharacterOffset < GetLength()) {
run.mCharacterOffset++;
}
// if the run has become empty, eliminate it
if ((i < lastRunIndex &&
run.mCharacterOffset >= mGlyphRunArray[i + 1].mCharacterOffset) ||
(i == lastRunIndex && run.mCharacterOffset == GetLength())) {
mGlyphRunArray.RemoveElementAt(i);
--lastRunIndex;
}
}
MOZ_ASSERT(mGlyphRunArray.Length() > 0);
if (mGlyphRunArray.Length() == 1) {
ConvertFromGlyphRunArray();
}
}
void gfxTextRun::CopyGlyphDataFrom(gfxShapedWord* aShapedWord,