Browse Source

Fix EmbeddedFontCollection TryGetNearestMatch caching (#20013)

Benedikt Stebner 3 weeks ago
parent
commit
de2aa227b7

+ 6 - 0
src/Avalonia.Base/Media/Fonts/EmbeddedFontCollection.cs

@@ -71,10 +71,16 @@ namespace Avalonia.Media.Fonts
 
                     if(matchedKey != key)
                     {
+                        //Create a synthetic glyph typeface. The successfull result will be cached.
                         if (TryCreateSyntheticGlyphTypeface(glyphTypeface, style, weight, stretch, out var syntheticGlyphTypeface))
                         {
                             glyphTypeface = syntheticGlyphTypeface;
                         }
+                        else
+                        {
+                            //Add the matched glyph typeface to the cache
+                            glyphTypefaces.TryAdd(key, glyphTypeface);
+                        }
                     }
 
                     return true;

BIN
tests/Avalonia.RenderTests/Assets/MiSans-Normal.ttf


+ 23 - 0
tests/Avalonia.Skia.UnitTests/Media/EmbeddedFontCollectionTests.cs

@@ -19,6 +19,8 @@ namespace Avalonia.Skia.UnitTests.Media
 
         private const string s_manrope = "resm:Avalonia.Skia.UnitTests.Fonts?assembly=Avalonia.Skia.UnitTests#Manrope";
 
+        private const string s_misans = "resm:Avalonia.Skia.UnitTests.Assets?assembly=Avalonia.Skia.UnitTests#MiSans";
+
 
         [InlineData(FontWeight.SemiLight, FontStyle.Normal)]
         [InlineData(FontWeight.Bold, FontStyle.Italic)]
@@ -120,6 +122,27 @@ namespace Avalonia.Skia.UnitTests.Media
             }
         }
 
+        [Fact]
+        public void Should_Cache_Nearest_Match_For_MiSans()
+        {
+            using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
+            {
+                var source = new Uri(s_misans, UriKind.Absolute);
+
+                var fontCollection = new TestEmbeddedFontCollection(source, source);
+
+                fontCollection.Initialize(new CustomFontManagerImpl());
+
+                Assert.True(fontCollection.TryGetGlyphTypeface("MiSans", FontStyle.Normal, FontWeight.Normal, FontStretch.Normal, out var regularGlyphTypeface));
+
+                Assert.True(fontCollection.TryGetGlyphTypeface("MiSans", FontStyle.Normal, FontWeight.Bold, FontStretch.Normal, out var boldGlyphTypeface));
+
+                Assert.True(fontCollection.GlyphTypefaceCache.TryGetValue("MiSans", out var glyphTypefaces));
+
+                Assert.Equal(3, glyphTypefaces.Count);
+            }
+        }
+
         private class TestEmbeddedFontCollection : EmbeddedFontCollection
         {
             private bool _createSyntheticTypefaces;