Browse Source

[Text] Glyph Outline Part 12/17 - FontVariations property, XAML and animation (#22185)

* Bake FontVariationSettings into Typeface

Typeface is the value every text property funnels into before font
resolution, so variable-font axis values belong on it - same pattern as
weight and stretch, and the only way a single settings value can flow
from a style through layout to the renderer.

- both ctors take an optional FontVariationSettings; Empty is coerced to
  null at construction so equality, hashing and cache keys never
  distinguish the two "design defaults" spellings
- equality and hash include the settings (structural, cached hash)
- Normalize() and the FormattedText per-run updaters (SetFontFamily /
  SetFontWeight / SetFontStyle) carry the settings over when rebuilding

* Apply Typeface.FontVariations during font resolution

FontManager is the single seam every Typeface passes through on its way
to a GlyphTypeface, so the user-space settings are applied there - once,
at the end, whichever resolution path produced the base typeface.

- the resolution body moves to a private TryResolveGlyphTypeface (the
  default-family recursions target it directly); the public method
  resolves, then binds the variations via GlyphTypeface.WithVariations
- per-variation instances are cached on the resolved typeface, so
  repeated lookups with equal settings return the same instance (pinned
  by test against the embedded Inter Variable)
- font fallback carries the variations over: the matched fallback family
  renders at the same axis values the primary typeface requested, each
  font clamping to its own axes (CSS behavior)

* Expose FontVariations as an inherited text property

TextElement.FontVariationsProperty is the user-facing entry point for
variable-font configuration, following the FontStretch pattern exactly:
an inherited attached property that every typeface bake site folds into
the Typeface it constructs.

- attached property on TextElement (inherits) + CLR accessors and
  Get/SetFontVariations statics
- AddOwner on TemplatedControl, ContentPresenter and TextBlock
- baked into the typeface at every control bake site: TextBlock,
  SelectableTextBlock, TextPresenter, TextBox line-height layouts, and
  Inline run properties
- property changes invalidate like the sibling font properties
  (TextBlock/TextPresenter shaping group, TextElement inline host)
- XAML attribute strings ("wght=700, wdth=85") convert through the
  static Parse the XAML compiler picks up - no TypeConverter needed
  (pinned by a Markup.Xaml test)

* Animate FontVariations with CSS interpolation semantics

FontVariationSettings.Interpolate blends two settings the way CSS
font-variation-settings does: per-axis linear interpolation when both
endpoints set exactly the same axes (easing overshoot extrapolates),
discrete switch at the midpoint otherwise. Discrete is the only sound
fallback because a missing axis means "the font''s default", a value that
is not knowable in user space.

- FontVariationSettingsAnimator registered like the other value
  animators, so keyframe Animations on FontVariations work out of the box
- FontVariationSettingsTransition for the Transitions collection,
  following the TransformOperationsTransition pattern
- interpolation contract pinned at the value level (lerp, order
  independence, overshoot, discrete mismatches, null/Empty endpoints)
  and at the transition level through a test clock

* Quantize normalized coordinates to the F2Dot14 grid

An animated axis sweeps through arbitrary float user values; without
quantization every frame produced a fresh normalized position and a
fresh clone in the per-source variation cache, growing it without bound
across repeated sweeps.

Snap each coordinate to 1/16384 after avar correction. That is the
resolution the font binary itself stores - gvar, avar and the item
variation stores speak F2Dot14 - so no representable position is lost,
while a swept axis lands on at most 32769 distinct cache entries and
sub-resolution user values collapse to one clone (pinned by tests at the
position and clone-identity level).

* Add failing tests for shaping varied typefaces

A variation clone shares the source's HarfBuzz font, so shaping places
its glyphs at default-instance hmtx advances while GlyphTypeface reports
HVAR-adjusted advances for the same glyphs.

- Shaped advances of a wght=900 Inter Variable clone must equal the
  clone's HVAR advances and differ from the default instance
- The default position keeps the source's shaper typeface
- Disposing a clone must leave the source shaper usable

* Shape variation clones with their own HarfBuzz coordinates

Layout advances come from HarfBuzz, but a varied GlyphTypeface shared the
source's hb_font, so text set through FontVariations was placed at
default-instance advances while its metrics and bounds were varied.

- HarfBuzzTypeface.WithVariation returns an instance owning a sub-font of
  the source font with the normalized coordinates set in fvar axis order;
  the face stays shared and only the sub-font is released on dispose
- The sub-font installs the OpenType font functions itself, since the
  inherited parent functions evaluate HVAR at the parent's coordinates
- Bind hb_font_set_var_coords_normalized, which HarfBuzzSharp exports but
  does not wrap, under HarfBuzzSharp's library name; map it to the
  embedded framework on iOS, tvOS and Mac Catalyst, and fall back to the
  default instance if the entry point cannot be resolved
- Let Avalonia.HarfBuzz see Avalonia.Base internals to implement the
  internal ITextShaperTypeface members
pull/22656/head
Benedikt Stebner 3 weeks ago
committed by GitHub
parent
commit
dfee7f224b
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 1
      src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs
  2. 18
      src/Avalonia.Base/Animation/Animators/FontVariationSettingsAnimator.cs
  3. 26
      src/Avalonia.Base/Animation/Transitions/FontVariationSettingsTransition.cs
  4. 1
      src/Avalonia.Base/Avalonia.Base.csproj
  5. 25
      src/Avalonia.Base/Media/FontManager.cs
  6. 58
      src/Avalonia.Base/Media/FontVariationSettings.cs
  7. 9
      src/Avalonia.Base/Media/FormattedText.cs
  8. 16
      src/Avalonia.Base/Media/GlyphTypeface.cs
  9. 23
      src/Avalonia.Base/Media/ITextShaperTypeface.cs
  10. 25
      src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs
  11. 72
      src/Avalonia.Base/Media/Typeface.cs
  12. 9
      src/Avalonia.Controls/Documents/Inline.cs
  13. 41
      src/Avalonia.Controls/Documents/TextElement.cs
  14. 16
      src/Avalonia.Controls/Presenters/ContentPresenter.cs
  15. 13
      src/Avalonia.Controls/Presenters/TextPresenter.cs
  16. 16
      src/Avalonia.Controls/Primitives/TemplatedControl.cs
  17. 2
      src/Avalonia.Controls/SelectableTextBlock.cs
  18. 19
      src/Avalonia.Controls/TextBlock.cs
  19. 4
      src/Avalonia.Controls/TextBox.cs
  20. 75
      src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzNative.cs
  21. 61
      src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs
  22. 66
      tests/Avalonia.Base.UnitTests/Animation/FontVariationSettingsTransitionTests.cs
  23. 129
      tests/Avalonia.Base.UnitTests/Media/FontManagerVariationTests.cs
  24. 104
      tests/Avalonia.Base.UnitTests/Media/FontVariationSettingsTests.cs
  25. 18
      tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs
  26. 17
      tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs
  27. 46
      tests/Avalonia.Base.UnitTests/Media/TypefaceTests.cs
  28. 18
      tests/Avalonia.Controls.UnitTests/InlineTests.cs
  29. 14
      tests/Avalonia.Controls.UnitTests/Presenters/TextPresenter_Tests.cs
  30. 32
      tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
  31. 12
      tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs
  32. 110
      tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextShaperVariationTests.cs

1
src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs

@ -43,6 +43,7 @@ partial class Animation
RegisterAnimator<IBrush?, BaseBrushAnimator>(); RegisterAnimator<IBrush?, BaseBrushAnimator>();
RegisterAnimator<CornerRadius, CornerRadiusAnimator>(); RegisterAnimator<CornerRadius, CornerRadiusAnimator>();
RegisterAnimator<Color, ColorAnimator>(); RegisterAnimator<Color, ColorAnimator>();
RegisterAnimator<FontVariationSettings?, FontVariationSettingsAnimator>();
RegisterAnimator<Vector, VectorAnimator>(); RegisterAnimator<Vector, VectorAnimator>();
RegisterAnimator<Point, PointAnimator>(); RegisterAnimator<Point, PointAnimator>();
RegisterAnimator<Rect, RectAnimator>(); RegisterAnimator<Rect, RectAnimator>();

18
src/Avalonia.Base/Animation/Animators/FontVariationSettingsAnimator.cs

@ -0,0 +1,18 @@
using Avalonia.Media;
namespace Avalonia.Animation.Animators
{
/// <summary>
/// Animator for <see cref="FontVariationSettings"/>: per-axis linear interpolation
/// when both keyframes set the same axes, discrete otherwise (CSS semantics — see
/// <see cref="FontVariationSettings.Interpolate"/>).
/// </summary>
internal class FontVariationSettingsAnimator : Animator<FontVariationSettings?>
{
public override FontVariationSettings? Interpolate(double progress,
FontVariationSettings? oldValue, FontVariationSettings? newValue)
{
return FontVariationSettings.Interpolate(oldValue, newValue, progress);
}
}
}

26
src/Avalonia.Base/Animation/Transitions/FontVariationSettingsTransition.cs

@ -0,0 +1,26 @@
using System;
using Avalonia.Animation.Animators;
using Avalonia.Media;
namespace Avalonia.Animation
{
/// <summary>
/// Transition for <see cref="FontVariationSettings"/> values, e.g. animating
/// <c>TextElement.FontVariations</c> between weights. Axis values interpolate
/// per axis when both endpoints set the same axes and switch discretely otherwise
/// (CSS <c>font-variation-settings</c> semantics).
/// </summary>
public class FontVariationSettingsTransition : Transition<FontVariationSettings?>
{
private static readonly FontVariationSettingsAnimator s_animator = new();
internal override IObservable<FontVariationSettings?> DoTransition(
IObservable<double> progress,
FontVariationSettings? oldValue,
FontVariationSettings? newValue)
{
return new AnimatorTransitionObservable<FontVariationSettings?, FontVariationSettingsAnimator>(
s_animator, progress, Easing, oldValue, newValue);
}
}
}

1
src/Avalonia.Base/Avalonia.Base.csproj

@ -34,6 +34,7 @@
<InternalsVisibleTo Include="Avalonia.OpenGL, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.OpenGL, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.Vulkan, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.Vulkan, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.Skia, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.Skia, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.HarfBuzz, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.Controls.ColorPicker, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.Controls.ColorPicker, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.Controls.DataGrid, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.Controls.DataGrid, PublicKey=$(AvaloniaPublicKey)" />
<InternalsVisibleTo Include="Avalonia.Headless, PublicKey=$(AvaloniaPublicKey)" /> <InternalsVisibleTo Include="Avalonia.Headless, PublicKey=$(AvaloniaPublicKey)" />

25
src/Avalonia.Base/Media/FontManager.cs

@ -127,6 +127,25 @@ namespace Avalonia.Media
/// <c>True</c>, if the <see cref="FontManager"/> could create the glyph typeface, <c>False</c> otherwise. /// <c>True</c>, if the <see cref="FontManager"/> could create the glyph typeface, <c>False</c> otherwise.
/// </returns> /// </returns>
public bool TryGetGlyphTypeface(Typeface typeface, [NotNullWhen(true)] out GlyphTypeface? glyphTypeface) public bool TryGetGlyphTypeface(Typeface typeface, [NotNullWhen(true)] out GlyphTypeface? glyphTypeface)
{
if (!TryResolveGlyphTypeface(typeface, out glyphTypeface))
{
return false;
}
// Variations are applied once, here, whichever resolution path (mapped family,
// composite key, system fonts, default fallback) produced the base typeface.
// Static fonts ignore the request; per-variation instances are cached on the
// resolved GlyphTypeface, so repeated lookups stay cheap.
if (typeface.FontVariations is { } variations)
{
glyphTypeface = glyphTypeface.WithVariations(variations);
}
return true;
}
private bool TryResolveGlyphTypeface(Typeface typeface, [NotNullWhen(true)] out GlyphTypeface? glyphTypeface)
{ {
glyphTypeface = null; glyphTypeface = null;
@ -134,7 +153,7 @@ namespace Avalonia.Media
if (typeface.FontFamily.Name == FontFamily.DefaultFontFamilyName) if (typeface.FontFamily.Name == FontFamily.DefaultFontFamilyName)
{ {
return TryGetGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface); return TryResolveGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface);
} }
@ -164,7 +183,7 @@ namespace Avalonia.Media
if (familyName == FontFamily.DefaultFontFamilyName) if (familyName == FontFamily.DefaultFontFamilyName)
{ {
return TryGetGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface); return TryResolveGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface);
} }
if (TryGetGlyphTypefaceByKeyAndName(typeface, key, familyName, out glyphTypeface) && if (TryGetGlyphTypefaceByKeyAndName(typeface, key, familyName, out glyphTypeface) &&
@ -202,7 +221,7 @@ namespace Avalonia.Media
} }
//Nothing was found so use the default //Nothing was found so use the default
return TryGetGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface); return TryResolveGlyphTypeface(new Typeface(DefaultFontFamily, typeface.Style, typeface.Weight, typeface.Stretch), out glyphTypeface);
FontFamily GetMappedFontFamily(FontFamily fontFamily) FontFamily GetMappedFontFamily(FontFamily fontFamily)
{ {

58
src/Avalonia.Base/Media/FontVariationSettings.cs

@ -213,6 +213,64 @@ namespace Avalonia.Media
return variations.Count == 0 ? Empty : new FontVariationSettings(variations); return variations.Count == 0 ? Empty : new FontVariationSettings(variations);
} }
/// <summary>
/// Interpolates between two settings values, for animation.
/// </summary>
/// <remarks>
/// Matches CSS <c>font-variation-settings</c> interpolation: when both endpoints
/// set exactly the same axes, each axis value is interpolated linearly (easing
/// overshoot extrapolates); otherwise the result is discrete — <paramref name="from"/>
/// below the midpoint, <paramref name="to"/> at and above it. Discrete is the only
/// sound fallback because a missing axis means "the font's default", a value that
/// is not knowable in user space. <c>null</c> and <see cref="Empty"/> both mean
/// "no axes set".
/// </remarks>
public static FontVariationSettings? Interpolate(
FontVariationSettings? from,
FontVariationSettings? to,
double progress)
{
var fromVariations = from?._variations ?? ImmutableArray<FontVariation>.Empty;
var toVariations = to?._variations ?? ImmutableArray<FontVariation>.Empty;
if (fromVariations.Length != toVariations.Length || fromVariations.IsEmpty)
{
return progress < 0.5 ? from : to;
}
// Both sides are sorted by tag, so a positional comparison decides whether
// the axis sets match.
for (var i = 0; i < fromVariations.Length; i++)
{
if (fromVariations[i].Tag != toVariations[i].Tag)
{
return progress < 0.5 ? from : to;
}
}
var builder = ImmutableArray.CreateBuilder<FontVariation>(fromVariations.Length);
for (var i = 0; i < fromVariations.Length; i++)
{
var a = fromVariations[i].Value;
var b = toVariations[i].Value;
var lerped = a + (b - a) * progress;
// Infinite endpoints collapse the lerp arithmetic to NaN (infinity minus
// infinity); snap that axis to the nearer endpoint instead so the no-NaN
// invariant holds.
if (double.IsNaN(lerped))
{
lerped = progress < 0.5 ? a : b;
}
builder.Add(new FontVariation(fromVariations[i].Tag, lerped));
}
return new FontVariationSettings(builder.MoveToImmutable());
}
/// <summary>Returns the parseable string form, e.g. <c>wght=700,wdth=85</c>.</summary> /// <summary>Returns the parseable string form, e.g. <c>wght=700,wdth=85</c>.</summary>
public override string ToString() public override string ToString()
{ {

9
src/Avalonia.Base/Media/FormattedText.cs

@ -327,7 +327,8 @@ namespace Avalonia.Media
} }
var newProps = new GenericTextRunProperties( var newProps = new GenericTextRunProperties(
new Typeface(fontFamily, oldTypeface.Style, oldTypeface.Weight), new Typeface(fontFamily, oldTypeface.Style, oldTypeface.Weight,
FontStretch.Normal, oldTypeface.FontVariations),
runProps.FontRenderingEmSize, runProps.FontRenderingEmSize,
runProps.TextDecorations, runProps.TextDecorations,
runProps.ForegroundBrush, runProps.ForegroundBrush,
@ -509,7 +510,8 @@ namespace Avalonia.Media
} }
var newProps = new GenericTextRunProperties( var newProps = new GenericTextRunProperties(
new Typeface(oldTypeface.FontFamily, oldTypeface.Style, weight), new Typeface(oldTypeface.FontFamily, oldTypeface.Style, weight,
FontStretch.Normal, oldTypeface.FontVariations),
runProps.FontRenderingEmSize, runProps.FontRenderingEmSize,
runProps.TextDecorations, runProps.TextDecorations,
runProps.ForegroundBrush, runProps.ForegroundBrush,
@ -566,7 +568,8 @@ namespace Avalonia.Media
} }
var newProps = new GenericTextRunProperties( var newProps = new GenericTextRunProperties(
new Typeface(oldTypeface.FontFamily, style, oldTypeface.Weight), new Typeface(oldTypeface.FontFamily, style, oldTypeface.Weight,
FontStretch.Normal, oldTypeface.FontVariations),
runProps.FontRenderingEmSize, runProps.FontRenderingEmSize,
runProps.TextDecorations, runProps.TextDecorations,
runProps.ForegroundBrush, runProps.ForegroundBrush,

16
src/Avalonia.Base/Media/GlyphTypeface.cs

@ -1002,10 +1002,11 @@ namespace Avalonia.Media
/// <para> /// <para>
/// For variation clones, the shaper is derived from the source's shaper via /// For variation clones, the shaper is derived from the source's shaper via
/// <see cref="ITextShaperTypeface.WithVariation"/> so face-level state (HarfBuzz /// <see cref="ITextShaperTypeface.WithVariation"/> so face-level state (HarfBuzz
/// <c>hb_face_t</c>, parsed shaping tables) stays shared. The default /// <c>hb_face_t</c>, parsed shaping tables) stays shared. The HarfBuzz shaper
/// <c>WithVariation</c> implementation is a no-op; a shaper integration (e.g. /// returns a distinct shaping font carrying the clone's normalized coordinates,
/// HarfBuzz with <c>Font.SetVariationCoordsNormalized</c>) overrides it to /// which the clone owns and releases on <see cref="Dispose()"/>. A shaper without
/// configure variation coordinates on the produced shaping font. /// variation support returns the source's instance, and the clone is shaped at
/// the default instance.
/// </para> /// </para>
/// </remarks> /// </remarks>
public ITextShaperTypeface TextShaperTypeface public ITextShaperTypeface TextShaperTypeface
@ -1593,6 +1594,13 @@ namespace Avalonia.Media
normalizedValue = _avarTable.Remap(i, normalizedValue); normalizedValue = _avarTable.Remap(i, normalizedValue);
} }
// Quantize to the F2Dot14 grid (1/16384) the font binary itself uses for
// normalized coordinates — gvar, avar and the item variation stores cannot
// represent a finer position, so this loses nothing. It also bounds the
// per-source variation-clone cache under animation: a swept axis lands on
// at most 32769 distinct positions instead of one per float progress value.
normalizedValue = MathF.Round(normalizedValue * 16384f) / 16384f;
if (normalizedValue != 0f) if (normalizedValue != 0f)
{ {
normalized ??= new Dictionary<OpenTypeTag, float>(axes.Length); normalized ??= new Dictionary<OpenTypeTag, float>(axes.Length);

23
src/Avalonia.Base/Media/ITextShaperTypeface.cs

@ -13,10 +13,10 @@ namespace Avalonia.Media
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The default implementation returns <c>default</c>. Shaper implementations /// The default implementation returns <c>default</c>. Shaper implementations
/// that support variation (e.g. HarfBuzz via <c>Font.SetVariationCoordsNormalized</c>) /// that support variation (the HarfBuzz shaper, through
/// override this property alongside <see cref="WithVariation"/> to /// <c>hb_font_set_var_coords_normalized</c>) override this property alongside
/// report whatever variation coordinates are configured on the underlying /// <see cref="WithVariation"/> to report the variation coordinates configured on
/// shaping font. The member is <c>internal</c> because it traffics in normalized /// the underlying shaping font. The member is <c>internal</c> because it traffics in normalized
/// (font-relative) coordinates — only Avalonia's own shaper backends implement /// (font-relative) coordinates — only Avalonia's own shaper backends implement
/// it; user code speaks user-space <see cref="FontVariationSettings"/> at the /// it; user code speaks user-space <see cref="FontVariationSettings"/> at the
/// <see cref="GlyphTypeface"/> layer. /// <see cref="GlyphTypeface"/> layer.
@ -33,11 +33,16 @@ namespace Avalonia.Media
/// </param> /// </param>
/// <remarks> /// <remarks>
/// <para> /// <para>
/// The default implementation returns <c>this</c> unchanged — the same no-op /// The default implementation returns <c>this</c> unchanged, the same contract
/// contract used by <see cref="IPlatformTypeface.WithVariation"/>. Shapers /// used by <see cref="IPlatformTypeface.WithVariation"/>: a shaper without
/// override this to derive a new shaping font configured for the requested /// variation support shapes every variation at the default instance. The
/// variation while sharing face-level state (HarfBuzz <c>hb_face_t</c>, parsed /// HarfBuzz shaper returns <c>this</c> for its own position and otherwise a new
/// shaping tables) with the source. /// instance owning an <c>hb_font_t</c> sub-font with the requested normalized
/// coordinates, so shaped advances include HVAR deltas.
/// </para>
/// <para>
/// A distinct returned instance is owned by the caller: disposing it releases only
/// its own shaping font, never the face state shared with <c>this</c>.
/// </para> /// </para>
/// <para> /// <para>
/// Overrides must share face-level resources between the returned instance and /// Overrides must share face-level resources between the returned instance and

25
src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs

@ -216,14 +216,25 @@ namespace Avalonia.Media.TextFormatting
if (fontManager.TryMatchCharacter(fallbackCodepoint, defaultTypeface.Style, defaultTypeface.Weight, if (fontManager.TryMatchCharacter(fallbackCodepoint, defaultTypeface.Style, defaultTypeface.Weight,
defaultTypeface.Stretch, defaultTypeface.FontFamily, defaultProperties.CultureInfo, defaultTypeface.Stretch, defaultTypeface.FontFamily, defaultProperties.CultureInfo,
shapingConstraint, out fallbackTypeface) shapingConstraint, out fallbackTypeface))
&& !fontManager.TryGetGlyphTypeface(fallbackTypeface, out fallbackGlyphTypeface))
{ {
// The platform matched a fallback family but its glyph typeface could not // Variations follow the text, not the font: the matched fallback
// be loaded; the cluster degrades to .notdef. Surface it for diagnosis. // family renders at the same axis values the primary typeface
Logger.TryGet(LogEventLevel.Warning, LogArea.Fonts)?.Log(null, // requested (each font clamps to its own axes; CSS behavior).
"Matched fallback typeface {FamilyName} for codepoint U+{Codepoint} but could not load its glyph typeface.", if (defaultTypeface.FontVariations is { } fallbackVariations)
fallbackTypeface.FontFamily.Name, ((uint)fallbackCodepoint).ToString("X4")); {
fallbackTypeface = new Typeface(fallbackTypeface.FontFamily, fallbackTypeface.Style,
fallbackTypeface.Weight, fallbackTypeface.Stretch, fallbackVariations);
}
if (!fontManager.TryGetGlyphTypeface(fallbackTypeface, out fallbackGlyphTypeface))
{
// The platform matched a fallback family but its glyph typeface could not
// be loaded; the cluster degrades to .notdef. Surface it for diagnosis.
Logger.TryGet(LogEventLevel.Warning, LogArea.Fonts)?.Log(null,
"Matched fallback typeface {FamilyName} for codepoint U+{Codepoint} but could not load its glyph typeface.",
fallbackTypeface.FontFamily.Name, ((uint)fallbackCodepoint).ToString("X4"));
}
} }
} }

