File: build.gradle

package info (click to toggle)
jalview 2.11.4.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 445,392 kB
  • sloc: java: 365,549; xml: 2,989; sh: 1,511; perl: 336; lisp: 139; python: 116; makefile: 81; haskell: 60
file content (2251 lines) | stat: -rw-r--r-- 68,095 bytes parent folder | download
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
/* Convention for properties.  Read from gradle.properties, use lower_case_underlines for property names.
 * For properties set within build.gradle, use camelCaseNoSpace.
 */
import org.apache.tools.ant.filters.ReplaceTokens
import org.gradle.internal.os.OperatingSystem
import org.gradle.plugins.ide.internal.generator.PropertiesPersistableConfigurationObject
import org.gradle.api.internal.PropertiesTransformer
import org.gradle.util.ConfigureUtil
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.regex.Matcher
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import groovy.transform.ExternalizeMethods
import groovy.util.XmlParser
import groovy.xml.XmlUtil
import groovy.json.JsonBuilder

buildscript {
  repositories {
    mavenCentral()
    mavenLocal()
  }
}


plugins {
  id 'java'
  id 'application'
}

repositories {
  mavenCentral()
  mavenLocal()
}



// in ext the values are cast to Object. Ensure string values are cast as String (and not GStringImpl) for later use
def string(Object o) {
  return o == null ? "" : o.toString()
}

def overrideProperties(String propsFileName, boolean output = false) {
  if (propsFileName == null) {
    return
  }
  def propsFile = file(propsFileName)
  if (propsFile != null && propsFile.exists()) {
    println("Using properties from file '${propsFileName}'")
    try {
      def p = new Properties()
      def localPropsFIS = new FileInputStream(propsFile)
      p.load(localPropsFIS)
      localPropsFIS.close()
      p.each {
        key, val -> 
          def oldval
          if (project.hasProperty(key)) {
            oldval = project.findProperty(key)
            project.setProperty(key, val)
            if (output) {
              println("Overriding property '${key}' ('${oldval}') with ${file(propsFile).getName()} value '${val}'")
            }
          } else {
            ext.setProperty(key, val)
            if (output) {
              println("Setting ext property '${key}' with ${file(propsFile).getName()}s value '${val}'")
            }
          }
      }
    } catch (Exception e) {
      println("Exception reading local.properties")
      e.printStackTrace()
    }
  }
}

ext {
  jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
  jalviewDirRelativePath = jalviewDir

  // Verbose and maybe not efficient hack to put the changelog date into the
  // "date" variable, which will be used to insert e.g. years in doc files.
  // This is to make the build reproducible.
  def outBAdate = new ByteArrayOutputStream()
  exec {
    commandLine 'dpkg-parsechangelog', '-Stimestamp'
    standardOutput = outBAdate
  }
  dateWithEOL = outBAdate.toString()
  dateWithoutEOL = dateWithEOL.substring(0, dateWithEOL.length() - 1)

  def outBA = new ByteArrayOutputStream()
  exec {
    commandLine 'date', '--utc', "--date=@${dateWithoutEOL}", '+"%d/%m/%Y-%H:%M:%S"'
    standardOutput = outBA
  }
  toParseWithEOLAndQuotes = outBA.toString()
  toParseWithoutEOLAndQuotes = toParseWithEOLAndQuotes.substring(1, toParseWithEOLAndQuotes.length() - 2)
  date = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss").parse(toParseWithoutEOLAndQuotes)

  // default to "default". Currently only has different cosmetics for "develop", "release", "default"
  propertiesChannelName = "default"
  channelDirName = propertiesChannelName
  channelDir = string("${jalviewDir}/${channel_properties_dir}/${channelDirName}")
  channelGradleProperties = string("${channelDir}/channel_gradle.properties")
  channelPropsFile = string("${channelDir}/${resource_dir}/${channel_props}")
  overrideProperties(channelGradleProperties, false)
  // local build environment properties
  // can be "projectDir/local.properties"
  overrideProperties("${projectDir}/local.properties", true)
  // or "../projectDir_local.properties"
  overrideProperties(projectDir.getParent() + "/" + projectDir.getName() + "_local.properties", true)

  ////  
  // Import releaseProps from the RELEASE file
  // or a file specified via JALVIEW_RELEASE_FILE if defined
  // Expect jalview.version and target release branch in jalview.release        
  releaseProps = new Properties();
  def releasePropFile = findProperty("JALVIEW_RELEASE_FILE");
  def defaultReleasePropFile = "${jalviewDirAbsolutePath}/RELEASE";
  try {
    (new File(releasePropFile!=null ? releasePropFile : defaultReleasePropFile)).withInputStream { 
     releaseProps.load(it)
    }
  } catch (Exception fileLoadError) {
    throw new Error("Couldn't load release properties file "+(releasePropFile==null ? defaultReleasePropFile : "from custom location: releasePropFile"),fileLoadError);
  }
  ////
  // Set JALVIEW_VERSION if it is not already set
  if (findProperty("JALVIEW_VERSION")==null || "".equals(JALVIEW_VERSION)) {
    JALVIEW_VERSION = releaseProps.get("jalview.version")
  }
  println("JALVIEW_VERSION is set to '${JALVIEW_VERSION}'")
  
  J2S_ENABLED = (project.hasProperty('j2s.compiler.status') && project['j2s.compiler.status'] != null && project['j2s.compiler.status'] == "enable")
  if (J2S_ENABLED) {
    println("J2S ENABLED")
  } 
  /* *-/
  System.properties.sort { it.key }.each {
    key, val -> println("SYSTEM PROPERTY ${key}='${val}'")
  }
  /-* *-/
  if (false && IN_ECLIPSE) {
    jalviewDir = jalviewDirAbsolutePath
  }
  */

  // datestamp
  buildDate = new Date().format("yyyyMMdd")

  // essentials
  bareSourceDir = string(source_dir)
  sourceDir = string("${jalviewDir}/${bareSourceDir}")
  resourceDir = string("${jalviewDir}/${resource_dir}")
  bareTestSourceDir = string(test_source_dir)
  testDir = string("${jalviewDir}/${bareTestSourceDir}")

  classesDir = string("${jalviewDir}/${classes_dir}")

  testSourceDir = testDir
  testClassesDir = "${jalviewDir}/${test_output_dir}"

  channelSuffix = ""
  backgroundImageText = BACKGROUNDIMAGETEXT
  buildDist = true
  buildProperties = null

  reportRsyncCommand = false
  jvlChannelName = CHANNEL.toLowerCase()

  applicationName = "${jalview_name}"
  JALVIEW_VERSION_UNDERSCORES = JALVIEW_VERSION.replaceAll("\\.", "_")
  hugoDataJsonFile = file("${jalviewDir}/${hugo_build_dir}/${hugo_data_installers_dir}/installers-${JALVIEW_VERSION_UNDERSCORES}.json")
  hugoArchiveMdFile = file("${jalviewDir}/${hugo_build_dir}/${hugo_version_archive_dir}/Version-${JALVIEW_VERSION_UNDERSCORES}/_index.md")

  /* compile without modules -- using classpath libraries
  modules_compileClasspath = fileTree(dir: "${jalviewDir}/${j11modDir}", include: ["*.jar"])
  modules_runtimeClasspath = modules_compileClasspath
  */

  additional_compiler_args = []
  // configure classpath/args for j8/j11 compilation
  if (JAVA_VERSION.equals("1.8")) {
    JAVA_INTEGER_VERSION = string("8")
    //libDir = j8libDir
    libDir = "${jalviewDir}/cpJars"
    libDistDir = "${jalviewDir}/cpJars"
    compile_source_compatibility = 1.8
    compile_target_compatibility = 1.8
  } else if (JAVA_VERSION.equals("11")) {
    JAVA_INTEGER_VERSION = string("11")
    libDir = "${jalviewDir}/cpJars"
    libDistDir = "${jalviewDir}/cpJars"
    compile_source_compatibility = 11
    compile_target_compatibility = 11
    /* compile without modules -- using classpath libraries
    additional_compiler_args += [
    '--module-path', modules_compileClasspath.asPath,
    '--add-modules', j11modules
    ]
     */
  } else if (JAVA_VERSION.equals("17")) {
    JAVA_INTEGER_VERSION = string("17")
    libDir = "${jalviewDir}/cpJars"
    libDistDir = "${jalviewDir}/cpJars"
    compile_source_compatibility = 17
    compile_target_compatibility = 17
    /* compile without modules -- using classpath libraries
    additional_compiler_args += [
    '--module-path', modules_compileClasspath.asPath,
    '--add-modules', j11modules
    ]
     */
  } else {
    throw new GradleException("JAVA_VERSION=${JAVA_VERSION} not currently supported by Jalview")
  }


  resourceBuildDir = string("${buildDir}/resources")
  resourcesBuildDir = string("${resourceBuildDir}/resources_build")
  helpBuildDir = string("${resourceBuildDir}/help_build")
  docBuildDir = string("${resourceBuildDir}/doc_build")

  if (buildProperties == null) {
    buildProperties = string("${resourcesBuildDir}/${build_properties_file}")
  }
  buildingHTML = string("${jalviewDir}/${doc_dir}/building.html")
  helpParentDir = string("${jalviewDir}/${help_parent_dir}")
  helpSourceDir = string("${helpParentDir}/${help_dir}")
  helpFile = string("${helpBuildDir}/${help_dir}/help.jhm")

  convertBinary = null
  convertBinaryExpectedLocation = imagemagick_convert
  if (convertBinaryExpectedLocation.startsWith("~/")) {
    convertBinaryExpectedLocation = System.getProperty("user.home") + convertBinaryExpectedLocation.substring(1)
  }
  if (file(convertBinaryExpectedLocation).exists()) {
    convertBinary = convertBinaryExpectedLocation
  }

  relativeBuildDir = file(jalviewDirAbsolutePath).toPath().relativize(buildDir.toPath())
  jalviewjsBuildDir = string("${relativeBuildDir}/jalviewjs")
  jalviewjsSiteDir = string("${jalviewjsBuildDir}/${jalviewjs_site_dir}")
    jalviewjsTransferSiteJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_js")
  jalviewjsTransferSiteLibDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_lib")
  jalviewjsTransferSiteSwingJsDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_swingjs")
  jalviewjsTransferSiteCoreDir = string("${jalviewjsBuildDir}/tmp/${jalviewjs_site_dir}_core")
  jalviewjsJalviewCoreHtmlFile = string("")
  jalviewjsJalviewCoreName = string(jalviewjs_core_name)
  jalviewjsCoreClasslists = []
  jalviewjsJalviewTemplateName = string(jalviewjs_name)
  jalviewjsJ2sSettingsFileName = string("${jalviewDir}/${jalviewjs_j2s_settings}")
  jalviewjsJ2sAltSettingsFileName = string("${jalviewDir}/${jalviewjs_j2s_alt_settings}")
  jalviewjsJ2sProps = null
  jalviewjsJ2sPlugin = jalviewjs_j2s_plugin
  jalviewjsStderrLaunchFilename = "${jalviewjsSiteDir}/"+(file(jalviewjs_stderr_launch).getName())

  jalviewjsChromiumUserDir = "${jalviewjsBuildDir}/${jalviewjs_chromium_user_dir}"
  jalviewjsChromiumProfileDir = "${ext.jalviewjsChromiumUserDir}/${jalviewjs_chromium_profile_name}"

  // ENDEXT
}


