Skip to content

Commit 909b727

Browse files
committed
[Xamarin.Android.Build.Tasks] Add ConvertCustomView
Fixed #2100 Currently `ConvertResourcesCases` is called twice on ALL resources referenced by the project. This is terribly inefficient. However it is required. The first pass is done before a `Compile`, this fixes up the casing for things like drawables etc ready to be processed by aapt. The second is done after `GenerateJavaStubs` which happens AFTER the `Compile` step. This is to replace any custom view references with the correct `{md5}.View` style references. This is because we replace the normal readable namespace with an md5 hash. The problem was that `ConvertResourcesCases` is doing a TON of work it doesn't really need to do the second time around. For example checking if it needs to lower case names of items. The second pass really only needs to worry about custom views. In addition to that it was also re-scanning ALL the files again. This commit introduces a new Task `ConvertCustomView`. The sole purpose of this task is to fix up the layout files which contain custom views. It does nothing else. To make this even quicker we modify `ConvertResourcesCases` to emit a mapping file (class-map.txt). This file contains items like MonoDroid.Example.MyLayout;/fullpath/to/file.xml android.support.v7.widget.ActionBarOverlayLayout;/fullpath/to/some/other/file.xml This allows us to know were the files are which contain ANY layout. With this information in conjuction with the `acw_map.txt` file will allow us to do a targeted update. So we go through the `acw_map.txt` values and fix up those files where we have entires in the `class-map.txt`. This reduces the amount of time spent processing files quite a bit. For a Blank Xamarin Forms app from a clean build. 2639 ms ConvertResourcesCases 1 calls 3 ms ConvertCustomView 1 calls Normally the `ConvertResourcesCases` would be called twice and would take a total of 5-6 seconds.
1 parent c2d3681 commit 909b727

File tree

7 files changed

+278
-78
lines changed

7 files changed

