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

Multiple Fixes for Resizetizer (esp. Android App Icons) #8020

Merged
merged 1 commit into from
Jun 15, 2022
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
8 changes: 5 additions & 3 deletions .nuspec/Microsoft.Maui.Resizetizer.targets
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@

<WriteLinesToFile
File="$(_MauiSplashInputsFile)"
Lines="@(MauiSplashScreen->'File=%(Identity);Color=%(Color)')"
Lines="@(MauiSplashScreen->'File=%(Identity);Link=%(Link);BaseSize=%(BaseSize);Resize=%(Resize);TintColor=%(TintColor);Color=%(Color);ForegroundScale=%(ForegroundScale)')"
Overwrite="true"
WriteOnlyWhenDifferent="true" />

Expand Down Expand Up @@ -636,10 +636,11 @@
on "_ValidatePresenceOfAppxManifestItems" and we need to get in before then. -->
<Target Name="_ValidatePresenceOfAppxManifestItemsBeforeTarget"
BeforeTargets="_ValidatePresenceOfAppxManifestItems"
DependsOnTargets="MauiGeneratePackageAppxManifest" />
DependsOnTargets="MauiGeneratePackageAppxManifest"
Condition="'$(_ResizetizerIsUWPApp)' == 'True' Or '$(_ResizetizerIsWindowsAppSdk)' == 'True'" />

<Target Name="MauiGeneratePackageAppxManifest"
Condition="'$(WindowsPackageType)' != 'None'"
Condition="('$(_ResizetizerIsUWPApp)' == 'True' Or '$(_ResizetizerIsWindowsAppSdk)' == 'True') And '$(WindowsPackageType)' != 'None'"
DependsOnTargets="$(MauiGeneratePackageAppxManifestDependsOnTargets)"
Inputs="$(MSBuildThisFileFullPath);$(_ResizetizerTaskAssemblyName);$(_ResizetizerInputsFile);$(_MauiSplashInputsFile);@(AppxManifest)"
Outputs="$(_MauiManifestStampFile);$(_MauiIntermediateManifest)Package.appxmanifest">
Expand Down Expand Up @@ -671,6 +672,7 @@
<ItemGroup>
<FileWrites Include="$(_MauiManifestStampFile)" />
</ItemGroup>

</Target>

<Target Name="_CleanResizetizer">
Expand Down
1 change: 0 additions & 1 deletion eng/automation/SignList.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
<ThirdParty Include="ShimSkiaSharp.dll" />
<ThirdParty Include="Fizzler.dll" />
<ThirdParty Include="Newtonsoft.Json.dll;" />
<ThirdParty Include="Svg2VectorDrawable.Net.dll" />
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing this svg2vector as the library is not currently used nor is it super useful if it is.

</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
Version="1.0.0.0" />

<Properties>
<DisplayName>.NET MAUI Controls</DisplayName>
<DisplayName>$placeholder$</DisplayName>
<PublisherDisplayName>.NET Foundation</PublisherDisplayName>
<Logo>appiconStoreLogo.png</Logo>
<Logo>$placeholder$.png</Logo>
</Properties>

