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
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
/*************************************************************************/
/*  export.cpp                                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "export.h"

#include "core/config/project_settings.h"
#include "core/io/image_loader.h"
#include "core/io/marshalls.h"
#include "core/io/zip_io.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "core/version.h"
#include "drivers/png/png_driver_common.h"
#include "editor/editor_export.h"
#include "editor/editor_log.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
#include "main/splash.gen.h"
#include "platform/android/export/gradle_export_util.h"
#include "platform/android/logo.gen.h"
#include "platform/android/plugin/godot_plugin_config.h"
#include "platform/android/run_icon.gen.h"

#include <string.h>

static const char *android_perms[] = {
	"ACCESS_CHECKIN_PROPERTIES",
	"ACCESS_COARSE_LOCATION",
	"ACCESS_FINE_LOCATION",
	"ACCESS_LOCATION_EXTRA_COMMANDS",
	"ACCESS_MOCK_LOCATION",
	"ACCESS_NETWORK_STATE",
	"ACCESS_SURFACE_FLINGER",
	"ACCESS_WIFI_STATE",
	"ACCOUNT_MANAGER",
	"ADD_VOICEMAIL",
	"AUTHENTICATE_ACCOUNTS",
	"BATTERY_STATS",
	"BIND_ACCESSIBILITY_SERVICE",
	"BIND_APPWIDGET",
	"BIND_DEVICE_ADMIN",
	"BIND_INPUT_METHOD",
	"BIND_NFC_SERVICE",
	"BIND_NOTIFICATION_LISTENER_SERVICE",
	"BIND_PRINT_SERVICE",
	"BIND_REMOTEVIEWS",
	"BIND_TEXT_SERVICE",
	"BIND_VPN_SERVICE",
	"BIND_WALLPAPER",
	"BLUETOOTH",
	"BLUETOOTH_ADMIN",
	"BLUETOOTH_PRIVILEGED",
	"BRICK",
	"BROADCAST_PACKAGE_REMOVED",
	"BROADCAST_SMS",
	"BROADCAST_STICKY",
	"BROADCAST_WAP_PUSH",
	"CALL_PHONE",
	"CALL_PRIVILEGED",
	"CAMERA",
	"CAPTURE_AUDIO_OUTPUT",
	"CAPTURE_SECURE_VIDEO_OUTPUT",
	"CAPTURE_VIDEO_OUTPUT",
	"CHANGE_COMPONENT_ENABLED_STATE",
	"CHANGE_CONFIGURATION",
	"CHANGE_NETWORK_STATE",
	"CHANGE_WIFI_MULTICAST_STATE",
	"CHANGE_WIFI_STATE",
	"CLEAR_APP_CACHE",
	"CLEAR_APP_USER_DATA",
	"CONTROL_LOCATION_UPDATES",
	"DELETE_CACHE_FILES",
	"DELETE_PACKAGES",
	"DEVICE_POWER",
	"DIAGNOSTIC",
	"DISABLE_KEYGUARD",
	"DUMP",
	"EXPAND_STATUS_BAR",
	"FACTORY_TEST",
	"FLASHLIGHT",
	"FORCE_BACK",
	"GET_ACCOUNTS",
	"GET_PACKAGE_SIZE",
	"GET_TASKS",
	"GET_TOP_ACTIVITY_INFO",
	"GLOBAL_SEARCH",
	"HARDWARE_TEST",
	"INJECT_EVENTS",
	"INSTALL_LOCATION_PROVIDER",
	"INSTALL_PACKAGES",
	"INSTALL_SHORTCUT",
	"INTERNAL_SYSTEM_WINDOW",
	"INTERNET",
	"KILL_BACKGROUND_PROCESSES",
	"LOCATION_HARDWARE",
	"MANAGE_ACCOUNTS",
	"MANAGE_APP_TOKENS",
	"MANAGE_DOCUMENTS",
	"MASTER_CLEAR",
	"MEDIA_CONTENT_CONTROL",
	"MODIFY_AUDIO_SETTINGS",
	"MODIFY_PHONE_STATE",
	"MOUNT_FORMAT_FILESYSTEMS",
	"MOUNT_UNMOUNT_FILESYSTEMS",
	"NFC",
	"PERSISTENT_ACTIVITY",
	"PROCESS_OUTGOING_CALLS",
	"READ_CALENDAR",
	"READ_CALL_LOG",
	"READ_CONTACTS",
	"READ_EXTERNAL_STORAGE",
	"READ_FRAME_BUFFER",
	"READ_HISTORY_BOOKMARKS",
	"READ_INPUT_STATE",
	"READ_LOGS",
	"READ_PHONE_STATE",
	"READ_PROFILE",
	"READ_SMS",
	"READ_SOCIAL_STREAM",
	"READ_SYNC_SETTINGS",
	"READ_SYNC_STATS",
	"READ_USER_DICTIONARY",
	"REBOOT",
	"RECEIVE_BOOT_COMPLETED",
	"RECEIVE_MMS",
	"RECEIVE_SMS",
	"RECEIVE_WAP_PUSH",
	"RECORD_AUDIO",
	"REORDER_TASKS",
	"RESTART_PACKAGES",
	"SEND_RESPOND_VIA_MESSAGE",
	"SEND_SMS",
	"SET_ACTIVITY_WATCHER",
	"SET_ALARM",
	"SET_ALWAYS_FINISH",
	"SET_ANIMATION_SCALE",
	"SET_DEBUG_APP",
	"SET_ORIENTATION",
	"SET_POINTER_SPEED",
	"SET_PREFERRED_APPLICATIONS",
	"SET_PROCESS_LIMIT",
	"SET_TIME",
	"SET_TIME_ZONE",
	"SET_WALLPAPER",
	"SET_WALLPAPER_HINTS",
	"SIGNAL_PERSISTENT_PROCESSES",
	"STATUS_BAR",
	"SUBSCRIBED_FEEDS_READ",
	"SUBSCRIBED_FEEDS_WRITE",
	"SYSTEM_ALERT_WINDOW",
	"TRANSMIT_IR",
	"UNINSTALL_SHORTCUT",
	"UPDATE_DEVICE_STATS",
	"USE_CREDENTIALS",
	"USE_SIP",
	"VIBRATE",
	"WAKE_LOCK",
	"WRITE_APN_SETTINGS",
	"WRITE_CALENDAR",
	"WRITE_CALL_LOG",
	"WRITE_CONTACTS",
	"WRITE_EXTERNAL_STORAGE",
	"WRITE_GSERVICES",
	"WRITE_HISTORY_BOOKMARKS",
	"WRITE_PROFILE",
	"WRITE_SECURE_SETTINGS",
	"WRITE_SETTINGS",
	"WRITE_SMS",
	"WRITE_SOCIAL_STREAM",
	"WRITE_SYNC_SETTINGS",
	"WRITE_USER_DICTIONARY",
	nullptr
};

static const char *SPLASH_IMAGE_EXPORT_PATH = "res/drawable/splash.png";
static const char *SPLASH_BG_COLOR_PATH = "res/drawable/splash_bg_color.png";

struct LauncherIcon {
	const char *export_path;
	int dimensions;
};

static const int icon_densities_count = 6;
static const char *launcher_icon_option = "launcher_icons/main_192x192";
static const char *launcher_adaptive_icon_foreground_option = "launcher_icons/adaptive_foreground_432x432";
static const char *launcher_adaptive_icon_background_option = "launcher_icons/adaptive_background_432x432";

static const LauncherIcon launcher_icons[icon_densities_count] = {
	{ "res/mipmap-xxxhdpi-v4/icon.png", 192 },
	{ "res/mipmap-xxhdpi-v4/icon.png", 144 },
	{ "res/mipmap-xhdpi-v4/icon.png", 96 },
	{ "res/mipmap-hdpi-v4/icon.png", 72 },
	{ "res/mipmap-mdpi-v4/icon.png", 48 },
	{ "res/mipmap/icon.png", 192 }
};

static const LauncherIcon launcher_adaptive_icon_foregrounds[icon_densities_count] = {
	{ "res/mipmap-xxxhdpi-v4/icon_foreground.png", 432 },
	{ "res/mipmap-xxhdpi-v4/icon_foreground.png", 324 },
	{ "res/mipmap-xhdpi-v4/icon_foreground.png", 216 },
	{ "res/mipmap-hdpi-v4/icon_foreground.png", 162 },
	{ "res/mipmap-mdpi-v4/icon_foreground.png", 108 },
	{ "res/mipmap/icon_foreground.png", 432 }
};

static const LauncherIcon launcher_adaptive_icon_backgrounds[icon_densities_count] = {
	{ "res/mipmap-xxxhdpi-v4/icon_background.png", 432 },
	{ "res/mipmap-xxhdpi-v4/icon_background.png", 324 },
	{ "res/mipmap-xhdpi-v4/icon_background.png", 216 },
	{ "res/mipmap-hdpi-v4/icon_background.png", 162 },
	{ "res/mipmap-mdpi-v4/icon_background.png", 108 },
	{ "res/mipmap/icon_background.png", 432 }
};

class EditorExportPlatformAndroid : public EditorExportPlatform {
	GDCLASS(EditorExportPlatformAndroid, EditorExportPlatform);

	Ref<ImageTexture> logo;
	Ref<ImageTexture> run_icon;

	struct Device {
		String id;
		String name;
		String description;
		int api_level;
	};

	struct APKExportData {
		zipFile apk;
		EditorProgress *ep;
	};

	Vector<PluginConfig> plugins;
	String last_plugin_names;
	uint64_t last_custom_build_time = 0;
	volatile bool plugins_changed;
	Mutex plugins_lock;
	Vector<Device> devices;<--- Shadowed declaration
	volatile bool devices_changed;
	Mutex device_lock;
	Thread *check_for_changes_thread;
	volatile bool quit_request;

	static void _check_for_changes_poll_thread(void *ud) {
		EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud;

		while (!ea->quit_request) {
			// Check for plugins updates
			{
				// Nothing to do if we already know the plugins have changed.
				if (!ea->plugins_changed) {
					Vector<PluginConfig> loaded_plugins = get_plugins();

					MutexLock lock(ea->plugins_lock);

					if (ea->plugins.size() != loaded_plugins.size()) {
						ea->plugins_changed = true;
					} else {
						for (int i = 0; i < ea->plugins.size(); i++) {
							if (ea->plugins[i].name != loaded_plugins[i].name) {
								ea->plugins_changed = true;
								break;
							}
						}
					}

					if (ea->plugins_changed) {
						ea->plugins = loaded_plugins;
					}
				}
			}

			// Check for devices updates
			String adb = EditorSettings::get_singleton()->get("export/android/adb");
			if (FileAccess::exists(adb)) {
				String devices;<--- Shadow variable
				List<String> args;
				args.push_back("devices");
				int ec;
				OS::get_singleton()->execute(adb, args, true, nullptr, &devices, &ec);

				Vector<String> ds = devices.split("\n");
				Vector<String> ldevices;
				for (int i = 1; i < ds.size(); i++) {
					String d = ds[i];
					int dpos = d.find("device");
					if (dpos == -1) {
						continue;
					}
					d = d.substr(0, dpos).strip_edges();
					ldevices.push_back(d);
				}

				MutexLock lock(ea->device_lock);

				bool different = false;

				if (ea->devices.size() != ldevices.size()) {
					different = true;
				} else {
					for (int i = 0; i < ea->devices.size(); i++) {
						if (ea->devices[i].id != ldevices[i]) {
							different = true;
							break;
						}
					}
				}

				if (different) {
					Vector<Device> ndevices;

					for (int i = 0; i < ldevices.size(); i++) {
						Device d;
						d.id = ldevices[i];
						for (int j = 0; j < ea->devices.size(); j++) {
							if (ea->devices[j].id == ldevices[i]) {
								d.description = ea->devices[j].description;
								d.name = ea->devices[j].name;
								d.api_level = ea->devices[j].api_level;
							}
						}

						if (d.description == "") {
							//in the oven, request!
							args.clear();
							args.push_back("-s");
							args.push_back(d.id);
							args.push_back("shell");
							args.push_back("getprop");
							int ec2;
							String dp;

							OS::get_singleton()->execute(adb, args, true, nullptr, &dp, &ec2);

							Vector<String> props = dp.split("\n");
							String vendor;
							String device;
							d.description = "Device ID: " + d.id + "\n";
							d.api_level = 0;
							for (int j = 0; j < props.size(); j++) {
								// got information by `shell cat /system/build.prop` before and its format is "property=value"
								// it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above
								// its format is "[property]: [value]" so changed it as like build.prop
								String p = props[j];
								p = p.replace("]: ", "=");
								p = p.replace("[", "");
								p = p.replace("]", "");

								if (p.begins_with("ro.product.model=")) {
									device = p.get_slice("=", 1).strip_edges();
								} else if (p.begins_with("ro.product.brand=")) {
									vendor = p.get_slice("=", 1).strip_edges().capitalize();
								} else if (p.begins_with("ro.build.display.id=")) {
									d.description += "Build: " + p.get_slice("=", 1).strip_edges() + "\n";
								} else if (p.begins_with("ro.build.version.release=")) {
									d.description += "Release: " + p.get_slice("=", 1).strip_edges() + "\n";
								} else if (p.begins_with("ro.build.version.sdk=")) {
									d.api_level = p.get_slice("=", 1).to_int();
								} else if (p.begins_with("ro.product.cpu.abi=")) {
									d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n";
								} else if (p.begins_with("ro.product.manufacturer=")) {
									d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n";
								} else if (p.begins_with("ro.board.platform=")) {
									d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n";
								} else if (p.begins_with("ro.opengles.version=")) {
									uint32_t opengl = p.get_slice("=", 1).to_int();
									d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n";
								}
							}

							d.name = vendor + " " + device;
							if (device == String()) {
								continue;
							}
						}

						ndevices.push_back(d);
					}

					ea->devices = ndevices;
					ea->devices_changed = true;
				}
			}

			uint64_t sleep = 200;
			uint64_t wait = 3000000;
			uint64_t time = OS::get_singleton()->get_ticks_usec();
			while (OS::get_singleton()->get_ticks_usec() - time < wait) {
				OS::get_singleton()->delay_usec(1000 * sleep);
				if (ea->quit_request) {
					break;
				}
			}
		}

		if (EditorSettings::get_singleton()->get("export/android/shutdown_adb_on_exit")) {
			String adb = EditorSettings::get_singleton()->get("export/android/adb");
			if (!FileAccess::exists(adb)) {
				return; //adb not configured
			}

			List<String> args;
			args.push_back("kill-server");
			OS::get_singleton()->execute(adb, args, true);
		};
	}

	String get_project_name(const String &p_name) const {
		String aname;
		if (p_name != "") {
			aname = p_name;
		} else {
			aname = ProjectSettings::get_singleton()->get("application/config/name");
		}

		if (aname == "") {
			aname = VERSION_NAME;
		}

		return aname;
	}

	String get_package_name(const String &p_package) const {
		String pname = p_package;
		String basename = ProjectSettings::get_singleton()->get("application/config/name");
		basename = basename.to_lower();

		String name;
		bool first = true;
		for (int i = 0; i < basename.length(); i++) {
			char32_t c = basename[i];
			if (c >= '0' && c <= '9' && first) {
				continue;
			}
			if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
				name += String::chr(c);
				first = false;
			}
		}
		if (name == "") {
			name = "noname";
		}

		pname = pname.replace("$genname", name);

		return pname;
	}

	bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const {
		String pname = p_package;

		if (pname.length() == 0) {
			if (r_error) {
				*r_error = TTR("Package name is missing.");
			}
			return false;
		}

		int segments = 0;
		bool first = true;
		for (int i = 0; i < pname.length(); i++) {
			char32_t c = pname[i];
			if (first && c == '.') {
				if (r_error) {
					*r_error = TTR("Package segments must be of non-zero length.");
				}
				return false;
			}
			if (c == '.') {
				segments++;
				first = true;
				continue;
			}
			if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) {
				if (r_error) {
					*r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c));
				}
				return false;
			}
			if (first && (c >= '0' && c <= '9')) {
				if (r_error) {
					*r_error = TTR("A digit cannot be the first character in a package segment.");
				}
				return false;
			}
			if (first && c == '_') {
				if (r_error) {
					*r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c));
				}
				return false;
			}
			first = false;
		}

		if (segments == 0) {
			if (r_error) {
				*r_error = TTR("The package must have at least one '.' separator.");
			}
			return false;
		}

		if (first) {
			if (r_error) {
				*r_error = TTR("Package segments must be of non-zero length.");
			}
			return false;
		}

		return true;
	}

	static bool _should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) {
		/*
		 *  By not compressing files with little or not benefit in doing so,
		 *  a performance gain is expected attime. Moreover, if the APK is
		 *  zip-aligned, assets stored as they are can be efficiently read by
		 *  Android by memory-mapping them.
		 */

		// -- Unconditional uncompress to mimic AAPT plus some other

		static const char *unconditional_compress_ext[] = {
			// From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp
			// These formats are already compressed, or don't compress well:
			".jpg", ".jpeg", ".png", ".gif",
			".wav", ".mp2", ".mp3", ".ogg", ".aac",
			".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
			".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
			".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
			".amr", ".awb", ".wma", ".wmv",
			// Godot-specific:
			".webp", // Same reasoning as .png
			".cfb", // Don't let small config files slow-down startup
			".scn", // Binary scenes are usually already compressed
			".stex", // Streamable textures are usually already compressed
			// Trailer for easier processing
			nullptr
		};

		for (const char **ext = unconditional_compress_ext; *ext; ++ext) {
			if (p_path.to_lower().ends_with(String(*ext))) {
				return false;
			}
		}

		// -- Compressed resource?

		if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') {
			// Already compressed
			return false;
		}

		// --- TODO: Decide on texture resources according to their image compression setting

		return true;
	}

	static zip_fileinfo get_zip_fileinfo() {
		OS::Time time = OS::get_singleton()->get_time();
		OS::Date date = OS::get_singleton()->get_date();

		zip_fileinfo zipfi;
		zipfi.tmz_date.tm_hour = time.hour;
		zipfi.tmz_date.tm_mday = date.day;
		zipfi.tmz_date.tm_min = time.min;
		zipfi.tmz_date.tm_mon = date.month - 1; // tm_mon is zero indexed
		zipfi.tmz_date.tm_sec = time.sec;
		zipfi.tmz_date.tm_year = date.year;
		zipfi.dosDate = 0;
		zipfi.external_fa = 0;
		zipfi.internal_fa = 0;

		return zipfi;
	}

	static Vector<String> get_abis() {
		Vector<String> abis;
		abis.push_back("armeabi-v7a");
		abis.push_back("arm64-v8a");
		abis.push_back("x86");
		abis.push_back("x86_64");
		return abis;
	}

	/// List the gdap files in the directory specified by the p_path parameter.
	static Vector<String> list_gdap_files(const String &p_path) {
		Vector<String> dir_files;
		DirAccessRef da = DirAccess::open(p_path);
		if (da) {
			da->list_dir_begin();
			while (true) {
				String file = da->get_next();
				if (file == "") {
					break;
				}

				if (da->current_is_dir() || da->current_is_hidden()) {
					continue;
				}

				if (file.ends_with(PLUGIN_CONFIG_EXT)) {
					dir_files.push_back(file);
				}
			}
			da->list_dir_end();
		}

		return dir_files;
	}

	static Vector<PluginConfig> get_plugins() {
		Vector<PluginConfig> loaded_plugins;

		String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/plugins");

		// Add the prebuilt plugins
		loaded_plugins.append_array(get_prebuilt_plugins(plugins_dir));

		if (DirAccess::exists(plugins_dir)) {
			Vector<String> plugins_filenames = list_gdap_files(plugins_dir);

			if (!plugins_filenames.empty()) {
				Ref<ConfigFile> config_file = memnew(ConfigFile);
				for (int i = 0; i < plugins_filenames.size(); i++) {
					PluginConfig config = load_plugin_config(config_file, plugins_dir.plus_file(plugins_filenames[i]));
					if (config.valid_config) {
						loaded_plugins.push_back(config);
					} else {
						print_error("Invalid plugin config file " + plugins_filenames[i]);
					}
				}
			}
		}

		return loaded_plugins;
	}

	static Vector<PluginConfig> get_enabled_plugins(const Ref<EditorExportPreset> &p_presets) {
		Vector<PluginConfig> enabled_plugins;
		Vector<PluginConfig> all_plugins = get_plugins();
		for (int i = 0; i < all_plugins.size(); i++) {
			PluginConfig plugin = all_plugins[i];
			bool enabled = p_presets->get("plugins/" + plugin.name);
			if (enabled) {
				enabled_plugins.push_back(plugin);
			}
		}

		return enabled_plugins;
	}

	static Error store_in_apk(APKExportData *ed, const String &p_path, const Vector<uint8_t> &p_data, int compression_method = Z_DEFLATED) {
		zip_fileinfo zipfi = get_zip_fileinfo();
		zipOpenNewFileInZip(ed->apk,
				p_path.utf8().get_data(),
				&zipfi,
				nullptr,
				0,
				nullptr,
				0,
				nullptr,
				compression_method,
				Z_DEFAULT_COMPRESSION);

		zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size());
		zipCloseFileInZip(ed->apk);

		return OK;
	}

	static Error save_apk_so(void *p_userdata, const SharedObject &p_so) {
		if (!p_so.path.get_file().begins_with("lib")) {
			String err = "Android .so file names must start with \"lib\", but got: " + p_so.path;
			ERR_PRINT(err);
			return FAILED;
		}
		APKExportData *ed = (APKExportData *)p_userdata;
		Vector<String> abis = get_abis();
		bool exported = false;
		for (int i = 0; i < p_so.tags.size(); ++i) {
			// shared objects can be fat (compatible with multiple ABIs)
			int abi_index = abis.find(p_so.tags[i]);
			if (abi_index != -1) {
				exported = true;
				String abi = abis[abi_index];
				String dst_path = String("lib").plus_file(abi).plus_file(p_so.path.get_file());
				Vector<uint8_t> array = FileAccess::get_file_as_array(p_so.path);
				Error store_err = store_in_apk(ed, dst_path, array);
				ERR_FAIL_COND_V_MSG(store_err, store_err, "Cannot store in apk file '" + dst_path + "'.");
			}
		}
		if (!exported) {
			String abis_string = String(" ").join(abis);
			String err = "Cannot determine ABI for library \"" + p_so.path + "\". One of the supported ABIs must be used as a tag: " + abis_string;
			ERR_PRINT(err);
			return FAILED;
		}
		return OK;
	}

	static Error save_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) {
		APKExportData *ed = (APKExportData *)p_userdata;
		String dst_path = p_path.replace_first("res://", "assets/");

		store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0);
		return OK;
	}

	static Error ignore_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) {
		return OK;
	}

	void _get_permissions(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, Vector<String> &r_permissions) {
		const char **aperms = android_perms;
		while (*aperms) {
			bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());
			if (enabled) {
				r_permissions.push_back("android.permission." + String(*aperms));
			}
			aperms++;
		}
		PackedStringArray user_perms = p_preset->get("permissions/custom_permissions");
		for (int i = 0; i < user_perms.size(); i++) {
			String user_perm = user_perms[i].strip_edges();
			if (!user_perm.empty()) {
				r_permissions.push_back(user_perm);
			}
		}
		if (p_give_internet) {
			if (r_permissions.find("android.permission.INTERNET") == -1) {
				r_permissions.push_back("android.permission.INTERNET");
			}
		}

		int xr_mode_index = p_preset->get("xr_features/xr_mode");
		if (xr_mode_index == 1 /* XRMode.OVR */) {
			int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required
			if (hand_tracking_index > 0) {
				if (r_permissions.find("com.oculus.permission.HAND_TRACKING") == -1) {
					r_permissions.push_back("com.oculus.permission.HAND_TRACKING");
				}
			}
		}
	}

	void _write_tmp_manifest(const Ref<EditorExportPreset> &p_preset, bool p_give_internet, bool p_debug) {
		String manifest_text =
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
				"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
				"    xmlns:tools=\"http://schemas.android.com/tools\">\n";

		manifest_text += _get_screen_sizes_tag(p_preset);
		manifest_text += _get_gles_tag();

		Vector<String> perms;
		_get_permissions(p_preset, p_give_internet, perms);
		for (int i = 0; i < perms.size(); i++) {
			manifest_text += vformat("    <uses-permission android:name=\"%s\" />\n", perms.get(i));
		}

		manifest_text += _get_xr_features_tag(p_preset);
		manifest_text += _get_instrumentation_tag(p_preset);
		String plugins_names = get_plugins_names(get_enabled_plugins(p_preset));
		manifest_text += _get_application_tag(p_preset, plugins_names);
		manifest_text += "</manifest>\n";
		String manifest_path = vformat("res://android/build/src/%s/AndroidManifest.xml", (p_debug ? "debug" : "release"));
		store_string_at_path(manifest_path, manifest_text);
	}

	void _fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {
		// Leaving the unused types commented because looking these constants up
		// again later would be annoying
		// const int CHUNK_AXML_FILE = 0x00080003;
		// const int CHUNK_RESOURCEIDS = 0x00080180;
		const int CHUNK_STRINGS = 0x001C0001;
		// const int CHUNK_XML_END_NAMESPACE = 0x00100101;
		const int CHUNK_XML_END_TAG = 0x00100103;
		// const int CHUNK_XML_START_NAMESPACE = 0x00100100;
		const int CHUNK_XML_START_TAG = 0x00100102;
		// const int CHUNK_XML_TEXT = 0x00100104;
		const int UTF8_FLAG = 0x00000100;

		Vector<String> string_table;

		uint32_t ofs = 8;

		uint32_t string_count = 0;
		//uint32_t styles_count = 0;
		uint32_t string_flags = 0;
		uint32_t string_data_offset = 0;

		//uint32_t styles_offset = 0;
		uint32_t string_table_begins = 0;
		uint32_t string_table_ends = 0;
		Vector<uint8_t> stable_extra;

		String version_name = p_preset->get("version/name");
		int version_code = p_preset->get("version/code");
		String package_name = p_preset->get("package/unique_name");

		const int screen_orientation = _get_android_orientation_value(_get_screen_orientation());

		bool screen_support_small = p_preset->get("screen/support_small");
		bool screen_support_normal = p_preset->get("screen/support_normal");
		bool screen_support_large = p_preset->get("screen/support_large");
		bool screen_support_xlarge = p_preset->get("screen/support_xlarge");

		int xr_mode_index = p_preset->get("xr_features/xr_mode");
		bool focus_awareness = p_preset->get("xr_features/focus_awareness");

		String plugins_names = get_plugins_names(get_enabled_plugins(p_preset));

		Vector<String> perms;
		// Write permissions into the perms variable.
		_get_permissions(p_preset, p_give_internet, perms);

		while (ofs < (uint32_t)p_manifest.size()) {
			uint32_t chunk = decode_uint32(&p_manifest[ofs]);
			uint32_t size = decode_uint32(&p_manifest[ofs + 4]);

			switch (chunk) {
				case CHUNK_STRINGS: {
					int iofs = ofs + 8;

					string_count = decode_uint32(&p_manifest[iofs]);
					//styles_count = decode_uint32(&p_manifest[iofs + 4]);
					string_flags = decode_uint32(&p_manifest[iofs + 8]);
					string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
					//styles_offset = decode_uint32(&p_manifest[iofs + 16]);
					/*
					printf("string count: %i\n",string_count);
					printf("flags: %i\n",string_flags);
					printf("sdata ofs: %i\n",string_data_offset);
					printf("styles ofs: %i\n",styles_offset);
					*/
					uint32_t st_offset = iofs + 20;
					string_table.resize(string_count);
					uint32_t string_end = 0;

					string_table_begins = st_offset;

					for (uint32_t i = 0; i < string_count; i++) {
						uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
						string_at += st_offset + string_count * 4;

						ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table.");

						if (string_flags & UTF8_FLAG) {
						} else {
							uint32_t len = decode_uint16(&p_manifest[string_at]);
							Vector<char32_t> ucstring;
							ucstring.resize(len + 1);
							for (uint32_t j = 0; j < len; j++) {
								uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
								ucstring.write[j] = c;
							}
							string_end = MAX(string_at + 2 + 2 * len, string_end);
							ucstring.write[len] = 0;
							string_table.write[i] = ucstring.ptr();
						}
					}

					for (uint32_t i = string_end; i < (ofs + size); i++) {
						stable_extra.push_back(p_manifest[i]);
					}

					string_table_ends = ofs + size;

				} break;
				case CHUNK_XML_START_TAG: {
					int iofs = ofs + 8;
					uint32_t name = decode_uint32(&p_manifest[iofs + 12]);

					String tname = string_table[name];
					uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
					iofs += 28;
					bool is_focus_aware_metadata = false;

					for (uint32_t i = 0; i < attrcount; i++) {
						uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
						uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
						uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
						uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);

						const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid);
						String attrname = string_table[attr_name];
						const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : "";

						//replace project information
						if (tname == "manifest" && attrname == "package") {
							string_table.write[attr_value] = get_package_name(package_name);
						}

						if (tname == "manifest" && attrname == "versionCode") {
							encode_uint32(version_code, &p_manifest.write[iofs + 16]);
						}

						if (tname == "manifest" && attrname == "versionName") {
							if (attr_value == 0xFFFFFFFF) {
								WARN_PRINT("Version name in a resource, should be plain text");
							} else {
								string_table.write[attr_value] = version_name;
							}
						}

						if (tname == "instrumentation" && attrname == "targetPackage") {
							string_table.write[attr_value] = get_package_name(package_name);
						}

						if (tname == "activity" && attrname == "screenOrientation") {
							encode_uint32(screen_orientation, &p_manifest.write[iofs + 16]);
						}

						if (tname == "supports-screens") {
							if (attrname == "smallScreens") {
								encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);

							} else if (attrname == "normalScreens") {
								encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);

							} else if (attrname == "largeScreens") {
								encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);

							} else if (attrname == "xlargeScreens") {
								encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
							}
						}

						// FIXME: `attr_value != 0xFFFFFFFF` below added as a stopgap measure for GH-32553,
						// but the issue should be debugged further and properly addressed.
						if (tname == "meta-data" && attrname == "name" && value == "xr_mode_metadata_name") {
							// Update the meta-data 'android:name' attribute based on the selected XR mode.
							if (xr_mode_index == 1 /* XRMode.OVR */) {
								string_table.write[attr_value] = "com.samsung.android.vr.application.mode";
							}
						}

						if (tname == "meta-data" && attrname == "value" && value == "xr_mode_metadata_value") {
							// Update the meta-data 'android:value' attribute based on the selected XR mode.
							if (xr_mode_index == 1 /* XRMode.OVR */) {
								string_table.write[attr_value] = "vr_only";
							}
						}

						if (tname == "meta-data" && attrname == "value" && is_focus_aware_metadata) {
							// Update the focus awareness meta-data value
							encode_uint32(xr_mode_index == /* XRMode.OVR */ 1 && focus_awareness ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
						}

						if (tname == "meta-data" && attrname == "value" && value == "plugins_value" && !plugins_names.empty()) {
							// Update the meta-data 'android:value' attribute with the list of enabled plugins.
							string_table.write[attr_value] = plugins_names;
						}

						is_focus_aware_metadata = tname == "meta-data" && attrname == "name" && value == "com.oculus.vr.focusaware";
						iofs += 20;
					}

				} break;
				case CHUNK_XML_END_TAG: {
					int iofs = ofs + 8;
					uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
					String tname = string_table[name];

					if (tname == "uses-feature") {
						Vector<String> feature_names;
						Vector<bool> feature_required_list;
						Vector<int> feature_versions;

						if (xr_mode_index == 1 /* XRMode.OVR */) {
							// Check for degrees of freedom
							int dof_index = p_preset->get("xr_features/degrees_of_freedom"); // 0: none, 1: 3dof and 6dof, 2: 6dof

							if (dof_index > 0) {
								feature_names.push_back("android.hardware.vr.headtracking");
								feature_required_list.push_back(dof_index == 2);
								feature_versions.push_back(1);
							}

							// Check for hand tracking
							int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required
							if (hand_tracking_index > 0) {
								feature_names.push_back("oculus.software.handtracking");
								feature_required_list.push_back(hand_tracking_index == 2);
								feature_versions.push_back(-1); // no version attribute should be added.
							}
						}

						if (feature_names.size() > 0) {
							ofs += 24; // skip over end tag

							// save manifest ending so we can restore it
							Vector<uint8_t> manifest_end;
							uint32_t manifest_cur_size = p_manifest.size();

							manifest_end.resize(p_manifest.size() - ofs);
							memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());

							int32_t attr_name_string = string_table.find("name");
							ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");

							int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android");
							if (ns_android_string == -1) {
								string_table.push_back("http://schemas.android.com/apk/res/android");
								ns_android_string = string_table.size() - 1;
							}

							int32_t attr_uses_feature_string = string_table.find("uses-feature");
							if (attr_uses_feature_string == -1) {
								string_table.push_back("uses-feature");
								attr_uses_feature_string = string_table.size() - 1;
							}

							int32_t attr_required_string = string_table.find("required");
							if (attr_required_string == -1) {
								string_table.push_back("required");
								attr_required_string = string_table.size() - 1;
							}

							for (int i = 0; i < feature_names.size(); i++) {
								String feature_name = feature_names[i];
								bool feature_required = feature_required_list[i];
								int feature_version = feature_versions[i];
								bool has_version_attribute = feature_version != -1;

								print_line("Adding feature " + feature_name);

								int32_t feature_string = string_table.find(feature_name);
								if (feature_string == -1) {
									string_table.push_back(feature_name);
									feature_string = string_table.size() - 1;
								}

								String required_value_string = feature_required ? "true" : "false";
								int32_t required_value = string_table.find(required_value_string);
								if (required_value == -1) {
									string_table.push_back(required_value_string);
									required_value = string_table.size() - 1;
								}

								int32_t attr_version_string = -1;
								int32_t version_value = -1;
								int tag_size;
								int attr_count;
								if (has_version_attribute) {
									attr_version_string = string_table.find("version");
									if (attr_version_string == -1) {
										string_table.push_back("version");
										attr_version_string = string_table.size() - 1;
									}

									version_value = string_table.find(itos(feature_version));
									if (version_value == -1) {
										string_table.push_back(itos(feature_version));
										version_value = string_table.size() - 1;
									}

									tag_size = 96; // node and three attrs + end node
									attr_count = 3;
								} else {
									tag_size = 76; // node and two attrs + end node
									attr_count = 2;
								}
								manifest_cur_size += tag_size + 24;
								p_manifest.resize(manifest_cur_size);

								// start tag
								encode_uint16(0x102, &p_manifest.write[ofs]); // type
								encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
								encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size
								encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
								encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
								encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
								encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name
								encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
								encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
								encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs
								encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
								encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
								encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index

								// android:name attribute
								encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
								encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
								encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value
								encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
								p_manifest.write[ofs + 50] = 0; // typedvalue_always0
								p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
								encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference

								// android:required attribute
								encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns
								encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name'
								encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value
								encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size
								p_manifest.write[ofs + 70] = 0; // typedvalue_always0
								p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string)
								encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference

								ofs += 76;

								if (has_version_attribute) {
									// android:version attribute
									encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns
									encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name'
									encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value
									encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size
									p_manifest.write[ofs + 14] = 0; // typedvalue_always0
									p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string)
									encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference

									ofs += 20;
								}

								// end tag
								encode_uint16(0x103, &p_manifest.write[ofs]); // type
								encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
								encode_uint32(24, &p_manifest.write[ofs + 4]); // size
								encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
								encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
								encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
								encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name

								ofs += 24;
							}
							memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
							ofs -= 24; // go back over back end
						}
					}
					if (tname == "manifest") {
						// save manifest ending so we can restore it
						Vector<uint8_t> manifest_end;
						uint32_t manifest_cur_size = p_manifest.size();

						manifest_end.resize(p_manifest.size() - ofs);
						memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());

						int32_t attr_name_string = string_table.find("name");
						ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute.");

						int32_t ns_android_string = string_table.find("android");
						ERR_FAIL_COND_MSG(ns_android_string == -1, "Template does not have 'android' namespace.");

						int32_t attr_uses_permission_string = string_table.find("uses-permission");
						if (attr_uses_permission_string == -1) {
							string_table.push_back("uses-permission");
							attr_uses_permission_string = string_table.size() - 1;
						}

						for (int i = 0; i < perms.size(); ++i) {
							print_line("Adding permission " + perms[i]);

							manifest_cur_size += 56 + 24; // node + end node
							p_manifest.resize(manifest_cur_size);

							// Add permission to the string pool
							int32_t perm_string = string_table.find(perms[i]);
							if (perm_string == -1) {
								string_table.push_back(perms[i]);
								perm_string = string_table.size() - 1;
							}

							// start tag
							encode_uint16(0x102, &p_manifest.write[ofs]); // type
							encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
							encode_uint32(56, &p_manifest.write[ofs + 4]); // size
							encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
							encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
							encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
							encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
							encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
							encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
							encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
							encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
							encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
							encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index

							// attribute
							encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
							encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
							encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
							encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
							p_manifest.write[ofs + 50] = 0; // typedvalue_always0
							p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
							encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference

							ofs += 56;

							// end tag
							encode_uint16(0x103, &p_manifest.write[ofs]); // type
							encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
							encode_uint32(24, &p_manifest.write[ofs + 4]); // size
							encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
							encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
							encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
							encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name

							ofs += 24;
						}

						// copy footer back in
						memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
					}
				} break;
			}

			ofs += size;
		}

		//create new andriodmanifest binary

		Vector<uint8_t> ret;
		ret.resize(string_table_begins + string_table.size() * 4);

		for (uint32_t i = 0; i < string_table_begins; i++) {
			ret.write[i] = p_manifest[i];
		}

		ofs = 0;
		for (int i = 0; i < string_table.size(); i++) {
			encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
			ofs += string_table[i].length() * 2 + 2 + 2;
		}

		ret.resize(ret.size() + ofs);
		string_data_offset = ret.size() - ofs;
		uint8_t *chars = &ret.write[string_data_offset];
		for (int i = 0; i < string_table.size(); i++) {
			String s = string_table[i];
			encode_uint16(s.length(), chars);
			chars += 2;
			for (int j = 0; j < s.length(); j++) {
				encode_uint16(s[j], chars);
				chars += 2;
			}
			encode_uint16(0, chars);
			chars += 2;
		}

		for (int i = 0; i < stable_extra.size(); i++) {
			ret.push_back(stable_extra[i]);
		}

		//pad
		while (ret.size() % 4) {
			ret.push_back(0);
		}

		uint32_t new_stable_end = ret.size();

		uint32_t extra = (p_manifest.size() - string_table_ends);
		ret.resize(new_stable_end + extra);
		for (uint32_t i = 0; i < extra; i++) {
			ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
		}

		while (ret.size() % 4) {
			ret.push_back(0);
		}
		encode_uint32(ret.size(), &ret.write[4]); //update new file size

		encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
		encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
		encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset

		p_manifest = ret;
	}

	static String _parse_string(const uint8_t *p_bytes, bool p_utf8) {
		uint32_t offset = 0;
		uint32_t len = 0;

		if (p_utf8) {
			uint8_t byte = p_bytes[offset];
			if (byte & 0x80) {
				offset += 2;
			} else {
				offset += 1;
			}
			byte = p_bytes[offset];
			offset++;
			if (byte & 0x80) {
				len = byte & 0x7F;
				len = (len << 8) + p_bytes[offset];
				offset++;
			} else {
				len = byte;
			}
		} else {
			len = decode_uint16(&p_bytes[offset]);
			offset += 2;
			if (len & 0x8000) {
				len &= 0x7FFF;
				len = (len << 16) + decode_uint16(&p_bytes[offset]);
				offset += 2;
			}
		}

		if (p_utf8) {
			Vector<uint8_t> str8;
			str8.resize(len + 1);
			for (uint32_t i = 0; i < len; i++) {
				str8.write[i] = p_bytes[offset + i];
			}
			str8.write[len] = 0;
			String str;
			str.parse_utf8((const char *)str8.ptr());
			return str;
		} else {
			String str;
			for (uint32_t i = 0; i < len; i++) {
				char32_t c = decode_uint16(&p_bytes[offset + i * 2]);
				if (c == 0) {
					break;
				}
				str += String::chr(c);
			}
			return str;
		}
	}

	void _fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &r_manifest) {
		const int UTF8_FLAG = 0x00000100;

		uint32_t string_block_len = decode_uint32(&r_manifest[16]);
		uint32_t string_count = decode_uint32(&r_manifest[20]);
		uint32_t string_flags = decode_uint32(&r_manifest[28]);
		const uint32_t string_table_begins = 40;

		Vector<String> string_table;

		String package_name = p_preset->get("package/name");

		for (uint32_t i = 0; i < string_count; i++) {
			uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]);
			offset += string_table_begins + string_count * 4;

			String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG);

			if (str.begins_with("godot-project-name")) {
				if (str == "godot-project-name") {
					//project name
					str = get_project_name(package_name);

				} else {
					String lang = str.substr(str.rfind("-") + 1, str.length()).replace("-", "_");
					String prop = "application/config/name_" + lang;
					if (ProjectSettings::get_singleton()->has_setting(prop)) {
						str = ProjectSettings::get_singleton()->get(prop);
					} else {
						str = get_project_name(package_name);
					}
				}
			}

			string_table.push_back(str);
		}

		//write a new string table, but use 16 bits
		Vector<uint8_t> ret;
		ret.resize(string_table_begins + string_table.size() * 4);

		for (uint32_t i = 0; i < string_table_begins; i++) {
			ret.write[i] = r_manifest[i];
		}

		int ofs = 0;
		for (int i = 0; i < string_table.size(); i++) {
			encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
			ofs += string_table[i].length() * 2 + 2 + 2;
		}

		ret.resize(ret.size() + ofs);
		uint8_t *chars = &ret.write[ret.size() - ofs];
		for (int i = 0; i < string_table.size(); i++) {
			String s = string_table[i];
			encode_uint16(s.length(), chars);
			chars += 2;
			for (int j = 0; j < s.length(); j++) {
				encode_uint16(s[j], chars);
				chars += 2;
			}
			encode_uint16(0, chars);
			chars += 2;
		}

		//pad
		while (ret.size() % 4) {
			ret.push_back(0);
		}

		//change flags to not use utf8
		encode_uint32(string_flags & ~0x100, &ret.write[28]);
		//change length
		encode_uint32(ret.size() - 12, &ret.write[16]);
		//append the rest...
		int rest_from = 12 + string_block_len;
		int rest_to = ret.size();
		int rest_len = (r_manifest.size() - rest_from);
		ret.resize(ret.size() + (r_manifest.size() - rest_from));
		for (int i = 0; i < rest_len; i++) {
			ret.write[rest_to + i] = r_manifest[rest_from + i];
		}
		//finally update the size
		encode_uint32(ret.size(), &ret.write[4]);

		r_manifest = ret;
		//printf("end\n");
	}

	void _load_image_data(const Ref<Image> &p_splash_image, Vector<uint8_t> &p_data) {
		Vector<uint8_t> png_buffer;
		Error err = PNGDriverCommon::image_to_png(p_splash_image, png_buffer);
		if (err == OK) {
			p_data.resize(png_buffer.size());
			memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());
		} else {
			String err_str = String("Failed to convert splash image to png.");
			WARN_PRINT(err_str.utf8().get_data());
		}
	}

	void _process_launcher_icons(const String &p_file_name, const Ref<Image> &p_source_image, int dimension, Vector<uint8_t> &p_data) {
		Ref<Image> working_image = p_source_image;

		if (p_source_image->get_width() != dimension || p_source_image->get_height() != dimension) {
			working_image = p_source_image->duplicate();
			working_image->resize(dimension, dimension, Image::Interpolation::INTERPOLATE_LANCZOS);
		}

		Vector<uint8_t> png_buffer;
		Error err = PNGDriverCommon::image_to_png(working_image, png_buffer);
		if (err == OK) {
			p_data.resize(png_buffer.size());
			memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size());
		} else {
			String err_str = String("Failed to convert resized icon (") + p_file_name + ") to png.";
			WARN_PRINT(err_str.utf8().get_data());
		}
	}

	void load_splash_refs(Ref<Image> &splash_image, Ref<Image> &splash_bg_color_image) {
		// TODO: Figure out how to handle remaining boot splash parameters (e.g: fullsize, filter)
		String project_splash_path = ProjectSettings::get_singleton()->get("application/boot_splash/image");

		if (!project_splash_path.empty()) {
			splash_image.instance();
			const Error err = ImageLoader::load_image(project_splash_path, splash_image);
			if (err) {
				splash_image.unref();
			}
		}

		if (splash_image.is_null()) {
			// Use the default
			splash_image = Ref<Image>(memnew(Image(boot_splash_png)));
		}

		// Setup the splash bg color
		bool bg_color_valid;
		Color bg_color = ProjectSettings::get_singleton()->get("application/boot_splash/bg_color", &bg_color_valid);
		if (!bg_color_valid) {
			bg_color = boot_splash_bg_color;
		}

		splash_bg_color_image.instance();
		splash_bg_color_image->create(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format());
		splash_bg_color_image->fill(bg_color);
	}

	void load_icon_refs(const Ref<EditorExportPreset> &p_preset, Ref<Image> &icon, Ref<Image> &foreground, Ref<Image> &background) {
		String project_icon_path = ProjectSettings::get_singleton()->get("application/config/icon");

		icon.instance();
		foreground.instance();
		background.instance();

		// Regular icon: user selection -> project icon -> default.
		String path = static_cast<String>(p_preset->get(launcher_icon_option)).strip_edges();
		if (path.empty() || ImageLoader::load_image(path, icon) != OK) {
			ImageLoader::load_image(project_icon_path, icon);
		}

		// Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default).
		path = static_cast<String>(p_preset->get(launcher_adaptive_icon_foreground_option)).strip_edges();
		if (path.empty() || ImageLoader::load_image(path, foreground) != OK) {
			foreground = icon;
		}

		// Adaptive background: user selection -> default.
		path = static_cast<String>(p_preset->get(launcher_adaptive_icon_background_option)).strip_edges();
		if (!path.empty()) {
			ImageLoader::load_image(path, background);
		}
	}

	void store_image(const LauncherIcon launcher_icon, const Vector<uint8_t> &data) {
		store_image(launcher_icon.export_path, data);
	}

	void store_image(const String &export_path, const Vector<uint8_t> &data) {
		String img_path = export_path.insert(0, "res://android/build/");
		store_file_at_path(img_path, data);
	}

	void _copy_icons_to_gradle_project(const Ref<EditorExportPreset> &p_preset,
			const Ref<Image> &splash_image,
			const Ref<Image> &splash_bg_color_image,
			const Ref<Image> &main_image,
			const Ref<Image> &foreground,
			const Ref<Image> &background) {
		// Store the splash image
		if (splash_image.is_valid() && !splash_image->empty()) {
			Vector<uint8_t> data;
			_load_image_data(splash_image, data);
			store_image(SPLASH_IMAGE_EXPORT_PATH, data);
		}

		// Store the splash bg color image
		if (splash_bg_color_image.is_valid() && !splash_bg_color_image->empty()) {
			Vector<uint8_t> data;
			_load_image_data(splash_bg_color_image, data);
			store_image(SPLASH_BG_COLOR_PATH, data);
		}

		// Prepare images to be resized for the icons. If some image ends up being uninitialized,
		// the default image from the export template will be used.

		for (int i = 0; i < icon_densities_count; ++i) {
			if (main_image.is_valid() && !main_image->empty()) {
				Vector<uint8_t> data;
				_process_launcher_icons(launcher_icons[i].export_path, main_image, launcher_icons[i].dimensions, data);
				store_image(launcher_icons[i], data);
			}

			if (foreground.is_valid() && !foreground->empty()) {
				Vector<uint8_t> data;
				_process_launcher_icons(launcher_adaptive_icon_foregrounds[i].export_path, foreground,
						launcher_adaptive_icon_foregrounds[i].dimensions, data);
				store_image(launcher_adaptive_icon_foregrounds[i], data);
			}

			if (background.is_valid() && !background->empty()) {
				Vector<uint8_t> data;
				_process_launcher_icons(launcher_adaptive_icon_backgrounds[i].export_path, background,
						launcher_adaptive_icon_backgrounds[i].dimensions, data);
				store_image(launcher_adaptive_icon_backgrounds[i], data);
			}
		}
	}

	static Vector<String> get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
		Vector<String> abis = get_abis();
		Vector<String> enabled_abis;
		for (int i = 0; i < abis.size(); ++i) {
			bool is_enabled = p_preset->get("architectures/" + abis[i]);
			if (is_enabled) {
				enabled_abis.push_back(abis[i]);
			}
		}
		return enabled_abis;
	}