sourceSets {
  main {
    java {
      srcDirs sourceDir
      outputDir = file(classesDir)
      exclude "**/appletgui/**"
      exclude "**/AppletPDBViewer.java"
      exclude "**/AppletPDBCanvas.java"
      exclude "**/javascript/J*.java"
      exclude "**/javascript/MouseOverListener.java"
      exclude "**/javascript/MouseOverStructureListener.java"
      exclude "**/JalviewLite*"
    }

    resources {
      srcDirs = [ resourcesBuildDir, docBuildDir, helpBuildDir ]
    }

    compileClasspath = files(sourceSets.main.java.outputDir)
    compileClasspath += fileTree(dir: "${libDir}", include: ["*.jar"])

    runtimeClasspath = compileClasspath
    runtimeClasspath += files(sourceSets.main.resources.srcDirs)
  }

  test {
    java {
      srcDirs testSourceDir
      outputDir = file(testClassesDir)
      exclude "**/CommandLineOperationsNG.java"
      exclude "**/JalviewLiteTest.java"
    }

    resources {
      srcDirs = sourceSets.main.resources.srcDirs
    }

    compileClasspath = files( sourceSets.test.java.outputDir )
    compileClasspath += sourceSets.main.compileClasspath

    runtimeClasspath = compileClasspath
    runtimeClasspath += files(sourceSets.test.resources.srcDirs)
  }

}


/* hack to change eclipse prefs in .settings files other than org.eclipse.jdt.core.prefs */
// Class to allow updating arbitrary properties files
class PropertiesFile extends PropertiesPersistableConfigurationObject {
  public PropertiesFile(PropertiesTransformer t) { super(t); }
  @Override protected void load(Properties properties) { }
  @Override protected void store(Properties properties) { }
  @Override protected String getDefaultResourceName() { return ""; }
  // This is necessary, because PropertiesPersistableConfigurationObject fails
  // if no default properties file exists.
  @Override public void loadDefaults() { load(new StringBufferInputStream("")); }
}

// Task to update arbitrary properties files (set outputFile)
class PropertiesFileTask extends PropertiesGeneratorTask<PropertiesFile> {
  private final PropertiesFileContentMerger file;
  public PropertiesFileTask() { file = new PropertiesFileContentMerger(getTransformer()); }
  protected PropertiesFile create() { return new PropertiesFile(getTransformer()); }
  protected void configure(PropertiesFile props) {
    file.getBeforeMerged().execute(props); file.getWhenMerged().execute(props);
  }
  public void file(Closure closure) { ConfigureUtil.configure(closure, file); }
}


compileJava {
  // JBP->BS should the print statement in doFirst refer to compile_target_compatibility ?
  sourceCompatibility = compile_source_compatibility
  targetCompatibility = compile_target_compatibility
  options.compilerArgs += additional_compiler_args
  options.encoding = "UTF-8"
  excludes = ["**/GetdownLauncherUpdate.java"]
  doFirst {
    print ("Setting target compatibility to "+compile_target_compatibility+"\n")
  }

}


compileTestJava {
  sourceCompatibility = compile_source_compatibility
  targetCompatibility = compile_target_compatibility
  options.compilerArgs += additional_compiler_args
  doFirst {
    print ("Setting target compatibility to "+targetCompatibility+"\n")
  }
}


clean {
  doFirst {
    delete sourceSets.main.java.outputDir
  }
}


cleanTest {
  doFirst {
    delete sourceSets.test.java.outputDir
  }
}


// format is a string like date.format("dd MMMM yyyy")
def getDate(format) {
  return date.format(format)
}


task copyDocs(type: Copy) {
  def inputDir = "${jalviewDir}/${doc_dir}"
  def outputDir = "${docBuildDir}/${doc_dir}"
  from(inputDir) {
    include('**/*.txt')
    include('**/*.md')
    include('**/*.html')
    include('**/*.xml')
    filter(ReplaceTokens,
      beginToken: '$$',
      endToken: '$$',
      tokens: [
        'Version-Rel': JALVIEW_VERSION,
        'Year-Rel': getDate("yyyy")
      ]
    )
  }
  from(inputDir) {
    exclude('**/*.txt')
    exclude('**/*.md')
    exclude('**/*.html')
    exclude('**/*.xml')
  }
  into outputDir

  inputs.dir(inputDir)
  outputs.dir(outputDir)
}


task convertMdFiles {
  dependsOn copyDocs
  def mdFiles = fileTree(dir: docBuildDir, include: "**/*.md")
  def cssFile = file("${jalviewDir}/${flexmark_css}")

  inputs.files(mdFiles)
  inputs.file(cssFile)

  def htmlFiles = []
  mdFiles.each { mdFile ->
    def htmlFilePath = mdFile.getPath().replaceAll(/\..*?$/, ".html")
    htmlFiles.add(file(htmlFilePath))
  }
  outputs.files(htmlFiles)
}


def hugoTemplateSubstitutions(String input, Map extras=null) {
  def replacements = [
    DATE: getDate("yyyy-MM-dd"),
    CHANNEL: propertiesChannelName,
    APPLICATION_NAME: applicationName,
    GIT_HASH: gitHash,
    GIT_BRANCH: gitBranch,
    VERSION: JALVIEW_VERSION,
    JAVA_VERSION: JAVA_VERSION,
    VERSION_UNDERSCORES: JALVIEW_VERSION_UNDERSCORES,
    DRAFT: "false",
    JVL_HEADER: ""
  ]
  def output = input
  if (extras != null) {
    extras.each{ k, v ->
      output = output.replaceAll("__${k}__", ((v == null)?"":v))
    }
  }
  replacements.each{ k, v ->
    output = output.replaceAll("__${k}__", ((v == null)?"":v))
  }
  return output
}

def mdFileComponents(File mdFile, def dateOnly=false) {
  def map = [:]
  def content = ""
  if (mdFile.exists()) {
    def inFrontMatter = false
    def firstLine = true
    mdFile.eachLine { line ->
      if (line.matches("---")) {
        def prev = inFrontMatter
        inFrontMatter = firstLine
        if (inFrontMatter != prev)
          return false
      }
      if (inFrontMatter) {
        if (dateOnly && map["date"] != null) {
          return false
        }
      } else {
        if (dateOnly)
          return false
        content += line+"\n"
      }
      firstLine = false
    }
  }
  return dateOnly ? map["date"] : [map, content]
}

def setReleaseAndWhatsNew(File whatsnewMdFile, File releaseMdFile) {
  if (CHANNEL != "") {
    // we may have a version string that has additional bits vs the actual release version
    if (CHANNEL != "RELEASE")
    {
      var nearestVersion = "${JALVIEW_VERSION_UNDERSCORES}"
      println "Stripping rc/test/etc for ${nearestVersion}"
      nearestVersion = nearestVersion.replaceAll(~/-?(d|rc|test|develop|dev).*/,"")
      var nearestMd = file("${jalviewDir}/${whatsnew_dir}/whatsnew-${nearestVersion}.md")
      println "Looking in ${nearestMd}"
      if (nearestMd.exists()) {
        whatsnewMdFile = nearestMd
        releaseMdFile = file("${jalviewDir}/${releases_dir}/release-${nearestVersion}.md")
      }
    }
  }
  return [whatsnewMdFile,releaseMdFile]
}

