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

[Android] Ensure custom fonts also get weight/slant #1011

Merged
merged 7 commits into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public void Font()
Assert.Inconclusive("needs testing");
#else
var font = remote.GetProperty<Font>(Button.FontProperty);
Assert.True(font.Weight.HasFlag(FontWeight.Bold));
Assert.AreEqual (FontWeight.Bold, font.Weight);
#endif
}

Expand Down
2 changes: 1 addition & 1 deletion src/Compatibility/Core/src/Compatibility-net6.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@
<Compile Include="AppHostBuilderExtensions.cs" />
<Compile Include="MauiHandlersCollectionExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
Expand Down
5 changes: 5 additions & 0 deletions src/Compatibility/Core/src/WinUI/Compatibility.UAP.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@
</ProjectReference>
</ItemGroup>

<ItemGroup>
<Compile Include="..\AppHostBuilderExtensions.cs" Link="AppHostBuilderExtensions.cs" />
<Compile Include="..\MauiHandlersCollectionExtensions.cs" Link="MauiHandlersCollectionExtensions.cs" />
</ItemGroup>

</Project>
10 changes: 4 additions & 6 deletions src/Compatibility/Core/src/iOS/Compatibility.iOS.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\AppHostBuilderExtensions.cs" Link="AppHostBuilderExtensions.cs" />
<Compile Include="..\MauiHandlersCollectionExtensions.cs" Link="MauiHandlersCollectionExtensions.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)ContextActionCell.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ContextScrollViewDelegate.cs" />
Expand Down Expand Up @@ -112,12 +116,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Renderers\TimePickerRenderer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Properties\AssemblyInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\CellExtensions.cs" />
<Compile Include="..\AppHostBuilderExtensions.cs">
<Link>AppHostBuilderExtensions.cs</Link>
</Compile>
<Compile Include="..\MauiHandlersCollectionExtensions.cs">
<Link>MauiHandlersCollectionExtensions.cs</Link>
</Compile>
<Compile Include="CADisplayLinkTicker.cs" />
<Compile Include="CollectionView\CarouselViewDelegator.cs" />
<Compile Include="CollectionView\CarouselViewRenderer.cs" />
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
4 changes: 4 additions & 0 deletions src/Controls/samples/Controls.Sample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ public void Configure(IAppHostBuilder appBuilder)
.ConfigureFonts(fonts =>
{
fonts.AddFont("Dokdo-Regular.ttf", "Dokdo");
fonts.AddFont("LobsterTwo-Regular.ttf", "Lobster Two");
fonts.AddFont("LobsterTwo-Bold.ttf", "Lobster Two Bold");
fonts.AddFont("LobsterTwo-Italic.ttf", "Lobster Two Italic");
fonts.AddFont("LobsterTwo-BoldItalic.ttf", "Lobster Two BoldItalic");
fonts.AddFont("ionicons.ttf", "Ionicons");
})
//.ConfigureEssentials(essentials =>
Expand Down
2 changes: 1 addition & 1 deletion src/Core/src/Fonts/EmbeddedFontLoader.Standard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ namespace Microsoft.Maui
{
public partial class EmbeddedFontLoader
{
public (bool success, string? filePath) LoadFont(EmbeddedFont font) => (false, null);
public string? LoadFont(EmbeddedFont font) => null;
}
}
8 changes: 4 additions & 4 deletions src/Core/src/Fonts/EmbeddedFontLoader.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ public partial class EmbeddedFontLoader
{
const string FontCacheFolderName = "fonts";

public (bool success, string? filePath) LoadFont(EmbeddedFont font)
public string? LoadFont(EmbeddedFont font)
{
var tmpdir = ApplicationData.Current.LocalFolder.CreateFolderAsync(FontCacheFolderName, CreationCollisionOption.OpenIfExists).AsTask().Result;

var file = tmpdir.TryGetItemAsync(font.FontName).AsTask().Result;
if (file != null)
return (true, CleanseFilePath(file.Path));
return CleanseFilePath(file.Path);

StorageFile? newFile = null;
try
Expand All @@ -30,7 +30,7 @@ public partial class EmbeddedFontLoader
font.ResourceStream.CopyTo(fileStream);
}

return (true, CleanseFilePath(newFile.Path));
return CleanseFilePath(newFile.Path);
}
catch (Exception ex)
{
Expand All @@ -40,7 +40,7 @@ public partial class EmbeddedFontLoader
newFile.DeleteAsync().AsTask().Wait();
}