public:
	typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key);

public:
	virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) override {
		String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
		if (driver == "GLES2") {
			r_features->push_back("etc");
		}
		// FIXME: Review what texture formats are used for Vulkan.
		if (driver == "Vulkan") {
			r_features->push_back("etc2");
		}

		Vector<String> abis = get_enabled_abis(p_preset);
		for (int i = 0; i < abis.size(); ++i) {
			r_features->push_back(abis[i]);
		}
	}

	virtual void get_export_options(List<ExportOption> *r_options) override {
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,Oculus Mobile VR"), 0));
		r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/degrees_of_freedom", PROPERTY_HINT_ENUM, "None,3DOF and 6DOF,6DOF"), 0));
		r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking", PROPERTY_HINT_ENUM, "None,Optional,Required"), 0));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "xr_features/focus_awareness"), false));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), false));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_template/use_custom_build"), false));
		r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "custom_template/export_format", PROPERTY_HINT_ENUM, "Export APK,Export AAB"), 0));

		Vector<PluginConfig> plugins_configs = get_plugins();
		for (int i = 0; i < plugins_configs.size(); i++) {
			print_verbose("Found Android plugin " + plugins_configs[i].name);
			r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "plugins/" + plugins_configs[i].name), false));
		}
		plugins_changed = false;

		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/opengl_debug"), false));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icon_option, PROPERTY_HINT_FILE, "*.png"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_foreground_option, PROPERTY_HINT_FILE, "*.png"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_background_option, PROPERTY_HINT_FILE, "*.png"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
		r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));

		Vector<String> abis = get_abis();
		for (int i = 0; i < abis.size(); ++i) {
			String abi = abis[i];
			bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a");
			r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default));
		}

		r_options->push_back(ExportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "permissions/custom_permissions"), PackedStringArray()));

		const char **perms = android_perms;
		while (*perms) {
			r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false));
			perms++;
		}
	}

	virtual String get_name() const override {
		return "Android";
	}

	virtual String get_os_name() const override {
		return "Android";
	}

	virtual Ref<Texture2D> get_logo() const override {
		return logo;
	}

	virtual bool should_update_export_options() override {
		bool export_options_changed = plugins_changed;
		if (export_options_changed) {
			// don't clear unless we're reporting true, to avoid race
			plugins_changed = false;
		}
		return export_options_changed;
	}

	virtual bool poll_export() override {
		bool dc = devices_changed;
		if (dc) {
			// don't clear unless we're reporting true, to avoid race
			devices_changed = false;
		}
		return dc;
	}

	virtual int get_options_count() const override {
		MutexLock lock(device_lock);
		return devices.size();
	}

	virtual String get_options_tooltip() const override {
		return TTR("Select device from the list");
	}

	virtual String get_option_label(int p_index) const override {
		ERR_FAIL_INDEX_V(p_index, devices.size(), "");
		MutexLock lock(device_lock);
		return devices[p_index].name;
	}

	virtual String get_option_tooltip(int p_index) const override {
		ERR_FAIL_INDEX_V(p_index, devices.size(), "");
		MutexLock lock(device_lock);
		String s = devices[p_index].description;
		if (devices.size() == 1) {
			// Tooltip will be:
			// Name
			// Description
			s = devices[p_index].name + "\n\n" + s;
		}
		return s;
	}

	virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) override {
		ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);

		String can_export_error;
		bool can_export_missing_templates;
		if (!can_export(p_preset, can_export_error, can_export_missing_templates)) {
			EditorNode::add_io_error(can_export_error);
			return ERR_UNCONFIGURED;
		}

		MutexLock lock(device_lock);

		EditorProgress ep("run", "Running on " + devices[p_device].name, 3);

		String adb = EditorSettings::get_singleton()->get("export/android/adb");

		// Export_temp APK.
		if (ep.step("Exporting APK...", 0)) {
			return ERR_SKIP;
		}

		const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
		const bool use_reverse = devices[p_device].api_level >= 21;

		if (use_reverse) {
			p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
		}

		String tmp_export_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport.apk");