task hugoTemplates {
  group "website"
  description "Create partially populated md pages for hugo website build"

  def hugoTemplatesDir = file("${jalviewDir}/${hugo_templates_dir}")
  def hugoBuildDir = "${jalviewDir}/${hugo_build_dir}"
  def templateFiles = fileTree(dir: hugoTemplatesDir)
  def releaseMdFile = file("${jalviewDir}/${releases_dir}/release-${JALVIEW_VERSION_UNDERSCORES}.md")
  def whatsnewMdFile = file("${jalviewDir}/${whatsnew_dir}/whatsnew-${JALVIEW_VERSION_UNDERSCORES}.md")
  def oldJvlFile = file("${jalviewDir}/${hugo_old_jvl}")
  def jalviewjsFile = file("${jalviewDir}/${hugo_jalviewjs}")

  doFirst {
    // specific release template for version archive
    def changes = ""
    def whatsnew = null
    def givenDate = null
    def givenChannel = null
    def givenVersion = null
    
    if (CHANNEL!="") {
      (whatsnewMdFile, releaseMdFile) = setReleaseAndWhatsNew(whatsnewMdFile, releaseMdFile)

      def (map, content) = mdFileComponents(releaseMdFile)
      givenDate = map.date
      givenChannel = map.channel
      givenVersion = map.version
      changes = content
      if (CHANNEL=="RELEASE" && givenVersion != null && givenVersion != JALVIEW_VERSION) {
        throw new GradleException("'version' header (${givenVersion}) found in ${releaseMdFile} does not match JALVIEW_VERSION (${JALVIEW_VERSION})")
      }
      if (whatsnewMdFile.exists())
        whatsnew = whatsnewMdFile.text
    }

    def oldJvl = oldJvlFile.exists() ? oldJvlFile.collect{it} : []
    def jalviewjsLink = jalviewjsFile.exists() ? jalviewjsFile.collect{it} : []

    def changesHugo = null
    if (changes != null) {
      changesHugo = '<div class="release_notes">\n\n'
      def inSection = false
      changes.eachLine { line ->
        changesHugo += line+"\n"
      }
      if (inSection) {
        changesHugo += "\n</div>\n\n"
      }
      changesHugo += '</div>'
    }

    templateFiles.each{ templateFile ->
      def newFileName = string(hugoTemplateSubstitutions(templateFile.getName()))
      def relPath = hugoTemplatesDir.toPath().relativize(templateFile.toPath()).getParent()
      def newRelPathName = hugoTemplateSubstitutions( relPath.toString() )

      def outPathName = string("${hugoBuildDir}/$newRelPathName")

      copy {
        from templateFile
        rename(templateFile.getName(), newFileName)
        into outPathName
      }

      def newFile = file("${outPathName}/${newFileName}".toString())
      def content = newFile.text
      newFile.text = hugoTemplateSubstitutions(content,
        [
          WHATSNEW: whatsnew,
          CHANGES: changesHugo,
          DATE: givenDate == null ? "" : givenDate.format("yyyy-MM-dd"),
          DRAFT: givenDate == null ? "true" : "false",
          JALVIEWJSLINK: jalviewjsLink.contains(JALVIEW_VERSION) ? "true" : "false",
          JVL_HEADER: oldJvl.contains(JALVIEW_VERSION) ? "jvl: true" : ""
        ]
      )
    }

  }

  inputs.file(oldJvlFile)
  inputs.dir(hugoTemplatesDir)
  inputs.property("JALVIEW_VERSION", { JALVIEW_VERSION })
  inputs.property("CHANNEL", { CHANNEL })
}

def getMdDate(File mdFile) {
  return mdFileComponents(mdFile, true)
}

def getMdSections(String content) {
  def sections = [:]
  def sectionContent = ""
  def sectionName = null
  if (sectionContent != null) {
    sections[sectionName] = sectionContent
  }
  return sections
}


task copyHelp(type: Copy) {
  def inputDir = helpSourceDir
  def outputDir = "${helpBuildDir}/${help_dir}"
  from(inputDir) {
    include('**/*.txt')
    include('**/*.md')
    include('**/*.html')
    include('**/*.hs')
    include('**/*.xml')
    include('**/*.jhm')
    filter(ReplaceTokens,
      beginToken: '$$',
      endToken: '$$',
      tokens: [
        'Version-Rel': JALVIEW_VERSION,
        'Year-Rel': getDate("yyyy")
      ]
    )
  }
  from(inputDir) {
    exclude('**/*.txt')
    exclude('**/*.md')
    exclude('**/*.html')
    exclude('**/*.hs')
    exclude('**/*.xml')
    exclude('**/*.jhm')
  }
  into outputDir

  inputs.dir(inputDir)
  outputs.files(helpFile)
  outputs.dir(outputDir)
}


task releasesTemplates {
  group "help"
  description "Recreate whatsNew.html and releases.html from markdown files and templates in help"

  dependsOn copyHelp

  def releasesTemplateFile = file("${jalviewDir}/${releases_template}")
  def whatsnewTemplateFile = file("${jalviewDir}/${whatsnew_template}")
  def releasesHtmlFile = file("${helpBuildDir}/${help_dir}/${releases_html}")
  def whatsnewHtmlFile = file("${helpBuildDir}/${help_dir}/${whatsnew_html}")
  def releasesMdDir = "${jalviewDir}/${releases_dir}"
  def whatsnewMdDir = "${jalviewDir}/${whatsnew_dir}"

  inputs.file(releasesTemplateFile)
  inputs.file(whatsnewTemplateFile)
  inputs.dir(releasesMdDir)
  inputs.dir(whatsnewMdDir)
  outputs.file(releasesHtmlFile)
  outputs.file(whatsnewHtmlFile)
}


task copyResources(type: Copy) {
  group = "build"
  description = "Copy (and make text substitutions in) the resources dir to the build area"

  def inputDir = resourceDir
  def outputDir = resourcesBuildDir
  from(inputDir) {
    include('**/*.txt')
    include('**/*.md')
    include('**/*.html')
    include('**/*.xml')
    filter(ReplaceTokens,
      beginToken: '$$',
      endToken: '$$',
      tokens: [
        'Version-Rel': JALVIEW_VERSION,
        'Year-Rel': getDate("yyyy")
      ]
    )
  }
  from(inputDir) {
    exclude('**/*.txt')
    exclude('**/*.md')
    exclude('**/*.html')
    exclude('**/*.xml')
  }
  into outputDir

  inputs.dir(inputDir)
  outputs.dir(outputDir)
}

task copyChannelResources(type: Copy) {
  dependsOn copyResources
  group = "build"
  description = "Copy the channel resources dir to the build resources area"

  def inputDir = "${channelDir}/${resource_dir}"
  def outputDir = resourcesBuildDir
  from(inputDir) {
    include(channel_props)
    filter(ReplaceTokens,
      beginToken: '__',
      endToken: '__',
      tokens: [
        'SUFFIX': channelSuffix
      ]
    )
  }
  from(inputDir) {
    exclude(channel_props)
  }
  into outputDir

  inputs.dir(inputDir)
  outputs.dir(outputDir)
}

//task createBuildProperties(type: WriteProperties) {
task createBuildProperties(type: Exec) {
  dependsOn copyResources
  group = "build"
  description = "Create the ${buildProperties} file"
  
  commandLine 'sh', 'debian/write_build_properties_file.sh'
}


task buildIndices(type: JavaExec) {
  dependsOn copyHelp
  classpath = sourceSets.main.compileClasspath
  main = "com.sun.java.help.search.Indexer"
  workingDir = "${helpBuildDir}/${help_dir}"
  def argDir = "html"
  args = [ argDir ]
  inputs.dir("${workingDir}/${argDir}")

  outputs.dir("${classesDir}/doc")
  outputs.dir("${classesDir}/help")
  outputs.file("${workingDir}/JavaHelpSearch/DOCS")
  outputs.file("${workingDir}/JavaHelpSearch/DOCS.TAB")
  outputs.file("${workingDir}/JavaHelpSearch/OFFSETS")
  outputs.file("${workingDir}/JavaHelpSearch/POSITIONS")
  outputs.file("${workingDir}/JavaHelpSearch/SCHEMA")
  outputs.file("${workingDir}/JavaHelpSearch/TMAP")
}

task buildResources {
  dependsOn copyResources
  dependsOn copyChannelResources
  dependsOn createBuildProperties
}

task prepare {
  dependsOn buildResources
  dependsOn copyDocs
  dependsOn copyHelp
  dependsOn releasesTemplates
  dependsOn convertMdFiles
  dependsOn buildIndices
}


compileJava.dependsOn prepare
run.dependsOn compileJava
compileTestJava.dependsOn compileJava



