Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
152 changes: 152 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Tasks/ConvertCustomView.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright (C) 2018 Microsoft, Inc. All rights reserved.

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Monodroid;

namespace Xamarin.Android.Tasks {
public class ConvertCustomView : Task {

[Required]
public string CustomViewMapFile { get; set; }

[Required]
public string AcwMapFile { get; set; }

public string ResourceNameCaseMap { get; set; }

public ITaskItem [] ResourceDirectories { get; set; }

public override bool Execute ()
{
var resource_name_case_map = MonoAndroidHelper.LoadResourceCaseMap (ResourceNameCaseMap);
var acw_map = MonoAndroidHelper.LoadAcwMapFile (AcwMapFile);
var customViewMap = MonoAndroidHelper.LoadCustomViewMapFile (BuildEngine4, CustomViewMapFile);
var processed = new HashSet<string> ();

foreach (var kvp in acw_map) {
var key = kvp.Key;
var value = kvp.Value;
if (key == value)
continue;
if (customViewMap.TryGetValue (key, out HashSet<string> resourceFiles)) {
foreach (var file in resourceFiles) {
if (processed.Contains (file))
continue;
if (!File.Exists (file))
continue;
var document = XDocument.Load (file);
var e = document.Root;
bool update = false;
foreach (var elem in AndroidResource.GetElements (e).Prepend (e)) {
update |= TryFixCustomView (elem, acw_map, (t, m) => {
string targetfile = file;
ITaskItem resdir = ResourceDirectories?.FirstOrDefault (x => file.StartsWith (x.ItemSpec)) ?? null;
if (resdir != null && targetfile.StartsWith (resdir.ItemSpec, StringComparison.InvariantCultureIgnoreCase)) {
targetfile = file.Substring (resdir.ItemSpec.Length).TrimStart (Path.DirectorySeparatorChar);
if (resource_name_case_map.TryGetValue (targetfile, out string temp))
targetfile = temp;
targetfile = Path.Combine ("Resources", targetfile);
}
switch (t) {
case TraceLevel.Error:
Log.LogCodedError ("XA1002", file: targetfile, lineNumber: 0, message: m);
break;
case TraceLevel.Warning:
Log.LogCodedWarning ("XA1001", file: targetfile, lineNumber: 0, message: m);
break;
default:
Log.LogDebugMessage (m);
break;
}
});
}
foreach (XAttribute a in AndroidResource.GetAttributes (e)) {
update |= TryFixCustomClassAttribute (a, acw_map);
update |= TryFixFragment (a, acw_map);
}
if (update) {
document.Save (file);
}
processed.Add (file);
}
}
}

return !Log.HasLoggedErrors;
}

static readonly XNamespace res_auto = "http://schemas.android.com/apk/res-auto";
static readonly XNamespace android = "http://schemas.android.com/apk/res/android";

bool TryFixCustomClassAttribute (XAttribute attr, Dictionary<string, string> acwMap)
{
/* Some attributes reference a Java class name.
* try to convert those like for TryFixCustomView
*/
if (attr.Name != (res_auto + "layout_behavior") // For custom CoordinatorLayout behavior
&& (attr.Parent.Name != "transition" || attr.Name.LocalName != "class")) // For custom transitions
return false;

if (!acwMap.TryGetValue (attr.Value, out string mappedValue))
return false;

attr.Value = mappedValue;
return true;
}

bool TryFixFragment (XAttribute attr, Dictionary<string, string> acwMap)
{
// Looks for any:
// <fragment class="My.DotNet.Class"
// <fragment android:name="My.DotNet.Class" ...
// and tries to change it to the ACW name
if (attr.Parent.Name != "fragment")
return false;

if (attr.Name == "class" || attr.Name == android + "name") {
if (acwMap.TryGetValue (attr.Value, out string mappedValue)) {
attr.Value = mappedValue;

return true;
} else if (attr.Value?.Contains (',') ?? false) {
// attr.Value could be an assembly-qualified name that isn't in acw-map.txt;
// see e5b1c92c, https://github.com/xamarin/xamarin-android/issues/1296#issuecomment-365091948
var n = attr.Value.Substring (0, attr.Value.IndexOf (','));
if (acwMap.TryGetValue (n, out mappedValue)) {
attr.Value = mappedValue;
return true;
}
}
}

return false;
}

bool TryFixCustomView (XElement elem, Dictionary<string, string> acwMap, Action<TraceLevel, string> logMessage = null)
{
// Looks for any <My.DotNet.Class ...
// and tries to change it to the ACW name
string name = elem.Name.ToString ();
if (acwMap.TryGetValue (name, out string mappedValue)) {
elem.Name = mappedValue;
return true;
}
if (logMessage == null)
return false;
var matchingKey = acwMap.FirstOrDefault (x => String.Equals (x.Key, name, StringComparison.OrdinalIgnoreCase));
if (matchingKey.Key != null) {
// we have elements with slightly different casing.
// lets issue a error.
logMessage (TraceLevel.Error, $"We found a matching key '{matchingKey.Key}' for '{name}'. But the casing was incorrect. Please correct the casing");
}
return false;
}
}
}
38 changes: 24 additions & 14 deletions src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,31 @@ public class ConvertResourcesCases : Task
[Required]
public string AcwMapFile { get; set; }

