diff --git a/src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs b/src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs index da3c4cb8e6..a0066e3df7 100644 --- a/src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs +++ b/src/Avalonia.Base/Animation/Animation.AnimatorRegistry.cs @@ -43,6 +43,7 @@ partial class Animation RegisterAnimator(); RegisterAnimator(); RegisterAnimator(); + RegisterAnimator(); RegisterAnimator(); RegisterAnimator(); RegisterAnimator(); diff --git a/src/Avalonia.Base/Animation/Animators/FontVariationSettingsAnimator.cs b/src/Avalonia.Base/Animation/Animators/FontVariationSettingsAnimator.cs new file mode 100644 index 0000000000..9d6143321b --- /dev/null +++ b/src/Avalonia.Base/Animation/Animators/FontVariationSettingsAnimator.cs @@ -0,0 +1,18 @@ +using Avalonia.Media; + +namespace Avalonia.Animation.Animators +{ + /// + /// Animator for : per-axis linear interpolation + /// when both keyframes set the same axes, discrete otherwise (CSS semantics — see + /// ). + /// + internal class FontVariationSettingsAnimator : Animator + { + public override FontVariationSettings? Interpolate(double progress, + FontVariationSettings? oldValue, FontVariationSettings? newValue) + { + return FontVariationSettings.Interpolate(oldValue, newValue, progress); + } + } +} diff --git a/src/Avalonia.Base/Animation/Transitions/FontVariationSettingsTransition.cs b/src/Avalonia.Base/Animation/Transitions/FontVariationSettingsTransition.cs new file mode 100644 index 0000000000..c05ea48fa3 --- /dev/null +++ b/src/Avalonia.Base/Animation/Transitions/FontVariationSettingsTransition.cs @@ -0,0 +1,26 @@ +using System; +using Avalonia.Animation.Animators; +using Avalonia.Media; + +namespace Avalonia.Animation +{ + /// + /// Transition for values, e.g. animating + /// TextElement.FontVariations between weights. Axis values interpolate + /// per axis when both endpoints set the same axes and switch discretely otherwise + /// (CSS font-variation-settings semantics). + /// + public class FontVariationSettingsTransition : Transition + { + private static readonly FontVariationSettingsAnimator s_animator = new(); + + internal override IObservable DoTransition( + IObservable progress, + FontVariationSettings? oldValue, + FontVariationSettings? newValue) + { + return new AnimatorTransitionObservable( + s_animator, progress, Easing, oldValue, newValue); + } + } +} diff --git a/src/Avalonia.Base/Avalonia.Base.csproj b/src/Avalonia.Base/Avalonia.Base.csproj index 45f792bb96..26215a7a24 100644 --- a/src/Avalonia.Base/Avalonia.Base.csproj +++ b/src/Avalonia.Base/Avalonia.Base.csproj @@ -34,6 +34,7 @@ + diff --git a/src/Avalonia.Base/Media/FontManager.cs b/src/Avalonia.Base/Media/FontManager.cs index 517f30308a..ecf078d766 100644 --- a/src/Avalonia.Base/Media/FontManager.cs +++ b/src/Avalonia.Base/Media/FontManager.cs @@ -127,6 +127,25 @@ namespace Avalonia.Media /// True, if the could create the glyph typeface, False otherwise. /// 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; @@ -134,7 +153,7 @@ namespace Avalonia.Media 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) { - 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) && @@ -202,7 +221,7 @@ namespace Avalonia.Media } //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) { diff --git a/src/Avalonia.Base/Media/FontVariationSettings.cs b/src/Avalonia.Base/Media/FontVariationSettings.cs index 2cba73f8ce..1807b91870 100644 --- a/src/Avalonia.Base/Media/FontVariationSettings.cs +++ b/src/Avalonia.Base/Media/FontVariationSettings.cs @@ -213,6 +213,64 @@ namespace Avalonia.Media return variations.Count == 0 ? Empty : new FontVariationSettings(variations); } + /// + /// Interpolates between two settings values, for animation. + /// + /// + /// Matches CSS font-variation-settings interpolation: when both endpoints + /// set exactly the same axes, each axis value is interpolated linearly (easing + /// overshoot extrapolates); otherwise the result is discrete — + /// below the midpoint, 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. null and both mean + /// "no axes set". + /// + public static FontVariationSettings? Interpolate( + FontVariationSettings? from, + FontVariationSettings? to, + double progress) + { + var fromVariations = from?._variations ?? ImmutableArray.Empty; + var toVariations = to?._variations ?? ImmutableArray.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(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()); + } + /// Returns the parseable string form, e.g. wght=700,wdth=85. public override string ToString() { diff --git a/src/Avalonia.Base/Media/FormattedText.cs b/src/Avalonia.Base/Media/FormattedText.cs index 5000acb2c5..d48320ee2b 100644 --- a/src/Avalonia.Base/Media/FormattedText.cs +++ b/src/Avalonia.Base/Media/FormattedText.cs @@ -327,7 +327,8 @@ namespace Avalonia.Media } 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.TextDecorations, runProps.ForegroundBrush, @@ -509,7 +510,8 @@ namespace Avalonia.Media } 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.TextDecorations, runProps.ForegroundBrush, @@ -566,7 +568,8 @@ namespace Avalonia.Media } 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.TextDecorations, runProps.ForegroundBrush, diff --git a/src/Avalonia.Base/Media/GlyphTypeface.cs b/src/Avalonia.Base/Media/GlyphTypeface.cs index 13a5b055fc..5f2f196419 100644 --- a/src/Avalonia.Base/Media/GlyphTypeface.cs +++ b/src/Avalonia.Base/Media/GlyphTypeface.cs @@ -1002,10 +1002,11 @@ namespace Avalonia.Media /// /// For variation clones, the shaper is derived from the source's shaper via /// so face-level state (HarfBuzz - /// hb_face_t, parsed shaping tables) stays shared. The default - /// WithVariation implementation is a no-op; a shaper integration (e.g. - /// HarfBuzz with Font.SetVariationCoordsNormalized) overrides it to - /// configure variation coordinates on the produced shaping font. + /// hb_face_t, parsed shaping tables) stays shared. The HarfBuzz shaper + /// returns a distinct shaping font carrying the clone's normalized coordinates, + /// which the clone owns and releases on . A shaper without + /// variation support returns the source's instance, and the clone is shaped at + /// the default instance. /// /// public ITextShaperTypeface TextShaperTypeface @@ -1593,6 +1594,13 @@ namespace Avalonia.Media 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) { normalized ??= new Dictionary(axes.Length); diff --git a/src/Avalonia.Base/Media/ITextShaperTypeface.cs b/src/Avalonia.Base/Media/ITextShaperTypeface.cs index aff0508675..2e289725f6 100644 --- a/src/Avalonia.Base/Media/ITextShaperTypeface.cs +++ b/src/Avalonia.Base/Media/ITextShaperTypeface.cs @@ -13,10 +13,10 @@ namespace Avalonia.Media /// /// /// The default implementation returns default. Shaper implementations - /// that support variation (e.g. HarfBuzz via Font.SetVariationCoordsNormalized) - /// override this property alongside to - /// report whatever variation coordinates are configured on the underlying - /// shaping font. The member is internal because it traffics in normalized + /// that support variation (the HarfBuzz shaper, through + /// hb_font_set_var_coords_normalized) override this property alongside + /// to report the variation coordinates configured on + /// the underlying shaping font. The member is internal because it traffics in normalized /// (font-relative) coordinates — only Avalonia's own shaper backends implement /// it; user code speaks user-space at the /// layer. @@ -33,11 +33,16 @@ namespace Avalonia.Media /// /// /// - /// The default implementation returns this unchanged — the same no-op - /// contract used by . Shapers - /// override this to derive a new shaping font configured for the requested - /// variation while sharing face-level state (HarfBuzz hb_face_t, parsed - /// shaping tables) with the source. + /// The default implementation returns this unchanged, the same contract + /// used by : a shaper without + /// variation support shapes every variation at the default instance. The + /// HarfBuzz shaper returns this for its own position and otherwise a new + /// instance owning an hb_font_t sub-font with the requested normalized + /// coordinates, so shaped advances include HVAR deltas. + /// + /// + /// A distinct returned instance is owned by the caller: disposing it releases only + /// its own shaping font, never the face state shared with this. /// /// /// Overrides must share face-level resources between the returned instance and diff --git a/src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs b/src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs index 591189ae6e..f941076e76 100644 --- a/src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs +++ b/src/Avalonia.Base/Media/TextFormatting/TextCharacters.cs @@ -216,14 +216,25 @@ namespace Avalonia.Media.TextFormatting if (fontManager.TryMatchCharacter(fallbackCodepoint, defaultTypeface.Style, defaultTypeface.Weight, defaultTypeface.Stretch, defaultTypeface.FontFamily, defaultProperties.CultureInfo, - shapingConstraint, out fallbackTypeface) - && !fontManager.TryGetGlyphTypeface(fallbackTypeface, out fallbackGlyphTypeface)) + shapingConstraint, out fallbackTypeface)) { - // 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")); + // Variations follow the text, not the font: the matched fallback + // family renders at the same axis values the primary typeface + // requested (each font clamps to its own axes; CSS behavior). + if (defaultTypeface.FontVariations is { } fallbackVariations) + { + 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")); + } } } diff --git a/src/Avalonia.Base/Media/Typeface.cs b/src/Avalonia.Base/Media/Typeface.cs index 1d1acd88c6..87b0637b5e 100644 --- a/src/Avalonia.Base/Media/Typeface.cs +++ b/src/Avalonia.Base/Media/Typeface.cs @@ -22,12 +22,34 @@ namespace Avalonia.Media FontStyle style = FontStyle.Normal, FontWeight weight = FontWeight.Normal, FontStretch stretch = FontStretch.Normal) + : this(fontFamily, style, weight, stretch, null) + { + } + + /// + /// Initializes a new instance of the struct bound to a + /// variable-font position. + /// + /// The font family. + /// The font style. + /// The font weight. + /// The font stretch. + /// + /// Variable-font axis values in user space (e.g. wght = 700), applied when the + /// resolved font is a variable font. null and + /// both mean the design defaults. + /// + public Typeface(FontFamily fontFamily, + FontStyle style, + FontWeight weight, + FontStretch stretch, + FontVariationSettings? fontVariations) { if (weight <= 0) { throw new ArgumentException("Font weight must be > 0."); } - + if ((int)stretch < 1) { throw new ArgumentException("Font stretch must be > 1."); @@ -37,6 +59,10 @@ namespace Avalonia.Media Style = style; Weight = weight; 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; } /// @@ -50,8 +76,30 @@ namespace Avalonia.Media FontStyle style = FontStyle.Normal, FontWeight weight = FontWeight.Normal, FontStretch stretch = FontStretch.Normal) + : this(fontFamilyName, style, weight, stretch, null) + { + } + + /// + /// Initializes a new instance of the struct bound to a + /// variable-font position. + /// + /// The name of the font family. + /// The font style. + /// The font weight. + /// The font stretch. + /// + /// Variable-font axis values in user space (e.g. wght = 700), applied when the + /// resolved font is a variable font. null and + /// both mean the design defaults. + /// + public Typeface(string fontFamilyName, + FontStyle style, + FontWeight weight, + FontStretch stretch, + FontVariationSettings? fontVariations) : this(string.IsNullOrEmpty(fontFamilyName) ? FontFamily.Default : new FontFamily(fontFamilyName), - style, weight, stretch) + style, weight, stretch, fontVariations) { } @@ -77,6 +125,14 @@ namespace Avalonia.Media /// public FontStretch Stretch { get; } + /// + /// Gets the variable-font axis values in user space, or null when the + /// typeface uses the font's design defaults. Never + /// — empty settings are normalized to + /// null at construction. + /// + public FontVariationSettings? FontVariations { get; } + /// /// Gets the glyph typeface. /// @@ -93,7 +149,7 @@ namespace Avalonia.Media } 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) { - return FontFamily == other.FontFamily && Style == other.Style && - Weight == other.Weight && Stretch == other.Stretch; + // FontVariations is stored canonically (Empty coerced to null), so the + // 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() @@ -126,6 +185,7 @@ namespace Avalonia.Media hashCode = (hashCode * 397) ^ (int)Style; hashCode = (hashCode * 397) ^ (int)Weight; hashCode = (hashCode * 397) ^ (int)Stretch; + hashCode = (hashCode * 397) ^ (FontVariations?.GetHashCode() ?? 0); return hashCode; } } @@ -211,7 +271,7 @@ namespace Avalonia.Media normalizedFamilyName = (normalizedFamilyNameBuilder?.ToString() ?? normalizedFamilyName).TrimEnd(); //Preserve old font source - return new Typeface(FontFamily, style, weight, stretch); + return new Typeface(FontFamily, style, weight, stretch, FontVariations); } /// diff --git a/src/Avalonia.Controls/Documents/Inline.cs b/src/Avalonia.Controls/Documents/Inline.cs index db13308cdf..4a68b9fdd3 100644 --- a/src/Avalonia.Controls/Documents/Inline.cs +++ b/src/Avalonia.Controls/Documents/Inline.cs @@ -89,10 +89,11 @@ namespace Avalonia.Controls.Documents var parentOrSelfBackground = Background ?? FindParentBackground(); var typeface = new Typeface( - FontFamily, - FontStyle, - FontWeight, - FontStretch); + FontFamily, + FontStyle, + FontWeight, + FontStretch, + FontVariations); return new GenericTextRunProperties( typeface, diff --git a/src/Avalonia.Controls/Documents/TextElement.cs b/src/Avalonia.Controls/Documents/TextElement.cs index cac8d6f97f..1efee4fbe5 100644 --- a/src/Avalonia.Controls/Documents/TextElement.cs +++ b/src/Avalonia.Controls/Documents/TextElement.cs @@ -67,6 +67,14 @@ namespace Avalonia.Controls.Documents inherits: true, defaultValue: FontStretch.Normal); + /// + /// Defines the property. + /// + public static readonly AttachedProperty FontVariationsProperty = + AvaloniaProperty.RegisterAttached( + nameof(FontVariations), + inherits: true); + /// /// Defines the property. /// @@ -156,6 +164,18 @@ namespace Avalonia.Controls.Documents set => SetValue(FontStretchProperty, value); } + /// + /// Gets or sets the variable-font axis values in user space, e.g. + /// wght=700, wdth=85. null means the font's design defaults. + /// Fonts that are not variable ignore the settings; variable fonts clamp each + /// value to their own axis range. + /// + public FontVariationSettings? FontVariations + { + get => GetValue(FontVariationsProperty); + set => SetValue(FontVariationsProperty, value); + } + /// /// Gets or sets a brush used to paint the text. /// @@ -314,6 +334,26 @@ namespace Avalonia.Controls.Documents control.SetValue(FontStretchProperty, value); } + /// + /// Gets the value of the attached on a control. + /// + /// The control. + /// The font variation settings. + public static FontVariationSettings? GetFontVariations(Control control) + { + return control.GetValue(FontVariationsProperty); + } + + /// + /// Sets the value of the attached on a control. + /// + /// The control. + /// The property value to set. + public static void SetFontVariations(Control control, FontVariationSettings? value) + { + control.SetValue(FontVariationsProperty, value); + } + /// /// Gets the value of the attached on a control. /// @@ -362,6 +402,7 @@ namespace Avalonia.Controls.Documents case nameof(FontStyle): case nameof(FontWeight): case nameof(FontStretch): + case nameof(FontVariations): case nameof(Foreground): InlineHost?.Invalidate(); break; diff --git a/src/Avalonia.Controls/Presenters/ContentPresenter.cs b/src/Avalonia.Controls/Presenters/ContentPresenter.cs index 0628e0c0b9..843d88e67c 100644 --- a/src/Avalonia.Controls/Presenters/ContentPresenter.cs +++ b/src/Avalonia.Controls/Presenters/ContentPresenter.cs @@ -94,6 +94,12 @@ namespace Avalonia.Controls.Presenters public static readonly StyledProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(); + /// + /// Defines the property. + /// + public static readonly StyledProperty FontVariationsProperty = + TextElement.FontVariationsProperty.AddOwner(); + /// /// Defines the property /// @@ -298,6 +304,16 @@ namespace Avalonia.Controls.Presenters set => SetValue(FontStretchProperty, value); } + /// + /// Gets or sets the variable-font axis values (e.g. wght=700). + /// null means the font's design defaults. + /// + public FontVariationSettings? FontVariations + { + get => GetValue(FontVariationsProperty); + set => SetValue(FontVariationsProperty, value); + } + /// /// Gets or sets the text alignment /// diff --git a/src/Avalonia.Controls/Presenters/TextPresenter.cs b/src/Avalonia.Controls/Presenters/TextPresenter.cs index dd66cc1183..9214162085 100644 --- a/src/Avalonia.Controls/Presenters/TextPresenter.cs +++ b/src/Avalonia.Controls/Presenters/TextPresenter.cs @@ -215,6 +215,16 @@ namespace Avalonia.Controls.Presenters set => TextElement.SetFontStretch(this, value); } + /// + /// Gets or sets the variable-font axis values (e.g. wght=700). + /// null means the font's design defaults. + /// + public FontVariationSettings? FontVariations + { + get => TextElement.GetFontVariations(this); + set => TextElement.SetFontVariations(this, value); + } + /// /// Gets or sets a brush used to paint the text. /// @@ -579,7 +589,7 @@ namespace Avalonia.Controls.Presenters var caretIndex = CaretIndex; var preeditText = 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 selectionEnd = SelectionEnd; var start = Math.Min(selectionStart, selectionEnd); @@ -1121,6 +1131,7 @@ namespace Avalonia.Controls.Presenters case nameof(FontWeight): case nameof(FontFamily): case nameof(FontStretch): + case nameof(FontVariations): case nameof(Text): case nameof(LetterSpacing): case nameof(PasswordChar): diff --git a/src/Avalonia.Controls/Primitives/TemplatedControl.cs b/src/Avalonia.Controls/Primitives/TemplatedControl.cs index 80f4aa572e..f98ce7ce26 100644 --- a/src/Avalonia.Controls/Primitives/TemplatedControl.cs +++ b/src/Avalonia.Controls/Primitives/TemplatedControl.cs @@ -82,6 +82,12 @@ namespace Avalonia.Controls.Primitives public static readonly StyledProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(); + /// + /// Defines the property. + /// + public static readonly StyledProperty FontVariationsProperty = + TextElement.FontVariationsProperty.AddOwner(); + /// /// Defines the property. /// @@ -239,6 +245,16 @@ namespace Avalonia.Controls.Primitives set => SetValue(FontStretchProperty, value); } + /// + /// Gets or sets the variable-font axis values (e.g. wght=700) used to draw + /// the control's text. null means the font's design defaults. + /// + public FontVariationSettings? FontVariations + { + get => GetValue(FontVariationsProperty); + set => SetValue(FontVariationsProperty, value); + } + /// /// Gets or sets the brush used to draw the control's text and other foreground elements. /// diff --git a/src/Avalonia.Controls/SelectableTextBlock.cs b/src/Avalonia.Controls/SelectableTextBlock.cs index 4bd0258062..22368e5e34 100644 --- a/src/Avalonia.Controls/SelectableTextBlock.cs +++ b/src/Avalonia.Controls/SelectableTextBlock.cs @@ -193,7 +193,7 @@ namespace Avalonia.Controls 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( typeface, diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index e1417b545f..7a9267a6b5 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -60,6 +60,12 @@ namespace Avalonia.Controls public static readonly StyledProperty FontStretchProperty = TextElement.FontStretchProperty.AddOwner(); + /// + /// Defines the property. + /// + public static readonly StyledProperty FontVariationsProperty = + TextElement.FontVariationsProperty.AddOwner(); + /// /// Defines the property. /// @@ -280,6 +286,16 @@ namespace Avalonia.Controls set => SetValue(FontStretchProperty, value); } + /// + /// Gets or sets the variable-font axis values (e.g. wght=700) used to draw + /// the control's text. null means the font's design defaults. + /// + public FontVariationSettings? FontVariations + { + get => GetValue(FontVariationsProperty); + set => SetValue(FontVariationsProperty, value); + } + /// /// Gets or sets the brush used to draw the control's text and other foreground elements. /// @@ -678,7 +694,7 @@ namespace Avalonia.Controls /// A object. 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( typeface, @@ -940,6 +956,7 @@ namespace Avalonia.Controls case nameof(FontStyle): case nameof(FontFamily): case nameof(FontStretch): + case nameof(FontVariations): case nameof(FlowDirection): case nameof(LetterSpacing): case nameof(Text): diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index 7c85e8d39b..6123f11e90 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -2751,7 +2751,7 @@ namespace Avalonia.Controls if (MaxLines > 0 && double.IsNaN(Height)) { 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 textLayout = new TextLayout(new LineTextSource(MaxLines), paragraphProperties); var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter(); @@ -2767,7 +2767,7 @@ namespace Avalonia.Controls if (MinLines > 0 && double.IsNaN(Height)) { 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 textLayout = new TextLayout(new LineTextSource(MinLines), paragraphProperties); var verticalSpace = GetVerticalSpaceBetweenScrollViewerAndPresenter(); diff --git a/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzNative.cs b/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzNative.cs new file mode 100644 index 0000000000..d841857534 --- /dev/null +++ b/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzNative.cs @@ -0,0 +1,75 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Avalonia.Harfbuzz +{ + /// + /// HarfBuzz entry points that HarfBuzzSharp exports natively but does not wrap. + /// + 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); + } + } + + /// + /// Sets normalized variation coordinates, in fvar axis order and F2Dot14 units, on + /// . + /// + /// + /// false when the loaded native library lacks the entry point; the font is left + /// at the default instance. + /// + public static bool TrySetVarCoordsNormalized(IntPtr font, ReadOnlySpan 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); + } +} diff --git a/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs b/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs index 284ac4fa74..7f0802b46e 100644 --- a/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs +++ b/src/HarfBuzz/Avalonia.HarfBuzz/HarfBuzzTypeface.cs @@ -7,6 +7,9 @@ namespace Avalonia.Harfbuzz { internal class HarfBuzzTypeface : ITextShaperTypeface { + private readonly bool _ownsFace; + private readonly NormalizedVariationPosition _variationPosition; + public HarfBuzzTypeface(GlyphTypeface glyphTypeface) { GlyphTypeface = glyphTypeface; @@ -16,12 +19,63 @@ namespace Avalonia.Harfbuzz HBFont = new Font(HBFace); 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 Face HBFace { 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 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) { if (!GlyphTypeface.PlatformTypeface.TryGetTable((uint)tag, out var table)) @@ -57,7 +111,12 @@ namespace Avalonia.Harfbuzz public void Dispose() { HBFont.Dispose(); - HBFace.Dispose(); + + // A variation instance shares the face with the typeface it was derived from. + if (_ownsFace) + { + HBFace.Dispose(); + } } } diff --git a/tests/Avalonia.Base.UnitTests/Animation/FontVariationSettingsTransitionTests.cs b/tests/Avalonia.Base.UnitTests/Animation/FontVariationSettingsTransitionTests.cs new file mode 100644 index 0000000000..0d036cd287 --- /dev/null +++ b/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); + } + } +} diff --git a/tests/Avalonia.Base.UnitTests/Media/FontManagerVariationTests.cs b/tests/Avalonia.Base.UnitTests/Media/FontManagerVariationTests.cs new file mode 100644 index 0000000000..751e9b3fd9 --- /dev/null +++ b/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 +{ + /// + /// 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. + /// + 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())); + + /// + /// 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. + /// + 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? familyTypefaces) + { + familyTypefaces = null; + return false; + } + } + } +} diff --git a/tests/Avalonia.Base.UnitTests/Media/FontVariationSettingsTests.cs b/tests/Avalonia.Base.UnitTests/Media/FontVariationSettingsTests.cs index 296019a8ef..0192d04c06 100644 --- a/tests/Avalonia.Base.UnitTests/Media/FontVariationSettingsTests.cs +++ b/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("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)); + } } } diff --git a/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs index 9054ef6f46..e3862f7e2b 100644 --- a/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs +++ b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceVariationTests.cs @@ -161,6 +161,24 @@ namespace Avalonia.Base.UnitTests.Media 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] public void CreateNormalizedPosition_Uses_Named_Instance_Coordinates() { diff --git a/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs index 56e346f412..f0976bafa3 100644 --- a/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs +++ b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceWithVariationTests.cs @@ -283,6 +283,23 @@ namespace Avalonia.Base.UnitTests.Media 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] public void WithVariations_Selects_Named_Instance_By_Index() { diff --git a/tests/Avalonia.Base.UnitTests/Media/TypefaceTests.cs b/tests/Avalonia.Base.UnitTests/Media/TypefaceTests.cs index cec0ca543f..81cb6de3f0 100644 --- a/tests/Avalonia.Base.UnitTests/Media/TypefaceTests.cs +++ b/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()); } + [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 Italic", "Hello World", FontStyle.Italic, FontWeight.Normal)] [InlineData("Hello World Italic Bold", "Hello World", FontStyle.Italic, FontWeight.Bold)] diff --git a/tests/Avalonia.Controls.UnitTests/InlineTests.cs b/tests/Avalonia.Controls.UnitTests/InlineTests.cs index 2d01215497..f1b8bd52a1 100644 --- a/tests/Avalonia.Controls.UnitTests/InlineTests.cs +++ b/tests/Avalonia.Controls.UnitTests/InlineTests.cs @@ -61,6 +61,24 @@ namespace Avalonia.Controls.UnitTests 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(); + span.BuildTextRun(textRuns); + + var runProperties = textRuns[0].Properties; + Assert.NotNull(runProperties); + Assert.Equal(FontVariationSettings.Parse("wght=700"), runProperties.Typeface.FontVariations); + } + [Fact] public void Should_Inherit_Background_In_Nested_Inlines() { diff --git a/tests/Avalonia.Controls.UnitTests/Presenters/TextPresenter_Tests.cs b/tests/Avalonia.Controls.UnitTests/Presenters/TextPresenter_Tests.cs index 1c901d538f..f362dee94b 100644 --- a/tests/Avalonia.Controls.UnitTests/Presenters/TextPresenter_Tests.cs +++ b/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] public void Measure_And_Arrange_Should_Use_WidthIncludingTrailingWhitespace_For_Bounds() { diff --git a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs index d0c78e73ea..4311b57433 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs +++ b/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] public void Changing_InlinesCollection_Should_Invalidate_Measure() { diff --git a/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs b/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs index 3c6f895ea8..9030001e0f 100644 --- a/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs +++ b/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/BasicTests.cs @@ -876,6 +876,18 @@ namespace Avalonia.Markup.Xaml.UnitTests.Xaml 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 = @""; + + var textBlock = AvaloniaRuntimeXamlLoader.Parse(xaml); + + Assert.Equal(FontVariationSettings.Parse("wght=700, wdth=85"), textBlock.FontVariations); + } + [Fact] public void AddChild_Child_Is_Set() { diff --git a/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextShaperVariationTests.cs b/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextShaperVariationTests.cs new file mode 100644 index 0000000000..f44fdb7978 --- /dev/null +++ b/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))); + } + } +}