Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SystemFontCollection nearest match lookup #13365

Merged
merged 10 commits into from
Oct 26, 2023
25 changes: 15 additions & 10 deletions src/Avalonia.Base/Media/Fonts/SystemFontCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,23 @@ public override bool TryGetGlyphTypeface(string familyName, FontStyle style, Fon

var key = new FontCollectionKey(style, weight, stretch);

var glyphTypefaces = _glyphTypefaceCache.GetOrAdd(familyName, (key) => new ConcurrentDictionary<FontCollectionKey, IGlyphTypeface?>());
var glyphTypefaces = _glyphTypefaceCache.GetOrAdd(familyName,
(_) => new ConcurrentDictionary<FontCollectionKey, IGlyphTypeface?>());

if (!glyphTypefaces.TryGetValue(key, out glyphTypeface))
if (glyphTypefaces.TryGetValue(key, out glyphTypeface))
{
_fontManager.PlatformImpl.TryCreateGlyphTypeface(familyName, style, weight, stretch, out glyphTypeface);
return glyphTypeface != null;
}

if (!glyphTypefaces.TryAdd(key, glyphTypeface))
{
return false;
}
if(!_fontManager.PlatformImpl.TryCreateGlyphTypeface(familyName, style, weight, stretch, out glyphTypeface) ||
!glyphTypeface.FamilyName.Contains(familyName))
{
//Try to find nearest match first
TryGetNearestMatch(glyphTypefaces, key, out glyphTypeface);
}

glyphTypefaces.TryAdd(key, glyphTypeface);

return glyphTypeface != null;
}

Expand Down Expand Up @@ -101,9 +106,9 @@ private void LoadGlyphTypefaces(IFontManagerImpl fontManager, Uri source)
}

var key = new FontCollectionKey(
glyphTypeface.Style,
glyphTypeface.Weight,
glyphTypeface.Stretch);
glyphTypeface.Style,
glyphTypeface.Weight,
glyphTypeface.Stretch);

glyphTypefaces.TryAdd(key, glyphTypeface);
}
Expand Down
21 changes: 21 additions & 0 deletions tests/Avalonia.Skia.UnitTests/Media/FontManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,5 +239,26 @@ public void Should_Use_Custom_SystemFont()
}
}
}


[Fact]
public void Should_Get_Nearest_Match_For_Custom_SystemFont()
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface.With(fontManagerImpl: new FontManagerImpl())))
{
using (AvaloniaLocator.EnterScope())
{
var systemFontCollection = FontManager.Current.SystemFonts as SystemFontCollection;

Assert.NotNull(systemFontCollection);

systemFontCollection.AddCustomFontSource(new Uri(s_fontUri, UriKind.Absolute));

Assert.True(FontManager.Current.TryGetGlyphTypeface(new Typeface("Noto Mono", FontStyle.Oblique), out var glyphTypeface));

Assert.Equal("Noto Mono", glyphTypeface.FamilyName);
}
}
}
}
}