[Required]
public string CustomViewMapFile { get; set; }

public string AndroidConversionFlagFile { get; set; }

public string ResourceNameCaseMap { get; set; }

Dictionary<string,string> resource_name_case_map;
Dictionary<string, HashSet<string>> customViewMap;

public override bool Execute ()
{
Log.LogDebugMessage ("ConvertResourcesCases Task");
Log.LogDebugMessage (" ResourceDirectories: {0}", ResourceDirectories);
Log.LogDebugMessage (" AcwMapFile: {0}", AcwMapFile);
Log.LogDebugMessage (" AndroidConversionFlagFile: {0}", AndroidConversionFlagFile);
Log.LogDebugMessage (" ResourceNameCaseMap: {0}", ResourceNameCaseMap);

resource_name_case_map = MonoAndroidHelper.LoadResourceCaseMap (ResourceNameCaseMap);
var acw_map = MonoAndroidHelper.LoadAcwMapFile (AcwMapFile);


if (CustomViewMapFile != null)
customViewMap = Xamarin.Android.Tasks.MonoAndroidHelper.LoadCustomViewMapFile (BuildEngine4, CustomViewMapFile);

// Look in the resource xml's for capitalized stuff and fix them
FixupResources (acw_map);

if (customViewMap != null)
Xamarin.Android.Tasks.MonoAndroidHelper.SaveCustomViewMapFile (BuildEngine4, CustomViewMapFile, customViewMap);

return true;
}