72
src/Avalonia.Base/Media/Typeface.cs

@ -22,12 +22,34 @@ namespace Avalonia.Media
FontStyle style = FontStyle.Normal, FontStyle style = FontStyle.Normal,
FontWeight weight = FontWeight.Normal, FontWeight weight = FontWeight.Normal,
FontStretch stretch = FontStretch.Normal) FontStretch stretch = FontStretch.Normal)
: this(fontFamily, style, weight, stretch, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Typeface"/> struct bound to a
/// variable-font position.
/// </summary>
/// <param name="fontFamily">The font family.</param>
/// <param name="style">The font style.</param>
/// <param name="weight">The font weight.</param>
/// <param name="stretch">The font stretch.</param>
/// <param name="fontVariations">
/// Variable-font axis values in user space (e.g. <c>wght = 700</c>), applied when the
/// resolved font is a variable font. <c>null</c> and
/// <see cref="FontVariationSettings.Empty"/> both mean the design defaults.
/// </param>
public Typeface(FontFamily fontFamily,
FontStyle style,
FontWeight weight,
FontStretch stretch,
FontVariationSettings? fontVariations)
{ {
if (weight <= 0) if (weight <= 0)
{ {
throw new ArgumentException("Font weight must be > 0."); throw new ArgumentException("Font weight must be > 0.");
} }
if ((int)stretch < 1) if ((int)stretch < 1)
{ {
throw new ArgumentException("Font stretch must be > 1."); throw new ArgumentException("Font stretch must be > 1.");
@ -37,6 +59,10 @@ namespace Avalonia.Media
Style = style; Style = style;
Weight = weight; Weight = weight;
Stretch = stretch; Stretch = stretch;
// Empty and null both mean "design defaults"; store the canonical form so
// equality, hashing and cache keys never distinguish the two spellings.
FontVariations = fontVariations is { IsEmpty: true } ? null : fontVariations;
} }
/// <summary> /// <summary>
@ -50,8 +76,30 @@ namespace Avalonia.Media
FontStyle style = FontStyle.Normal, FontStyle style = FontStyle.Normal,
FontWeight weight = FontWeight.Normal, FontWeight weight = FontWeight.Normal,
FontStretch stretch = FontStretch.Normal) FontStretch stretch = FontStretch.Normal)
: this(fontFamilyName, style, weight, stretch, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Typeface"/> struct bound to a
/// variable-font position.
/// </summary>
/// <param name="fontFamilyName">The name of the font family.</param>
/// <param name="style">The font style.</param>
/// <param name="weight">The font weight.</param>
/// <param name="stretch">The font stretch.</param>
/// <param name="fontVariations">
/// Variable-font axis values in user space (e.g. <c>wght = 700</c>), applied when the
/// resolved font is a variable font. <c>null</c> and
/// <see cref="FontVariationSettings.Empty"/> both mean the design defaults.
/// </param>
public Typeface(string fontFamilyName,
FontStyle style,
FontWeight weight,
FontStretch stretch,
FontVariationSettings? fontVariations)
: this(string.IsNullOrEmpty(fontFamilyName) ? FontFamily.Default : new FontFamily(fontFamilyName), : this(string.IsNullOrEmpty(fontFamilyName) ? FontFamily.Default : new FontFamily(fontFamilyName),
style, weight, stretch) style, weight, stretch, fontVariations)
{ {
} }
@ -77,6 +125,14 @@ namespace Avalonia.Media
/// </summary> /// </summary>
public FontStretch Stretch { get; } public FontStretch Stretch { get; }
/// <summary>
/// Gets the variable-font axis values in user space, or <c>null</c> when the
/// typeface uses the font's design defaults. Never
/// <see cref="FontVariationSettings.Empty"/> — empty settings are normalized to
/// <c>null</c> at construction.
/// </summary>
public FontVariationSettings? FontVariations { get; }
/// <summary> /// <summary>
/// Gets the glyph typeface. /// Gets the glyph typeface.
/// </summary> /// </summary>
@ -93,7 +149,7 @@ namespace Avalonia.Media
} }
throw new InvalidOperationException( throw new InvalidOperationException(
$"Could not create glyphTypeface. Font family: {FontFamily?.Name} (key: {FontFamily?.Key}). Style: {Style}. Weight: {Weight}. Stretch: {Stretch}"); $"Could not create glyphTypeface. Font family: {FontFamily?.Name} (key: {FontFamily?.Key}). Style: {Style}. Weight: {Weight}. Stretch: {Stretch}. Variations: {FontVariations?.ToString() ?? "none"}");
} }
} }
@ -114,8 +170,11 @@ namespace Avalonia.Media
public bool Equals(Typeface other) public bool Equals(Typeface other)
{ {
return FontFamily == other.FontFamily && Style == other.Style && // FontVariations is stored canonically (Empty coerced to null), so the
Weight == other.Weight && Stretch == other.Stretch; // reference-null fast path plus structural equality covers all cases.
return FontFamily == other.FontFamily && Style == other.Style &&
Weight == other.Weight && Stretch == other.Stretch &&
Equals(FontVariations, other.FontVariations);
} }
public override int GetHashCode() public override int GetHashCode()
@ -126,6 +185,7 @@ namespace Avalonia.Media
hashCode = (hashCode * 397) ^ (int)Style; hashCode = (hashCode * 397) ^ (int)Style;
hashCode = (hashCode * 397) ^ (int)Weight; hashCode = (hashCode * 397) ^ (int)Weight;
hashCode = (hashCode * 397) ^ (int)Stretch; hashCode = (hashCode * 397) ^ (int)Stretch;
hashCode = (hashCode * 397) ^ (FontVariations?.GetHashCode() ?? 0);
return hashCode; return hashCode;
} }
} }
@ -211,7 +271,7 @@ namespace Avalonia.Media
normalizedFamilyName = (normalizedFamilyNameBuilder?.ToString() ?? normalizedFamilyName).TrimEnd(); normalizedFamilyName = (normalizedFamilyNameBuilder?.ToString() ?? normalizedFamilyName).TrimEnd();
//Preserve old font source //Preserve old font source
return new Typeface(FontFamily, style, weight, stretch); return new Typeface(FontFamily, style, weight, stretch, FontVariations);
} }
/// <summary> /// <summary>