+278
-78
lines changed
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright (C) 2018 Microsoft, Inc. All rights reserved.
2+
3+
using System;
4+
using System.Diagnostics;
5+
using System.Collections.Generic;
6+
using System.IO;
7+
using System.Linq;
8+
using System.Xml.Linq;
9+
using Microsoft.Build.Framework;
10+
using Microsoft.Build.Utilities;
11+
using Monodroid;
12+
13+
namespace Xamarin.Android.Tasks {
14+
public class ConvertCustomView : Task {
15+
16+
[Required]
17+
public string CustomViewMapFile { get; set; }
18+
19+
[Required]
20+
public string AcwMapFile { get; set; }
21+
22+
public string ResourceNameCaseMap { get; set; }
23+
24+
public ITaskItem [] ResourceDirectories { get; set; }
25+
26+
public override bool Execute ()
27+
{
28+
var resource_name_case_map = MonoAndroidHelper.LoadResourceCaseMap (ResourceNameCaseMap);
29+
var acw_map = MonoAndroidHelper.LoadAcwMapFile (AcwMapFile);
30+
var customViewMap = MonoAndroidHelper.LoadCustomViewMapFile (BuildEngine4, CustomViewMapFile);
31+
var processed = new HashSet<string> ();
32+
33+
foreach (var kvp in acw_map) {
34+
var key = kvp.Key;
35+
var value = kvp.Value;
36+
if (key == value)
37+
continue;
38+
if (customViewMap.TryGetValue (key, out HashSet<string> resourceFiles)) {
39+
foreach (var file in resourceFiles) {
40+
if (processed.Contains (file))
41+
continue;
42+
if (!File.Exists (file))
43+
continue;
44+
var document = XDocument.Load (file);
45+
var e = document.Root;
46+
bool update = false;
47+
foreach (var elem in AndroidResource.GetElements (e).Prepend (e)) {
48+
update |= TryFixCustomView (elem, acw_map, (t, m) => {
49+
string targetfile = file;
50+
ITaskItem resdir = ResourceDirectories?.FirstOrDefault (x => file.StartsWith (x.ItemSpec)) ?? null;
51+
if (resdir != null && targetfile.StartsWith (resdir.ItemSpec, StringComparison.InvariantCultureIgnoreCase)) {
52+
targetfile = file.Substring (resdir.ItemSpec.Length).TrimStart (Path.DirectorySeparatorChar);
53+
if (resource_name_case_map.TryGetValue (targetfile, out string temp))
54+
targetfile = temp;
55+
targetfile = Path.Combine ("Resources", targetfile);
56+
}
57+
switch (t) {
58+
case TraceLevel.Error:
59+
Log.LogCodedError ("XA1002", file: targetfile, lineNumber: 0, message: m);
60+
break;
61+
case TraceLevel.Warning:
62+
Log.LogCodedWarning ("XA1001", file: targetfile, lineNumber: 0, message: m);
63+
break;
64+
default:
65+
Log.LogDebugMessage (m);
66+
break;
67+
}
68+
});
69+
}
70+
foreach (XAttribute a in AndroidResource.GetAttributes (e)) {
71+
update |= TryFixCustomClassAttribute (a, acw_map);
72+
update |= TryFixFragment (a, acw_map);
73+
}
74+
if (update) {
75+
document.Save (file);
76+
}
77+
processed.Add (file);
78+
}
79+
}
80+
}
81+
82+
return !Log.HasLoggedErrors;
83+
}
84+
85+
static readonly XNamespace res_auto = "http://schemas.android.com/apk/res-auto";
86+
static readonly XNamespace android = "http://schemas.android.com/apk/res/android";
87+
88+
bool TryFixCustomClassAttribute (XAttribute attr, Dictionary<string, string> acwMap)
89+
{
90+
/* Some attributes reference a Java class name.
91+
* try to convert those like for TryFixCustomView
92+
*/
93+
if (attr.Name != (res_auto + "layout_behavior") // For custom CoordinatorLayout behavior
94+
&& (attr.Parent.Name != "transition" || attr.Name.LocalName != "class")) // For custom transitions
95+
return false;
96+
97+
if (!acwMap.TryGetValue (attr.Value, out string mappedValue))
98+
return false;
99+
100+
attr.Value = mappedValue;
101+
return true;
102+
}
103+
104+
bool TryFixFragment (XAttribute attr, Dictionary<string, string> acwMap)
105+
{
106+
// Looks for any:
107+
// <fragment class="My.DotNet.Class"
108+
// <fragment android:name="My.DotNet.Class" ...
109+
// and tries to change it to the ACW name
110+
if (attr.Parent.Name != "fragment")
111+
return false;
112+
113+
if (attr.Name == "class" || attr.Name == android + "name") {
114+
if (acwMap.TryGetValue (attr.Value, out string mappedValue)) {
115+
attr.Value = mappedValue;
116+
117+
return true;
118+
} else if (attr.Value?.Contains (',') ?? false) {
119+
// attr.Value could be an assembly-qualified name that isn't in acw-map.txt;
120+
// see e5b1c92c, https://github.com/xamarin/xamarin-android/issues/1296#issuecomment-365091948
121+
var n = attr.Value.Substring (0, attr.Value.IndexOf (','));
122+
if (acwMap.TryGetValue (n, out mappedValue)) {
123+
attr.Value = mappedValue;
124+
return true;
125+
}
126+
}
127+
}
128+
129+
return false;
130+
}
131+
132+
bool TryFixCustomView (XElement elem, Dictionary<string, string> acwMap, Action<TraceLevel, string> logMessage = null)
133+
{
134+
// Looks for any <My.DotNet.Class ...
135+
// and tries to change it to the ACW name
136+
string name = elem.Name.ToString ();
137+
if (acwMap.TryGetValue (name, out string mappedValue)) {
138+
elem.Name = mappedValue;
139+
return true;
140+
}
141+
if (logMessage == null)
142+
return false;
143+
var matchingKey = acwMap.FirstOrDefault (x => String.Equals (x.Key, name, StringComparison.OrdinalIgnoreCase));
144+
if (matchingKey.Key != null) {
145+
// we have elements with slightly different casing.
146+
// lets issue a error.
147+
logMessage (TraceLevel.Error, $"We found a matching key '{matchingKey.Key}' for '{name}'. But the casing was incorrect. Please correct the casing");
148+
}
149+
return false;
150+
}
151+
}
152+
}