test {
  group = "Verification"
  description = "Runs all testTaskN tasks)"

    dependsOn testClasses

  // not running tests in this task
  exclude "**/*"
}
/* testTask0 is the main test task */
task testTask0(type: Test) {
  group = "Verification"
  description = "The main test task. Runs all non-testTaskN-labelled tests (unless excluded)"
  useTestNG() {
    includeGroups testng_groups.split(",")
    excludeGroups "Network"
    tasks.withType(Test).matching {it.name.startsWith("testTask") && it.name != name}.all {t -> excludeGroups t.name}
    preserveOrder true
    useDefaultListeners=true
  }

  include '**/AtomSpecModelTest.class'
  include '**/AtomSpecTest.class'
  include '**/ClustalFileTest.class'
  include '**/ConcurrentModificationTest.class'
  include '**/ConditionTest.class'
  include '**/CustomUrlProviderTest.class'
  include '**/DesktopUrlProviderFactoryTest.class'
  include '**/EmblFlatFileTest.class'
  include '**/EmblXmlSourceTest.class'
  include '**/EnsemblRestClientTest.class'
  include '**/FeatureAttributesTest.class'
  include '**/FeatureMatcherSetTest.class'
  include '**/FeatureMatcherTest.class'
  include '**/FeatureStoreTest.class'
  include '**/FileFormatsTest.class'
  include '**/FileLoaderTest.class'
  include '**/GeneticCodesTest.class'
  include '**/HiddenColumnsCursorTest.class'
  include '**/HiddenColumnsTest.class'
  include '**/IdentifiersUrlProviderTest.class'
  include '**/JalviewColourSchemeTest.class'
  include '**/JalviewFileViewTest.class'
  include '**/JSONUtilsTest.class'
  include '**/JvCacheableInputBoxTest.class'
  include '**/MappedFeaturesTest.class'
  include '**/MatcherTest.class'
  include '**/MathUtilsTest.class'
  include '**/MatrixTest.class'
  include '**/MemorySettingTest.class'
  include '**/MessageManagerTest.class'
  include '**/OverviewDimensionsHideHiddenTest.class'
  include '**/OverviewDimensionsShowHiddenTest.class'
  include '**/PfamFullTest.class'
  include '**/PfamSeedTest.class'
  include '**/PIDModelTest.class'
  include '**/RangeElementsIteratorTest.class'
  include '**/RemoteFormatTest.class'
  include '**/RfamFullTest.class'
  include '**/RfamSeedTest.class'
  include '**/RotatableMatrixTest.class'
  include '**/ScoreMatrixFileTest.class'
  include '**/ScoreMatrixTest.class'
  include '**/ScoreModelsTest.class'
  include '**/SequenceFeaturesTest.class'
  include '**/SequenceOntologyLiteTest.class'
  include '**/SparseDoubleArrayTest.class'
  include '**/SparseMatrixTest.class'
  include '**/SpeciesTest.class'
  include '**/StartRegionIteratorTest.class'
  include '**/StructureMappingTest.class'
  include '**/UrlDownloadClientTest.class'
  include '**/UrlLinkDisplayTest.class'
  include '**/UrlLinkTableModelTest.class'
  include '**/UrlProviderTest.class'
  include '**/VCFReaderTest.class'
  include '**/ViewportRangesTest.class'
  include '**/VisibleContigsIteratorTest.class'
  include '**/VisibleRowsIteratorTest.class'
  exclude 'jalview/gui/**'
}

/* separated tests */
task testTask1(type: Test) {
  group = "Verification"
  description = "Tests that need to be isolated from the main test run"
  useTestNG() {
    includeGroups name
    excludeGroups testng_excluded_groups.split(",")
    preserveOrder true
    useDefaultListeners=true
  }
}

task testTask2(type: Test) {
  group = "Verification"
  description = "Tests that need to be isolated from the main test run"
  useTestNG() {
    includeGroups name
    excludeGroups testng_excluded_groups.split(",")
    preserveOrder true
    useDefaultListeners=true
  }
}
task testTask3(type: Test) {
  group = "Verification"
  description = "Tests that need to be isolated from the main test run"
  useTestNG() {
    includeGroups name
    excludeGroups testng_excluded_groups.split(",")
    preserveOrder true
    useDefaultListeners=true
  }
}

/* insert more testTaskNs here -- change N to next digit or other string */
/*
task testTaskN(type: Test) {
  group = "Verification"
  description = "Tests that need to be isolated from the main test run"
  useTestNG() {
    includeGroups name
    excludeGroups testng_excluded_groups.split(",")
    preserveOrder true
    useDefaultListeners=true
  }
}
*/


/*
 * adapted from https://medium.com/@wasyl/pretty-tests-summary-in-gradle-744804dd676c
 * to summarise test results from all Test tasks
 */
/* START of test tasks results summary */
import groovy.time.TimeCategory
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
rootProject.ext.testsResults = [] // Container for tests summaries

tasks.withType(Test).matching {t -> t.getName().startsWith("testTask")}.all { testTask ->

  // from original test task
    dependsOn testClasses //?

  // run main tests first
  if (!testTask.name.equals("testTask0"))
    testTask.mustRunAfter "testTask0"

  testTask.testLogging { logging ->
    events TestLogEvent.FAILED
//      TestLogEvent.SKIPPED,
//      TestLogEvent.STANDARD_OUT,
//      TestLogEvent.STANDARD_ERROR

    exceptionFormat TestExceptionFormat.FULL
    showExceptions true
    showCauses true
    showStackTraces true
    if (test_output) {
      showStandardStreams true
    }
    info.events = [ TestLogEvent.FAILED ]
  }

  if (OperatingSystem.current().isMacOsX()) {
    testTask.systemProperty "apple.awt.UIElement", "true"
    testTask.environment "JAVA_TOOL_OPTIONS", "-Dapple.awt.UIElement=true"
  }


  ignoreFailures = true // Always try to run all tests for all modules

  afterSuite { desc, result ->
    if (desc.parent)
      return // Only summarize results for whole modules

    def resultsInfo = [testTask.project.name, testTask.name, result, TimeCategory.minus(new Date(result.endTime), new Date(result.startTime)), testTask.reports.html.entryPoint]

    rootProject.ext.testsResults.add(resultsInfo)
  }

  // from original test task
  maxHeapSize = "1024m"

  workingDir = jalviewDir
  def testLaf = project.findProperty("test_laf")
  if (testLaf != null) {
    println("Setting Test LaF to '${testLaf}'")
    systemProperty "laf", testLaf
  }
  def testHiDPIScale = project.findProperty("test_HiDPIScale")
  if (testHiDPIScale != null) {
    println("Setting Test HiDPI Scale to '${testHiDPIScale}'")
    systemProperty "sun.java2d.uiScale", testHiDPIScale
  }
  sourceCompatibility = compile_source_compatibility
  targetCompatibility = compile_target_compatibility
  jvmArgs += additional_compiler_args

  doFirst {
    // this is not perfect yet -- we should only add the commandLineIncludePatterns to the
    // testTasks that include the tests, and exclude all from the others.
    // get --test argument
    filter.commandLineIncludePatterns = test.filter.commandLineIncludePatterns
    // do something with testTask.getCandidateClassFiles() to see if the test should silently finish because of the
    // commandLineIncludePatterns not matching anything.  Instead we are doing setFailOnNoMatchingTests(false) below


  }


  /* don't fail on no matching tests (so --tests will run across all testTasks) */
  testTask.filter.setFailOnNoMatchingTests(false)

  /* ensure the "test" task dependsOn all the testTasks */
  test.dependsOn testTask
}

gradle.buildFinished {
    def allResults = rootProject.ext.testsResults

    if (!allResults.isEmpty()) {
        printResults allResults
        allResults.each {r ->
          if (r[2].resultType == TestResult.ResultType.FAILURE)
            throw new GradleException("Failed tests!")
        }
    }
}

private static String colString(styler, col, colour, text) {
  return col?"${styler[colour](text)}":text
}

private static String getSummaryLine(s, pn, tn, rt, rc, rs, rf, rsk, t, col) {
  def colour = 'black'
  def text = rt
  def nocol = false
  if (rc == 0) {
    text = "-----"
    nocol = true
  } else {
    switch(rt) {
      case TestResult.ResultType.SUCCESS:
        colour = 'green'
        break;
      case TestResult.ResultType.FAILURE:
        colour = 'red'
        break;
      default:
        nocol = true
        break;
    }
  }
  StringBuilder sb = new StringBuilder()
  sb.append("${pn}")
  if (tn != null)
    sb.append(":${tn}")
  sb.append(" results: ")
  sb.append(colString(s, col && !nocol, colour, text))
  sb.append(" (")
  sb.append("${rc} tests, ")
  sb.append(colString(s, col && rs > 0, 'green', rs))
  sb.append(" successes, ")
  sb.append(colString(s, col && rf > 0, 'red', rf))
  sb.append(" failures, ")
  sb.append("${rsk} skipped) in ${t}")
  return sb.toString()
}

private static void printResults(allResults) {

    // styler from https://stackoverflow.com/a/56139852
    def styler = 'black red green yellow blue magenta cyan white'.split().toList().withIndex(30).collectEntries { key, val -> [(key) : { "\033[${val}m${it}\033[0m" }] }

    def maxLength = 0
    def failedTests = false
    def summaryLines = []
    def totalcount = 0
    def totalsuccess = 0
    def totalfail = 0
    def totalskip = 0
    def totaltime = TimeCategory.getSeconds(0)
    // sort on project name then task name
    allResults.sort {a, b -> a[0] == b[0]? a[1]<=>b[1]:a[0] <=> b[0]}.each {
      def projectName = it[0]
      def taskName = it[1]
      def result = it[2]
      def time = it[3]
      def report = it[4]
      def summaryCol = getSummaryLine(styler, projectName, taskName, result.resultType, result.testCount, result.successfulTestCount, result.failedTestCount, result.skippedTestCount, time, true)
      def summaryPlain = getSummaryLine(styler, projectName, taskName, result.resultType, result.testCount, result.successfulTestCount, result.failedTestCount, result.skippedTestCount, time, false)
      def reportLine = "Report file: ${report}"
      def ls = summaryPlain.length()
      def lr = reportLine.length()
      def m = [ls, lr].max()
      if (m > maxLength)
        maxLength = m
      def info = [ls, summaryCol, reportLine]
      summaryLines.add(info)
      failedTests |= result.resultType == TestResult.ResultType.FAILURE
      totalcount += result.testCount
      totalsuccess += result.successfulTestCount
      totalfail += result.failedTestCount
      totalskip += result.skippedTestCount
      totaltime += time
    }
    def totalSummaryCol = getSummaryLine(styler, "OVERALL", "", failedTests?TestResult.ResultType.FAILURE:TestResult.ResultType.SUCCESS, totalcount, totalsuccess, totalfail, totalskip, totaltime, true)
    def totalSummaryPlain = getSummaryLine(styler, "OVERALL", "", failedTests?TestResult.ResultType.FAILURE:TestResult.ResultType.SUCCESS, totalcount, totalsuccess, totalfail, totalskip, totaltime, false)
    def tls = totalSummaryPlain.length()
    if (tls > maxLength)
      maxLength = tls
    def info = [tls, totalSummaryCol, null]
    summaryLines.add(info)

    def allSummaries = []
    for(sInfo in summaryLines) {
      def ls = sInfo[0]
      def summary = sInfo[1]
      def report = sInfo[2]

      StringBuilder sb = new StringBuilder()
      sb.append("│" + summary + " " * (maxLength - ls) + "│")
      if (report != null) {
        sb.append("\n│" + report + " " * (maxLength - report.length()) + "│")
      }
      allSummaries += sb.toString()
    }

    println "┌${"${"─" * maxLength}"}┐"
    println allSummaries.join("\n├${"${"─" * maxLength}"}┤\n")
    println "└${"${"─" * maxLength}"}┘"
}
/* END of test tasks results summary */