9
src/Avalonia.Controls/Documents/Inline.cs

@ -89,10 +89,11 @@ namespace Avalonia.Controls.Documents
var parentOrSelfBackground = Background ?? FindParentBackground(); var parentOrSelfBackground = Background ?? FindParentBackground();
var typeface = new Typeface( var typeface = new Typeface(
FontFamily, FontFamily,
FontStyle, FontStyle,
FontWeight, FontWeight,
FontStretch); FontStretch,
FontVariations);
return new GenericTextRunProperties( return new GenericTextRunProperties(
typeface, typeface,

41
src/Avalonia.Controls/Documents/TextElement.cs

@ -67,6 +67,14 @@ namespace Avalonia.Controls.Documents
inherits: true, inherits: true,
defaultValue: FontStretch.Normal); defaultValue: FontStretch.Normal);
/// <summary>
/// Defines the <see cref="FontVariations"/> property.
/// </summary>
public static readonly AttachedProperty<FontVariationSettings?> FontVariationsProperty =
AvaloniaProperty.RegisterAttached<TextElement, TextElement, FontVariationSettings?>(
nameof(FontVariations),
inherits: true);
/// <summary> /// <summary>
/// Defines the <see cref="Foreground"/> property. /// Defines the <see cref="Foreground"/> property.
/// </summary> /// </summary>
@ -156,6 +164,18 @@ namespace Avalonia.Controls.Documents
set => SetValue(FontStretchProperty, value); set => SetValue(FontStretchProperty, value);
} }
/// <summary>
/// Gets or sets the variable-font axis values in user space, e.g.
/// <c>wght=700, wdth=85</c>. <c>null</c> means the font's design defaults.
/// Fonts that are not variable ignore the settings; variable fonts clamp each
/// value to their own axis range.
/// </summary>
public FontVariationSettings? FontVariations
{
get => GetValue(FontVariationsProperty);
set => SetValue(FontVariationsProperty, value);
}
/// <summary> /// <summary>
/// Gets or sets a brush used to paint the text. /// Gets or sets a brush used to paint the text.
/// </summary> /// </summary>
@ -314,6 +334,26 @@ namespace Avalonia.Controls.Documents
control.SetValue(FontStretchProperty, value); control.SetValue(FontStretchProperty, value);
} }
/// <summary>
/// Gets the value of the attached <see cref="FontVariationsProperty"/> on a control.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>The font variation settings.</returns>
public static FontVariationSettings? GetFontVariations(Control control)
{
return control.GetValue(FontVariationsProperty);
}
/// <summary>
/// Sets the value of the attached <see cref="FontVariationsProperty"/> on a control.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="value">The property value to set.</param>
public static void SetFontVariations(Control control, FontVariationSettings? value)
{
control.SetValue(FontVariationsProperty, value);
}
/// <summary> /// <summary>
/// Gets the value of the attached <see cref="ForegroundProperty"/> on a control. /// Gets the value of the attached <see cref="ForegroundProperty"/> on a control.
/// </summary> /// </summary>
@ -362,6 +402,7 @@ namespace Avalonia.Controls.Documents
case nameof(FontStyle): case nameof(FontStyle):
case nameof(FontWeight): case nameof(FontWeight):
case nameof(FontStretch): case nameof(FontStretch):
case nameof(FontVariations):
case nameof(Foreground): case nameof(Foreground):
InlineHost?.Invalidate(); InlineHost?.Invalidate();
break; break;

