1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=4 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
12 #include "PLDHashTable.h"
13 #include "ThebesRLBoxTypes.h"
14 #include "gfxFontVariations.h"
17 #include "mozilla/AlreadyAddRefed.h"
18 #include "mozilla/Attributes.h"
19 #include "mozilla/FontPropertyTypes.h"
20 #include "mozilla/MemoryReporting.h"
21 #include "mozilla/RefPtr.h"
22 #include "mozilla/ServoStyleConsts.h"
23 #include "mozilla/TypedEnumBits.h"
24 #include "mozilla/UniquePtr.h"
25 #include "mozilla/gfx/MatrixFwd.h"
26 #include "mozilla/gfx/Point.h"
29 #include "nsTHashMap.h"
30 #include "nsTHashSet.h"
31 #include "nsExpirationTracker.h"
32 #include "nsFontMetrics.h"
33 #include "nsHashKeys.h"
34 #include "nsIMemoryReporter.h"
35 #include "nsIObserver.h"
36 #include "nsISupports.h"
39 #include "nsTHashtable.h"
40 #include "nsUnicodeScriptCodes.h"
43 // Only required for function bodys
47 #include "mozilla/Assertions.h"
48 #include "mozilla/HashFunctions.h"
49 #include "mozilla/ServoUtils.h"
50 #include "mozilla/gfx/2D.h"
51 #include "gfxFontEntry.h"
52 #include "gfxFontFeatures.h"
53 #include "gfxFontUtils.h"
54 #include "gfxPlatform.h"
57 #include "nsMathUtils.h"
60 class gfxGlyphExtents
;
69 struct gfxTextRunDrawCallbacks
;
70 enum class DrawMode
: int;
73 class SVGContextPaint
;
77 } // namespace mozilla
79 typedef struct _cairo cairo_t
;
80 typedef struct _cairo_scaled_font cairo_scaled_font_t
;
82 #define FONT_MAX_SIZE 2000.0
84 #define SMALL_CAPS_SCALE_FACTOR 0.8
86 // The skew factor used for synthetic-italic [oblique] fonts;
87 // we use a platform-dependent value to harmonize with the platform's own APIs.
89 # define OBLIQUE_SKEW_FACTOR 0.3f
90 #elif defined(MOZ_WIDGET_GTK)
91 # define OBLIQUE_SKEW_FACTOR 0.2f
93 # define OBLIQUE_SKEW_FACTOR 0.25f
97 using FontStretch
= mozilla::FontStretch
;
98 using FontSlantStyle
= mozilla::FontSlantStyle
;
99 using FontWeight
= mozilla::FontWeight
;
100 using FontSizeAdjust
= mozilla::StyleFontSizeAdjust
;
103 gfxFontStyle(FontSlantStyle aStyle
, FontWeight aWeight
, FontStretch aStretch
,
104 gfxFloat aSize
, const FontSizeAdjust
& aSizeAdjust
,
105 bool aSystemFont
, bool aPrinterFont
, bool aWeightSynthesis
,
106 bool aStyleSynthesis
, bool aSmallCapsSynthesis
,
107 uint32_t aLanguageOverride
);
108 // Features are composed of (1) features from style rules (2) features
109 // from feature settings rules and (3) family-specific features. (1) and
110 // (3) are guaranteed to be mutually exclusive
112 // custom opentype feature settings
113 CopyableTArray
<gfxFontFeature
> featureSettings
;
115 // Some font-variant property values require font-specific settings
116 // defined via @font-feature-values rules. These are resolved after
117 // font matching occurs.
119 // -- list of value tags for specific alternate features
120 mozilla::StyleVariantAlternatesList variantAlternates
;
122 // -- object used to look these up once the font is matched
123 RefPtr
<gfxFontFeatureValueSet
> featureValueLookup
;
125 // opentype variation settings
126 CopyableTArray
<gfxFontVariation
> variationSettings
;
128 // The logical size of the font, in pixels
131 // The optical size value to apply (if supported); negative means none.
132 float autoOpticalSize
= -1.0f
;
134 // The aspect-value (ie., the ratio actualsize:actualxheight) that any
135 // actual physical font created from this font structure must have when
136 // rendering or measuring a string. A value of -1.0 means no adjustment
137 // needs to be done; otherwise the value must be nonnegative.
140 // baseline offset, used when simulating sub/superscript glyphs
141 float baselineOffset
;
143 // Language system tag, to override document language;
144 // an OpenType "language system" tag represented as a 32-bit integer
145 // (see http://www.microsoft.com/typography/otspec/languagetags.htm).
146 // Normally 0, so font rendering will use the document or element language
147 // (see above) to control any language-specific rendering, but the author
148 // can override this for cases where the options implemented in the font
149 // do not directly match the actual language. (E.g. lang may be Macedonian,
150 // but the font in use does not explicitly support this; the author can
151 // use font-language-override to request the Serbian option in the font
152 // in order to get correct glyph shapes.)
153 uint32_t languageOverride
;
155 // The estimated background color behind the text. Enables a special
156 // rendering mode when NS_GET_A(.) > 0. Only used for text in the chrome.
157 nscolor fontSmoothingBackgroundColor
;
159 // The Font{Weight,Stretch,SlantStyle} fields are each a 16-bit type.
161 // The weight of the font: 100, 200, ... 900.
164 // The stretch of the font
168 FontSlantStyle style
;
170 // Whether face-selection properties weight/style/stretch are all 'normal'
171 bool IsNormalStyle() const {
172 return weight
.IsNormal() && style
.IsNormal() && stretch
.IsNormal();
175 // We pack these three small-integer fields into a single byte to avoid
176 // overflowing an 8-byte boundary [in a 64-bit build] and ending up with
177 // 7 bytes of padding at the end of the struct.
179 // caps variant (small-caps, petite-caps, etc.)
180 uint8_t variantCaps
: 3; // uses range 0..6
182 // sub/superscript variant
183 uint8_t variantSubSuper
: 2; // uses range 0..2
185 // font metric used as basis of font-size-adjust
186 uint8_t sizeAdjustBasis
: 3; // uses range 0..4
188 // Say that this font is a system font and therefore does not
189 // require certain fixup that we do for fonts from untrusted
193 // Say that this font is used for print or print preview.
194 bool printerFont
: 1;
196 // Used to imitate -webkit-font-smoothing: antialiased
197 bool useGrayscaleAntialiasing
: 1;
199 // Whether synthetic styles are allowed
200 bool allowSyntheticWeight
: 1;
201 bool allowSyntheticStyle
: 1;
202 bool allowSyntheticSmallCaps
: 1;
204 // some variant features require fallback which complicates the shaping
205 // code, so set up a bool to indicate when shaping with fallback is needed
206 bool noFallbackVariantFeatures
: 1;
208 // Return the final adjusted font size for the given aspect ratio.
209 // Not meant to be called when sizeAdjustBasis is NONE.
210 gfxFloat
GetAdjustedSize(gfxFloat aspect
) const {
212 FontSizeAdjust::Tag(sizeAdjustBasis
) != FontSizeAdjust::Tag::None
,
213 "Not meant to be called when sizeAdjustBasis is none");
214 gfxFloat adjustedSize
=
215 std::max(NS_round(size
* (sizeAdjust
/ aspect
)), 1.0);
216 return std::min(adjustedSize
, FONT_MAX_SIZE
);
219 // Some callers want to take a short-circuit path if they can be sure the
220 // adjusted size will be zero.
221 bool AdjustedSizeMustBeZero() const {
222 return size
== 0.0 ||
223 (FontSizeAdjust::Tag(sizeAdjustBasis
) != FontSizeAdjust::Tag::None
&&
227 PLDHashNumber
Hash() const;
229 // Adjust this style to simulate sub/superscript (as requested in the
230 // variantSubSuper field) using size and baselineOffset instead.
231 void AdjustForSubSuperscript(int32_t aAppUnitsPerDevPixel
);
233 // Should this style cause the given font entry to use synthetic bold?
234 bool NeedsSyntheticBold(gfxFontEntry
* aFontEntry
) const {
235 return weight
.IsBold() && allowSyntheticWeight
&&
236 !aFontEntry
->SupportsBold();
239 bool Equals(const gfxFontStyle
& other
) const {
240 return mozilla::NumbersAreBitwiseIdentical(size
, other
.size
) &&
241 (style
== other
.style
) && (weight
== other
.weight
) &&
242 (stretch
== other
.stretch
) && (variantCaps
== other
.variantCaps
) &&
243 (variantSubSuper
== other
.variantSubSuper
) &&
244 (allowSyntheticWeight
== other
.allowSyntheticWeight
) &&
245 (allowSyntheticStyle
== other
.allowSyntheticStyle
) &&
246 (systemFont
== other
.systemFont
) &&
247 (printerFont
== other
.printerFont
) &&
248 (useGrayscaleAntialiasing
== other
.useGrayscaleAntialiasing
) &&
249 (baselineOffset
== other
.baselineOffset
) &&
250 mozilla::NumbersAreBitwiseIdentical(sizeAdjust
, other
.sizeAdjust
) &&
251 (sizeAdjustBasis
== other
.sizeAdjustBasis
) &&
252 (featureSettings
== other
.featureSettings
) &&
253 (variantAlternates
== other
.variantAlternates
) &&
254 (featureValueLookup
== other
.featureValueLookup
) &&
255 (variationSettings
== other
.variationSettings
) &&
256 (languageOverride
== other
.languageOverride
) &&
257 mozilla::NumbersAreBitwiseIdentical(autoOpticalSize
,
258 other
.autoOpticalSize
) &&
259 (fontSmoothingBackgroundColor
== other
.fontSmoothingBackgroundColor
);
266 * The mFonts hashtable contains most fonts, indexed by (gfxFontEntry*, style).
267 * It does not add a reference to the fonts it contains.
268 * When a font's refcount decreases to zero, instead of deleting it we
269 * add it to our expiration tracker.
270 * The expiration tracker tracks fonts with zero refcount. After a certain
271 * period of time, such fonts expire and are deleted.
273 * We're using 3 generations with a ten-second generation interval, so
274 * zero-refcount fonts will be deleted 20-30 seconds after their refcount
275 * goes to zero, if timer events fire in a timely manner.
277 * The font cache also handles timed expiration of cached ShapedWords
278 * for "persistent" fonts: it has a repeating timer, and notifies
279 * each cached font to "age" its shaped words. The words will be released
280 * by the fonts if they get aged three times without being re-used in the
283 * Note that the ShapedWord timeout is much larger than the font timeout,
284 * so that in the case of a short-lived font, we'll discard the gfxFont
285 * completely, with all its words, and avoid the cost of aging the words
286 * individually. That only happens with longer-lived fonts.
288 struct FontCacheSizes
{
289 FontCacheSizes() : mFontInstances(0), mShapedWords(0) {}
291 size_t mFontInstances
; // memory used by instances of gfxFont subclasses
292 size_t mShapedWords
; // memory used by the per-font shapedWord caches
295 class gfxFontCacheExpirationTracker
296 : public ExpirationTrackerImpl
<gfxFont
, 3, ::detail::PlaceholderLock
,
297 ::detail::PlaceholderAutoLock
> {
299 typedef ::detail::PlaceholderLock Lock
;
300 typedef ::detail::PlaceholderAutoLock AutoLock
;
304 AutoLock
FakeLock() { return AutoLock(mLock
); }
306 Lock
& GetMutex() override
{
307 mozilla::AssertIsMainThreadOrServoFontMetricsLocked();
312 enum { FONT_TIMEOUT_SECONDS
= 10 };
314 explicit gfxFontCacheExpirationTracker(nsIEventTarget
* aEventTarget
)
315 : ExpirationTrackerImpl
<gfxFont
, 3, Lock
, AutoLock
>(
316 FONT_TIMEOUT_SECONDS
* 1000, "gfxFontCache", aEventTarget
) {}
319 class gfxFontCache final
: private gfxFontCacheExpirationTracker
{
321 enum { SHAPED_WORD_TIMEOUT_SECONDS
= 60 };
323 explicit gfxFontCache(nsIEventTarget
* aEventTarget
);
327 * Get the global gfxFontCache. You must call Init() before
328 * calling this method --- the result will not be null.
330 static gfxFontCache
* GetCache() { return gGlobalCache
; }
332 static nsresult
Init();
333 // It's OK to call this even if Init() has not been called.
334 static void Shutdown();
336 // Look up a font in the cache. Returns null if there's nothing matching
338 gfxFont
* Lookup(const gfxFontEntry
* aFontEntry
, const gfxFontStyle
* aStyle
,
339 const gfxCharacterMap
* aUnicodeRangeMap
);
341 // We created a new font (presumably because Lookup returned null);
342 // put it in the cache. The font's refcount should be nonzero. It is
343 // allowable to add a new font even if there is one already in the
344 // cache with the same key; we'll forget about the old one.
345 void AddNew(gfxFont
* aFont
);
347 // The font's refcount has gone to zero; give ownership of it to
348 // the cache. We delete it if it's not acquired again after a certain
350 void NotifyReleased(gfxFont
* aFont
);
352 // Cleans out the hashtable and removes expired fonts waiting for cleanup.
353 // Other gfxFont objects may be still in use but they will be pushed
354 // into the expiration queues and removed.
360 uint32_t Count() const { return mFonts
.Count(); }
362 void FlushShapedWordCaches();
363 void NotifyGlyphsChanged();
365 void RunWordCacheExpirationTimer() {
366 if (mWordCacheExpirationTimer
&& !mTimerRunning
) {
367 mWordCacheExpirationTimer
->InitWithNamedFuncCallback(
368 WordCacheExpirationTimerCallback
, this,
369 SHAPED_WORD_TIMEOUT_SECONDS
* 1000, nsITimer::TYPE_REPEATING_SLACK
,
370 "gfxFontCache::WordCacheExpiration");
371 mTimerRunning
= true;
374 void PauseWordCacheExpirationTimer() {
375 if (mWordCacheExpirationTimer
&& mTimerRunning
) {
376 mWordCacheExpirationTimer
->Cancel();
377 mTimerRunning
= false;
381 void AddSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf
,
382 FontCacheSizes
* aSizes
) const;
383 void AddSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf
,
384 FontCacheSizes
* aSizes
) const;
386 void AgeAllGenerations() { AgeAllGenerationsLocked(FakeLock()); }
388 void RemoveObject(gfxFont
* aFont
) { RemoveObjectLocked(aFont
, FakeLock()); }
391 class MemoryReporter final
: public nsIMemoryReporter
{
392 ~MemoryReporter() = default;
396 NS_DECL_NSIMEMORYREPORTER
399 // Observer for notifications that the font cache cares about
400 class Observer final
: public nsIObserver
{
401 ~Observer() = default;
408 nsresult
AddObject(gfxFont
* aFont
) {
409 return AddObjectLocked(aFont
, FakeLock());
412 // This gets called when the timeout has expired on a zero-refcount
413 // font; we just delete it.
414 void NotifyExpiredLocked(gfxFont
* aFont
, const AutoLock
&) override
{
415 NotifyExpired(aFont
);
418 void NotifyExpired(gfxFont
* aFont
);
420 void DestroyFont(gfxFont
* aFont
);
422 static gfxFontCache
* gGlobalCache
;
424 struct MOZ_STACK_CLASS Key
{
425 const gfxFontEntry
* mFontEntry
;
426 const gfxFontStyle
* mStyle
;
427 const gfxCharacterMap
* mUnicodeRangeMap
;
428 Key(const gfxFontEntry
* aFontEntry
, const gfxFontStyle
* aStyle
,
429 const gfxCharacterMap
* aUnicodeRangeMap
)
430 : mFontEntry(aFontEntry
),
432 mUnicodeRangeMap(aUnicodeRangeMap
) {}
435 class HashEntry
: public PLDHashEntryHdr
{
437 typedef const Key
& KeyType
;
438 typedef const Key
* KeyTypePointer
;
440 // When constructing a new entry in the hashtable, we'll leave this
441 // blank. The caller of Put() will fill this in.
442 explicit HashEntry(KeyTypePointer aStr
) : mFont(nullptr) {}
444 bool KeyEquals(const KeyTypePointer aKey
) const;
445 static KeyTypePointer
KeyToPointer(KeyType aKey
) { return &aKey
; }
446 static PLDHashNumber
HashKey(const KeyTypePointer aKey
) {
447 return mozilla::HashGeneric(aKey
->mStyle
->Hash(), aKey
->mFontEntry
,
448 aKey
->mUnicodeRangeMap
);
450 enum { ALLOW_MEMMOVE
= true };
452 // The cache tracks gfxFont objects whose refcount has dropped to zero,
453 // so they are not immediately deleted but may be "resurrected" if they
454 // have not yet expired from the tracker when they are needed again.
455 // See the custom AddRef/Release methods in gfxFont.
456 gfxFont
* MOZ_UNSAFE_REF("tracking for deferred deletion") mFont
;
459 nsTHashtable
<HashEntry
> mFonts
;
461 static void WordCacheExpirationTimerCallback(nsITimer
* aTimer
, void* aCache
);
462 nsCOMPtr
<nsITimer
> mWordCacheExpirationTimer
;
463 bool mTimerRunning
= false;
466 class gfxTextPerfMetrics
{
469 uint32_t numContentTextRuns
;
470 uint32_t numChromeTextRuns
;
472 uint32_t maxTextRunLen
;
473 uint32_t wordCacheSpaceRules
;
474 uint32_t wordCacheLong
;
475 uint32_t wordCacheHit
;
476 uint32_t wordCacheMiss
;
477 uint32_t fallbackPrefs
;
478 uint32_t fallbackSystem
;
479 uint32_t textrunConst
;
480 uint32_t textrunDestr
;
481 uint32_t genericLookups
;
484 uint32_t reflowCount
;
486 // counts per reflow operation
489 // totals for the lifetime of a document
490 TextCounts cumulative
;
492 gfxTextPerfMetrics() { memset(this, 0, sizeof(gfxTextPerfMetrics
)); }
494 // add current totals to cumulative ones
496 if (current
.numChars
== 0) {
499 cumulative
.numContentTextRuns
+= current
.numContentTextRuns
;
500 cumulative
.numChromeTextRuns
+= current
.numChromeTextRuns
;
501 cumulative
.numChars
+= current
.numChars
;
502 if (current
.maxTextRunLen
> cumulative
.maxTextRunLen
) {
503 cumulative
.maxTextRunLen
= current
.maxTextRunLen
;
505 cumulative
.wordCacheSpaceRules
+= current
.wordCacheSpaceRules
;
506 cumulative
.wordCacheLong
+= current
.wordCacheLong
;
507 cumulative
.wordCacheHit
+= current
.wordCacheHit
;
508 cumulative
.wordCacheMiss
+= current
.wordCacheMiss
;
509 cumulative
.fallbackPrefs
+= current
.fallbackPrefs
;
510 cumulative
.fallbackSystem
+= current
.fallbackSystem
;
511 cumulative
.textrunConst
+= current
.textrunConst
;
512 cumulative
.textrunDestr
+= current
.textrunDestr
;
513 cumulative
.genericLookups
+= current
.genericLookups
;
514 memset(¤t
, 0, sizeof(current
));
520 // Flags that live in the gfxShapedText::mFlags field.
521 // (Note that gfxTextRun has an additional mFlags2 field for use
522 // by textrun clients like nsTextFrame.)
524 // If you add a flag, please add support for it in gfxTextRun::Dump.
525 enum class ShapedTextFlags
: uint16_t {
527 * When set, the text is RTL.
529 TEXT_IS_RTL
= 0x0001,
531 * When set, spacing is enabled and the textrun needs to call GetSpacing
532 * on the spacing provider.
534 TEXT_ENABLE_SPACING
= 0x0002,
536 * When set, the text has no characters above 255 and it is stored
537 * in the textrun in 8-bit format.
539 TEXT_IS_8BIT
= 0x0004,
541 * When set, GetHyphenationBreaks may return true for some character
542 * positions, otherwise it will always return false for all characters.
544 TEXT_ENABLE_HYPHEN_BREAKS
= 0x0008,
546 * When set, the RunMetrics::mBoundingBox field will be initialized
547 * properly based on glyph extents, in particular, glyph extents that
548 * overflow the standard font-box (the box defined by the ascent, descent
549 * and advance width of the glyph). When not set, it may just be the
550 * standard font-box even if glyphs overflow.
552 TEXT_NEED_BOUNDING_BOX
= 0x0010,
554 * When set, optional ligatures are disabled. Ligatures that are
555 * required for legible text should still be enabled.
557 TEXT_DISABLE_OPTIONAL_LIGATURES
= 0x0020,
559 * When set, the textrun should favour speed of construction over
560 * quality. This may involve disabling ligatures and/or kerning or
563 TEXT_OPTIMIZE_SPEED
= 0x0040,
565 * When set, the textrun should discard control characters instead of
566 * turning them into hexboxes.
568 TEXT_HIDE_CONTROL_CHARACTERS
= 0x0080,
571 * nsTextFrameThebes sets these, but they're defined here rather than
572 * in nsTextFrameUtils.h because ShapedWord creation/caching also needs
573 * to check the _INCOMING flag
575 TEXT_TRAILING_ARABICCHAR
= 0x0100,
577 * When set, the previous character for this textrun was an Arabic
578 * character. This is used for the context detection necessary for
579 * bidi.numeral implementation.
581 TEXT_INCOMING_ARABICCHAR
= 0x0200,
584 * Set if the textrun should use the OpenType 'math' script.
586 TEXT_USE_MATH_SCRIPT
= 0x0400,
589 * Bit 0x0800 is currently unused.
593 * Field for orientation of the textrun and glyphs within it.
594 * Possible values of the TEXT_ORIENT_MASK field:
595 * TEXT_ORIENT_HORIZONTAL
596 * TEXT_ORIENT_VERTICAL_UPRIGHT
597 * TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT
598 * TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT
599 * TEXT_ORIENT_VERTICAL_MIXED
600 * For all VERTICAL settings, the x and y coordinates of glyph
601 * positions are exchanged, so that simple advances are vertical.
603 * The MIXED value indicates vertical textRuns for which the CSS
604 * text-orientation property is 'mixed', but is never used for
605 * individual glyphRuns; it will be resolved to either UPRIGHT
606 * or SIDEWAYS_RIGHT according to the UTR50 properties of the
607 * characters, and separate glyphRuns created for the resulting
608 * glyph orientations.
610 TEXT_ORIENT_MASK
= 0x7000,
611 TEXT_ORIENT_HORIZONTAL
= 0x0000,
612 TEXT_ORIENT_VERTICAL_UPRIGHT
= 0x1000,
613 TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT
= 0x2000,
614 TEXT_ORIENT_VERTICAL_MIXED
= 0x3000,
615 TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT
= 0x4000,
618 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(ShapedTextFlags
)
620 } // namespace mozilla
622 class gfxTextRunFactory
{
624 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(gfxTextRunFactory
)
627 typedef mozilla::gfx::DrawTarget DrawTarget
;
630 * This record contains all the parameters needed to initialize a textrun.
632 struct MOZ_STACK_CLASS Parameters
{
633 // Shape text params suggesting where the textrun will be rendered
634 DrawTarget
* mDrawTarget
;
635 // Pointer to arbitrary user data (which should outlive the textrun)
637 // A description of which characters have been stripped from the original
638 // DOM string to produce the characters in the textrun. May be null
639 // if that information is not relevant.
640 gfxSkipChars
* mSkipChars
;
641 // A list of where linebreaks are currently placed in the textrun. May
642 // be null if mInitialBreakCount is zero.
643 uint32_t* mInitialBreaks
;
644 uint32_t mInitialBreakCount
;
645 // The ratio to use to convert device pixels to application layout units
646 int32_t mAppUnitsPerDevUnit
;
650 // Protected destructor, to discourage deletion outside of Release():
651 virtual ~gfxTextRunFactory();
657 * This class implements text shaping (character to glyph mapping and
658 * glyph layout). There is a gfxFontShaper subclass for each text layout
659 * technology (uniscribe, core text, harfbuzz,....) we support.
661 * The shaper is responsible for setting up glyph data in gfxTextRuns.
663 * A generic, platform-independent shaper relies only on the standard
664 * gfxFont interface and can work with any concrete subclass of gfxFont.
666 * Platform-specific implementations designed to interface to platform
667 * shaping APIs such as Uniscribe or CoreText may rely on features of a
668 * specific font subclass to access native font references
669 * (such as CTFont, HFONT, DWriteFont, etc).
672 class gfxFontShaper
{
674 typedef mozilla::gfx::DrawTarget DrawTarget
;
675 typedef mozilla::unicode::Script Script
;
677 enum class RoundingFlags
: uint8_t { kRoundX
= 0x01, kRoundY
= 0x02 };
679 explicit gfxFontShaper(gfxFont
* aFont
) : mFont(aFont
) {
680 NS_ASSERTION(aFont
, "shaper requires a valid font!");
683 virtual ~gfxFontShaper() = default;
685 // Shape a piece of text and store the resulting glyph data into
686 // aShapedText. Parameters aOffset/aLength indicate the range of
687 // aShapedText to be updated; aLength is also the length of aText.
688 virtual bool ShapeText(DrawTarget
* aDrawTarget
, const char16_t
* aText
,
689 uint32_t aOffset
, uint32_t aLength
, Script aScript
,
690 nsAtom
* aLanguage
, // may be null, indicating no
691 // lang-specific shaping to be
693 bool aVertical
, RoundingFlags aRounding
,
694 gfxShapedText
* aShapedText
) = 0;
696 gfxFont
* GetFont() const { return mFont
; }
698 static void MergeFontFeatures(
699 const gfxFontStyle
* aStyle
, const nsTArray
<gfxFontFeature
>& aFontFeatures
,
700 bool aDisableLigatures
, const nsACString
& aFamilyName
, bool aAddSmallCaps
,
701 void (*aHandleFeature
)(const uint32_t&, uint32_t&, void*),
702 void* aHandleFeatureData
);
705 // the font this shaper is working with. The font owns a UniquePtr reference
706 // to this object, and will destroy it before it dies. Thus, mFont will always
708 gfxFont
* MOZ_NON_OWNING_REF mFont
;
711 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(gfxFontShaper::RoundingFlags
)
714 * gfxShapedText is an abstract superclass for gfxShapedWord and gfxTextRun.
715 * These are objects that store a list of zero or more glyphs for each
716 * character. For each glyph we store the glyph ID, the advance, and possibly
717 * x/y-offsets. The idea is that a string is rendered by a loop that draws each
718 * glyph at its designated offset from the current point, then advances the
719 * current point by the glyph's advance in the direction of the textrun (LTR or
720 * RTL). Each glyph advance is always rounded to the nearest appunit; this
721 * ensures consistent results when dividing the text in a textrun into multiple
722 * text frames (frame boundaries are always aligned to appunits). We optimize
723 * for the case where a character has a single glyph and zero xoffset and
724 * yoffset, and the glyph ID and advance are in a reasonable range so we can
725 * pack all necessary data into 32 bits.
727 * gfxFontShaper can shape text into either a gfxShapedWord (cached by a
728 * gfxFont) or directly into a gfxTextRun (for cases where we want to shape
729 * textruns in their entirety rather than using cached words, because there may
730 * be layout features that depend on the inter-word spaces).
732 class gfxShapedText
{
734 typedef mozilla::unicode::Script Script
;
736 gfxShapedText(uint32_t aLength
, mozilla::gfx::ShapedTextFlags aFlags
,
737 uint16_t aAppUnitsPerDevUnit
)
740 mAppUnitsPerDevUnit(aAppUnitsPerDevUnit
) {}
742 virtual ~gfxShapedText() = default;
745 * This class records the information associated with a character in the
746 * input string. It's optimized for the case where there is one glyph
747 * representing that character alone.
749 * A character can have zero or more associated glyphs. Each glyph
750 * has an advance width and an x and y offset.
751 * A character may be the start of a cluster.
752 * A character may be the start of a ligature group.
753 * A character can be "missing", indicating that the system is unable
754 * to render the character.
756 * All characters in a ligature group conceptually share all the glyphs
757 * associated with the characters in a group.
759 class CompressedGlyph
{
762 // Indicates that a cluster and ligature group starts at this
763 // character; this character has a single glyph with a reasonable
764 // advance and zero offsets. A "reasonable" advance
765 // is one that fits in the available bits (currently 12) (specified
767 FLAG_IS_SIMPLE_GLYPH
= 0x80000000U
,
769 // These flags are applicable to both "simple" and "complex" records.
770 COMMON_FLAGS_MASK
= 0x70000000U
,
772 // Indicates whether a linebreak is allowed before this character;
773 // this is a two-bit field that holds a FLAG_BREAK_TYPE_xxx value
774 // indicating the kind of linebreak (if any) allowed here.
775 FLAGS_CAN_BREAK_BEFORE
= 0x60000000U
,
777 FLAGS_CAN_BREAK_SHIFT
= 29,
778 FLAG_BREAK_TYPE_NONE
= 0,
779 FLAG_BREAK_TYPE_NORMAL
= 1,
780 FLAG_BREAK_TYPE_HYPHEN
= 2,
782 FLAG_CHAR_IS_SPACE
= 0x10000000U
,
784 // Fields present only when FLAG_IS_SIMPLE_GLYPH is /true/.
785 // The advance is stored in appunits as a 12-bit field:
786 ADVANCE_MASK
= 0x0FFF0000U
,
788 // and the glyph ID is stored in the low 16 bits.
789 GLYPH_MASK
= 0x0000FFFFU
,
791 // Fields present only when FLAG_IS_SIMPLE_GLYPH is /false/.
792 // Non-simple glyphs may or may not have glyph data in the
793 // corresponding mDetailedGlyphs entry. They have a glyph count
794 // stored in the low 16 bits, and the following flag bits:
795 GLYPH_COUNT_MASK
= 0x0000FFFFU
,
797 // When NOT set, indicates that this character corresponds to a
798 // missing glyph and should be skipped (or possibly, render the character
799 // Unicode value in some special way). If there are glyphs,
800 // the mGlyphID is actually the UTF16 character code. The bit is
801 // inverted so we can memset the array to zero to indicate all missing.
802 FLAG_NOT_MISSING
= 0x010000,
803 FLAG_NOT_CLUSTER_START
= 0x020000,
804 FLAG_NOT_LIGATURE_GROUP_START
= 0x040000,
805 // Flag bit 0x080000 is currently unused.
807 // Certain types of characters are marked so that they can be given
808 // special treatment in rendering. This may require use of a "complex"
809 // CompressedGlyph record even for a character that would otherwise be
810 // treated as "simple".
811 CHAR_TYPE_FLAGS_MASK
= 0xF00000,
812 FLAG_CHAR_IS_TAB
= 0x100000,
813 FLAG_CHAR_IS_NEWLINE
= 0x200000,
814 // Per CSS Text Decoration Module Level 3, emphasis marks are not
815 // drawn for any character in Unicode categories Z*, Cc, Cf, and Cn
816 // which is not combined with any combining characters. This flag is
817 // set for all those characters except 0x20 whitespace.
818 FLAG_CHAR_NO_EMPHASIS_MARK
= 0x400000,
819 // Per CSS Text, letter-spacing is not applied to formatting chars
820 // (category Cf). We mark those in the textrun so as to be able to
821 // skip them when setting up spacing in nsTextFrame.
822 FLAG_CHAR_IS_FORMATTING_CONTROL
= 0x800000,
824 // The bits 0x0F000000 are currently unused in non-simple glyphs.
827 // "Simple glyphs" have a simple glyph ID, simple advance and their
828 // x and y offsets are zero. Also the glyph extents do not overflow
829 // the font-box defined by the font ascent, descent and glyph advance width.
830 // These case is optimized to avoid storing DetailedGlyphs.
832 // Returns true if the glyph ID aGlyph fits into the compressed
834 static bool IsSimpleGlyphID(uint32_t aGlyph
) {
835 return (aGlyph
& GLYPH_MASK
) == aGlyph
;
837 // Returns true if the advance aAdvance fits into the compressed
838 // representation. aAdvance is in appunits.
839 static bool IsSimpleAdvance(uint32_t aAdvance
) {
840 return (aAdvance
& (ADVANCE_MASK
>> ADVANCE_SHIFT
)) == aAdvance
;
843 bool IsSimpleGlyph() const { return mValue
& FLAG_IS_SIMPLE_GLYPH
; }
844 uint32_t GetSimpleAdvance() const {
845 MOZ_ASSERT(IsSimpleGlyph());
846 return (mValue
& ADVANCE_MASK
) >> ADVANCE_SHIFT
;
848 uint32_t GetSimpleGlyph() const {
849 MOZ_ASSERT(IsSimpleGlyph());
850 return mValue
& GLYPH_MASK
;
853 bool IsMissing() const {
854 return !(mValue
& (FLAG_NOT_MISSING
| FLAG_IS_SIMPLE_GLYPH
));
856 bool IsClusterStart() const {
857 return IsSimpleGlyph() || !(mValue
& FLAG_NOT_CLUSTER_START
);
859 bool IsLigatureGroupStart() const {
860 return IsSimpleGlyph() || !(mValue
& FLAG_NOT_LIGATURE_GROUP_START
);
862 bool IsLigatureContinuation() const {
863 return !IsSimpleGlyph() &&
864 (mValue
& (FLAG_NOT_LIGATURE_GROUP_START
| FLAG_NOT_MISSING
)) ==
865 (FLAG_NOT_LIGATURE_GROUP_START
| FLAG_NOT_MISSING
);
868 // Return true if the original character was a normal (breakable,
869 // trimmable) space (U+0020). Not true for other characters that
870 // may happen to map to the space glyph (U+00A0).
871 bool CharIsSpace() const { return mValue
& FLAG_CHAR_IS_SPACE
; }
873 bool CharIsTab() const {
874 return !IsSimpleGlyph() && (mValue
& FLAG_CHAR_IS_TAB
);
876 bool CharIsNewline() const {
877 return !IsSimpleGlyph() && (mValue
& FLAG_CHAR_IS_NEWLINE
);
879 bool CharMayHaveEmphasisMark() const {
880 return !CharIsSpace() &&
881 (IsSimpleGlyph() || !(mValue
& FLAG_CHAR_NO_EMPHASIS_MARK
));
883 bool CharIsFormattingControl() const {
884 return !IsSimpleGlyph() && (mValue
& FLAG_CHAR_IS_FORMATTING_CONTROL
);
887 uint32_t CharTypeFlags() const {
888 return IsSimpleGlyph() ? 0 : (mValue
& CHAR_TYPE_FLAGS_MASK
);
891 void SetClusterStart(bool aIsClusterStart
) {
892 MOZ_ASSERT(!IsSimpleGlyph());
893 if (aIsClusterStart
) {
894 mValue
&= ~FLAG_NOT_CLUSTER_START
;
896 mValue
|= FLAG_NOT_CLUSTER_START
;
900 uint8_t CanBreakBefore() const {
901 return (mValue
& FLAGS_CAN_BREAK_BEFORE
) >> FLAGS_CAN_BREAK_SHIFT
;
903 // Returns FLAGS_CAN_BREAK_BEFORE if the setting changed, 0 otherwise
904 uint32_t SetCanBreakBefore(uint8_t aCanBreakBefore
) {
905 MOZ_ASSERT(aCanBreakBefore
<= 2, "Bogus break-before value!");
906 uint32_t breakMask
= (uint32_t(aCanBreakBefore
) << FLAGS_CAN_BREAK_SHIFT
);
907 uint32_t toggle
= breakMask
^ (mValue
& FLAGS_CAN_BREAK_BEFORE
);
912 // Create a CompressedGlyph value representing a simple glyph with
913 // no extra flags (line-break or is_space) set.
914 static CompressedGlyph
MakeSimpleGlyph(uint32_t aAdvanceAppUnits
,
916 MOZ_ASSERT(IsSimpleAdvance(aAdvanceAppUnits
));
917 MOZ_ASSERT(IsSimpleGlyphID(aGlyph
));
920 FLAG_IS_SIMPLE_GLYPH
| (aAdvanceAppUnits
<< ADVANCE_SHIFT
) | aGlyph
;
924 // Assign a simple glyph value to an existing CompressedGlyph record,
925 // preserving line-break/is-space flags if present.
926 CompressedGlyph
& SetSimpleGlyph(uint32_t aAdvanceAppUnits
,
928 MOZ_ASSERT(!CharTypeFlags(), "Char type flags lost");
929 mValue
= (mValue
& COMMON_FLAGS_MASK
) |
930 MakeSimpleGlyph(aAdvanceAppUnits
, aGlyph
).mValue
;
934 // Create a CompressedGlyph value representing a complex glyph record,
935 // without any line-break or char-type flags.
936 static CompressedGlyph
MakeComplex(bool aClusterStart
,
937 bool aLigatureStart
) {
939 g
.mValue
= FLAG_NOT_MISSING
|
940 (aClusterStart
? 0 : FLAG_NOT_CLUSTER_START
) |
941 (aLigatureStart
? 0 : FLAG_NOT_LIGATURE_GROUP_START
);
945 // Assign a complex glyph value to an existing CompressedGlyph record,
946 // preserving line-break/char-type flags if present.
947 // This sets the glyphCount to zero; it will be updated when we call
948 // gfxShapedText::SetDetailedGlyphs.
949 CompressedGlyph
& SetComplex(bool aClusterStart
, bool aLigatureStart
) {
950 mValue
= (mValue
& COMMON_FLAGS_MASK
) | CharTypeFlags() |
951 MakeComplex(aClusterStart
, aLigatureStart
).mValue
;
956 * Mark a glyph record as being a missing-glyph.
957 * Missing glyphs are treated as ligature group starts; don't mess with
958 * the cluster-start flag (see bugs 618870 and 619286).
959 * We also preserve the glyph count here, as this is used after any
960 * required DetailedGlyphs (to store the char code for a hexbox) has been
962 * This must be called *after* SetDetailedGlyphs is used for the relevant
963 * offset in the shaped-word, because that will mark it as not-missing.
965 CompressedGlyph
& SetMissing() {
966 MOZ_ASSERT(!IsSimpleGlyph());
967 mValue
&= ~(FLAG_NOT_MISSING
| FLAG_NOT_LIGATURE_GROUP_START
);
971 uint32_t GetGlyphCount() const {
972 MOZ_ASSERT(!IsSimpleGlyph());
973 return mValue
& GLYPH_COUNT_MASK
;
975 void SetGlyphCount(uint32_t aGlyphCount
) {
976 MOZ_ASSERT(!IsSimpleGlyph());
977 MOZ_ASSERT(GetGlyphCount() == 0, "Glyph count already set");
978 MOZ_ASSERT(aGlyphCount
<= 0xffff, "Glyph count out of range");
979 mValue
|= FLAG_NOT_MISSING
| aGlyphCount
;
982 void SetIsSpace() { mValue
|= FLAG_CHAR_IS_SPACE
; }
984 MOZ_ASSERT(!IsSimpleGlyph());
985 mValue
|= FLAG_CHAR_IS_TAB
;
987 void SetIsNewline() {
988 MOZ_ASSERT(!IsSimpleGlyph());
989 mValue
|= FLAG_CHAR_IS_NEWLINE
;
991 void SetNoEmphasisMark() {
992 MOZ_ASSERT(!IsSimpleGlyph());
993 mValue
|= FLAG_CHAR_NO_EMPHASIS_MARK
;
995 void SetIsFormattingControl() {
996 MOZ_ASSERT(!IsSimpleGlyph());
997 mValue
|= FLAG_CHAR_IS_FORMATTING_CONTROL
;
1004 // Accessor for the array of CompressedGlyph records, which will be in
1005 // a different place in gfxShapedWord vs gfxTextRun
1006 virtual const CompressedGlyph
* GetCharacterGlyphs() const = 0;
1007 virtual CompressedGlyph
* GetCharacterGlyphs() = 0;
1010 * When the glyphs for a character don't fit into a CompressedGlyph record
1011 * in SimpleGlyph format, we use an array of DetailedGlyphs instead.
1013 struct DetailedGlyph
{
1014 // The glyphID, or the Unicode character if this is a missing glyph
1016 // The advance of the glyph, in appunits.
1017 // mAdvance is in the text direction (RTL or LTR),
1018 // and will normally be non-negative (although this is not guaranteed)
1020 // The offset from the glyph's default position, in line-relative
1021 // coordinates (so mOffset.x is an offset in the line-right direction,
1022 // and mOffset.y is an offset in line-downwards direction).
1023 // These values are in floating-point appUnits.
1024 mozilla::gfx::Point mOffset
;
1027 // Store DetailedGlyph records for the given index. (This does not modify
1028 // the associated CompressedGlyph character-type or break flags.)
1029 void SetDetailedGlyphs(uint32_t aIndex
, uint32_t aGlyphCount
,
1030 const DetailedGlyph
* aGlyphs
);
1032 void SetMissingGlyph(uint32_t aIndex
, uint32_t aChar
, gfxFont
* aFont
);
1034 void SetIsSpace(uint32_t aIndex
) {
1035 GetCharacterGlyphs()[aIndex
].SetIsSpace();
1038 bool HasDetailedGlyphs() const { return mDetailedGlyphs
!= nullptr; }
1040 bool IsLigatureGroupStart(uint32_t aPos
) {
1041 NS_ASSERTION(aPos
< GetLength(), "aPos out of range");
1042 return GetCharacterGlyphs()[aPos
].IsLigatureGroupStart();
1045 // NOTE that this must not be called for a character offset that does
1046 // not have any DetailedGlyph records; callers must have verified that
1047 // GetCharacterGlyphs()[aCharIndex].GetGlyphCount() is greater than zero.
1048 DetailedGlyph
* GetDetailedGlyphs(uint32_t aCharIndex
) const {
1049 NS_ASSERTION(GetCharacterGlyphs() && HasDetailedGlyphs() &&
1050 !GetCharacterGlyphs()[aCharIndex
].IsSimpleGlyph() &&
1051 GetCharacterGlyphs()[aCharIndex
].GetGlyphCount() > 0,
1052 "invalid use of GetDetailedGlyphs; check the caller!");
1053 return mDetailedGlyphs
->Get(aCharIndex
);
1056 void AdjustAdvancesForSyntheticBold(float aSynBoldOffset
, uint32_t aOffset
,
1059 // Mark clusters in the CompressedGlyph records, starting at aOffset,
1060 // based on the Unicode properties of the text in aString.
1061 // This is also responsible to set the IsSpace flag for space characters.
1062 void SetupClusterBoundaries(uint32_t aOffset
, const char16_t
* aString
,
1064 // In 8-bit text, there won't actually be any clusters, but we still need
1065 // the space-marking functionality.
1066 void SetupClusterBoundaries(uint32_t aOffset
, const uint8_t* aString
,
1069 mozilla::gfx::ShapedTextFlags
GetFlags() const { return mFlags
; }
1071 bool IsVertical() const {
1072 return (GetFlags() & mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_MASK
) !=
1073 mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_HORIZONTAL
;
1076 bool UseCenterBaseline() const {
1077 mozilla::gfx::ShapedTextFlags orient
=
1078 GetFlags() & mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_MASK
;
1080 mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_MIXED
||
1082 mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_UPRIGHT
;
1085 bool IsRightToLeft() const {
1086 return (GetFlags() & mozilla::gfx::ShapedTextFlags::TEXT_IS_RTL
) ==
1087 mozilla::gfx::ShapedTextFlags::TEXT_IS_RTL
;
1090 bool IsSidewaysLeft() const {
1091 return (GetFlags() & mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_MASK
) ==
1092 mozilla::gfx::ShapedTextFlags::TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT
;
1095 // Return true if the logical inline direction is reversed compared to
1096 // normal physical coordinates (i.e. if it is leftwards or upwards)
1097 bool IsInlineReversed() const { return IsSidewaysLeft() != IsRightToLeft(); }
1099 gfxFloat
GetDirection() const { return IsInlineReversed() ? -1.0f
: 1.0f
; }
1101 bool DisableLigatures() const {
1102 return (GetFlags() &
1103 mozilla::gfx::ShapedTextFlags::TEXT_DISABLE_OPTIONAL_LIGATURES
) ==
1104 mozilla::gfx::ShapedTextFlags::TEXT_DISABLE_OPTIONAL_LIGATURES
;
1107 bool TextIs8Bit() const {
1108 return (GetFlags() & mozilla::gfx::ShapedTextFlags::TEXT_IS_8BIT
) ==
1109 mozilla::gfx::ShapedTextFlags::TEXT_IS_8BIT
;
1112 int32_t GetAppUnitsPerDevUnit() const { return mAppUnitsPerDevUnit
; }
1114 uint32_t GetLength() const { return mLength
; }
1116 bool FilterIfIgnorable(uint32_t aIndex
, uint32_t aCh
);
1119 // Allocate aCount DetailedGlyphs for the given index
1120 DetailedGlyph
* AllocateDetailedGlyphs(uint32_t aCharIndex
, uint32_t aCount
);
1122 // Ensure the glyph on the given index is complex glyph so that we can use
1123 // it to record specific characters that layout may need to detect.
1124 void EnsureComplexGlyph(uint32_t aIndex
, CompressedGlyph
& aGlyph
) {
1125 MOZ_ASSERT(GetCharacterGlyphs() + aIndex
== &aGlyph
);
1126 if (aGlyph
.IsSimpleGlyph()) {
1127 DetailedGlyph details
= {aGlyph
.GetSimpleGlyph(),
1128 (int32_t)aGlyph
.GetSimpleAdvance(),
1129 mozilla::gfx::Point()};
1130 aGlyph
.SetComplex(true, true);
1131 SetDetailedGlyphs(aIndex
, 1, &details
);
1135 // For characters whose glyph data does not fit the "simple" glyph criteria
1136 // in CompressedGlyph, we use a sorted array to store the association
1137 // between the source character offset and an index into an array
1138 // DetailedGlyphs. The CompressedGlyph record includes a count of
1139 // the number of DetailedGlyph records that belong to the character,
1140 // starting at the given index.
1141 class DetailedGlyphStore
{
1143 DetailedGlyphStore() = default;
1145 // This is optimized for the most common calling patterns:
1146 // we rarely need random access to the records, access is most commonly
1147 // sequential through the textRun, so we record the last-used index
1148 // and check whether the caller wants the same record again, or the
1149 // next; if not, it's most likely we're starting over from the start
1150 // of the run, so we check the first entry before resorting to binary
1151 // search as a last resort.
1152 // NOTE that this must not be called for a character offset that does
1153 // not have any DetailedGlyph records; callers must have verified that
1154 // mCharacterGlyphs[aOffset].GetGlyphCount() is greater than zero
1155 // before calling this, otherwise the assertions here will fire (in a
1156 // debug build), and we'll probably crash.
1157 DetailedGlyph
* Get(uint32_t aOffset
) {
1158 NS_ASSERTION(mOffsetToIndex
.Length() > 0, "no detailed glyph records!");
1159 DetailedGlyph
* details
= mDetails
.Elements();
1160 // check common cases (fwd iteration, initial entry, etc) first
1161 if (mLastUsed
< mOffsetToIndex
.Length() - 1 &&
1162 aOffset
== mOffsetToIndex
[mLastUsed
+ 1].mOffset
) {
1164 } else if (aOffset
== mOffsetToIndex
[0].mOffset
) {
1166 } else if (aOffset
== mOffsetToIndex
[mLastUsed
].mOffset
) {
1168 } else if (mLastUsed
> 0 &&
1169 aOffset
== mOffsetToIndex
[mLastUsed
- 1].mOffset
) {
1172 mLastUsed
= mOffsetToIndex
.BinaryIndexOf(aOffset
, CompareToOffset());
1174 NS_ASSERTION(mLastUsed
!= nsTArray
<DGRec
>::NoIndex
,
1175 "detailed glyph record missing!");
1176 return details
+ mOffsetToIndex
[mLastUsed
].mIndex
;
1179 DetailedGlyph
* Allocate(uint32_t aOffset
, uint32_t aCount
) {
1180 uint32_t detailIndex
= mDetails
.Length();
1181 DetailedGlyph
* details
= mDetails
.AppendElements(aCount
);
1182 // We normally set up glyph records sequentially, so the common case
1183 // here is to append new records to the mOffsetToIndex array;
1184 // test for that before falling back to the InsertElementSorted
1186 if (mOffsetToIndex
.Length() == 0 ||
1187 aOffset
> mOffsetToIndex
[mOffsetToIndex
.Length() - 1].mOffset
) {
1188 mOffsetToIndex
.AppendElement(DGRec(aOffset
, detailIndex
));
1190 mOffsetToIndex
.InsertElementSorted(DGRec(aOffset
, detailIndex
),
1191 CompareRecordOffsets());
1196 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf
) {
1197 return aMallocSizeOf(this) +
1198 mDetails
.ShallowSizeOfExcludingThis(aMallocSizeOf
) +
1199 mOffsetToIndex
.ShallowSizeOfExcludingThis(aMallocSizeOf
);
1204 DGRec(const uint32_t& aOffset
, const uint32_t& aIndex
)
1205 : mOffset(aOffset
), mIndex(aIndex
) {}
1206 uint32_t mOffset
; // source character offset in the textrun
1207 uint32_t mIndex
; // index where this char's DetailedGlyphs begin
1210 struct CompareToOffset
{
1211 bool Equals(const DGRec
& a
, const uint32_t& b
) const {
1212 return a
.mOffset
== b
;
1214 bool LessThan(const DGRec
& a
, const uint32_t& b
) const {
1215 return a
.mOffset
< b
;
1219 struct CompareRecordOffsets
{
1220 bool Equals(const DGRec
& a
, const DGRec
& b
) const {
1221 return a
.mOffset
== b
.mOffset
;
1223 bool LessThan(const DGRec
& a
, const DGRec
& b
) const {
1224 return a
.mOffset
< b
.mOffset
;
1228 // Concatenated array of all the DetailedGlyph records needed for the
1229 // textRun; individual character offsets are associated with indexes
1230 // into this array via the mOffsetToIndex table.
1231 nsTArray
<DetailedGlyph
> mDetails
;
1233 // For each character offset that needs DetailedGlyphs, we record the
1234 // index in mDetails where the list of glyphs begins. This array is
1235 // sorted by mOffset.
1236 nsTArray
<DGRec
> mOffsetToIndex
;
1238 // Records the most recently used index into mOffsetToIndex, so that
1239 // we can support sequential access more quickly than just doing
1240 // a binary search each time.
1241 nsTArray
<DGRec
>::index_type mLastUsed
= 0;
1244 mozilla::UniquePtr
<DetailedGlyphStore
> mDetailedGlyphs
;
1246 // Number of char16_t characters and CompressedGlyph glyph records
1249 // Shaping flags (direction, ligature-suppression)
1250 mozilla::gfx::ShapedTextFlags mFlags
;
1252 uint16_t mAppUnitsPerDevUnit
;
1256 * gfxShapedWord: an individual (space-delimited) run of text shaped with a
1257 * particular font, without regard to external context.
1259 * The glyph data is copied into gfxTextRuns as needed from the cache of
1260 * ShapedWords associated with each gfxFont instance.
1262 class gfxShapedWord final
: public gfxShapedText
{
1264 typedef mozilla::unicode::Script Script
;
1266 // Create a ShapedWord that can hold glyphs for aLength characters,
1267 // with mCharacterGlyphs sized appropriately.
1269 // Returns null on allocation failure (does NOT use infallible alloc)
1270 // so caller must check for success.
1272 // This does NOT perform shaping, so the returned word contains no
1273 // glyph data; the caller must call gfxFont::ShapeText() with appropriate
1274 // parameters to set up the glyphs.
1275 static gfxShapedWord
* Create(const uint8_t* aText
, uint32_t aLength
,
1276 Script aRunScript
, nsAtom
* aLanguage
,
1277 uint16_t aAppUnitsPerDevUnit
,
1278 mozilla::gfx::ShapedTextFlags aFlags
,
1279 gfxFontShaper::RoundingFlags aRounding
) {
1280 NS_ASSERTION(aLength
<= gfxPlatform::GetPlatform()->WordCacheCharLimit(),
1281 "excessive length for gfxShapedWord!");
1283 // Compute size needed including the mCharacterGlyphs array
1284 // and a copy of the original text
1285 uint32_t size
= offsetof(gfxShapedWord
, mCharGlyphsStorage
) +
1286 aLength
* (sizeof(CompressedGlyph
) + sizeof(uint8_t));
1287 void* storage
= malloc(size
);
1292 // Construct in the pre-allocated storage, using placement new
1293 return new (storage
) gfxShapedWord(aText
, aLength
, aRunScript
, aLanguage
,
1294 aAppUnitsPerDevUnit
, aFlags
, aRounding
);
1297 static gfxShapedWord
* Create(const char16_t
* aText
, uint32_t aLength
,
1298 Script aRunScript
, nsAtom
* aLanguage
,
1299 uint16_t aAppUnitsPerDevUnit
,
1300 mozilla::gfx::ShapedTextFlags aFlags
,
1301 gfxFontShaper::RoundingFlags aRounding
) {
1302 NS_ASSERTION(aLength
<= gfxPlatform::GetPlatform()->WordCacheCharLimit(),
1303 "excessive length for gfxShapedWord!");
1305 // In the 16-bit version of Create, if the TEXT_IS_8BIT flag is set,
1306 // then we convert the text to an 8-bit version and call the 8-bit
1307 // Create function instead.
1308 if (aFlags
& mozilla::gfx::ShapedTextFlags::TEXT_IS_8BIT
) {
1309 nsAutoCString narrowText
;
1310 LossyAppendUTF16toASCII(nsDependentSubstring(aText
, aLength
), narrowText
);
1311 return Create((const uint8_t*)(narrowText
.BeginReading()), aLength
,
1312 aRunScript
, aLanguage
, aAppUnitsPerDevUnit
, aFlags
,
1316 uint32_t size
= offsetof(gfxShapedWord
, mCharGlyphsStorage
) +
1317 aLength
* (sizeof(CompressedGlyph
) + sizeof(char16_t
));
1318 void* storage
= malloc(size
);
1323 return new (storage
) gfxShapedWord(aText
, aLength
, aRunScript
, aLanguage
,
1324 aAppUnitsPerDevUnit
, aFlags
, aRounding
);
1327 // Override operator delete to properly free the object that was
1328 // allocated via malloc.
1329 void operator delete(void* p
) { free(p
); }
1331 const CompressedGlyph
* GetCharacterGlyphs() const override
{
1332 return &mCharGlyphsStorage
[0];
1334 CompressedGlyph
* GetCharacterGlyphs() override
{
1335 return &mCharGlyphsStorage
[0];
1338 const uint8_t* Text8Bit() const {
1339 NS_ASSERTION(TextIs8Bit(), "invalid use of Text8Bit()");
1340 return reinterpret_cast<const uint8_t*>(mCharGlyphsStorage
+ GetLength());
1343 const char16_t
* TextUnicode() const {
1344 NS_ASSERTION(!TextIs8Bit(), "invalid use of TextUnicode()");
1345 return reinterpret_cast<const char16_t
*>(mCharGlyphsStorage
+ GetLength());
1348 char16_t
GetCharAt(uint32_t aOffset
) const {
1349 NS_ASSERTION(aOffset
< GetLength(), "aOffset out of range");
1350 return TextIs8Bit() ? char16_t(Text8Bit()[aOffset
])
1351 : TextUnicode()[aOffset
];
1354 Script
GetScript() const { return mScript
; }
1355 nsAtom
* GetLanguage() const { return mLanguage
.get(); }
1357 gfxFontShaper::RoundingFlags
GetRounding() const { return mRounding
; }
1359 void ResetAge() { mAgeCounter
= 0; }
1360 uint32_t IncrementAge() { return ++mAgeCounter
; }
1362 // Helper used when hashing a word for the shaped-word caches
1363 static uint32_t HashMix(uint32_t aHash
, char16_t aCh
) {
1364 return (aHash
>> 28) ^ (aHash
<< 4) ^ aCh
;
1368 // so that gfxTextRun can share our DetailedGlyphStore class
1369 friend class gfxTextRun
;
1371 // Construct storage for a ShapedWord, ready to receive glyph data
1372 gfxShapedWord(const uint8_t* aText
, uint32_t aLength
, Script aRunScript
,
1373 nsAtom
* aLanguage
, uint16_t aAppUnitsPerDevUnit
,
1374 mozilla::gfx::ShapedTextFlags aFlags
,
1375 gfxFontShaper::RoundingFlags aRounding
)
1376 : gfxShapedText(aLength
,
1377 aFlags
| mozilla::gfx::ShapedTextFlags::TEXT_IS_8BIT
,
1378 aAppUnitsPerDevUnit
),
1379 mLanguage(aLanguage
),
1380 mScript(aRunScript
),
1381 mRounding(aRounding
),
1383 memset(mCharGlyphsStorage
, 0, aLength
* sizeof(CompressedGlyph
));
1384 uint8_t* text
= reinterpret_cast<uint8_t*>(&mCharGlyphsStorage
[aLength
]);
1385 memcpy(text
, aText
, aLength
* sizeof(uint8_t));
1388 gfxShapedWord(const char16_t
* aText
, uint32_t aLength
, Script aRunScript
,
1389 nsAtom
* aLanguage
, uint16_t aAppUnitsPerDevUnit
,
1390 mozilla::gfx::ShapedTextFlags aFlags
,
1391 gfxFontShaper::RoundingFlags aRounding
)
1392 : gfxShapedText(aLength
, aFlags
, aAppUnitsPerDevUnit
),
1393 mLanguage(aLanguage
),
1394 mScript(aRunScript
),
1395 mRounding(aRounding
),
1397 memset(mCharGlyphsStorage
, 0, aLength
* sizeof(CompressedGlyph
));
1398 char16_t
* text
= reinterpret_cast<char16_t
*>(&mCharGlyphsStorage
[aLength
]);
1399 memcpy(text
, aText
, aLength
* sizeof(char16_t
));
1400 SetupClusterBoundaries(0, aText
, aLength
);
1403 RefPtr
<nsAtom
> mLanguage
;
1406 gfxFontShaper::RoundingFlags mRounding
;
1408 uint32_t mAgeCounter
;
1410 // The mCharGlyphsStorage array is actually a variable-size member;
1411 // when the ShapedWord is created, its size will be increased as necessary
1412 // to allow the proper number of glyphs to be stored.
1413 // The original text, in either 8-bit or 16-bit form, will be stored
1414 // immediately following the CompressedGlyphs.
1415 CompressedGlyph mCharGlyphsStorage
[1];
1418 class GlyphBufferAzure
;
1419 struct TextRunDrawParams
;
1420 struct FontDrawParams
;
1421 struct EmphasisMarkDrawParams
;
1424 friend class gfxHarfBuzzShaper
;
1425 friend class gfxGraphiteShaper
;
1428 using DrawTarget
= mozilla::gfx::DrawTarget
;
1429 using Script
= mozilla::unicode::Script
;
1430 using SVGContextPaint
= mozilla::SVGContextPaint
;
1432 using RoundingFlags
= gfxFontShaper::RoundingFlags
;
1435 using FontSlantStyle
= mozilla::FontSlantStyle
;
1436 using FontSizeAdjust
= mozilla::StyleFontSizeAdjust
;
1438 nsrefcnt
AddRef(void) {
1439 MOZ_ASSERT(int32_t(mRefCnt
) >= 0, "illegal refcnt");
1440 if (mExpirationState
.IsTracked()) {
1441 gfxFontCache::GetCache()->RemoveObject(this);
1444 NS_LOG_ADDREF(this, mRefCnt
, "gfxFont", sizeof(*this));
1447 nsrefcnt
Release(void) {
1448 MOZ_ASSERT(0 != mRefCnt
, "dup release");
1450 NS_LOG_RELEASE(this, mRefCnt
, "gfxFont");
1453 // |this| may have been deleted.
1459 int32_t GetRefCount() { return mRefCnt
; }
1461 // options to specify the kind of AA to be used when creating a font
1462 typedef enum : uint8_t {
1465 kAntialiasGrayscale
,
1470 nsAutoRefCnt mRefCnt
;
1472 void NotifyReleased() {
1473 gfxFontCache
* cache
= gfxFontCache::GetCache();
1475 // Don't delete just yet; return the object to the cache for
1476 // possibly recycling within some time limit
1477 cache
->NotifyReleased(this);
1479 // The cache may have already been shut down.
1484 gfxFont(const RefPtr
<mozilla::gfx::UnscaledFont
>& aUnscaledFont
,
1485 gfxFontEntry
* aFontEntry
, const gfxFontStyle
* aFontStyle
,
1486 AntialiasOption anAAOption
= kAntialiasDefault
);
1491 bool Valid() const { return mIsValid
; }
1493 // options for the kind of bounding box to return from measurement
1496 // A box that encloses all the painted pixels, and may
1497 // include sidebearings and/or additional ascent/descent
1498 // within the glyph cell even if the ink is smaller.
1500 // A box that tightly encloses all the painted pixels
1501 // (although actually on Windows, at least, it may be
1502 // slightly larger than strictly necessary because
1503 // we can't get precise extents with ClearType).
1504 TIGHT_HINTED_OUTLINE_EXTENTS
1505 // A box that tightly encloses the glyph outline,
1506 // ignoring possible antialiasing pixels that extend
1508 // NOTE: The default implementation of gfxFont::Measure(),
1509 // which works with the glyph extents cache, does not
1510 // differentiate between this and TIGHT_INK_EXTENTS.
1511 // Whether the distinction is important depends on the
1512 // antialiasing behavior of the platform; currently the
1513 // distinction is only implemented in the gfxWindowsFont
1514 // subclass, because of ClearType's tendency to paint
1515 // outside the hinted outline.
1516 // Also NOTE: it is relatively expensive to request this,
1517 // as it does not use cached glyph extents in the font.
1520 const nsCString
& GetName() const { return mFontEntry
->Name(); }
1521 const gfxFontStyle
* GetStyle() const { return &mStyle
; }
1523 virtual mozilla::UniquePtr
<gfxFont
> CopyWithAntialiasOption(
1524 AntialiasOption anAAOption
) {
1525 // platforms where this actually matters should override
1529 gfxFloat
GetAdjustedSize() const {
1530 // mAdjustedSize is cached here if not already set to a non-zero value;
1531 // but it may be overridden by a value computed in metrics initialization
1532 // from font-size-adjust.
1533 if (mAdjustedSize
< 0.0) {
1534 mAdjustedSize
= mStyle
.AdjustedSizeMustBeZero()
1536 : mStyle
.size
* mFontEntry
->mSizeAdjust
;
1538 return mAdjustedSize
;
1541 float FUnitsToDevUnitsFactor() const {
1542 // check this was set up during font initialization
1543 NS_ASSERTION(mFUnitsConvFactor
>= 0.0f
, "mFUnitsConvFactor not valid");
1544 return mFUnitsConvFactor
;
1547 // check whether this is an sfnt we can potentially use with harfbuzz
1548 bool FontCanSupportHarfBuzz() { return mFontEntry
->HasCmapTable(); }
1550 // check whether this is an sfnt we can potentially use with Graphite
1551 bool FontCanSupportGraphite() { return mFontEntry
->HasGraphiteTables(); }
1553 // Whether this is a font that may be doing full-color rendering,
1554 // and therefore needs us to use a mask for text-shadow even when
1555 // we're not actually blurring.
1556 bool AlwaysNeedsMaskForShadow() {
1557 return mFontEntry
->TryGetColorGlyphs() || mFontEntry
->TryGetSVGData(this) ||
1558 mFontEntry
->HasFontTable(TRUETYPE_TAG('C', 'B', 'D', 'T')) ||
1559 mFontEntry
->HasFontTable(TRUETYPE_TAG('s', 'b', 'i', 'x'));
1562 // whether a feature is supported by the font (limited to a small set
1563 // of features for which some form of fallback needs to be implemented)
1564 bool SupportsFeature(Script aScript
, uint32_t aFeatureTag
);
1566 // whether the font supports "real" small caps, petite caps etc.
1567 // aFallbackToSmallCaps true when petite caps should fallback to small caps
1568 bool SupportsVariantCaps(Script aScript
, uint32_t aVariantCaps
,
1569 bool& aFallbackToSmallCaps
,
1570 bool& aSyntheticLowerToSmallCaps
,
1571 bool& aSyntheticUpperToSmallCaps
);
1573 // whether the font supports subscript/superscript feature
1574 // for fallback, need to verify that all characters in the run
1575 // have variant substitutions
1576 bool SupportsSubSuperscript(uint32_t aSubSuperscript
, const uint8_t* aString
,
1577 uint32_t aLength
, Script aRunScript
);
1579 bool SupportsSubSuperscript(uint32_t aSubSuperscript
, const char16_t
* aString
,
1580 uint32_t aLength
, Script aRunScript
);
1582 // whether the specified feature will apply to the given character
1583 bool FeatureWillHandleChar(Script aRunScript
, uint32_t aFeature
,
1586 // Subclasses may choose to look up glyph ids for characters.
1587 // If they do not override this, gfxHarfBuzzShaper will fetch the cmap
1588 // table and use that.
1589 virtual bool ProvidesGetGlyph() const { return false; }
1590 // Map unicode character to glyph ID.
1591 // Only used if ProvidesGetGlyph() returns true.
1592 virtual uint32_t GetGlyph(uint32_t unicode
, uint32_t variation_selector
) {
1596 // Return the advance of a glyph.
1597 gfxFloat
GetGlyphAdvance(uint16_t aGID
, bool aVertical
= false);
1599 // Return the advance of a given Unicode char in isolation.
1600 // Returns -1.0 if the char is not supported.
1601 gfxFloat
GetCharAdvance(uint32_t aUnicode
, bool aVertical
= false);
1603 gfxFloat
SynthesizeSpaceWidth(uint32_t aCh
);
1605 // Work out whether cairo will snap inter-glyph spacing to pixels
1606 // when rendering to the given drawTarget.
1607 RoundingFlags
GetRoundOffsetsToPixels(DrawTarget
* aDrawTarget
);
1609 virtual bool ShouldHintMetrics() const { return true; }
1610 virtual bool ShouldRoundXOffset(cairo_t
* aCairo
) const { return true; }
1616 gfxFloat strikeoutSize
;
1617 gfxFloat strikeoutOffset
;
1618 gfxFloat underlineSize
;
1619 gfxFloat underlineOffset
;
1621 gfxFloat internalLeading
;
1622 gfxFloat externalLeading
;
1629 gfxFloat maxDescent
;
1630 gfxFloat maxAdvance
;
1632 gfxFloat aveCharWidth
;
1633 gfxFloat spaceWidth
;
1634 gfxFloat zeroWidth
; // -1 if there was no zero glyph
1636 gfxFloat
ZeroOrAveCharWidth() const {
1637 return zeroWidth
>= 0 ? zeroWidth
: aveCharWidth
;
1641 typedef nsFontMetrics::FontOrientation Orientation
;
1643 const Metrics
& GetMetrics(Orientation aOrientation
) {
1644 if (aOrientation
== nsFontMetrics::eHorizontal
) {
1645 return GetHorizontalMetrics();
1647 if (!mVerticalMetrics
) {
1648 mVerticalMetrics
= CreateVerticalMetrics();
1650 return *mVerticalMetrics
;
1654 * We let layout specify spacing on either side of any
1655 * character. We need to specify both before and after
1656 * spacing so that substring measurement can do the right things.
1657 * These values are in appunits. They're always an integral number of
1658 * appunits, but we specify them in floats in case very large spacing
1659 * values are required.
1666 * Metrics for a particular string
1669 RunMetrics() { mAdvanceWidth
= mAscent
= mDescent
= 0.0; }
1671 void CombineWith(const RunMetrics
& aOther
, bool aOtherIsOnLeft
);
1673 // can be negative (partly due to negative spacing).
1674 // Advance widths should be additive: the advance width of the
1675 // (offset1, length1) plus the advance width of (offset1 + length1,
1676 // length2) should be the advance width of (offset1, length1 + length2)
1677 gfxFloat mAdvanceWidth
;
1679 // For zero-width substrings, these must be zero!
1680 gfxFloat mAscent
; // always non-negative
1681 gfxFloat mDescent
; // always non-negative
1683 // Bounding box that is guaranteed to include everything drawn.
1684 // If a tight boundingBox was requested when these metrics were
1685 // generated, this will tightly wrap the glyphs, otherwise it is
1686 // "loose" and may be larger than the true bounding box.
1687 // Coordinates are relative to the baseline left origin, so typically
1688 // mBoundingBox.y == -mAscent
1689 gfxRect mBoundingBox
;
1693 * Draw a series of glyphs to aContext. The direction of aTextRun must
1695 * @param aStart the first character to draw
1696 * @param aEnd draw characters up to here
1697 * @param aPt the baseline origin; the left end of the baseline
1698 * for LTR textruns, the right end for RTL textruns.
1699 * On return, this will be updated to the other end of the baseline.
1700 * In application units, really!
1701 * @param aRunParams record with drawing parameters, see TextRunDrawParams.
1702 * Particular fields of interest include
1703 * .spacing spacing to insert before and after characters (for RTL
1704 * glyphs, before-spacing is inserted to the right of characters). There
1705 * are aEnd - aStart elements in this array, unless it's null to indicate
1706 * that there is no spacing.
1707 * .drawMode specifies whether the fill or stroke of the glyph should be
1708 * drawn, or if it should be drawn into the current path
1709 * .contextPaint information about how to construct the fill and
1710 * stroke pattern. Can be nullptr if we are not stroking the text, which
1711 * indicates that the current source from context should be used for fill
1712 * .context the Thebes graphics context to which we're drawing
1713 * .dt Moz2D DrawTarget to which we're drawing
1715 * Callers guarantee:
1716 * -- aStart and aEnd are aligned to cluster and ligature boundaries
1717 * -- all glyphs use this font
1719 void Draw(const gfxTextRun
* aTextRun
, uint32_t aStart
, uint32_t aEnd
,
1720 mozilla::gfx::Point
* aPt
, const TextRunDrawParams
& aRunParams
,
1721 mozilla::gfx::ShapedTextFlags aOrientation
);
1724 * Draw the emphasis marks for the given text run. Its prerequisite
1725 * and output are similiar to the method Draw().
1726 * @param aPt the baseline origin of the emphasis marks.
1727 * @param aParams some drawing parameters, see EmphasisMarkDrawParams.
1729 void DrawEmphasisMarks(const gfxTextRun
* aShapedText
,
1730 mozilla::gfx::Point
* aPt
, uint32_t aOffset
,
1732 const EmphasisMarkDrawParams
& aParams
);
1735 * Measure a run of characters. See gfxTextRun::Metrics.
1736 * @param aTight if false, then return the union of the glyph extents
1737 * with the font-box for the characters (the rectangle with x=0,width=
1738 * the advance width for the character run,y=-(font ascent), and height=
1739 * font ascent + font descent). Otherwise, we must return as tight as possible
1740 * an approximation to the area actually painted by glyphs.
1741 * @param aDrawTargetForTightBoundingBox when aTight is true, this must
1743 * @param aSpacing spacing to insert before and after glyphs. The bounding box
1744 * need not include the spacing itself, but the spacing affects the glyph
1745 * positions. null if there is no spacing.
1747 * Callers guarantee:
1748 * -- aStart and aEnd are aligned to cluster and ligature boundaries
1749 * -- all glyphs use this font
1751 * The default implementation just uses font metrics and aTextRun's
1752 * advances, and assumes no characters fall outside the font box. In
1753 * general this is insufficient, because that assumption is not always true.
1755 virtual RunMetrics
Measure(const gfxTextRun
* aTextRun
, uint32_t aStart
,
1756 uint32_t aEnd
, BoundingBoxType aBoundingBoxType
,
1757 DrawTarget
* aDrawTargetForTightBoundingBox
,
1759 mozilla::gfx::ShapedTextFlags aOrientation
);
1761 * Line breaks have been changed at the beginning and/or end of a substring
1762 * of the text. Reshaping may be required; glyph updating is permitted.
1763 * @return true if anything was changed, false otherwise
1765 bool NotifyLineBreaksChanged(gfxTextRun
* aTextRun
, uint32_t aStart
,
1770 // Expiration tracking
1771 nsExpirationState
* GetExpirationState() { return &mExpirationState
; }
1773 // Get the glyphID of a space
1774 uint16_t GetSpaceGlyph() { return mSpaceGlyph
; }
1776 gfxGlyphExtents
* GetOrCreateGlyphExtents(int32_t aAppUnitsPerDevUnit
);
1778 void SetupGlyphExtents(DrawTarget
* aDrawTarget
, uint32_t aGlyphID
,
1779 bool aNeedTight
, gfxGlyphExtents
* aExtents
);
1781 virtual bool AllowSubpixelAA() { return true; }
1783 bool IsSyntheticBold() const { return mApplySyntheticBold
; }
1785 float AngleForSyntheticOblique() const;
1786 float SkewForSyntheticOblique() const;
1788 // Amount by which synthetic bold "fattens" the glyphs:
1789 // For size S up to a threshold size T, we use (0.25 + 3S / 4T),
1790 // so that the result ranges from 0.25 to 1.0; thereafter,
1791 // simply use (S / T).
1792 gfxFloat
GetSyntheticBoldOffset() {
1793 gfxFloat size
= GetAdjustedSize();
1794 const gfxFloat threshold
= 48.0;
1795 return size
< threshold
? (0.25 + 0.75 * size
/ threshold
)
1796 : (size
/ threshold
);
1799 gfxFontEntry
* GetFontEntry() const { return mFontEntry
.get(); }
1800 bool HasCharacter(uint32_t ch
) {
1801 if (!mIsValid
|| (mUnicodeRangeMap
&& !mUnicodeRangeMap
->test(ch
))) {
1804 return mFontEntry
->HasCharacter(ch
);
1807 const gfxCharacterMap
* GetUnicodeRangeMap() const {
1808 return mUnicodeRangeMap
.get();
1811 void SetUnicodeRangeMap(gfxCharacterMap
* aUnicodeRangeMap
) {
1812 mUnicodeRangeMap
= aUnicodeRangeMap
;
1815 uint16_t GetUVSGlyph(uint32_t aCh
, uint32_t aVS
) {
1819 return mFontEntry
->GetUVSGlyph(aCh
, aVS
);
1822 template <typename T
>
1823 bool InitFakeSmallCapsRun(nsPresContext
* aPresContext
,
1824 DrawTarget
* aDrawTarget
, gfxTextRun
* aTextRun
,
1825 const T
* aText
, uint32_t aOffset
, uint32_t aLength
,
1826 FontMatchType aMatchType
,
1827 mozilla::gfx::ShapedTextFlags aOrientation
,
1828 Script aScript
, nsAtom
* aLanguage
,
1829 bool aSyntheticLower
, bool aSyntheticUpper
);
1831 // call the (virtual) InitTextRun method to do glyph generation/shaping,
1832 // limiting the length of text passed by processing the run in multiple
1833 // segments if necessary
1834 template <typename T
>
1835 bool SplitAndInitTextRun(DrawTarget
* aDrawTarget
, gfxTextRun
* aTextRun
,
1836 const T
* aString
, uint32_t aRunStart
,
1837 uint32_t aRunLength
, Script aRunScript
,
1839 mozilla::gfx::ShapedTextFlags aOrientation
);
1841 // Get a ShapedWord representing the given text (either 8- or 16-bit)
1842 // for use in setting up a gfxTextRun.
1843 template <typename T
>
1844 gfxShapedWord
* GetShapedWord(DrawTarget
* aDrawTarget
, const T
* aText
,
1845 uint32_t aLength
, uint32_t aHash
,
1846 Script aRunScript
, nsAtom
* aLanguage
,
1847 bool aVertical
, int32_t aAppUnitsPerDevUnit
,
1848 mozilla::gfx::ShapedTextFlags aFlags
,
1849 RoundingFlags aRounding
,
1850 gfxTextPerfMetrics
* aTextPerf
);
1852 // Ensure the ShapedWord cache is initialized. This MUST be called before
1853 // any attempt to use GetShapedWord().
1854 void InitWordCache() {
1856 mWordCache
= mozilla::MakeUnique
<nsTHashtable
<CacheHashEntry
>>();
1860 // Called by the gfxFontCache timer to increment the age of all the words,
1861 // so that they'll expire after a sufficient period of non-use.
1862 // Returns true if the cache is now empty, otherwise false.
1863 bool AgeCachedWords();
1865 // Discard all cached word records; called on memory-pressure notification.
1866 void ClearCachedWords() {
1868 mWordCache
->Clear();
1872 // Glyph rendering/geometry has changed, so invalidate data as necessary.
1873 void NotifyGlyphsChanged();
1875 virtual void AddSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf
,
1876 FontCacheSizes
* aSizes
) const;
1877 virtual void AddSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf
,
1878 FontCacheSizes
* aSizes
) const;
1887 FONT_TYPE_FONTCONFIG
1890 virtual FontType
GetType() const = 0;
1892 const RefPtr
<mozilla::gfx::UnscaledFont
>& GetUnscaledFont() const {
1893 return mUnscaledFont
;
1896 virtual already_AddRefed
<mozilla::gfx::ScaledFont
> GetScaledFont(
1897 DrawTarget
* aTarget
) = 0;
1898 virtual already_AddRefed
<mozilla::gfx::ScaledFont
> GetScaledFontNoGDI(
1899 DrawTarget
* aTarget
) {
1900 return GetScaledFont(aTarget
);
1903 void InitializeScaledFont();
1905 bool KerningDisabled() { return mKerningSet
&& !mKerningEnabled
; }
1908 * Subclass this object to be notified of glyph changes. Delete the object
1909 * when no longer needed.
1911 class GlyphChangeObserver
{
1913 virtual ~GlyphChangeObserver() {
1915 mFont
->RemoveGlyphChangeObserver(this);
1918 // This gets called when the gfxFont dies.
1919 void ForgetFont() { mFont
= nullptr; }
1920 virtual void NotifyGlyphsChanged() = 0;
1923 explicit GlyphChangeObserver(gfxFont
* aFont
) : mFont(aFont
) {
1924 mFont
->AddGlyphChangeObserver(this);
1926 // This pointer is nulled by ForgetFont in the gfxFont's
1927 // destructor. Before the gfxFont dies.
1928 gfxFont
* MOZ_NON_OWNING_REF mFont
;
1930 friend class GlyphChangeObserver
;
1932 bool GlyphsMayChange() {
1933 // Currently only fonts with SVG glyphs can have animated glyphs
1934 return mFontEntry
->TryGetSVGData(this);
1937 static void DestroySingletons() {
1938 delete sScriptTagToCode
;
1939 delete sDefaultFeatures
;
1942 // Call TryGetMathTable() to try and load the Open Type MATH table.
1943 // If (and ONLY if) TryGetMathTable() has returned true, the MathTable()
1944 // method may be called to access the gfxMathTable data.
1945 bool TryGetMathTable();
1946 gfxMathTable
* MathTable() {
1947 MOZ_RELEASE_ASSERT(mMathTable
,
1948 "A successful call to TryGetMathTable() must be "
1949 "performed before calling this function");
1950 return mMathTable
.get();
1953 // Return a cloned font resized and offset to simulate sub/superscript
1954 // glyphs. This does not add a reference to the returned font.
1955 gfxFont
* GetSubSuperscriptFont(int32_t aAppUnitsPerDevPixel
);
1957 bool HasColorGlyphFor(uint32_t aCh
, uint32_t aNextCh
);
1960 virtual const Metrics
& GetHorizontalMetrics() = 0;
1962 mozilla::UniquePtr
<const Metrics
> CreateVerticalMetrics();
1964 // Template parameters for DrawGlyphs/DrawOneGlyph, used to select
1965 // simplified versions of the methods in the most common cases.
1966 enum class FontComplexityT
{ SimpleFont
, ComplexFont
};
1967 enum class SpacingT
{ NoSpacing
, HasSpacing
};
1969 // Output a run of glyphs at *aPt, which is updated to follow the last glyph
1970 // in the run. This method also takes account of any letter-spacing provided
1972 template <FontComplexityT FC
, SpacingT S
>
1973 bool DrawGlyphs(const gfxShapedText
* aShapedText
,
1974 uint32_t aOffset
, // offset in the textrun
1975 uint32_t aCount
, // length of run to draw
1976 mozilla::gfx::Point
* aPt
,
1977 // transform for mOffset field in DetailedGlyph records,
1978 // to account for rotations (may be null)
1979 const mozilla::gfx::Matrix
* aOffsetMatrix
,
1980 GlyphBufferAzure
& aBuffer
);
1982 // Output a single glyph at *aPt.
1983 // Normal glyphs are simply accumulated in aBuffer until it is full and
1984 // gets flushed, but SVG or color-font glyphs will instead be rendered
1985 // directly to the destination (found from the buffer's parameters).
1986 template <FontComplexityT FC
>
1987 void DrawOneGlyph(uint32_t aGlyphID
, const mozilla::gfx::Point
& aPt
,
1988 GlyphBufferAzure
& aBuffer
, bool* aEmittedGlyphs
);
1990 // Helper for DrawOneGlyph to handle missing glyphs, rendering either
1991 // nothing (for default-ignorables) or a missing-glyph hexbox.
1992 bool DrawMissingGlyph(const TextRunDrawParams
& aRunParams
,
1993 const FontDrawParams
& aFontParams
,
1994 const gfxShapedText::DetailedGlyph
* aDetails
,
1995 const mozilla::gfx::Point
& aPt
);
1997 // set the font size and offset used for
1998 // synthetic subscript/superscript glyphs
1999 void CalculateSubSuperSizeAndOffset(int32_t aAppUnitsPerDevPixel
,
2000 gfxFloat
& aSubSuperSizeRatio
,
2001 float& aBaselineOffset
);
2003 // Return a font that is a "clone" of this one, but reduced to 80% size
2004 // (and with variantCaps set to normal). This does not add a reference to
2005 // the returned font.
2006 gfxFont
* GetSmallCapsFont();
2008 // subclasses may provide (possibly hinted) glyph widths (in font units);
2009 // if they do not override this, harfbuzz will use unhinted widths
2010 // derived from the font tables
2011 virtual bool ProvidesGlyphWidths() const { return false; }
2013 // The return value is interpreted as a horizontal advance in 16.16 fixed
2015 virtual int32_t GetGlyphWidth(uint16_t aGID
) { return -1; }
2017 virtual bool GetGlyphBounds(uint16_t aGID
, gfxRect
* aBounds
,
2018 bool aTight
= false) {
2022 bool IsSpaceGlyphInvisible(DrawTarget
* aRefDrawTarget
,
2023 const gfxTextRun
* aTextRun
);
2025 void AddGlyphChangeObserver(GlyphChangeObserver
* aObserver
);
2026 void RemoveGlyphChangeObserver(GlyphChangeObserver
* aObserver
);
2028 // whether font contains substitution lookups containing spaces
2029 bool HasSubstitutionRulesWithSpaceLookups(Script aRunScript
);
2031 // do spaces participate in shaping rules? if so, can't used word cache
2032 // Note that this function uses HasGraphiteSpaceContextuals, so it can only
2033 // return a "hint" to the correct answer. The calling code must ensure it
2034 // performs safe actions independent of the value returned.
2035 tainted_boolean_hint
SpaceMayParticipateInShaping(Script aRunScript
);
2037 // For 8-bit text, expand to 16-bit and then call the following method.
2038 bool ShapeText(DrawTarget
* aContext
, const uint8_t* aText
,
2039 uint32_t aOffset
, // dest offset in gfxShapedText
2040 uint32_t aLength
, Script aScript
, nsAtom
* aLanguage
,
2041 bool aVertical
, RoundingFlags aRounding
,
2042 gfxShapedText
* aShapedText
); // where to store the result
2044 // Call the appropriate shaper to generate glyphs for aText and store
2045 // them into aShapedText.
2046 virtual bool ShapeText(DrawTarget
* aContext
, const char16_t
* aText
,
2047 uint32_t aOffset
, uint32_t aLength
, Script aScript
,
2048 nsAtom
* aLanguage
, bool aVertical
,
2049 RoundingFlags aRounding
, gfxShapedText
* aShapedText
);
2051 // Helper to adjust for synthetic bold and set character-type flags
2052 // in the shaped text; implementations of ShapeText should call this
2053 // after glyph shaping has been completed.
2054 void PostShapingFixup(DrawTarget
* aContext
, const char16_t
* aText
,
2055 uint32_t aOffset
, // position within aShapedText
2056 uint32_t aLength
, bool aVertical
,
2057 gfxShapedText
* aShapedText
);
2059 // Shape text directly into a range within a textrun, without using the
2060 // font's word cache. Intended for use when the font has layout features
2061 // that involve space, and therefore require shaping complete runs rather
2062 // than isolated words, or for long strings that are inefficient to cache.
2063 // This will split the text on "invalid" characters (tab/newline) that are
2064 // not handled via normal shaping, but does not otherwise divide up the
2066 template <typename T
>
2067 bool ShapeTextWithoutWordCache(DrawTarget
* aDrawTarget
, const T
* aText
,
2068 uint32_t aOffset
, uint32_t aLength
,
2069 Script aScript
, nsAtom
* aLanguage
,
2070 bool aVertical
, RoundingFlags aRounding
,
2071 gfxTextRun
* aTextRun
);
2073 // Shape a fragment of text (a run that is known to contain only
2074 // "valid" characters, no newlines/tabs/other control chars).
2075 // All non-wordcache shaping goes through here; this is the function
2076 // that will ensure we don't pass excessively long runs to the various
2077 // platform shapers.
2078 template <typename T
>
2079 bool ShapeFragmentWithoutWordCache(DrawTarget
* aDrawTarget
, const T
* aText
,
2080 uint32_t aOffset
, uint32_t aLength
,
2081 Script aScript
, nsAtom
* aLanguage
,
2082 bool aVertical
, RoundingFlags aRounding
,
2083 gfxTextRun
* aTextRun
);
2085 void CheckForFeaturesInvolvingSpace();
2087 // whether a given feature is included in feature settings from both the
2088 // font and the style. aFeatureOn set if resolved feature value is non-zero
2089 bool HasFeatureSet(uint32_t aFeature
, bool& aFeatureOn
);
2091 // used when analyzing whether a font has space contextual lookups
2092 static nsTHashMap
<nsUint32HashKey
, Script
>* sScriptTagToCode
;
2093 static nsTHashSet
<uint32_t>* sDefaultFeatures
;
2095 RefPtr
<gfxFontEntry
> mFontEntry
;
2097 struct CacheHashKey
{
2099 const uint8_t* mSingle
;
2100 const char16_t
* mDouble
;
2103 mozilla::gfx::ShapedTextFlags mFlags
;
2105 RefPtr
<nsAtom
> mLanguage
;
2106 int32_t mAppUnitsPerDevUnit
;
2107 PLDHashNumber mHashKey
;
2109 RoundingFlags mRounding
;
2111 CacheHashKey(const uint8_t* aText
, uint32_t aLength
, uint32_t aStringHash
,
2112 Script aScriptCode
, nsAtom
* aLanguage
,
2113 int32_t aAppUnitsPerDevUnit
,
2114 mozilla::gfx::ShapedTextFlags aFlags
, RoundingFlags aRounding
)
2117 mScript(aScriptCode
),
2118 mLanguage(aLanguage
),
2119 mAppUnitsPerDevUnit(aAppUnitsPerDevUnit
),
2120 mHashKey(aStringHash
+ static_cast<int32_t>(aScriptCode
) +
2121 aAppUnitsPerDevUnit
* 0x100 + uint16_t(aFlags
) * 0x10000 +
2122 int(aRounding
) + (aLanguage
? aLanguage
->hash() : 0)),
2124 mRounding(aRounding
) {
2125 NS_ASSERTION(aFlags
& mozilla::gfx::ShapedTextFlags::TEXT_IS_8BIT
,
2126 "8-bit flag should have been set");
2127 mText
.mSingle
= aText
;
2130 CacheHashKey(const char16_t
* aText
, uint32_t aLength
, uint32_t aStringHash
,
2131 Script aScriptCode
, nsAtom
* aLanguage
,
2132 int32_t aAppUnitsPerDevUnit
,
2133 mozilla::gfx::ShapedTextFlags aFlags
, RoundingFlags aRounding
)
2136 mScript(aScriptCode
),
2137 mLanguage(aLanguage
),
2138 mAppUnitsPerDevUnit(aAppUnitsPerDevUnit
),
2139 mHashKey(aStringHash
+ static_cast<int32_t>(aScriptCode
) +
2140 aAppUnitsPerDevUnit
* 0x100 + uint16_t(aFlags
) * 0x10000 +
2143 mRounding(aRounding
) {
2144 // We can NOT assert that TEXT_IS_8BIT is false in aFlags here,
2145 // because this might be an 8bit-only word from a 16-bit textrun,
2146 // in which case the text we're passed is still in 16-bit form,
2147 // and we'll have to use an 8-to-16bit comparison in KeyEquals.
2148 mText
.mDouble
= aText
;
2152 class CacheHashEntry
: public PLDHashEntryHdr
{
2154 typedef const CacheHashKey
& KeyType
;
2155 typedef const CacheHashKey
* KeyTypePointer
;
2157 // When constructing a new entry in the hashtable, the caller of Put()
2159 explicit CacheHashEntry(KeyTypePointer aKey
) {}
2160 CacheHashEntry(const CacheHashEntry
&) = delete;
2161 CacheHashEntry
& operator=(const CacheHashEntry
&) = delete;
2162 CacheHashEntry(CacheHashEntry
&&) = default;
2163 CacheHashEntry
& operator=(CacheHashEntry
&&) = default;
2165 bool KeyEquals(const KeyTypePointer aKey
) const;
2167 static KeyTypePointer
KeyToPointer(KeyType aKey
) { return &aKey
; }
2169 static PLDHashNumber
HashKey(const KeyTypePointer aKey
) {
2170 return aKey
->mHashKey
;
2173 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf
) const {
2174 return aMallocSizeOf(mShapedWord
.get());
2177 enum { ALLOW_MEMMOVE
= true };
2179 mozilla::UniquePtr
<gfxShapedWord
> mShapedWord
;
2182 mozilla::UniquePtr
<nsTHashtable
<CacheHashEntry
>> mWordCache
;
2184 static const uint32_t kShapedWordCacheMaxAge
= 3;
2186 nsTArray
<mozilla::UniquePtr
<gfxGlyphExtents
>> mGlyphExtentsArray
;
2187 mozilla::UniquePtr
<nsTHashSet
<GlyphChangeObserver
*>> mGlyphChangeObservers
;
2189 // a copy of the font without antialiasing, if needed for separate
2190 // measurement by mathml code
2191 mozilla::UniquePtr
<gfxFont
> mNonAAFont
;
2193 // we create either or both of these shapers when needed, depending
2194 // whether the font has graphite tables, and whether graphite shaping
2195 // is actually enabled
2196 mozilla::UniquePtr
<gfxFontShaper
> mHarfBuzzShaper
;
2197 mozilla::UniquePtr
<gfxFontShaper
> mGraphiteShaper
;
2199 // if a userfont with unicode-range specified, contains map of *possible*
2200 // ranges supported by font
2201 RefPtr
<gfxCharacterMap
> mUnicodeRangeMap
;
2203 RefPtr
<mozilla::gfx::UnscaledFont
> mUnscaledFont
;
2204 RefPtr
<mozilla::gfx::ScaledFont
> mAzureScaledFont
;
2206 // For vertical metrics, created on demand.
2207 mozilla::UniquePtr
<const Metrics
> mVerticalMetrics
;
2209 // Table used for MathML layout.
2210 mozilla::UniquePtr
<gfxMathTable
> mMathTable
;
2212 gfxFontStyle mStyle
;
2213 mutable gfxFloat mAdjustedSize
;
2215 // Conversion factor from font units to dev units; note that this may be
2216 // zero (in the degenerate case where mAdjustedSize has become zero).
2217 // This is OK because we only multiply by this factor, never divide.
2218 float mFUnitsConvFactor
;
2220 nsExpirationState mExpirationState
;
2222 // Glyph ID of the font's <space> glyph, zero if missing
2223 uint16_t mSpaceGlyph
= 0;
2225 // the AA setting requested for this font - may affect glyph bounds
2226 AntialiasOption mAntialiasOption
;
2230 // use synthetic bolding for environments where this is not supported
2232 bool mApplySyntheticBold
;
2234 bool mKerningSet
; // kerning explicitly set?
2235 bool mKerningEnabled
; // if set, on or off?
2237 bool mMathInitialized
; // TryGetMathTable() called?
2239 // Helper for subclasses that want to initialize standard metrics from the
2240 // tables of sfnt (TrueType/OpenType) fonts.
2241 // This will use mFUnitsConvFactor if it is already set, else compute it
2242 // from mAdjustedSize and the unitsPerEm in the font's 'head' table.
2243 // Returns TRUE and sets mIsValid=TRUE if successful;
2244 // Returns TRUE but leaves mIsValid=FALSE if the font seems to be broken.
2245 // Returns FALSE if the font does not appear to be an sfnt at all,
2246 // and should be handled (if possible) using other APIs.
2247 bool InitMetricsFromSfntTables(Metrics
& aMetrics
);
2249 // Helper to calculate various derived metrics from the results of
2250 // InitMetricsFromSfntTables or equivalent platform code
2251 void CalculateDerivedMetrics(Metrics
& aMetrics
);
2253 // some fonts have bad metrics, this method sanitize them.
2254 // if this font has bad underline offset, aIsBadUnderlineFont should be true.
2255 void SanitizeMetrics(Metrics
* aMetrics
, bool aIsBadUnderlineFont
);
2257 bool RenderSVGGlyph(gfxContext
* aContext
,
2258 mozilla::layout::TextDrawTarget
* aTextDrawer
,
2259 mozilla::gfx::Point aPoint
, uint32_t aGlyphId
,
2260 SVGContextPaint
* aContextPaint
) const;
2261 bool RenderSVGGlyph(gfxContext
* aContext
,
2262 mozilla::layout::TextDrawTarget
* aTextDrawer
,
2263 mozilla::gfx::Point aPoint
, uint32_t aGlyphId
,
2264 SVGContextPaint
* aContextPaint
,
2265 gfxTextRunDrawCallbacks
* aCallbacks
,
2266 bool& aEmittedGlyphs
) const;
2268 bool RenderColorGlyph(DrawTarget
* aDrawTarget
, gfxContext
* aContext
,
2269 mozilla::layout::TextDrawTarget
* aTextDrawer
,
2270 mozilla::gfx::ScaledFont
* scaledFont
,
2271 mozilla::gfx::DrawOptions drawOptions
,
2272 const mozilla::gfx::Point
& aPoint
,
2273 uint32_t aGlyphId
) const;
2275 // Bug 674909. When synthetic bolding text by drawing twice, need to
2276 // render using a pixel offset in device pixels, otherwise text
2277 // doesn't appear bolded, it appears as if a bad text shadow exists
2278 // when a non-identity transform exists. Use an offset factor so that
2279 // the second draw occurs at a constant offset in device pixels.
2280 // This helper calculates the scale factor we need to apply to the
2281 // synthetic-bold offset.
2282 static mozilla::gfx::Float
CalcXScale(DrawTarget
* aDrawTarget
);
2285 // proportion of ascent used for x-height, if unable to read value from font
2286 #define DEFAULT_XHEIGHT_FACTOR 0.56f
2288 // Parameters passed to gfxFont methods for drawing glyphs from a textrun.
2289 // The TextRunDrawParams are set up once per textrun; the FontDrawParams
2290 // are dependent on the specific font, so they are set per GlyphRun.
2292 struct MOZ_STACK_CLASS TextRunDrawParams
{
2293 RefPtr
<mozilla::gfx::DrawTarget
> dt
;
2294 gfxContext
* context
;
2295 gfxFont::Spacing
* spacing
;
2296 gfxTextRunDrawCallbacks
* callbacks
;
2297 mozilla::SVGContextPaint
* runContextPaint
;
2298 mozilla::gfx::Float direction
;
2300 nscolor textStrokeColor
;
2301 gfxPattern
* textStrokePattern
;
2302 const mozilla::gfx::StrokeOptions
* strokeOpts
;
2303 const mozilla::gfx::DrawOptions
* drawOpts
;
2307 bool paintSVGGlyphs
;
2311 struct MOZ_STACK_CLASS FontDrawParams
{
2312 RefPtr
<mozilla::gfx::ScaledFont
> scaledFont
;
2313 mozilla::SVGContextPaint
* contextPaint
;
2314 mozilla::gfx::Float synBoldOnePixelOffset
;
2315 mozilla::gfx::Float obliqueSkew
;
2316 int32_t extraStrikes
;
2317 mozilla::gfx::DrawOptions drawOptions
;
2318 gfxFloat advanceDirection
;
2319 bool isVerticalFont
;
2321 bool haveColorGlyphs
;
2324 struct MOZ_STACK_CLASS EmphasisMarkDrawParams
{
2325 gfxContext
* context
;
2326 gfxFont::Spacing
* spacing
;