-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathGenerateLayoutBindings.cs
More file actions
383 lines (316 loc) · 12.6 KB
/
GenerateLayoutBindings.cs
File metadata and controls
383 lines (316 loc) · 12.6 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Android.Build.Tasks;
namespace Xamarin.Android.Tasks
{
// TODO: add doc comments to the generated properties
//
public partial class GenerateLayoutBindings : AsyncTask
{
public override string TaskPrefix => "GLB";
sealed class PartialClass
{
public string? Name { get; set; }
public string? Namespace { get; set; }
public string? OutputFilePath { get; set; }
public StreamWriter? Writer { get; set; }
public FileStream? Stream { get; set; }
public BindingGenerator.State? State { get; set; }
}
sealed class LayoutGroup
{
public List<ITaskItem> Items { get; set; } = [];
public List<PartialClass> Classes { get; set; } = [];
public HashSet<string> ClassNames { get; set; } = new HashSet<string>(StringComparer.Ordinal);
}
internal sealed class BindingGeneratorLanguage
{
public readonly string Name;
public readonly string Extension;
public Func<BindingGenerator> Creator { get; }
public BindingGeneratorLanguage (string name, string extension, Func<BindingGenerator> creator)
{
if (name.IsNullOrEmpty ())
throw new ArgumentException (nameof (name));
if (extension.IsNullOrEmpty ())
throw new ArgumentException (nameof (extension));
Creator = creator ?? throw new ArgumentNullException (nameof (creator));
Name = name;
Extension = extension;
}
}
internal static readonly BindingGeneratorLanguage DefaultOutputGenerator = new BindingGeneratorLanguage ("C#", ".cs", () => new CSharpBindingGenerator ());
internal static readonly Dictionary <string, BindingGeneratorLanguage> KnownBindingGenerators = new Dictionary <string, BindingGeneratorLanguage> (StringComparer.OrdinalIgnoreCase) {
{"C#", DefaultOutputGenerator},
};
public string? OutputLanguage { get; set; }
[Required]
public string MonoAndroidCodeBehindDir { get; set; } = "";
[Required]
public string AndroidFragmentType { get; set; } = "";
public string? AppNamespace { get; set; }
[Required]
public ITaskItem [] ResourceFiles { get; set; } = [];
public ITaskItem []? PartialClassFiles { get; set; }
[Output]
public ITaskItem []? GeneratedFiles { get; set; }
BindingGenerator? GetBindingGenerator (string language)
{
BindingGeneratorLanguage? gen;
if (!KnownBindingGenerators.TryGetValue (language, out gen) || gen == null)
return null;
return gen.Creator ();
}
public async override System.Threading.Tasks.Task RunTaskAsync ()
{
if (OutputLanguage.IsNullOrWhiteSpace ())
OutputLanguage = DefaultOutputGenerator.Name;
BindingGenerator? generator = GetBindingGenerator (OutputLanguage);
if (generator == null) {
LogMessage ($"Unknown binding output language '{OutputLanguage}', will use {DefaultOutputGenerator.Name} instead");
generator = DefaultOutputGenerator.Creator ();
}
if (generator == null) {
// Should "never" happen
LogCodedError ("XA4219", Properties.Resources.XA4219, OutputLanguage, DefaultOutputGenerator.Name);
return;
}
generator.SetCodeBehindDir (MonoAndroidCodeBehindDir);
LogDebugMessage ($"Generating {generator.LanguageName} binding sources");
var layoutGroups = new Dictionary <string, LayoutGroup> (StringComparer.Ordinal);
string layoutGroupName;
LayoutGroup group;
foreach (ITaskItem item in ResourceFiles) {
if (item == null)
continue;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.LayoutGroupMetadata, out layoutGroupName))
return;
if (!layoutGroups.TryGetValue (layoutGroupName, out group) || group == null) {
group = new LayoutGroup ();
layoutGroups [layoutGroupName] = group;
}
group.Items.Add (item);
}
if (PartialClassFiles != null && PartialClassFiles.Length > 0) {
foreach (ITaskItem item in PartialClassFiles) {
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.LayoutGroupMetadata, out layoutGroupName))
return;
if (!layoutGroups.TryGetValue (layoutGroupName, out group) || group == null) {
LogCodedError ("XA4220", Properties.Resources.XA4220, item.ItemSpec, layoutGroupName);
return;
}
string partialClassName;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.PartialCodeBehindClassNameMetadata, out partialClassName))
return;
string outputFileName;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.LayoutPartialClassFileNameMetadata, out outputFileName))
return;
if (group.ClassNames.Contains (partialClassName))
continue;
string shortName;
string? namespaceName;
int idx = partialClassName.LastIndexOf ('.');
if (idx >= 0) {
shortName = partialClassName.Substring (idx + 1);
namespaceName = partialClassName.Substring (0, idx);
} else {
shortName = partialClassName;
namespaceName = null;
}
group.Classes.Add (new PartialClass {
Name = shortName,
Namespace = namespaceName,
OutputFilePath = Path.Combine (MonoAndroidCodeBehindDir, outputFileName)
});
group.ClassNames.Add (partialClassName);
}
}
IEnumerable<string> generatedFilePaths;
if (ResourceFiles.Length >= CalculateLayoutCodeBehind.ParallelGenerationThreshold) {
// NOTE: Update the tests in $TOP_DIR/tests/CodeBehind/UnitTests/BuildTests.cs if this message
// is changed!
LogDebugMessage ($"Generating binding code in parallel (threshold of {CalculateLayoutCodeBehind.ParallelGenerationThreshold} layouts met)");
var fileSet = new ConcurrentBag <string> ();
await this.WhenAll (layoutGroups, kvp => GenerateSourceForLayoutGroup (generator, kvp.Value, rpath => fileSet.Add (rpath)));
generatedFilePaths = fileSet;
} else {
var fileSet = new List<string> ();
foreach (var kvp in layoutGroups)
GenerateSourceForLayoutGroup (generator, kvp.Value, rpath => fileSet.Add (rpath));
generatedFilePaths = fileSet;
}
GeneratedFiles = generatedFilePaths.Where (gfp => !gfp.IsNullOrEmpty ()).Select (gfp => new TaskItem (gfp)).ToArray ();
if (GeneratedFiles.Length == 0)
LogCodedWarning ("XA4221", Properties.Resources.XA4221);
LogDebugTaskItems (" GeneratedFiles:", GeneratedFiles);
}
void GenerateSourceForLayoutGroup (BindingGenerator generator, LayoutGroup group, Action <string> pathAdder)
{
List<ITaskItem> resourceItems = group.Items;
if (resourceItems.Count == 0)
return;
ITaskItem? item = resourceItems.FirstOrDefault ();
if (item == null)
return;
string collectionKey;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.WidgetCollectionKeyMetadata, out collectionKey))
return;
ICollection<LayoutWidget>? widgets = BuildEngine4.GetRegisteredTaskObjectAssemblyLocal<ICollection<LayoutWidget>> (ProjectSpecificTaskObjectKey (collectionKey), RegisteredTaskObjectLifetime.Build);
if (widgets is null || widgets.Count == 0) {
string inputPaths = String.Join ("; ", resourceItems.Select (i => i.ItemSpec));
LogCodedWarning ("XA4222", Properties.Resources.XA4222, inputPaths);
return;
}
string outputFileName;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.LayoutBindingFileNameMetadata, out outputFileName))
return;
string fullClassName;
if (!GetRequiredMetadata (item, CalculateLayoutCodeBehind.ClassNameMetadata, out fullClassName))
return;
string outputFilePath = Path.Combine (MonoAndroidCodeBehindDir, outputFileName);
string classNamespace;
string className;
int idx = fullClassName.LastIndexOf ('.');
if (idx < 0) {
classNamespace = String.Empty;
className = fullClassName;
} else {
bool fail = false;
classNamespace = fullClassName.Substring (0, idx);
if (classNamespace.IsNullOrEmpty ()) {
LogCodedError ("XA4223", Properties.Resources.XA4223, fullClassName);
fail = true;
}
className = fullClassName.Substring (idx + 1);
if (className.IsNullOrEmpty ()) {
LogCodedError ("XA4224", Properties.Resources.XA4224, fullClassName);
fail = true;
}
if (fail)
return;
}
if (!GenerateSource (generator, outputFilePath, widgets!, classNamespace, className, group.Classes))
return;
pathAdder (outputFilePath);
}
bool GenerateSource (BindingGenerator generator, string outputFilePath, ICollection <LayoutWidget> widgets, string classNamespace, string className, List<PartialClass>? partialClasses)
{
bool result = false;
var tempFile = Path.GetTempFileName ();
try {
if (partialClasses != null && partialClasses.Count > 0) {
foreach (var pc in partialClasses) {
if (pc == null)
continue;
pc.Stream = File.Open (pc.OutputFilePath!, FileMode.Create);
pc.Writer = new StreamWriter (pc.Stream, Encoding.UTF8);
}
}
using (var fs = File.Open (tempFile, FileMode.Create)) {
using (var sw = new StreamWriter (fs, Encoding.UTF8)) {
result = GenerateSource (sw, generator, widgets, classNamespace, className, partialClasses);
}
}
if (result)
Files.CopyIfChanged (tempFile, outputFilePath);
} finally {
if (File.Exists (tempFile))
File.Delete (tempFile);
if (partialClasses != null && partialClasses.Count > 0) {
foreach (var pc in partialClasses) {
if (pc == null)
continue;
if (pc.Writer != null) {
pc.Writer.Close ();
pc.Writer.Dispose ();
}
if (pc.Stream == null)
continue;
pc.Stream.Close ();
pc.Stream.Dispose ();
}
}
}
return result;
}
bool GenerateSource (StreamWriter writer, BindingGenerator generator, ICollection <LayoutWidget> widgets, string classNamespace, string className, List<PartialClass>? partialClasses)
{
bool havePartialClasses = partialClasses != null && partialClasses.Count > 0;
string ns = AppNamespace == null ? String.Empty : $"{AppNamespace}.";
if (havePartialClasses) {
string fullBindingClassName = $"{classNamespace}.{className}";
WriteToPartialClasses (pc => pc.State = generator.BeginPartialClassFile (pc.Writer!, fullBindingClassName, pc.Namespace!, pc.Name!, AndroidFragmentType));
}
var state = generator.BeginBindingFile (writer, $"global::{ns}Resource.Layout.{className}", classNamespace, className, AndroidFragmentType);
foreach (LayoutWidget widget in widgets) {
DetermineWidgetType (widget, widget.Type == null);
if (widget.Type == null) {
widget.TypeFixups = null; // Not needed - we'll use decayed type
string? decayedType = null;
switch (widget.WidgetType) {
case LayoutWidgetType.View:
decayedType = "global::Android.Views.View";
break;
case LayoutWidgetType.Fragment:
decayedType = $"global::{AndroidFragmentType}";
break;
case LayoutWidgetType.Mixed:
decayedType = "object";
break;
default:
throw new InvalidOperationException ($"Widget {widget.Name} is of unknown type {widget.WidgetType}");
}
widget.Type = decayedType;
LogCodedWarning ("XA4225", Properties.Resources.XA4225, widget.Name ?? "", className, decayedType ?? "");
}
if (widget.Type.IsNullOrWhiteSpace ())
throw new InvalidOperationException ($"Widget {widget.Name} does not have a type");
generator.WriteBindingProperty (state, widget, ns);
WriteToPartialClasses (pc => generator.WritePartialClassProperty (pc.State!, widget));
}
generator.EndBindingFile (state);
WriteToPartialClasses (pc => generator.EndPartialClassFile (pc.State!));
return true;
void WriteToPartialClasses (Action<PartialClass> code)
{
if (!havePartialClasses || partialClasses == null)
return;
foreach (var pc in partialClasses) {
if (pc == null)
continue;
code (pc);
}
}
}
void DetermineWidgetType (LayoutWidget widget, bool needsFullCheck)
{
if (!needsFullCheck && widget.WidgetType != LayoutWidgetType.Unknown)
return;
if (widget.AllTypes.All (wt => wt == LayoutWidgetType.View))
widget.WidgetType = LayoutWidgetType.View;
else if (widget.AllTypes.All (wt => wt == LayoutWidgetType.Fragment))
widget.WidgetType = LayoutWidgetType.Fragment;
else
widget.WidgetType = LayoutWidgetType.Mixed;
}
bool GetRequiredMetadata (ITaskItem resourceItem, string metadataName, out string metadataValue)
{
metadataValue = resourceItem.GetMetadata (metadataName);
if (String.IsNullOrEmpty (metadataValue)) {
LogCodedError ("XA4226", Properties.Resources.XA4226, resourceItem.ItemSpec, metadataName);
return false;
}
return true;
}
}
}