Skip to content

Commit

Permalink
Rework Design Time Build to use .aar files directly.
Browse files Browse the repository at this point in the history
  • Loading branch information
dellis1972 committed Oct 21, 2024
1 parent 4fdc801 commit d40967b
Show file tree
Hide file tree
Showing 12 changed files with 158 additions and 81 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.


<Target Name="_InjectAaptDependencies">
<PropertyGroup>
<PropertyGroup Condition="'$(DesignTimeBuild)' != 'True'">
<_SetLatestTargetFrameworkVersionDependsOnTargets>
$(_SetLatestTargetFrameworkVersionDependsOnTargets);
_CreateAapt2VersionCache;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Copyright (C) 2016 Xamarin. All rights reserved.
per TargetFramework.
-->
<_DesignerIntermediateOutputPath Condition=" '$(_DesignerIntermediateOutputPath)' == '' And '$(_OuterIntermediateOutputPath)' != '' ">$(_OuterIntermediateOutputPath)</_DesignerIntermediateOutputPath>
<_DesignerIntermediateOutputPath Condition=" '$(_DesignerIntermediateOutputPath)' == '' And '$(_OuterIntermediateOutputPath)' != '' And '$(AndroidUseDesignerAssembly)' == 'True' And '$(DesignTimeBuild)' == 'true' ">$(_OuterIntermediateOutputPath)designtime\</_DesignerIntermediateOutputPath>
<_DesignerIntermediateOutputPath Condition=" '$(_DesignerIntermediateOutputPath)' == '' And '$(AndroidUseDesignerAssembly)' == 'True' And '$(DesignTimeBuild)' == 'true' ">$(IntermediateOutputPath)designtime\</_DesignerIntermediateOutputPath>
<_DesignerIntermediateOutputPath Condition=" '$(_DesignerIntermediateOutputPath)' == '' ">$(IntermediateOutputPath)</_DesignerIntermediateOutputPath>
<_GenerateResourceDesignerAssemblyOutput>$(_DesignerIntermediateOutputPath)$(_DesignerAssemblyName).dll</_GenerateResourceDesignerAssemblyOutput>
<_GenerateResourceDesignerClassFile Condition=" '$(Language)' == 'F#' ">$(_DesignerIntermediateOutputPath)_$(_DesignerAssemblyName).fs</_GenerateResourceDesignerClassFile>
Expand All @@ -65,6 +67,7 @@ Copyright (C) 2016 Xamarin. All rights reserved.
<!-- Generate an R.txt file using the Managed Parser -->
<GenerateRtxt
AdditionalResourceDirectories="@(LibraryResourceDirectories)"
AarLibraries="@(AndroidAarLibrary)"
CaseMapFile="$(_GenerateResourceCaseMapFile)"
JavaPlatformJarPath="$(JavaPlatformJarPath)"
ResourceDirectory="$(MonoAndroidResDirIntermediate)"
Expand All @@ -82,6 +85,7 @@ Copyright (C) 2016 Xamarin. All rights reserved.
<!-- Generate a ResourceMap file for the project and its resources -->
<GenerateResourceCaseMap
AdditionalResourceDirectories="@(LibraryResourceDirectories)"
AarLibraries="@(AndroidAarLibrary)"
OutputFile="$(_GenerateResourceCaseMapFile)"
ProjectDir="$(ProjectDir)"
ResourceDirectory="$(MonoAndroidResDirIntermediate)"
Expand Down Expand Up @@ -159,6 +163,7 @@ Copyright (C) 2016 Xamarin. All rights reserved.
<PropertyGroup>
<_BuildResourceDesignerDependsOn>
_SetupDesignerProperties;
_ResolveAars;
_GenerateResourceCaseMap;
_GenerateRtxt;
_GenerateResourceDesignerIntermediateClass;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ projects.
<_AarOutputPath>$(OutputPath)$(TargetName).aar</_AarOutputPath>
</PropertyGroup>

