-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathGenerateResourceDesigner.cs
More file actions
274 lines (216 loc) · 9.52 KB
/
GenerateResourceDesigner.cs
File metadata and controls
274 lines (216 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright (C) 2011 Xamarin, Inc. All rights reserved.
#nullable enable
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Android.Build.Tasks;
namespace Xamarin.Android.Tasks
{
public class GenerateResourceDesigner : AndroidTask
{
public override string TaskPrefix => "GRD";
[Required]
public string NetResgenOutputFile { get; set; } = "";
public string? DesignTimeOutputFile { get; set; }
public string? JavaResgenInputFile { get; set; }
public string? RTxtFile { get; set; }
public string? Namespace { get; set; }
[Required]
public string ProjectDir { get; set; } = "";
[Required]
public ITaskItem[] Resources { get; set; } = [];
[Required]
public string ResourceDirectory { get; set; } = "";
public ITaskItem[]? AdditionalResourceDirectories { get; set; }
[Required]
public bool IsApplication { get; set; }
public ITaskItem[]? References { get; set; }
[Required]
public bool UseManagedResourceGenerator { get; set; }
[Required]
public bool DesignTimeBuild { get; set; }
[Required]
public string JavaPlatformJarPath { get; set; } = "";
public string? ResourceFlagFile { get; set; }
public string? CaseMapFile { get; set; }
private Dictionary<string, string> resource_fixup = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
public override bool RunTask ()
{
// In Xamarin Studio, if the project name isn't a valid C# identifier
// then $(RootNamespace) is not set, and the generated Activity is
// placed into the "Application" namespace. VS just munges the project
// name to be a valid C# identifier.
// Use "Application" as the default namespace name to work with XS.
Namespace ??= "Application";
string namespaceName = Namespace; // Local variable for null-safety
if (!File.Exists (JavaResgenInputFile) && !UseManagedResourceGenerator)
return true;
// ResourceDirectory may be a relative path, and
// we need to compare it to absolute paths
ResourceDirectory = Path.GetFullPath (ResourceDirectory);
var javaPlatformDirectory = Path.GetDirectoryName (JavaPlatformJarPath);
resource_fixup = MonoAndroidHelper.LoadMapFile (BuildEngine4, Path.GetFullPath (CaseMapFile), StringComparer.OrdinalIgnoreCase);
// Parse out the resources from the R.java file
CodeTypeDeclaration resources;
if (UseManagedResourceGenerator) {
var parser = new ManagedResourceParser (Log) { JavaPlatformDirectory = javaPlatformDirectory, ResourceFlagFile = ResourceFlagFile };
resources = parser.Parse (ResourceDirectory, RTxtFile ?? string.Empty, AdditionalResourceDirectories?.Select (x => x.ItemSpec), IsApplication, resource_fixup);
} else {
if (JavaResgenInputFile == null) {
throw new ArgumentNullException (nameof (JavaResgenInputFile));
}
var parser = new JavaResourceParser (Log);
resources = parser.Parse (JavaResgenInputFile, IsApplication, resource_fixup);
}
var extension = Path.GetExtension (NetResgenOutputFile);
var language = string.Compare (extension, ".fs", StringComparison.OrdinalIgnoreCase) == 0 ? "F#" : CodeDomProvider.GetLanguageFromExtension (extension);
bool isVB = string.Equals (extension, ".vb", StringComparison.OrdinalIgnoreCase);
bool isFSharp = string.Equals (language, "F#", StringComparison.OrdinalIgnoreCase);
bool isCSharp = string.Equals (language, "C#", StringComparison.OrdinalIgnoreCase);
if (isFSharp) {
language = "C#";
isCSharp = true;
NetResgenOutputFile = Path.ChangeExtension (NetResgenOutputFile, ".cs");
}
// Let VB put this in the default namespace
if (isVB)
Namespace = "";
List<string> aliases = new List<string> ();
// Create static resource overwrite methods for each Resource class in libraries.
if (IsApplication && References != null && References.Length > 0) {
var assemblies = new List<ITaskItem> (References.Length);
foreach (var assembly in References) {
var assemblyPath = assembly.ItemSpec;
var fileName = Path.GetFileName (assemblyPath);
if (MonoAndroidHelper.IsFrameworkAssembly (fileName)) {
Log.LogDebugMessage ($"Skipping framework assembly '{fileName}'.");
continue;
}
if (!File.Exists (assemblyPath)) {
Log.LogDebugMessage ($"Skipping non-existent dependency '{assemblyPath}'.");
continue;
}
ITaskItem item = new TaskItem (assemblyPath);
assembly.CopyMetadataTo (item);
assemblies.Add (item);
string aliasMetaData = assembly.GetMetadata ("Aliases");
if (!aliasMetaData.IsNullOrEmpty ()) {
foreach (var alias in aliasMetaData.Split (new [] {','}, StringSplitOptions.RemoveEmptyEntries)) {
string aliasName = alias.Trim ();
// don't emit an `extern alias global` as it is implicitly done.
if (string.Compare ("global", aliasName, StringComparison.Ordinal) == 0)
continue;
aliases.Add (aliasName);
// only add the first alias for each reference.
break;
}
}
Log.LogDebugMessage ("Scan assembly {0} for resource generator", fileName);
}
new ResourceDesignerImportGenerator (namespaceName, resources, Log)
.CreateImportMethods (assemblies);
}
AdjustConstructor (resources);
foreach (var member in resources.Members)
if (member is CodeTypeDeclaration)
AdjustConstructor ((CodeTypeDeclaration) member);
// Write out our Resources.Designer.cs file
WriteFile (NetResgenOutputFile, resources, language, isCSharp, aliases, namespaceName);
// During a regular build, write the designtime/Resource.designer.cs file as well
if (!DesignTimeOutputFile.IsNullOrEmpty () && Files.CopyIfChanged (NetResgenOutputFile, DesignTimeOutputFile)) {
Log.LogDebugMessage ($"Writing to: {DesignTimeOutputFile}");
}
return !Log.HasLoggedErrors;
}
// Remove private constructor in F#.
// Add static constructor. (but ignored in F#)
void AdjustConstructor (CodeTypeDeclaration type)
{
var staticCtor = new CodeTypeConstructor () { Attributes = MemberAttributes.Static };
staticCtor.Statements.Add (
new CodeExpressionStatement (
new CodeMethodInvokeExpression (
new CodeTypeReferenceExpression (
new CodeTypeReference (
"Android.Runtime.ResourceIdManager",
CodeTypeReferenceOptions.GlobalReference)),
"UpdateIdValues")));
type.Members.Add (staticCtor);
}
private void WriteFile (string file, CodeTypeDeclaration resources, string language, bool isCSharp, IEnumerable<string> aliases, string namespaceName)
{
CodeDomProvider provider = CodeDomProvider.CreateProvider (language);
using (var o = MemoryStreamPool.Shared.CreateStreamWriter ()) {
var options = new CodeGeneratorOptions () {
BracingStyle = "C",
IndentString = "\t",
};
var ns = namespaceName.IsNullOrEmpty ()
? new CodeNamespace ()
: new CodeNamespace (namespaceName);
if (resources != null)
ns.Types.Add (resources);
var unit = new CodeCompileUnit ();
unit.Namespaces.Add (ns);
var resgenatt = new CodeAttributeDeclaration (new CodeTypeReference ("Android.Runtime.ResourceDesignerAttribute", CodeTypeReferenceOptions.GlobalReference));
resgenatt.Arguments.Add (new CodeAttributeArgument (new CodePrimitiveExpression (namespaceName.Length > 0 ? namespaceName + ".Resource" : "Resource")));
resgenatt.Arguments.Add (new CodeAttributeArgument ("IsApplication", new CodePrimitiveExpression (IsApplication)));
unit.AssemblyCustomAttributes.Add (resgenatt);
// Add Pragma to disable warnings about no Xml documentation
if (isCSharp) {
foreach (var alias in aliases)
provider.GenerateCodeFromStatement (new CodeSnippetStatement ($"extern alias {alias};"), o, options);
provider.GenerateCodeFromCompileUnit (new CodeSnippetCompileUnit ("#pragma warning disable 1591"), o, options);
}
provider.CreateGenerator (o).GenerateCodeFromCompileUnit (unit, o, options);
// Add Pragma to re-enable warnings about no Xml documentation
if (isCSharp)
provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning restore 1591"), o, options);
o.Flush ();
if (Files.CopyIfStreamChanged (o.BaseStream, file)) {
Log.LogDebugMessage ($"Writing to: {file}");
} else {
Log.LogDebugMessage ($"Up to date: {file}");
}
}
}
private void AddRename (string android, string user)
{
var from = android;
var to = user;
if (from.Contains ('.'))
from = from.Substring (0, from.LastIndexOf ('.'));
if (to.Contains ('.'))
to = to.Substring (0, to.LastIndexOf ('.'));
from = NormalizeAlternative (from);
to = NormalizeAlternative (to);
string curTo;
if (resource_fixup.TryGetValue (from, out curTo)) {
if (string.Compare (to, curTo, StringComparison.OrdinalIgnoreCase) != 0) {
var ext = Path.GetExtension (android);
var dir = Path.GetDirectoryName (user);
Log.LogDebugMessage ("Resource target names differ; got '{0}', expected '{1}'.",
Path.Combine (dir, Path.GetFileName (to) + ext),
Path.Combine (dir, Path.GetFileName (curTo) + ext));
}
return;
}
resource_fixup.Add (from, to);
}
static string NormalizeAlternative (string value)
{
int s = value.IndexOfAny (new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
if (s < 0)
return value;
int a = value.IndexOf ('-');
return
ResourceParser.GetNestedTypeName (value.Substring (0, (a < 0 || a >= s) ? s : a)).ToLowerInvariant () +
value.Substring (s);
}
}
}