/
GenerateJavaStubs.cs
289 lines (233 loc) · 11.6 KB
/
GenerateJavaStubs.cs
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
// Copyright (C) 2011 Xamarin, Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using MonoDroid.Utils;
using Mono.Cecil;
using Java.Interop.Tools.Cecil;
using Java.Interop.Tools.Diagnostics;
using Java.Interop.Tools.JavaCallableWrappers;
using Java.Interop.Tools.TypeNameMappings;
using Xamarin.Android.Tools;
namespace Xamarin.Android.Tasks
{
using PackageNamingPolicyEnum = PackageNamingPolicy;
public class GenerateJavaStubs : Task
{
[Required]
public ITaskItem[] ResolvedAssemblies { get; set; }
[Required]
public ITaskItem[] ResolvedUserAssemblies { get; set; }
[Required]
public string AcwMapFile { get; set; }
public string ManifestTemplate { get; set; }
public string[] MergedManifestDocuments { get; set; }
public bool Debug { get; set; }
public string ApplicationName { get; set; }
public string PackageName { get; set; }
public string [] ManifestPlaceholders { get; set; }
public string AndroidSdkDir { get; set; }
public string AndroidSdkPlatform { get; set; }
public string OutputDirectory { get; set; }
public string MergedAndroidManifestOutput { get; set; }
public bool EmbedAssemblies { get; set; }
public bool NeedsInternet { get; set; }
public bool UseSharedRuntime { get; set; }
[Required]
public string ResourceDirectory { get; set; }
public string BundledWearApplicationName { get; set; }
public string PackageNamingPolicy { get; set; }
public string ApplicationJavaClass { get; set; }
public override bool Execute ()
{
Log.LogDebugMessage ("GenerateJavaStubs Task");
Log.LogDebugMessage (" ManifestTemplate: {0}", ManifestTemplate);
Log.LogDebugMessage (" Debug: {0}", Debug);
Log.LogDebugMessage (" ApplicationName: {0}", ApplicationName);
Log.LogDebugMessage (" PackageName: {0}", PackageName);
Log.LogDebugMessage (" AndroidSdkDir: {0}", AndroidSdkDir);
Log.LogDebugMessage (" AndroidSdkPlatform: {0}", AndroidSdkPlatform);
Log.LogDebugMessage (" OutputDirectory: {0}", OutputDirectory);
Log.LogDebugMessage (" MergedAndroidManifestOutput: {0}", MergedAndroidManifestOutput);
Log.LogDebugMessage (" UseSharedRuntime: {0}", UseSharedRuntime);
Log.LogDebugTaskItems (" ResolvedAssemblies:", ResolvedAssemblies);
Log.LogDebugTaskItems (" ResolvedUserAssemblies:", ResolvedUserAssemblies);
Log.LogDebugMessage (" BundledWearApplicationName: {0}", BundledWearApplicationName);
Log.LogDebugTaskItems (" MergedManifestDocuments:", MergedManifestDocuments);
Log.LogDebugMessage (" PackageNamingPolicy: {0}", PackageNamingPolicy);
Log.LogDebugMessage (" ApplicationJavaClass: {0}", ApplicationJavaClass);
Log.LogDebugTaskItems (" ManifestPlaceholders: ", ManifestPlaceholders);
try {
// We're going to do 3 steps here instead of separate tasks so
// we can share the list of JLO TypeDefinitions between them
using (var res = new DirectoryAssemblyResolver (Log.LogWarning, loadDebugSymbols: true)) {
Run (res);
}
}
catch (XamarinAndroidException e) {
Log.LogCodedError (string.Format ("XA{0:0000}", e.Code), e.MessageWithoutCode);
if (MonoAndroidHelper.LogInternalExceptions)
Log.LogMessage (e.ToString ());
}
return !Log.HasLoggedErrors;
}
void Run (DirectoryAssemblyResolver res)
{
PackageNamingPolicy pnp;
JniType.PackageNamingPolicy = Enum.TryParse (PackageNamingPolicy, out pnp) ? pnp : PackageNamingPolicyEnum.LowercaseHash;
var temp = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ());
Directory.CreateDirectory (temp);
var selectedWhitelistAssemblies = new List<string> ();
// Put every assembly we'll need in the resolver
foreach (var assembly in ResolvedAssemblies) {
res.Load (Path.GetFullPath (assembly.ItemSpec));
if (MonoAndroidHelper.FrameworkAttributeLookupTargets.Any (a => Path.GetFileName (assembly.ItemSpec) == a))
selectedWhitelistAssemblies.Add (Path.GetFullPath (assembly.ItemSpec));
}
// However we only want to look for JLO types in user code
var assemblies = ResolvedUserAssemblies.Select (p => p.ItemSpec).ToList ();
var fxAdditions = MonoAndroidHelper.GetFrameworkAssembliesToTreatAsUserAssemblies (ResolvedAssemblies)
.Where (a => assemblies.All (x => Path.GetFileName (x) != Path.GetFileName (a)));
assemblies = assemblies.Concat (fxAdditions).ToList ();
// Step 1 - Find all the JLO types
var all_java_types = JavaTypeScanner.GetJavaTypes (assemblies, res, Log.LogWarning);
WriteTypeMappings (all_java_types);
var java_types = all_java_types.Where (t => !JavaTypeScanner.ShouldSkipJavaCallableWrapperGeneration (t));
// Step 2 - Generate Java stub code
var keep_going = Generator.CreateJavaSources (
Log,
java_types,
temp,
ApplicationJavaClass,
UseSharedRuntime,
int.Parse (AndroidSdkPlatform) <= 10,
ResolvedAssemblies.Any (assembly => Path.GetFileName (assembly.ItemSpec) == "Mono.Android.Export.dll"));
var temp_map_file = Path.Combine (temp, "acw-map.temp");
// We need to save a map of .NET type -> ACW type for resource file fixups
var managed = new Dictionary<string, TypeDefinition> ();
var java = new Dictionary<string, TypeDefinition> ();
var acw_map = new StreamWriter (temp_map_file);
foreach (var type in java_types) {
string managedKey = type.FullName.Replace ('/', '.');
string javaKey = JniType.ToJniName (type).Replace ('/', '.');
acw_map.WriteLine ("{0};{1}", type.GetPartialAssemblyQualifiedName (), javaKey);
acw_map.WriteLine ("{0};{1}", type.GetAssemblyQualifiedName (), javaKey);
TypeDefinition conflict;
if (managed.TryGetValue (managedKey, out conflict)) {
Log.LogWarning (
"Duplicate managed type found! Mappings between managed types and Java types must be unique. " +
"First Type: '{0}'; Second Type: '{1}'.",
conflict.GetAssemblyQualifiedName (),
type.GetAssemblyQualifiedName ());
Log.LogWarning (
"References to the type '{0}' will refer to '{1}'.",
managedKey, conflict.GetAssemblyQualifiedName ());
continue;
}
if (java.TryGetValue (javaKey, out conflict)) {
Log.LogError (
"Duplicate Java type found! Mappings between managed types and Java types must be unique. " +
"First Type: '{0}'; Second Type: '{1}'",
conflict.GetAssemblyQualifiedName (),
type.GetAssemblyQualifiedName ());
keep_going = false;
continue;
}
managed.Add (managedKey, type);
java.Add (javaKey, type);
acw_map.WriteLine ("{0};{1}", managedKey, javaKey);
acw_map.WriteLine ("{0};{1}", JniType.ToCompatJniName (type).Replace ('/', '.'), javaKey);
}
acw_map.Close ();
//The previous steps found an error, so we must abort and not generate any further output
//We must do so subsequent unchanged builds fail too.
if (!keep_going) {
File.Delete (temp_map_file);
return;
}
MonoAndroidHelper.CopyIfChanged (temp_map_file, AcwMapFile);
try { File.Delete (temp_map_file); } catch (Exception) { }
// Only overwrite files if the contents actually changed
foreach (var file in Directory.GetFiles (temp, "*", SearchOption.AllDirectories)) {
var dest = Path.GetFullPath (Path.Combine (OutputDirectory, "src", file.Substring (temp.Length + 1)));
MonoAndroidHelper.CopyIfChanged (file, dest);
}
// Step 3 - Merge [Activity] and friends into AndroidManifest.xml
var manifest = new ManifestDocument (ManifestTemplate, this.Log);
manifest.PackageName = PackageName;
manifest.ApplicationName = ApplicationName ?? PackageName;
manifest.Placeholders = ManifestPlaceholders;
manifest.Assemblies.AddRange (assemblies);
manifest.Resolver = res;
manifest.SdkDir = AndroidSdkDir;
manifest.SdkVersion = AndroidSdkPlatform;
manifest.Debug = Debug;
manifest.NeedsInternet = NeedsInternet;
var additionalProviders = manifest.Merge (all_java_types, selectedWhitelistAssemblies, ApplicationJavaClass, EmbedAssemblies, BundledWearApplicationName, MergedManifestDocuments);
var temp_manifest = Path.Combine (temp, "AndroidManifest.xml");
var real_manifest = Path.GetFullPath (MergedAndroidManifestOutput);
manifest.Save (temp_manifest);
// Only write the new manifest if it actually changed
MonoAndroidHelper.CopyIfChanged (temp_manifest, real_manifest);
// Create additional runtime provider java sources.
string providerTemplateFile = UseSharedRuntime ? "MonoRuntimeProvider.Shared.java" : "MonoRuntimeProvider.Bundled.java";
string providerTemplate = new StreamReader (typeof (JavaCallableWrapperGenerator).Assembly.GetManifestResourceStream (providerTemplateFile)).ReadToEnd ();
foreach (var provider in additionalProviders) {
var temp_provider = Path.Combine (temp, provider + ".java");
File.WriteAllText (temp_provider, providerTemplate.Replace ("MonoRuntimeProvider", provider));
var real_provider_dir = Path.GetFullPath (Path.Combine (OutputDirectory, "src", "mono"));
Directory.CreateDirectory (real_provider_dir);
var real_provider = Path.Combine (real_provider_dir, provider + ".java");
MonoAndroidHelper.CopyIfChanged (temp_provider, real_provider);
}
// Create additional application java sources.
Action<string,string,string,Func<string,string>> save = (resource, filename, destDir, applyTemplate) => {
string temp_file = Path.Combine (temp, filename);
string template = applyTemplate (new StreamReader (typeof (GenerateJavaStubs).Assembly.GetManifestResourceStream (resource)).ReadToEnd ());
File.WriteAllText (temp_file, template);
Directory.CreateDirectory (destDir);
var real_file = Path.Combine (destDir, filename);
MonoAndroidHelper.CopyIfChanged (temp_file, real_file);
};
StringWriter regCallsWriter = new StringWriter ();
regCallsWriter.WriteLine ("\t\t// Application and Instrumentation ACWs must be registered first.");
foreach (var type in java_types) {
if (JniType.IsApplication (type) || JniType.IsInstrumentation (type)) {
string javaKey = JniType.ToJniName (type).Replace ('/', '.');
regCallsWriter.WriteLine ("\t\tmono.android.Runtime.register (\"{0}\", {1}.class, {1}.__md_methods);",
type.GetAssemblyQualifiedName (), javaKey);
}
}
regCallsWriter.Close ();
var real_app_dir = Path.GetFullPath (Path.Combine (OutputDirectory, "src", "mono", "android", "app"));
string applicationTemplateFile = "ApplicationRegistration.java";
save (applicationTemplateFile, applicationTemplateFile, real_app_dir,
template => template.Replace ("// REGISTER_APPLICATION_AND_INSTRUMENTATION_CLASSES_HERE", regCallsWriter.ToString ()));
// Create NotifyTimeZoneChanges java sources.
string notifyTimeZoneChangesFile = "NotifyTimeZoneChanges.java";
save (notifyTimeZoneChangesFile, notifyTimeZoneChangesFile, real_app_dir, template => template);
// Delete our temp directory
try { Directory.Delete (temp, true); } catch (Exception) { }
}
void WriteTypeMappings (List<TypeDefinition> types)
{
using (var gen = UseSharedRuntime
? new TypeNameMapGenerator (types, Log.LogDebugMessage)
: new TypeNameMapGenerator (ResolvedAssemblies.Select (p => p.ItemSpec), Log.LogDebugMessage)) {
UpdateWhenChanged (Path.Combine (OutputDirectory, "typemap.jm"), gen.WriteJavaToManaged);
UpdateWhenChanged (Path.Combine (OutputDirectory, "typemap.mj"), gen.WriteManagedToJava);
}
}
void UpdateWhenChanged (string path, Action<Stream> generator)
{
var np = path + ".new";
using (var o = File.OpenWrite (np))
generator (o);
Files.CopyIfChanged (np, path);
File.Delete (np);
}
}
}