16
src/Avalonia.Controls/Presenters/ContentPresenter.cs

@ -94,6 +94,12 @@ namespace Avalonia.Controls.Presenters
public static readonly StyledProperty<FontStretch> FontStretchProperty = public static readonly StyledProperty<FontStretch> FontStretchProperty =
TextElement.FontStretchProperty.AddOwner<ContentPresenter>(); TextElement.FontStretchProperty.AddOwner<ContentPresenter>();
/// <summary>
/// Defines the <see cref="FontVariations"/> property.
/// </summary>
public static readonly StyledProperty<FontVariationSettings?> FontVariationsProperty =
TextElement.FontVariationsProperty.AddOwner<ContentPresenter>();
/// <summary> /// <summary>
/// Defines the <see cref="TextAlignment"/> property /// Defines the <see cref="TextAlignment"/> property
/// </summary> /// </summary>
@ -298,6 +304,16 @@ namespace Avalonia.Controls.Presenters
set => SetValue(FontStretchProperty, value); set => SetValue(FontStretchProperty, value);
} }
/// <summary>
/// Gets or sets the variable-font axis values (e.g. <c>wght=700</c>).
/// <c>null</c> means the font's design defaults.
/// </summary>
public FontVariationSettings? FontVariations
{
get => GetValue(FontVariationsProperty);
set => SetValue(FontVariationsProperty, value);
}
/// <summary> /// <summary>
/// Gets or sets the text alignment /// Gets or sets the text alignment
/// </summary> /// </summary>

13
src/Avalonia.Controls/Presenters/TextPresenter.cs