src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,31 @@ public class ConvertResourcesCases : Task
1919
[Required]
2020
public string AcwMapFile { get; set; }
2121

22+
[Required]
23+
public string CustomViewMapFile { get; set; }
24+
2225
public string AndroidConversionFlagFile { get; set; }
2326

2427
public string ResourceNameCaseMap { get; set; }
2528

2629
Dictionary<string,string> resource_name_case_map;
30+
Dictionary<string, HashSet<string>> customViewMap;
2731

2832
public override bool Execute ()
2933
{
30-
Log.LogDebugMessage ("ConvertResourcesCases Task");
31-
Log.LogDebugMessage (" ResourceDirectories: {0}", ResourceDirectories);
32-
Log.LogDebugMessage (" AcwMapFile: {0}", AcwMapFile);
33-
Log.LogDebugMessage (" AndroidConversionFlagFile: {0}", AndroidConversionFlagFile);
34-
Log.LogDebugMessage (" ResourceNameCaseMap: {0}", ResourceNameCaseMap);
35-
3634
resource_name_case_map = MonoAndroidHelper.LoadResourceCaseMap (ResourceNameCaseMap);
3735
var acw_map = MonoAndroidHelper.LoadAcwMapFile (AcwMapFile);
3836

37+
38+
if (CustomViewMapFile != null)
39+
customViewMap = Xamarin.Android.Tasks.MonoAndroidHelper.LoadCustomViewMapFile (BuildEngine4, CustomViewMapFile);
40+
3941
// Look in the resource xml's for capitalized stuff and fix them
4042
FixupResources (acw_map);
4143

44+
if (customViewMap != null)
45+
Xamarin.Android.Tasks.MonoAndroidHelper.SaveCustomViewMapFile (BuildEngine4, CustomViewMapFile, customViewMap);
46+
4247
return true;
4348
}
4449

@@ -80,11 +85,9 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
8085
continue;
8186
}
8287
Log.LogDebugMessage (" Processing: {0} {1} > {2}", file, srcmodifiedDate, lastUpdate);
83-
var tmpdest = Path.GetTempFileName ();
84-
File.Copy (file, tmpdest, overwrite: true);
85-
MonoAndroidHelper.SetWriteable (tmpdest);
88+
MonoAndroidHelper.SetWriteable (file);
8689
try {
87-
bool success = AndroidResource.UpdateXmlResource (resdir, tmpdest, acwMap,
90+
bool success = AndroidResource.UpdateXmlResource (resdir, file, acwMap,
8891
resourcedirectories, (t, m) => {
8992
string targetfile = file;
9093
if (targetfile.StartsWith (resdir, StringComparison.InvariantCultureIgnoreCase)) {
@@ -104,7 +107,14 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
104107
Log.LogDebugMessage (m);
105108
break;
106109
}
107-
});
110+
}, registerCustomView : (e, filename) => {
111+
if (customViewMap == null)
112+
return;
113+
HashSet<string> set;
114+
if (!customViewMap.TryGetValue (e, out set))
115+
customViewMap.Add (e, set = new HashSet<string> ());
116+
set.Add (filename);
117+
});
108118
if (!success) {
109119
//If we failed to write the file, a warning is logged, we should skip to the next file
110120
continue;
@@ -115,11 +125,11 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
115125
// doesn't support those type of BOM (it really wants the document to start
116126
// with "<?"). Since there is no way to plug into the file saving mechanism in X.S
117127
// we strip those here and point the designer to use resources from obj/
118-
MonoAndroidHelper.CleanBOM (tmpdest);
128+
MonoAndroidHelper.CleanBOM (file);
129+
119130

120-
MonoAndroidHelper.CopyIfChanged (tmpdest, file);
121131
} finally {
122-
File.Delete (tmpdest);
132+
123133
}
124134
}
125135
}