#define CLEANUP_AND_RETURN(m_err)                         \
	{                                                     \
		DirAccess::remove_file_or_error(tmp_export_path); \
		return m_err;                                     \
	}

		// Export to temporary APK before sending to device.
		Error err = export_project(p_preset, true, tmp_export_path, p_debug_flags);

		if (err != OK) {
			CLEANUP_AND_RETURN(err);
		}

		List<String> args;
		int rv;

		bool remove_prev = p_preset->get("one_click_deploy/clear_previous_install");
		String version_name = p_preset->get("version/name");<--- Variable 'version_name' is assigned a value that is never used.
		String package_name = p_preset->get("package/unique_name");

		if (remove_prev) {
			if (ep.step("Uninstalling...", 1)) {
				CLEANUP_AND_RETURN(ERR_SKIP);
			}

			print_line("Uninstalling previous version: " + devices[p_device].name);

			args.push_back("-s");
			args.push_back(devices[p_device].id);
			args.push_back("uninstall");
			args.push_back(get_package_name(package_name));

			err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);<--- err is assigned
		}

		print_line("Installing to device (please wait...): " + devices[p_device].name);
		if (ep.step("Installing to device, please wait...", 2)) {
			CLEANUP_AND_RETURN(ERR_SKIP);
		}

		args.clear();
		args.push_back("-s");
		args.push_back(devices[p_device].id);
		args.push_back("install");
		args.push_back("-r");
		args.push_back(tmp_export_path);

		err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);<--- err is overwritten
		if (err || rv != 0) {
			EditorNode::add_io_error("Could not install to device.");
			CLEANUP_AND_RETURN(ERR_CANT_CREATE);
		}

		if (use_remote) {
			if (use_reverse) {
				static const char *const msg = "--- Device API >= 21; debugging over USB ---";
				EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
				print_line(String(msg).to_upper());

				args.clear();
				args.push_back("-s");
				args.push_back(devices[p_device].id);
				args.push_back("reverse");
				args.push_back("--remove-all");
				OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);

				if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) {
					int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port");
					args.clear();
					args.push_back("-s");
					args.push_back(devices[p_device].id);
					args.push_back("reverse");
					args.push_back("tcp:" + itos(dbg_port));
					args.push_back("tcp:" + itos(dbg_port));

					OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);
					print_line("Reverse result: " + itos(rv));
				}

				if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) {
					int fs_port = EditorSettings::get_singleton()->get("filesystem/file_server/port");

					args.clear();
					args.push_back("-s");
					args.push_back(devices[p_device].id);
					args.push_back("reverse");
					args.push_back("tcp:" + itos(fs_port));
					args.push_back("tcp:" + itos(fs_port));

					err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);<--- err is assigned
					print_line("Reverse result2: " + itos(rv));
				}
			} else {
				static const char *const msg = "--- Device API < 21; debugging over Wi-Fi ---";
				EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR);
				print_line(String(msg).to_upper());
			}
		}

		if (ep.step("Running on device...", 3)) {
			CLEANUP_AND_RETURN(ERR_SKIP);
		}
		args.clear();
		args.push_back("-s");
		args.push_back(devices[p_device].id);
		args.push_back("shell");
		args.push_back("am");
		args.push_back("start");
		if ((bool)EditorSettings::get_singleton()->get("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17
			args.push_back("--user");
			args.push_back("0");
		}
		args.push_back("-a");
		args.push_back("android.intent.action.MAIN");
		args.push_back("-n");
		args.push_back(get_package_name(package_name) + "/com.godot.game.GodotApp");

		err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv);<--- err is overwritten
		if (err || rv != 0) {
			EditorNode::add_io_error("Could not execute on device.");
			CLEANUP_AND_RETURN(ERR_CANT_CREATE);
		}

		CLEANUP_AND_RETURN(OK);