Expand Down Expand Up @@ -80,11 +85,9 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
continue;
}
Log.LogDebugMessage (" Processing: {0} {1} > {2}", file, srcmodifiedDate, lastUpdate);
var tmpdest = Path.GetTempFileName ();
File.Copy (file, tmpdest, overwrite: true);
MonoAndroidHelper.SetWriteable (tmpdest);
MonoAndroidHelper.SetWriteable (file);
try {
bool success = AndroidResource.UpdateXmlResource (resdir, tmpdest, acwMap,
bool success = AndroidResource.UpdateXmlResource (resdir, file, acwMap,
resourcedirectories, (t, m) => {
string targetfile = file;
if (targetfile.StartsWith (resdir, StringComparison.InvariantCultureIgnoreCase)) {
Expand All @@ -104,7 +107,14 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
Log.LogDebugMessage (m);
break;
}
});
}, registerCustomView : (e, filename) => {
if (customViewMap == null)
return;
HashSet<string> set;
if (!customViewMap.TryGetValue (e, out set))
customViewMap.Add (e, set = new HashSet<string> ());
set.Add (filename);
});
if (!success) {
//If we failed to write the file, a warning is logged, we should skip to the next file
continue;
Expand All @@ -115,11 +125,11 @@ void FixupResources (ITaskItem item, Dictionary<string, string> acwMap)
// doesn't support those type of BOM (it really wants the document to start
// with "<?"). Since there is no way to plug into the file saving mechanism in X.S
// we strip those here and point the designer to use resources from obj/
MonoAndroidHelper.CleanBOM (tmpdest);
MonoAndroidHelper.CleanBOM (file);


MonoAndroidHelper.CopyIfChanged (tmpdest, file);
} finally {
File.Delete (tmpdest);

}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public void CheckClassIsReplacedWithMd5 ()
<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'>
<ClassLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
<classlibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
<fragment android:name='classlibrary1.CustomView' />
<fragment class='ClassLibrary1.CustomView' />
</LinearLayout>
");
var errors = new List<BuildErrorEventArgs> ();
Expand All @@ -36,11 +38,21 @@ public void CheckClassIsReplacedWithMd5 ()
new TaskItem (resPath),
};
task.AcwMapFile = Path.Combine (path, "acwmap.txt");
task.CustomViewMapFile = Path.Combine (path, "classmap.txt");
File.WriteAllLines (task.AcwMapFile, new string [] {
"ClassLibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
"classlibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
});
Assert.IsTrue (task.Execute (), "Task should have executed successfully");
var custom = new ConvertCustomView () {
BuildEngine = engine,
CustomViewMapFile = task.CustomViewMapFile,
AcwMapFile = task.AcwMapFile,
ResourceDirectories = new ITaskItem [] {
new TaskItem (resPath),
},
};
Assert.IsTrue (custom.Execute (), "Task should have executed successfully");
var output = File.ReadAllText (Path.Combine (resPath, "layout", "main.xml"));
StringAssert.Contains ("md5d6f7135293df7527c983d45d07471c5e.CustomTextView", output, "md5d6f7135293df7527c983d45d07471c5e.CustomTextView should exist in the main.xml");
StringAssert.DoesNotContain ("ClassLibrary1.CustomView", output, "ClassLibrary1.CustomView should have been replaced.");
Expand All @@ -59,6 +71,8 @@ public void CheckClassIsNotReplacedWithMd5 ()
<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'>
<ClassLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
<classLibrary1.CustomView xmlns:android='http://schemas.android.com/apk/res/android' />
<fragment android:name='classLibrary1.CustomView' />
<fragment class='ClassLibrary1.CustomView' />
</LinearLayout>
");
var errors = new List<BuildErrorEventArgs> ();
Expand All @@ -70,17 +84,29 @@ public void CheckClassIsNotReplacedWithMd5 ()
new TaskItem (resPath),
};
task.AcwMapFile = Path.Combine (path, "acwmap.txt");
task.CustomViewMapFile = Path.Combine (path, "classmap.txt");
File.WriteAllLines (task.AcwMapFile, new string [] {
"ClassLibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
"classlibrary1.CustomView;md5d6f7135293df7527c983d45d07471c5e.CustomTextView",
});
Assert.IsTrue (task.Execute (), "Task should have executed successfully");
var custom = new ConvertCustomView () {
BuildEngine = engine,
CustomViewMapFile = task.CustomViewMapFile,
AcwMapFile = task.AcwMapFile,
ResourceDirectories = new ITaskItem [] {
new TaskItem (resPath),
},
};
Assert.IsFalse (custom.Execute (), "Task should have executed successfully");
var output = File.ReadAllText (Path.Combine (resPath, "layout", "main.xml"));
StringAssert.Contains ("md5d6f7135293df7527c983d45d07471c5e.CustomTextView", output, "md5d6f7135293df7527c983d45d07471c5e.CustomTextView should exist in the main.xml");
StringAssert.DoesNotContain ("ClassLibrary1.CustomView", output, "ClassLibrary1.CustomView should have been replaced.");
StringAssert.Contains ("classLibrary1.CustomView", output, "classLibrary1.CustomView should have been replaced.");
Assert.AreEqual (1, errors.Count, "One Error should have been raised.");
Assert.AreEqual ("XA1002", errors [0].Code, "XA1002 should have been raised.");
var expected = Path.Combine ("Resources", "layout", "main.xml");
Assert.AreEqual (expected, errors [0].File, $"Error should have the \"{expected}\" path. But contained \"{errors [0].File}\"");
Directory.Delete (path, recursive: true);
}
}
Expand Down
Loading