return (false, null);
return null;
}

static string CleanseFilePath(string filePath)
Expand Down
14 changes: 7 additions & 7 deletions src/Core/src/Fonts/EmbeddedFontLoader.iOS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Maui
{
public partial class EmbeddedFontLoader
{
public (bool success, string? filePath) LoadFont(EmbeddedFont font)
public string? LoadFont(EmbeddedFont font)
{
try
{
Expand All @@ -19,15 +19,15 @@ public partial class EmbeddedFontLoader

var data = NSData.FromStream(font.ResourceStream);
var provider = new CGDataProvider(data);
var cGFont = CGFont.CreateFromProvider(provider);
var name = cGFont.PostScriptName;
var cgFont = CGFont.CreateFromProvider(provider);
var name = cgFont.PostScriptName;

if (CTFontManager.RegisterGraphicsFont(cGFont, out var error))
return (true, name);
if (CTFontManager.RegisterGraphicsFont(cgFont, out var error))
return name;

var uiFont = UIFont.FromName(name, 10);
if (uiFont != null)
return (true, name);
return name;

throw new NSErrorException(error);
}
Expand All @@ -36,7 +36,7 @@ public partial class EmbeddedFontLoader
_logger?.LogWarning(ex, "Unable register font {Font} with the system.", font.FontName);
}

return (false, null);
return null;
}
}
}
8 changes: 4 additions & 4 deletions src/Core/src/Fonts/FileSystemEmbeddedFontLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ public FileSystemEmbeddedFontLoader(string rootPath, ILogger<EmbeddedFontLoader>
_logger = logger;
}