#undef CLEANUP_AND_RETURN
	}

	virtual Ref<Texture2D> get_run_icon() const override {
		return run_icon;
	}

	virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const override {
		String err;
		bool valid = false;

		// Look for export templates (first official, and if defined custom templates).

		if (!bool(p_preset->get("custom_template/use_custom_build"))) {
			String template_err;
			bool dvalid = false;
			bool rvalid = false;

			if (p_preset->get("custom_template/debug") != "") {
				dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
				if (!dvalid) {
					template_err += TTR("Custom debug template not found.") + "\n";
				}
			} else {
				dvalid = exists_export_template("android_debug.apk", &template_err);
			}

			if (p_preset->get("custom_template/release") != "") {
				rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
				if (!rvalid) {
					template_err += TTR("Custom release template not found.") + "\n";
				}
			} else {
				rvalid = exists_export_template("android_release.apk", &template_err);
			}

			valid = dvalid || rvalid;
			if (!valid) {
				err += template_err;
			}
		} else {
			valid = exists_export_template("android_source.zip", &err);
		}
		r_missing_templates = !valid;

		// Validate the rest of the configuration.

		String adb = EditorSettings::get_singleton()->get("export/android/adb");

		if (!FileAccess::exists(adb)) {
			valid = false;
			err += TTR("ADB executable not configured in the Editor Settings.") + "\n";
		}

		String js = EditorSettings::get_singleton()->get("export/android/jarsigner");

		if (!FileAccess::exists(js)) {
			valid = false;
			err += TTR("OpenJDK jarsigner not configured in the Editor Settings.") + "\n";
		}

		String dk = p_preset->get("keystore/debug");

		if (!FileAccess::exists(dk)) {
			dk = EditorSettings::get_singleton()->get("export/android/debug_keystore");
			if (!FileAccess::exists(dk)) {
				valid = false;
				err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";
			}
		}

		String rk = p_preset->get("keystore/release");

		if (!rk.empty() && !FileAccess::exists(rk)) {
			valid = false;
			err += TTR("Release keystore incorrectly configured in the export preset.") + "\n";
		}

		if (bool(p_preset->get("custom_template/use_custom_build"))) {
			String sdk_path = EditorSettings::get_singleton()->get("export/android/custom_build_sdk_path");
			if (sdk_path == "") {
				err += TTR("Custom build requires a valid Android SDK path in Editor Settings.") + "\n";
				valid = false;
			} else {
				Error errn;
				// Check for the platform-tools directory.
				DirAccessRef da = DirAccess::open(sdk_path.plus_file("platform-tools"), &errn);<--- Variable 'da' is assigned a value that is never used.
				if (errn != OK) {
					err += TTR("Invalid Android SDK path for custom build in Editor Settings.");
					err += TTR("Missing 'platform-tools' directory!");
					err += "\n";
					valid = false;
				}

				// Check for the build-tools directory.
				DirAccessRef build_tools_da = DirAccess::open(sdk_path.plus_file("build-tools"), &errn);<--- Variable 'build_tools_da' is assigned a value that is never used.
				if (errn != OK) {
					err += TTR("Invalid Android SDK path for custom build in Editor Settings.");
					err += TTR("Missing 'build-tools' directory!");
					err += "\n";
					valid = false;
				}
			}

			if (!FileAccess::exists("res://android/build/build.gradle")) {
				err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n";
				valid = false;
			}
		}

		bool apk_expansion = p_preset->get("apk_expansion/enable");

		if (apk_expansion) {
			String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");

			if (apk_expansion_pkey == "") {
				valid = false;

				err += TTR("Invalid public key for APK expansion.") + "\n";
			}
		}

		String pn = p_preset->get("package/unique_name");
		String pn_err;

		if (!is_package_name_valid(get_package_name(pn), &pn_err)) {
			valid = false;
			err += TTR("Invalid package name:") + " " + pn_err + "\n";
		}

		String etc_error = test_etc2();
		if (etc_error != String()) {
			valid = false;
			err += etc_error;
		}

		// Ensure that `Use Custom Build` is enabled if a plugin is selected.
		String enabled_plugins_names = get_plugins_names(get_enabled_plugins(p_preset));
		bool custom_build_enabled = p_preset->get("custom_template/use_custom_build");
		if (!enabled_plugins_names.empty() && !custom_build_enabled) {
			valid = false;
			err += TTR("\"Use Custom Build\" must be enabled to use the plugins.");
			err += "\n";
		}

		// Validate the Xr features are properly populated
		int xr_mode_index = p_preset->get("xr_features/xr_mode");
		int degrees_of_freedom = p_preset->get("xr_features/degrees_of_freedom");
		int hand_tracking = p_preset->get("xr_features/hand_tracking");
		bool focus_awareness = p_preset->get("xr_features/focus_awareness");
		if (xr_mode_index != /* XRMode.OVR*/ 1) {
			if (degrees_of_freedom > 0) {
				valid = false;
				err += TTR("\"Degrees Of Freedom\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
				err += "\n";
			}

			if (hand_tracking > 0) {
				valid = false;
				err += TTR("\"Hand Tracking\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
				err += "\n";
			}

			if (focus_awareness) {
				valid = false;
				err += TTR("\"Focus Awareness\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\".");
				err += "\n";
			}
		}

		if (int(p_preset->get("custom_template/export_format")) == 1 && /*AAB*/
				!bool(p_preset->get("custom_template/use_custom_build"))) {
			valid = false;
			err += TTR("\"Export AAB\" is only valid when \"Use Custom Build\" is enabled.");
			err += "\n";
		}

		r_error = err;
		return valid;
	}

	virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const override {
		List<String> list;
		list.push_back("apk");
		list.push_back("aab");
		return list;
	}

	inline bool is_clean_build_required(Vector<PluginConfig> enabled_plugins) {
		String plugin_names = get_plugins_names(enabled_plugins);
		bool first_build = last_custom_build_time == 0;
		bool have_plugins_changed = false;

		if (!first_build) {
			have_plugins_changed = plugin_names != last_plugin_names;
			if (!have_plugins_changed) {
				for (int i = 0; i < enabled_plugins.size(); i++) {
					if (enabled_plugins.get(i).last_updated > last_custom_build_time) {
						have_plugins_changed = true;
						break;
					}
				}
			}
		}

		last_custom_build_time = OS::get_singleton()->get_unix_time();
		last_plugin_names = plugin_names;

		return have_plugins_changed || first_build;
	}

	String get_apk_expansion_fullpath(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
		int version_code = p_preset->get("version/code");
		String package_name = p_preset->get("package/unique_name");
		String apk_file_name = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
		String fullpath = p_path.get_base_dir().plus_file(apk_file_name);
		return fullpath;
	}

	Error save_apk_expansion_file(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
		String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
		Error err = save_pack(p_preset, fullpath);
		return err;
	}

	void get_command_line_flags(const Ref<EditorExportPreset> &p_preset, const String &p_path, int p_flags, Vector<uint8_t> &r_command_line_flags) {
		String cmdline = p_preset->get("command_line/extra_args");
		Vector<String> command_line_strings = cmdline.strip_edges().split(" ");
		for (int i = 0; i < command_line_strings.size(); i++) {
			if (command_line_strings[i].strip_edges().length() == 0) {
				command_line_strings.remove(i);
				i--;
			}
		}

		gen_export_flags(command_line_strings, p_flags);

		bool apk_expansion = p_preset->get("apk_expansion/enable");
		if (apk_expansion) {
			String fullpath = get_apk_expansion_fullpath(p_preset, p_path);
			String apk_expansion_public_key = p_preset->get("apk_expansion/public_key");

			command_line_strings.push_back("--use_apk_expansion");
			command_line_strings.push_back("--apk_expansion_md5");
			command_line_strings.push_back(FileAccess::get_md5(fullpath));
			command_line_strings.push_back("--apk_expansion_key");
			command_line_strings.push_back(apk_expansion_public_key.strip_edges());
		}

		int xr_mode_index = p_preset->get("xr_features/xr_mode");
		if (xr_mode_index == 1) {
			command_line_strings.push_back("--xr_mode_ovr");
		} else { // XRMode.REGULAR is the default.
			command_line_strings.push_back("--xr_mode_regular");
		}

		bool use_32_bit_framebuffer = p_preset->get("graphics/32_bits_framebuffer");
		if (use_32_bit_framebuffer) {
			command_line_strings.push_back("--use_depth_32");
		}

		bool immersive = p_preset->get("screen/immersive_mode");
		if (immersive) {
			command_line_strings.push_back("--use_immersive");
		}

		bool debug_opengl = p_preset->get("screen/opengl_debug");
		if (debug_opengl) {
			command_line_strings.push_back("--debug_opengl");
		}

		if (command_line_strings.size()) {
			r_command_line_flags.resize(4);
			encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]);
			for (int i = 0; i < command_line_strings.size(); i++) {
				print_line(itos(i) + " param: " + command_line_strings[i]);
				CharString command_line_argument = command_line_strings[i].utf8();
				int base = r_command_line_flags.size();
				int length = command_line_argument.length();
				if (length == 0)
					continue;
				r_command_line_flags.resize(base + 4 + length);
				encode_uint32(length, &r_command_line_flags.write[base]);
				copymem(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length);
			}
		}
	}

	Error sign_apk(const Ref<EditorExportPreset> &p_preset, bool p_debug, String export_path, EditorProgress ep) {
		int export_format = int(p_preset->get("custom_template/export_format"));
		String export_label = export_format == 1 ? "AAB" : "APK";
		String release_keystore = p_preset->get("keystore/release");
		String release_username = p_preset->get("keystore/release_user");
		String release_password = p_preset->get("keystore/release_password");

		String jarsigner = EditorSettings::get_singleton()->get("export/android/jarsigner");
		if (!FileAccess::exists(jarsigner)) {
			EditorNode::add_io_error("'jarsigner' could not be found.\nPlease supply a path in the Editor Settings.\nThe resulting " + export_label + " is unsigned.");
			return OK;
		}

		String keystore;
		String password;
		String user;
		if (p_debug) {
			keystore = p_preset->get("keystore/debug");
			password = p_preset->get("keystore/debug_password");
			user = p_preset->get("keystore/debug_user");

			if (keystore.empty()) {
				keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
				password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
				user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
			}

			if (ep.step("Signing debug " + export_label + "...", 103)) {
				return ERR_SKIP;
			}

		} else {
			keystore = release_keystore;
			password = release_password;
			user = release_username;

			if (ep.step("Signing release " + export_label + "...", 103)) {
				return ERR_SKIP;
			}
		}

		if (!FileAccess::exists(keystore)) {
			EditorNode::add_io_error("Could not find keystore, unable to export.");
			return ERR_FILE_CANT_OPEN;
		}

		List<String> args;
		args.push_back("-digestalg");
		args.push_back("SHA-256");
		args.push_back("-sigalg");
		args.push_back("SHA256withRSA");
		String tsa_url = EditorSettings::get_singleton()->get("export/android/timestamping_authority_url");
		if (tsa_url != "") {
			args.push_back("-tsa");
			args.push_back(tsa_url);
		}
		args.push_back("-verbose");
		args.push_back("-keystore");
		args.push_back(keystore);
		args.push_back("-storepass");
		args.push_back(password);
		args.push_back(export_path);
		args.push_back(user);
		int retval;
		OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
		if (retval) {
			EditorNode::add_io_error("'jarsigner' returned with error #" + itos(retval));
			return ERR_CANT_CREATE;
		}

		if (ep.step("Verifying " + export_label + "...", 104)) {
			return ERR_SKIP;
		}

		args.clear();
		args.push_back("-verify");
		args.push_back("-keystore");
		args.push_back(keystore);
		args.push_back(export_path);
		args.push_back("-verbose");

		OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
		if (retval) {
			EditorNode::add_io_error("'jarsigner' verification of " + export_label + " failed. Make sure to use a jarsigner from OpenJDK 8.");
			return ERR_CANT_CREATE;
		}
		return OK;
	}

	void _clear_assets_directory() {
		DirAccessRef da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);
		if (da_res->dir_exists("res://android/build/assets")) {
			DirAccessRef da_assets = DirAccess::open("res://android/build/assets");
			da_assets->erase_contents_recursive();
			da_res->remove("res://android/build/assets");
		}
	}

	Error _zip_align_project(const String &sdk_path, const String &unaligned_file_path, const String &aligned_file_path) {
		// Look for the zipalign tool.
		String zipalign_command;
		Error errn;
		String build_tools_dir = sdk_path.plus_file("build-tools");
		DirAccessRef da = DirAccess::open(build_tools_dir, &errn);
		if (errn != OK) {
			return errn;
		}

		// There are additional versions directories we need to go through.
		da->list_dir_begin();
		String sub_dir = da->get_next();
		while (!sub_dir.empty()) {
			if (!sub_dir.begins_with(".") && da->current_is_dir()) {
				// Check if the tool is here.
				String tool_path = build_tools_dir.plus_file(sub_dir).plus_file("zipalign");
				if (FileAccess::exists(tool_path)) {
					zipalign_command = tool_path;
					break;
				}
			}
			sub_dir = da->get_next();
		}
		da->list_dir_end();

		if (zipalign_command.empty()) {
			EditorNode::get_singleton()->show_warning(TTR("Unable to find the zipalign tool."));
			return ERR_CANT_CREATE;
		}

		List<String> zipalign_args;
		zipalign_args.push_back("-f");
		zipalign_args.push_back("-v");
		zipalign_args.push_back("4");
		zipalign_args.push_back(unaligned_file_path); // source file
		zipalign_args.push_back(aligned_file_path); // destination file

		int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Aligning APK..."), zipalign_command, zipalign_args);
		if (result != 0) {
			EditorNode::get_singleton()->show_warning(TTR("Unable to complete APK alignment."));
			return ERR_CANT_CREATE;
		}

		// Delete the unaligned path.
		errn = da->remove(unaligned_file_path);
		if (errn != OK) {
			EditorNode::get_singleton()->show_warning(TTR("Unable to delete unaligned APK."));
		}
		return OK;
	}

	virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override {
		ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);

		String src_apk;
		Error err;

		EditorProgress ep("export", "Exporting for Android", 105, true);

		bool use_custom_build = bool(p_preset->get("custom_template/use_custom_build"));
		int export_format = int(p_preset->get("custom_template/export_format"));
		bool p_give_internet = p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG);
		bool _signed = p_preset->get("package/signed");
		bool apk_expansion = p_preset->get("apk_expansion/enable");
		Vector<String> enabled_abis = get_enabled_abis(p_preset);

		Ref<Image> splash_image;
		Ref<Image> splash_bg_color_image;
		load_splash_refs(splash_image, splash_bg_color_image);

		Ref<Image> main_image;
		Ref<Image> foreground;
		Ref<Image> background;

		load_icon_refs(p_preset, main_image, foreground, background);

		Vector<uint8_t> command_line_flags;
		// Write command line flags into the command_line_flags variable.
		get_command_line_flags(p_preset, p_path, p_flags, command_line_flags);

		if (export_format == 1) {
			if (!p_path.ends_with(".aab")) {
				EditorNode::get_singleton()->show_warning(TTR("Invalid filename! Android App Bundle requires the *.aab extension."));
				return ERR_UNCONFIGURED;
			}
			if (apk_expansion) {
				EditorNode::get_singleton()->show_warning(TTR("APK Expansion not compatible with Android App Bundle."));
				return ERR_UNCONFIGURED;
			}
		}
		if (export_format == 0 && !p_path.ends_with(".apk")) {
			EditorNode::get_singleton()->show_warning(
					TTR("Invalid filename! Android APK requires the *.apk extension."));
			return ERR_UNCONFIGURED;
		}
		if (export_format > 1 || export_format < 0) {
			EditorNode::add_io_error("Unsupported export format!\n");
			return ERR_UNCONFIGURED; //TODO: is this the right error?
		}

		if (use_custom_build) {
			//test that installed build version is alright
			{
				FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ);
				if (!f) {
					EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu."));
					return ERR_UNCONFIGURED;
				}
				String version = f->get_line().strip_edges();
				f->close();
				if (version != VERSION_FULL_CONFIG) {
					EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n   Template installed: %s\n   Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG));
					return ERR_UNCONFIGURED;
				}
			}
			String sdk_path = EDITOR_GET("export/android/custom_build_sdk_path");
			ERR_FAIL_COND_V_MSG(sdk_path == "", ERR_UNCONFIGURED, "Android SDK path must be configured in Editor Settings at 'export/android/custom_build_sdk_path'.");

			// TODO: should we use "package/name" or "application/config/name"?
			String project_name = get_project_name(p_preset->get("package/name"));
			err = _create_project_name_strings_files(p_preset, project_name); //project name localization.
			if (err != OK) {
				EditorNode::add_io_error("Unable to overwrite res://android/build/res/*.xml files with project name");
			}
			// Copies the project icon files into the appropriate Gradle project directory.
			_copy_icons_to_gradle_project(p_preset, splash_image, splash_bg_color_image, main_image, foreground, background);
			// Write an AndroidManifest.xml file into the Gradle project directory.
			_write_tmp_manifest(p_preset, p_give_internet, p_debug);

			//stores all the project files inside the Gradle project directory. Also includes all ABIs
			_clear_assets_directory();
			if (!apk_expansion) {
				err = export_project_files(p_preset, rename_and_store_file_in_gradle_project, NULL, ignore_so_file);
				if (err != OK) {
					EditorNode::add_io_error("Could not export project files to gradle project\n");
					return err;
				}
			} else {
				err = save_apk_expansion_file(p_preset, p_path);
				if (err != OK) {
					EditorNode::add_io_error("Could not write expansion package file!");
					return err;
				}
			}
			store_file_at_path("res://android/build/assets/_cl_", command_line_flags);

			OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
			String build_command;