@ -215,6 +215,16 @@ namespace Avalonia.Controls.Presenters
set => TextElement.SetFontStretch(this, value); set => TextElement.SetFontStretch(this, value);
} }
/// <summary>
/// Gets or sets the variable-font axis values (e.g. <c>wght=700</c>).
/// <c>null</c> means the font's design defaults.
/// </summary>
public FontVariationSettings? FontVariations
{
get => TextElement.GetFontVariations(this);
set => TextElement.SetFontVariations(this, value);
}
/// <summary> /// <summary>
/// Gets or sets a brush used to paint the text. /// Gets or sets a brush used to paint the text.
/// </summary> /// </summary>
@ -579,7 +589,7 @@ namespace Avalonia.Controls.Presenters
var caretIndex = CaretIndex; var caretIndex = CaretIndex;
var preeditText = PreeditText; var preeditText = PreeditText;
var text = GetCombinedText(Text, caretIndex, preeditText); var text = GetCombinedText(Text, caretIndex, preeditText);
var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch, FontVariations);
var selectionStart = SelectionStart; var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd; var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd); var start = Math.Min(selectionStart, selectionEnd);
@ -1121,6 +1131,7 @@ namespace Avalonia.Controls.Presenters
case nameof(FontWeight): case nameof(FontWeight):
case nameof(FontFamily): case nameof(FontFamily):
case nameof(FontStretch): case nameof(FontStretch):
case nameof(FontVariations):
case nameof(Text): case nameof(Text):
case nameof(LetterSpacing): case nameof(LetterSpacing):
case nameof(PasswordChar): case nameof(PasswordChar):

16
src/Avalonia.Controls/Primitives/TemplatedControl.cs

@ -82,6 +82,12 @@ namespace Avalonia.Controls.Primitives
public static readonly StyledProperty<FontStretch> FontStretchProperty = public static readonly StyledProperty<FontStretch> FontStretchProperty =
TextElement.FontStretchProperty.AddOwner<TemplatedControl>(); TextElement.FontStretchProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="FontVariations"/> property.
/// </summary>
public static readonly StyledProperty<FontVariationSettings?> FontVariationsProperty =
TextElement.FontVariationsProperty.AddOwner<TemplatedControl>();
/// <summary> /// <summary>
/// Defines the <see cref="Foreground"/> property. /// Defines the <see cref="Foreground"/> property.
/// </summary> /// </summary>
@ -239,6 +245,16 @@ namespace Avalonia.Controls.Primitives
set => SetValue(FontStretchProperty, value); set => SetValue(FontStretchProperty, value);
} }
/// <summary>
/// Gets or sets the variable-font axis values (e.g. <c>wght=700</c>) used to draw
/// the control's text. <c>null</c> means the font's design defaults.
/// </summary>
public FontVariationSettings? FontVariations
{
get => GetValue(FontVariationsProperty);
set => SetValue(FontVariationsProperty, value);
}
/// <summary> /// <summary>
/// Gets or sets the brush used to draw the control's text and other foreground elements. /// Gets or sets the brush used to draw the control's text and other foreground elements.
/// </summary> /// </summary>

2
src/Avalonia.Controls/SelectableTextBlock.cs

