File: jucer_ProjectExport_MSVC.h

package info (click to toggle)
juce 8.0.6%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 78,204 kB
  • sloc: cpp: 521,891; ansic: 159,819; java: 2,996; javascript: 847; xml: 273; python: 224; sh: 162; makefile: 84
file content (2682 lines) | stat: -rw-r--r-- 125,071 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
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
/*
  ==============================================================================

   This file is part of the JUCE framework.
   Copyright (c) Raw Material Software Limited

   JUCE is an open source framework subject to commercial or open source
   licensing.

   By downloading, installing, or using the JUCE framework, or combining the
   JUCE framework with any other source code, object code, content or any other
   copyrightable work, you agree to the terms of the JUCE End User Licence
   Agreement, and all incorporated terms including the JUCE Privacy Policy and
   the JUCE Website Terms of Service, as applicable, which will bind you. If you
   do not agree to the terms of these agreements, we will not license the JUCE
   framework to you, and you must discontinue the installation or download
   process and cease use of the JUCE framework.

   JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
   JUCE Privacy Policy: https://juce.com/juce-privacy-policy
   JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/

   Or:

   You may also use this code under the terms of the AGPLv3:
   https://www.gnu.org/licenses/agpl-3.0.en.html

   THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
   WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.

  ==============================================================================
*/

#pragma once

#include "jucer_ProjectSaver.h"

inline String msBuildEscape (String str)
{
    // see https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-special-characters?view=vs-2019
    for (const auto& special : { "%", "$", "@", "'", ";", "?", "\""})
        str = str.replace (special, "%" + String::toHexString (*special));

    return str;
}

inline StringArray msBuildEscape (StringArray range)
{
    for (auto& i : range)
        i = msBuildEscape (i);

    return range;
}

class MSVCScriptBuilder
{
public:
    struct StringOrBuilder
    {
        StringOrBuilder() = default;
        StringOrBuilder (const String& s)             : value (s) {}
        StringOrBuilder (const char* s)               : StringOrBuilder (String { s }) {}
        StringOrBuilder (const MSVCScriptBuilder& sb) : StringOrBuilder (sb.build()) {}

        bool isNotEmpty() const { return value.isNotEmpty(); }

        String value;
    };

