Browse Source
* 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
committed by
GitHub
32 changed files with 1054 additions and 42 deletions
@ -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); |
|||
} |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
} |
|||
@ -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; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -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…
Reference in new issue