#ifdef WINDOWS_ENABLED
			build_command = "gradlew.bat";
#else
			build_command = "gradlew";
#endif

			String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build");
			build_command = build_path.plus_file(build_command);

			String package_name = get_package_name(p_preset->get("package/unique_name"));
			String version_code = itos(p_preset->get("version/code"));
			String version_name = p_preset->get("version/name");
			String enabled_abi_string = String("|").join(enabled_abis);

			Vector<PluginConfig> enabled_plugins = get_enabled_plugins(p_preset);
			String local_plugins_binaries = get_plugins_binaries(BINARY_TYPE_LOCAL, enabled_plugins);
			String remote_plugins_binaries = get_plugins_binaries(BINARY_TYPE_REMOTE, enabled_plugins);
			String custom_maven_repos = get_plugins_custom_maven_repos(enabled_plugins);
			bool clean_build_required = is_clean_build_required(enabled_plugins);

			List<String> cmdline;
			if (clean_build_required) {
				cmdline.push_back("clean");
			}

			String build_type = p_debug ? "Debug" : "Release";
			if (export_format == 1) {
				String bundle_build_command = vformat("bundle%s", build_type);
				cmdline.push_back(bundle_build_command);
			} else if (export_format == 0) {
				String apk_build_command = vformat("assemble%s", build_type);
				cmdline.push_back(apk_build_command);
			}

			cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name.
			cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code.
			cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name.
			cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs.
			cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies.
			cmdline.push_back("-Pplugins_remote_binaries=" + remote_plugins_binaries); // argument to specify the list of plugins remote dependencies.
			cmdline.push_back("-Pplugins_maven_repos=" + custom_maven_repos); // argument to specify the list of custom maven repos for the plugins dependencies.
			cmdline.push_back("-p"); // argument to specify the start directory.
			cmdline.push_back(build_path); // start directory.
			/*{ used for debug
				int ec;
				String pipe;
				OS::get_singleton()->execute(build_command, cmdline, true, nullptr, nullptr, &ec);
				print_line("exit code: " + itos(ec));
			}
			*/
			int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
			if (result != 0) {
				EditorNode::get_singleton()->show_warning(TTR("Building of Android project failed, check output for the error.\nAlternatively visit docs.godotengine.org for Android build documentation."));
				return ERR_CANT_CREATE;
			}

			List<String> copy_args;
			String copy_command;
			if (export_format == 1) {
				copy_command = vformat("copyAndRename%sAab", build_type);
			} else if (export_format == 0) {
				copy_command = vformat("copyAndRename%sApk", build_type);
			}

			copy_args.push_back(copy_command);

			copy_args.push_back("-p"); // argument to specify the start directory.
			copy_args.push_back(build_path); // start directory.

			String export_filename = p_path.get_file();
			if (export_format == 0) {
				// By default, generated apk are not aligned.
				export_filename += ".unaligned";
			}
			String export_path = p_path.get_base_dir();
			if (export_path.is_rel_path()) {
				export_path = OS::get_singleton()->get_resource_dir().plus_file(export_path);
			}
			export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path();
			String export_file_path = export_path.plus_file(export_filename);

			copy_args.push_back("-Pexport_path=file:" + export_path);
			copy_args.push_back("-Pexport_filename=" + export_filename);

			int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args);
			if (copy_result != 0) {
				EditorNode::get_singleton()->show_warning(TTR("Unable to copy and rename export file, check gradle project directory for outputs."));
				return ERR_CANT_CREATE;
			}
			if (_signed) {
				err = sign_apk(p_preset, p_debug, export_file_path, ep);
				if (err != OK) {
					return err;
				}
			}

			if (export_format == 0) {
				// Perform zip alignment
				err = _zip_align_project(sdk_path, export_file_path, export_path.plus_file(p_path.get_file()));
				if (err != OK) {
					return err;
				}
			}

			return OK;
		}
		// This is the start of the Legacy build system
		if (p_debug)
			src_apk = p_preset->get("custom_template/debug");
		else
			src_apk = p_preset->get("custom_template/release");
		src_apk = src_apk.strip_edges();
		if (src_apk == "") {
			if (p_debug) {
				src_apk = find_export_template("android_debug.apk");
			} else {
				src_apk = find_export_template("android_release.apk");
			}
			if (src_apk == "") {
				EditorNode::add_io_error("Package not found: " + src_apk);
				return ERR_FILE_NOT_FOUND;
			}
		}

		if (!DirAccess::exists(p_path.get_base_dir())) {
			return ERR_FILE_BAD_PATH;
		}

		FileAccess *src_f = nullptr;
		zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

		if (ep.step("Creating APK...", 0)) {
			return ERR_SKIP;
		}

		unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
		if (!pkg) {
			EditorNode::add_io_error("Could not find template APK to export:\n" + src_apk);
			return ERR_FILE_NOT_FOUND;
		}

		int ret = unzGoToFirstFile(pkg);

		zlib_filefunc_def io2 = io;
		FileAccess *dst_f = nullptr;
		io2.opaque = &dst_f;

		String tmp_unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk");