src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/ConvertResourcesCasesTests.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ public void CheckClassIsReplacedWithMd5 ()
2525
<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'>
2626
<ClassLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
2727
<classlibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
28+
<fragment android:type='classlibrary1.CustomView' />
29+
<fragment android:type='ClassLibrary1.CustomView' />
2830
</LinearLayout>
2931
");
3032
var errors = new List<BuildErrorEventArgs> ();
@@ -36,11 +38,21 @@ public void CheckClassIsReplacedWithMd5 ()
3638
new TaskItem (resPath),
3739
};
3840
task.AcwMapFile = Path.Combine (path, "acwmap.txt");
41+
task.CustomViewMapFile = Path.Combine (path, "classmap.txt");
3942
File.WriteAllLines (task.AcwMapFile, new string [] {
4043
"ClassLibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
4144
"classlibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
4245
});
4346
Assert.IsTrue (task.Execute (), "Task should have executed successfully");
47+
var custom = new ConvertCustomView () {
48+
BuildEngine = engine,
49+
CustomViewMapFile = task.CustomViewMapFile,
50+
AcwMapFile = task.AcwMapFile,
51+
ResourceDirectories = new ITaskItem [] {
52+
new TaskItem (resPath),
53+
},
54+
};
55+
Assert.IsTrue (custom.Execute (), "Task should have executed successfully");
4456
var output = File.ReadAllText (Path.Combine (resPath, "layout", "main.xml"));
4557
StringAssert.Contains ("md5d6f7135293df7527c983d45d07471c5e.CustomTextView", output, "md5d6f7135293df7527c983d45d07471c5e.CustomTextView should exist in the main.xml");
4658
StringAssert.DoesNotContain ("ClassLibrary1.CustomView", output, "ClassLibrary1.CustomView should have been replaced.");
@@ -59,6 +71,8 @@ public void CheckClassIsNotReplacedWithMd5 ()
5971
<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'>
6072
<ClassLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
6173
<classLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
74+
<fragment android:type='classLibrary1.CustomView' />
75+
<fragment android:type='ClassLibrary1.CustomView' />
6276
</LinearLayout>
6377
");
6478
var errors = new List<BuildErrorEventArgs> ();
@@ -70,17 +84,28 @@ public void CheckClassIsNotReplacedWithMd5 ()
7084
new TaskItem (resPath),
7185
};
7286
task.AcwMapFile = Path.Combine (path, "acwmap.txt");
87+
task.CustomViewMapFile = Path.Combine (path, "classmap.txt");
7388
File.WriteAllLines (task.AcwMapFile, new string [] {
7489
"ClassLibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
7590
"classlibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
7691
});
7792
Assert.IsTrue (task.Execute (), "Task should have executed successfully");
93+
var custom = new ConvertCustomView () {
94+
BuildEngine = engine,
95+
CustomViewMapFile = task.CustomViewMapFile,
96+
AcwMapFile = task.AcwMapFile,
97+
ResourceDirectories = new ITaskItem [] {
98+
new TaskItem (resPath),
99+
},
100+
};
101+
Assert.IsFalse (custom.Execute (), "Task should have executed successfully");
78102
var output = File.ReadAllText (Path.Combine (resPath, "layout", "main.xml"));
79103
StringAssert.Contains ("md5d6f7135293df7527c983d45d07471c5e.CustomTextView", output, "md5d6f7135293df7527c983d45d07471c5e.CustomTextView should exist in the main.xml");
80104
StringAssert.DoesNotContain ("ClassLibrary1.CustomView", output, "ClassLibrary1.CustomView should have been replaced.");
81105
StringAssert.Contains ("classLibrary1.CustomView", output, "classLibrary1.CustomView should have been replaced.");
82-
Assert.AreEqual (1, errors.Count, "One Error should have been raised.");
106+
Assert.AreEqual (2, errors.Count, "One Error should have been raised.");
83107
Assert.AreEqual ("XA1002", errors [0].Code, "XA1002 should have been raised.");
108+
Assert.AreEqual ("XA1002", errors [1].Code, "XA1002 should have been raised.");
84109
Directory.Delete (path, recursive: true);
85110
}
86111
}

0 commit comments

Comments
 (0)