This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
FontRegistrar.cs
78 lines (66 loc) · 2.48 KB
/
FontRegistrar.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Xamarin.Forms.Internals
{
public static class FontRegistrar
{
internal static readonly Dictionary<string, (ExportFontAttribute attribute, Assembly assembly)> EmbeddedFonts = new Dictionary<string, (ExportFontAttribute attribute, Assembly assembly)>();
static Dictionary<string, (bool, string)> fontLookupCache = new Dictionary<string, (bool, string)>();
public static void Register(ExportFontAttribute fontAttribute, Assembly assembly)
{
EmbeddedFonts[fontAttribute.FontFileName] = (fontAttribute, assembly);
if (!string.IsNullOrWhiteSpace(fontAttribute.Alias))
EmbeddedFonts[fontAttribute.Alias] = (fontAttribute, assembly);
}
//TODO: Investigate making this Async
public static (bool hasFont, string fontPath) HasFont(string font)
{
try
{
if (!EmbeddedFonts.TryGetValue(font, out var foundFont))
{
return (false, null);
}
if (fontLookupCache.TryGetValue(font, out var foundResult))
return foundResult;
var fontStream = GetEmbeddedResourceStream(foundFont.assembly, foundFont.attribute.FontFileName);
var type = Registrar.Registered.GetHandlerType(typeof(EmbeddedFont));
var fontHandler = (IEmbeddedFontLoader)Activator.CreateInstance(type);
var result = fontHandler.LoadFont(new EmbeddedFont { FontName = foundFont.attribute.FontFileName, ResourceStream = fontStream });
return fontLookupCache[font] = result;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return fontLookupCache[font] = (false, null);
}
static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourceNames = assembly.GetManifestResourceNames();
var resourcePaths = resourceNames
.Where(x => x.EndsWith(resourceFileName, StringComparison.CurrentCultureIgnoreCase))
.ToArray();
if (!resourcePaths.Any())
{
throw new Exception(string.Format("Resource ending with {0} not found.", resourceFileName));
}
if (resourcePaths.Length > 1)
{
resourcePaths = resourcePaths.Where(x => IsFile(x, resourceFileName)).ToArray();
}
return assembly.GetManifestResourceStream(resourcePaths.FirstOrDefault());
}
static bool IsFile(string path, string file)
{
if (!path.EndsWith(file, StringComparison.Ordinal))
return false;
return path.Replace(file, "").EndsWith(".", StringComparison.Ordinal);
}
}
}