#define CLEANUP_AND_RETURN(m_err)                            \
	{                                                        \
		DirAccess::remove_file_or_error(tmp_unaligned_path); \
		return m_err;                                        \
	}

		zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);

		String cmdline = p_preset->get("command_line/extra_args");<--- Variable 'cmdline' is assigned a value that is never used.

		String version_name = p_preset->get("version/name");<--- Variable 'version_name' is assigned a value that is never used.
		String package_name = p_preset->get("package/unique_name");<--- Variable 'package_name' is assigned a value that is never used.

		String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");<--- Variable 'apk_expansion_pkey' is assigned a value that is never used.

		Vector<String> invalid_abis(enabled_abis);
		while (ret == UNZ_OK) {
			//get filename
			unz_file_info info;
			char fname[16384];
			ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);<--- ret is assigned

			bool skip = false;

			String file = fname;

			Vector<uint8_t> data;
			data.resize(info.uncompressed_size);

			//read
			unzOpenCurrentFile(pkg);
			unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			//write
			if (file == "AndroidManifest.xml") {
				_fix_manifest(p_preset, data, p_give_internet);
			}
			if (file == "resources.arsc") {
				_fix_resources(p_preset, data);
			}

			// Process the splash image
			if (file == SPLASH_IMAGE_EXPORT_PATH && splash_image.is_valid() && !splash_image->empty()) {
				_load_image_data(splash_image, data);
			}

			// Process the splash bg color image
			if (file == SPLASH_BG_COLOR_PATH && splash_bg_color_image.is_valid() && !splash_bg_color_image->empty()) {
				_load_image_data(splash_bg_color_image, data);
			}

			for (int i = 0; i < icon_densities_count; ++i) {
				if (main_image.is_valid() && !main_image->empty()) {
					if (file == launcher_icons[i].export_path) {
						_process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data);
					}
				}
				if (foreground.is_valid() && !foreground->empty()) {
					if (file == launcher_adaptive_icon_foregrounds[i].export_path) {
						_process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data);
					}
				}
				if (background.is_valid() && !background->empty()) {
					if (file == launcher_adaptive_icon_backgrounds[i].export_path) {
						_process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data);
					}
				}
			}

			if (file.ends_with(".so")) {
				bool enabled = false;
				for (int i = 0; i < enabled_abis.size(); ++i) {
					if (file.begins_with("lib/" + enabled_abis[i] + "/")) {
						invalid_abis.erase(enabled_abis[i]);
						enabled = true;
						break;
					}
				}
				if (!enabled) {
					skip = true;
				}
			}

			if (file.begins_with("META-INF") && _signed) {
				skip = true;
			}

			if (!skip) {
				print_line("ADDING: " + file);

				// Respect decision on compression made by AAPT for the export template
				const bool uncompressed = info.compression_method == 0;

				zip_fileinfo zipfi = get_zip_fileinfo();

				zipOpenNewFileInZip(unaligned_apk,
						file.utf8().get_data(),
						&zipfi,
						nullptr,
						0,
						nullptr,
						0,
						nullptr,
						uncompressed ? 0 : Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
				zipCloseFileInZip(unaligned_apk);
			}

			ret = unzGoToNextFile(pkg);<--- ret is overwritten
		}

		if (!invalid_abis.empty()) {
			String unsupported_arch = String(", ").join(invalid_abis);
			EditorNode::add_io_error("Missing libraries in the export template for the selected architectures: " + unsupported_arch + ".\n" +
									 "Please build a template with all required libraries, or uncheck the missing architectures in the export preset.");
			CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
		}

		if (ep.step("Adding files...", 1)) {
			CLEANUP_AND_RETURN(ERR_SKIP);
		}
		err = OK;<--- err is assigned

		if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
			APKExportData ed;
			ed.ep = &ep;
			ed.apk = unaligned_apk;
			err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so);<--- err is overwritten
		} else {
			if (apk_expansion) {
				err = save_apk_expansion_file(p_preset, p_path);
				if (err != OK) {
					EditorNode::add_io_error("Could not write expansion package file!");
					return err;
				}
			} else {
				APKExportData ed;
				ed.ep = &ep;
				ed.apk = unaligned_apk;
				err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so);
			}
		}

		if (err != OK) {
			unzClose(pkg);
			EditorNode::add_io_error("Could not export project files");
			CLEANUP_AND_RETURN(ERR_SKIP);
		}

		zip_fileinfo zipfi = get_zip_fileinfo();
		zipOpenNewFileInZip(unaligned_apk,
				"assets/_cl_",
				&zipfi,
				NULL,
				0,
				NULL,
				0,
				NULL,
				0, // No compress (little size gain and potentially slower startup)
				Z_DEFAULT_COMPRESSION);
		zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size());
		zipCloseFileInZip(unaligned_apk);
		zipClose(unaligned_apk, nullptr);
		unzClose(pkg);

		if (err != OK) {
			CLEANUP_AND_RETURN(err);
		}

		if (_signed) {
			err = sign_apk(p_preset, p_debug, tmp_unaligned_path, ep);
			if (err != OK) {
				CLEANUP_AND_RETURN(err);
			}
		}

		// Let's zip-align (must be done after signing)

		static const int ZIP_ALIGNMENT = 4;

		if (ep.step("Aligning APK...", 105)) {
			CLEANUP_AND_RETURN(ERR_SKIP);
		}

		unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io);
		if (!tmp_unaligned) {
			EditorNode::add_io_error("Could not unzip temporary unaligned APK.");
			CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND);
		}

		ret = unzGoToFirstFile(tmp_unaligned);

		io2 = io;
		dst_f = nullptr;
		io2.opaque = &dst_f;
		zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2);

		// Take files from the unaligned APK and write them out to the aligned one
		// in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
		// following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
		int bias = 0;
		while (ret == UNZ_OK) {
			unz_file_info info;
			memset(&info, 0, sizeof(info));

			char fname[16384];
			char extra[16384];
			ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0);<--- ret is assigned

			String file = fname;

			Vector<uint8_t> data;
			data.resize(info.compressed_size);

			// read
			int method, level;
			unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
			long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
			unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
			unzCloseCurrentFile(tmp_unaligned);

			// align
			int padding = 0;
			if (!info.compression_method) {
				// Uncompressed file => Align
				long new_offset = file_offset + bias;
				padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
			}

			memset(extra + info.size_file_extra, 0, padding);

			zip_fileinfo fileinfo = get_zip_fileinfo();
			zipOpenNewFileInZip2(final_apk,
					file.utf8().get_data(),
					&fileinfo,
					extra,
					info.size_file_extra + padding,
					nullptr,
					0,
					nullptr,
					method,
					level,
					1); // raw write
			zipWriteInFileInZip(final_apk, data.ptr(), data.size());
			zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);

			bias += padding;

			ret = unzGoToNextFile(tmp_unaligned);<--- ret is overwritten
		}

		zipClose(final_apk, nullptr);
		unzClose(tmp_unaligned);

		CLEANUP_AND_RETURN(OK);
	}

	virtual void get_platform_features(List<String> *r_features) override {
		r_features->push_back("mobile");
		r_features->push_back("Android");
	}

	virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) override {
	}

	EditorExportPlatformAndroid() {
		Ref<Image> img = memnew(Image(_android_logo));
		logo.instance();
		logo->create_from_image(img);

		img = Ref<Image>(memnew(Image(_android_run_icon)));
		run_icon.instance();
		run_icon->create_from_image(img);

		devices_changed = true;
		plugins_changed = true;
		quit_request = false;
		check_for_changes_thread = Thread::create(_check_for_changes_poll_thread, this);
	}

	~EditorExportPlatformAndroid() {
		quit_request = true;
		Thread::wait_to_finish(check_for_changes_thread);
		memdelete(check_for_changes_thread);
	}
};

void register_android_exporter() {
	String exe_ext;
	if (OS::get_singleton()->get_name() == "Windows") {
		exe_ext = "*.exe";
	}

	EDITOR_DEF("export/android/adb", "");
	EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/adb", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
	EDITOR_DEF("export/android/jarsigner", "");
	EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/jarsigner", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
	EDITOR_DEF("export/android/debug_keystore", "");
	EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"));
	EDITOR_DEF("export/android/debug_keystore_user", "androiddebugkey");
	EDITOR_DEF("export/android/debug_keystore_pass", "android");
	EDITOR_DEF("export/android/force_system_user", false);
	EDITOR_DEF("export/android/custom_build_sdk_path", "");
	EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/custom_build_sdk_path", PROPERTY_HINT_GLOBAL_DIR));

	EDITOR_DEF("export/android/timestamping_authority_url", "");
	EDITOR_DEF("export/android/shutdown_adb_on_exit", true);

	Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>(memnew(EditorExportPlatformAndroid));
	EditorExport::get_singleton()->add_export_platform(exporter);
}