<Dependencies>
Expand All @@ -31,22 +31,22 @@
Executable="$targetnametoken$.exe"
EntryPoint="$targetentrypoint$">
<uap:VisualElements
DisplayName=".NET MAUI Controls"
Description=".NET MAUI Controls sample application"
BackgroundColor="transparent"
Square150x150Logo="appiconMediumTile.png"
Square44x44Logo="appiconLogo.png">
DisplayName="$placeholder$"
Description="$placeholder$"
Square150x150Logo="$placeholder$.png"
Square44x44Logo="$placeholder$.png"
BackgroundColor="transparent">
<uap:DefaultTile
Wide310x150Logo="appiconWideTile.png"
Square71x71Logo="appiconSmallTile.png"
Square310x310Logo="appiconLargeTile.png"
ShortName="Single Project">
Square71x71Logo="$placeholder$.png"
Wide310x150Logo="$placeholder$.png"
Square310x310Logo="$placeholder$.png">
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo"/>
<uap:ShowOn Tile="wide310x150Logo"/>
</uap:ShowNameOnTiles>
</uap:DefaultTile >
<uap:SplashScreen Image="dotnet_botSplashScreen.png" />
<uap:SplashScreen
Image="$placeholder$.png" />
</uap:VisualElements>
</Application>
</Applications>
Expand Down
171 changes: 81 additions & 90 deletions src/SingleProject/Resizetizer/src/AndroidAdaptiveIconGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,150 +1,141 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace Microsoft.Maui.Resizetizer
{
internal class AndroidAdaptiveIconGenerator
{
public AndroidAdaptiveIconGenerator(ResizeImageInfo info, string appIconName, string intermediateOutputPath, ILogger logger, bool useVectors)
public AndroidAdaptiveIconGenerator(ResizeImageInfo info, string appIconName, string intermediateOutputPath, ILogger logger)
{
Info = info;
Logger = logger;
UseVectors = useVectors;
IntermediateOutputPath = intermediateOutputPath;
AppIconName = appIconName;
}

public ResizeImageInfo Info { get; }

public string IntermediateOutputPath { get; }

public ILogger Logger { get; private set; }
public bool UseVectors { get; }

public string AppIconName { get; }

const string AdaptiveIconDrawableXml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<adaptive-icon xmlns:android=""http://schemas.android.com/apk/res/android"">
<background android:drawable=""@{backgroundType}/{name}_background""/>
<foreground android:drawable=""@{foregroundType}/{name}_foreground""/>
<background android:drawable=""@mipmap/{name}_background""/>
<foreground android:drawable=""@mipmap/{name}_foreground""/>
</adaptive-icon>";

const string EmptyVectorDrawable =
@"<vector xmlns:android=""http://schemas.android.com/apk/res/android"" xmlns:aapt=""http://schemas.android.com/aapt""
android:viewportWidth=""1024""
android:viewportHeight=""1024""
android:width=""1024dp""
android:height=""1024dp"" />
";

public IEnumerable<ResizedImageInfo> Generate()
{
var sw = new Stopwatch();
sw.Start();

var results = new List<ResizedImageInfo>();

var fullIntermediateOutputPath = new DirectoryInfo(IntermediateOutputPath);

ProcessBackground(results, fullIntermediateOutputPath);
ProcessForeground(results, fullIntermediateOutputPath);
ProcessAdaptiveIcon(results, fullIntermediateOutputPath);

sw.Stop();
Logger?.Log($"Generating app icon took {sw.ElapsedMilliseconds}ms");

return results;
}

void ProcessBackground(List<ResizedImageInfo> results, DirectoryInfo fullIntermediateOutputPath)
{
var backgroundFile = Info.Filename;
var backgroundIsVector = UseVectors && Info.IsVector;
var backgroundExt = backgroundIsVector ? ".xml" : ".png";
var backgroundDestFilename = AppIconName + "_background" + backgroundExt;
var backgroundExists = File.Exists(backgroundFile);
var backgroundDestFilename = AppIconName + "_background.png";

var foregroundFile = Info.ForegroundFilename;
var foregroundExists = File.Exists(foregroundFile);
var foregroundIsVector = !foregroundExists || (UseVectors && Info.ForegroundIsVector);
var foregroundExt = foregroundIsVector ? ".xml" : ".png";
var foregroundDestFilename = AppIconName + "_foreground" + foregroundExt;
if (backgroundExists)
Logger.Log("Converting Background SVG to PNG: " + backgroundFile);
else
Logger.Log("Background was not found (will manufacture): " + backgroundFile);

if (backgroundIsVector)
foreach (var dpi in DpiPath.Android.AppIconParts)
{
Logger.Log("Converting Background SVG to Android Drawable Vector: " + backgroundFile);

var dir = Path.Combine(fullIntermediateOutputPath.FullName, "drawable-v24");
var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path);
var destination = Path.Combine(dir, backgroundDestFilename);
Directory.CreateDirectory(dir);

Svg2VectorDrawable.Svg2Vector.Convert(backgroundFile, destination);

results.Add(new ResizedImageInfo { Dpi = new DpiPath("drawable-v24", 1, "_background"), Filename = destination });
}
else
{
Logger.Log("Converting Background SVG to PNG: " + backgroundFile);
Logger.Log($"App Icon Background Part: " + destination);

foreach (var dpi in DpiPath.Android.AppIconParts)
if (backgroundExists)
{
var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path);
var destination = Path.Combine(dir, backgroundDestFilename);
Directory.CreateDirectory(dir);

Logger.Log($"App Icon Background Part: " + destination);

var tools = SkiaSharpTools.Create(Info.IsVector, Info.Filename, dpi.Size, null, Logger);
// resize the background
var tools = SkiaSharpTools.Create(Info.IsVector, Info.Filename, dpi.Size, Info.Color, null, Logger);
tools.Resize(dpi, destination, dpiSizeIsAbsolute: true);
}
else
{
// manufacture
var tools = SkiaSharpTools.CreateImaginary(Info.Color, Logger);
tools.Resize(dpi, destination);

results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination });
}
}