<Target Name="_ResolveAars">
<Target Name="_ResolveAars" AfterTargets="ResolveReferences">
<ItemGroup>
<_AarSearchDirectory Include="@(_ReferencePath->'%(RootDir)%(Directory)')" />
<_AarSearchDirectory Include="@(_ReferenceDependencyPaths->'%(RootDir)%(Directory)')" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ _ResolveAssemblies MSBuild target.
<_AdditionalProperties>
_ComputeFilesToPublishForRuntimeIdentifiers=true
;SelfContained=true
;DesignTimeBuild=$(DesignTimeBuild)
;AppendRuntimeIdentifierToOutputPath=true
;ResolveAssemblyReferencesFindRelatedSatellites=false
;SkipCompilerExecution=true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,22 +112,16 @@ properties that determine build ordering.
<ResolveReferencesDependsOn>
$(CoreResolveReferencesDependsOn);
UpdateAndroidResources;
_BuildResourceDesigner;
UpdateAndroidInterfaceProxies;
_CheckForInvalidDesignerConfig;
</ResolveReferencesDependsOn>
<DesignTimeResolveAssemblyReferencesDependsOn>
$(DesignTimeResolveAssemblyReferencesDependsOn);
_BuildResourceDesigner;
</DesignTimeResolveAssemblyReferencesDependsOn>
<_UpdateAndroidResourcesDependsOn>
$(CoreResolveReferencesDependsOn);
_CreatePropertiesCache;
_CheckForDeletedResourceFile;
_ComputeAndroidResourcePaths;
_UpdateAndroidResgen;
_CreateAar;
_BuildResourceDesigner;
</_UpdateAndroidResourcesDependsOn>
<CompileDependsOn>
_SetupMSBuildAllProjects;
Expand All @@ -142,9 +136,9 @@ properties that determine build ordering.
_CollectGeneratedManagedBindingFiles;
_ClearGeneratedManagedBindings;
AddBindingsToCompile;
$(CompileDependsOn);
_BuildResourceDesigner;
_AddResourceDesignerFiles;
$(CompileDependsOn);
_CheckAndroidHttpClientHandlerType;
</CompileDependsOn>
<CoreCompileDependsOn>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@
<Import Project="Microsoft.Android.Sdk.BundledVersions.targets" />
<Import Project="Microsoft.Android.Sdk.DefaultProperties.targets" />
<Import Project="$(MSBuildThisFileDirectory)..\tools\Xamarin.Android.Common.Debugging.props"
Condition="Exists('$(MSBuildThisFileDirectory)..\tools\Xamarin.Android.Common.Debugging.props')"/>
Condition="Exists('$(MSBuildThisFileDirectory)..\tools\Xamarin.Android.Common.Debugging.props') And '$(DesignTimeBuild)' != 'true'"/>

</Project>
33 changes: 33 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceCaseMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Android.Build.Tasks;
using Xamarin.Android.Tools;
using Xamarin.Tools.Zip;

namespace Xamarin.Android.Tasks
{
Expand All @@ -22,6 +24,8 @@ public class GenerateResourceCaseMap : AndroidTask

public ITaskItem[] AdditionalResourceDirectories { get; set; }

public string[] AarLibraries { get; set; }

[Required]
public ITaskItem OutputFile { get; set; }

Expand Down Expand Up @@ -64,6 +68,35 @@ public override bool RunTask ()
AddRename (tok [1].Replace ('/', Path.DirectorySeparatorChar), tok [0].Replace ('/', Path.DirectorySeparatorChar));
}
}
var resmap = ".net/__res_name_case_map.txt";
foreach (var aar in AarLibraries ?? Array.Empty<string>()) {
Log.LogDebugMessage ($"Processing Aar file {aar}");
if (!File.Exists (aar)) {
Log.LogDebugMessage ($"Skipping non-existent aar: {aar}");
continue;
}
using (var file = File.OpenRead (aar)) {
using var zip = ZipArchive.Open (file);
foreach (var entry in zip) {
if (entry.IsDirectory)
continue;
if (entry.FullName != resmap)
continue;
using var ms = new MemoryStream();
entry.Extract (ms);
ms.Position = 0;
using var reader = new StreamReader (ms);
string line;
// Read each line until the end of the file
while ((line = reader.ReadLine()) != null) {
if (string.IsNullOrEmpty (line))
continue;
//string [] tok = line.Split (';');
//AddRename (tok [1].Replace ('/', Path.DirectorySeparatorChar), tok [0].Replace ('/', Path.DirectorySeparatorChar));
}
}
}
}