    MSVCScriptBuilder& exit (int code)
    {
        script << "exit /b " << code;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& deleteFile (const StringOrBuilder& path)
    {
        script << "del /s /q " << path.value;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& mkdir (const StringOrBuilder& path)
    {
        script << "mkdir " << path.value;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& delay (int timeSeconds)
    {
        script << "timeout /t " << String { timeSeconds } << " /nobreak";
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& warning (const String& message)
    {
        script << "echo : Warning: " + message;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& info (const String& message)
    {
        script << "echo : Info: " << message;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& error (const String& message)
    {
        script << "echo : Error: " << message;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& run (const StringOrBuilder& command, bool echo = false)
    {
        if (echo)
            script << "echo \"running " << command.value << "\"" << newLine;

        script << command.value;
        script << newLine;
        return *this;
    }

    template <typename T>
    MSVCScriptBuilder& set (const String& name, T value)
    {
        script << "set " << name << "=" << value;
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& runAndCheck (const StringOrBuilder& command,
                                    const StringOrBuilder& success,
                                    const StringOrBuilder& failed = {})
    {
        run (command.value);
        ifelse ("%ERRORLEVEL% equ 0", success.value, failed.value);
        return *this;
    }

    MSVCScriptBuilder& ifAllConditionsTrue (const StringArray& conditions, const StringOrBuilder& left)
    {
        jassert (left.isNotEmpty());

        for (const auto& string : conditions)
            script << "if " << string << " ";

        script << "(" << newLine << left.value << ")";
        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& ifelse (const String& expr,
                               const StringOrBuilder& left,
                               const StringOrBuilder& right = {})
    {
        jassert (left.isNotEmpty());

        script << "if " << expr << " (" << newLine << left.value;

        if (right.isNotEmpty())
            script << ") else (" << newLine << right.value << ")";
        else
            script << ")";

        script << newLine;
        return *this;
    }

    MSVCScriptBuilder& append (const StringOrBuilder& string)
    {
        script << string.value << newLine;
        return *this;
    }

    MSVCScriptBuilder& labelledSection (const String& name, const StringOrBuilder& body)
    {
        script << ":" << name << newLine << body.value << newLine;
        return *this;
    }

    MSVCScriptBuilder& call (const String& label)
    {
        script << "call :" << label << newLine;
        return *this;
    }

    MSVCScriptBuilder& jump (const String& label)
    {
        script << "goto :" << label << newLine;
        return *this;
    }

    String build() const
    {
        MemoryOutputStream stream;
        build (stream);
        return stream.toUTF8();
    }

private:
    void build (OutputStream& stream) const
    {
        const auto genTab = [] (int depth, const int tabWidth = 4)
        {
            return String{}.paddedLeft (' ', depth * tabWidth);
        };

        int depth = 0;
        auto lines = StringArray::fromLines (script);

        for (auto [lineIndex, line] : enumerate (lines))
        {
            const auto trimmed = line.trim();
            const auto enter = trimmed.endsWith ("(");
            const auto leave = trimmed.startsWith (")");

            if (leave && depth > 0)
                depth--;

            if (trimmed.isNotEmpty())
            {
                stream << genTab (depth) << trimmed;

                if (lineIndex < lines.size() - 1)
                    stream << newLine;
            }

            if (enter)
                depth++;
        }
    }

    String script;
};

enum class Architecture
{
    win32,
    win64,
    arm64,
    arm64ec
};

static String getArchitectureValueString (Architecture arch)
{
    switch (arch)
    {
        case Architecture::win32:   return "Win32";
        case Architecture::win64:   return "x64";
        case Architecture::arm64:   return "ARM64";
        case Architecture::arm64ec: return "ARM64EC";
    }

    jassertfalse;
    return "";
}

static std::optional<Architecture> architectureTypeFromString (const String& string)
{
    constexpr Architecture values[] { Architecture::win32,
                                      Architecture::win64,
                                      Architecture::arm64,
                                      Architecture::arm64ec };

    for (auto value : values)
    {
        if (getArchitectureValueString (value) == string)
            return value;
    }

    jassertfalse;
    return {};
}

static String getVisualStudioArchitectureId (Architecture architecture)
{
    switch (architecture)
    {
        case Architecture::win32:   return "x86";
        case Architecture::win64:   return "AMD64";
        case Architecture::arm64:   return "ARM64";
        case Architecture::arm64ec: return "ARM64";
    }

    jassertfalse;
    return "";
}

static String getVisualStudioPlatformId (Architecture architecture)
{
    switch (architecture)
    {
        case Architecture::win32:   return "x86";
        case Architecture::win64:   return "x64";
        case Architecture::arm64:   return "ARM64";
        case Architecture::arm64ec: return "ARM64EC";
    }

    jassertfalse;
    return "";
}

//==============================================================================
class MSVCProjectExporterBase : public ProjectExporter
{
public:
    MSVCProjectExporterBase (Project& p, const ValueTree& t, String folderName)
        : ProjectExporter (p, t),
          IPPLibraryValue       (settings, Ids::IPPLibrary,                   getUndoManager()),
          IPP1ALibraryValue     (settings, Ids::IPP1ALibrary,                 getUndoManager()),
          MKL1ALibraryValue     (settings, Ids::MKL1ALibrary,                 getUndoManager()),
          platformToolsetValue  (settings, Ids::toolset,                      getUndoManager()),
          targetPlatformVersion (settings, Ids::windowsTargetPlatformVersion, getUndoManager()),
          manifestFileValue     (settings, Ids::msvcManifestFile,             getUndoManager())
    {
        targetLocationValue.setDefault (getDefaultBuildsRootFolder() + folderName);
    }

    virtual int getVisualStudioVersion() const = 0;

    virtual String getSolutionComment() const = 0;
    virtual String getToolsVersion() const = 0;
    virtual String getDefaultToolset() const = 0;
    virtual String getDefaultWindowsTargetPlatformVersion() const = 0;

    //==============================================================================
    String getIPPLibrary() const                      { return IPPLibraryValue.get(); }
    String getIPP1ALibrary() const                    { return IPP1ALibraryValue.get(); }
    String getMKL1ALibrary() const                    { return MKL1ALibraryValue.get(); }
    String getPlatformToolset() const                 { return platformToolsetValue.get(); }
    String getWindowsTargetPlatformVersion() const    { return targetPlatformVersion.get(); }

    //==============================================================================
    void addToolsetProperty (PropertyListBuilder& props, std::initializer_list<const char*> valueStrings)
    {
        StringArray names;
        Array<var> values;

        for (const auto& valueString : valueStrings)
        {
            names.add (valueString);
            values.add (valueString);
        }

        props.add (new ChoicePropertyComponent (platformToolsetValue, "Platform Toolset", names, values),
                   "Specifies the version of the platform toolset that will be used when building this project.\n"
                   "In order to use the ClangCL toolset, you must first install the \"C++ Clang Tools for Windows\" "
                   "package using the Visual Studio Installer.");
    }

    void create (const OwnedArray<LibraryModule>&) const override
    {
        createResourcesAndIcon();
        createPackagesConfigFile();

        for (int i = 0; i < targets.size(); ++i)
            if (auto* target = targets[i])
                target->writeProjectFile();

        build_tools::writeStreamToFile (getSLNFile(), [&] (MemoryOutputStream& mo)
        {
            writeSolutionFile (mo, "11.00", getSolutionComment());
        });
    }

    //==============================================================================
    void updateDeprecatedSettings() override
    {
        {
            auto oldStylePrebuildCommand = getSettingString (Ids::prebuildCommand);
            settings.removeProperty (Ids::prebuildCommand, nullptr);

            if (oldStylePrebuildCommand.isNotEmpty())
                for (ConfigIterator config (*this); config.next();)
                    static_cast<MSVCBuildConfiguration*> (&*config)->getValue (Ids::prebuildCommand) = oldStylePrebuildCommand;
        }

        {
            auto oldStyleLibName = getSettingString ("libraryName_Debug");
            settings.removeProperty ("libraryName_Debug", nullptr);

            if (oldStyleLibName.isNotEmpty())
                for (ConfigIterator config (*this); config.next();)
                    if (config->isDebug())
                        config->getValue (Ids::targetName) = oldStyleLibName;
        }

        {
            auto oldStyleLibName = getSettingString ("libraryName_Release");
            settings.removeProperty ("libraryName_Release", nullptr);

            if (oldStyleLibName.isNotEmpty())
                for (ConfigIterator config (*this); config.next();)
                    if (! config->isDebug())
                        config->getValue (Ids::targetName) = oldStyleLibName;
        }

        {
            std::vector<ValueTree> toErase;

            for (const auto& config : getConfigurations())
            {
                if (config.getProperty (Ids::winArchitecture) == "ARM")
                    toErase.push_back (config);
            }

            if (! toErase.empty())
            {
                for (const auto& e : toErase)
                    e.getParent().removeChild (e, nullptr);

                getProject().addProjectMessage (ProjectMessages::Ids::unsupportedArm32Config, {});
            }
        }

        for (ConfigIterator i (*this); i.next();)
        {
            auto& config = *static_cast<MSVCBuildConfiguration*> (&*i);
            config.updateOldLTOSetting();
            config.updateOldArchSetting();
        }
    }

    Array<Architecture> getAllActiveArchitectures() const
    {
        Array<Architecture> archs;

        for (ConstConfigIterator i (*this); i.next();)
        {
            const auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);
            const auto configArchs = config.getArchitectures();

            for (const auto& arch : configArchs)
                if (! archs.contains (arch))
                    archs.add (arch);
        }

        return archs;
    }

    void initialiseDependencyPathValues() override
    {
        vstLegacyPathValueWrapper.init ({ settings, Ids::vstLegacyFolder, nullptr },
                                        getAppSettings().getStoredPath (Ids::vstLegacyPath, TargetOS::windows), TargetOS::windows);

        aaxPathValueWrapper.init ({ settings, Ids::aaxFolder, nullptr },
                                  getAppSettings().getStoredPath (Ids::aaxPath,  TargetOS::windows), TargetOS::windows);

        araPathValueWrapper.init ({ settings, Ids::araFolder, nullptr },
                                  getAppSettings().getStoredPath (Ids::araPath, TargetOS::windows), TargetOS::windows);
    }

    //==============================================================================
    class MSVCBuildConfiguration final : public BuildConfiguration,
                                         private ValueTree::Listener
    {
    public:
        MSVCBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
            : BuildConfiguration (p, settings, e),
              warningLevelValue              (config, Ids::winWarningLevel,            getUndoManager(), 4),
              warningsAreErrorsValue         (config, Ids::warningsAreErrors,          getUndoManager(), false),
              prebuildCommandValue           (config, Ids::prebuildCommand,            getUndoManager()),
              postbuildCommandValue          (config, Ids::postbuildCommand,           getUndoManager()),
              generateDebugSymbolsValue      (config, Ids::alwaysGenerateDebugSymbols, getUndoManager(), false),
              enableIncrementalLinkingValue  (config, Ids::enableIncrementalLinking,   getUndoManager(), false),
              useRuntimeLibDLLValue          (config, Ids::useRuntimeLibDLL,           getUndoManager(), true),
              multiProcessorCompilationValue (config, Ids::multiProcessorCompilation,  getUndoManager(), true),
              intermediatesPathValue         (config, Ids::intermediatesPath,          getUndoManager()),
              characterSetValue              (config, Ids::characterSet,               getUndoManager()),
              architectureTypeValue          (config, Ids::winArchitecture,            getUndoManager(), Array<var> { getArchitectureValueString (Architecture::win64) }, ","),
              fastMathValue                  (config, Ids::fastMath,                   getUndoManager()),
              debugInformationFormatValue    (config, Ids::debugInformationFormat,     getUndoManager(), isDebug() ? "ProgramDatabase" : "None"),
              pluginBinaryCopyStepValue      (config, Ids::enablePluginBinaryCopyStep, getUndoManager(), false),
              vstBinaryLocation              (config, Ids::vstBinaryLocation,          getUndoManager()),
              vst3BinaryLocation             (config, Ids::vst3BinaryLocation,         getUndoManager()),
              aaxBinaryLocation              (config, Ids::aaxBinaryLocation,          getUndoManager()),
              lv2BinaryLocation              (config, Ids::lv2BinaryLocation,          getUndoManager()),
              unityPluginBinaryLocation      (config, Ids::unityPluginBinaryLocation,  getUndoManager())
        {
            constexpr std::tuple<Architecture, const char*, const char*> paths[]
            {
                { Architecture::win32,   "%programfiles(x86)%", "%CommonProgramFiles(x86)%" },
                { Architecture::win64,   "%ProgramW6432%",      "%CommonProgramW6432%" },
                { Architecture::arm64,   "%ProgramW6432%",      "%CommonProgramW6432%" },
                { Architecture::arm64ec, "%ProgramW6432%",      "%CommonProgramW6432%" }
            };

            for (const auto& [arch, programFolderPath, commonFolderPath] : paths)
            {
                setBinaryPathDefault (Ids::vstBinaryLocation,  arch, programFolderPath + String ("\\Steinberg\\Vstplugins"));
                setBinaryPathDefault (Ids::vst3BinaryLocation, arch, commonFolderPath  + String ("\\VST3"));
                setBinaryPathDefault (Ids::aaxBinaryLocation,  arch, commonFolderPath  + String ("\\Avid\\Audio\\Plug-Ins"));
                setBinaryPathDefault (Ids::lv2BinaryLocation,  arch, "%APPDATA%\\LV2");
            }

            optimisationLevelValue.setDefault (isDebug() ? optimisationOff : optimiseFull);

            config.addListener (this);
        }

        ~MSVCBuildConfiguration() override
        {
            config.removeListener (this);
        }

        void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
        {
            if (property != Ids::winArchitecture)
                return;

            project.removeProjectMessage (ProjectMessages::Ids::arm64Warning);

            const auto selectedArchs = architectureTypeValue.get();

            if (! selectedArchs.getArray()->contains (getArchitectureValueString (Architecture::arm64)))
                return;

            if (selectedArchs.getArray()->contains (getArchitectureValueString (Architecture::arm64ec)))
                return;

            project.addProjectMessage (ProjectMessages::Ids::arm64Warning, {});
        }

        String getBinaryPath (const Identifier& id, Architecture arch) const
        {
            if (auto* location = getLocationForArchitecture (id, arch))
                return location->get().toString();

            return "";
        }

        void setBinaryPathDefault (const Identifier& id, Architecture arch, const String& path)
        {
            if (auto* location = getLocationForArchitecture (id, arch))
                location->setDefault (path);
        }

        //==============================================================================
        int getWarningLevel() const                       { return warningLevelValue.get(); }
        bool areWarningsTreatedAsErrors() const           { return warningsAreErrorsValue.get(); }

        Array<Architecture> getArchitectures() const
        {
            auto value = architectureTypeValue.get();
            auto* array = value.getArray();

            if (array == nullptr)
                return {};

            Array<Architecture> result;
            result.resize (array->size());

            std::transform (array->begin(), array->end(), result.begin(), [] (const var& archVar)
            {
                return *architectureTypeFromString (archVar.toString());
            });

            return result;
        }

        String getPrebuildCommandString() const           { return prebuildCommandValue.get(); }
        String getPostbuildCommandString() const          { return postbuildCommandValue.get(); }
        String getIntermediatesPathString() const         { return intermediatesPathValue.get(); }
        String getCharacterSetString() const              { return characterSetValue.get(); }
        String getDebugInformationFormatString() const    { return debugInformationFormatValue.get(); }

        bool shouldGenerateDebugSymbols() const           { return generateDebugSymbolsValue.get(); }
        bool shouldLinkIncremental() const                { return enableIncrementalLinkingValue.get(); }
        bool isUsingRuntimeLibDLL() const                 { return useRuntimeLibDLLValue.get(); }
        bool shouldUseMultiProcessorCompilation() const   { return multiProcessorCompilationValue.get(); }
        bool isFastMathEnabled() const                    { return fastMathValue.get(); }
        bool isPluginBinaryCopyStepEnabled() const        { return pluginBinaryCopyStepValue.get(); }

        static bool shouldBuildTarget (build_tools::ProjectType::Target::Type targetType, Architecture arch)
        {
            return targetType != build_tools::ProjectType::Target::AAXPlugIn
                || (arch != Architecture::arm64 && arch != Architecture::arm64ec);
        }

        //==============================================================================
        String createMSVCConfigName (Architecture arch) const
        {
            return getName() + "|" + getArchitectureValueString (arch);
        }

        String getOutputFilename (const String& suffix,
                                  bool forceSuffix,
                                  build_tools::ProjectType::Target::Type type) const
        {
            using Target = build_tools::ProjectType::Target::Type;

            if (type == Target::LV2Helper)
                return Project::getLV2FileWriterName() + suffix;

            if (type == Target::VST3Helper)
                return Project::getVST3FileWriterName() + suffix;

            const auto forceUnityPrefix = type == Target::UnityPlugIn;
            auto target = File::createLegalFileName (getTargetBinaryNameString (forceUnityPrefix).trim());

            if (forceSuffix || ! target.containsChar ('.'))
                return target.upToLastOccurrenceOf (".", false, false) + suffix;

            return target;
        }

        void createConfigProperties (PropertyListBuilder& props) override
        {
            if (project.isAudioPluginProject())
                addVisualStudioPluginInstallPathProperties (props);

            const auto architectureList = exporter.getExporterIdentifier() == Identifier { "VS2022" }
                                        ? std::vector<Architecture> { Architecture::win32, Architecture::win64, Architecture::arm64, Architecture::arm64ec }
                                        : std::vector<Architecture> { Architecture::win32, Architecture::win64, Architecture::arm64 };

            Array<String> architectureListAsStrings;
            Array<var> architectureListAsVars;

            for (const auto& arch : architectureList)
            {
                architectureListAsStrings.add (getArchitectureValueString (arch));
                architectureListAsVars.add (getArchitectureValueString (arch));
            }

            props.add (new MultiChoicePropertyComponent (architectureTypeValue, "Architecture", architectureListAsStrings, architectureListAsVars),
                       "Which Windows architecture to use.");

            props.add (new ChoicePropertyComponentWithEnablement (debugInformationFormatValue,
                                                                  isDebug() ? isDebugValue : generateDebugSymbolsValue,
                                                                  "Debug Information Format",
                                                                  { "None", "C7 Compatible (/Z7)", "Program Database (/Zi)", "Program Database for Edit And Continue (/ZI)" },
                                                                  { "None", "OldStyle",            "ProgramDatabase",        "EditAndContinue" }),
                       "The type of debugging information created for your program for this configuration."
                       " This will always be used in a debug configuration and will be used in a release configuration"
                       " with forced generation of debug symbols.");

            props.add (new ChoicePropertyComponent (fastMathValue, "Relax IEEE Compliance"),
                       "Enable this to use FAST_MATH non-IEEE mode. (Warning: this can have unexpected results!)");

            props.add (new ChoicePropertyComponent (optimisationLevelValue, "Optimisation",
                                                    { "Disabled (/Od)", "Minimise size (/O1)", "Maximise speed (/O2)", "Full optimisation (/Ox)" },
                                                    { optimisationOff,  optimiseMinSize,       optimiseMaxSpeed,       optimiseFull }),
                       "The optimisation level for this configuration");

            props.add (new TextPropertyComponent (intermediatesPathValue, "Intermediates Path", 2048, false),
                       "An optional path to a folder to use for the intermediate build files. Note that Visual Studio allows "
                       "you to use macros in this path, e.g. \"$(TEMP)\\MyAppBuildFiles\\$(Configuration)\", which is a handy way to "
                       "send them to the user's temp folder.");

            props.add (new ChoicePropertyComponent (warningLevelValue, "Warning Level",
                                                    { "Low", "Medium", "High" },
                                                    { 2,     3,        4 }),
                       "The compilation warning level to use.");

            props.add (new ChoicePropertyComponent (warningsAreErrorsValue, "Treat Warnings as Errors"),
                       "Enable this to treat compilation warnings as errors.");

            props.add (new ChoicePropertyComponent (useRuntimeLibDLLValue, "Runtime Library",
                                                    { "Use static runtime", "Use DLL runtime" },
                                                    { false,                true }),
                       "If the static runtime is selected then your app/plug-in will not be dependent upon users having Microsoft's redistributable "
                       "C++ runtime installed. However, if you are linking libraries from different sources you must select the same type of runtime "
                       "used by the libraries.");

            props.add (new ChoicePropertyComponent (multiProcessorCompilationValue, "Multi-Processor Compilation",
                                                    { "Enabled", "Disabled" },
                                                    { true,      false }),
                       "Allows the compiler to use of all the available processors, which can reduce compilation time. "
                       "This is enabled by default and should only be disabled if you know what you are doing.");

            props.add (new ChoicePropertyComponent (enableIncrementalLinkingValue, "Incremental Linking"),
                       "Enable to avoid linking from scratch for every new build. "
                       "Disable to ensure that your final release build does not contain padding or thunks.");

            if (! isDebug())
            {
                props.add (new ChoicePropertyComponent (generateDebugSymbolsValue, "Force Generation of Debug Symbols"),
                           "Enable this to force generation of debug symbols in a release configuration.");
            }

            props.add (new TextPropertyComponent (prebuildCommandValue,  "Pre-build Command",  2048, true),
                       "Some command that will be run before a build starts.");

            props.add (new TextPropertyComponent (postbuildCommandValue, "Post-build Command", 2048, true),
                       "Some command that will be run after a build starts.");

            props.add (new ChoicePropertyComponent (characterSetValue, "Character Set",
                                                    { "MultiByte", "Unicode" },
                                                    { "MultiByte", "Unicode" }),
                       "Specifies the character set used when building.");
        }

        String getModuleLibraryArchName() const override
        {
            String result ("$(Platform)\\");
            result += isUsingRuntimeLibDLL() ? "MD" : "MT";

            if (isDebug())
                result += "d";

            return result;
        }

        void updateOldLTOSetting()
        {
            if (! isDebug() && config.getPropertyAsValue ("wholeProgramOptimisation", nullptr) != Value())
                linkTimeOptimisationValue = (static_cast<int> (config ["wholeProgramOptimisation"]) == 0);
        }

        void updateOldArchSetting()
        {
            if (architectureTypeValue.get().isArray())
                return;

            const auto archString = architectureTypeValue.get().toString();
            const auto archType = architectureTypeFromString (archString);

            if (! archType)
                return;

            const auto pluginBinaryPathLocationIds =
            {
                Ids::vstBinaryLocation,
                Ids::vst3BinaryLocation,
                Ids::lv2BinaryLocation,
                Ids::aaxBinaryLocation,
                Ids::unityPluginBinaryLocation
            };

            for (const auto& location : pluginBinaryPathLocationIds)
            {
                if (auto* prop = config.getPropertyPointer (location))
                {
                    setBinaryPathDefault (location, *archType, prop->toString());
                }
            }

            architectureTypeValue = Array<var> { archString };
        }

    private:
        ValueTreePropertyWithDefault warningLevelValue, warningsAreErrorsValue, prebuildCommandValue, postbuildCommandValue, generateDebugSymbolsValue,
                                     enableIncrementalLinkingValue, useRuntimeLibDLLValue, multiProcessorCompilationValue,
                                     intermediatesPathValue, characterSetValue, architectureTypeValue, fastMathValue, debugInformationFormatValue,
                                     pluginBinaryCopyStepValue;

        struct LocationProperties
        {
            LocationProperties (ValueTree& tree, const Identifier& propertyID, UndoManager* um)
                : win32   (tree, propertyID + "_Win32",   um),
                  x64     (tree, propertyID + "_x64",     um),
                  arm64   (tree, propertyID + "_arm64",   um),
                  arm64ec (tree, propertyID + "_arm64ec", um)
            {
            }

            const ValueTreePropertyWithDefault* get (Architecture arch) const
            {
                return get (*this, arch);
            }

            ValueTreePropertyWithDefault* get (Architecture arch)
            {
                return get (*this, arch);
            }

            ValueTreePropertyWithDefault win32, x64, arm64, arm64ec;

        private:
            template <typename This>
            static auto get (This& t, Architecture arch) -> decltype (t.get (arch))
            {
                switch (arch)
                {
                    case Architecture::win32:   return &t.win32;
                    case Architecture::win64:   return &t.x64;
                    case Architecture::arm64:   return &t.arm64;
                    case Architecture::arm64ec: return &t.arm64ec;
                }

                jassertfalse;
                return nullptr;
            }
        };

        template <typename This>
        static auto getLocationForArchitecture (This& t, const Identifier& id, Architecture arch)
        {
            const auto properties =
            {
                std::pair { Ids::vstBinaryLocation,  &t.vstBinaryLocation },
                std::pair { Ids::vst3BinaryLocation, &t.vst3BinaryLocation },
                std::pair { Ids::aaxBinaryLocation,  &t.aaxBinaryLocation },
                std::pair { Ids::lv2BinaryLocation,  &t.lv2BinaryLocation }
            };

            const auto iter = std::find_if (properties.begin(),
                                            properties.end(),
                                            [id] (auto pair) { return id == pair.first; });

            return iter != properties.end() ? iter->second->get (arch) : nullptr;
        }

        ValueTreePropertyWithDefault* getLocationForArchitecture (const Identifier& id, Architecture arch)
        {
            return getLocationForArchitecture (*this, id, arch);
        }

        const ValueTreePropertyWithDefault* getLocationForArchitecture (const Identifier& id, Architecture arch) const
        {
            return getLocationForArchitecture (*this, id, arch);
        }

        LocationProperties vstBinaryLocation, vst3BinaryLocation, aaxBinaryLocation, lv2BinaryLocation, unityPluginBinaryLocation;

        //==============================================================================
        void addVisualStudioPluginInstallPathProperties (PropertyListBuilder& props)
        {
            auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3()
                                          || project.shouldBuildAAX() || project.shouldBuildUnityPlugin());

            if (isBuildingAnyPlugins)
                props.add (new ChoicePropertyComponent (pluginBinaryCopyStepValue, "Enable Plugin Copy Step"),
                           "Enable this to copy plugin binaries to a specified folder after building.");

            const auto addLocationProperties = [&] (auto& locationProps, const String& format)
            {
                for (const auto& [member, arch] : { std::tuple (&LocationProperties::win32,   Architecture::win32),
                                                    std::tuple (&LocationProperties::x64,     Architecture::win64),
                                                    std::tuple (&LocationProperties::arm64,   Architecture::arm64),
                                                    std::tuple (&LocationProperties::arm64ec, Architecture::arm64ec) })
                {
                    const auto archAndFormat = getArchitectureValueString (arch) + " " + format;
                    props.add (new TextPropertyComponentWithEnablement (locationProps.*member, pluginBinaryCopyStepValue, archAndFormat + " Binary Location", 1024, false),
                               "The folder in which the compiled " + archAndFormat + " binary should be placed.");
                }
            };

            if (project.shouldBuildVST3())
                addLocationProperties (vst3BinaryLocation, "VST3");

            if (project.shouldBuildAAX())
                addLocationProperties (aaxBinaryLocation, "AAX");

            if (project.shouldBuildLV2())
                addLocationProperties (lv2BinaryLocation, "LV2");

            if (project.shouldBuildUnityPlugin())
                addLocationProperties (unityPluginBinaryLocation, "Unity");

            if (project.shouldBuildVST())
                addLocationProperties (vstBinaryLocation, "VST (Legacy)");
        }
    };

    //==============================================================================
    class MSVCTarget final : public build_tools::ProjectType::Target
    {
    public:
        MSVCTarget (build_tools::ProjectType::Target::Type targetType, const MSVCProjectExporterBase& exporter)
            : build_tools::ProjectType::Target (targetType), owner (exporter)
        {
            projectGuid = createGUID (owner.getProject().getProjectUIDString() + getName());
        }

        virtual ~MSVCTarget() = default;

        String getProjectVersionString() const     { return "10.00"; }
        String getProjectFileSuffix() const        { return ".vcxproj"; }
        String getFiltersFileSuffix() const        { return ".vcxproj.filters"; }
        String getTopLevelXmlEntity() const        { return "Project"; }

        //==============================================================================
        void fillInProjectXml (XmlElement& projectXml) const
        {
            projectXml.setAttribute ("DefaultTargets", "Build");
            projectXml.setAttribute ("ToolsVersion", getOwner().getToolsVersion());
            projectXml.setAttribute ("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003");

            const auto allArchitectures = owner.getAllActiveArchitectures();

            {
                auto* configsGroup = projectXml.createNewChildElement ("ItemGroup");
                configsGroup->setAttribute ("Label", "ProjectConfigurations");

                for (ConstConfigIterator i (owner); i.next();)
                {
                    auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);
                    for (const auto& arch : allArchitectures)
                    {
                        auto* e = configsGroup->createNewChildElement ("ProjectConfiguration");
                        e->setAttribute ("Include", config.createMSVCConfigName (arch));
                        e->createNewChildElement ("Configuration")->addTextElement (config.getName());
                        e->createNewChildElement ("Platform")->addTextElement (getArchitectureValueString (arch));
                    }
                }
            }

            {
                auto* globals = projectXml.createNewChildElement ("PropertyGroup");
                globals->setAttribute ("Label", "Globals");
                globals->createNewChildElement ("ProjectGuid")->addTextElement (getProjectGuid());
            }

            {
                auto* imports = projectXml.createNewChildElement ("Import");
                imports->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props");
            }

            for (ConstConfigIterator i (owner); i.next();)
            {
                auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                for (const auto& arch : allArchitectures)
                {
                    auto* e = projectXml.createNewChildElement ("PropertyGroup");
                    setConditionAttribute (*e, config, arch);
                    e->setAttribute ("Label", "Configuration");
                    e->createNewChildElement ("ConfigurationType")->addTextElement (getProjectType());
                    e->createNewChildElement ("UseOfMfc")->addTextElement ("false");
                    e->createNewChildElement ("WholeProgramOptimization")->addTextElement (config.isLinkTimeOptimisationEnabled() ? "true"
                                                                                                                                  : "false");

                    auto charSet = config.getCharacterSetString();

                    if (charSet.isNotEmpty())
                        e->createNewChildElement ("CharacterSet")->addTextElement (charSet);

                    if (config.shouldLinkIncremental())
                        e->createNewChildElement ("LinkIncremental")->addTextElement ("true");

                    e->createNewChildElement ("PlatformToolset")->addTextElement (owner.getPlatformToolset());

                    addWindowsTargetPlatformToConfig (*e);

                    struct IntelLibraryInfo
                    {
                        String libraryKind;
                        String configString;
                    };

                    for (const auto& info : { IntelLibraryInfo { owner.getIPPLibrary(),   "UseIntelIPP" },
                                              IntelLibraryInfo { owner.getIPP1ALibrary(), "UseIntelIPP1A" },
                                              IntelLibraryInfo { owner.getMKL1ALibrary(), "UseInteloneMKL" } })
                    {
                        if (info.libraryKind.isNotEmpty())
                            e->createNewChildElement (info.configString)->addTextElement (info.libraryKind);
                    }
                }
            }

            {
                auto* e = projectXml.createNewChildElement ("Import");
                e->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props");
            }

            {
                auto* e = projectXml.createNewChildElement ("ImportGroup");
                e->setAttribute ("Label", "ExtensionSettings");
            }

            {
                auto* e = projectXml.createNewChildElement ("ImportGroup");
                e->setAttribute ("Label", "PropertySheets");
                auto* p = e->createNewChildElement ("Import");
                p->setAttribute ("Project", "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props");
                p->setAttribute ("Condition", "exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')");
                p->setAttribute ("Label", "LocalAppDataPlatform");
            }

            {
                auto* props = projectXml.createNewChildElement ("PropertyGroup");
                props->createNewChildElement ("_ProjectFileVersion")->addTextElement ("10.0.30319.1");
                props->createNewChildElement ("TargetExt")->addTextElement (getTargetSuffix());

                for (ConstConfigIterator i (owner); i.next();)
                {
                    auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                    for (const auto& arch : allArchitectures)
                    {
                        if (getConfigTargetPath (config).isNotEmpty())
                        {
                            auto* outdir = props->createNewChildElement ("OutDir");
                            setConditionAttribute (*outdir, config, arch);
                            outdir->addTextElement (build_tools::windowsStylePath (getConfigTargetPath (config)) + "\\");
                        }

                        {
                            auto* intdir = props->createNewChildElement ("IntDir");
                            setConditionAttribute (*intdir, config, arch);

                            auto intermediatesPath = getIntermediatesPath (config);
                            if (! intermediatesPath.endsWithChar (L'\\'))
                                intermediatesPath += L'\\';

                            intdir->addTextElement (build_tools::windowsStylePath (intermediatesPath));
                        }

                        {
                            auto* targetName = props->createNewChildElement ("TargetName");
                            setConditionAttribute (*targetName, config, arch);
                            targetName->addTextElement (msBuildEscape (config.getOutputFilename ("", false, type)));
                        }

                        {
                            auto* manifest = props->createNewChildElement ("GenerateManifest");
                            setConditionAttribute (*manifest, config, arch);
                            manifest->addTextElement ("true");
                        }

                        if (type != SharedCodeTarget)
                        {
                            auto librarySearchPaths = getLibrarySearchPaths (config);

                            if (! librarySearchPaths.isEmpty())
                            {
                                auto* libPath = props->createNewChildElement ("LibraryPath");
                                setConditionAttribute (*libPath, config, arch);
                                libPath->addTextElement ("$(LibraryPath);" + librarySearchPaths.joinIntoString (";"));
                            }
                        }

                        const auto enabled = config.getArchitectures().contains (arch) ? "true" : "false";

                        for (const auto optionName : { "PreBuildEventUseInBuild", "PostBuildEventUseInBuild" })
                        {
                            auto* tag = props->createNewChildElement (optionName);
                            setConditionAttribute (*tag, config, arch);
                            tag->addTextElement (enabled);
                        }
                    }
                }
            }

            for (ConstConfigIterator i (owner); i.next();)
            {
                auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                for (const auto& arch : allArchitectures)
                {
                    enum class EscapeQuotes { no, yes };

                    // VS doesn't correctly escape double quotes in preprocessor definitions, so we have
                    // to add our own layer of escapes
                    const auto addIncludePathsAndPreprocessorDefinitions = [this, &config] (XmlElement& xml, EscapeQuotes escapeQuotes)
                    {
                        auto includePaths = getOwner().getHeaderSearchPaths (config);
                        includePaths.add ("%(AdditionalIncludeDirectories)");
                        xml.createNewChildElement ("AdditionalIncludeDirectories")->addTextElement (includePaths.joinIntoString (";"));

                        const auto preprocessorDefs = getPreprocessorDefs (config, ";") + ";%(PreprocessorDefinitions)";
                        const auto preprocessorDefsEscaped = escapeQuotes == EscapeQuotes::yes ? preprocessorDefs.replace ("\"", "\\\"")
                                                                                               : preprocessorDefs;
                        xml.createNewChildElement ("PreprocessorDefinitions")->addTextElement (preprocessorDefsEscaped);
                    };

                    bool isDebug = config.isDebug();

                    auto* group = projectXml.createNewChildElement ("ItemDefinitionGroup");
                    setConditionAttribute (*group, config, arch);

                    {
                        auto* midl = group->createNewChildElement ("Midl");
                        midl->createNewChildElement ("PreprocessorDefinitions")->addTextElement (isDebug ? "_DEBUG;%(PreprocessorDefinitions)"
                                                                                                         : "NDEBUG;%(PreprocessorDefinitions)");
                        midl->createNewChildElement ("MkTypLibCompatible")->addTextElement ("true");
                        midl->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
                        midl->createNewChildElement ("TargetEnvironment")->addTextElement ("Win32");
                        midl->createNewChildElement ("HeaderFileName");
                    }

                    bool isUsingEditAndContinue = false;
                    const auto pdbFilename = getOwner().getIntDirFile (config, config.getOutputFilename (".pdb", true, type));

                    {
                        auto* cl = group->createNewChildElement ("ClCompile");

                        cl->createNewChildElement ("Optimization")->addTextElement (getOptimisationLevelString (config.getOptimisationLevelInt()));

                        if (isDebug || config.shouldGenerateDebugSymbols())
                        {
                            cl->createNewChildElement ("DebugInformationFormat")
                              ->addTextElement (config.getDebugInformationFormatString());
                        }

                        addIncludePathsAndPreprocessorDefinitions (*cl, EscapeQuotes::no);

                        cl->createNewChildElement ("RuntimeLibrary")->addTextElement (config.isUsingRuntimeLibDLL() ? (isDebug ? "MultiThreadedDebugDLL" : "MultiThreadedDLL")
                                                                                                                    : (isDebug ? "MultiThreadedDebug"    : "MultiThreaded"));
                        cl->createNewChildElement ("RuntimeTypeInfo")->addTextElement ("true");
                        cl->createNewChildElement ("PrecompiledHeader")->addTextElement ("NotUsing");
                        cl->createNewChildElement ("AssemblerListingLocation")->addTextElement ("$(IntDir)\\");
                        cl->createNewChildElement ("ObjectFileName")->addTextElement ("$(IntDir)\\");
                        cl->createNewChildElement ("ProgramDataBaseFileName")->addTextElement (pdbFilename);
                        cl->createNewChildElement ("WarningLevel")->addTextElement ("Level" + String (config.getWarningLevel()));
                        cl->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
                        cl->createNewChildElement ("MultiProcessorCompilation")->addTextElement (config.shouldUseMultiProcessorCompilation() ? "true" : "false");

                        if (config.isFastMathEnabled())
                            cl->createNewChildElement ("FloatingPointModel")->addTextElement ("Fast");

                        auto extraFlags = getOwner().replacePreprocessorTokens (config, config.getAllCompilerFlagsString()).trim();

                        if (extraFlags.isNotEmpty())
                            cl->createNewChildElement ("AdditionalOptions")->addTextElement (extraFlags + " %(AdditionalOptions)");

                        if (config.areWarningsTreatedAsErrors())
                            cl->createNewChildElement ("TreatWarningAsError")->addTextElement ("true");

                        auto cppStandard = owner.project.getCppStandardString();
                        cl->createNewChildElement ("LanguageStandard")->addTextElement ("stdcpp" + cppStandard);
                    }

                    {
                        auto* res = group->createNewChildElement ("ResourceCompile");
                        addIncludePathsAndPreprocessorDefinitions (*res, EscapeQuotes::yes);
                    }

                    auto externalLibraries = getExternalLibraries (config, getOwner().getExternalLibrariesStringArray());
                    auto additionalDependencies = type != SharedCodeTarget && type != LV2Helper && type != VST3Helper && ! externalLibraries.isEmpty()
                                                  ? externalLibraries.joinIntoString (";") + ";%(AdditionalDependencies)"
                                                  : String();

                    auto librarySearchPaths = config.getLibrarySearchPaths();
                    auto additionalLibraryDirs = type != SharedCodeTarget && type != LV2Helper && type != VST3Helper && librarySearchPaths.size() > 0
                                                 ? getOwner().replacePreprocessorTokens (config, librarySearchPaths.joinIntoString (";")) + ";%(AdditionalLibraryDirectories)"
                                                 : String();

                    {
                        auto* link = group->createNewChildElement ("Link");
                        link->createNewChildElement ("OutputFile")->addTextElement (getOutputFilePath (config));
                        link->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
                        link->createNewChildElement ("IgnoreSpecificDefaultLibraries")->addTextElement (isDebug ? "libcmt.lib; msvcrt.lib;;%(IgnoreSpecificDefaultLibraries)"
                                                                                                                : "%(IgnoreSpecificDefaultLibraries)");
                        link->createNewChildElement ("GenerateDebugInformation")->addTextElement ((isDebug || config.shouldGenerateDebugSymbols()) ? "true" : "false");
                        link->createNewChildElement ("ProgramDatabaseFile")->addTextElement (pdbFilename);
                        link->createNewChildElement ("SubSystem")->addTextElement (type == ConsoleApp || type == LV2Helper || type == VST3Helper ? "Console" : "Windows");

                        if (arch == Architecture::win32)
                            link->createNewChildElement ("TargetMachine")->addTextElement ("MachineX86");

                        if (isUsingEditAndContinue)
                            link->createNewChildElement ("ImageHasSafeExceptionHandlers")->addTextElement ("false");

                        if (! isDebug)
                        {
                            link->createNewChildElement ("OptimizeReferences")->addTextElement ("true");
                            link->createNewChildElement ("EnableCOMDATFolding")->addTextElement ("true");
                        }

                        if (additionalLibraryDirs.isNotEmpty())
                            link->createNewChildElement ("AdditionalLibraryDirectories")->addTextElement (additionalLibraryDirs);

                        link->createNewChildElement ("LargeAddressAware")->addTextElement ("true");

                        if (config.isLinkTimeOptimisationEnabled())
                            link->createNewChildElement ("LinkTimeCodeGeneration")->addTextElement ("UseLinkTimeCodeGeneration");

                        if (additionalDependencies.isNotEmpty())
                            link->createNewChildElement ("AdditionalDependencies")->addTextElement (additionalDependencies);

                        auto extraLinkerOptions = config.getAllLinkerFlagsString();
                        if (extraLinkerOptions.isNotEmpty())
                            link->createNewChildElement ("AdditionalOptions")->addTextElement (getOwner().replacePreprocessorTokens (config, extraLinkerOptions).trim()
                                                                                               + " %(AdditionalOptions)");

                        auto delayLoadedDLLs = getOwner().msvcDelayLoadedDLLs;
                        if (delayLoadedDLLs.isNotEmpty())
                            link->createNewChildElement ("DelayLoadDLLs")->addTextElement (delayLoadedDLLs);

                        auto moduleDefinitionsFile = getModuleDefinitions (config);
                        if (moduleDefinitionsFile.isNotEmpty())
                            link->createNewChildElement ("ModuleDefinitionFile")
                                ->addTextElement (moduleDefinitionsFile);
                    }

                    {
                        auto* bsc = group->createNewChildElement ("Bscmake");
                        bsc->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
                        bsc->createNewChildElement ("OutputFile")->addTextElement (getOwner().getIntDirFile (config, config.getOutputFilename (".bsc", true, type)));
                    }

                    if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
                    {
                        auto* lib = group->createNewChildElement ("Lib");

                        if (additionalDependencies.isNotEmpty())
                            lib->createNewChildElement ("AdditionalDependencies")->addTextElement (additionalDependencies);

                        if (additionalLibraryDirs.isNotEmpty())
                            lib->createNewChildElement ("AdditionalLibraryDirectories")->addTextElement (additionalLibraryDirs);
                    }

                    if (auto manifestFile = getOwner().getManifestPath(); manifestFile.getRoot() != build_tools::RelativePath::unknown || type == VST3Helper)
                    {
                        auto* bsc = group->createNewChildElement ("Manifest");
                        auto* additional = bsc->createNewChildElement ("AdditionalManifestFiles");

                        if (manifestFile.getRoot() != build_tools::RelativePath::unknown)
                        {
                            additional->addTextElement (manifestFile.rebased (getOwner().getProject().getFile().getParentDirectory(),
                                                                              getOwner().getTargetFolder(),
                                                                              build_tools::RelativePath::buildTargetFolder).toWindowsStyle());
                        }
                    }

                    if (getTargetFileType() == staticLibrary && arch == Architecture::win32)
                    {
                        auto* lib = group->createNewChildElement ("Lib");
                        lib->createNewChildElement ("TargetMachine")->addTextElement ("MachineX86");
                    }

                    auto preBuild = getPreBuildSteps (config, arch);
                    if (preBuild.isNotEmpty())
                        group->createNewChildElement ("PreBuildEvent")
                             ->createNewChildElement ("Command")
                             ->addTextElement (preBuild);

                    auto postBuild = getPostBuildSteps (config, arch);
                    if (postBuild.isNotEmpty())
                        group->createNewChildElement ("PostBuildEvent")
                             ->createNewChildElement ("Command")
                             ->addTextElement (postBuild);
                }
            }

            std::unique_ptr<XmlElement> otherFilesGroup (new XmlElement ("ItemGroup"));

            {
                auto* cppFiles    = projectXml.createNewChildElement ("ItemGroup");
                auto* headerFiles = projectXml.createNewChildElement ("ItemGroup");

                writePrecompiledHeaderFiles (*cppFiles);

                for (int i = 0; i < getOwner().getAllGroups().size(); ++i)
                {
                    auto& group = getOwner().getAllGroups().getReference (i);

                    if (group.getNumChildren() > 0)
                        addFilesToCompile (group, *cppFiles, *headerFiles, *otherFilesGroup);
                }

                if (type == LV2Helper)
                {
                    const auto location = owner.rebaseFromProjectFolderToBuildTarget (owner.getLV2HelperProgramSource())
                                               .toWindowsStyle();
                    cppFiles->createNewChildElement ("ClCompile")->setAttribute ("Include", location);
                }
                else if (type == VST3Helper)
                {
                    const auto location = owner.rebaseFromProjectFolderToBuildTarget (owner.getVST3HelperProgramSource())
                                               .toWindowsStyle();
                    cppFiles->createNewChildElement ("ClCompile")->setAttribute ("Include", location);
                }
            }

            if (getOwner().iconFile.existsAsFile())
            {
                auto* e = otherFilesGroup->createNewChildElement ("None");
                e->setAttribute ("Include", prependDot (getOwner().iconFile.getFileName()));
            }

            if (getOwner().packagesConfigFile.existsAsFile())
            {
                auto* e = otherFilesGroup->createNewChildElement ("None");
                e->setAttribute ("Include", getOwner().packagesConfigFile.getFileName());
            }

            if (otherFilesGroup->getFirstChildElement() != nullptr)
                projectXml.addChildElement (otherFilesGroup.release());

            if (type != SharedCodeTarget && getOwner().hasResourceFile())
            {
                auto* rcGroup = projectXml.createNewChildElement ("ItemGroup");
                auto* e = rcGroup->createNewChildElement ("ResourceCompile");
                e->setAttribute ("Include", prependDot (getOwner().rcFile.getFileName()));
            }

            {
                auto* e = projectXml.createNewChildElement ("Import");
                e->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets");
            }

            {
                if (owner.shouldAddWebView2Package())
                {
                    auto* importGroup = projectXml.createNewChildElement ("ImportGroup");
                    importGroup->setAttribute ("Label", "ExtensionTargets");

                    auto packageTargetsPath = "packages\\" + getWebView2PackageName() + "." + getWebView2PackageVersion()
                                            + "\\build\\native\\" + getWebView2PackageName() + ".targets";

                    auto* e = importGroup->createNewChildElement ("Import");
                    e->setAttribute ("Project", packageTargetsPath);
                    e->setAttribute ("Condition", "Exists('" + packageTargetsPath + "')");
                }

                if (owner.shouldLinkWebView2Statically())
                {
                    auto* propertyGroup = projectXml.createNewChildElement ("PropertyGroup");
                    auto* loaderPref = propertyGroup->createNewChildElement ("WebView2LoaderPreference");
                    loaderPref->addTextElement ("Static");
                }
            }
        }

        String getProjectType() const
        {
            auto targetFileType = getTargetFileType();

            if (targetFileType == executable)     return "Application";
            if (targetFileType == staticLibrary)  return "StaticLibrary";

            return "DynamicLibrary";
        }

        //==============================================================================
        static void setSourceFilePCHSettings (XmlElement& element,
                                              const File& pchFile,
                                              const String& option,
                                              const BuildConfiguration& config,
                                              Architecture arch)
        {
            auto setConfigConditionAttribute = [&config, arch] (XmlElement* elementToSet) -> XmlElement*
            {
                setConditionAttribute (*elementToSet, config, arch);
                return elementToSet;
            };

            setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeader"))->addTextElement (option);
            setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeaderFile"))->addTextElement (pchFile.getFileName());
            setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeaderOutputFile"))->addTextElement ("$(Platform)\\$(Configuration)\\JucePrecompiledHeader.pch");
            setConfigConditionAttribute (element.createNewChildElement ("ForcedIncludeFiles"))->addTextElement (pchFile.getFileName());
        }

        void writePrecompiledHeaderFiles (XmlElement& cpps) const
        {
            for (ConstConfigIterator i (owner); i.next();)
            {
                if (! i->shouldUsePrecompiledHeaderFile())
                    continue;

                auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                for (const auto& arch : config.getArchitectures())
                {
                    auto pchFileContent = config.getPrecompiledHeaderFileContent();

                    if (pchFileContent.isEmpty())
                        continue;

                    auto pchFile = owner.getTargetFolder().getChildFile (config.getPrecompiledHeaderFilename()).withFileExtension (".h");

                    build_tools::writeStreamToFile (pchFile, [&] (MemoryOutputStream& mo)
                    {
                        mo << pchFileContent;
                    });

                    auto pchSourceFile = pchFile.withFileExtension (".cpp");

                    build_tools::writeStreamToFile (pchSourceFile, [this] (MemoryOutputStream& mo)
                    {
                        mo.setNewLineString (owner.getNewLineString());

                        writeAutoGenWarningComment (mo);

                        mo << "    This is an empty source file generated by JUCE required for Visual Studio PCH." << newLine
                            << newLine
                            << "*/" << newLine
                            << newLine;
                    });

                    auto* pchSourceElement = cpps.createNewChildElement ("ClCompile");
                    pchSourceElement->setAttribute ("Include", prependDot (pchSourceFile.getFileName()));
                    setSourceFilePCHSettings (*pchSourceElement, pchFile, "Create", config, arch);
                }
            }
        }

        void addFilesToCompile (const Project::Item& projectItem, XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles) const
        {
            auto targetType = (getOwner().getProject().isAudioPluginProject() ? type : SharedCodeTarget);

            if (projectItem.isGroup())
            {
                for (int i = 0; i < projectItem.getNumChildren(); ++i)
                    addFilesToCompile (projectItem.getChild (i), cpps, headers, otherFiles);
            }
            else if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (getOwner())
                     && getOwner().getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
            {
                build_tools::RelativePath path (projectItem.getFile(), getOwner().getTargetFolder(), build_tools::RelativePath::buildTargetFolder);

                jassert (path.getRoot() == build_tools::RelativePath::buildTargetFolder);

                if (path.hasFileExtension (cOrCppFileExtensions) || path.hasFileExtension (asmFileExtensions))
                {
                    auto* e = cpps.createNewChildElement ("ClCompile");
                    e->setAttribute ("Include", path.toWindowsStyle());

                    if (projectItem.shouldBeCompiled())
                    {
                        auto extraCompilerFlags = getOwner().getCompilerFlagsForProjectItem (projectItem);

                        if (shouldAddBigobjFlag (path))
                        {
                            const String bigobjFlag ("/bigobj");

                            if (! extraCompilerFlags.contains (bigobjFlag))
                            {
                                extraCompilerFlags << " " << bigobjFlag;
                                extraCompilerFlags.trim();
                            }
                        }

                        if (extraCompilerFlags.isNotEmpty())
                            e->createNewChildElement ("AdditionalOptions")->addTextElement (extraCompilerFlags + " %(AdditionalOptions)");

                        if (! projectItem.shouldSkipPCH())
                        {
                            for (ConstConfigIterator i (owner); i.next();)
                            {
                                auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                                if (config.shouldUsePrecompiledHeaderFile())
                                {
                                    for (const auto& arch : config.getArchitectures())
                                    {
                                        auto pchFile = owner.getTargetFolder().getChildFile (i->getPrecompiledHeaderFilename()).withFileExtension (".h");

                                        if (pchFile.existsAsFile())
                                            setSourceFilePCHSettings (*e, pchFile, "Use", *i, arch);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        e->createNewChildElement ("ExcludedFromBuild")->addTextElement ("true");
                    }
                }
                else if (path.hasFileExtension (headerFileExtensions))
                {
                    headers.createNewChildElement ("ClInclude")->setAttribute ("Include", path.toWindowsStyle());
                }
                else if (! path.hasFileExtension (objCFileExtensions))
                {
                    otherFiles.createNewChildElement ("None")->setAttribute ("Include", path.toWindowsStyle());
                }
            }
        }

        static void setConditionAttribute (XmlElement& xml, const BuildConfiguration& config, Architecture arch)
        {
            auto& msvcConfig = *static_cast<const MSVCBuildConfiguration*> (&config);
            xml.setAttribute ("Condition", "'$(Configuration)|$(Platform)'=='" + msvcConfig.createMSVCConfigName (arch) + "'");
        }

        //==============================================================================
        void addFilterGroup (XmlElement& groups, const String& path) const
        {
            auto* e = groups.createNewChildElement ("Filter");
            e->setAttribute ("Include", path);
            e->createNewChildElement ("UniqueIdentifier")->addTextElement (createGUID (path + "_guidpathsaltxhsdf"));
        }

        void addFileToFilter (const build_tools::RelativePath& file, const String& groupPath,
                              XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles) const
        {
            XmlElement* e = nullptr;

            if (file.hasFileExtension (headerFileExtensions))
                e = headers.createNewChildElement ("ClInclude");
            else if (file.hasFileExtension (sourceFileExtensions))
                e = cpps.createNewChildElement ("ClCompile");
            else
                e = otherFiles.createNewChildElement ("None");

            jassert (file.getRoot() == build_tools::RelativePath::buildTargetFolder);
            e->setAttribute ("Include", file.toWindowsStyle());
            e->createNewChildElement ("Filter")->addTextElement (groupPath);
        }

        bool addFilesToFilter (const Project::Item& projectItem, const String& path,
                               XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles, XmlElement& groups) const
        {
            auto targetType = (getOwner().getProject().isAudioPluginProject() ? type : SharedCodeTarget);

            if (projectItem.isGroup())
            {
                bool filesWereAdded = false;

                for (int i = 0; i < projectItem.getNumChildren(); ++i)
                    if (addFilesToFilter (projectItem.getChild (i),
                                          (path.isEmpty() ? String() : (path + "\\")) + projectItem.getChild (i).getName(),
                                          cpps, headers, otherFiles, groups))
                        filesWereAdded = true;

                if (filesWereAdded)
                    addFilterGroup (groups, path);

                return filesWereAdded;
            }
            else if (projectItem.shouldBeAddedToTargetProject()
                     && projectItem.shouldBeAddedToTargetExporter (getOwner())
                     && getOwner().getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
            {
                build_tools::RelativePath relativePath (projectItem.getFile(),
                                                        getOwner().getTargetFolder(),
                                                        build_tools::RelativePath::buildTargetFolder);

                jassert (relativePath.getRoot() == build_tools::RelativePath::buildTargetFolder);

                addFileToFilter (relativePath, path.upToLastOccurrenceOf ("\\", false, false), cpps, headers, otherFiles);
                return true;
            }

            return false;
        }

        void fillInFiltersXml (XmlElement& filterXml) const
        {
            filterXml.setAttribute ("ToolsVersion", getOwner().getToolsVersion());
            filterXml.setAttribute ("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003");

            auto* groupsXml  = filterXml.createNewChildElement ("ItemGroup");
            auto* cpps       = filterXml.createNewChildElement ("ItemGroup");
            auto* headers    = filterXml.createNewChildElement ("ItemGroup");
            std::unique_ptr<XmlElement> otherFilesGroup (new XmlElement ("ItemGroup"));

            for (int i = 0; i < getOwner().getAllGroups().size(); ++i)
            {
                auto& group = getOwner().getAllGroups().getReference (i);

                if (group.getNumChildren() > 0)
                    addFilesToFilter (group, group.getName(), *cpps, *headers, *otherFilesGroup, *groupsXml);
            }

            if (getOwner().iconFile.existsAsFile())
            {
                auto* e = otherFilesGroup->createNewChildElement ("None");
                e->setAttribute ("Include", prependDot (getOwner().iconFile.getFileName()));
                e->createNewChildElement ("Filter")->addTextElement (ProjectSaver::getJuceCodeGroupName());
            }

            if (getOwner().packagesConfigFile.existsAsFile())
            {
                auto* e = otherFilesGroup->createNewChildElement ("None");
                e->setAttribute ("Include", getOwner().packagesConfigFile.getFileName());
            }

            if (otherFilesGroup->getFirstChildElement() != nullptr)
                filterXml.addChildElement (otherFilesGroup.release());

            if (type != SharedCodeTarget && getOwner().hasResourceFile())
            {
                auto* rcGroup = filterXml.createNewChildElement ("ItemGroup");
                auto* e = rcGroup->createNewChildElement ("ResourceCompile");
                e->setAttribute ("Include", prependDot (getOwner().rcFile.getFileName()));
                e->createNewChildElement ("Filter")->addTextElement (ProjectSaver::getJuceCodeGroupName());
            }
        }

        const MSVCProjectExporterBase& getOwner() const { return owner; }
        const String& getProjectGuid() const            { return projectGuid; }

        //==============================================================================
        void writeProjectFile()
        {
            {
                XmlElement projectXml (getTopLevelXmlEntity());
                fillInProjectXml (projectXml);
                writeXmlOrThrow (projectXml, getVCProjFile(), "UTF-8", 10);
            }

            {
                XmlElement filtersXml (getTopLevelXmlEntity());
                fillInFiltersXml (filtersXml);
                writeXmlOrThrow (filtersXml, getVCProjFiltersFile(), "UTF-8", 100);
            }
        }

        String getSolutionTargetPath (const BuildConfiguration& config) const
        {
            auto binaryPath = config.getTargetBinaryRelativePathString().trim();
            if (binaryPath.isEmpty())
                return "$(SolutionDir)$(Platform)\\$(Configuration)";

            build_tools::RelativePath binaryRelPath (binaryPath, build_tools::RelativePath::projectFolder);

            if (binaryRelPath.isAbsolute())
                return binaryRelPath.toWindowsStyle();

            return prependDot (binaryRelPath.rebased (getOwner().projectFolder,
                                                      getOwner().getTargetFolder(),
                                                      build_tools::RelativePath::buildTargetFolder)
                               .toWindowsStyle());
        }

        String getConfigTargetPath (const MSVCBuildConfiguration& config) const
        {
            const auto result = getSolutionTargetPath (config) + "\\" + getName();

            if (type == LV2PlugIn)
                return result + "\\" + config.getTargetBinaryNameString() + ".lv2";

            return result;
        }

        /*  Like getConfigTargetPath, but expands $(ProjectName) so that build products can be used
            in other projects where $(ProjectName) will expand to a different value.
        */
        String getExpandedConfigTargetPath (const MSVCBuildConfiguration& config) const
        {
            return getConfigTargetPath (config).replace ("$(ProjectName)", getOwner().getProjectFileBaseName (getName()));
        }

        String getIntermediatesPath (const MSVCBuildConfiguration& config) const
        {
            auto intDir = (config.getIntermediatesPathString().isNotEmpty() ? config.getIntermediatesPathString()
                                                                            : "$(Platform)\\$(Configuration)");

            if (! intDir.endsWithChar (L'\\'))
                intDir += L'\\';

            return intDir + getName();
        }

        static const char* getOptimisationLevelString (int level)
        {
            switch (level)
            {
                case optimiseMinSize:   return "MinSpace";
                case optimiseMaxSpeed:  return "MaxSpeed";
                case optimiseFull:      return "Full";
                default:                return "Disabled";
            }
        }

        String getTargetSuffix() const
        {
            auto fileType = getTargetFileType();

            if (fileType == executable)          return ".exe";
            if (fileType == staticLibrary)       return ".lib";
            if (fileType == sharedLibraryOrDLL)  return ".dll";

            if (fileType == pluginBundle)
            {
                if (type == AAXPlugIn)   return ".aaxdll";

                return ".dll";
            }

            return {};
        }

        String getPreprocessorDefs (const BuildConfiguration& config, const String& joinString) const
        {
            auto defines = getOwner().msvcExtraPreprocessorDefs;
            defines.set ("WIN32", "");
            defines.set ("_WINDOWS", "");

            if (config.isDebug())
            {
                defines.set ("DEBUG", "");
                defines.set ("_DEBUG", "");
            }
            else
            {
                defines.set ("NDEBUG", "");
            }

            defines = mergePreprocessorDefs (defines, getOwner().getAllPreprocessorDefs (config, type));

            if (getTargetFileType() == staticLibrary || getTargetFileType() == sharedLibraryOrDLL)
                defines.set("_LIB", "");

            StringArray result;

            for (int i = 0; i < defines.size(); ++i)
            {
                auto def = defines.getAllKeys()[i];
                auto value = defines.getAllValues()[i];
                if (value.isNotEmpty())
                    def << "=" << value;

                result.add (def);
            }

            return result.joinIntoString (joinString);
        }

        //==============================================================================
        build_tools::RelativePath getAAXIconFile() const
        {
            const auto aaxSdk = owner.getAAXPathRelative();
            build_tools::RelativePath projectIcon ("icon.ico", build_tools::RelativePath::buildTargetFolder);

            if (getOwner().getTargetFolder().getChildFile ("icon.ico").existsAsFile())
                return projectIcon.rebased (getOwner().getTargetFolder(),
                                            getOwner().getProject().getProjectFolder(),
                                            build_tools::RelativePath::projectFolder);

            return aaxSdk.getChildFile ("Utilities").getChildFile ("PlugIn.ico");
        }

        String getExtraPostBuildSteps (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            using Builder = MSVCScriptBuilder;

            const auto copyBuildOutputIntoBundle = [&] (const StringArray& segments)
            {
                return "copy /Y "
                     + getOutputFilePath (config).quoted()
                     + " "
                     + getOwner().getOutDirFile (config, segments.joinIntoString ("\\")).quoted();
            };

            const auto copyBundleToInstallDirectory = [&] (const StringArray& segments, const String& directory)
            {
                const auto copyStep = "\r\nxcopy /E /H /K /R /Y /I "
                                    + getOwner().getOutDirFile (config, segments[0]).quoted()
                                    + " "
                                    + (directory + "\\" + segments[0] + "\\").quoted();

                return config.isPluginBinaryCopyStepEnabled() ? copyStep : "";
            };

            if (type == AAXPlugIn)
            {
                const auto aaxSdk = owner.getAAXPathRelative();
                const auto aaxLibsFolder = aaxSdk.getChildFile ("Libs");
                const auto bundleScript  = aaxSdk.getChildFile ("Utilities").getChildFile ("CreatePackage.bat");
                const auto iconFilePath  = getAAXIconFile();

                const auto segments = getAaxBundleStructure (config, arch);

                const auto pkgScript = copyBuildOutputIntoBundle (segments);

                const auto archDir = StringArray (segments.strings.data(), segments.size() - 1).joinIntoString ("\\");
                const auto rebasedArchDir = getOwner().getOutDirFile (config, archDir);
                const auto fixScript = "\r\ncall "
                                     + createRebasedPath (bundleScript)
                                     + " "
                                     + rebasedArchDir.quoted()
                                     + String (" ")
                                     + createRebasedPath (iconFilePath);

                const auto copyScript = copyBundleToInstallDirectory (segments, config.getBinaryPath (Ids::aaxBinaryLocation, arch));

                return pkgScript + fixScript + copyScript;
            }

            if (type == UnityPlugIn)
            {
                build_tools::RelativePath scriptPath (config.project.getGeneratedCodeFolder().getChildFile (config.project.getUnityScriptName()),
                                                      getOwner().getTargetFolder(),
                                                      build_tools::RelativePath::projectFolder);

                auto pkgScript = String ("copy /Y ") + scriptPath.toWindowsStyle().quoted() + " \"$(OutDir)\"";

                if (config.isPluginBinaryCopyStepEnabled())
                {
                    auto copyLocation = config.getBinaryPath (Ids::unityPluginBinaryLocation, arch);

                    pkgScript += "\r\ncopy /Y \"$(OutDir)$(TargetFileName)\" " +  String (copyLocation + "\\$(TargetFileName)").quoted();
                    pkgScript += "\r\ncopy /Y " + String ("$(OutDir)" + config.project.getUnityScriptName()).quoted() + " " + String (copyLocation + "\\" + config.project.getUnityScriptName()).quoted();
                }

                return pkgScript;
            }

            if (type == LV2PlugIn)
            {
                const auto* writerTarget = [&]() -> MSVCTarget*
                {
                    for (auto* target : owner.targets)
                        if (target->type == LV2Helper)
                            return target;

                    return nullptr;
                }();

                Builder builder;
                const auto writer = (writerTarget->getExpandedConfigTargetPath (config)
                                  + "\\"
                                  + writerTarget->getBinaryNameWithSuffix (config)).quoted()
                                  + " \"$(OutDir)$(TargetFileName)\"\r\n";

                const auto copyStep = "xcopy /E /H /I /K /R /Y \"$(OutDir)\" \""
                                    + config.getBinaryPath (Ids::lv2BinaryLocation, arch)
                                    + '\\'
                                    + config.getTargetBinaryNameString()
                                    + ".lv2\"\r\n";

                builder.runAndCheck (writer,
                                     config.isPluginBinaryCopyStepEnabled() ? copyStep : Builder{}.info ("Sucessfully generated LV2 manifest").build(),
                                     Builder{}.error ("Failed to generate LV2 manifest.")
                                              .exit (-1));

                return builder.build();
            }

            if (type == VST3PlugIn)
            {
                const auto segments = getVst3BundleStructure (config, arch);

                const auto manifestScript = [&]() -> String
                {
                    const auto* writerTarget = [&]() -> MSVCTarget*
                    {
                        for (auto* target : owner.targets)
                            if (target->type == VST3Helper)
                                return target;

                        return nullptr;
                    }();

                    if (writerTarget == nullptr)
                        return "";

                    const auto helperExecutablePath = writerTarget->getExpandedConfigTargetPath (config)
                                                    + "\\"
                                                    + writerTarget->getBinaryNameWithSuffix (config);

                    {
                        // moduleinfotool doesn't handle Windows-style path separators properly when computing the bundle name
                        const auto normalisedBundlePath = getOwner().getOutDirFile (config, segments[0]).replace ("\\", "/");
                        const auto contentsDir = normalisedBundlePath + "\\Contents";
                        const auto resourceDir = contentsDir + "\\Resources";
                        const auto manifestPath = (resourceDir + "\\moduleinfo.json");
                        const auto resourceDirPath = resourceDir + "\\";
                        const auto pluginName = getOwner().project.getPluginNameString();

                        const auto manifestInvocationString = StringArray
                        {
                            helperExecutablePath.quoted(),
                            "-create",
                            "-version", getOwner().project.getVersionString().quoted(),
                            "-path",    normalisedBundlePath.quoted(),
                            "-output",  manifestPath.quoted()
                        }.joinIntoString (" ");

                        const auto crossCompilationPairs =
                        {
                            // This catches ARM64 and EC for x64 manifest generation
                            std::pair { Architecture::arm64, Architecture::win64 },
                            std::pair { arch, arch }
                        };

                        Builder builder;

                        builder.set ("manifest_generated", 0);

                        for (auto [hostArch, targetArch] : crossCompilationPairs)
                        {
                            const StringArray expr
                            {
                                "\"$(PROCESSOR_ARCHITECTURE)\" == " + getVisualStudioArchitectureId (hostArch).quoted(),
                                "\"$(Platform)\""            " == " + getVisualStudioPlatformId (targetArch).quoted()
                            };

                            builder.ifAllConditionsTrue (expr, Builder{}.call ("_generate_manifest")
                                                                        .set ("manifest_generated", 1));
                        }

                        const auto archMismatchErrorString = StringArray
                        {
                            "VST3 manifest generation is disabled for",
                            pluginName,
                            "because a",
                            getVisualStudioArchitectureId (arch),
                            "manifest helper cannot run on a host system",
                            "processor detected to be $(PROCESSOR_ARCHITECTURE)."
                        }.joinIntoString (" ");

                        const auto architectureMatched = Builder{}
                            .ifelse ("exist " + manifestPath.quoted(),
                                     Builder{}.deleteFile (manifestPath.quoted()))
                            .ifelse ("not exist "  + resourceDirPath.quoted(),
                                     Builder{}.mkdir (resourceDirPath.quoted()))
                            .runAndCheck (manifestInvocationString,
                                          Builder{}.info ("Successfully generated a manifest for " + pluginName)
                                                   .jump ("_continue"),
                                          Builder{}.info ("The manifest helper failed")
                                                   .jump ("_continue"));

                        builder.ifelse ("%manifest_generated% equ 0",
                                        Builder{}.jump ("_arch_mismatch"));

                        builder.jump ("_continue");
                        builder.labelledSection ("_generate_manifest", architectureMatched);
                        builder.labelledSection ("_arch_mismatch",     Builder{}.info (archMismatchErrorString));
                        builder.labelledSection ("_continue", "");

                        return builder.build();
                    }
                }();

                const auto pkgScript = copyBuildOutputIntoBundle (segments);
                const auto copyScript = copyBundleToInstallDirectory (segments, config.getBinaryPath (Ids::vst3BinaryLocation, arch));

                return MSVCScriptBuilder{}
                    .append (pkgScript)
                    .append (manifestScript)
                    .append (copyScript)
                    .build();
            }

            if (type == VSTPlugIn && config.isPluginBinaryCopyStepEnabled())
            {
                const String copyCommand = "copy /Y \"$(OutDir)$(TargetFileName)\" \""
                                         + config.getBinaryPath (Ids::vstBinaryLocation, arch)
                                         + "\\$(TargetFileName)\"";

                return MSVCScriptBuilder{}
                    .mkdir (config.getBinaryPath (Ids::vstBinaryLocation, arch).quoted())
                    .append (copyCommand)
                    .build();
            }

            return {};
        }

        String getExtraPreBuildSteps (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            const auto createBundleStructure = [&] (const StringArray& segments)
            {
                auto directory = getOwner().getOutDirFile (config, "");
                MSVCScriptBuilder script;

                std::for_each (segments.begin(), std::prev (segments.end()), [&] (const auto& s)
                {
                    directory += (directory.isEmpty() ? "" : "\\") + s;

                    script.ifelse ("not exist " + (directory + "\\").quoted(),
                                   MSVCScriptBuilder{}.deleteFile (directory.quoted())
                                                      .mkdir (directory.quoted()).build());
                });

                return script.build();
            };

            MSVCScriptBuilder builder;

            if (arch == Architecture::win64)
            {
                const auto x86ToolchainErrorMessage =
                    "echo : Warning: Toolchain configuration issue!"
                    " You are using a 32-bit toolchain to compile a 64-bit target on a 64-bit system."
                    " This may cause problems with the build system."
                    " To resolve this, use the x64 version of MSBuild. You can invoke it directly at:"
                    " \"<VisualStudioPathHere>/MSBuild/Current/Bin/amd64/MSBuild.exe\""
                    " Or, use the \"x64 Native Tools Command Prompt\" script.";

                builder.ifAllConditionsTrue (
                {
                    "\"$(PROCESSOR_ARCHITECTURE)\" == " + getVisualStudioArchitectureId (Architecture::win32).quoted(),

                    // This only exists if the process is x86 but the host is x64.
                    "defined PROCESSOR_ARCHITEW6432"
                }, MSVCScriptBuilder{}.append (x86ToolchainErrorMessage));
            }

            if (type == LV2PlugIn)
            {
                const auto crossCompilationPairs =
                {
                    // This catches ARM64 and EC for x64 manifest generation
                    std::pair { Architecture::arm64, Architecture::win64 },
                    std::pair { arch, arch }
                };

                for (auto [hostArch, targetArch] : crossCompilationPairs)
                {
                    const StringArray expr
                    {
                        "\"$(PROCESSOR_ARCHITECTURE)\" == " + getVisualStudioArchitectureId (hostArch).quoted(),
                        "\"$(Platform)\""            " == " + getVisualStudioPlatformId (targetArch).quoted()
                    };

                    builder.ifAllConditionsTrue (expr, MSVCScriptBuilder{}.jump ("_continue"));
                }

                builder.error (StringArray
                               {
                                   "\"$(Platform)\"",
                                   "LV2 cross-compilation is not available on",
                                   "\"$(PROCESSOR_ARCHITECTURE)\" hosts."
                               }.joinIntoString (" "));
                builder.exit (-1);
                builder.labelledSection ("_continue", "");

                return builder.build();
            }

            if (type == AAXPlugIn)
                return createBundleStructure (getAaxBundleStructure (config, arch));

            if (type == VST3PlugIn)
                return builder.build() + "\r\n" + createBundleStructure (getVst3BundleStructure (config, arch));

            return {};
        }

        String getPostBuildSteps (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            const auto post = config.getPostbuildCommandString();
            const auto extra = getExtraPostBuildSteps (config, arch);

            if (post.isNotEmpty() || extra.isNotEmpty())
            {
                return MSVCScriptBuilder{}
                    .append (post.replace ("\n", "\r\n"))
                    .append (extra)
                    .build();
            }

            return "";
        }

        String getPreBuildSteps (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            const auto pre = config.getPrebuildCommandString();
            const auto extra = getExtraPreBuildSteps (config, arch);

            if (pre.isNotEmpty() || extra.isNotEmpty())
            {
                return MSVCScriptBuilder{}
                    .append (pre.replace ("\n", "\r\n"))
                    .append (extra)
                    .build();
            }

            return "";
        }

        String getBinaryNameWithSuffix (const MSVCBuildConfiguration& config) const
        {
            return config.getOutputFilename (getTargetSuffix(), true, type);
        }

        String getOutputFilePath (const MSVCBuildConfiguration& config) const
        {
            return getOwner().getOutDirFile (config, getBinaryNameWithSuffix (config));
        }

        StringArray getLibrarySearchPaths (const MSVCBuildConfiguration& config) const
        {
            auto librarySearchPaths = config.getLibrarySearchPaths();

            if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
                if (auto* shared = getOwner().getSharedCodeTarget())
                    librarySearchPaths.add (shared->getExpandedConfigTargetPath (config));

            return librarySearchPaths;
        }

        /*  Libraries specified in the Projucer don't get escaped automatically.
            To include a special character in the name of a library,
            you must use the appropriate escape code instead.
            Module and shared code library names are not preprocessed.
            Special characters in the names of these libraries will be toEscape
            as appropriate.
        */
        StringArray getExternalLibraries (const MSVCBuildConfiguration& config, const StringArray& otherLibs) const
        {
            auto result = otherLibs;

            for (auto& i : result)
                i = getOwner().replacePreprocessorTokens (config, i).trim();

            result.addArray (msBuildEscape (getOwner().getModuleLibs()));

            if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
                if (auto* shared = getOwner().getSharedCodeTarget())
                    result.add (msBuildEscape (shared->getBinaryNameWithSuffix (config)));

            return result;
        }

        String getModuleDefinitions (const MSVCBuildConfiguration& config) const
        {
            auto moduleDefinitions = config.config [Ids::msvcModuleDefinitionFile].toString();

            if (moduleDefinitions.isNotEmpty())
                return moduleDefinitions;

            return {};
        }

        File getVCProjFile() const                                   { return getOwner().getProjectFile (getProjectFileSuffix(), getName()); }
        File getVCProjFiltersFile() const                            { return getOwner().getProjectFile (getFiltersFileSuffix(), getName()); }

        String createRebasedPath (const build_tools::RelativePath& path) const { return getOwner().createRebasedPath (path); }

        void addWindowsTargetPlatformToConfig (XmlElement& e) const
        {
            auto target = owner.getWindowsTargetPlatformVersion();

            if (target == "Latest")
            {
                auto* child = e.createNewChildElement ("WindowsTargetPlatformVersion");

                child->setAttribute ("Condition", "'$(WindowsTargetPlatformVersion)' == ''");
                child->addTextElement ("$([Microsoft.Build.Utilities.ToolLocationHelper]::GetLatestSDKTargetPlatformVersion('Windows', '10.0'))");
            }
            else
            {
                e.createNewChildElement ("WindowsTargetPlatformVersion")->addTextElement (target);
            }
        }

    protected:
        StringArray getAaxBundleStructure (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            const auto dllName = config.getOutputFilename (".aaxplugin", false, type);
            return { dllName, "Contents", getArchitectureValueString (arch), dllName };
        }

        StringArray getVst3BundleStructure (const MSVCBuildConfiguration& config, Architecture arch) const
        {
            // These suffixes are defined in the VST3 SDK docs
            const auto suffix = std::invoke ([&]() -> String
            {
                switch (arch)
                {
                    case Architecture::win32:    return "x86";
                    case Architecture::win64:    return "x86_64";
                    case Architecture::arm64:    return "arm64";
                    case Architecture::arm64ec:  return "arm64ec";
                }

                jassertfalse;
                return {};
            });

            const auto dllName = config.getOutputFilename (".vst3", false, type);
            return { dllName, "Contents", suffix + "-win", dllName };
        }

        const MSVCProjectExporterBase& owner;
        String projectGuid;
    };

    //==============================================================================
    bool usesMMFiles() const override                        { return false; }
    bool canCopeWithDuplicateFiles() override                { return false; }
    bool supportsUserDefinedConfigurations() const override  { return true; }

    bool isXcode() const override                            { return false; }
    bool isVisualStudio() const override                     { return true; }
    bool isMakefile() const override                         { return false; }
    bool isAndroidStudio() const override                    { return false; }

    bool isAndroid() const override                          { return false; }
    bool isWindows() const override                          { return true; }
    bool isLinux() const override                            { return false; }
    bool isOSX() const override                              { return false; }
    bool isiOS() const override                              { return false; }

    bool supportsPrecompiledHeaders() const override         { return true; }

    String getNewLineString() const override                 { return "\r\n"; }

    bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
    {
        using Target = build_tools::ProjectType::Target;

        switch (type)
        {
        case Target::StandalonePlugIn:
        case Target::GUIApp:
        case Target::ConsoleApp:
        case Target::StaticLibrary:
        case Target::SharedCodeTarget:
        case Target::AggregateTarget:
        case Target::VSTPlugIn:
        case Target::VST3PlugIn:
        case Target::VST3Helper:
        case Target::AAXPlugIn:
        case Target::UnityPlugIn:
        case Target::LV2PlugIn:
        case Target::LV2Helper:
        case Target::DynamicLibrary:
            return true;
        case Target::AudioUnitPlugIn:
        case Target::AudioUnitv3PlugIn:
        case Target::unspecified:
        default:
            break;
        }

        return false;
    }

    //==============================================================================
    build_tools::RelativePath getManifestPath() const
    {
        auto path = manifestFileValue.get().toString();

        return path.isEmpty() ? build_tools::RelativePath()
                              : build_tools::RelativePath (path, build_tools::RelativePath::projectFolder);
    }

    //==============================================================================
    bool launchProject() override
    {
       #if JUCE_WINDOWS
        // Don't launch if already open
        const auto foundDBFiles = getSLNFile().getSiblingFile (".vs").findChildFiles (File::findFiles, true, "*.opendb", File::FollowSymlinks::no);

        if (! foundDBFiles.isEmpty())
            return false;

        return getSLNFile().startAsProcess();
       #else
        return false;
       #endif
    }

    bool canLaunchProject() override
    {
       #if JUCE_WINDOWS
        return true;
       #else
        return false;
       #endif
    }

    void createExporterProperties (PropertyListBuilder& props) override
    {
        props.add (new TextPropertyComponent (manifestFileValue, "Manifest file", 8192, false),
            "Path to a manifest input file which should be linked into your binary (path is relative to jucer file).");

        props.add (new ChoicePropertyComponent (IPPLibraryValue, "(deprecated) Use IPP Library",
                                                { "No",  "Yes (Default Linking)",  "Multi-Threaded Static Library", "Single-Threaded Static Library", "Multi-Threaded DLL", "Single-Threaded DLL" },
                                                { var(), "true",                   "Parallel_Static",               "Sequential",                     "Parallel_Dynamic",   "Sequential_Dynamic" }),
                   "This option is deprecated, use the \"Use IPP Library (oneAPI)\" option instead. "
                   "Enable this to use Intel's Integrated Performance Primitives library, if you have an older version that was not supplied in the oneAPI toolkit.");

        props.add (new ChoicePropertyComponent (IPP1ALibraryValue, "Use IPP Library (oneAPI)",
                                                { "No",  "Yes (Default Linking)",  "Static Library",     "Dynamic Library" },
                                                { var(), "true",                   "Static_Library",     "Dynamic_Library" }),
                   "Enable this to use Intel's Integrated Performance Primitives library, supplied as part of the oneAPI toolkit.");

        props.add (new ChoicePropertyComponent (MKL1ALibraryValue, "Use MKL Library (oneAPI)",
                                                { "No",  "Parallel", "Sequential", "Cluster" },
                                                { var(), "Parallel", "Sequential", "Cluster" }),
                   "Enable this to use Intel's MKL library, supplied as part of the oneAPI toolkit.");

        {
            auto isWindows10SDK = getVisualStudioVersion() > 14;

            props.add (new TextPropertyComponent (targetPlatformVersion, "Windows Target Platform", 20, false),
                       String ("Specifies the version of the Windows SDK that will be used when building this project. ")
                       + (isWindows10SDK ? "Leave this field empty to use the latest Windows 10 SDK installed on the build machine."
                                         : "The default value for this exporter is " + getDefaultWindowsTargetPlatformVersion()));
        }
    }

    enum OptimisationLevel
    {
        optimisationOff = 1,
        optimiseMinSize = 2,
        optimiseFull = 3,
        optimiseMaxSpeed = 4
    };

    //==============================================================================
    void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType& type) override
    {
        msvcExtraPreprocessorDefs.set ("_CRT_SECURE_NO_WARNINGS", "");

        if (type.isCommandLineApp())
            msvcExtraPreprocessorDefs.set ("_CONSOLE", "");

        callForAllSupportedTargets ([this] (build_tools::ProjectType::Target::Type targetType)
                                    {
                                        if (targetType != build_tools::ProjectType::Target::AggregateTarget)
                                            targets.add (new MSVCTarget (targetType, *this));
                                    });

        // If you hit this assert, you tried to generate a project for an exporter
        // that does not support any of your targets!
        jassert (targets.size() > 0);
    }

    const MSVCTarget* getSharedCodeTarget() const
    {
        for (auto target : targets)
            if (target->type == build_tools::ProjectType::Target::SharedCodeTarget)
                return target;

        return nullptr;
    }

    bool hasTarget (build_tools::ProjectType::Target::Type type) const
    {
        for (auto target : targets)
            if (target->type == type)
                return true;

        return false;
    }

    static void createRCFile (const Project& p, const File& iconFile, const File& rcFile)
    {
        build_tools::ResourceRcOptions resourceRc;
        resourceRc.version = p.getVersionString();
        resourceRc.companyName = p.getCompanyNameString();
        resourceRc.companyCopyright = p.getCompanyCopyrightString();
        resourceRc.projectName = p.getProjectNameString();
        resourceRc.icon = iconFile;

        resourceRc.write (rcFile);
    }

private:
    //==============================================================================
    String createRebasedPath (const build_tools::RelativePath& path) const
    {
        auto rebasedPath = rebaseFromProjectFolderToBuildTarget (path).toWindowsStyle();

        return getVisualStudioVersion() < 10  // (VS10 automatically adds escape characters to the quotes for this definition)
                                          ? CppTokeniserFunctions::addEscapeChars (rebasedPath.quoted())
                                          : CppTokeniserFunctions::addEscapeChars (rebasedPath).quoted();
    }

protected:
    //==============================================================================
    mutable File rcFile, iconFile, packagesConfigFile;
    OwnedArray<MSVCTarget> targets;

    ValueTreePropertyWithDefault IPPLibraryValue,
                                 IPP1ALibraryValue,
                                 MKL1ALibraryValue,
                                 platformToolsetValue,
                                 targetPlatformVersion,
                                 manifestFileValue;

    String getProjectFileBaseName (const String& target) const
    {
        const auto filename = project.getProjectFilenameRootString();

        return filename + (target.isNotEmpty()
                           ? (String ("_") + target.removeCharacters (" "))
                           : "");
    }

    File getProjectFile (const String& extension, const String& target) const
    {
        const auto filename = getProjectFileBaseName (target);

        return getTargetFolder().getChildFile (filename).withFileExtension (extension);
    }

    File getSLNFile() const     { return getProjectFile (".sln", String()); }

    static String prependIfNotAbsolute (const String& file, const char* prefix)
    {
        if (File::isAbsolutePath (file) || file.startsWithChar ('$'))
            prefix = "";

        return prefix + build_tools::windowsStylePath (file);
    }

    String getIntDirFile (const BuildConfiguration& config, const String& file) const  { return prependIfNotAbsolute (replacePreprocessorTokens (config, file), "$(IntDir)\\"); }
    String getOutDirFile (const BuildConfiguration& config, const String& file) const  { return prependIfNotAbsolute (replacePreprocessorTokens (config, file), "$(OutDir)\\"); }

    BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
    {
        return *new MSVCBuildConfiguration (project, v, *this);
    }

    StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
    {
        auto searchPaths = extraSearchPaths;
        searchPaths.addArray (config.getHeaderSearchPaths());
        return getCleanedStringArray (searchPaths);
    }

    String getTargetGuid (MSVCTarget::Type type) const
    {
        for (auto* target : targets)
            if (target != nullptr && target->type == type)
                return target->getProjectGuid();

        return {};
    }

    //==============================================================================
    void writeProjectDependencies (OutputStream& out) const
    {
        const auto sharedCodeGuid = getTargetGuid (MSVCTarget::SharedCodeTarget);
        const auto lv2HelperGuid  = getTargetGuid (MSVCTarget::LV2Helper);
        const auto vst3HelperGuid = getTargetGuid (MSVCTarget::VST3Helper);

        for (int addingOtherTargets = 0; addingOtherTargets < (sharedCodeGuid.isNotEmpty() ? 2 : 1); ++addingOtherTargets)
        {
            for (int i = 0; i < targets.size(); ++i)
            {
                if (auto* target = targets[i])
                {
                    if (sharedCodeGuid.isEmpty() || (addingOtherTargets != 0) == (target->type != MSVCTarget::StandalonePlugIn))
                    {
                        out << "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"" << projectName << " - "
                            << target->getName() << "\", \""
                            << target->getVCProjFile().getFileName() << "\", \"" << target->getProjectGuid() << '"' << newLine;

                        if (sharedCodeGuid.isNotEmpty()
                            && target->type != MSVCTarget::SharedCodeTarget
                            && target->type != MSVCTarget::LV2Helper
                            && target->type != MSVCTarget::VST3Helper)
                        {
                            out << "\tProjectSection(ProjectDependencies) = postProject" << newLine
                                << "\t\t" << sharedCodeGuid << " = " << sharedCodeGuid << newLine;

                            if (target->type == MSVCTarget::LV2PlugIn && lv2HelperGuid.isNotEmpty())
                                out << "\t\t" << lv2HelperGuid << " = " << lv2HelperGuid << newLine;

                            if (target->type == MSVCTarget::VST3PlugIn && vst3HelperGuid.isNotEmpty())
                                out << "\t\t" << vst3HelperGuid << " = " << vst3HelperGuid << newLine;

                            out << "\tEndProjectSection" << newLine;
                        }

                        out << "EndProject" << newLine;
                    }
                }
            }
        }
    }

    void writeSolutionFile (OutputStream& out, const String& versionString, String commentString) const
    {
        const unsigned char bomBytes[] { CharPointer_UTF8::byteOrderMark1,
                                         CharPointer_UTF8::byteOrderMark2,
                                         CharPointer_UTF8::byteOrderMark3 };

        for (const auto& byte : bomBytes)
            out.writeByte ((char) byte);

        if (commentString.isNotEmpty())
            commentString += newLine;

        out << newLine
            << "Microsoft Visual Studio Solution File, Format Version " << versionString << newLine
            << commentString << newLine;

        writeProjectDependencies (out);

        out << "Global" << newLine
            << "\tGlobalSection(SolutionConfigurationPlatforms) = preSolution" << newLine;

        for (ConstConfigIterator i (*this); i.next();)
        {
            auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

            for (const auto& arch : config.getArchitectures())
            {
                auto configName = config.createMSVCConfigName (arch);
                out << "\t\t" << configName << " = " << configName << newLine;
            }
        }

        out << "\tEndGlobalSection" << newLine
            << "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution" << newLine;

        const auto allArchitectures = getAllActiveArchitectures();

        for (auto& target : targets)
        {
            for (ConstConfigIterator i (*this); i.next();)
            {
                auto& config = *static_cast<const MSVCBuildConfiguration*> (&*i);

                // Add a configuration for all projects but only mark the desired to be built.
                // We have to do this as VS will automatically add the entry anyway.
                for (const auto& arch : allArchitectures)
                {
                    auto configName = config.createMSVCConfigName (arch);

                    out << "\t\t" << target->getProjectGuid() << "." << configName << "." << "ActiveCfg" << " = " << configName << newLine;

                    const auto shouldBuild = config.shouldBuildTarget (target->type, arch) && config.getArchitectures().contains (arch);

                    if (shouldBuild)
                        out << "\t\t" << target->getProjectGuid() << "." << configName << "." << "Build.0" << " = " << configName << newLine;
                }
            }
        }

        out << "\tEndGlobalSection" << newLine
            << "\tGlobalSection(SolutionProperties) = preSolution" << newLine
            << "\t\tHideSolutionNode = FALSE" << newLine
            << "\tEndGlobalSection" << newLine;

        out << "EndGlobal" << newLine;
    }

    //==============================================================================
    bool hasResourceFile() const
    {
        return ! projectType.isStaticLibrary();
    }

    void createResourcesAndIcon() const
    {
        if (hasResourceFile())
        {
            iconFile = getTargetFolder().getChildFile ("icon.ico");
            build_tools::writeWinIcon (getIcons(), iconFile);
            rcFile = getTargetFolder().getChildFile ("resources.rc");
            createRCFile (project, iconFile, rcFile);
        }
    }

    bool shouldAddWebView2Package() const
    {
        return project.getEnabledModules().isModuleEnabled ("juce_gui_extra")
              && (   project.isConfigFlagEnabled ("JUCE_USE_WIN_WEBVIEW2", false)
                  || project.isConfigFlagEnabled ("JUCE_USE_WIN_WEBVIEW2_WITH_STATIC_LINKING", false));
    }

    bool shouldLinkWebView2Statically() const
    {
        return project.getEnabledModules().isModuleEnabled ("juce_gui_extra")
               && project.isConfigFlagEnabled ("JUCE_USE_WIN_WEBVIEW2_WITH_STATIC_LINKING", false);
    }

    static String getWebView2PackageName()     { return "Microsoft.Web.WebView2"; }
    static String getWebView2PackageVersion()  { return "1.0.1901.177"; }

    void createPackagesConfigFile() const
    {
        if (shouldAddWebView2Package())
        {
            packagesConfigFile = getTargetFolder().getChildFile ("packages.config");

            build_tools::writeStreamToFile (packagesConfigFile, [] (MemoryOutputStream& mo)
            {
                mo.setNewLineString ("\r\n");

                mo << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"                   << newLine
                   << "<packages>"                                                   << newLine
                   << "\t" << "<package id=" << getWebView2PackageName().quoted()
                           << " version="    << getWebView2PackageVersion().quoted()
                           << " />"                                                  << newLine
                   << "</packages>"                                                  << newLine;
            });
        }
    }

    static String prependDot (const String& filename)
    {
        return build_tools::isAbsolutePath (filename) ? filename
                                                      : (".\\" + filename);
    }

    static bool shouldAddBigobjFlag (const build_tools::RelativePath& path)
    {
        const auto name = path.getFileNameWithoutExtension();

        return name.equalsIgnoreCase ("include_juce_gui_basics")
            || name.equalsIgnoreCase ("include_juce_audio_processors")
            || name.equalsIgnoreCase ("include_juce_core")
            || name.equalsIgnoreCase ("include_juce_graphics");
    }

    StringArray getModuleLibs() const
    {
        StringArray result;

        for (auto& lib : windowsLibs)
            result.add (lib + ".lib");

        return result;
    }

    JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterBase)
};

//==============================================================================
class MSVCProjectExporterVC2019 final : public MSVCProjectExporterBase
{
public:
    MSVCProjectExporterVC2019 (Project& p, const ValueTree& t)
        : MSVCProjectExporterBase (p, t, getTargetFolderName())
    {
        name = getDisplayName();

        targetPlatformVersion.setDefault (defaultTargetPlatform);
        platformToolsetValue.setDefault (defaultToolset);
    }

    static String getDisplayName()        { return "Visual Studio 2019"; }
    static String getValueTreeTypeName()  { return "VS2019"; }
    static String getTargetFolderName()   { return "VisualStudio2019"; }

    Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }

    int getVisualStudioVersion() const override                      { return 16; }
    String getSolutionComment() const override                       { return "# Visual Studio Version 16"; }
    String getToolsVersion() const override                          { return "16.0"; }
    String getDefaultToolset() const override                        { return defaultToolset; }
    String getDefaultWindowsTargetPlatformVersion() const override   { return defaultTargetPlatform; }

    static MSVCProjectExporterVC2019* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
    {
        if (settingsToUse.hasType (getValueTreeTypeName()))
            return new MSVCProjectExporterVC2019 (projectToUse, settingsToUse);

        return nullptr;
    }

    void createExporterProperties (PropertyListBuilder& props) override
    {
        addToolsetProperty (props, { "v140", "v140_xp", "v141", "v141_xp", "v142", "ClangCL" });
        MSVCProjectExporterBase::createExporterProperties (props);
    }

private:
    const String defaultToolset { "v142" }, defaultTargetPlatform { "10.0" };

    JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterVC2019)
};

//==============================================================================
class MSVCProjectExporterVC2022 final : public MSVCProjectExporterBase
{
public:
    MSVCProjectExporterVC2022 (Project& p, const ValueTree& t)
        : MSVCProjectExporterBase (p, t, getTargetFolderName())
    {
        name = getDisplayName();

        targetPlatformVersion.setDefault (defaultTargetPlatform);
        platformToolsetValue.setDefault (defaultToolset);
    }

    static String getDisplayName()        { return "Visual Studio 2022"; }
    static String getValueTreeTypeName()  { return "VS2022"; }
    static String getTargetFolderName()   { return "VisualStudio2022"; }

    Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }

    int getVisualStudioVersion() const override                      { return 17; }
    String getSolutionComment() const override                       { return "# Visual Studio Version 17"; }
    String getToolsVersion() const override                          { return "17.0"; }
    String getDefaultToolset() const override                        { return defaultToolset; }
    String getDefaultWindowsTargetPlatformVersion() const override   { return defaultTargetPlatform; }

    static MSVCProjectExporterVC2022* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
    {
        if (settingsToUse.hasType (getValueTreeTypeName()))
            return new MSVCProjectExporterVC2022 (projectToUse, settingsToUse);

        return nullptr;
    }

    void createExporterProperties (PropertyListBuilder& props) override
    {
        addToolsetProperty (props, { "v140", "v140_xp", "v141", "v141_xp", "v142", "v143", "ClangCL" });
        MSVCProjectExporterBase::createExporterProperties (props);
    }

private:
    const String defaultToolset { "v143" }, defaultTargetPlatform { "10.0" };

    JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterVC2022)
};