Merge branch 'develop' of https://source.jalview.org/git/jalview into develop
[jalview.git] / build.gradle
1 import org.apache.tools.ant.filters.ReplaceTokens
2 //import org.apache.tools.ant.filters.ReplaceRegexp
3 import org.gradle.internal.os.OperatingSystem
4 import org.gradle.plugins.ide.eclipse.model.*
5
6
7 import groovy.transform.ExternalizeMethods
8
9 buildscript {
10   dependencies {
11     classpath 'org.openclover:clover:4.3.1'
12     classpath 'org.apache.commons:commons-compress:1.18'
13   }
14 }
15
16 plugins {
17   id 'java'
18   id 'application'
19   id 'eclipse'
20   id 'com.github.johnrengelman.shadow' version '4.0.3'
21   id 'com.install4j.gradle' version '7.0.9'
22 }
23
24 repositories {
25   jcenter()
26   mavenCentral()
27   mavenLocal()
28   flatDir {
29     dirs gradlePluginsDir
30   }
31 }
32
33 mainClassName = launcherClass
34 def cloverInstrDir = file("$buildDir/$cloverSourcesInstrDir")
35 def classes = "$jalviewDir/$classesDir"
36
37 if (clover.equals("true")) {
38   use_clover = true
39   classes = "$buildDir/$cloverClassesDir"
40 } else {
41   use_clover = false
42   classes = "$jalviewDir/$classesDir"
43 }
44
45 // configure classpath/args for j8/j11 compilation
46
47 def jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
48 def libDir
49 def libDistDir
50 def compile_source_compatibility
51 def compile_target_compatibility
52
53 ext {
54   // where the getdown channel will be built.
55   // TODO: consider allowing this expression to  be overridden by -P arg
56   getdownWebsiteDir = jalviewDir + '/' + getdown_website_dir + '/' + JAVA_VERSION
57   getdownAppDir = getdownWebsiteDir + '/' + getdown_app_dir
58   getdownJ11libDir = getdownWebsiteDir + '/' + getdown_j11lib_dir
59   getdownResourceDir = getdownWebsiteDir + '/' + getdown_resource_dir
60   getdownLauncher = jalviewDir + '/' + getdown_launcher
61   getdownFilesDir = jalviewDir + '/' + getdown_files_dir + '/' + JAVA_VERSION + '/'
62   getdown_app_base = getdown_channel_base+"/"+getdown_channel_name+"/"+JAVA_VERSION+"/"
63   modules_compileClasspath = fileTree(dir: "$jalviewDir/$j11modDir", include: ["*.jar"])
64   modules_runtimeClasspath = modules_compileClasspath
65   gitHash = ""
66   gitBranch = ""
67 }
68
69 def JAVA_INTEGER_VERSION
70 def additional_compiler_args = []
71 // these are getdown.txt properties defined dependent on the JAVA_VERSION
72 def getdown_alt_java_min_version
73 // this property is assigned below and expanded to multiple lines in the getdown task
74 def getdown_alt_multi_java_location
75 if (JAVA_VERSION.equals("1.8")) {
76   JAVA_INTEGER_VERSION = "8"
77   libDir = j11libDir
78   libDistDir = j8libDir
79   compile_source_compatibility = 1.8
80   compile_target_compatibility = 1.8
81   getdown_alt_java_min_version = getdown_alt_java8_min_version
82   getdown_alt_multi_java_location = getdown_alt_java8_txt_multi_java_location
83 } else if (JAVA_VERSION.equals("11")) {
84   JAVA_INTEGER_VERSION = "11"
85   libDir = j11libDir
86   libDistDir = j11libDir
87   compile_source_compatibility = 11
88   compile_target_compatibility = 11
89   getdown_alt_java_min_version = getdown_alt_java11_min_version
90   getdown_alt_multi_java_location = getdown_alt_java11_txt_multi_java_location
91   additional_compiler_args += [
92     '--module-path', ext.modules_compileClasspath.asPath,
93     '--add-modules', j11modules
94   ]
95 } else {
96   throw new GradleException("JAVA_VERSION=$JAVA_VERSION not currently supported by Jalview")
97 }
98
99 sourceSets {
100
101   main {
102     java {
103       srcDirs "$jalviewDir/$sourceDir"
104       outputDir = file("$classes")
105     }
106
107     resources {
108       srcDirs "$jalviewDir/$resourceDir"
109       srcDirs "$jalviewDir/$libDistDir"
110     }
111
112     jar.destinationDir = file("$jalviewDir/$packageDir")
113
114     compileClasspath = files(sourceSets.main.java.outputDir)
115     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
116
117     runtimeClasspath = compileClasspath
118   }
119   clover {
120     java {
121       srcDirs = [ cloverInstrDir ]
122       outputDir = file("${buildDir}/${cloverClassesDir}")
123     }
124
125     resources {
126       srcDirs = sourceSets.main.resources.srcDirs
127     }
128     compileClasspath = configurations.cloverRuntime + files( sourceSets.clover.java.outputDir )
129     compileClasspath += files(sourceSets.main.java.outputDir)
130     compileClasspath += sourceSets.main.compileClasspath
131     compileClasspath += fileTree(dir: "$jalviewDir/$utilsDir", include: ["**/*.jar"])
132     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
133
134     runtimeClasspath = compileClasspath
135   }
136
137   test {
138     java {
139       srcDirs "$jalviewDir/$testSourceDir"
140       outputDir = file("$jalviewDir/$testOutputDir")
141     }
142
143     resources {
144       srcDirs = sourceSets.main.resources.srcDirs
145     }
146
147     compileClasspath = files( sourceSets.test.java.outputDir )
148
149     if (use_clover) {
150       compileClasspath += sourceSets.clover.compileClasspath
151     } else {
152       compileClasspath += files(sourceSets.main.java.outputDir)
153     }
154     //compileClasspath += sourceSets.main.compileClasspath
155     //compileClasspath += files( sourceSets.main.resources.srcDirs)
156     compileClasspath += fileTree(dir: "$jalviewDir/$utilsDir", include: ["**/*.jar"])
157     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
158
159     runtimeClasspath = compileClasspath
160   }
161 }
162
163 // clover bits
164 dependencies {
165   if (use_clover) {
166     cloverCompile 'org.openclover:clover:4.3.1'
167     testCompile 'org.openclover:clover:4.3.1'
168   }
169 }
170
171 configurations {
172   cloverRuntime
173   cloverRuntime.extendsFrom cloverCompile
174 }
175
176 eclipse {
177   project {
178     name = "Jalview with gradle build"
179
180     natures 'org.eclipse.jdt.core.javanature',
181         'org.eclipse.jdt.groovy.core.groovyNature',
182         'org.eclipse.buildship.core.gradleprojectnature'
183
184     buildCommand 'org.eclipse.jdt.core.javabuilder'
185     buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
186   }
187
188   classpath {
189     //defaultOutputDir = sourceSets.main.java.outputDir
190     def removeThese = []
191     configurations.each{ if (it.isCanBeResolved()) {
192         removeThese += it
193       }
194     }
195
196     minusConfigurations += removeThese
197     plusConfigurations = [ ]
198     file {
199
200       whenMerged { cp ->
201         def removeTheseToo = []
202         HashMap<String, Boolean> addedSrcPath = new HashMap<>();
203         cp.entries.each { entry ->
204           if (entry.kind == 'src') {
205             if (addedSrcPath.getAt(entry.path) || !(entry.path == "src" || entry.path == "test")) {
206               removeTheseToo += entry
207             } else {
208               addedSrcPath.putAt(entry.path, true)
209             }
210           }
211         }
212         cp.entries.removeAll(removeTheseToo)
213         
214         cp.entries += new Output("bin/main")
215         cp.entries += new Library(fileReference(helpParentDir))
216         cp.entries += new Library(fileReference(resourceDir))
217         
218         HashMap<String, Boolean> addedLibPath = new HashMap<>();
219         def allPaths = sourceSets.test.compileClasspath + sourceSets.main.compileClasspath
220         sourceSets.main.compileClasspath.each{
221           //if ((it.isDirectory() || ! it.exists()) && ! (it.equals(sourceSets.main.java.outputDir))) {
222           //no longer want to add outputDir as eclipse is using its own output dir in bin/main
223           if (it.isDirectory() || ! it.exists()) {
224             // don't add dirs to classpath
225             return
226           }
227           def itPath = it.toString()
228           if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
229             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
230           }
231           if (addedLibPath.get(itPath)) {
232             //println("Not adding duplicate entry "+itPath)
233           } else {
234             //println("Adding entry "+itPath)
235             cp.entries += new Library(fileReference(itPath))
236             addedLibPath.put(itPath, true)
237           }
238         }
239
240         sourceSets.test.compileClasspath.each{
241           //if ((it.isDirectory() || ! it.exists()) && ! (it.equals(sourceSets.main.java.outputDir))) {
242           //no longer want to add outputDir as eclipse is using its own output dir in bin/main
243           if (it.isDirectory() || ! it.exists()) {
244             // don't add dirs to classpath
245             return false // groovy "break" in .each loop
246           }
247           def itPath = it.toString()
248           if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
249             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
250           }
251           if (addedLibPath.get(itPath)) {
252             // don't duplicate
253           } else {
254             def lib = new Library(fileReference(itPath))
255             // this doesn't work... yet.  Adding test=true attribute using withXml below
256             //def attrs = new Node(null, 'attributes', ["test":"true"])
257             //lib.appendNode(attrs) //
258             cp.entries += lib
259             addedLibPath.put(itPath, true)
260           }
261         }
262       }  
263
264       // withXml changes ignored by buildship, these add the "test=true" attribute
265       withXml {
266         def node = it.asNode()
267         
268         def srcTestAttributes
269         node.children().each{ cpe ->
270           def attributes = cpe.attributes()
271           if (attributes.get("kind") == "src" && attributes.get("path") == "test") {
272             srcTestAttributes = cpe.find { a -> a.name() == "attributes" }
273             return
274           }
275         }
276         def addTestAttribute = true
277         srcTestAttributes.each{a ->
278           if (a.name() == "attribute" && a.attributes().getAt("name") == "test") {
279             addTestAttribute = false
280           }
281         }
282         if (addTestAttribute) {
283           srcTestAttributes.append(new Node(null, "attribute", [name:"test", value:"true"]))
284         }
285
286         node.children().each{ cpe ->
287           def attributes = cpe.attributes()
288           if (attributes.get("kind") == "lib" && attributes.get("path").startsWith("utils/")) {
289             cpe.appendNode('attributes')
290                 .appendNode('attribute', [name:"test", value:"true"])
291           }
292         }
293       } // withXML
294     } // file
295
296     containers 'org.eclipse.buildship.core.gradleclasspathcontainer'
297   } // classpath
298
299   jdt {
300     // for the IDE, use java 11 compatibility
301     sourceCompatibility = 11
302     targetCompatibility = 11
303     javaRuntimeName = "JavaSE-11"
304
305     file {
306       withProperties { props ->
307         def jalview_prefs = new Properties()
308         def ins = new FileInputStream(jalviewDirAbsolutePath+"/"+eclipse_extra_jdt_prefs_file)
309         jalview_prefs.load(ins)
310         ins.close()
311         jalview_prefs.forEach { t, v ->
312           if (props.getAt(t) == null) {
313             props.putAt(t, v)
314           }
315         }
316       }
317     }
318   }
319   
320   //synchronizationTasks eclipseClasspath
321   //autoBuildTasks eclipseClasspath
322
323
324 task cloverInstr() {
325   // only instrument source, we build test classes as normal
326   inputs.files files (sourceSets.main.allJava) // , fileTree(dir:"$jalviewDir/$testSourceDir", include: ["**/*.java"]))
327   outputs.dir cloverInstrDir
328
329   doFirst {
330     delete cloverInstrDir
331     def argsList = ["--initstring", "${buildDir}/clover/clover.db",
332       "-d", "${buildDir}/${cloverSourcesInstrDir}"]
333     argsList.addAll(inputs.files.files.collect({ file ->
334       file.absolutePath
335     }))
336     String[] args = argsList.toArray()
337     println("About to instrument "+args.length +" files")
338     com.atlassian.clover.CloverInstr.mainImpl(args)
339   }
340 }
341   
342
343 task cloverReport {
344   group = "Verification"
345   description = "Createst the Clover report"
346   inputs.dir "${buildDir}/clover"
347   outputs.dir "${reportsDir}/clover"
348   onlyIf {
349     file("${buildDir}/clover/clover.db").exists()
350   }
351   doFirst {
352     def argsList = ["--initstring", "${buildDir}/clover/clover.db",
353       "-o", "${reportsDir}/clover"]
354     String[] args = argsList.toArray()
355     com.atlassian.clover.reporters.html.HtmlReporter.runReport(args)
356
357     // and generate ${reportsDir}/clover/clover.xml
358     args = ["--initstring", "${buildDir}/clover/clover.db",
359       "-o", "${reportsDir}/clover/clover.xml"].toArray()
360     com.atlassian.clover.reporters.xml.XMLReporter.runReport(args)
361   }
362 }
363
364 // end clover bits
365
366
367 compileJava {
368
369   doFirst {
370     sourceCompatibility = compile_source_compatibility
371     targetCompatibility = compile_target_compatibility
372     options.compilerArgs = additional_compiler_args
373     print ("Setting target compatibility to "+targetCompatibility+"\n")
374   }
375
376 }
377
378 compileTestJava {
379   if (use_clover) {
380     dependsOn compileCloverJava
381     classpath += configurations.cloverRuntime
382   } else {
383     classpath += sourceSets.main.runtimeClasspath
384   }
385   doFirst {
386     sourceCompatibility = compile_source_compatibility
387     targetCompatibility = compile_target_compatibility
388     options.compilerArgs = additional_compiler_args
389     print ("Setting target compatibility to "+targetCompatibility+"\n")
390   }
391 }
392
393
394 compileCloverJava {
395
396   doFirst {
397     sourceCompatibility = compile_source_compatibility
398     targetCompatibility = compile_target_compatibility
399     options.compilerArgs += additional_compiler_args
400     print ("Setting target compatibility to "+targetCompatibility+"\n")
401   }
402   classpath += configurations.cloverRuntime
403 }
404
405 clean {
406   delete sourceSets.main.java.outputDir
407 }
408
409 cleanTest {
410   delete sourceSets.test.java.outputDir
411   delete cloverInstrDir
412 }
413
414 def getDate(format) {
415   def date = new Date()
416   //return date.format("dd MMMM yyyy")
417   return date.format(format)
418 }
419
420 task setGitHash(type: Exec) {
421   workingDir = jalviewDir
422   commandLine "git", "rev-parse", "--short", "HEAD"
423   standardOutput = new ByteArrayOutputStream()
424   project.ext.gitHash = {
425     return standardOutput.toString().trim()
426   }
427 }
428
429 task setGitBranch(type: Exec) {
430   workingDir = jalviewDir
431   commandLine "git", "rev-parse", "--abbrev-ref", "HEAD"
432   standardOutput = new ByteArrayOutputStream()
433   project.ext.gitBranch = {
434     return standardOutput.toString().trim()
435   }
436 }
437
438 task setGitVals {
439   dependsOn setGitHash
440   dependsOn setGitBranch
441 }
442
443 task createBuildProperties(type: WriteProperties) {
444   dependsOn setGitVals
445   inputs.dir("$jalviewDir/$sourceDir")
446   inputs.dir("$jalviewDir/$resourceDir")
447   outputFile "$classes/$buildPropertiesFile"
448   // taking time specific comment out to allow better incremental builds
449   //comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd HH:mm:ss")
450   comment "--Jalview Build Details--\n"+getDate("yyyy-MM-dd")
451   property "BUILD_DATE", getDate("dd MMMM yyyy")
452   property "VERSION", JALVIEW_VERSION
453   property "INSTALLATION", INSTALLATION+" git-commit:"+project.ext.gitHash+" ["+project.ext.gitBranch+"]"
454   outputs.file(outputFile)
455   outputs.dir("$classes")
456 }
457
458 def buildingHTML = "$jalviewDir/$docDir/building.html"
459 task deleteBuildingHTML(type: Delete) {
460   delete buildingHTML
461 }
462
463 task convertBuildingMD(type: Exec) {
464   dependsOn deleteBuildingHTML
465   def buildingMD = "$jalviewDir/$docDir/building.md"
466   def css = "$jalviewDir/$docDir/github.css"
467
468   def pandoc = null
469   pandoc_exec.split(",").each {
470     if (file(it.trim()).exists()) {
471       pandoc = it.trim()
472       return true
473     }
474   }
475
476   def hostname = "hostname".execute().text.trim()
477   if ((pandoc == null || ! file(pandoc).exists()) && hostname.equals("jv-bamboo")) {
478     pandoc = System.getProperty("user.home")+"/buildtools/pandoc/bin/pandoc"
479   }
480
481   if (pandoc != null && file(pandoc).exists()) {
482     commandLine pandoc, '-s', '-o', buildingHTML, '--metadata', 'pagetitle="Building Jalview from Source"', '--toc', '-H', css, buildingMD
483   } else {
484     commandLine "true"
485   }
486
487   ignoreExitValue true
488
489   inputs.file(buildingMD)
490   inputs.file(css)
491   outputs.file(buildingHTML)
492 }
493 clean {
494   delete buildingHTML
495 }
496
497 task syncDocs(type: Sync) {
498   dependsOn convertBuildingMD
499   def syncDir = "$classes/$docDir"
500   from fileTree("$jalviewDir/$docDir")
501   into syncDir
502
503 }
504
505 def helpFile = "$classes/$helpDir/help.jhm"
506
507 task copyHelp(type: Copy) {
508   def inputDir = "$jalviewDir/$helpParentDir/$helpDir"
509   def outputDir = "$classes/$helpDir"
510   from(inputDir) {
511     exclude '**/*.gif'
512     exclude '**/*.jpg'
513     exclude '**/*.png'
514     filter(ReplaceTokens, beginToken: '$$', endToken: '$$', tokens: ['Version-Rel': JALVIEW_VERSION])
515   }
516   from(inputDir) {
517     include '**/*.gif'
518     include '**/*.jpg'
519     include '**/*.png'
520   }
521   into outputDir
522
523   inputs.dir(inputDir)
524   outputs.files(helpFile)
525   outputs.dir(outputDir)
526 }
527
528 task syncLib(type: Sync) {
529   def syncDir = "$classes/$libDistDir"
530   from fileTree("$jalviewDir/$libDistDir")
531   into syncDir
532 }
533
534 task syncResources(type: Sync) {
535   from "$jalviewDir/$resourceDir"
536   include "**/*.*"
537   exclude "install4j"
538   into "$classes"
539   preserve {
540     include "**"
541   }
542 }
543
544 task prepare {
545   dependsOn syncResources
546   dependsOn syncDocs
547   dependsOn copyHelp
548 }
549
550
551 //testReportDirName = "test-reports" // note that test workingDir will be $jalviewDir
552 test {
553   dependsOn prepare
554   dependsOn compileJava
555   if (use_clover) {
556     dependsOn cloverInstr
557   }
558
559   print("Running tests " + (use_clover?"WITH":"WITHOUT") + " clover [clover="+use_clover+"]\n")
560
561   useTestNG() {
562     includeGroups testngGroups
563     preserveOrder true
564     useDefaultListeners=true
565   }
566
567   workingDir = jalviewDir
568   //systemProperties 'clover.jar' System.properties.clover.jar
569   sourceCompatibility = compile_source_compatibility
570   targetCompatibility = compile_target_compatibility
571   jvmArgs += additional_compiler_args
572   print ("Setting target compatibility to "+targetCompatibility+"\n")
573 }
574
575 task buildIndices(type: JavaExec) {
576   dependsOn copyHelp
577   classpath = sourceSets.main.compileClasspath
578   main = "com.sun.java.help.search.Indexer"
579   workingDir = "$classes/$helpDir"
580   def argDir = "html"
581   args = [ argDir ]
582   inputs.dir("$workingDir/$argDir")
583
584   outputs.dir("$classes/doc")
585   outputs.dir("$classes/help")
586   outputs.file("$workingDir/JavaHelpSearch/DOCS")
587   outputs.file("$workingDir/JavaHelpSearch/DOCS.TAB")
588   outputs.file("$workingDir/JavaHelpSearch/OFFSETS")
589   outputs.file("$workingDir/JavaHelpSearch/POSITIONS")
590   outputs.file("$workingDir/JavaHelpSearch/SCHEMA")
591   outputs.file("$workingDir/JavaHelpSearch/TMAP")
592 }
593
594 task compileLinkCheck(type: JavaCompile) {
595   options.fork = true
596   classpath = files("$jalviewDir/$utilsDir")
597   destinationDir = file("$jalviewDir/$utilsDir")
598   source = fileTree(dir: "$jalviewDir/$utilsDir", include: ["HelpLinksChecker.java", "BufferedLineReader.java"])
599
600   inputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.java")
601   inputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.java")
602   outputs.file("$jalviewDir/$utilsDir/HelpLinksChecker.class")
603   outputs.file("$jalviewDir/$utilsDir/BufferedLineReader.class")
604 }
605
606 def helplinkscheckeroutputfile = file("$jalviewDir/$utilsDir/HelpLinksChecker.out")
607 task linkCheck(type: JavaExec) {
608   dependsOn prepare, compileLinkCheck
609   classpath = files("$jalviewDir/$utilsDir")
610   main = "HelpLinksChecker"
611   workingDir = jalviewDir
612   def help = "$classes/$helpDir"
613   args = [ "$classes/$helpDir", "-nointernet" ]
614
615   doFirst {
616     helplinkscheckeroutputfile.createNewFile()
617     standardOutput new FileOutputStream(helplinkscheckeroutputfile, false)
618   }
619
620   outputs.file(helplinkscheckeroutputfile)
621 }
622
623 task cleanPackageDir(type: Delete) {
624   delete fileTree("$jalviewDir/$packageDir").include("*.jar")
625 }
626
627 jar {
628   dependsOn linkCheck
629   dependsOn buildIndices
630   dependsOn createBuildProperties
631
632   manifest {
633     attributes "Main-Class": mainClass,
634     "Permissions": "all-permissions",
635     "Application-Name": "Jalview Desktop",
636     "Codebase": application_codebase
637   }
638
639   destinationDir = file("$jalviewDir/$packageDir")
640   archiveName = rootProject.name+".jar"
641
642   exclude "cache*/**"
643   exclude "*.jar"
644   exclude "*.jar.*"
645   exclude "**/*.jar"
646   exclude "**/*.jar.*"
647
648   inputs.dir("$classes")
649   outputs.file("$jalviewDir/$packageDir/$archiveName")
650 }
651
652 task copyJars(type: Copy) {
653   from fileTree("$classes").include("**/*.jar").include("*.jar").files
654   into "$jalviewDir/$packageDir"
655 }
656
657 // doing a Sync instead of Copy as Copy doesn't deal with "outputs" very well
658 task syncJars(type: Sync) {
659   from fileTree("$jalviewDir/$libDistDir").include("**/*.jar").include("*.jar").files
660   into "$jalviewDir/$packageDir"
661   preserve {
662     include jar.archiveName
663   }
664 }
665
666 task makeDist {
667   group = "build"
668   description = "Put all required libraries in dist"
669   // order of "cleanPackageDir", "copyJars", "jar" important!
670   jar.mustRunAfter cleanPackageDir
671   syncJars.mustRunAfter cleanPackageDir
672   dependsOn cleanPackageDir
673   dependsOn syncJars
674   dependsOn jar
675   outputs.dir("$jalviewDir/$packageDir")
676 }
677
678 task cleanDist {
679   dependsOn cleanPackageDir
680   dependsOn cleanTest
681   dependsOn clean
682 }
683
684 shadowJar {
685   group = "distribution"
686   dependsOn makeDist
687   from ("$jalviewDir/$libDistDir") {
688     include("*.jar")
689   }
690   mainClassName = shadowJarMainClass
691   mergeServiceFiles()
692   classifier = "all-"+JAVA_VERSION
693   minimize()
694 }
695
696 task getdownWebsite() {
697   group = "distribution"
698   description = "Create the getdown minimal app folder, and website folder for this version of jalview. Website folder also used for offline app installer"
699   dependsOn makeDist
700   def getdownWebsiteResourceFilenames = []
701   def getdownTextString = ""
702   def getdownResourceDir = project.ext.getdownResourceDir
703   def getdownAppDir = project.ext.getdownAppDir
704   def getdownResourceFilenames = []
705   doFirst {
706     // go through properties looking for getdown_txt_...
707     def props = project.properties.sort { it.key }
708     props.put("getdown_txt_java_min_version", getdown_alt_java_min_version)
709     props.put("getdown_txt_multi_java_location", getdown_alt_multi_java_location)
710
711     if (getdown_local == "true") {
712       getdown_app_base = file(getdownWebsiteDir).toURI().toString()
713     }
714     props.put("getdown_txt_appbase", getdown_app_base)
715     props.each{ prop, val ->
716       if (prop.startsWith("getdown_txt_") && val != null) {
717         if (prop.startsWith("getdown_txt_multi_")) {
718           def key = prop.substring(18)
719           val.split(",").each{ v ->
720             def line = key + " = " + v + "\n"
721             getdownTextString += line
722           }
723         } else {
724           // file values rationalised
725           if (val.indexOf('/') > -1) {
726             def r = null
727             if (val.indexOf('/') == 0) {
728               // absolute path
729               r = file(val)
730             } else if (val.indexOf('/') > 0) {
731               // relative path (relative to jalviewDir)
732               r = file( jalviewDir + '/' + val )
733             }
734             if (r.exists()) {
735               val = getdown_resource_dir + '/' + r.getName()
736               getdownWebsiteResourceFilenames += val
737               getdownResourceFilenames += r.getPath()
738             }
739           }
740           def line = prop.substring(12) + " = " + val + "\n"
741           getdownTextString += line
742         }
743       }
744     }
745
746     getdownWebsiteResourceFilenames.each{ filename ->
747       getdownTextString += "resource = "+filename+"\n"
748     }
749     getdownResourceFilenames.each{ filename ->
750       copy {
751         from filename
752         into project.ext.getdownResourceDir
753       }
754     }
755
756     def codeFiles = []
757     makeDist.outputs.files.each{ f ->
758       if (f.isDirectory()) {
759         def files = fileTree(dir: f, include: ["*"]).getFiles()
760         codeFiles += files
761       } else if (f.exists()) {
762         codeFiles += f
763       }
764     }
765     codeFiles.sort().each{f ->
766       def line = "code = " + getdown_app_dir + '/' + f.getName() + "\n"
767       getdownTextString += line
768       copy {
769         from f.getPath()
770         into project.ext.getdownAppDir
771       }
772     }
773
774     // NOT USING MODULES YET, EVERYTHING SHOULD BE IN dist
775     /*
776      if (JAVA_VERSION.equals("11")) {
777      def j11libFiles = fileTree(dir: "$jalviewDir/$j11libDir", include: ["*.jar"]).getFiles()
778      j11libFiles.sort().each{f ->
779      def line = "code = " + getdown_j11lib_dir + '/' + f.getName() + "\n"
780      getdownTextString += line
781      copy {
782      from f.getPath()
783      into project.ext.getdownJ11libDir
784      }
785      }
786      }
787      */
788
789     // getdown-launcher.jar should not be in main application class path so the main application can move it when updated.  Listed as a resource so it gets updated.
790     //getdownTextString += "class = " + file(getdownLauncher).getName() + "\n"
791     getdownTextString += "resource = " + file(getdownLauncher).getName() + "\n"
792     getdownTextString += "class = " + mainClass + "\n"
793
794     def getdown_txt = file(project.ext.getdownWebsiteDir + "/getdown.txt")
795     getdown_txt.write(getdownTextString)
796
797     copy {
798       from getdown_txt
799       into project.ext.getdownFilesDir
800     }
801
802     copy {
803       from getdownLauncher
804       into project.ext.getdownFilesDir
805     }
806
807     copy {
808       from getdownLauncher
809       into project.ext.getdownWebsiteDir
810     }
811
812     copy {
813       from jalviewDir + '/' + project.getProperty('getdown_txt_ui.background_image')
814       from jalviewDir + '/' + project.getProperty('getdown_txt_ui.error_background')
815       from jalviewDir + '/' + project.getProperty('getdown_txt_ui.progress_image')
816       from jalviewDir + '/' + project.getProperty('getdown_txt_ui.icon')
817       from jalviewDir + '/' + project.getProperty('getdown_txt_ui.mac_dock_icon')
818       into project.ext.getdownFilesDir + '/' + getdown_resource_dir
819     }
820   }
821
822   inputs.dir(jalviewDir + '/' + packageDir)
823   outputs.dir(project.ext.getdownWebsiteDir)
824   outputs.dir(project.ext.getdownFilesDir)
825 }
826
827 task getdownDigest(type: JavaExec) {
828   group = "distribution"
829   description = "Digest the getdown website folder"
830   dependsOn getdownWebsite
831   classpath = files(jalviewDir + '/' + getdown_core, jalviewDir+'/'+getdown_launcher)
832   main = "com.threerings.getdown.tools.Digester"
833   args project.ext.getdownWebsiteDir
834   inputs.dir(project.ext.getdownWebsiteDir)
835   outputs.file(project.ext.getdownWebsiteDir + '/' + "digest2.txt")
836 }
837
838 task getdown() {
839   group = "distribution"
840   description = "Create the minimal and full getdown app folder for installers and website and create digest file"
841   dependsOn getdownDigest
842 }
843
844 clean {
845   delete project.ext.getdownWebsiteDir
846   delete project.ext.getdownFilesDir
847 }
848
849 install4j {
850   def install4jHomeDir = "/opt/install4j"
851   def hostname = "hostname".execute().text.trim()
852   if (hostname.equals("jv-bamboo")) {
853     install4jHomeDir = System.getProperty("user.home")+"/buildtools/install4j"
854   } else if (OperatingSystem.current().isMacOsX()) {
855     install4jHomeDir = '/Applications/install4j.app/Contents/Resources/app'
856     if (! file(install4jHomeDir).exists()) {
857       install4jHomeDir = System.getProperty("user.home")+install4jHomeDir
858     }
859   } else if (OperatingSystem.current().isLinux()) {
860     install4jHomeDir = System.getProperty("user.home")+"/buildtools/install4j"
861   }
862   installDir = file(install4jHomeDir)
863   mediaTypes = Arrays.asList(install4jMediaTypes.split(","))
864   if (install4jFaster.equals("true")) {
865     faster = true
866   }
867 }
868
869 def install4jConf
870 def macosJavaVMDir
871 def macosJavaVMTgz
872 def windowsJavaVMDir
873 def windowsJavaVMTgz
874 def install4jDir = "$jalviewDir/$install4jResourceDir"
875 def install4jConfFile = "jalview-installers-java"+JAVA_VERSION+".install4j"
876 install4jConf = "$install4jDir/$install4jConfFile"
877
878 task copyInstall4jTemplate(type: Copy) {
879   macosJavaVMDir = System.env.HOME+"/buildtools/jre/openjdk-java_vm/getdown/macos-jre"+JAVA_VERSION+"/jre"
880   macosJavaVMTgz = System.env.HOME+"/buildtools/jre/openjdk-java_vm/install4j/tgz/macos-jre"+JAVA_VERSION+".tar.gz"
881   windowsJavaVMDir = System.env.HOME+"/buildtools/jre/openjdk-java_vm/getdown/windows-jre"+JAVA_VERSION+"/jre"
882   windowsJavaVMTgz = System.env.HOME+"/buildtools/jre/openjdk-java_vm/install4j/tgz/windows-jre"+JAVA_VERSION+".tar.gz"
883   from (install4jDir) {
884     include install4jTemplate
885     rename (install4jTemplate, install4jConfFile)
886     filter(ReplaceTokens, beginToken: '', endToken: '', tokens: ['9999999999': JAVA_VERSION])
887     filter(ReplaceTokens, beginToken: '$$', endToken: '$$',
888       tokens: [
889         'JAVA_VERSION': JAVA_VERSION,
890         'JAVA_INTEGER_VERSION': JAVA_INTEGER_VERSION,
891         'VERSION': JALVIEW_VERSION,
892         'MACOS_JAVA_VM_DIR': macosJavaVMDir,
893         'MACOS_JAVA_VM_TGZ': macosJavaVMTgz,
894         'WINDOWS_JAVA_VM_DIR': windowsJavaVMDir,
895         'WINDOWS_JAVA_VM_TGZ': windowsJavaVMTgz,
896         'INSTALL4JINFOPLISTFILEASSOCIATIONS': install4jInfoPlistFileAssociations,
897         'COPYRIGHT_MESSAGE': install4jCopyrightMessage,
898         'MACOS_BUNDLE_ID': install4jMacOSBundleId
899       ]
900     )
901     if (OSX_KEYPASS=="") {
902       filter(ReplaceTokens, beginToken: 'codeSigning macEnabled="', endToken: '"', tokens: ['true':'codeSigning macEnabled="false"'])
903       filter(ReplaceTokens, beginToken: 'runPostProcessor="true" ',endToken: 'Processor', tokens: ['post':'runPostProcessor="false" postProcessor'])
904     }
905   }
906   into install4jDir
907   outputs.files(install4jConf)
908
909   doLast {
910     // include file associations in installer
911     def installerFileAssociationsXml = file("$install4jDir/$install4jInstallerFileAssociations").text
912     ant.replaceregexp(
913       byline: false,
914       flags: "s",
915       match: '<action name="EXTENSIONS_REPLACED_BY_GRADLE".*?</action>',
916       replace: installerFileAssociationsXml,
917       file: install4jConf
918     )
919     /*
920     // include uninstaller applescript app files in dmg
921     def installerDMGUninstallerXml = file("$install4jDir/$install4jDMGUninstallerAppFiles").text
922     ant.replaceregexp(
923       byline: false,
924       flags: "s",
925       match: '<file name="UNINSTALL_OLD_JALVIEW_APP_REPLACED_IN_GRADLE" file=.*?>',
926       replace: installerDMGUninstallerXml,
927       file: install4jConf
928     )
929     */
930   }
931 }
932
933 task installers(type: com.install4j.gradle.Install4jTask) {
934   group = "distribution"
935   description = "Create the install4j installers"
936   dependsOn getdown
937   dependsOn copyInstall4jTemplate
938   projectFile = file(install4jConf)
939   println("Using projectFile "+projectFile)
940   variables = [majorVersion: version.substring(2, 11), build: 001, OSX_KEYSTORE: OSX_KEYSTORE, JSIGN_SH: JSIGN_SH]
941   destination = "$jalviewDir/$install4jBuildDir/$JAVA_VERSION"
942   buildSelected = true
943
944   if (OSX_KEYPASS) {
945     macKeystorePassword=OSX_KEYPASS
946     
947   }
948   
949   inputs.dir(project.ext.getdownWebsiteDir)
950   inputs.file(install4jConf)
951   inputs.dir(macosJavaVMDir)
952   inputs.dir(windowsJavaVMDir)
953   outputs.dir("$jalviewDir/$install4jBuildDir/$JAVA_VERSION")
954 }
955
956 clean {
957   delete install4jConf
958 }