public (bool success, string? filePath) LoadFont(EmbeddedFont font)
public string? LoadFont(EmbeddedFont font)
{
var filePath = Path.Combine(_rootPath, font.FontName!);
if (File.Exists(filePath))
return (true, filePath);
return filePath;

try
{
Expand All @@ -35,7 +35,7 @@ public FileSystemEmbeddedFontLoader(string rootPath, ILogger<EmbeddedFontLoader>
font.ResourceStream.CopyTo(fileStream);
}

return (true, filePath);
return filePath;
}
catch (Exception ex)
{
Expand All @@ -44,7 +44,7 @@ public FileSystemEmbeddedFontLoader(string rootPath, ILogger<EmbeddedFontLoader>
File.Delete(filePath);
}

return (false, null);
return null;
}
}
}
115 changes: 46 additions & 69 deletions src/Core/src/Fonts/FontManager.Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ namespace Microsoft.Maui
{
public class FontManager : IFontManager
{
static readonly string[] FontFolders = new[]
{
"",
"Fonts/",
"fonts/",
};

readonly ConcurrentDictionary<(string fontFamilyName, FontWeight weight, bool italic), Typeface?> _typefaces = new();
readonly IFontRegistrar _fontRegistrar;
readonly ILogger<FontManager>? _logger;
Expand All @@ -31,77 +38,63 @@ public FontManager(IFontRegistrar fontRegistrar, ILogger<FontManager>? logger =
}

public float GetFontSize(Font font, float defaultFontSize = 0) =>
font.FontSize > 0 ? (float)font.FontSize : (defaultFontSize > 0 ? defaultFontSize : 14f);
font.FontSize <= 0
? (defaultFontSize > 0 ? defaultFontSize : 14f)
: (float)font.FontSize;


(bool success, Typeface? typeface) TryGetFromAssets(string fontName)
Typeface? GetFromAssets(string fontName)
{
//First check Alias
var (hasFontAlias, fontPostScriptName) = _fontRegistrar.HasFont(fontName);
if (hasFontAlias)
return (true, Typeface.CreateFromFile(fontPostScriptName));
// First check Alias
if (_fontRegistrar.GetFont(fontName) is string fontPostScriptName)
return Typeface.CreateFromFile(fontPostScriptName);

var isAssetFont = IsAssetFontFamily(fontName);
if (isAssetFont)
{
return LoadTypefaceFromAsset(fontName);
}

var folders = new[]
{
"",
"Fonts/",
"fonts/",
};

//copied text
// copied text
var fontFile = FontFile.FromString(fontName);

if (!string.IsNullOrWhiteSpace(fontFile.Extension))
{
var (hasFont, fontPath) = _fontRegistrar.HasFont(fontFile.FileNameWithExtension());
if (hasFont)
{
return (true, Typeface.CreateFromFile(fontPath));
}
if (_fontRegistrar.GetFont(fontFile.FileNameWithExtension()) is string fontPath)
return Typeface.CreateFromFile(fontPath);
}
else
{
foreach (var ext in FontFile.Extensions)
{
var formated = fontFile.FileNameWithExtension(ext);
var (hasFont, fontPath) = _fontRegistrar.HasFont(formated);
if (hasFont)
{
return (true, Typeface.CreateFromFile(fontPath));
}
var formatted = fontFile.FileNameWithExtension(ext);
if (_fontRegistrar.GetFont(formatted) is string fontPath)
return Typeface.CreateFromFile(fontPath);

foreach (var folder in folders)
foreach (var folder in FontFolders)
{
formated = $"{folder}{fontFile.FileNameWithExtension()}#{fontFile.PostScriptName}";
var result = LoadTypefaceFromAsset(formated);
if (result.success)
formatted = $"{folder}{fontFile.FileNameWithExtension()}#{fontFile.PostScriptName}";
var result = LoadTypefaceFromAsset(formatted, false);
if (result != null)
return result;
}

}
}

return (false, null);
return null;
}

(bool success, Typeface? typeface) LoadTypefaceFromAsset(string fontfamily)
Typeface? LoadTypefaceFromAsset(string fontfamily, bool warning = true)
{
try
{
var result = Typeface.CreateFromAsset(AApplication.Context.Assets, FontNameToFontFile(fontfamily));
return (true, result);
return Typeface.CreateFromAsset(AApplication.Context.Assets, FontNameToFontFile(fontfamily));
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Unable to load font '{Font}' from assets.", fontfamily);
return (false, null);
if (warning)
_logger?.LogWarning(ex, "Unable to load font '{Font}' from assets.", fontfamily);
}

return null;
}

bool IsAssetFontFamily(string name)
Expand All @@ -113,54 +106,37 @@ bool IsAssetFontFamily(string name)
{
var (fontFamily, weight, italic) = fontData;
fontFamily ??= string.Empty;
var style = ToTypefaceStyle(weight, italic);

Typeface? result;
var result = Typeface.Default;

if (string.IsNullOrWhiteSpace(fontFamily))
if (!string.IsNullOrWhiteSpace(fontFamily))
{
if (NativeVersion.IsAtLeast(28))
if (IsAssetFontFamily(fontFamily))
{
result = Typeface.Create(Typeface.Default, (int)weight, italic);
result = Typeface.CreateFromAsset(AApplication.Context.Assets, FontNameToFontFile(fontFamily));
}
else
{
var style = ToTypefaceStyle(weight, italic);
result = Typeface.Create(Typeface.Default, style);
}
}
else if (IsAssetFontFamily(fontFamily))
{
result = Typeface.CreateFromAsset(AApplication.Context.Assets, FontNameToFontFile(fontFamily));
}
else
{
fontFamily ??= string.Empty;
var (success, typeface) = TryGetFromAssets(fontFamily);
if (success)
{
return typeface;
}
else
{
if (NativeVersion.IsAtLeast(28))
{
return Typeface.Create(Typeface.Default, (int)weight, italic);
}
if (GetFromAssets(fontFamily) is Typeface typeface)
result = typeface;
else
{
var style = ToTypefaceStyle(weight, italic);
return Typeface.Create(Typeface.Default, style);
}
result = Typeface.Create(fontFamily, style);
}
}

if (NativeVersion.IsAtLeast(28))
result = Typeface.Create(result, (int)weight, italic);
else
result = Typeface.Create(result, style);

return result;
}

TypefaceStyle ToTypefaceStyle(FontWeight weight, bool italic)
{
var style = TypefaceStyle.Normal;
var bold = weight > FontWeight.Bold;
var bold = weight >= FontWeight.Bold;
if (bold && italic)
style = TypefaceStyle.BoldItalic;
else if (bold)
Expand All @@ -169,6 +145,7 @@ TypefaceStyle ToTypefaceStyle(FontWeight weight, bool italic)
style = TypefaceStyle.Italic;
return style;
}

string FontNameToFontFile(string fontFamily)
{
fontFamily ??= string.Empty;
Expand Down
Loading