task compileLinkCheck(type: JavaCompile) {
  options.fork = true
  classpath = files("${jalviewDir}/${utils_dir}")
  destinationDir = file("${jalviewDir}/${utils_dir}")
  source = fileTree(dir: "${jalviewDir}/${utils_dir}", include: ["HelpLinksChecker.java", "BufferedLineReader.java"])

  inputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.java")
  inputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.java")
  outputs.file("${jalviewDir}/${utils_dir}/HelpLinksChecker.class")
  outputs.file("${jalviewDir}/${utils_dir}/BufferedLineReader.class")
}


task linkCheck(type: JavaExec) {
  dependsOn prepare
  dependsOn compileLinkCheck

  def helpLinksCheckerOutFile = file("${jalviewDir}/${utils_dir}/HelpLinksChecker.out")
  classpath = files("${jalviewDir}/${utils_dir}")
  main = "HelpLinksChecker"
  workingDir = "${helpBuildDir}"
  args = [ "${helpBuildDir}/${help_dir}", "-nointernet" ]

  def outFOS = new FileOutputStream(helpLinksCheckerOutFile, false) // false == don't append
  standardOutput = new org.apache.tools.ant.util.TeeOutputStream(
    outFOS,
    System.out)
  errorOutput = new org.apache.tools.ant.util.TeeOutputStream(
    outFOS,
    System.err)

  inputs.dir(helpBuildDir)
  outputs.file(helpLinksCheckerOutFile)
}


// import the pubhtmlhelp target
ant.properties.basedir = "${jalviewDir}"
ant.properties.helpBuildDir = "${helpBuildDir}/${help_dir}"
ant.importBuild "${utils_dir}/publishHelp.xml"


task cleanPackageDir(type: Delete) {
  doFirst {
    delete fileTree(dir: "${jalviewDir}/${package_dir}", include: "*.jar")
  }
}


jar {
  dependsOn prepare

  manifest {
    attributes "Main-Class": main_class,
    "Permissions": "all-permissions",
    "Application-Name": applicationName,
    "Codebase": application_codebase,
    "Implementation-Version": JALVIEW_VERSION
  }

  def outputDir = "${jalviewDir}/${package_dir}"
  destinationDir = file(outputDir)
  archiveName = rootProject.name+".jar"
  duplicatesStrategy "EXCLUDE"


  exclude "cache*/**"
  exclude "*.jar"
  exclude "*.jar.*"
  exclude "**/*.jar"
  exclude "**/*.jar.*"

  inputs.dir(sourceSets.main.java.outputDir)
  sourceSets.main.resources.srcDirs.each{ dir ->
    inputs.dir(dir)
  }
  outputs.file("${outputDir}/${archiveName}")
}


task copyJars(type: Copy) {
  from fileTree(dir: classesDir, include: "**/*.jar").files
  into "${jalviewDir}/${package_dir}"
}


// doing a Sync instead of Copy as Copy doesn't deal with "outputs" very well
task syncJars(type: Sync) {
  dependsOn jar
  from fileTree(dir: "${jalviewDir}/${libDistDir}", include: "**/*.jar").files
  into "${jalviewDir}/${package_dir}"
  preserve {
    include jar.archiveName != null ? jar.archiveName : null
  }
}


task makeDist {
  group = "build"
  description = "Put all required libraries in dist"
  // order of "cleanPackageDir", "copyJars", "jar" important!
  jar.mustRunAfter cleanPackageDir
  syncJars.mustRunAfter cleanPackageDir
  dependsOn cleanPackageDir
  dependsOn syncJars
  dependsOn jar
  outputs.dir("${jalviewDir}/${package_dir}")
}


task cleanDist {
  dependsOn cleanPackageDir
  dependsOn cleanTest
  dependsOn clean
}


task launcherJar(type: Jar) {
  manifest {
      attributes (
        "Main-Class": shadow_jar_main_class,
        "Implementation-Version": JALVIEW_VERSION,
        "Application-Name": applicationName
      )
  }
}

tasks.withType(JavaCompile) {
	options.encoding = 'UTF-8'
}