Logger.Log("Looking for Foreground File: " + foregroundFile);
results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination });
}
}

var foregroundDestinationDir = Path.Combine(fullIntermediateOutputPath.FullName, "drawable");
var foregroundDestination = Path.Combine(foregroundDestinationDir, foregroundDestFilename);
Directory.CreateDirectory(foregroundDestinationDir);
void ProcessForeground(List<ResizedImageInfo> results, DirectoryInfo fullIntermediateOutputPath)
{
var foregroundFile = Info.ForegroundFilename;
var foregroundExists = File.Exists(foregroundFile);
var foregroundDestFilename = AppIconName + "_foreground.png";

if (foregroundExists)
Logger.Log("Converting Foreground SVG to PNG: " + foregroundFile);
else
Logger.Log("Foreground was not found (will manufacture): " + foregroundFile);

foreach (var dpi in DpiPath.Android.AppIconParts)
{
if (foregroundIsVector)
{
Logger.Log("Converting Foreground SVG to Android Drawable Vector: " + foregroundFile);
Svg2VectorDrawable.Svg2Vector.Convert(foregroundFile, foregroundDestination);
var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path);
var destination = Path.Combine(dir, foregroundDestFilename);
Directory.CreateDirectory(dir);

results.Add(new ResizedImageInfo { Dpi = new DpiPath("drawable", 1, "_foreground"), Filename = foregroundDestination });
Logger.Log($"App Icon Foreground Part: " + destination);

if (foregroundExists)
{
// resize the forground
var tools = SkiaSharpTools.Create(Info.ForegroundIsVector, Info.ForegroundFilename, dpi.Size, null, Info.TintColor, Logger);
tools.Resize(dpi, destination, Info.ForegroundScale, dpiSizeIsAbsolute: true);
}
else
{
Logger.Log("Converting Foreground SVG to PNG: " + foregroundFile);

foreach (var dpi in DpiPath.Android.AppIconParts)
{
var dir = Path.Combine(fullIntermediateOutputPath.FullName, dpi.Path);
var destination = Path.Combine(dir, foregroundDestFilename);
Directory.CreateDirectory(dir);

Logger.Log($"App Icon Foreground Part: " + destination);

var tools = SkiaSharpTools.Create(Info.ForegroundIsVector, Info.ForegroundFilename, dpi.Size, null, Logger);
tools.Resize(dpi, destination);

results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination });
}
// manufacture
var tools = SkiaSharpTools.CreateImaginary(null, Logger);
tools.Resize(dpi, destination);
}
}
else
{
Logger.Log("Foreground was not found: " + foregroundFile);

File.WriteAllText(foregroundDestination, EmptyVectorDrawable);
results.Add(new ResizedImageInfo { Dpi = dpi, Filename = destination });
}
}

// process adaptive icon xml
{
var adaptiveIconXmlStr = AdaptiveIconDrawableXml
.Replace("{name}", AppIconName)
.Replace("{backgroundType}", backgroundIsVector ? "drawable" : "mipmap")
.Replace("{foregroundType}", foregroundIsVector ? "drawable" : "mipmap");

var dir = Path.Combine(fullIntermediateOutputPath.FullName, "mipmap-anydpi-v26");
var adaptiveIconDestination = Path.Combine(dir, AppIconName + ".xml");
var adaptiveIconRoundDestination = Path.Combine(dir, AppIconName + "_round.xml");
Directory.CreateDirectory(dir);
void ProcessAdaptiveIcon(List<ResizedImageInfo> results, DirectoryInfo fullIntermediateOutputPath)
{
var adaptiveIconXmlStr = AdaptiveIconDrawableXml
.Replace("{name}", AppIconName);

// Write out the adaptive icon xml drawables
File.WriteAllText(adaptiveIconDestination, adaptiveIconXmlStr);
File.WriteAllText(adaptiveIconRoundDestination, adaptiveIconXmlStr);
var dir = Path.Combine(fullIntermediateOutputPath.FullName, "mipmap-anydpi-v26");
var adaptiveIconDestination = Path.Combine(dir, AppIconName + ".xml");
var adaptiveIconRoundDestination = Path.Combine(dir, AppIconName + "_round.xml");
Directory.CreateDirectory(dir);

results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1), Filename = adaptiveIconDestination });
results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1, "_round"), Filename = adaptiveIconRoundDestination });
}
// Write out the adaptive icon xml drawables
File.WriteAllText(adaptiveIconDestination, adaptiveIconXmlStr);
File.WriteAllText(adaptiveIconRoundDestination, adaptiveIconXmlStr);

