diff --git a/src/Avalonia.Base/Media/Fonts/Tables/Variation/MvarTable.cs b/src/Avalonia.Base/Media/Fonts/Tables/Variation/MvarTable.cs new file mode 100644 index 0000000000..9d400d0609 --- /dev/null +++ b/src/Avalonia.Base/Media/Fonts/Tables/Variation/MvarTable.cs @@ -0,0 +1,164 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Avalonia.Media.Fonts.Tables.Variation +{ + /// + /// Parses the OpenType 'MVAR' (Metrics Variations) table. Provides font-wide metric + /// deltas (ascender, descender, line gap, x-height, cap height, underline, strikeout, + /// etc.) at a given active variation point. + /// + /// + /// + /// MVAR is the cousin of HVAR: where HVAR varies per-glyph horizontal metrics, MVAR + /// varies the font-wide constants that line up multiple glyphs into a row of text + /// (ascent + descent + line gap → line height; underline / strikeout positions and + /// thicknesses; x-height / cap height for vertical alignment). + /// + /// + /// Each MVAR value is addressed by a 4-character tag (e.g. hasc = horizontal + /// ascender from OS/2's sTypoAscender, unds = underline thickness from + /// post's underlineThickness). The header lists which tags are present along + /// with their (outer, inner) coordinates into the embedded + /// ; the delta math is identical to HVAR. + /// + /// + /// Reference: . + /// + /// + /// + /// Well-known OpenType MVAR value tags. Mapped to fields + /// in 's clone constructor. The full list of standard + /// tags is larger (~30 entries spanning sub/superscript offsets, caret slope, gasp + /// ranges, vertical metrics); the set surfaced here is the one that maps onto our + /// public FontMetrics surface today. + /// + internal static class MvarTags + { + public static readonly OpenTypeTag HorizontalAscender = OpenTypeTag.Parse("hasc"); + public static readonly OpenTypeTag HorizontalDescender = OpenTypeTag.Parse("hdsc"); + public static readonly OpenTypeTag HorizontalLineGap = OpenTypeTag.Parse("hlgp"); + public static readonly OpenTypeTag UnderlineSize = OpenTypeTag.Parse("unds"); + public static readonly OpenTypeTag UnderlineOffset = OpenTypeTag.Parse("undo"); + public static readonly OpenTypeTag StrikeoutSize = OpenTypeTag.Parse("strs"); + public static readonly OpenTypeTag StrikeoutOffset = OpenTypeTag.Parse("stro"); + } + + internal sealed class MvarTable + { + internal const string TableName = "MVAR"; + internal static OpenTypeTag Tag { get; } = OpenTypeTag.Parse(TableName); + + private const ushort SupportedMajorVersion = 1; + private const int HeaderSize = 12; + private const int MinValueRecordSize = 8; + + private readonly ItemVariationStore _store; + // Tag → (outer, inner) lookup map. Built at parse time; constant for the table's + // lifetime. We use a Dictionary because the typical valueRecordCount is small + // (~5-20) and consumers query a handful of well-known tags — a dictionary keeps + // lookups O(1) without a more complex data structure. + private readonly Dictionary _records; + + private MvarTable( + ItemVariationStore store, + Dictionary records) + { + _store = store; + _records = records; + } + + public ItemVariationStore Store => _store; + + public int RecordCount => _records.Count; + + public static bool TryLoad( + GlyphTypeface glyphTypeface, + int expectedAxisCount, + [NotNullWhen(true)] out MvarTable? mvarTable) + { + mvarTable = null; + + if (!glyphTypeface.PlatformTypeface.TryGetTable(Tag, out var data)) + { + return false; + } + + var span = data.Span; + if (span.Length < HeaderSize) + { + return false; + } + + var majorVersion = BinaryPrimitives.ReadUInt16BigEndian(span); + if (majorVersion != SupportedMajorVersion) + { + return false; + } + + // Header layout: majorVersion(2) + minorVersion(2) + reserved(2) + + // valueRecordSize(2) + valueRecordCount(2) + itemVariationStoreOffset(2). + // minorVersion and reserved are skipped — we already validated majorVersion. + var valueRecordSize = BinaryPrimitives.ReadUInt16BigEndian(span.Slice(6)); + var valueRecordCount = BinaryPrimitives.ReadUInt16BigEndian(span.Slice(8)); + var ivsOffset = BinaryPrimitives.ReadUInt16BigEndian(span.Slice(10)); + + // A version 1.x record starts with the 8 bytes this reader uses. Later minor + // versions may append fields, so records are stepped through by + // valueRecordSize; anything smaller cannot hold a record. + if (valueRecordSize < MinValueRecordSize) + { + return false; + } + + if (HeaderSize + valueRecordCount * valueRecordSize > span.Length) + { + return false; + } + + if (ivsOffset == 0 || ivsOffset >= data.Length) + { + return false; + } + + if (!ItemVariationStore.TryLoad(data.Slice(ivsOffset), expectedAxisCount, out var store)) + { + return false; + } + + var records = new Dictionary(valueRecordCount); + for (var i = 0; i < valueRecordCount; i++) + { + var recordPos = HeaderSize + i * valueRecordSize; + var tag = new OpenTypeTag(BinaryPrimitives.ReadUInt32BigEndian(span.Slice(recordPos, 4))); + var outer = BinaryPrimitives.ReadUInt16BigEndian(span.Slice(recordPos + 4, 2)); + var inner = BinaryPrimitives.ReadUInt16BigEndian(span.Slice(recordPos + 6, 2)); + + // Duplicate tags would be a malformed table; first-seen wins. + records.TryAdd(tag, (outer, inner)); + } + + mvarTable = new MvarTable(store, records); + return true; + } + + /// + /// Computes the delta for the font-wide metric identified by + /// at the supplied active variation point. Returns + /// false when the font doesn't declare a value record for that tag + /// (a common case — most variable fonts only vary a subset of metrics). + /// + public bool TryGetMetricDelta(OpenTypeTag valueTag, ReadOnlySpan activeCoords, out float delta) + { + if (!_records.TryGetValue(valueTag, out var indices)) + { + delta = 0f; + return false; + } + + return _store.TryGetDelta(indices.outer, indices.inner, activeCoords, out delta); + } + } +} diff --git a/src/Avalonia.Base/Media/GlyphTypeface.cs b/src/Avalonia.Base/Media/GlyphTypeface.cs index 563d53b713..2a711b4352 100644 --- a/src/Avalonia.Base/Media/GlyphTypeface.cs +++ b/src/Avalonia.Base/Media/GlyphTypeface.cs @@ -60,6 +60,15 @@ namespace Avalonia.Media // neighbors). Inter Variable carries HVAR; most production variable fonts do. private readonly HvarTable? _hvarTable; + // MVAR table — font-wide metric deltas (ascender, descender, line gap, underline, + // strikeout, etc.) at the active variation point. Loaded once per source typeface + // and applied to the FontMetrics struct in the clone constructor — clones therefore + // see Metrics that reflect their variation without paying any per-call cost. + // Null on static fonts and on variable fonts that don't carry MVAR (which is fine — + // it just means metrics don't vary across axis space, like Inter Variable's + // ascent/descent). + private readonly MvarTable? _mvarTable; + // Source typeface for variation clones. Null for default-instance typefaces // (the source) — every WithVariation clone points back to its source so all // variations of the same font share a single cache and resource owner. @@ -345,6 +354,11 @@ namespace Avalonia.Media // RSB deltas). Loaded once per typeface; per-call TryGetHorizontalGlyphAdvance // pays a field-access + IsDefault check when no variation is active. HvarTable.TryLoad(this, _fvarTable.Axes.Length, out _hvarTable); + + // MVAR provides font-wide metric deltas (ascent, descent, line gap, + // underline, strikeout). Loaded here so clones can apply the deltas to + // their FontMetrics struct in their own constructor — see the clone ctor. + MvarTable.TryLoad(this, _fvarTable.Axes.Length, out _mvarTable); } static CultureInfo GetCulture(int lcid) @@ -414,6 +428,7 @@ namespace Avalonia.Media _avarTable = source._avarTable; _gvarTable = source._gvarTable; _hvarTable = source._hvarTable; + _mvarTable = source._mvarTable; _hasOs2Table = source._hasOs2Table; _hasHorizontalMetrics = source._hasHorizontalMetrics; @@ -442,8 +457,14 @@ namespace Avalonia.Media Style = source.Style; Stretch = source.Stretch; - // Metrics are shared with the source; no variation data adjusts them yet. - Metrics = source.Metrics; + // Metrics: apply MVAR deltas to the source's default-instance metrics. The + // sign conventions follow GlyphTypeface's source constructor — Avalonia's + // Ascent / Descent / UnderlinePosition / StrikethroughPosition are stored + // negated relative to their OpenType raw values, so the corresponding MVAR + // deltas get subtracted; thicknesses and line gap are added as-is. + Metrics = source._mvarTable is not null + ? ApplyMvarDeltas(source.Metrics, source._mvarTable, variation, source._fvarTable!) + : source.Metrics; // _supportedFeatures is lazy — let each clone materialize independently. // _textShaperTypeface is intentionally null so the getter derives a variation-aware @@ -471,6 +492,71 @@ namespace Avalonia.Media } } + /// + /// Builds a varied by applying MVAR deltas to the + /// source's default-instance metrics at the clone's variation point. + /// + /// + /// Sign conventions match GlyphTypeface's source constructor: hasc, + /// hdsc, undo, stro deltas are subtracted because + /// Avalonia stores Ascent / Descent / UnderlinePosition / StrikethroughPosition + /// negated relative to their OpenType raw values; hlgp, unds, + /// strs are added as-is. Missing MVAR records on a tag leave that field + /// at the source's value (i.e. constant across axis space — common for fonts + /// like Inter that hold ascent/descent fixed across the weight axis). + /// + private static FontMetrics ApplyMvarDeltas( + FontMetrics baseMetrics, + MvarTable mvar, + NormalizedVariationPosition variation, + FvarTable fvar) + { + // Project the variation onto fvar's axis order. We don't reuse the + // GlyphTypeface._activeCoords cache here because Metrics is computed inside + // the clone constructor itself, before _activeCoords has been assigned. + var axes = fvar.AxisTags; + Span coords = stackalloc float[axes.Length]; + for (var i = 0; i < axes.Length; i++) + { + variation.TryGetCoordinate(axes[i], out var v); + coords[i] = v; + } + + var ascent = baseMetrics.Ascent; + var descent = baseMetrics.Descent; + var lineGap = baseMetrics.LineGap; + var underlinePosition = baseMetrics.UnderlinePosition; + var underlineThickness = baseMetrics.UnderlineThickness; + var strikethroughPosition = baseMetrics.StrikethroughPosition; + var strikethroughThickness = baseMetrics.StrikethroughThickness; + + if (mvar.TryGetMetricDelta(MvarTags.HorizontalAscender, coords, out var d)) + ascent -= (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.HorizontalDescender, coords, out d)) + descent -= (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.HorizontalLineGap, coords, out d)) + lineGap += (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.UnderlineOffset, coords, out d)) + underlinePosition -= (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.UnderlineSize, coords, out d)) + underlineThickness += (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.StrikeoutOffset, coords, out d)) + strikethroughPosition -= (int)MathF.Round(d); + if (mvar.TryGetMetricDelta(MvarTags.StrikeoutSize, coords, out d)) + strikethroughThickness += (int)MathF.Round(d); + + return baseMetrics with + { + Ascent = ascent, + Descent = descent, + LineGap = lineGap, + UnderlinePosition = underlinePosition, + UnderlineThickness = underlineThickness, + StrikethroughPosition = strikethroughPosition, + StrikethroughThickness = strikethroughThickness, + }; + } + private static ushort GetFontDesignEmHeight(HeadTable? headTable) { var unitsPerEm = headTable?.UnitsPerEm ?? 0; diff --git a/tests/Avalonia.Base.UnitTests/Media/Fonts/Tables/MvarTableTests.cs b/tests/Avalonia.Base.UnitTests/Media/Fonts/Tables/MvarTableTests.cs new file mode 100644 index 0000000000..a985f36d15 --- /dev/null +++ b/tests/Avalonia.Base.UnitTests/Media/Fonts/Tables/MvarTableTests.cs @@ -0,0 +1,186 @@ +using System; +using System.Buffers.Binary; +using Avalonia.Base.UnitTests.Media.Fonts.Tables; +using Avalonia.Media; +using Avalonia.Media.Fonts; +using Avalonia.Media.Fonts.Tables.Variation; +using Avalonia.Platform; +using Avalonia.UnitTests; +using Xunit; + +namespace Avalonia.Base.UnitTests.Media.Fonts.Tables +{ + public class MvarTableTests + { + private const string InterRegularAsset = + "resm:Avalonia.Base.UnitTests.Assets.Inter-Regular.ttf?assembly=Avalonia.Base.UnitTests"; + + private const string InterVariableAsset = + "resm:Avalonia.Base.UnitTests.Assets.InterVariable.ttf?assembly=Avalonia.Base.UnitTests"; + + private static GlyphTypeface LoadTypeface(string assetUri) + { + var assetLoader = new StandardAssetLoader(); + using var stream = assetLoader.Open(new Uri(assetUri)); + return new GlyphTypeface(new CustomPlatformTypeface(stream)); + } + + [Fact] + public void TryLoad_Returns_False_For_Static_Font() + { + var typeface = LoadTypeface(InterRegularAsset); + + Assert.False(MvarTable.TryLoad(typeface, expectedAxisCount: 0, out var mvar)); + Assert.Null(mvar); + } + + [Fact] + public void TryLoad_Returns_True_For_Inter_Variable() + { + var typeface = LoadTypeface(InterVariableAsset); + + Assert.True(MvarTable.TryLoad(typeface, expectedAxisCount: 2, out var mvar)); + Assert.NotNull(mvar); + Assert.NotNull(mvar!.Store); + Assert.Equal(2, mvar.Store.AxisCount); + } + + [Fact] + public void TryLoad_Rejects_Mismatched_Axis_Count() + { + var typeface = LoadTypeface(InterVariableAsset); + + Assert.False(MvarTable.TryLoad(typeface, expectedAxisCount: 5, out _)); + } + + [Fact] + public void Inter_Variable_Declares_Underline_And_Strikeout_Records() + { + // Verified directly against Inter Variable's MVAR binary: 5 records + // (stro, strs, undo, unds, xhgt). Ascent/descent/line gap are NOT in MVAR + // for Inter — they're held constant across weights. + var typeface = LoadTypeface(InterVariableAsset); + Assert.True(MvarTable.TryLoad(typeface, 2, out var mvar)); + + Assert.Equal(5, mvar!.RecordCount); + + Span bold = stackalloc float[2] { 0f, 1f }; + + // Underline / strikeout deltas should be non-zero at wght=1.0 (Inter's + // strokes thicken with weight, so the underline / strikeout sizes do too). + Assert.True(mvar.TryGetMetricDelta(MvarTags.UnderlineSize, bold, out var unds)); + Assert.NotEqual(0f, unds); + + Assert.True(mvar.TryGetMetricDelta(MvarTags.StrikeoutSize, bold, out var strs)); + Assert.NotEqual(0f, strs); + } + + [Fact] + public void Inter_Variable_Does_Not_Declare_Ascent_Record() + { + // hasc, hdsc, hlgp are absent in Inter Variable's MVAR — TryGetMetricDelta + // should return false rather than guess a delta. + var typeface = LoadTypeface(InterVariableAsset); + Assert.True(MvarTable.TryLoad(typeface, 2, out var mvar)); + + Span coords = stackalloc float[2] { 0f, 1f }; + + Assert.False(mvar!.TryGetMetricDelta(MvarTags.HorizontalAscender, coords, out var d)); + Assert.Equal(0f, d); + + Assert.False(mvar.TryGetMetricDelta(MvarTags.HorizontalDescender, coords, out d)); + Assert.False(mvar.TryGetMetricDelta(MvarTags.HorizontalLineGap, coords, out d)); + } + + [Fact] + public void TryGetMetricDelta_Returns_Zero_At_Default_Variation() + { + // At the default-instance point every region's scaler is 0 (peaks are at + // axis extrema), so every delta sum is 0. + var typeface = LoadTypeface(InterVariableAsset); + Assert.True(MvarTable.TryLoad(typeface, 2, out var mvar)); + + Span defaultCoords = stackalloc float[2] { 0f, 0f }; + + Assert.True(mvar!.TryGetMetricDelta(MvarTags.UnderlineSize, defaultCoords, out var delta)); + Assert.Equal(0f, delta); + } + + [Fact] + public void TryLoad_Reads_Records_Larger_Than_The_Version_1_0_Layout() + { + // A later minor version may append fields to each value record; readers step + // through the records by valueRecordSize and keep reading the first 8 bytes. + // Re-encode Inter Variable's MVAR with 10-byte records and compare. + var original = LoadTypeface(InterVariableAsset); + Assert.True(MvarTable.TryLoad(original, 2, out var expected)); + + var font = SyntheticFont.FromAsset(SyntheticFont.Assets.InterVariable); + Assert.True(original.PlatformTypeface.TryGetTable(OpenTypeTag.Parse("MVAR"), out var mvarData)); + var widened = WidenValueRecords(mvarData.Span, extraBytes: 2); + + var typeface = font.Replace("MVAR", widened).TryCreateGlyphTypeface(); + Assert.NotNull(typeface); + + Assert.True(MvarTable.TryLoad(typeface!, 2, out var mvar)); + Assert.Equal(expected!.RecordCount, mvar!.RecordCount); + + Span bold = stackalloc float[2] { 0f, 1f }; + + foreach (var tag in new[] { MvarTags.UnderlineSize, MvarTags.StrikeoutSize }) + { + Assert.True(expected.TryGetMetricDelta(tag, bold, out var expectedDelta)); + Assert.True(mvar.TryGetMetricDelta(tag, bold, out var actualDelta)); + Assert.Equal(expectedDelta, actualDelta); + } + } + + [Fact] + public void TryLoad_Rejects_Records_Smaller_Than_8_Bytes() + { + var original = LoadTypeface(InterVariableAsset); + Assert.True(original.PlatformTypeface.TryGetTable(OpenTypeTag.Parse("MVAR"), out var mvarData)); + + var shrunk = mvarData.ToArray(); + BinaryPrimitives.WriteUInt16BigEndian(shrunk.AsSpan(6), 6); + + var typeface = SyntheticFont.FromAsset(SyntheticFont.Assets.InterVariable) + .Replace("MVAR", shrunk) + .TryCreateGlyphTypeface(); + + Assert.NotNull(typeface); + Assert.False(MvarTable.TryLoad(typeface!, 2, out _)); + } + + /// + /// Rewrites a version 1.0 MVAR table so every value record carries + /// trailing zero bytes, moving the item variation store + /// behind the larger record array. + /// + private static byte[] WidenValueRecords(ReadOnlySpan mvar, int extraBytes) + { + const int headerSize = 12; + + var recordSize = BinaryPrimitives.ReadUInt16BigEndian(mvar.Slice(6)); + var recordCount = BinaryPrimitives.ReadUInt16BigEndian(mvar.Slice(8)); + var storeOffset = BinaryPrimitives.ReadUInt16BigEndian(mvar.Slice(10)); + var newRecordSize = recordSize + extraBytes; + var newStoreOffset = storeOffset + recordCount * extraBytes; + + var result = new byte[mvar.Length + recordCount * extraBytes]; + mvar.Slice(0, headerSize).CopyTo(result); + BinaryPrimitives.WriteUInt16BigEndian(result.AsSpan(6), (ushort)newRecordSize); + BinaryPrimitives.WriteUInt16BigEndian(result.AsSpan(10), (ushort)newStoreOffset); + + for (var i = 0; i < recordCount; i++) + { + mvar.Slice(headerSize + i * recordSize, recordSize) + .CopyTo(result.AsSpan(headerSize + i * newRecordSize)); + } + + mvar.Slice(storeOffset).CopyTo(result.AsSpan(newStoreOffset)); + + return result; + } + } +} diff --git a/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceMvarMetricsTests.cs b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceMvarMetricsTests.cs new file mode 100644 index 0000000000..15be02cf2b --- /dev/null +++ b/tests/Avalonia.Base.UnitTests/Media/GlyphTypefaceMvarMetricsTests.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using Avalonia.Base.UnitTests.Media.Fonts.Tables; +using Avalonia.Media; +using Avalonia.Media.Fonts; +using Avalonia.Platform; +using Xunit; + +namespace Avalonia.Base.UnitTests.Media +{ + /// + /// End-to-end tests for MVAR: on a typeface + /// produced by reflects the variation + /// point via MVAR. + /// + public class GlyphTypefaceMvarMetricsTests + { + private const string InterRegularAsset = + "resm:Avalonia.Base.UnitTests.Assets.Inter-Regular.ttf?assembly=Avalonia.Base.UnitTests"; + + private const string InterVariableAsset = + "resm:Avalonia.Base.UnitTests.Assets.InterVariable.ttf?assembly=Avalonia.Base.UnitTests"; + + private static readonly OpenTypeTag s_wghtTag = OpenTypeTag.Parse("wght"); + + private static GlyphTypeface LoadTypeface(string assetUri) + { + var assetLoader = new StandardAssetLoader(); + using var stream = assetLoader.Open(new Uri(assetUri)); + return new GlyphTypeface(new CustomPlatformTypeface(stream)); + } + + private static NormalizedVariationPosition WghtPosition(GlyphTypeface gt, double weight) + => gt.CreateNormalizedPosition(new FontVariationSettings( + new[] { new FontVariation(s_wghtTag, weight) })); + + [Fact] + public void Static_Font_Metrics_Unchanged_Across_WithVariation() + { + // WithVariation returns 'this' for static fonts, so Metrics is trivially + // identical. Pins the no-regression promise. + var gt = LoadTypeface(InterRegularAsset); + var alsoGt = gt.WithVariation(NormalizedVariationPosition.FromCoordinates( + new Dictionary { [s_wghtTag] = 0.5f })); + + Assert.Same(gt, alsoGt); + Assert.Equal(gt.Metrics, alsoGt.Metrics); + } + + [Fact] + public void Variable_Font_Source_Metrics_Equal_Default_Instance() + { + // The source typeface's Metrics is at the default instance — no MVAR delta + // applied. This is what gives the existing PR2 default-instance render tests + // their stability. + var gt = LoadTypeface(InterVariableAsset); + + // Ascent / Descent values are non-zero (sanity). + Assert.NotEqual(0, gt.Metrics.Ascent); + Assert.NotEqual(0, gt.Metrics.Descent); + } + + [Fact] + public void Underline_Thickness_Grows_With_Weight() + { + // Inter Variable's MVAR declares 'unds' (underline size). At wght=900 the + // underline should be thicker than at wght=400. + var gt = LoadTypeface(InterVariableAsset); + var black = gt.WithVariation(WghtPosition(gt, 900)); + + Assert.True(black.Metrics.UnderlineThickness > gt.Metrics.UnderlineThickness, + $"Expected wght=900 underline thickness ({black.Metrics.UnderlineThickness}) " + + $"> regular ({gt.Metrics.UnderlineThickness})"); + } + + [Fact] + public void Strikeout_Thickness_Grows_With_Weight() + { + // Same reasoning for strs (strikeout size). Inter Variable declares it. + var gt = LoadTypeface(InterVariableAsset); + var black = gt.WithVariation(WghtPosition(gt, 900)); + + Assert.True(black.Metrics.StrikethroughThickness > gt.Metrics.StrikethroughThickness, + $"Expected wght=900 strikeout thickness ({black.Metrics.StrikethroughThickness}) " + + $"> regular ({gt.Metrics.StrikethroughThickness})"); + } + + [Fact] + public void Ascent_And_Descent_Unchanged_Across_Inter_Weights() + { + // Inter Variable doesn't declare hasc/hdsc in MVAR — those metrics are + // designed to be constant across weights so all weights share a baseline. + // Verifies that missing MVAR records leave the field at the source's value. + var gt = LoadTypeface(InterVariableAsset); + var black = gt.WithVariation(WghtPosition(gt, 900)); + + Assert.Equal(gt.Metrics.Ascent, black.Metrics.Ascent); + Assert.Equal(gt.Metrics.Descent, black.Metrics.Descent); + Assert.Equal(gt.Metrics.LineGap, black.Metrics.LineGap); + } + + [Fact] + public void Default_Variation_Clone_Returns_Source_With_Identical_Metrics() + { + // WithVariation(default) on a variable font returns the source itself, so + // Metrics is identical by reference equality of the underlying record struct. + var gt = LoadTypeface(InterVariableAsset); + var defaultClone = gt.WithVariation(default); + + Assert.Same(gt, defaultClone); + Assert.Equal(gt.Metrics, defaultClone.Metrics); + } + + [Fact] + public void Intermediate_Weight_Has_Intermediate_Underline_Thickness() + { + // wght=700 lies between wght=400 (default) and wght=900 along ItemVariationStore's + // linear region scaler. Underline thickness should follow the same + // monotonic growth. + var gt = LoadTypeface(InterVariableAsset); + var semiBold = gt.WithVariation(WghtPosition(gt, 700)); + var black = gt.WithVariation(WghtPosition(gt, 900)); + + Assert.True(semiBold.Metrics.UnderlineThickness >= gt.Metrics.UnderlineThickness, + $"semiBold {semiBold.Metrics.UnderlineThickness} should be >= regular {gt.Metrics.UnderlineThickness}"); + Assert.True(black.Metrics.UnderlineThickness >= semiBold.Metrics.UnderlineThickness, + $"black {black.Metrics.UnderlineThickness} should be >= semiBold {semiBold.Metrics.UnderlineThickness}"); + } + } +}