if (MonoAndroidHelper.SaveMapFile (BuildEngine4, Path.GetFullPath (OutputFile.ItemSpec), resource_fixup)) {
Log.LogDebugMessage ($"Writing to: {OutputFile.ItemSpec}");
Expand Down
4 changes: 3 additions & 1 deletion src/Xamarin.Android.Build.Tasks/Tasks/GenerateRtxt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class GenerateRtxt : AndroidTask
public string ResourceDirectory { get; set; }
public string[] AdditionalResourceDirectories { get; set; }

public string[] AarLibraries { get; set; }

public string JavaPlatformJarPath { get; set; }

public string ResourceFlagFile { get; set; }
Expand All @@ -31,7 +33,7 @@ public override bool RunTask ()

var javaPlatformDirectory = string.IsNullOrEmpty (JavaPlatformJarPath) ? "" : Path.GetDirectoryName (JavaPlatformJarPath);
var parser = new FileResourceParser () { Log = Log, JavaPlatformDirectory = javaPlatformDirectory, ResourceFlagFile = ResourceFlagFile};
var resources = parser.Parse (ResourceDirectory, AdditionalResourceDirectories, resource_fixup);
var resources = parser.Parse (ResourceDirectory, AdditionalResourceDirectories, AarLibraries, resource_fixup);

// only update if it changed.
writer.Write (RTxtFile, resources);
Expand Down
162 changes: 102 additions & 60 deletions src/Xamarin.Android.Build.Tasks/Utilities/FileResourceParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Text.RegularExpressions;
using Microsoft.Build.Utilities;
using Microsoft.Android.Build.Tasks;
using Xamarin.Tools.Zip;

namespace Xamarin.Android.Tasks
{
Expand Down Expand Up @@ -43,7 +44,7 @@ protected XDocument LoadPublicXml () {
return null;
}

public IList<R> Parse (string resourceDirectory, IEnumerable<string> additionalResourceDirectories, Dictionary<string, string> resourceMap)
public IList<R> Parse (string resourceDirectory, IEnumerable<string> additionalResourceDirectories, IEnumerable<string> aarLibraries, Dictionary<string, string> resourceMap)
{
Log.LogDebugMessage ($"Parsing Directory {resourceDirectory}");
publicXml = LoadPublicXml ();
Expand Down Expand Up @@ -71,6 +72,34 @@ public IList<R> Parse (string resourceDirectory, IEnumerable<string> additionalR
Log.LogDebugMessage ($"Skipping non-existent directory: {dir}");
}
}
foreach (var aar in aarLibraries ?? Array.Empty<string>()) {
Log.LogDebugMessage ($"Processing Aar file {aar}");
if (!File.Exists (aar)) {
Log.LogDebugMessage ($"Skipping non-existent aar: {aar}");
continue;
}
using (var file = File.Open (aar, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) {
using var zip = ZipArchive.Open (file);
foreach (var entry in zip) {
if (entry.IsDirectory)
continue;
if (!entry.FullName.StartsWith ("res"))
continue;
var ext = Path.GetExtension (entry.FullName);
var path = Directory.GetParent (entry.FullName).Name;
if (ext == ".xml" || ext == ".axml") {
if (string.Compare (path, "raw", StringComparison.OrdinalIgnoreCase) != 0) {
using var ms = new MemoryStream();
entry.Extract (ms);
ms.Position = 0;
using XmlReader reader = XmlReader.Create (ms);
ProcessXmlFile (reader, resources);
}
}
ProcessResourceFile (entry.FullName, resources, processXml: false);
}
}
}

// now generate the Id's we need in a specific order
List<string> declarationIds = new List<string> ();
Expand Down Expand Up @@ -172,7 +201,7 @@ int GetId (ICollection<R> resources, string identifier)
return -1;
}

void ProcessResourceFile (string file, Dictionary<string, ICollection<R>> resources)
void ProcessResourceFile (string file, Dictionary<string, ICollection<R>> resources, bool processXml = true)
{
Log.LogDebugMessage ($"{nameof(ProcessResourceFile)} {file}");
var fileName = Path.GetFileNameWithoutExtension (file);
Expand All @@ -181,6 +210,10 @@ void ProcessResourceFile (string file, Dictionary<string, ICollection<R>> resour
if (fileName.EndsWith (".9", StringComparison.OrdinalIgnoreCase))
fileName = Path.GetFileNameWithoutExtension (fileName);
var path = Directory.GetParent (file).Name;
if (!processXml) {
CreateResourceField (path, fileName, resources);
return;
}
var ext = Path.GetExtension (file);
switch (ext) {
case ".xml":
Expand Down Expand Up @@ -321,72 +354,81 @@ resources [field.ResourceTypeName].Add (new R () {

void ProcessXmlFile (string file, Dictionary<string, ICollection<R>> resources)
{
Log.LogDebugMessage ($"{nameof(ProcessXmlFile)}");
using (var reader = XmlReader.Create (file)) {
while (reader.Read ()) {
if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.Comment)
continue;
if (reader.IsStartElement ()) {
var elementName = reader.Name;
var elementNS = reader.NamespaceURI;
if (!string.IsNullOrEmpty (elementNS)) {
if (elementNS != "http://schemas.android.com/apk/res/android")
continue;
}
if (elementName == "declare-styleable" || elementName == "configVarying" || elementName == "add-resource") {
ProcessStyleable (reader.ReadSubtree (), resources);
ProcessXmlFile (reader, resources);
}
}

void ProcessXmlFile (XmlReader reader, Dictionary<string, ICollection<R>> resources)
{
Log.LogDebugMessage ($"{nameof(ProcessXmlFile)}");
while (reader.Read ()) {
if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.Comment)
continue;
if (reader.IsStartElement ()) {
var elementName = reader.Name;
var elementNS = reader.NamespaceURI;
if (!string.IsNullOrEmpty (elementNS)) {
if (elementNS != "http://schemas.android.com/apk/res/android")
continue;
}
if (elementName == "declare-styleable" || elementName == "configVarying" || elementName == "add-resource") {
try {
ProcessStyleable (reader.ReadSubtree (), resources);
} catch (Exception ex) {
Log.LogErrorFromException (ex);
}
if (reader.HasAttributes) {
string name = null;
string type = null;
string id = null;
string custom_id = null;
while (reader.MoveToNextAttribute ()) {
if (reader.LocalName == "name")
name = reader.Value;
if (reader.LocalName == "type")
type = reader.Value;
if (reader.LocalName == "id") {
string[] values = reader.Value.Split ('/');
if (values.Length != 2) {
id = reader.Value.Replace ("@+id/", "").Replace ("@id/", "");
} else {
if (values [0] != "@+id" && values [0] != "@id" && !values [0].Contains ("android:")) {
custom_id = values [0].Replace ("@", "").Replace ("+", "");
}
id = values [1];
continue;
}
if (reader.HasAttributes) {
string name = null;
string type = null;
string id = null;
string custom_id = null;
while (reader.MoveToNextAttribute ()) {
if (reader.LocalName == "name")
name = reader.Value;
if (reader.LocalName == "type")
type = reader.Value;
if (reader.LocalName == "id") {
string[] values = reader.Value.Split ('/');
if (values.Length != 2) {
id = reader.Value.Replace ("@+id/", "").Replace ("@id/", "");
} else {
if (values [0] != "@+id" && values [0] != "@id" && !values [0].Contains ("android:")) {
custom_id = values [0].Replace ("@", "").Replace ("+", "");
}

id = values [1];
}
if (reader.LocalName == "inflatedId") {
string inflateId = reader.Value.Replace ("@+id/", "").Replace ("@id/", "");
var r = new R () {
ResourceTypeName = "id",
Identifier = inflateId,
Id = -1,
};
Log.LogDebugMessage ($"Adding 1 {r}");
resources[r.ResourceTypeName].Add (r);
}
}
if (name?.Contains ("android:") ?? false)
continue;
if (id?.Contains ("android:") ?? false)
continue;
// Move the reader back to the element node.
reader.MoveToElement ();
if (!string.IsNullOrEmpty (name)) {
CreateResourceField (type ?? elementName, name, resources);
}
if (!string.IsNullOrEmpty (custom_id) && !resources.ContainsKey (custom_id)) {
resources.Add (custom_id, new SortedSet<R> (new RComparer ()));
custom_types.Add (custom_id);

}
if (!string.IsNullOrEmpty (id)) {
CreateResourceField (custom_id ?? "id", id.Replace ("-", "_").Replace (".", "_"), resources);
if (reader.LocalName == "inflatedId") {
string inflateId = reader.Value.Replace ("@+id/", "").Replace ("@id/", "");
var r = new R () {
ResourceTypeName = "id",
Identifier = inflateId,
Id = -1,
};
Log.LogDebugMessage ($"Adding 1 {r}");
resources[r.ResourceTypeName].Add (r);
}
}
if (name?.Contains ("android:") ?? false)
continue;
if (id?.Contains ("android:") ?? false)
continue;
// Move the reader back to the element node.
reader.MoveToElement ();
if (!string.IsNullOrEmpty (name)) {
CreateResourceField (type ?? elementName, name, resources);
}
if (!string.IsNullOrEmpty (custom_id) && !resources.ContainsKey (custom_id)) {
resources.Add (custom_id, new SortedSet<R> (new RComparer ()));
custom_types.Add (custom_id);
}
if (!string.IsNullOrEmpty (id)) {
CreateResourceField (custom_id ?? "id", id.Replace ("-", "_").Replace (".", "_"), resources);
}
}
}
}
Expand Down
Loading

0 comments on commit d40967b

Please sign in to comment.