@ -193,7 +193,7 @@ namespace Avalonia.Controls
protected override TextLayout CreateTextLayout(string? text) protected override TextLayout CreateTextLayout(string? text)
{ {
var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch, FontVariations);
var defaultProperties = new GenericTextRunProperties( var defaultProperties = new GenericTextRunProperties(
typeface, typeface,

19
src/Avalonia.Controls/TextBlock.cs

@ -60,6 +60,12 @@ namespace Avalonia.Controls
public static readonly StyledProperty<FontStretch> FontStretchProperty = public static readonly StyledProperty<FontStretch> FontStretchProperty =
TextElement.FontStretchProperty.AddOwner<TextBlock>(); TextElement.FontStretchProperty.AddOwner<TextBlock>();
/// <summary>
/// Defines the <see cref="FontVariations"/> property.
/// </summary>
public static readonly StyledProperty<FontVariationSettings?> FontVariationsProperty =
TextElement.FontVariationsProperty.AddOwner<TextBlock>();
/// <summary> /// <summary>
/// Defines the <see cref="Foreground"/> property. /// Defines the <see cref="Foreground"/> property.
/// </summary> /// </summary>
@ -280,6 +286,16 @@ namespace Avalonia.Controls
set => SetValue(FontStretchProperty, value); set => SetValue(FontStretchProperty, value);
} }
/// <summary>
/// Gets or sets the variable-font axis values (e.g. <c>wght=700</c>) used to draw
/// the control's text. <c>null</c> means the font's design defaults.
/// </summary>
public FontVariationSettings? FontVariations
{
get => GetValue(FontVariationsProperty);
set => SetValue(FontVariationsProperty, value);
}
/// <summary> /// <summary>
/// Gets or sets the brush used to draw the control's text and other foreground elements. /// Gets or sets the brush used to draw the control's text and other foreground elements.
/// </summary> /// </summary>
@ -678,7 +694,7 @@ namespace Avalonia.Controls
/// <returns>A <see cref="TextLayout"/> object.</returns> /// <returns>A <see cref="TextLayout"/> object.</returns>
protected virtual TextLayout CreateTextLayout(string? text) protected virtual TextLayout CreateTextLayout(string? text)
{ {
var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch, FontVariations);
var defaultProperties = new GenericTextRunProperties( var defaultProperties = new GenericTextRunProperties(
typeface, typeface,
@ -940,6 +956,7 @@ namespace Avalonia.Controls
case nameof(FontStyle): case nameof(FontStyle):
case nameof(FontFamily): case nameof(FontFamily):
case nameof(FontStretch): case nameof(FontStretch):
case nameof(FontVariations):
case nameof(FlowDirection): case nameof(FlowDirection):
case nameof(LetterSpacing): case nameof(LetterSpacing):
case nameof(Text): case nameof(Text):

4
src/Avalonia.Controls/TextBox.cs

@ -2751,7 +2751,7 @@ namespace Avalonia.Controls
if (MaxLines > 0 && double.IsNaN(Height)) if (MaxLines > 0 && double.IsNaN(Height))
{ {
var fontSize = FontSize; var fontSize = FontSize;
var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch, FontVariations);
var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures); var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
var textLayout = new TextLayout(new LineTextSource(MaxLines), paragraphProperties); var textLayout = new TextLayout(new LineTextSource(MaxLines), paragraphProperties);
var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter(); var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();
@ -2767,7 +2767,7 @@ namespace Avalonia.Controls
if (MinLines > 0 && double.IsNaN(Height)) if (MinLines > 0 && double.IsNaN(Height))
{ {
var fontSize = FontSize; var fontSize = FontSize;
var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch, FontVariations);
var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures); var paragraphProperties = TextLayout.CreateTextParagraphProperties(typeface, fontSize, null, default, default, null, default, LineHeight, default, FontFeatures);
var textLayout = new TextLayout(new LineTextSource(MinLines), paragraphProperties); var textLayout = new TextLayout(new LineTextSource(MinLines), paragraphProperties);
var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter(); var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter();

75
src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzNative.cs

@ -0,0 +1,75 @@
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Avalonia.Harfbuzz
{
/// <summary>
/// HarfBuzz entry points that HarfBuzzSharp exports natively but does not wrap.
/// </summary>
internal static unsafe partial class HarfBuzzNative
{
// The library name HarfBuzzSharp uses in its own imports, so both resolve to the one
// loaded binary (and to the same statically linked archive on WebAssembly).
private const string LibraryName = "libHarfBuzzSharp";
// HarfBuzzSharp's iOS, tvOS and Mac Catalyst builds import from the embedded
// framework; this assembly has no per-platform builds, so it maps the name at runtime.
private const string AppleFrameworkPath = "@rpath/libHarfBuzzSharp.framework/libHarfBuzzSharp";
private static bool s_isUnavailable;
static HarfBuzzNative()
{
if (OperatingSystem.IsIOS() || OperatingSystem.IsTvOS() || OperatingSystem.IsMacCatalyst())
{
NativeLibrary.SetDllImportResolver(typeof(HarfBuzzNative).Assembly, ResolveAppleFramework);
}
}
/// <summary>
/// Sets normalized variation coordinates, in fvar axis order and F2Dot14 units, on
/// <paramref name="font"/>.
/// </summary>
/// <returns>
/// <c>false</c> when the loaded native library lacks the entry point; the font is left
/// at the default instance.
/// </returns>
public static bool TrySetVarCoordsNormalized(IntPtr font, ReadOnlySpan<int> coords)
{
if (s_isUnavailable)
{
return false;
}
try
{
fixed (int* pCoords = coords)
{
hb_font_set_var_coords_normalized(font, pCoords, (uint)coords.Length);
}
return true;
}
catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException)
{
s_isUnavailable = true;
return false;
}
}
private static IntPtr ResolveAppleFramework(
string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (libraryName == LibraryName && NativeLibrary.TryLoad(AppleFrameworkPath, out var handle))
{
return handle;
}
return IntPtr.Zero;
}
[LibraryImport(LibraryName)]
private static partial void hb_font_set_var_coords_normalized(IntPtr font, int* coords, uint coordsLength);
}
}

61
src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs

@ -7,6 +7,9 @@ namespace Avalonia.Harfbuzz
{ {
internal class HarfBuzzTypeface : ITextShaperTypeface internal class HarfBuzzTypeface : ITextShaperTypeface
{ {
private readonly bool _ownsFace;
private readonly NormalizedVariationPosition _variationPosition;
public HarfBuzzTypeface(GlyphTypeface glyphTypeface) public HarfBuzzTypeface(GlyphTypeface glyphTypeface)
{ {
GlyphTypeface = glyphTypeface; GlyphTypeface = glyphTypeface;
@ -16,12 +19,63 @@ namespace Avalonia.Harfbuzz
HBFont = new Font(HBFace); HBFont = new Font(HBFace);
HBFont.SetFunctionsOpenType(); HBFont.SetFunctionsOpenType();
_ownsFace = true;
}
private HarfBuzzTypeface(HarfBuzzTypeface source, Font font, NormalizedVariationPosition variation)
{
GlyphTypeface = source.GlyphTypeface;
HBFace = source.HBFace;
HBFont = font;
_variationPosition = variation;
} }
public GlyphTypeface GlyphTypeface { get; } public GlyphTypeface GlyphTypeface { get; }
public Face HBFace { get; } public Face HBFace { get; }
public Font HBFont { get; } public Font HBFont { get; }
NormalizedVariationPosition ITextShaperTypeface.VariationPosition => _variationPosition;
ITextShaperTypeface ITextShaperTypeface.WithVariation(NormalizedVariationPosition variation)
{
if (variation == _variationPosition)
{
return this;
}
var axes = GlyphTypeface.VariationAxes;
if (axes.Count == 0)
{
return this;
}
Span<int> coords = axes.Count <= 16 ? stackalloc int[axes.Count] : new int[axes.Count];
for (var i = 0; i < axes.Count; i++)
{
variation.TryGetCoordinate(axes[i].Tag, out var value);
coords[i] = (int)MathF.Round(value * 16384f);
}
var font = new Font(HBFont);
// A sub-font delegates glyph advances to its parent, which evaluates HVAR at the
// parent's coordinates. Installing the OpenType functions on the sub-font itself
// makes advances and extents follow its own coordinates.
font.SetFunctionsOpenType();
if (!HarfBuzzNative.TrySetVarCoordsNormalized(font.Handle, coords))
{
font.Dispose();
return this;
}
return new HarfBuzzTypeface(this, font, variation);
}
private Blob? GetTable(Face face, Tag tag) private Blob? GetTable(Face face, Tag tag)
{ {
if (!GlyphTypeface.PlatformTypeface.TryGetTable((uint)tag, out var table)) if (!GlyphTypeface.PlatformTypeface.TryGetTable((uint)tag, out var table))
@ -57,7 +111,12 @@ namespace Avalonia.Harfbuzz
public void Dispose() public void Dispose()
{ {
HBFont.Dispose(); HBFont.Dispose();
HBFace.Dispose();
// A variation instance shares the face with the typeface it was derived from.
if (_ownsFace)
{
HBFace.Dispose();
}
} }
} }

66
tests/Avalonia.Base.UnitTests/Animation/FontVariationSettingsTransitionTests.cs

@ -0,0 +1,66 @@
using System;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.Fonts;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Base.UnitTests.Animation
{
public class FontVariationSettingsTransitionTests : ScopedTestBase
{
private static readonly OpenTypeTag s_wght = OpenTypeTag.Parse("wght");
[Fact]
public void FontVariations_Are_Interpolated_Per_Axis()
{
var clock = new TestClock();
var from = FontVariationSettings.Parse("wght=400");
var to = FontVariationSettings.Parse("wght=800");
var target = new TextBlock { FontVariations = from };
var sut = new FontVariationSettingsTransition
{
Duration = TimeSpan.FromSeconds(1),
Property = TextBlock.FontVariationsProperty,
};
sut.Apply(target, clock, from, to);
clock.Pulse(TimeSpan.Zero);
clock.Pulse(sut.Duration * 0.5);
Assert.NotNull(target.FontVariations);
Assert.True(target.FontVariations.TryGetValue(s_wght, out var wght));
Assert.Equal(600, wght);
}
[Fact]
public void Mismatched_Axis_Sets_Switch_Discretely()
{
var clock = new TestClock();
var from = FontVariationSettings.Parse("wght=700");
var to = FontVariationSettings.Parse("wdth=85");
var target = new TextBlock { FontVariations = from };
var sut = new FontVariationSettingsTransition
{
Duration = TimeSpan.FromSeconds(1),
Property = TextBlock.FontVariationsProperty,
};
sut.Apply(target, clock, from, to);
clock.Pulse(TimeSpan.Zero);
// TestClock.Pulse accumulates deltas: 0.25 then +0.35 = 0.6 of the duration.
// Staying below 1.0 keeps the transition alive — at completion it disposes
// and the property reverts to its base value.
clock.Pulse(sut.Duration * 0.25);
Assert.Equal(from, target.FontVariations);
clock.Pulse(sut.Duration * 0.35);
Assert.Equal(to, target.FontVariations);
}
}
}

129
tests/Avalonia.Base.UnitTests/Media/FontManagerVariationTests.cs

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using Avalonia.Base.UnitTests.Media.Fonts.Tables;
using Avalonia.Media;
using Avalonia.Media.Fonts;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Base.UnitTests.Media
{
/// <summary>
/// FontManager is the seam where a Typeface's user-space FontVariations are applied
/// to the resolved GlyphTypeface. These tests pin that application: the resolved
/// typeface is bound to the normalized position, equal settings share one cached
/// instance, and settings-free lookups stay at the default instance.
/// </summary>
public class FontManagerVariationTests
{
private const string InterVariableAsset =
"resm:Avalonia.Base.UnitTests.Assets.InterVariable.ttf?assembly=Avalonia.Base.UnitTests";
private static readonly OpenTypeTag s_wghtTag = OpenTypeTag.Parse("wght");
[Fact]
public void TryGetGlyphTypeface_Applies_FontVariations()
{
using (Start())
{
var typeface = new Typeface("Inter Variable",
FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
Assert.True(FontManager.Current.TryGetGlyphTypeface(typeface, out var glyphTypeface));
// wght=700 on Inter Variable normalizes to 0.54 (through avar) — the same
// value CreateNormalizedPosition produces, proving the settings reached
// the variation seam and were not dropped during resolution.
Assert.True(glyphTypeface.VariationPosition.TryGetCoordinate(s_wghtTag, out var wght));
Assert.Equal(0.54f, wght, precision: 4);
}
}
[Fact]
public void TryGetGlyphTypeface_Without_Variations_Resolves_Default_Instance()
{
using (Start())
{
var typeface = new Typeface("Inter Variable");
Assert.True(FontManager.Current.TryGetGlyphTypeface(typeface, out var glyphTypeface));
Assert.True(glyphTypeface.VariationPosition.IsDefault);
}
}
[Fact]
public void Equal_Variations_Resolve_To_The_Same_Instance()
{
using (Start())
{
var a = new Typeface("Inter Variable",
FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
var b = new Typeface("Inter Variable",
FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
Assert.True(FontManager.Current.TryGetGlyphTypeface(a, out var first));
Assert.True(FontManager.Current.TryGetGlyphTypeface(b, out var second));
// The base typeface is cached by the font collection and the varied clone
// is cached on the base, so equal settings must not allocate per lookup.
Assert.Same(first, second);
Assert.True(FontManager.Current.TryGetGlyphTypeface(new Typeface("Inter Variable"), out var plain));
Assert.NotSame(plain, first);
}
}
private static IDisposable Start() =>
UnitTestApplication.Start(TestServices.MockPlatformRenderInterface
.With(fontManagerImpl: new VariableFontManagerStub()));
/// <summary>
/// Serves the embedded Inter Variable font for every family request, so the
/// resolution pipeline (FontManager → SystemFontCollection → platform impl) runs
/// for real against a variable font without depending on system fonts.
/// </summary>
private class VariableFontManagerStub : IFontManagerImpl
{
public string GetDefaultFontFamilyName() => "Inter Variable";
public string[] GetInstalledFontFamilyNames(bool checkForUpdates = false) =>
new[] { "Inter Variable" };
public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight,
FontStretch fontStretch, string? familyName, CultureInfo? culture,
[NotNullWhen(true)] out IPlatformTypeface? platformTypeface)
{
platformTypeface = null;
return false;
}
public bool TryCreateGlyphTypeface(string familyName, FontStyle style, FontWeight weight,
FontStretch stretch, [NotNullWhen(true)] out IPlatformTypeface? platformTypeface)
{
var assetLoader = new StandardAssetLoader();
using var stream = assetLoader.Open(new Uri(InterVariableAsset));
platformTypeface = new CustomPlatformTypeface(stream, familyName);
return true;
}
public bool TryCreateGlyphTypeface(Stream stream, FontSimulations fontSimulations,
[NotNullWhen(true)] out IPlatformTypeface? platformTypeface)
{
platformTypeface = new CustomPlatformTypeface(stream);
return true;
}
public bool TryGetFamilyTypefaces(string familyName,
[NotNullWhen(true)] out IReadOnlyList<Typeface>? familyTypefaces)
{
familyTypefaces = null;
return false;
}
}
}
}

104
tests/Avalonia.Base.UnitTests/Media/FontVariationSettingsTests.cs

@ -144,5 +144,109 @@ namespace Avalonia.Base.UnitTests.Media
Assert.Equal("wght=700", new FontVariation(s_wght, 700).ToString()); Assert.Equal("wght=700", new FontVariation(s_wght, 700).ToString());
Assert.Equal("opsz=14.25", new FontVariation(s_opsz, 14.25).ToString()); Assert.Equal("opsz=14.25", new FontVariation(s_opsz, 14.25).ToString());
} }
[Fact]
public void Interpolate_Lerps_Matching_Axis_Sets_Per_Axis()
{
var from = FontVariationSettings.Parse("wght=400, wdth=75");
var to = FontVariationSettings.Parse("wght=800, wdth=125");
var quarter = FontVariationSettings.Interpolate(from, to, 0.25);
Assert.NotNull(quarter);
Assert.True(quarter.TryGetValue(s_wght, out var wght));
Assert.Equal(500, wght);
Assert.True(quarter.TryGetValue(s_wdth, out var wdth));
Assert.Equal(87.5, wdth);
Assert.Equal(from, FontVariationSettings.Interpolate(from, to, 0));
Assert.Equal(to, FontVariationSettings.Interpolate(from, to, 1));
}
[Fact]
public void Interpolate_Matches_Axis_Sets_Order_Independently()
{
// Both endpoints store sorted variations, so the authoring order of the
// pairs must not force the discrete path.
var from = FontVariationSettings.Parse("wdth=75, wght=400");
var to = FontVariationSettings.Parse("wght=800, wdth=125");
var mid = FontVariationSettings.Interpolate(from, to, 0.5);
Assert.NotNull(mid);
Assert.True(mid.TryGetValue(s_wght, out var wght));
Assert.Equal(600, wght);
}
[Fact]
public void Interpolate_Extrapolates_On_Easing_Overshoot()
{
// Springy easings report progress outside [0, 1]; matching axis sets keep
// lerping through, like every other continuous animator.
var from = FontVariationSettings.Parse("wght=400");
var to = FontVariationSettings.Parse("wght=800");
var overshot = FontVariationSettings.Interpolate(from, to, 1.25);
Assert.NotNull(overshot);
Assert.True(overshot.TryGetValue(s_wght, out var wght));
Assert.Equal(900, wght);
}
[Fact]
public void Interpolate_Snaps_Axes_With_Infinite_Endpoints()
{
// Lerping between an infinite and a finite endpoint is NaN arithmetic; such
// axes snap to the nearer endpoint instead.
var from = new FontVariationSettings(new[]
{
new FontVariation(s_wght, double.PositiveInfinity),
});
var to = FontVariationSettings.Parse("wght=800");
var early = FontVariationSettings.Interpolate(from, to, 0.25);
var late = FontVariationSettings.Interpolate(from, to, 0.75);
Assert.NotNull(early);
Assert.True(early.TryGetValue(s_wght, out var earlyWght));
Assert.Equal(double.PositiveInfinity, earlyWght);
Assert.NotNull(late);
Assert.True(late.TryGetValue(s_wght, out var lateWght));
Assert.Equal(800, lateWght);
}
[Fact]
public void Interpolate_Is_Discrete_When_Axis_Sets_Differ()
{
// CSS font-variation-settings semantics: a missing axis means "the font's
// default", which is unknowable in user space — so mismatched sets switch
// at the midpoint instead of blending.
var from = FontVariationSettings.Parse("wght=700");
var toOtherAxis = FontVariationSettings.Parse("wdth=85");
var toSuperset = FontVariationSettings.Parse("wght=700, wdth=85");
Assert.Same(from, FontVariationSettings.Interpolate(from, toOtherAxis, 0.49));
Assert.Same(toOtherAxis, FontVariationSettings.Interpolate(from, toOtherAxis, 0.5));
Assert.Same(from, FontVariationSettings.Interpolate(from, toSuperset, 0.49));
Assert.Same(toSuperset, FontVariationSettings.Interpolate(from, toSuperset, 0.5));
}
[Fact]
public void Interpolate_Is_Discrete_Against_Null_And_Empty()
{
var settings = FontVariationSettings.Parse("wght=700");
Assert.Null(FontVariationSettings.Interpolate(null, settings, 0.49));
Assert.Same(settings, FontVariationSettings.Interpolate(null, settings, 0.5));
Assert.Same(settings, FontVariationSettings.Interpolate(settings, null, 0.49));
Assert.Null(FontVariationSettings.Interpolate(settings, null, 0.5));
Assert.Null(FontVariationSettings.Interpolate(null, null, 0.5));
Assert.Same(FontVariationSettings.Empty,
FontVariationSettings.Interpolate(null, FontVariationSettings.Empty, 0.5));
}
} }
} }

18
tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs

@ -161,6 +161,24 @@ namespace Avalonia.Base.UnitTests.Media
Assert.False(position.TryGetCoordinate(bogus, out _)); Assert.False(position.TryGetCoordinate(bogus, out _));
} }
[Fact]
public void CreateNormalizedPosition_Quantizes_To_The_F2Dot14_Grid()
{
// Normalized coordinates are quantized to the 1/16384 grid the font binary
// uses, so user values that differ below that resolution produce the SAME
// position — this is what keeps the variation-clone cache bounded when an
// axis is animated through arbitrary float values.
var typeface = LoadTypeface(InterVariableAsset);
var a = typeface.CreateNormalizedPosition(Settings((s_wghtTag, 700)));
var b = typeface.CreateNormalizedPosition(Settings((s_wghtTag, 700.001)));
Assert.Equal(a, b);
Assert.True(a.TryGetCoordinate(s_wghtTag, out var wght));
Assert.Equal(MathF.Round(wght * 16384f) / 16384f, wght);
}
[Fact] [Fact]
public void CreateNormalizedPosition_Uses_Named_Instance_Coordinates() public void CreateNormalizedPosition_Uses_Named_Instance_Coordinates()
{ {

17
tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs

@ -283,6 +283,23 @@ namespace Avalonia.Base.UnitTests.Media
Assert.Same(atMax, clamped); Assert.Same(atMax, clamped);
} }
[Fact]
public void WithVariations_Shares_Clones_Within_A_Quantization_Cell()
{
// Under animation an axis sweeps through arbitrary float user values; the
// F2Dot14 quantization in CreateNormalizedPosition collapses sub-resolution
// differences so the sweep reuses clones instead of growing the cache
// per progress value.
var gt = LoadTypeface(InterVariableAsset);
var a = gt.WithVariations(new FontVariationSettings(
new[] { new FontVariation(s_wghtTag, 700) }));
var b = gt.WithVariations(new FontVariationSettings(
new[] { new FontVariation(s_wghtTag, 700.001) }));
Assert.Same(a, b);
}
[Fact] [Fact]
public void WithVariations_Selects_Named_Instance_By_Index() public void WithVariations_Selects_Named_Instance_By_Index()
{ {

46
tests/Avalonia.Base.UnitTests/Media/TypefaceTests.cs

@ -24,6 +24,52 @@ namespace Avalonia.Base.UnitTests.Media
Assert.Equal(new Typeface("Font A").GetHashCode(), new Typeface("Font A").GetHashCode()); Assert.Equal(new Typeface("Font A").GetHashCode(), new Typeface("Font A").GetHashCode());
} }
[Fact]
public void Typefaces_With_Equal_FontVariations_Are_Equal_With_Equal_Hash()
{
var a = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
var b = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
Assert.Equal(a, b);
Assert.Equal(a.GetHashCode(), b.GetHashCode());
}
[Fact]
public void Typefaces_With_Different_FontVariations_Are_Not_Equal()
{
var plain = new Typeface("Font A");
var bold = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=700"));
var black = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=900"));
Assert.NotEqual(plain, bold);
Assert.NotEqual(bold, black);
}
[Fact]
public void Empty_FontVariations_Normalize_To_Null()
{
// null and Empty both mean "design defaults"; the ctor stores the canonical
// form so equality, hashing and cache keys never split the two spellings.
var withNull = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, null);
var withEmpty = new Typeface("Font A", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Empty);
Assert.Null(withEmpty.FontVariations);
Assert.Equal(withNull, withEmpty);
Assert.Equal(withNull.GetHashCode(), withEmpty.GetHashCode());
}
[Fact]
public void Normalize_Preserves_FontVariations()
{
var typeface = new Typeface("Hello World Italic",
FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, FontVariationSettings.Parse("wght=650"));
var normalized = typeface.Normalize(out _);
Assert.Equal(FontStyle.Italic, normalized.Style);
Assert.Equal(typeface.FontVariations, normalized.FontVariations);
}
[InlineData("Hello World 6", "Hello World 6", FontStyle.Normal, FontWeight.Normal)] [InlineData("Hello World 6", "Hello World 6", FontStyle.Normal, FontWeight.Normal)]
[InlineData("Hello World Italic", "Hello World", FontStyle.Italic, FontWeight.Normal)] [InlineData("Hello World Italic", "Hello World", FontStyle.Italic, FontWeight.Normal)]
[InlineData("Hello World Italic Bold", "Hello World", FontStyle.Italic, FontWeight.Bold)] [InlineData("Hello World Italic Bold", "Hello World", FontStyle.Italic, FontWeight.Bold)]