def writeDataJsonFile(File installersOutputTxt, File installersSha256, File dataJsonFile) {
  def hash = [
    "date" : getDate("yyyy-MM-dd HH:mm:ss"),
    "git-commit" : "${gitHash} [${gitBranch}]",
    "version" : JALVIEW_VERSION
  ]
  // install4j installer files
  if (installersOutputTxt.exists()) {
    def idHash = [:]
    installersOutputTxt.readLines().each { def line ->
      if (line.startsWith("#")) {
        return;
      }
      line.replaceAll("\n","")
      def vals = line.split("\t")
      def filename = vals[3]
      def filesize = file(filename).length()
      filename = filename.replaceAll(/^.*\//, "")
      hash[vals[0]] = [ "id" : vals[0], "os" : vals[1], "name" : vals[2], "file" : filename, "filesize" : filesize ]
      idHash."${filename}" = vals[0]
    }
    if (install4jCheckSums && installersSha256.exists()) {
      installersSha256.readLines().each { def line ->
        if (line.startsWith("#")) {
          return;
        }
        line.replaceAll("\n","")
        def vals = line.split(/\s+\*?/)
        def filename = vals[1]
        def innerHash = (hash.(idHash."${filename}"))."sha256" = vals[0]
      }
    }
  }

  return dataJsonFile.write(new JsonBuilder(hash).toPrettyString())
}

task staticMakeInstallersJsonFile {
  doFirst {
    def output = findProperty("i4j_output")
    def sha256 = findProperty("i4j_sha256")
    def json = findProperty("i4j_json")
    if (output == null || sha256 == null || json == null) {
      throw new GradleException("Must provide paths to all of output.txt, sha256sums, and output.json with '-Pi4j_output=... -Pi4j_sha256=... -Pi4j_json=...")
    }
    writeDataJsonFile(file(output), file(sha256), file(json))
  }
}


task createSourceReleaseProperties(type: WriteProperties) {
  group = "distribution"
  description = "Create the source RELEASE properties file"
  
  def sourceTarBuildDir = "${buildDir}/sourceTar"
  def sourceReleasePropertiesFile = "${sourceTarBuildDir}/RELEASE"
  outputFile (sourceReleasePropertiesFile)

  doFirst {
    releaseProps.each{ key, val -> property key, val }
    property "git.branch", gitBranch
    property "git.hash", gitHash
  }

  outputs.file(outputFile)
}

task sourceDist(type: Tar) {
  group "distribution"
  description "Create a source .tar.gz file for distribution"

  dependsOn createBuildProperties
  dependsOn convertMdFiles
  dependsOn createSourceReleaseProperties


  def outputFileName = "${project.name}_${JALVIEW_VERSION_UNDERSCORES}.tar.gz"
  archiveName = outputFileName
  
  compression Compression.GZIP
  
  into project.name

  def EXCLUDE_FILES=[
    "dist/*",
    "build/*",
    "bin/*",
    "test-output/",
    "test-reports",
    "tests",
    ".*",
    "benchmarking/*",
    "**/.*",
    "*.class",
    "**/*.class","$j11modDir/**/*.jar","appletlib","**/*locales",
    "*locales/**",
    "utils/InstallAnywhere",
    "**/*.log",
    "RELEASE",
  ] 
  def PROCESS_FILES=[
    "AUTHORS",
    "CITATION",
    "FEATURETODO",
    "JAVA-11-README",
    "FEATURETODO",
    "LICENSE",
    "**/README",
    "THIRDPARTYLIBS",
    "TESTNG",
    "build.gradle",
    "gradle.properties",
    "**/*.java",
    "**/*.html",
    "**/*.xml",
    "**/*.gradle",
    "**/*.groovy",
    "**/*.properties",
    "**/*.perl",
    "**/*.sh",
  ]
  def INCLUDE_FILES=[
    ".classpath",
    ".settings/org.eclipse.buildship.core.prefs",
    ".settings/org.eclipse.jdt.core.prefs"
  ]

  from(jalviewDir) {
    exclude (EXCLUDE_FILES)
    include (PROCESS_FILES)
    filter(ReplaceTokens,
      beginToken: '$$',
      endToken: '$$',
      tokens: [
        'Version-Rel': JALVIEW_VERSION,
        'Year-Rel': getDate("yyyy")
      ]
    )
  }
  from(jalviewDir) {
    exclude (EXCLUDE_FILES)
    exclude (PROCESS_FILES)
    exclude ("appletlib")
    exclude ("**/*locales")
    exclude ("*locales/**")
    exclude ("utils/InstallAnywhere")

    // exluding these as not using jars as modules yet
    exclude ("${j11modDir}/**/*.jar")
  }
  from(jalviewDir) {
    include(INCLUDE_FILES)
  }
//  from (jalviewDir) {
//    // explicit includes for stuff that seemed to not get included
//    include(fileTree("test/**/*."))
//    exclude(EXCLUDE_FILES)
//    exclude(PROCESS_FILES)
//  }

  def sourceTarBuildDir = "${buildDir}/sourceTar"
  from(sourceTarBuildDir) {
    // this includes the appended RELEASE properties file
  }
}

task helppages {
  group "help"
  description "Copies all help pages to build dir. Runs ant task 'pubhtmlhelp'."

  dependsOn copyHelp
  dependsOn pubhtmlhelp
  
  inputs.dir("${helpBuildDir}/${help_dir}")
  outputs.dir("${buildDir}/distributions/${help_dir}")
}


task jalviewjsEnableAltFileProperty(type: WriteProperties) {
  group "jalviewjs"
  description "Enable the alternative J2S Config file for headless build"

  outputFile = jalviewjsJ2sSettingsFileName
  def j2sPropsFile = file(jalviewjsJ2sSettingsFileName)
  def j2sProps = new Properties()
  if (j2sPropsFile.exists()) {
    try {
      def j2sPropsFileFIS = new FileInputStream(j2sPropsFile)
      j2sProps.load(j2sPropsFileFIS)
      j2sPropsFileFIS.close()

      j2sProps.each { prop, val ->
        property(prop, val)
      }
    } catch (Exception e) {
      println("Exception reading ${jalviewjsJ2sSettingsFileName}")
      e.printStackTrace()
    }
  }
  if (! j2sProps.stringPropertyNames().contains(jalviewjs_j2s_alt_file_property_config)) {
    property(jalviewjs_j2s_alt_file_property_config, jalviewjs_j2s_alt_file_property)
  }
}


task printProperties {
  group "Debug"
  description "Output to console all System.properties"
  doFirst {
    System.properties.each { key, val -> System.out.println("Property: ${key}=${val}") }
  }
}


/* not really working yet
jalviewjsEclipseCopyDropins.finalizedBy jalviewjsCleanEclipse
*/


task jalviewjsTransferUnzipSwingJs {
  def file_zip = "${jalviewDir}/${jalviewjs_swingjs_zip}"

  doLast {
    copy {
      from zipTree(file_zip)
      into "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}"
    }
  }

  inputs.file file_zip
  outputs.dir "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}"
}


task jalviewjsTransferUnzipLib {
  def zipFiles = fileTree(dir: "${jalviewDir}/${jalviewjs_libjs_dir}", include: "*.zip")

  doLast {
    zipFiles.each { file_zip -> 
      copy {
        from zipTree(file_zip)
        into "${jalviewDir}/${jalviewjsTransferSiteLibDir}"
      }
    }
  }

  inputs.files zipFiles
  outputs.dir "${jalviewDir}/${jalviewjsTransferSiteLibDir}"
}


task jalviewjsTransferUnzipAllLibs {
  dependsOn jalviewjsTransferUnzipSwingJs
  dependsOn jalviewjsTransferUnzipLib
}


task jalviewjsCreateJ2sSettings(type: WriteProperties) {
  group "JalviewJS"
  description "Create the alternative j2s file from the j2s.* properties"

  jalviewjsJ2sProps = project.properties.findAll { it.key.startsWith("j2s.") }.sort { it.key }
  def siteDirProperty = "j2s.site.directory"
  def setSiteDir = false
  jalviewjsJ2sProps.each { prop, val ->
    if (val != null) {
      if (prop == siteDirProperty) {
        if (!(val.startsWith('/') || val.startsWith("file://") )) {
          val = "${jalviewDir}/${jalviewjsTransferSiteJsDir}/${val}"
        }
        setSiteDir = true
      }
      property(prop,val)
    }
    if (!setSiteDir) { // default site location, don't override specifically set property
      property(siteDirProperty,"${jalviewDirRelativePath}/${jalviewjsTransferSiteJsDir}")
    }
  }
  outputFile = jalviewjsJ2sAltSettingsFileName

    inputs.properties(jalviewjsJ2sProps)
    outputs.file(jalviewjsJ2sAltSettingsFileName)
}


task jalviewjsSyncAllLibs (type: Sync) {
  dependsOn jalviewjsTransferUnzipAllLibs
  def inputFiles = fileTree(dir: "${jalviewDir}/${jalviewjsTransferSiteLibDir}")
  inputFiles += fileTree(dir: "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}")
  def outputDir = "${jalviewDir}/${jalviewjsSiteDir}"

  from inputFiles
  into outputDir
  def outputFiles = []
  rename { filename ->
    outputFiles += "${outputDir}/${filename}"
    null
  }
  preserve {
    include "**"
  }

  // should this be exclude really ?
  duplicatesStrategy "INCLUDE"

  outputs.files outputFiles
  inputs.files inputFiles
}


task jalviewjsSyncResources (type: Sync) {
  dependsOn buildResources

  def inputFiles = fileTree(dir: resourcesBuildDir)
  def outputDir = "${jalviewDir}/${jalviewjsSiteDir}/${jalviewjs_j2s_subdir}"

  from inputFiles
  into outputDir
  def outputFiles = []
  rename { filename ->
    outputFiles += "${outputDir}/${filename}"
    null
  }
  preserve {
    include "**"
  }
  outputs.files outputFiles
  inputs.files inputFiles
}


task jalviewjsSyncSiteResources (type: Sync) {
  def inputFiles = fileTree(dir: "${jalviewDir}/${jalviewjs_site_resource_dir}")
  def outputDir = "${jalviewDir}/${jalviewjsSiteDir}"

  from inputFiles
  into outputDir
  def outputFiles = []
  rename { filename ->
    outputFiles += "${outputDir}/${filename}"
    null
  }
  preserve {
    include "**"
  }
  outputs.files outputFiles
  inputs.files inputFiles
}


task jalviewjsSyncBuildProperties (type: Sync) {
  dependsOn createBuildProperties
  def inputFiles = [file(buildProperties)]
  def outputDir = "${jalviewDir}/${jalviewjsSiteDir}/${jalviewjs_j2s_subdir}"

  from inputFiles
  into outputDir
  def outputFiles = []
  rename { filename ->
    outputFiles += "${outputDir}/${filename}"
    null
  }
  preserve {
    include "**"
  }
  outputs.files outputFiles
  inputs.files inputFiles
}


def jalviewjsCallCore(String name, FileCollection list, String prefixFile, String suffixFile, String jsfile, String zjsfile, File logOutFile, Boolean logOutConsole) {

  def stdout = new ByteArrayOutputStream()
  def stderr = new ByteArrayOutputStream()

  def coreFile = file(jsfile)
  def msg = ""
  msg = "Creating core for ${name}...\nGenerating ${jsfile}"
  println(msg)
  logOutFile.createNewFile()
  logOutFile.append(msg+"\n")

  def coreTop = file(prefixFile)
  def coreBottom = file(suffixFile)
  coreFile.getParentFile().mkdirs()
  coreFile.createNewFile()
  coreFile.write( coreTop.getText("UTF-8") )
  list.each {
    f ->
    if (f.exists()) {
      def t = f.getText("UTF-8")
      t.replaceAll("Clazz\\.([^_])","Clazz_${1}")
      coreFile.append( t )
    } else {
      msg = "...file '"+f.getPath()+"' does not exist, skipping"
      println(msg)
      logOutFile.append(msg+"\n")
    }
  }
  coreFile.append( coreBottom.getText("UTF-8") )

  msg = "Generating ${zjsfile}"
  println(msg)
  logOutFile.append(msg+"\n")
  def logOutFOS = new FileOutputStream(logOutFile, true) // true == append
  def logErrFOS = logOutFOS

  javaexec {
    classpath = files(["${jalviewDir}/${jalviewjs_closure_compiler}"])
    main = "com.google.javascript.jscomp.CommandLineRunner"
    jvmArgs = [ "-Dfile.encoding=UTF-8" ]
    args = [ "--compilation_level", "SIMPLE_OPTIMIZATIONS", "--warning_level", "QUIET", "--charset", "UTF-8", "--js", jsfile, "--js_output_file", zjsfile ]
    maxHeapSize = "2g"

    msg = "\nRunning '"+commandLine.join(' ')+"'\n"
    println(msg)
    logOutFile.append(msg+"\n")

    if (logOutConsole) {
      standardOutput = new org.apache.tools.ant.util.TeeOutputStream(
        new org.apache.tools.ant.util.TeeOutputStream(
          logOutFOS,
          stdout),
        standardOutput)
        errorOutput = new org.apache.tools.ant.util.TeeOutputStream(
          new org.apache.tools.ant.util.TeeOutputStream(
            logErrFOS,
            stderr),
          System.err)
    } else {
      standardOutput = new org.apache.tools.ant.util.TeeOutputStream(
        logOutFOS,
        stdout)
        errorOutput = new org.apache.tools.ant.util.TeeOutputStream(
          logErrFOS,
          stderr)
    }
  }
  msg = "--"
  println(msg)
  logOutFile.append(msg+"\n")
}


task jalviewjsBuildAllCores {
  group "JalviewJS"
  description "Build the core js lib closures listed in the classlists dir"
  dependsOn jalviewjsTransferUnzipSwingJs

  def j2sDir = "${jalviewDir}/${jalviewjsTransferSiteJsDir}/${jalviewjs_j2s_subdir}"
  def swingJ2sDir = "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}/${jalviewjs_j2s_subdir}"
  def libJ2sDir = "${jalviewDir}/${jalviewjsTransferSiteLibDir}/${jalviewjs_j2s_subdir}"
  def jsDir = "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}/${jalviewjs_js_subdir}"
  def outputDir = "${jalviewDir}/${jalviewjsTransferSiteCoreDir}/${jalviewjs_j2s_subdir}/core"
  def prefixFile = "${jsDir}/core/coretop2.js"
  def suffixFile = "${jsDir}/core/corebottom2.js"

  inputs.file prefixFile
  inputs.file suffixFile

  def classlistFiles = []
  // add the classlists found int the jalviewjs_classlists_dir
  fileTree(dir: "${jalviewDir}/${jalviewjs_classlists_dir}", include: "*.txt").each {
    file ->
    def name = file.getName() - ".txt"
    classlistFiles += [
      'file': file,
      'name': name
    ]
  }

  // _jmol and _jalview cores. Add any other peculiar classlist.txt files here
  //classlistFiles += [ 'file': file("${jalviewDir}/${jalviewjs_classlist_jmol}"), 'name': "_jvjmol" ]
  classlistFiles += [ 'file': file("${jalviewDir}/${jalviewjs_classlist_jalview}"), 'name': jalviewjsJalviewCoreName ]

  jalviewjsCoreClasslists = []

  classlistFiles.each {
    hash ->

    def file = hash['file']
    if (! file.exists()) {
      //println("...classlist file '"+file.getPath()+"' does not exist, skipping")
      return false // this is a "continue" in groovy .each closure
    }
    def name = hash['name']
    if (name == null) {
      name = file.getName() - ".txt"
    }

    def filelist = []
    file.eachLine {
      line ->
        filelist += line
    }
    def list = fileTree(dir: j2sDir, includes: filelist)

    def jsfile = "${outputDir}/core${name}.js"
    def zjsfile = "${outputDir}/core${name}.z.js"

    jalviewjsCoreClasslists += [
      'jsfile': jsfile,
      'zjsfile': zjsfile,
      'list': list,
      'name': name
    ]

    inputs.file(file)
    inputs.files(list)
    outputs.file(jsfile)
    outputs.file(zjsfile)
  }
  
  // _stevesoft core. add any cores without a classlist here (and the inputs and outputs)
  def stevesoftClasslistName = "_stevesoft"
  def stevesoftClasslist = [
    'jsfile': "${outputDir}/core${stevesoftClasslistName}.js",
    'zjsfile': "${outputDir}/core${stevesoftClasslistName}.z.js",
    'list': fileTree(dir: j2sDir, include: "com/stevesoft/pat/**/*.js"),
    'name': stevesoftClasslistName
  ]
  jalviewjsCoreClasslists += stevesoftClasslist
  inputs.files(stevesoftClasslist['list'])
  outputs.file(stevesoftClasslist['jsfile'])
  outputs.file(stevesoftClasslist['zjsfile'])

  // _all core
  def allClasslistName = "_all"
  def allJsFiles = fileTree(dir: j2sDir, include: "**/*.js")
  allJsFiles += fileTree(
    dir: libJ2sDir,
    include: "**/*.js",
    excludes: [
      // these exlusions are files that the closure-compiler produces errors for. Should fix them
      "**/org/jmol/jvxl/readers/IsoIntersectFileReader.js",
      "**/org/jmol/export/JSExporter.js"
    ]
  )
  allJsFiles += fileTree(
    dir: swingJ2sDir,
    include: "**/*.js",
    excludes: [
      // these exlusions are files that the closure-compiler produces errors for. Should fix them
      "**/sun/misc/Unsafe.js",
      "**/swingjs/jquery/jquery-editable-select.js",
      "**/swingjs/jquery/j2sComboBox.js",
      "**/sun/misc/FloatingDecimal.js"
    ]
  )
  def allClasslist = [
    'jsfile': "${outputDir}/core${allClasslistName}.js",
    'zjsfile': "${outputDir}/core${allClasslistName}.z.js",
    'list': allJsFiles,
    'name': allClasslistName
  ]
  // not including this version of "all" core at the moment
  //jalviewjsCoreClasslists += allClasslist
  inputs.files(allClasslist['list'])
  outputs.file(allClasslist['jsfile'])
  outputs.file(allClasslist['zjsfile'])

  doFirst {
    def logOutFile = file("${jalviewDirAbsolutePath}/${jalviewjsBuildDir}/${jalviewjs_j2s_closure_stdout}")
    logOutFile.getParentFile().mkdirs()
    logOutFile.createNewFile()
    logOutFile.write(getDate("yyyy-MM-dd HH:mm:ss")+" jalviewjsBuildAllCores\n----\n")

    jalviewjsCoreClasslists.each {
      jalviewjsCallCore(it.name, it.list, prefixFile, suffixFile, it.jsfile, it.zjsfile, logOutFile, jalviewjs_j2s_to_console.equals("true"))
    }
  }

}


def jalviewjsPublishCoreTemplate(String coreName, String templateName, File inputFile, String outputFile) {
  copy {
    from inputFile
    into file(outputFile).getParentFile()
    rename { filename ->
      if (filename.equals(inputFile.getName())) {
        return file(outputFile).getName()
      }
      return null
    }
    filter(ReplaceTokens,
      beginToken: '_',
      endToken: '_',
      tokens: [
        'MAIN': '"'+main_class+'"',
        'CODE': "null",
        'NAME': jalviewjsJalviewTemplateName+" [core ${coreName}]",
        'COREKEY': jalviewjs_core_key,
        'CORENAME': coreName
      ]
    )
  }
}


task jalviewjsPublishCoreTemplates {
  dependsOn jalviewjsBuildAllCores
  def inputFileName = "${jalviewDir}/${j2s_coretemplate_html}"
  def inputFile = file(inputFileName)
  def outputDir = "${jalviewDir}/${jalviewjsTransferSiteCoreDir}"

  def outputFiles = []
  jalviewjsCoreClasslists.each { cl ->
    def outputFile = "${outputDir}/${jalviewjsJalviewTemplateName}_${cl.name}.html"
    cl['outputfile'] = outputFile
    outputFiles += outputFile
  }

  doFirst {
    jalviewjsCoreClasslists.each { cl ->
      jalviewjsPublishCoreTemplate(cl.name, jalviewjsJalviewTemplateName, inputFile, cl.outputfile)
    }
  }
  inputs.file(inputFile)
  outputs.files(outputFiles)
}


task jalviewjsSyncCore (type: Sync) {
  dependsOn jalviewjsBuildAllCores
  dependsOn jalviewjsPublishCoreTemplates
  def inputFiles = fileTree(dir: "${jalviewDir}/${jalviewjsTransferSiteCoreDir}")
  def outputDir = "${jalviewDir}/${jalviewjsSiteDir}"

  from inputFiles
  into outputDir
  def outputFiles = []
  rename { filename ->
    outputFiles += "${outputDir}/${filename}"
    null
  }
  preserve {
    include "**"
  }
  outputs.files outputFiles
  inputs.files inputFiles
}


// this Copy version of TransferSiteJs will delete anything else in the target dir
task jalviewjsCopyTransferSiteJs(type: Copy) {
  from "${jalviewDir}/${jalviewjsTransferSiteJsDir}"
  into "${jalviewDir}/${jalviewjsSiteDir}"
}


// this Sync version of TransferSite is used by buildship to keep the website automatically up to date when a file changes
task jalviewjsSyncTransferSiteJs(type: Sync) {
  from "${jalviewDir}/${jalviewjsTransferSiteJsDir}"
  include "**/*.*"
  into "${jalviewDir}/${jalviewjsSiteDir}"
  preserve {
    include "**"
  }
}


jalviewjsSyncAllLibs.mustRunAfter jalviewjsCopyTransferSiteJs
jalviewjsSyncResources.mustRunAfter jalviewjsCopyTransferSiteJs
jalviewjsSyncSiteResources.mustRunAfter jalviewjsCopyTransferSiteJs
jalviewjsSyncBuildProperties.mustRunAfter jalviewjsCopyTransferSiteJs

jalviewjsSyncAllLibs.mustRunAfter jalviewjsSyncTransferSiteJs
jalviewjsSyncResources.mustRunAfter jalviewjsSyncTransferSiteJs
jalviewjsSyncSiteResources.mustRunAfter jalviewjsSyncTransferSiteJs
jalviewjsSyncBuildProperties.mustRunAfter jalviewjsSyncTransferSiteJs


task jalviewjsPrepareSite {
  group "JalviewJS"
  description "Prepares the website folder including unzipping files and copying resources"
  dependsOn jalviewjsSyncAllLibs
  dependsOn jalviewjsSyncResources
  dependsOn jalviewjsSyncSiteResources
  dependsOn jalviewjsSyncBuildProperties
  dependsOn jalviewjsSyncCore
}


task jalviewjsBuildSite {
  group "JalviewJS"
  description "Builds the whole website including transpiled code"
  dependsOn jalviewjsCopyTransferSiteJs
  dependsOn jalviewjsPrepareSite
}


task cleanJalviewjsTransferSite {
  doFirst {
    delete "${jalviewDir}/${jalviewjsTransferSiteJsDir}"
    delete "${jalviewDir}/${jalviewjsTransferSiteLibDir}"
    delete "${jalviewDir}/${jalviewjsTransferSiteSwingJsDir}"
    delete "${jalviewDir}/${jalviewjsTransferSiteCoreDir}"
  }
}


task cleanJalviewjsSite {
  dependsOn cleanJalviewjsTransferSite
  doFirst {
    delete "${jalviewDir}/${jalviewjsSiteDir}"
  }
}


task jalviewjsSiteTar(type: Tar) {
  group "JalviewJS"
  description "Creates a tar.gz file for the website"
  dependsOn jalviewjsBuildSite
  def outputFilename = "jalviewjs-site-${JALVIEW_VERSION}.tar.gz"
  archiveName = outputFilename

  compression Compression.GZIP

  from "${jalviewDir}/${jalviewjsSiteDir}"
  into jalviewjs_site_dir // this is inside the tar file

  inputs.dir("${jalviewDir}/${jalviewjsSiteDir}")
}


task jalviewjsServer {
  group "JalviewJS"
  def filename = "jalviewjsTest.html"
  description "Starts a webserver on localhost to test the website. See ${filename} to access local site on most recently used port."
  def htmlFile = "${jalviewDirAbsolutePath}/${filename}"
  doLast {

    def factory
    try {
      def f = Class.forName("org.gradle.plugins.javascript.envjs.http.simple.SimpleHttpFileServerFactory")
      factory = f.newInstance()
    } catch (ClassNotFoundException e) {
      throw new GradleException("Unable to create SimpleHttpFileServerFactory")
    }
    def port = Integer.valueOf(jalviewjs_server_port)
    def start = port
    def running = false
    def url
    def jalviewjsServer
    while(port < start+1000 && !running) {
      try {
        def doc_root = new File("${jalviewDirAbsolutePath}/${jalviewjsSiteDir}")
        jalviewjsServer = factory.start(doc_root, port)
        running = true
        url = jalviewjsServer.getResourceUrl(jalviewjs_server_resource)
        println("SERVER STARTED with document root ${doc_root}.")
        println("Go to "+url+" . Run  gradle --stop  to stop (kills all gradle daemons).")
        println("For debug: "+url+"?j2sdebug")
        println("For verbose: "+url+"?j2sverbose")
      } catch (Exception e) {
        port++;
      }
    }
    def htmlText = """
      <p><a href="${url}">JalviewJS Test. &lt;${url}&gt;</a></p>
      <p><a href="${url}?j2sdebug">JalviewJS Test with debug. &lt;${url}?j2sdebug&gt;</a></p>
      <p><a href="${url}?j2sverbose">JalviewJS Test with verbose. &lt;${url}?j2sdebug&gt;</a></p>
      """
    jalviewjsCoreClasslists.each { cl ->
      def urlcore = jalviewjsServer.getResourceUrl(file(cl.outputfile).getName())
      htmlText += """
      <p><a href="${urlcore}">${jalviewjsJalviewTemplateName} [core ${cl.name}]. &lt;${urlcore}&gt;</a></p>
      """
      println("For core ${cl.name}: "+urlcore)
    }

    file(htmlFile).text = htmlText
  }

  outputs.file(htmlFile)
  outputs.upToDateWhen({false})
}


task cleanJalviewjsAll {
  group "JalviewJS"
  description "Delete all configuration and build artifacts to do with JalviewJS build"
  dependsOn cleanJalviewjsSite
  
  doFirst {
    delete "${jalviewDir}/${jalviewjsBuildDir}"
    delete "${jalviewDir}/${eclipse_bin_dir}"
    if (eclipseWorkspace != null && file(eclipseWorkspace.getAbsolutePath()+"/.metadata").exists()) {
      delete file(eclipseWorkspace.getAbsolutePath()+"/.metadata")
    }
    delete jalviewjsJ2sAltSettingsFileName
  }

  outputs.upToDateWhen( { false } )
}


task jalviewjsIDE_j2sFile {
  group "00 JalviewJS in Eclipse"
  description "Creates the .j2s file"
  dependsOn jalviewjsCreateJ2sSettings
}


task jalviewjsIDE_SyncCore {
  group "00 JalviewJS in Eclipse"
  description "Build the core js lib closures listed in the classlists dir and publish core html from template"
  dependsOn jalviewjsSyncCore
}


task jalviewjsIDE_SyncSiteAll {
  dependsOn jalviewjsSyncAllLibs
  dependsOn jalviewjsSyncResources
  dependsOn jalviewjsSyncSiteResources
  dependsOn jalviewjsSyncBuildProperties
}


cleanJalviewjsTransferSite.mustRunAfter jalviewjsIDE_SyncSiteAll


task jalviewjsIDE_PrepareSite {
  group "00 JalviewJS in Eclipse"
  description "Sync libs and resources to site dir, but not closure cores"

  dependsOn jalviewjsIDE_SyncSiteAll
  //dependsOn cleanJalviewjsTransferSite // not sure why this clean is here -- will slow down a re-run of this task
}


task jalviewjsIDE_AssembleSite {
  group "00 JalviewJS in Eclipse"
  description "Assembles unzipped supporting zipfiles, resources, site resources and closure cores into the Eclipse transpiled site"
  dependsOn jalviewjsPrepareSite
}


task jalviewjsIDE_SiteClean {
  group "00 JalviewJS in Eclipse"
  description "Deletes the Eclipse transpiled site"
  dependsOn cleanJalviewjsSite
}


task jalviewjsIDE_Server {
  group "00 JalviewJS in Eclipse"
  description "Starts a webserver on localhost to test the website"
  dependsOn jalviewjsServer
}


// buildship runs this at build time or project refresh
task eclipseAutoBuildTask {
  //dependsOn jalviewjsIDE_PrepareSite
}


task jalviewjsCopyStderrLaunchFile(type: Copy) {
  from file(jalviewjs_stderr_launch)
  into jalviewjsSiteDir

  inputs.file jalviewjs_stderr_launch
  outputs.file jalviewjsStderrLaunchFilename
}

task cleanJalviewjsChromiumUserDir {
  doFirst {
    delete jalviewjsChromiumUserDir
  }
  outputs.dir jalviewjsChromiumUserDir
  // always run when depended on
  outputs.upToDateWhen { !file(jalviewjsChromiumUserDir).exists() }
}

task jalviewjsChromiumProfile {
  dependsOn cleanJalviewjsChromiumUserDir
  mustRunAfter cleanJalviewjsChromiumUserDir

  def firstRun = file("${jalviewjsChromiumUserDir}/First Run")

  doFirst {
    mkdir jalviewjsChromiumProfileDir
    firstRun.text = ""
  }
  outputs.file firstRun
}

task jalviewjsLaunchTest {
  group "Test"
  description "Check JalviewJS opens in a browser"
  dependsOn jalviewjsBuildSite
  dependsOn jalviewjsCopyStderrLaunchFile
  dependsOn jalviewjsChromiumProfile

  def macOS = OperatingSystem.current().isMacOsX()
  def chromiumBinary = macOS ? jalviewjs_macos_chromium_binary : jalviewjs_chromium_binary
  if (chromiumBinary.startsWith("~/")) {
    chromiumBinary = System.getProperty("user.home") + chromiumBinary.substring(1)
  }
  
  def stdout
  def stderr
  doFirst {
    def timeoutms = Integer.valueOf(jalviewjs_chromium_overall_timeout) * 1000
    
    def binary = file(chromiumBinary)
    if (!binary.exists()) {
      throw new StopExecutionException("Could not find chromium binary '${chromiumBinary}'. Cannot run task ${name}.")
    }
    stdout = new ByteArrayOutputStream()
    stderr = new ByteArrayOutputStream()
    def execStdout
    def execStderr
    if (jalviewjs_j2s_to_console.equals("true")) {
      execStdout = new org.apache.tools.ant.util.TeeOutputStream(
        stdout,
        System.out)
      execStderr = new org.apache.tools.ant.util.TeeOutputStream(
        stderr,
        System.err)
    } else {
      execStdout = stdout
      execStderr = stderr
    }
    def execArgs = [
      "--no-sandbox", // --no-sandbox IS USED BY THE THORIUM APPIMAGE ON THE BUILDSERVER
      "--headless=new",
      "--disable-gpu",
      "--timeout=${timeoutms}",
      "--virtual-time-budget=${timeoutms}",
      "--user-data-dir=${jalviewDirAbsolutePath}/${jalviewjsBuildDir}/${jalviewjs_chromium_user_dir}",
      "--profile-directory=${jalviewjs_chromium_profile_name}",
      "--allow-file-access-from-files",
      "--enable-logging=stderr",
      "file://${jalviewDirAbsolutePath}/${jalviewjsStderrLaunchFilename}"
    ]
    
    if (true || macOS) {
      ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
      Future f1 = executor.submit(
        {
          exec {
            standardOutput = execStdout
            errorOutput = execStderr
            executable(chromiumBinary)
            args(execArgs)
            println "COMMAND: '"+commandLine.join(" ")+"'"
          }
          executor.shutdownNow()
        }
      )

      def noChangeBytes = 0
      def noChangeIterations = 0
      executor.scheduleAtFixedRate(
        {
          String stderrString = stderr.toString()
          // shutdown the task if we have a success string
          if (stderrString.contains(jalviewjs_desktop_init_string)) {
            f1.cancel()
            Thread.sleep(1000)
            executor.shutdownNow()
          }
          // if no change in stderr for 10s then also end
          if (noChangeIterations >= jalviewjs_chromium_idle_timeout) {
            executor.shutdownNow()
          }
          if (stderrString.length() == noChangeBytes) {
            noChangeIterations++
          } else {
            noChangeBytes = stderrString.length()
            noChangeIterations = 0
          }
        },
        1, 1, TimeUnit.SECONDS)

      executor.schedule(new Runnable(){
        public void run(){
          f1.cancel()
          executor.shutdownNow()
        }
      }, timeoutms, TimeUnit.MILLISECONDS)

      executor.awaitTermination(timeoutms+10000, TimeUnit.MILLISECONDS)
      executor.shutdownNow()
    }

  }
  
  doLast {
    def found = false
    stderr.toString().eachLine { line ->
      if (line.contains(jalviewjs_desktop_init_string)) {
        println("Found line '"+line+"'")
        found = true
        return
      }
    }
    if (!found) {
      throw new GradleException("Could not find evidence of Desktop launch in JalviewJS.")
    }
  }
}
  

task jalviewjs {
  group "JalviewJS"
  description "Build the JalviewJS site and run the launch test"
  dependsOn jalviewjsBuildSite
  dependsOn jalviewjsLaunchTest
}