This repository was archived by the owner on Oct 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathAndroidBase.scala
More file actions
565 lines (463 loc) · 20.4 KB
/
AndroidBase.scala
File metadata and controls
565 lines (463 loc) · 20.4 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
package sbtandroid
import sbt._
import scala.xml._
import Keys._
import AndroidPlugin._
import AndroidHelpers._
import sbinary.DefaultProtocol.StringFormat
object AndroidBase {
def getNativeTarget(parent: File, name: String, abi: String) = {
val extension = "-" + abi + ".so"
if (name endsWith extension) {
val stripped = name.substring(0, name indexOf '-') + ".so"
val target = new File(abi) / stripped
Some(parent / target.toString)
} else None
}
def copyNativeLibrariesTask =
(streams, managedNativePath, dependencyClasspath) map {
(s, natives, deps) => {
val sos = (deps.map(_.data)).filter(_.name endsWith ".so")
var copied = Seq.empty[File]
for (so <- sos)
getNativeTarget(natives, so.name, "armeabi") orElse getNativeTarget(natives, so.name, "armeabi-v7a") map {
target =>
target.getParentFile.mkdirs
IO.copyFile(so, target)
copied +:= target
s.log.info("Copied native library: " + target.toString)
}
// Clean up stale native libraries
for (path <- IO.listFiles(natives / "armeabi") ++ IO.listFiles(natives / "armeabi-v7a")) {
s.log.debug("Checking native library: " + path.toString)
if (path.name.endsWith(".so") && !copied.contains(path)) {
IO.delete(path)
s.log.debug("Deleted native library: " + path.toString)
}
}
}
}
private def apklibSourcesTask =
(apklibDependencies, streams) map {
(projectLibs, s) => {
if (!projectLibs.isEmpty) {
s.log.debug("Generating source files from ApkLibs")
val xs = for (
l <- projectLibs;
f <- l.sources
) yield f
s.log.info("Generated " + xs.size + " source files from " + projectLibs.size + " ApkLibs")
xs
} else Seq.empty
}
}
private def apklibPackageTask =
(manifestPath, mainResPath, mainAssetsPath, javaSource, scalaSource, packageApkLibPath, streams) map {
(manPath, rPath, aPath, jPath, sPath, apklib, s) =>
s.log.info("packaging apklib")
val mapping =
(PathFinder(manPath) x flat) ++
(PathFinder(jPath) ** "*.java" x rebase(jPath, "src")) ++
(PathFinder(sPath) ** "*.scala" x rebase(sPath, "src")) ++
((PathFinder(rPath) ***) x rebase(rPath, "res")) ++
((PathFinder(aPath) ***) x rebase(aPath, "assets"))
IO.jar(mapping, apklib, new java.util.jar.Manifest)
apklib
}
private def aarlibDependenciesTask =
(update, aarlibBaseDirectory, aarlibManaged, aarlibResourceManaged, resourceManaged, streams,
unmanagedBase) map {
(updateReport, aarlibBaseDirectory, aarlibManaged, aarlibResourceManaged, resManaged, s,
unmanagedBase) => {
// We want to extract every aarlib in the classpath that is not already
// set to provided (which should mean that another project already
// provides the aarLib).
val allaarlibs = updateReport.matching(artifactFilter(`type` = "aar"))
val unmanagedaarlibs = Option(unmanagedBase.listFiles)
.map(f => f.filter(_.name.endsWith(".aar")).toList)
.getOrElse(Seq.empty)
val providedaarlibs = updateReport.matching(configurationFilter(name = "provided"))
val aarlibs = (allaarlibs --- providedaarlibs get) ++ unmanagedaarlibs
// Make the destination directories
aarlibBaseDirectory.mkdirs
aarlibManaged.mkdirs
aarlibResourceManaged.mkdirs
// Extract the aarLibs
aarlibs map { aarlib =>
// Check if the AAR lib is up to date
val dest = aarlibResourceManaged / aarlib.base
val destjar = aarlibManaged / (aarlib.base + ".jar")
val timestamp = dest / ".timestamp"
// Check if the AAR lib is up to date
if (timestamp.lastModified < aarlib.lastModified) {
// Unzip the aarlib to a temporary directory
s.log.info("Extracting library " + aarlib.name)
val unzipped = IO.unzip(aarlib, dest)
// Move the classres in place
IO.move(dest / "classes.jar", destjar)
// Add a marker
IO.delete(timestamp)
new java.io.PrintWriter(timestamp, "UTF-8").close
}
// Read the package name from the manifest
val manifest = dest / "AndroidManifest.xml"
val pkgName = XML.loadFile(manifest).attribute("package").get.head.text
// Return a LibraryProject instance with some info about this aarLib
LibraryProject(
pkgName,
manifest,
Set(destjar),
Some(dest / "res") filter { _.exists },
Some(dest / "assets") filter { _.exists }
)
}
}
}
private def apklibDependenciesTask =
(update, apklibBaseDirectory, apklibSourceManaged, apklibResourceManaged, resourceManaged, streams,
unmanagedBase) map {
(updateReport, apklibBaseDirectory, apklibSourceManaged, apklibResourceManaged, resManaged, s,
unmanagedBase) => {
// Make the destination directories
apklibBaseDirectory.mkdirs
apklibSourceManaged.mkdirs
apklibResourceManaged.mkdirs
// We want to extract every apklib in the classpath that is not already
// set to provided (which should mean that another project already
// provides the ApkLib).
// We also want to include apklibs in unmanagedBase.
val allApklibs = updateReport.matching(artifactFilter(`type` = "apklib"))
val unmanagedApklibs = Option(unmanagedBase.listFiles)
.map(f => f.filter(_.name.endsWith(".apklib")).toList)
.getOrElse(Seq.empty)
val providedApklibs = updateReport.matching(configurationFilter(name = "provided"))
val apklibs = (allApklibs --- providedApklibs get) ++ unmanagedApklibs
// Extract the ApkLibs
apklibs map { apklib =>
// Unzip the ApkLib to a temporary directory
s.log.info("Extracting library " + apklib.name)
val dest = apklibResourceManaged / apklib.base
val unzipped = IO.unzip(apklib, dest)
// Move sources to the managed dir
def moveContents(fromDir: File, toDir: File) = {
toDir.mkdirs()
val pairs = for (
file <- unzipped;
rel <- IO.relativize(fromDir, file)
) yield (file, toDir / rel)
IO.move(pairs)
pairs map { case (_,t) => t }
}
val sources = moveContents(dest / "src", apklibSourceManaged)
// Read the package name from the manifest
val manifest = dest / "AndroidManifest.xml"
val pkgName = XML.loadFile(manifest).attribute("package").get.head.text
// Return a LibraryProject instance with some info about this ApkLib
LibraryProject(
pkgName,
manifest,
sources,
Some(dest / "res") filter { _.exists },
Some(dest / "assets") filter { _.exists }
)
}
}
}
private def aaptGenerateTask =
(manifestPackage, aaptPath, manifestPath, resPath, libraryJarPath, managedJavaPath,
generatedProguardConfigPath, aarlibDependencies, apklibDependencies, apklibSourceManaged, streams, useDebug) map {
(mPackage, aPath, mPath, rPath, jarPath, javaPath, proGen, aarlibs, apklibs, apklibJavaPath, s, useDebug) =>
// Create the managed Java path if necessary
javaPath.mkdirs
// Arguments for resource directories
val libraryResPathArgs = rPath.flatMap(p => Seq("-S", p.absolutePath))
// Arguments for library assets
val extlibs = apklibs ++ aarlibs
val libraryAssetPathArgs = for (
lib <- extlibs;
d <- lib.assetsDir.toSeq;
arg <- Seq("-A", d.absolutePath)
) yield arg
def runAapt(`package`: String, outJavaPath: File, args: String*) {
s.log.info("Running AAPT for package " + `package`)
val aapt = Seq(aPath.absolutePath, "package", "--auto-add-overlay", "-m",
"--custom-package", `package`,
"-M", mPath.head.absolutePath,
"-I", jarPath.absolutePath,
"-J", outJavaPath.absolutePath,
"-G", proGen.absolutePath) ++
args ++
libraryResPathArgs ++
libraryAssetPathArgs
if (aapt.run(false).exitValue != 0) sys.error("error generating resources")
}
// Run aapt to generate resources for the main package
runAapt(mPackage, javaPath)
// Run aapt to generate resources for each apklib dependency
apklibs.foreach(lib => runAapt(lib.pkgName, apklibJavaPath, "--non-constant-id"))
def createBuildConfig(`package`: String) = {
var path = javaPath
`package`.split('.').foreach { path /= _ }
path.mkdirs
val buildConfig = path / "BuildConfig.java"
IO.write(buildConfig, """
package %s;
public final class BuildConfig {
public static final boolean DEBUG = %s;
}""".format(`package`, useDebug))
buildConfig
}
(javaPath ** "R.java" get) ++
(apklibJavaPath ** "R.java" get) ++
Seq(createBuildConfig(mPackage)) ++
apklibs.map(lib => createBuildConfig(lib.pkgName))
}
private def aidlGenerateTask =
(sourceDirectories, idlPath, platformPath, managedJavaPath, javaSource, streams) map {
(sDirs, idPath, platformPath, javaPath, jSource, s) =>
val aidlPaths = sDirs.map(_ ** "*.aidl").reduceLeft(_ +++ _).get
if (aidlPaths.isEmpty) {
s.log.debug("No AIDL files found, skipping")
Nil
} else {
val processor = aidlPaths.map { ap =>
idPath.absolutePath ::
"-p" + (platformPath / "framework.aidl").absolutePath ::
"-o" + javaPath.absolutePath ::
"-I" + jSource.absolutePath ::
ap.absolutePath :: Nil
}.foldLeft(None.asInstanceOf[Option[ProcessBuilder]]) { (f, s) =>
f match {
case None => Some(s)
case Some(first) => Some(first #&& s)
}
}.get
s.log.debug("generating aidl "+processor)
processor !
val rPath = javaPath ** "R.java"
javaPath ** "*.java" --- (rPath) get
}
}
def findPath() = (manifestPath) map { p =>
manifest(p.head).attribute("package").getOrElse(sys.error("package not defined")).text
}
def isPreinstalled(f: Attributed[java.io.File], preinstalled: Seq[ModuleID]): Boolean = {
f.get(moduleID.key) match {
case Some(m) => preinstalled exists (pm =>
pm.organization == m.organization &&
pm.name == m.name)
case None => false
}
}
/**
* Returns the internal dependencies for the "provided" scope only
*/
def providedInternalDependenciesTask(proj: ProjectRef, struct: Load.BuildStructure) = {
// "Provided" dependencies of a ResolvedProject
def providedDeps(op: ResolvedProject): Seq[ProjectRef] = {
op.dependencies
.filter(p => (p.configuration getOrElse "") == "provided")
.map(_.project)
}
// Collect every "provided" dependency in the dependency graph
def collectDeps(projRef: ProjectRef): Seq[ProjectRef] = {
val deps = Project.getProject(projRef, struct).toSeq.flatMap(providedDeps)
deps.flatMap(ref => ref +: collectDeps(ref)).distinct
}
// Return the list of "provided" internal dependencies for the ProjectRef
// in argument.
collectDeps(proj)
.flatMap(exportedProducts in (_, Compile) get struct.data)
.join.map(_.flatten.files)
}
val providedInternalDependencies = TaskKey[Seq[File]]("provided-internal-dependencies")
lazy val globalSettings: Seq[Setting[_]] = Seq(
// At the moment, we NEED to use Java 6 class files
javacOptions ++= Seq(
"-encoding", "utf8",
"-target", "1.6",
"-source", "1.6"
),
// Same thing for Scalac
scalacOptions ++= Seq(
"-encoding", "utf8",
"-target:jvm-1.6"
),
// By default, use the first device we find as the ADB target
adbTarget in Global := AndroidDefaultTargets.Auto,
// By default, don't cache passwords
cachePasswords in Global := false,
// By default, no additional Proguard options and optimizations
proguardOptions := Seq.empty,
proguardOptimizations := Seq.empty,
// Dex options
dxMemory := "-JXmx512m",
// Platform path for the current project
platformPath <<= (sdkPath, platformName) (_ / "platforms" / _),
// Path to the platform android.jar for the current project
libraryJarPath <<= (platformPath, libraryJarName) (_ / _),
// By default, if preloading is enabled, preload the Scala library
preloadFilters := Seq(filterName("scala-library")),
// Default IntelliJ configuration (for sbtidea integration)
ideaConfiguration := Compile,
// Default key alias
keyalias := "alias_name",
// Apk defaults to the Compile scope
apk <<= apk in Compile,
// Use typed resources by default
useTypedResources := true,
// Add the Android library as a provided dependency
unmanagedJars in Compile <+= (libraryJarPath) (p =>
Attributed.blank(p)) map (x => x),
// Gradle uses libs/ as the unmanaged JAR directory!
unmanagedBase <<= (baseDirectory) (_ / "libs"),
// Path to the unmanaged native libraries
unmanagedNativePath <<= (baseDirectory) (_ / "lib"),
// Path to the managed native libraries
managedNativePath <<= (crossTarget) (_ / "native_managed"),
// Default native directories
nativeDirectories := Seq.empty,
nativeDirectories <+= unmanagedNativePath map (x => x),
nativeDirectories <+= managedNativePath map (x => x)
)
lazy val settings: Seq[Setting[_]] = (Seq (
// Path to the Proguard-ed class JAR
classesMinJarName <<= (artifact, configuration, version) (
(a, c, v) => "classes-%s-%s-%s.min.jar".format(a.name, c.name, v) ),
// Path to the dexed class file
classesDexName <<= (artifact, configuration, version) (
(a, c, v) => "classes-%s-%s-%s.dex".format(a.name, c.name, v) ),
// Name and path to the resource APK
resourcesApkName <<= (artifact, configuration, version) (
(a, c, v) => "resources-%s-%s-%s.apk".format(a.name, c.name, v) ),
resourcesApkPath <<= (target, resourcesApkName) (_ / _),
// Name and path to the final APK
packageApkName <<= (artifact, configuration, versionName) map (
(a, c, v) => "%s-%s-%s.apk".format(a.name, c.name, v) ),
packageApkPath <<= (target, packageApkName) map (_ / _),
// Name and path to the final ApkLib
packageApkLibName <<= (artifact, configuration, versionName) map (
(a, c, v) => "%s-%s-%s.apklib".format(a.name, c.name, v) ),
packageApkLibPath <<= (target, packageApkLibName) map (_ / _),
// Path to the manifest file
manifestPath <<= (sourceDirectory, manifestName) map((s,m) => Seq(s / m)),
// Package information, extracted from the manifest
manifestPackage <<= findPath,
manifestPackageName <<= findPath storeAs manifestPackageName triggeredBy manifestPath,
minSdkVersion <<= (manifestPath, manifestSchema) map ( (p,s) => usesSdk(p.head, s, "minSdkVersion")),
maxSdkVersion <<= (manifestPath, manifestSchema) map ( (p,s) => usesSdk(p.head, s, "maxSdkVersion")),
versionName <<= (manifestPath, manifestSchema, version) map ((p, schema, version) =>
manifest(p.head).attribute(schema, "versionName").map(_.text).getOrElse(version)
),
// Main asset and resource paths
mainAssetsPath <<= (sourceDirectory, assetsDirectoryName) (_ / _),
mainResPath <<= (sourceDirectory, resDirectoryName) (_ / _) map (x=> x),
// Managed sources and resources
managedSourceDirectories <+= apklibSourceManaged,
managedJavaPath <<= (sourceManaged) (_ / "java"),
managedScalaPath <<= (sourceManaged) ( _ / "scala"),
// Resource paths
//
// By default, include the main resource path, as well as the resources
// from additional ApkLib dependencies.
resPath := Seq(),
resPath <+= mainResPath,
resPath <++= apklibDependencies map (apklibs => apklibs.flatMap(_.resDir)),
resPath <++= aarlibDependencies map (aarlibs => aarlibs.flatMap(_.resDir)),
// Path to the resources APK file
resourcesApkPath <<= (target, resourcesApkName) (_ / _),
// Assets go into the resource directories
resourceDirectories <<= resourceDirectories in Compile,
resourceDirectories <+= (mainAssetsPath),
// ApkLib paths
apklibBaseDirectory <<= crossTarget (_ / "apklib_managed"),
apklibSourceManaged <<= apklibBaseDirectory (_ / "src"),
apklibResourceManaged <<= apklibBaseDirectory (_ / "res"),
apklibDependencies <<= apklibDependenciesTask,
apklibPackage <<= apklibPackageTask,
apklibSources <<= apklibSourcesTask,
// AAR lib paths
aarlibBaseDirectory <<= crossTarget (_ / "aarlib_managed"),
aarlibManaged <<= aarlibBaseDirectory (_ / "lib"),
aarlibResourceManaged <<= aarlibBaseDirectory (_ / "res"),
aarlibDependencies <<= aarlibDependenciesTask,
// Output path of the DX command
dxOutputPath <<= (target, classesDexName) (_ / _),
// Inputs for the DX command
dxInputs <<=
(proguard, includedClasspath, classDirectory) map (
(proguard, includedClasspath, classDirectory) => proguard match {
case Some(f) => Seq(f)
case None => includedClasspath :+ classDirectory
}
),
// Paths to be predexed by DX to improve build times.
//
// Usually, libraries that won't change much over time, and, by default,
// the inputs that are part of the managed classpath.
dxPredex <<= (managedClasspath, dxInputs) map {
(cp, inputs) => { cp filter (inputs contains _.data) files }
},
// Provided internal dependencies (usually, class directories from a
// dependency project set as "provided")
providedInternalDependencies <<= (thisProjectRef, buildStructure) flatMap providedInternalDependenciesTask,
providedInternalDependencies <+= libraryJarPath map (x => x),
// The full input classpath
inputClasspath <<= (dependencyClasspath) map { dcp =>
dcp filterNot (cpe => cpe.get(artifact.key) match {
case Some(k) => k.`type` == "so"
case None => false
}) map (_.data)
},
// The included classpath entries
includedClasspath <<=
(update, libraryJarPath, usePreloaded, dependencyClasspath, preinstalledModules, preloadFilters, providedInternalDependencies) map {
(update, libraryJarPath, usePreloaded, dependencyClasspath, preinstalledModules, preloadFilters, providedInternalDependencies) =>
// Filters out the entries that are _not_ to be included in the final APK
val notIncludedFilters = (
(if (usePreloaded) preloadFilters else Seq.empty) ++
(preinstalledModules map (filterModule _))
)
// Provided dependencies that are not to be included in the APK
val provided = (
providedInternalDependencies ++
update.select(Set("provided"))
)
// Filter the full classpath
dependencyClasspath.filterNot { cpe =>
(notIncludedFilters exists (f => f(cpe))) ||
(provided contains cpe.data)
}.files
},
// The provided classpath entries are those that are in `fullClasspath` but
// not in `includedClasspath`.
providedClasspath <<= (inputClasspath, includedClasspath) map ((in, incl) =>
in filterNot (incl contains _)),
// Path to Proguard's output JAR
proguardOutputPath <<= (target, classesMinJarName) (_ / _),
// Path to the generated (with aapt -G) Proguard configuration
generatedProguardConfigPath <<= (target, generatedProguardConfigName) (_ / _),
// Copy native library dependencies
copyNativeLibraries <<= copyNativeLibrariesTask,
// AAPT and AIDL source generation
aaptGenerate <<= aaptGenerateTask,
aidlGenerate <<= aidlGenerateTask,
// Manifest generator rules
manifestRewriteRules := Seq.empty,
// Migrate settings from the defaults in Compile
sourceDirectory <<= sourceDirectory in Compile,
sourceDirectories <<= sourceDirectories in Compile,
resourceDirectory <<= resourceDirectory in Compile,
javaSource <<= javaSource in Compile,
scalaSource <<= scalaSource in Compile,
dependencyClasspath <<= dependencyClasspath in Compile,
managedClasspath <<= managedClasspath in Compile,
// Add the AAR library dependencies
unmanagedJars <++= (aarlibDependencies) map {
libs => libs.flatMap(_.sources).map(Attributed.blank(_)) },
// Set the default classpath types
classpathTypes := Set("jar", "bundle", "so"),
// Configure the source generators
sourceGenerators <+= (apklibSources, aaptGenerate, aidlGenerate) map (_ ++ _ ++ _)
))
}