18
tests/Avalonia.Controls.UnitTests/InlineTests.cs

@ -61,6 +61,24 @@ namespace Avalonia.Controls.UnitTests
Assert.Equal(FontStretch.Condensed, runProperties.Typeface.Stretch); Assert.Equal(FontStretch.Condensed, runProperties.Typeface.Stretch);
} }
[Fact]
public void Should_Inherit_FontVariations_In_Nested_Inlines()
{
var span = new Span();
var innerSpan = new Span();
var run = new Run("Test");
span.FontVariations = FontVariationSettings.Parse("wght=700");
innerSpan.Inlines.Add(run);
span.Inlines.Add(innerSpan);
var textRuns = new List<TextRun>();
span.BuildTextRun(textRuns);
var runProperties = textRuns[0].Properties;
Assert.NotNull(runProperties);
Assert.Equal(FontVariationSettings.Parse("wght=700"), runProperties.Typeface.FontVariations);
}
[Fact] [Fact]
public void Should_Inherit_Background_In_Nested_Inlines() public void Should_Inherit_Background_In_Nested_Inlines()
{ {

14
tests/Avalonia.Controls.UnitTests/Presenters/TextPresenter_Tests.cs

@ -76,6 +76,20 @@ namespace Avalonia.Controls.UnitTests.Presenters
} }
} }
[Fact]
public void TextPresenter_Should_Use_FontVariations_Property()
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
{
var variations = FontVariationSettings.Parse("wght=650, wdth=85");
var presenter = new TextPresenter { FontVariations = variations, Text = "test" };
Assert.NotNull(presenter.TextLayout);
Assert.NotNull(presenter.TextLayout.TextLines[0].TextRuns[0].Properties);
Assert.Equal(variations, presenter.TextLayout.TextLines[0].TextRuns[0].Properties!.Typeface.FontVariations);
}
}
[Fact] [Fact]
public void Measure_And_Arrange_Should_Use_WidthIncludingTrailingWhitespace_For_Bounds() public void Measure_And_Arrange_Should_Use_WidthIncludingTrailingWhitespace_For_Bounds()
{ {

32
tests/Avalonia.Controls.UnitTests/TextBlockTests.cs

@ -205,6 +205,38 @@ namespace Avalonia.Controls.UnitTests
} }
} }
[Fact]
public void TextLayout_Should_Use_FontVariations_Property()
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
{
var variations = FontVariationSettings.Parse("wght=700");
var target = new TextBlock { Text = "Hello World", FontVariations = variations };
target.Measure(Size.Infinity);
Assert.NotNull(target.TextLayout.TextLines[0].TextRuns[0].Properties);
Assert.Equal(variations, target.TextLayout.TextLines[0].TextRuns[0].Properties!.Typeface.FontVariations);
}
}
[Fact]
public void Changing_FontVariations_Should_Invalidate_Measure()
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
{
var target = new TextBlock { Text = "Hello World" };
target.Measure(Size.Infinity);
Assert.True(target.IsMeasureValid);
target.FontVariations = FontVariationSettings.Parse("wght=700");
Assert.False(target.IsMeasureValid);
}
}
[Fact] [Fact]
public void Changing_InlinesCollection_Should_Invalidate_Measure() public void Changing_InlinesCollection_Should_Invalidate_Measure()
{ {

12
tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs

@ -876,6 +876,18 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml
Assert.Equal("Foo", toolTip.Content); Assert.Equal("Foo", toolTip.Content);
} }
[Fact]
public void TextBlock_FontVariations_Is_Parsed_From_String()
{
// FontVariationSettings has a static Parse(string), which the XAML compiler
// picks up for attribute-string conversion — no TypeConverter involved.
var xaml = @"<TextBlock xmlns='https://github.com/avaloniaui' FontVariations='wght=700, wdth=85' />";
var textBlock = AvaloniaRuntimeXamlLoader.Parse<TextBlock>(xaml);
Assert.Equal(FontVariationSettings.Parse("wght=700, wdth=85"), textBlock.FontVariations);
}
[Fact] [Fact]
public void AddChild_Child_Is_Set() public void AddChild_Child_Is_Set()
{ {

110
tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextShaperVariationTests.cs

@ -0,0 +1,110 @@
using System;
using Avalonia.Media;
using Avalonia.Media.Fonts;
using Avalonia.Media.TextFormatting;
using Avalonia.Platform;
using Avalonia.UnitTests;
using SkiaSharp;
using Xunit;
namespace Avalonia.Skia.UnitTests.Media.TextFormatting
{
public class TextShaperVariationTests
{
private const string InterVariableAsset =
"resm:Avalonia.Skia.UnitTests.Assets.InterVariable.ttf?assembly=Avalonia.Skia.UnitTests";
private const string Text = "Hamburg";
private const double EmSize = 16;
private static readonly OpenTypeTag s_wghtTag = OpenTypeTag.Parse("wght");
[Fact]
public void Shaping_A_Varied_Clone_Uses_The_Variation_Advances()
{
using (Start())
{
var source = LoadInterVariable();
var black = source.WithVariations(Weight(900));
var defaultBuffer = ShapeUnkerned(source);
var blackBuffer = ShapeUnkerned(black);
Assert.Equal(Text.Length, blackBuffer.Length);
for (var i = 0; i < blackBuffer.Length; i++)
{
var glyph = blackBuffer[i].GlyphIndex;
Assert.True(black.TryGetHorizontalGlyphAdvance(glyph, out var variedAdvance));
var expected = variedAdvance * EmSize / black.Metrics.DesignEmHeight;
Assert.Equal(expected, blackBuffer[i].GlyphAdvance, 0.01);
Assert.NotEqual(defaultBuffer[i].GlyphAdvance, blackBuffer[i].GlyphAdvance, 0.01);
}
}
}
[Fact]
public void Requesting_The_Default_Position_Returns_The_Source_Shaper_Typeface()
{
using (Start())
{
var source = LoadInterVariable();
var shaper = source.TextShaperTypeface;
Assert.Same(shaper, shaper.WithVariation(default));
}
}
[Fact]
public void Disposing_A_Varied_Clone_Leaves_The_Source_Shaper_Usable()
{
using (Start())
{
var source = LoadInterVariable();
var before = TextShaper.Current.ShapeText(Text, new TextShaperOptions(source, EmSize));
var black = source.WithVariations(Weight(900));
TextShaper.Current.ShapeText(Text, new TextShaperOptions(black, EmSize));
black.Dispose();
var after = TextShaper.Current.ShapeText(Text, new TextShaperOptions(source, EmSize));
Assert.Equal(before.Length, after.Length);
for (var i = 0; i < before.Length; i++)
{
Assert.Equal(before[i].GlyphIndex, after[i].GlyphIndex);
Assert.Equal(before[i].GlyphAdvance, after[i].GlyphAdvance);
}
}
}
// Kerning adjusts advances in GPOS, so without it each shaped advance is the glyph's
// own horizontal advance and can be compared to GlyphTypeface directly.
private static ShapedBuffer ShapeUnkerned(GlyphTypeface glyphTypeface)
=> TextShaper.Current.ShapeText(Text, new TextShaperOptions(glyphTypeface, EmSize,
fontFeatures: new[] { FontFeature.Parse("-kern") }));
private static FontVariationSettings Weight(double value)
=> new(new[] { new FontVariation(s_wghtTag, value) });
private static GlyphTypeface LoadInterVariable()
{
var assetLoader = new StandardAssetLoader();
using var stream = assetLoader.Open(new Uri(InterVariableAsset));
return new GlyphTypeface(new SkiaTypeface(SKTypeface.FromStream(stream), FontSimulations.None));
}
private static IDisposable Start()
{
return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface
.With(renderInterface: new PlatformRenderInterface(null)));
}
}
}
Loading…
Cancel
Save