return results;
results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1), Filename = adaptiveIconDestination });
results.Add(new ResizedImageInfo { Dpi = new DpiPath("mipmap-anydpi-v26", 1, "_round"), Filename = adaptiveIconRoundDestination });
}
}
}
24 changes: 11 additions & 13 deletions src/SingleProject/Resizetizer/src/GenerateSplashAndroidResources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,41 +23,39 @@ public class GenerateSplashAndroidResources : Task
public override bool Execute()
{
var splash = MauiSplashScreen[0];
WriteColors(splash);
WriteDrawable(splash);

var info = ResizeImageInfo.Parse(splash);

WriteColors(info);
WriteDrawable(info);

return !Log.HasLoggedErrors;
}

static readonly XmlWriterSettings Settings = new XmlWriterSettings { Indent = true };
const string Namespace = "http://schemas.android.com/apk/res/android";
const string Comment = "This file was auto-generated by .NET MAUI.";

void WriteColors(ITaskItem splash)
void WriteColors(ResizeImageInfo splash)
{
Directory.CreateDirectory(Path.GetDirectoryName(ColorsFile));

using var writer = XmlWriter.Create(ColorsFile, Settings);
writer.WriteComment(Comment);
writer.WriteStartElement("resources");

var colorMetadata = splash.GetMetadata("Color");
var color = Utils.ParseColorString(colorMetadata);
if (color != null)
if (splash.Color is not null)
{
writer.WriteStartElement("color");
writer.WriteAttributeString("name", "maui_splash_color");
writer.WriteString(color.ToString());
writer.WriteString(splash.Color.ToString());
writer.WriteEndElement();
}
else if (!string.IsNullOrEmpty(colorMetadata))
{
Log.LogWarning($"Unable to parse color value '{colorMetadata}' for '{splash.ItemSpec}'.");
}

writer.WriteEndDocument();
}

void WriteDrawable(ITaskItem splash)
void WriteDrawable(ResizeImageInfo splash)
{
Directory.CreateDirectory(Path.GetDirectoryName(DrawableFile));

Expand All @@ -67,7 +65,7 @@ void WriteDrawable(ITaskItem splash)
writer.WriteAttributeString("xmlns", "android", ns: null, value: Namespace);

writer.WriteStartElement("item");
writer.WriteAttributeString("android", "drawable", Namespace, "@drawable/" + Path.GetFileNameWithoutExtension(splash.ItemSpec.ToLowerInvariant()));
writer.WriteAttributeString("android", "drawable", Namespace, "@drawable/" + splash.OutputName);

writer.WriteEndDocument();
}
Expand Down
15 changes: 1 addition & 14 deletions src/SingleProject/Resizetizer/src/GenerateSplashAssets.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,7 @@ public override bool Execute()
{
var splash = MauiSplashScreen[0];

var colorMetadata = splash.GetMetadata("Color");
var color = Utils.ParseColorString(colorMetadata);
if (color == null && !string.IsNullOrEmpty(colorMetadata))
Log.LogWarning($"Unable to parse color value '{colorMetadata}' for '{splash.ItemSpec}'.");

var fileInfo = new FileInfo(splash.GetMetadata("FullPath"));
if (!fileInfo.Exists)
throw new FileNotFoundException("Unable to find background file: " + fileInfo.FullName, fileInfo.FullName);

var img = new ResizeImageInfo
{
Filename = fileInfo.FullName,
Color = color ?? SKColors.Transparent,
};
var img = ResizeImageInfo.Parse(splash);

Directory.CreateDirectory(IntermediateOutputPath);

Expand Down
Loading