File: jucer_ProjectExport_Xcode.h

package info (click to toggle)
juce 6.1.3~ds0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 61,612 kB
  • sloc: cpp: 431,694; java: 2,592; ansic: 797; xml: 259; sh: 164; python: 126; makefile: 64
file content (3584 lines) | stat: -rw-r--r-- 178,566 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
/*
  ==============================================================================

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

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 6 End-User License
   Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).

   End User License Agreement: www.juce.com/juce-6-licence
   Privacy Policy: www.juce.com/juce-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

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

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

#pragma once

#include "jucer_XcodeProjectParser.h"

//==============================================================================
constexpr auto* macOSArch_Default        = "default";
constexpr auto* macOSArch_Native         = "Native";
constexpr auto* macOSArch_32BitUniversal = "32BitUniversal";
constexpr auto* macOSArch_64BitUniversal = "64BitUniversal";
constexpr auto* macOSArch_64Bit          = "64BitIntel";

//==============================================================================
class XcodeProjectExporter  : public ProjectExporter
{
public:
    //==============================================================================
    static String getDisplayNameMac()        { return "Xcode (macOS)"; }
    static String getDisplayNameiOS()        { return "Xcode (iOS)"; }

    static String getTargetFolderNameMac()   { return "MacOSX"; }
    static String getTargetFolderNameiOS()   { return "iOS"; }

    static String getValueTreeTypeNameMac()  { return "XCODE_MAC"; }
    static String getValueTreeTypeNameiOS()  { return "XCODE_IPHONE"; }

    //==============================================================================
    XcodeProjectExporter (Project& p, const ValueTree& t, const bool isIOS)
        : ProjectExporter (p, t),
          xcodeCanUseDwarf (true),
          iOS (isIOS),
          applicationCategoryValue                     (settings, Ids::applicationCategory,                     getUndoManager(), ""),
          customPListValue                             (settings, Ids::customPList,                             getUndoManager()),
          pListPrefixHeaderValue                       (settings, Ids::pListPrefixHeader,                       getUndoManager()),
          pListPreprocessValue                         (settings, Ids::pListPreprocess,                         getUndoManager()),
          subprojectsValue                             (settings, Ids::xcodeSubprojects,                        getUndoManager()),
          validArchsValue                              (settings, Ids::xcodeValidArchs,                         getUndoManager(), getAllArchs(), ","),
          extraFrameworksValue                         (settings, Ids::extraFrameworks,                         getUndoManager()),
          frameworkSearchPathsValue                    (settings, Ids::frameworkSearchPaths,                    getUndoManager()),
          extraCustomFrameworksValue                   (settings, Ids::extraCustomFrameworks,                   getUndoManager()),
          embeddedFrameworksValue                      (settings, Ids::embeddedFrameworks,                      getUndoManager()),
          postbuildCommandValue                        (settings, Ids::postbuildCommand,                        getUndoManager()),
          prebuildCommandValue                         (settings, Ids::prebuildCommand,                         getUndoManager()),
          duplicateAppExResourcesFolderValue           (settings, Ids::duplicateAppExResourcesFolder,           getUndoManager(), true),
          iosDeviceFamilyValue                         (settings, Ids::iosDeviceFamily,                         getUndoManager(), "1,2"),
          iPhoneScreenOrientationValue                 (settings, Ids::iPhoneScreenOrientation,                 getUndoManager(), getDefaultScreenOrientations(), ","),
          iPadScreenOrientationValue                   (settings, Ids::iPadScreenOrientation,                   getUndoManager(), getDefaultScreenOrientations(), ","),
          customXcodeResourceFoldersValue              (settings, Ids::customXcodeResourceFolders,              getUndoManager()),
          customXcassetsFolderValue                    (settings, Ids::customXcassetsFolder,                    getUndoManager()),
          appSandboxValue                              (settings, Ids::appSandbox,                              getUndoManager()),
          appSandboxInheritanceValue                   (settings, Ids::appSandboxInheritance,                   getUndoManager()),
          appSandboxOptionsValue                       (settings, Ids::appSandboxOptions,                       getUndoManager(), Array<var>(), ","),
          hardenedRuntimeValue                         (settings, Ids::hardenedRuntime,                         getUndoManager()),
          hardenedRuntimeOptionsValue                  (settings, Ids::hardenedRuntimeOptions,                  getUndoManager(), Array<var>(), ","),
          microphonePermissionNeededValue              (settings, Ids::microphonePermissionNeeded,              getUndoManager()),
          microphonePermissionsTextValue               (settings, Ids::microphonePermissionsText,               getUndoManager(),
                                                        "This app requires audio input. If you do not have an audio interface connected it will use the built-in microphone."),
          cameraPermissionNeededValue                  (settings, Ids::cameraPermissionNeeded,                  getUndoManager()),
          cameraPermissionTextValue                    (settings, Ids::cameraPermissionText,                    getUndoManager(),
                                                        "This app requires access to the camera to function correctly."),
          bluetoothPermissionNeededValue               (settings, Ids::iosBluetoothPermissionNeeded,            getUndoManager()),
          bluetoothPermissionTextValue                 (settings, Ids::iosBluetoothPermissionText,              getUndoManager(),
                                                        "This app requires access to Bluetooth to function correctly."),
          sendAppleEventsPermissionNeededValue         (settings, Ids::sendAppleEventsPermissionNeeded, getUndoManager()),
          sendAppleEventsPermissionTextValue           (settings, Ids::sendAppleEventsPermissionText, getUndoManager(),
                                                        "This app requires the ability to send Apple events to function correctly."),
          uiFileSharingEnabledValue                    (settings, Ids::UIFileSharingEnabled,                    getUndoManager()),
          uiSupportsDocumentBrowserValue               (settings, Ids::UISupportsDocumentBrowser,               getUndoManager()),
          uiStatusBarHiddenValue                       (settings, Ids::UIStatusBarHidden,                       getUndoManager()),
          uiRequiresFullScreenValue                    (settings, Ids::UIRequiresFullScreen,                    getUndoManager(), true),
          documentExtensionsValue                      (settings, Ids::documentExtensions,                      getUndoManager()),
          iosInAppPurchasesValue                       (settings, Ids::iosInAppPurchases,                       getUndoManager()),
          iosContentSharingValue                       (settings, Ids::iosContentSharing,                       getUndoManager(), true),
          iosBackgroundAudioValue                      (settings, Ids::iosBackgroundAudio,                      getUndoManager()),
          iosBackgroundBleValue                        (settings, Ids::iosBackgroundBle,                        getUndoManager()),
          iosPushNotificationsValue                    (settings, Ids::iosPushNotifications,                    getUndoManager()),
          iosAppGroupsValue                            (settings, Ids::iosAppGroups,                            getUndoManager()),
          iCloudPermissionsValue                       (settings, Ids::iCloudPermissions,                       getUndoManager()),
          networkingMulticastValue                     (settings, Ids::networkingMulticast,                     getUndoManager()),
          iosDevelopmentTeamIDValue                    (settings, Ids::iosDevelopmentTeamID,                    getUndoManager()),
          iosAppGroupsIDValue                          (settings, Ids::iosAppGroupsId,                          getUndoManager()),
          keepCustomXcodeSchemesValue                  (settings, Ids::keepCustomXcodeSchemes,                  getUndoManager()),
          useHeaderMapValue                            (settings, Ids::useHeaderMap,                            getUndoManager()),
          customLaunchStoryboardValue                  (settings, Ids::customLaunchStoryboard,                  getUndoManager()),
          exporterBundleIdentifierValue                (settings, Ids::bundleIdentifier,                        getUndoManager()),
          suppressPlistResourceUsageValue              (settings, Ids::suppressPlistResourceUsage,              getUndoManager()),
          useLegacyBuildSystemValue                    (settings, Ids::useLegacyBuildSystem,                    getUndoManager()),
          buildNumber                                  (settings, Ids::buildNumber,                             getUndoManager())
    {
        if (iOS)
        {
            name = getDisplayNameiOS();
            targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderNameiOS());
        }
        else
        {
            name = getDisplayNameMac();
            targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderNameMac());
        }
    }

    static XcodeProjectExporter* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
    {
        if (settingsToUse.hasType (getValueTreeTypeNameMac()))  return new XcodeProjectExporter (projectToUse, settingsToUse, false);
        if (settingsToUse.hasType (getValueTreeTypeNameiOS()))  return new XcodeProjectExporter (projectToUse, settingsToUse, true);

        return nullptr;
    }

    //==============================================================================
    String getApplicationCategoryString() const             { return applicationCategoryValue.get(); }

    String getPListToMergeString() const                    { return customPListValue.get(); }
    String getPListPrefixHeaderString() const               { return pListPrefixHeaderValue.get(); }
    bool isPListPreprocessEnabled() const                   { return pListPreprocessValue.get(); }

    String getSubprojectsString() const                     { return subprojectsValue.get(); }

    String getExtraFrameworksString() const                 { return extraFrameworksValue.get(); }
    String getFrameworkSearchPathsString() const            { return frameworkSearchPathsValue.get(); }
    String getExtraCustomFrameworksString() const           { return extraCustomFrameworksValue.get(); }
    String getEmbeddedFrameworksString() const              { return embeddedFrameworksValue.get(); }

    String getPostBuildScript() const                       { return postbuildCommandValue.get(); }
    String getPreBuildScript() const                        { return prebuildCommandValue.get(); }

    bool shouldDuplicateAppExResourcesFolder() const        { return duplicateAppExResourcesFolderValue.get(); }

    String getDeviceFamilyString() const                    { return iosDeviceFamilyValue.get(); }

    Array<var> getDefaultScreenOrientations() const         { return { "UIInterfaceOrientationPortrait",
                                                                       "UIInterfaceOrientationLandscapeLeft",
                                                                       "UIInterfaceOrientationLandscapeRight" }; }

    Array<var> getAllArchs() const                          { return { "i386", "x86_64", "arm64", "arm64e"}; }

    Array<var> getiPhoneScreenOrientations() const          { return *iPhoneScreenOrientationValue.get().getArray(); }
    Array<var> getiPadScreenOrientations() const            { return *iPadScreenOrientationValue.get().getArray(); }

    String getCustomResourceFoldersString() const           { return customXcodeResourceFoldersValue.get().toString().replaceCharacters ("\r\n", "::"); }
    String getCustomXcassetsFolderString() const            { return customXcassetsFolderValue.get(); }
    String getCustomLaunchStoryboardString() const          { return customLaunchStoryboardValue.get(); }
    bool shouldAddStoryboardToProject() const               { return getCustomLaunchStoryboardString().isNotEmpty() || getCustomXcassetsFolderString().isEmpty(); }

    bool isHardenedRuntimeEnabled() const                   { return hardenedRuntimeValue.get(); }
    Array<var> getHardenedRuntimeOptions() const            { return *hardenedRuntimeOptionsValue.get().getArray(); }

    bool isAppSandboxEnabled() const                        { return appSandboxValue.get(); }
    bool isAppSandboxInhertianceEnabled() const             { return appSandboxInheritanceValue.get(); }
    Array<var> getAppSandboxOptions() const                 { return *appSandboxOptionsValue.get().getArray(); }

    Array<var> getValidArchs() const                        { return *validArchsValue.get().getArray(); }

    bool isMicrophonePermissionEnabled() const              { return microphonePermissionNeededValue.get(); }
    String getMicrophonePermissionsTextString() const       { return microphonePermissionsTextValue.get(); }

    bool isCameraPermissionEnabled() const                  { return cameraPermissionNeededValue.get(); }
    String getCameraPermissionTextString() const            { return cameraPermissionTextValue.get(); }

    bool isBluetoothPermissionEnabled() const               { return bluetoothPermissionNeededValue.get(); }
    String getBluetoothPermissionTextString() const         { return bluetoothPermissionTextValue.get(); }

    bool isSendAppleEventsPermissionEnabled() const         { return sendAppleEventsPermissionNeededValue.get(); }
    String getSendAppleEventsPermissionTextString() const   { return sendAppleEventsPermissionTextValue.get(); }

    bool isInAppPurchasesEnabled() const                    { return iosInAppPurchasesValue.get(); }
    bool isContentSharingEnabled() const                    { return iosContentSharingValue.get(); }
    bool isBackgroundAudioEnabled() const                   { return iosBackgroundAudioValue.get(); }
    bool isBackgroundBleEnabled() const                     { return iosBackgroundBleValue.get(); }
    bool isPushNotificationsEnabled() const                 { return iosPushNotificationsValue.get(); }
    bool isAppGroupsEnabled() const                         { return iosAppGroupsValue.get(); }
    bool isiCloudPermissionsEnabled() const                 { return iCloudPermissionsValue.get(); }
    bool isNetworkingMulticastEnabled() const               { return networkingMulticastValue.get(); }
    bool isFileSharingEnabled() const                       { return uiFileSharingEnabledValue.get(); }
    bool isDocumentBrowserEnabled() const                   { return uiSupportsDocumentBrowserValue.get(); }
    bool isStatusBarHidden() const                          { return uiStatusBarHiddenValue.get(); }
    bool requiresFullScreen() const                         { return uiRequiresFullScreenValue.get(); }

    bool getSuppressPlistResourceUsage() const              { return suppressPlistResourceUsageValue.get(); }

    bool shouldUseLegacyBuildSystem() const                 { return useLegacyBuildSystemValue.get(); }

    String getDocumentExtensionsString() const              { return documentExtensionsValue.get(); }

    bool shouldKeepCustomXcodeSchemes() const               { return keepCustomXcodeSchemesValue.get(); }

    String getDevelopmentTeamIDString() const               { return iosDevelopmentTeamIDValue.get(); }
    String getAppGroupIdString() const                      { return iosAppGroupsIDValue.get(); }

    String getBuildNumber() const
    {
        const auto buildNumberString = buildNumber.get().toString();
        return buildNumberString.isNotEmpty() ? buildNumberString : project.getVersionString();
    }

    String getDefaultLaunchStoryboardName() const           { return "LaunchScreen"; }

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

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

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

    Identifier getExporterIdentifier() const override
    {
        return iOS ? getValueTreeTypeNameiOS() : getValueTreeTypeNameMac();
    }

    bool supportsPrecompiledHeaders() const override        { return true; }

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

    bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
    {
        switch (type)
        {
            case build_tools::ProjectType::Target::AudioUnitv3PlugIn:
            case build_tools::ProjectType::Target::StandalonePlugIn:
            case build_tools::ProjectType::Target::GUIApp:
            case build_tools::ProjectType::Target::StaticLibrary:
            case build_tools::ProjectType::Target::DynamicLibrary:
            case build_tools::ProjectType::Target::SharedCodeTarget:
            case build_tools::ProjectType::Target::AggregateTarget:
                return true;
            case build_tools::ProjectType::Target::ConsoleApp:
            case build_tools::ProjectType::Target::VSTPlugIn:
            case build_tools::ProjectType::Target::VST3PlugIn:
            case build_tools::ProjectType::Target::AAXPlugIn:
            case build_tools::ProjectType::Target::RTASPlugIn:
            case build_tools::ProjectType::Target::AudioUnitPlugIn:
            case build_tools::ProjectType::Target::UnityPlugIn:
                return ! iOS;
            case build_tools::ProjectType::Target::unspecified:
            default:
                break;
        }

        return false;
    }

    void createExporterProperties (PropertyListBuilder& props) override
    {
        if (iOS)
        {
            props.add (new TextPropertyComponent (customXcassetsFolderValue, "Custom Xcassets Folder", 128, false),
                       "If this field is not empty, your Xcode project will use the custom xcassets folder specified here "
                       "for the app icons and launchimages, and will ignore the Icon files specified above. This will also prevent "
                       "a launch storyboard from being used.");

            props.add (new TextPropertyComponent (customLaunchStoryboardValue, "Custom Launch Storyboard", 256, false),
                       "If this field is not empty then the specified launch storyboard file will be added to the project as an Xcode "
                       "resource and will be used for the app's launch screen, otherwise a default blank launch storyboard will be used. "
                       "The file path should be relative to the project folder.");
        }

        props.add (new TextPropertyComponent (customXcodeResourceFoldersValue, "Custom Xcode Resource Folders", 8192, true),
                   "You can specify a list of custom resource folders here (separated by newlines or whitespace). "
                   "References to these folders will then be added to the Xcode resources. "
                   "This way you can specify them for OS X and iOS separately, and modify the content of the resource folders "
                   "without re-saving the Projucer project.");

        if (getProject().isAudioPluginProject())
            props.add (new ChoicePropertyComponent (duplicateAppExResourcesFolderValue, "Add Duplicate Resources Folder to App Extension"),
                       "Disable this to prevent the Projucer from creating a duplicate resources folder for AUv3 app extensions.");

        props.add (new TextPropertyComponent (buildNumber, "Build Number", 128, false),
                   "The current version of the project. Used to disambiguate different builds of the same project on App Store Connect. "
                   "If this field is empty, the project's version will be used as the build number. "
                   "For more details about the difference between the project version and build version, see developer.apple.com/library/archive/technotes/tn2420/_index.html");

        if (iOS)
        {
            props.add (new ChoicePropertyComponent (iosDeviceFamilyValue, "Device Family",
                                                    { "iPhone", "iPad", "Universal" },
                                                    { "1",      "2",    "1,2" }),
                       "The device family to target.");

            {
                StringArray orientationStrings { "Portrait", "Portrait Upside Down",
                                                 "Landscape Left", "Landscape Right" };

                Array<var> orientationVars { "UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown",
                                             "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight" };

                props.add (new MultiChoicePropertyComponent (iPhoneScreenOrientationValue, "iPhone Screen Orientation", orientationStrings, orientationVars),
                           "The screen orientations that this app should support on iPhones.");

                props.add (new MultiChoicePropertyComponent (iPadScreenOrientationValue, "iPad Screen Orientation", orientationStrings, orientationVars),
                           "The screen orientations that this app should support on iPads.");
            }

            props.add (new ChoicePropertyComponent (uiFileSharingEnabledValue, "File Sharing Enabled"),
                       "Enable this to expose your app's files to iTunes.");

            props.add (new ChoicePropertyComponent (uiSupportsDocumentBrowserValue, "Support Document Browser"),
                       "Enable this to allow the user to access your app documents from a native file chooser.");

            props.add (new ChoicePropertyComponent (uiStatusBarHiddenValue, "Status Bar Hidden"),
                       "Enable this to disable the status bar in your app.");

            props.add (new ChoicePropertyComponent (uiRequiresFullScreenValue, "Requires Full Screen"),
                       "Disable this to enable non-fullscreen views such as Slide Over or Split View in your app. "
                       "You will also need to enable all orientations.");
        }
        else if (projectType.isGUIApplication())
        {
            props.add (new TextPropertyComponent (documentExtensionsValue, "Document File Extensions", 128, false),
                       "A comma-separated list of file extensions for documents that your app can open. "
                       "Using a leading '.' is optional, and the extensions are not case-sensitive.");
        }

        props.add (new ChoicePropertyComponent (useLegacyBuildSystemValue, "Use Legacy Build System"),
                   "Enable this to use the deprecated \"Legacy Build System\" in Xcode 10 and above. "
                   "This may fix build issues that were introduced with the new build system in Xcode 10 and subsequently fixed in Xcode 10.2, "
                   "however the new build system is recommended for apps targeting Apple silicon.");

        if (isOSX())
        {
            std::vector<std::pair<String, String>> appCategories
            {
                { "None",                 "" },
                { "Business",             "business" },
                { "Developer Tools",      "developer-tools" },
                { "Education",            "education" },
                { "Entertainment",        "entertainment" },
                { "Finace",               "finance" },
                { "Games",                "games" },
                { "Games - Action",       "action-games" },
                { "Games - Adventure",    "adventure-games" },
                { "Games - Arcade",       "arcade-games" },
                { "Games - Board",        "board-games" },
                { "Games - Card",         "card-games" },
                { "Games - Casino",       "casino-games" },
                { "Games - Dice",         "dice-games" },
                { "Games - Educational",  "educational-games" },
                { "Games - Family",       "family-games" },
                { "Games - Kids",         "kids-games" },
                { "Games - Music",        "music-games" },
                { "Games - Puzzle",       "puzzle-games" },
                { "Games - Racing",       "racing-games" },
                { "Games - Role Playing", "role-playing-games" },
                { "Games - Simulation",   "simulation-games" },
                { "Games - Sports",       "sports-games" },
                { "Games - Strategy",     "strategy-games" },
                { "Games - Trivia",       "trivia-games" },
                { "Games - Word",         "word-games" },
                { "Graphics Design",      "graphics-design" },
                { "Healthcare & Fitness", "healthcare-fitness" },
                { "Lifestyle",            "lifestyle" },
                { "Medial",               "medical" },
                { "Music",                "music" },
                { "News",                 "news" },
                { "Photography",          "photography" },
                { "Productivity",         "productivity" },
                { "Reference",            "reference" },
                { "Social Networking",    "social-networking" },
                { "Sports",               "sports" },
                { "Travel",               "travel" },
                { "Utilities",            "utilities" },
                { "Video",                "video" },
                { "Weather" ,             "weather" }
            };

            StringArray appCategoryKeys;
            Array<var> appCategoryValues;

            for (auto& opt : appCategories)
            {
                appCategoryKeys.add (opt.first);

                if (opt.second.isNotEmpty())
                    appCategoryValues.add ("public.app-category." + opt.second);
                else
                    appCategoryValues.add ("");
            }

            props.add (new ChoicePropertyComponent (applicationCategoryValue,
                                                    "App Category",
                                                    appCategoryKeys,
                                                    appCategoryValues),
                       "The application category.");

            props.add (new MultiChoicePropertyComponent (validArchsValue, "Valid Architectures", getAllArchs(), getAllArchs()),
                       "The full set of architectures which this project may target. "
                       "Each configuration will build for the intersection of this property, and the per-configuration macOS Architecture property");

            props.add (new ChoicePropertyComponent (appSandboxValue, "Use App Sandbox"),
                       "Enable this to use the app sandbox.");

            props.add (new ChoicePropertyComponentWithEnablement (appSandboxInheritanceValue, appSandboxValue, "App Sandbox Inheritance"),
                       "If app sandbox is enabled, this setting will configure a child process to inherit the sandbox of its parent. "
                       "Note that if you enable this and have specified any other app sandbox entitlements below, the child process "
                       "will fail to launch.");

            std::vector<std::pair<String, String>> sandboxOptions
            {
                { "Network: Incoming Connections (Server)",         "network.server" },
                { "Network: Outgoing Connections (Client)",         "network.client" },

                { "Hardware: Camera",                               "device.camera" },
                { "Hardware: Microphone",                           "device.microphone" },
                { "Hardware: USB",                                  "device.usb" },
                { "Hardware: Printing",                             "print" },
                { "Hardware: Bluetooth",                            "device.bluetooth" },

                { "App Data: Contacts",                             "personal-information.addressbook" },
                { "App Data: Location",                             "personal-information.location" },
                { "App Data: Calendar",                             "personal-information.calendars" },

                { "File Access: User Selected File (Read Only)",    "files.user-selected.read-only" },
                { "File Access: User Selected File (Read/Write)",   "files.user-selected.read-write" },
                { "File Access: Downloads Folder (Read Only)",      "files.downloads.read-only" },
                { "File Access: Downloads Folder (Read/Write)",     "files.downloads.read-write" },
                { "File Access: Pictures Folder (Read Only)",       "files.pictures.read-only" },
                { "File Access: Pictures Folder (Read/Write)",      "files.pictures.read-write" },
                { "File Access: Music Folder (Read Only)",          "assets.music.read-only" },
                { "File Access: Music Folder (Read/Write)",         "assets.music.read-write" },
                { "File Access: Movies Folder (Read Only)",         "assets.movies.read-only" },
                { "File Access: Movies Folder (Read/Write)",        "assets.movies.read-write" },

                { "Temporary Exception: Audio Unit Hosting",                       "temporary-exception.audio-unit-host" },
                { "Temporary Exception: Global Mach Service",                      "temporary-exception.mach-lookup.global-name" },
                { "Temporary Exception: Global Mach Service Dynamic Registration", "temporary-exception.mach-register.global-name" },
                { "Temporary Exception: Home Directory File Access (Read Only)",   "temporary-exception.files.home-relative-path.read-only" },
                { "Temporary Exception: Home Directory File Access (Read/Write)",  "temporary-exception.files.home-relative-path.read-write" },
                { "Temporary Exception: Absolute Path File Access (Read Only)",    "temporary-exception.files.absolute-path.read-only" },
                { "Temporary Exception: Absolute Path File Access (Read/Write)",   "temporary-exception.files.absolute-path.read-write" },
                { "Temporary Exception: IOKit User Client Class",                  "temporary-exception.iokit-user-client-class" },
                { "Temporary Exception: Shared Preference Domain (Read Only)",     "temporary-exception.shared-preference.read-only" },
                { "Temporary Exception: Shared Preference Domain (Read/Write)",    "temporary-exception.shared-preference.read-write" }
            };

            StringArray sandboxKeys;
            Array<var> sanboxValues;

            for (auto& opt : sandboxOptions)
            {
                sandboxKeys.add (opt.first);
                sanboxValues.add ("com.apple.security." + opt.second);
            }

            props.add (new MultiChoicePropertyComponentWithEnablement (appSandboxOptionsValue,
                                                                       appSandboxValue,
                                                                       "App Sandbox Options",
                                                                       sandboxKeys,
                                                                       sanboxValues));

            props.add (new ChoicePropertyComponent (hardenedRuntimeValue, "Use Hardened Runtime"),
                       "Enable this to use the hardened runtime required for app notarization.");

            std::vector<std::pair<String, String>> hardeningOptions
            {
                { "Runtime Exceptions: Allow Execution of JIT-compiled Code", "cs.allow-jit" },
                { "Runtime Exceptions: Allow Unsigned Executable Memory",     "cs.allow-unsigned-executable-memory" },
                { "Runtime Exceptions: Allow DYLD Environment Variables",     "cs.allow-dyld-environment-variables" },
                { "Runtime Exceptions: Disable Library Validation",           "cs.disable-library-validation" },
                { "Runtime Exceptions: Disable Executable Memory Protection", "cs.disable-executable-page-protection" },
                { "Runtime Exceptions: Debugging Tool",                       "cs.debugger" },

                { "Resource Access: Audio Input",                             "device.audio-input" },
                { "Resource Access: Camera",                                  "device.camera" },
                { "Resource Access: Location",                                "personal-information.location" },
                { "Resource Access: Address Book",                            "personal-information.addressbook" },
                { "Resource Access: Calendar",                                "personal-information.calendars" },
                { "Resource Access: Photos Library",                          "personal-information.photos-library" },
                { "Resource Access: Apple Events",                            "automation.apple-events" }
            };

            StringArray hardeningKeys;
            Array<var> hardeningValues;

            for (auto& opt : hardeningOptions)
            {
                hardeningKeys.add (opt.first);
                hardeningValues.add ("com.apple.security." + opt.second);
            }

            props.add (new MultiChoicePropertyComponentWithEnablement (hardenedRuntimeOptionsValue,
                                                                       hardenedRuntimeValue,
                                                                       "Hardened Runtime Options",
                                                                       hardeningKeys,
                                                                       hardeningValues));
        }

        props.add (new ChoicePropertyComponent (microphonePermissionNeededValue, "Microphone Access"),
                   "Enable this to allow your app to use the microphone. "
                   "The user of your app will be prompted to grant microphone access permissions.");

        props.add (new TextPropertyComponentWithEnablement (microphonePermissionsTextValue, microphonePermissionNeededValue,
                                                            "Microphone Access Text", 1024, false),
                   "A short description of why your app requires microphone access.");

        props.add (new ChoicePropertyComponent (cameraPermissionNeededValue, "Camera Access"),
                   "Enable this to allow your app to use the camera. "
                   "The user of your app will be prompted to grant camera access permissions.");

        props.add (new TextPropertyComponentWithEnablement (cameraPermissionTextValue, cameraPermissionNeededValue,
                                                            "Camera Access Text", 1024, false),
                   "A short description of why your app requires camera access.");

        props.add (new ChoicePropertyComponent (bluetoothPermissionNeededValue, "Bluetooth Access"),
                   "Enable this to allow your app to use Bluetooth on iOS 13.0 and above, and macOS 11.0 and above. "
                   "The user of your app will be prompted to grant Bluetooth access permissions.");

        props.add (new TextPropertyComponentWithEnablement (bluetoothPermissionTextValue, bluetoothPermissionNeededValue,
                                                            "Bluetooth Access Text", 1024, false),
                   "A short description of why your app requires Bluetooth access.");

        if (! iOS)
        {
            props.add (new ChoicePropertyComponent (sendAppleEventsPermissionNeededValue, "Send Apple Events"),
                       "Enable this to allow your app to send Apple events. "
                       "The user of your app will be prompted to grant permissions to control other apps.");

            props.add (new TextPropertyComponentWithEnablement (sendAppleEventsPermissionTextValue, sendAppleEventsPermissionNeededValue,
                                                                "Send Apple Events Text", 1024, false),
                       "A short description of why your app requires the ability to send Apple events.");
        }

        props.add (new ChoicePropertyComponent (iosInAppPurchasesValue, "In-App Purchases Capability"),
                   "Enable this to grant your app the capability for in-app purchases. "
                   "This option requires that you specify a valid Development Team ID.");

        if (iOS)
        {
            props.add (new ChoicePropertyComponent (iosContentSharingValue, "Content Sharing"),
                       "Enable this to allow your app to share content with other apps.");

            props.add (new ChoicePropertyComponent (iosBackgroundAudioValue, "Audio Background Capability"),
                       "Enable this to grant your app the capability to access audio when in background mode. "
                       "This permission is required if your app creates a MIDI input or output device.");

            props.add (new ChoicePropertyComponent (iosBackgroundBleValue, "Bluetooth MIDI Background Capability"),
                       "Enable this to grant your app the capability to connect to Bluetooth LE devices when in background mode.");

            props.add (new ChoicePropertyComponent (iosAppGroupsValue, "App Groups Capability"),
                       "Enable this to grant your app the capability to share resources between apps using the same app group ID.");

            props.add (new ChoicePropertyComponent (iCloudPermissionsValue, "iCloud Permissions"),
                       "Enable this to grant your app the capability to use native file load/save browser windows on iOS.");

        }

        props.add (new ChoicePropertyComponent (networkingMulticastValue, "Networking Multicast Capability"),
                   "Your app must have this entitlement to send or receive IP multicast or broadcast. "
                   "You will also need permission from Apple to use this entitlement.");

        props.add (new ChoicePropertyComponent (iosPushNotificationsValue, "Push Notifications Capability"),
                   "Enable this to grant your app the capability to receive push notifications.");

        props.add (new TextPropertyComponent (customPListValue, "Custom PList", 8192, true),
                   "You can paste the contents of an XML PList file in here, and the settings that it contains will override any "
                   "settings that the Projucer creates. BEWARE! When doing this, be careful to remove from the XML any "
                   "values that you DO want the Projucer to change!");

        props.add (new ChoicePropertyComponent (pListPreprocessValue, "PList Preprocess"),
                   "Enable this to preprocess PList file. This will allow you to set values to preprocessor defines,"
                   " for instance if you define: #define MY_FLAG 1 in a prefix header file (see PList prefix header), you can have"
                   " a key with MY_FLAG value and it will be replaced with 1.");

        props.add (new TextPropertyComponent (pListPrefixHeaderValue, "PList Prefix Header", 512, false),
                   "Header file containing definitions used in plist file (see PList Preprocess).");

        props.add (new ChoicePropertyComponent (suppressPlistResourceUsageValue, "Suppress AudioUnit Plist resourceUsage Key"),
                   "Suppress the resourceUsage key in the target's generated Plist. This is useful for AU"
                   " plugins that must access resources which cannot be declared in the resourceUsage block, such"
                   " as UNIX domain sockets. In particular, PACE-protected AU plugins may require this option to be enabled"
                   " in order for the plugin to load in GarageBand.");

        props.add (new TextPropertyComponent (extraFrameworksValue, "Extra System Frameworks", 2048, false),
                   "A comma-separated list of extra system frameworks that should be added to the build. "
                   "(Don't include the .framework extension in the name)"
                   " The frameworks are expected to be located in /System/Library/Frameworks");

        props.add (new TextPropertyComponent (frameworkSearchPathsValue, "Framework Search Paths", 8192, true),
                   "A set of paths to search for custom frameworks (one per line).");

        props.add (new TextPropertyComponent (extraCustomFrameworksValue, "Extra Custom Frameworks", 8192, true),
                   "Paths to custom frameworks that should be added to the build (one per line). "
                   "You will probably need to add an entry to the Framework Search Paths for each unique directory.");

        props.add (new TextPropertyComponent (embeddedFrameworksValue, "Embedded Frameworks", 8192, true),
                   "Paths to frameworks to be embedded with the app (one per line). "
                   "If you are adding a framework here then you do not need to specify it in Extra Custom Frameworks too. "
                   "You will probably need to add an entry to the Framework Search Paths for each unique directory.");

        props.add (new TextPropertyComponent (subprojectsValue, "Xcode Subprojects", 8192, true),
                   "Paths to Xcode projects that should be added to the build (one per line). "
                   "These can be absolute or relative to the build directory. "
                   "The names of the required build products can be specified after a colon, comma separated, "
                   "e.g. \"path/to/MySubProject.xcodeproj: MySubProject, OtherTarget\". "
                   "If no build products are specified, all build products associated with a subproject will be added.");

        props.add (new TextPropertyComponent (prebuildCommandValue, "Pre-Build Shell Script", 32768, true),
                   "Some shell-script that will be run before a build starts.");

        props.add (new TextPropertyComponent (postbuildCommandValue, "Post-Build Shell Script", 32768, true),
                   "Some shell-script that will be run after a build completes.");

        props.add (new TextPropertyComponent (exporterBundleIdentifierValue, "Exporter Bundle Identifier", 256, false),
                   "Use this to override the project bundle identifier for this exporter. "
                   "This is useful if you want to use different bundle identifiers for Mac and iOS exporters in the same project.");

        props.add (new TextPropertyComponent (iosDevelopmentTeamIDValue, "Development Team ID", 10, false),
                   "The Team ID to be used for setting up code-signing for your application. "
                   "This is a ten-character string (for example \"S7B6T5XJ2Q\") that can be found under the \"Organisational Unit\" "
                   "field of your developer certificate in Keychain Access or in the membership page of your account on developer.apple.com.");

        if (iOS)
            props.add (new TextPropertyComponentWithEnablement (iosAppGroupsIDValue, iosAppGroupsValue, "App Group ID", 256, false),
                       "The App Group ID to be used for allowing multiple apps to access a shared resource folder. Multiple IDs can be "
                       "added separated by a semicolon.");

        props.add (new ChoicePropertyComponent (keepCustomXcodeSchemesValue, "Keep Custom Xcode Schemes"),
                   "Enable this to keep any Xcode schemes you have created for debugging or running, e.g. to launch a plug-in in"
                   "various hosts. If disabled, all schemes are replaced by a default set.");

        props.add (new ChoicePropertyComponent (useHeaderMapValue, "USE_HEADERMAP"),
                   "Enable this to make Xcode search all the projects folders for include files. This means you can be lazy "
                   "and not bother using relative paths to include your headers, but it means your code won't be "
                   "compatible with other build systems");
    }

    bool launchProject() override
    {
       #if JUCE_MAC
        return getIDEProjectFile().startAsProcess();
       #else
        return false;
       #endif
    }

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

    File getIDEProjectFile() const override
    {
        return getProjectBundle();
    }

    //==============================================================================
    void create (const OwnedArray<LibraryModule>&) const override
    {
        for (auto& target : targets)
            if (target->shouldCreatePList())
                target->infoPlistFile = getTargetFolder().getChildFile (target->getInfoPlistName());

        menuNibFile = getTargetFolder().getChildFile ("RecentFilesMenuTemplate.nib");

        createIconFile();

        auto projectBundle = getProjectBundle();
        createDirectoryOrThrow (projectBundle);

        createObjects();

        build_tools::writeStreamToFile (projectBundle.getChildFile ("project.pbxproj"),
                                        [this] (MemoryOutputStream& mo) { writeProjectFile (mo); });

        writeInfoPlistFiles();
        writeWorkspaceSettings();

        // Deleting the .rsrc files can be needed to force Xcode to update the version number.
        deleteRsrcFiles (getTargetFolder().getChildFile ("build"));
    }

    //==============================================================================
    void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType&) override
    {
        callForAllSupportedTargets ([this] (build_tools::ProjectType::Target::Type targetType)
                                    {
                                        targets.insert (targetType == build_tools::ProjectType::Target::AggregateTarget ? 0 : -1,
                                                        new XcodeTarget (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);
    }

    void updateDeprecatedSettings() override
    {
        if (iOS)
            updateOldOrientationSettings();
    }

    void updateDeprecatedSettingsInteractively() override
    {
        if (hasInvalidPostBuildScript())
        {
            String alertWindowText = iOS ? "Your Xcode (iOS) Exporter settings use an invalid post-build script. Click 'Update' to remove it."
                                         : "Your Xcode (macOS) Exporter settings use a pre-JUCE 4.2 post-build script to move the plug-in binaries to their plug-in install folders.\n\n"
                                           "Since JUCE 4.2, this is instead done using \"AU/VST/VST2/AAX/RTAS Binary Location\" in the Xcode (OS X) configuration settings.\n\n"
                                           "Click 'Update' to remove the script (otherwise your plug-in may not compile correctly).";

            if (AlertWindow::showOkCancelBox (MessageBoxIconType::WarningIcon,
                                              "Project settings: " + project.getDocumentTitle(),
                                              alertWindowText, "Update", "Cancel", nullptr, nullptr))
                postbuildCommandValue.resetToDefault();
        }
    }

    bool hasInvalidPostBuildScript() const
    {
        // check whether the script is identical to the old one that the Introjucer used to auto-generate
        return (MD5 (getPostBuildScript().toUTF8()).toHexString() == "265ac212a7e734c5bbd6150e1eae18a1");
    }

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

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

        rtasPathValueWrapper.init ({ settings, Ids::rtasFolder, nullptr },
                                   getAppSettings().getStoredPath (Ids::rtasPath, TargetOS::osx), TargetOS::osx);
    }

protected:
    //==============================================================================
    class XcodeBuildConfiguration  : public BuildConfiguration,
                                     private ValueTree::Listener
    {
    public:
        XcodeBuildConfiguration (Project& p, const ValueTree& t, const bool isIOS, const ProjectExporter& e)
            : BuildConfiguration (p, t, e),
              iOS (isIOS),
              macOSBaseSDK                 (config, Ids::macOSBaseSDK,                 getUndoManager()),
              macOSDeploymentTarget        (config, Ids::macOSDeploymentTarget,        getUndoManager(), "10.11"),
              macOSArchitecture            (config, Ids::osxArchitecture,              getUndoManager(), macOSArch_Default),
              iosBaseSDK                   (config, Ids::iosBaseSDK,                   getUndoManager()),
              iosDeploymentTarget          (config, Ids::iosDeploymentTarget,          getUndoManager(), "9.3"),
              customXcodeFlags             (config, Ids::customXcodeFlags,             getUndoManager()),
              plistPreprocessorDefinitions (config, Ids::plistPreprocessorDefinitions, getUndoManager()),
              codeSignIdentity             (config, Ids::codeSigningIdentity,          getUndoManager()),
              fastMathEnabled              (config, Ids::fastMath,                     getUndoManager()),
              stripLocalSymbolsEnabled     (config, Ids::stripLocalSymbols,            getUndoManager()),
              pluginBinaryCopyStepEnabled  (config, Ids::enablePluginBinaryCopyStep,   getUndoManager(), true),
              vstBinaryLocation            (config, Ids::vstBinaryLocation,            getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST/"),
              vst3BinaryLocation           (config, Ids::vst3BinaryLocation,           getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST3/"),
              auBinaryLocation             (config, Ids::auBinaryLocation,             getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/Components/"),
              rtasBinaryLocation           (config, Ids::rtasBinaryLocation,           getUndoManager(), "/Library/Application Support/Digidesign/Plug-Ins/"),
              aaxBinaryLocation            (config, Ids::aaxBinaryLocation,            getUndoManager(), "/Library/Application Support/Avid/Audio/Plug-Ins/"),
              unityPluginBinaryLocation    (config, Ids::unityPluginBinaryLocation,    getUndoManager())
        {
            updateOldPluginBinaryLocations();
            updateOldSDKDefaults();

            optimisationLevelValue.setDefault (isDebug() ? gccO0 : gccO3);

            config.addListener (this);
        }

        //==============================================================================
        void createConfigProperties (PropertyListBuilder& props) override
        {
            if (project.isAudioPluginProject())
                addXcodePluginInstallPathProperties (props);

            addRecommendedLLVMCompilerWarningsProperty (props);
            addGCCOptimisationProperty (props);

            const String sdkInfoString ("\nThis must be in the format major.minor and contain only the numeric version number. "
                                        "If this is left empty then the default will be used."
                                        "\nThe minimum supported version is ");

            if (iOS)
            {
                props.add (new TextPropertyComponent (iosBaseSDK, "iOS Base SDK", 8, false),
                           "The version of the iOS SDK to link against." + sdkInfoString + "9.3.");

                props.add (new TextPropertyComponent (iosDeploymentTarget, "iOS Deployment Target", 8, false),
                           "The minimum version of iOS to target." + sdkInfoString + "9.0.");
            }
            else
            {
                props.add (new TextPropertyComponent (macOSBaseSDK, "macOS Base SDK", 8, false),
                           "The version of the macOS SDK to link against." + sdkInfoString + "10.11.");

                props.add (new TextPropertyComponent (macOSDeploymentTarget, "macOS Deployment Target", 8, false),
                           "The minimum version of macOS to target." + sdkInfoString + "10.7.");

                props.add (new ChoicePropertyComponent (macOSArchitecture, "macOS Architecture",
                                                        { "Native architecture of build machine", "Standard 32-bit",        "Standard 32/64-bit",     "Standard 64-bit" },
                                                        { macOSArch_Native,                       macOSArch_32BitUniversal, macOSArch_64BitUniversal, macOSArch_64Bit }),
                           "The type of macOS binary that will be produced.");
            }

            props.add (new TextPropertyComponent (customXcodeFlags, "Custom Xcode Flags", 8192, true),
                       "A comma-separated list of custom Xcode setting flags which will be appended to the list of generated flags, "
                       "e.g. MACOSX_DEPLOYMENT_TARGET_i386 = 10.5");

            props.add (new TextPropertyComponent (plistPreprocessorDefinitions, "PList Preprocessor Definitions", 2048, true),
                       "Preprocessor definitions used during PList preprocessing (see PList Preprocess).");

            props.add (new TextPropertyComponent (codeSignIdentity, "Code-Signing Identity", 1024, false),
                       "The name of a code-signing identity for Xcode to apply.");

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

            props.add (new ChoicePropertyComponent (stripLocalSymbolsEnabled, "Strip Local Symbols"),
                       "Enable this to strip any locally defined symbols resulting in a smaller binary size. Enabling this "
                       "will also remove any function names from crash logs. Must be disabled for static library projects. "
                       "Note that disabling this will not necessarily generate full debug symbols. For release configs, "
                       "you will also need to add the following to the \"Custom Xcode Flags\" field: "
                       "GCC_GENERATE_DEBUGGING_SYMBOLS = YES, STRIP_INSTALLED_PRODUCT = NO, COPY_PHASE_STRIP = NO");
        }

        String getModuleLibraryArchName() const override
        {
            return "${CURRENT_ARCH}";
        }

        //==============================================================================
        String getMacOSArchitectureString() const               { return macOSArchitecture.get(); }
        String getPListPreprocessorDefinitionsString() const    { return plistPreprocessorDefinitions.get(); }

        bool isFastMathEnabled() const                          { return fastMathEnabled.get(); }

        bool isStripLocalSymbolsEnabled() const                 { return stripLocalSymbolsEnabled.get(); }

        String getCustomXcodeFlagsString() const                { return customXcodeFlags.get(); }

        String getMacOSBaseSDKString() const                    { return macOSBaseSDK.get(); }
        String getMacOSDeploymentTargetString() const           { return macOSDeploymentTarget.get(); }

        String getCodeSignIdentityString() const                { return codeSignIdentity.get(); }

        String getiOSBaseSDKString() const                      { return iosBaseSDK.get(); }
        String getiOSDeploymentTargetString() const             { return iosDeploymentTarget.get(); }

        bool isPluginBinaryCopyStepEnabled() const              { return pluginBinaryCopyStepEnabled.get(); }
        String getVSTBinaryLocationString() const               { return vstBinaryLocation.get(); }
        String getVST3BinaryLocationString() const              { return vst3BinaryLocation.get(); }
        String getAUBinaryLocationString() const                { return auBinaryLocation.get(); }
        String getRTASBinaryLocationString() const              { return rtasBinaryLocation.get();}
        String getAAXBinaryLocationString() const               { return aaxBinaryLocation.get();}
        String getUnityPluginBinaryLocationString() const       { return unityPluginBinaryLocation.get(); }

    private:
        //==============================================================================
        bool iOS;

        ValueWithDefault macOSBaseSDK, macOSDeploymentTarget, macOSArchitecture, iosBaseSDK, iosDeploymentTarget,
                         customXcodeFlags, plistPreprocessorDefinitions, codeSignIdentity,
                         fastMathEnabled, stripLocalSymbolsEnabled, pluginBinaryCopyStepEnabled,
                         vstBinaryLocation, vst3BinaryLocation, auBinaryLocation, rtasBinaryLocation,
                         aaxBinaryLocation, unityPluginBinaryLocation;

        //==============================================================================
        void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
        {
            const auto updateOldSDKSetting = [this] (const Identifier& oldProperty,
                                                     const String& sdkString,
                                                     const String& sdkSuffix)
            {
                if (sdkString.isEmpty())
                    config.removeProperty (oldProperty, nullptr);
                else
                    config.setProperty (oldProperty, sdkString + sdkSuffix, nullptr);
            };

            if (property == Ids::macOSBaseSDK)
                updateOldSDKSetting (Ids::osxSDK, macOSBaseSDK.get(), " SDK");
            else if (property == Ids::macOSDeploymentTarget)
                updateOldSDKSetting (Ids::osxCompatibility, macOSDeploymentTarget.get(), " SDK");
            else if (property == Ids::iosDeploymentTarget)
                updateOldSDKSetting (Ids::iosCompatibility, iosDeploymentTarget.get(), {});
        }

        void addXcodePluginInstallPathProperties (PropertyListBuilder& props)
        {
            auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3() || project.shouldBuildAU()
                                         || project.shouldBuildRTAS() || project.shouldBuildAAX() || project.shouldBuildUnityPlugin());

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

            if (project.shouldBuildVST3())
                props.add (new TextPropertyComponentWithEnablement (vst3BinaryLocation, pluginBinaryCopyStepEnabled, "VST3 Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled VST3 binary should be placed.");

            if (project.shouldBuildAU())
                props.add (new TextPropertyComponentWithEnablement (auBinaryLocation, pluginBinaryCopyStepEnabled, "AU Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled AU binary should be placed.");

            if (project.shouldBuildRTAS())
                props.add (new TextPropertyComponentWithEnablement (rtasBinaryLocation, pluginBinaryCopyStepEnabled, "RTAS Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled RTAS binary should be placed.");

            if (project.shouldBuildAAX())
                props.add (new TextPropertyComponentWithEnablement (aaxBinaryLocation, pluginBinaryCopyStepEnabled, "AAX Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled AAX binary should be placed.");

            if (project.shouldBuildUnityPlugin())
                props.add (new TextPropertyComponentWithEnablement (unityPluginBinaryLocation, pluginBinaryCopyStepEnabled, "Unity Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled Unity plugin binary and associated C# GUI script should be placed.");

            if (project.shouldBuildVST())
                props.add (new TextPropertyComponentWithEnablement (vstBinaryLocation, pluginBinaryCopyStepEnabled, "VST Binary Location",
                                                                    1024, false),
                           "The folder in which the compiled legacy VST binary should be placed.");
        }

        void updateOldPluginBinaryLocations()
        {
            if (! config ["xcodeVstBinaryLocation"].isVoid())        vstBinaryLocation  = config ["xcodeVstBinaryLocation"];
            if (! config ["xcodeVst3BinaryLocation"].isVoid())       vst3BinaryLocation = config ["xcodeVst3BinaryLocation"];
            if (! config ["xcodeAudioUnitBinaryLocation"].isVoid())  auBinaryLocation   = config ["xcodeAudioUnitBinaryLocation"];
            if (! config ["xcodeRtasBinaryLocation"].isVoid())       rtasBinaryLocation = config ["xcodeRtasBinaryLocation"];
            if (! config ["xcodeAaxBinaryLocation"].isVoid())        aaxBinaryLocation  = config ["xcodeAaxBinaryLocation"];
        }

        void updateOldSDKDefaults()
        {
            if (macOSArchitecture.get() == "default")
                macOSArchitecture.resetToDefault();

            const auto updateSDKString = [this] (const Identifier& propertyName, ValueWithDefault& value, const String& suffix)
            {
                auto sdkString = config[propertyName].toString();

                if (sdkString == "default")
                    value.resetToDefault();
                else if (sdkString.isNotEmpty() && sdkString.endsWith (suffix))
                    value = sdkString.upToLastOccurrenceOf (suffix, false, false);
            };

            updateSDKString (Ids::osxSDK, macOSBaseSDK, " SDK");
            updateSDKString (Ids::osxCompatibility, macOSDeploymentTarget, " SDK");
            updateSDKString (Ids::iosCompatibility, iosDeploymentTarget, {});
        }
    };

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

public:
    //==============================================================================
    /* The numbers for these enum values are defined by Xcode for the different
       possible destinations of a "copy files" post-build step.
    */
    enum XcodeCopyFilesDestinationIDs
    {
        kWrapperFolder          = 1,
        kExecutablesFolder      = 6,
        kResourcesFolder        = 7,
        kFrameworksFolder       = 10,
        kSharedFrameworksFolder = 11,
        kSharedSupportFolder    = 12,
        kPluginsFolder          = 13,
        kJavaResourcesFolder    = 15,
        kXPCServicesFolder      = 16
    };

    //==============================================================================
    struct XcodeTarget : build_tools::ProjectType::Target
    {
        //==============================================================================
        XcodeTarget (build_tools::ProjectType::Target::Type targetType, const XcodeProjectExporter& exporter)
            : Target (targetType),
              owner (exporter)
        {
            switch (type)
            {
                case GUIApp:
                    xcodeFileType = "wrapper.application";
                    xcodeBundleExtension = ".app";
                    xcodeProductType = "com.apple.product-type.application";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case ConsoleApp:
                    xcodeFileType = "compiled.mach-o.executable";
                    xcodeBundleExtension = String();
                    xcodeProductType = "com.apple.product-type.tool";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case StaticLibrary:
                    xcodeFileType = "archive.ar";
                    xcodeBundleExtension = ".a";
                    xcodeProductType = "com.apple.product-type.library.static";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case DynamicLibrary:
                    xcodeFileType = "compiled.mach-o.dylib";
                    xcodeProductType = "com.apple.product-type.library.dynamic";
                    xcodeBundleExtension = ".dylib";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case VSTPlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".vst";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;
                    break;

                case VST3PlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".vst3";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;
                    break;

                case AudioUnitPlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".component";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;

                    addExtraAudioUnitTargetSettings();
                    break;

                case StandalonePlugIn:
                    xcodeFileType = "wrapper.application";
                    xcodeBundleExtension = ".app";
                    xcodeProductType = "com.apple.product-type.application";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case AudioUnitv3PlugIn:
                    xcodeFileType = "wrapper.app-extension";
                    xcodeBundleExtension = ".appex";
                    xcodeBundleIDSubPath = "AUv3";
                    xcodeProductType = "com.apple.product-type.app-extension";
                    xcodeCopyToProductInstallPathAfterBuild = false;

                    addExtraAudioUnitv3PlugInTargetSettings();
                    break;

                case AAXPlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".aaxplugin";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;
                    break;

                case RTASPlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".dpm";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;
                    break;

                case UnityPlugIn:
                    xcodeFileType = "wrapper.cfbundle";
                    xcodeBundleExtension = ".bundle";
                    xcodeProductType = "com.apple.product-type.bundle";
                    xcodeCopyToProductInstallPathAfterBuild = true;
                    break;

                case SharedCodeTarget:
                    xcodeFileType = "archive.ar";
                    xcodeBundleExtension = ".a";
                    xcodeProductType = "com.apple.product-type.library.static";
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case AggregateTarget:
                    xcodeCopyToProductInstallPathAfterBuild = false;
                    break;

                case unspecified:
                default:
                    // unknown target type!
                    jassertfalse;
                    break;
            }
        }

        String getXcodeSchemeName() const
        {
            return owner.projectName + " - " + getName();
        }

        String getID() const
        {
            return owner.createID (String ("__target") + getName());
        }

        String getInfoPlistName() const
        {
            return String ("Info-") + String (getName()).replace (" ", "_") + String (".plist");
        }

        String getEntitlementsFilename() const
        {
            return String (getName()).replace (" ", "_") + String (".entitlements");
        }

        String xcodeBundleExtension;
        String xcodeProductType, xcodeFileType;
        String xcodeOtherRezFlags, xcodeBundleIDSubPath;
        bool xcodeCopyToProductInstallPathAfterBuild;
        StringArray xcodeFrameworks, xcodeLibs;
        Array<XmlElement> xcodeExtraPListEntries;

        StringArray frameworkIDs, buildPhaseIDs, configIDs, sourceIDs, rezFileIDs, dependencyIDs;
        StringArray frameworkNames;
        String mainBuildProductID;
        File infoPlistFile;

        struct SourceFileInfo
        {
            build_tools::RelativePath path;
            bool shouldBeCompiled = false;
        };

        Array<SourceFileInfo> getSourceFilesInfo (const Project::Item& projectItem) const
        {
            Array<SourceFileInfo> result;

            auto targetType = (owner.getProject().isAudioPluginProject() ? type : SharedCodeTarget);

            if (projectItem.isGroup())
            {
                for (int i = 0; i < projectItem.getNumChildren(); ++i)
                    result.addArray (getSourceFilesInfo (projectItem.getChild (i)));
            }
            else if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (owner)
                     && owner.getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
            {
                SourceFileInfo info;

                info.path = build_tools::RelativePath (projectItem.getFile(),
                                                       owner.getTargetFolder(),
                                                       build_tools::RelativePath::buildTargetFolder);

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

                if (targetType == SharedCodeTarget || projectItem.shouldBeCompiled())
                    info.shouldBeCompiled = projectItem.shouldBeCompiled();

                result.add (info);
            }

            return result;
        }

        //==============================================================================
        void addMainBuildProduct() const
        {
            jassert (xcodeFileType.isNotEmpty());
            jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar ('.'));

            if (ProjectExporter::BuildConfiguration::Ptr config = owner.getConfiguration (0))
            {
                auto productName = owner.replacePreprocessorTokens (*config, config->getTargetBinaryNameString (type == UnityPlugIn));

                if (xcodeFileType == "archive.ar")
                    productName = getStaticLibbedFilename (productName);
                else
                    productName += xcodeBundleExtension;

                addBuildProduct (xcodeFileType, productName);
            }
        }

        //==============================================================================
        void addBuildProduct (const String& fileType, const String& binaryName) const
        {
            ValueTree v (owner.createID (String ("__productFileID") + getName()) + " /* " + getName() + " */");
            v.setProperty ("isa", "PBXFileReference", nullptr);
            v.setProperty ("explicitFileType", fileType, nullptr);
            v.setProperty ("includeInIndex", (int) 0, nullptr);
            v.setProperty ("path", binaryName, nullptr);
            v.setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);

            owner.addObject (v);
        }

        //==============================================================================
        String addDependencyFor (const XcodeTarget& dependentTarget)
        {
            auto dependencyID = owner.createID (String ("__dependency") + getName() + dependentTarget.getName());
            ValueTree v (dependencyID);
            v.setProperty ("isa", "PBXTargetDependency", nullptr);
            v.setProperty ("target", getID(), nullptr);

            owner.addObject (v);

            return dependencyID;
        }

        void addDependencies()
        {
            if (! owner.project.isAudioPluginProject())
                return;

            if (type == XcodeTarget::StandalonePlugIn) // depends on AUv3 and shared code
            {
                if (auto* auv3Target = owner.getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
                    dependencyIDs.add (auv3Target->addDependencyFor (*this));

                if (auto* sharedCodeTarget = owner.getTargetOfType (XcodeTarget::SharedCodeTarget))
                    dependencyIDs.add (sharedCodeTarget->addDependencyFor (*this));
            }
            else if (type == XcodeTarget::AggregateTarget) // depends on all other targets
            {
                for (auto* target : owner.targets)
                    if (target->type != XcodeTarget::AggregateTarget)
                        dependencyIDs.add (target->addDependencyFor (*this));
            }
            else if (type != XcodeTarget::SharedCodeTarget) // shared code doesn't depend on anything; all other targets depend only on the shared code
            {
                if (auto* sharedCodeTarget = owner.getTargetOfType (XcodeTarget::SharedCodeTarget))
                    dependencyIDs.add (sharedCodeTarget->addDependencyFor (*this));
            }
        }

        //==============================================================================
        void addTargetConfig (const String& configName, const StringArray& buildSettings)
        {
            auto configID = owner.createID (String ("targetconfigid_") + getName() + String ("_") + configName);

            ValueTree v (configID);
            v.setProperty ("isa", "XCBuildConfiguration", nullptr);
            v.setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
            v.setProperty (Ids::name, configName, nullptr);

            configIDs.add (configID);

            owner.addObject (v);
        }

        //==============================================================================
        String getTargetAttributes() const
        {
            StringArray attributes;

            auto developmentTeamID = owner.getDevelopmentTeamIDString();

            if (developmentTeamID.isNotEmpty())
            {
                attributes.add ("DevelopmentTeam = " + developmentTeamID);
                attributes.add ("ProvisioningStyle = Automatic");
            }

            std::map<String, bool> capabilities;

            capabilities["ApplicationGroups.iOS"] = owner.iOS && owner.isAppGroupsEnabled();
            capabilities["InAppPurchase"]         = owner.isInAppPurchasesEnabled();
            capabilities["InterAppAudio"]         = owner.iOS && type == Target::StandalonePlugIn && owner.getProject().shouldEnableIAA();
            capabilities["Push"]                  = owner.isPushNotificationsEnabled();
            capabilities["Sandbox"]               = type == Target::AudioUnitv3PlugIn || owner.isAppSandboxEnabled();
            capabilities["HardenedRuntime"]       = owner.isHardenedRuntimeEnabled();

            if (owner.iOS && owner.isiCloudPermissionsEnabled())
                capabilities["com.apple.iCloud"] = true;

            StringArray capabilitiesStrings;

            for (auto& capability : capabilities)
                capabilitiesStrings.add ("com.apple." + capability.first + " = " + indentBracedList ({ String ("enabled = ") + (capability.second ? "1" : "0") }, 4));

            attributes.add ("SystemCapabilities = " + indentBracedList (capabilitiesStrings, 3));

            attributes.sort (false);

            return getID() + " = " + indentBracedList (attributes, 2);
        }

        //==============================================================================
        ValueTree addBuildPhase (const String& buildPhaseType, const StringArray& fileIds, const StringRef humanReadableName = StringRef())
        {
            auto buildPhaseName = buildPhaseType + "_" + getName() + "_" + (humanReadableName.isNotEmpty() ? String (humanReadableName) : String ("resbuildphase"));
            auto buildPhaseId (owner.createID (buildPhaseName));

            int n = 0;
            while (buildPhaseIDs.contains (buildPhaseId))
                buildPhaseId = owner.createID (buildPhaseName + String (++n));

            buildPhaseIDs.add (buildPhaseId);

            ValueTree v (buildPhaseId);
            v.setProperty ("isa", buildPhaseType, nullptr);
            v.setProperty ("buildActionMask", "2147483647", nullptr);
            v.setProperty ("files", indentParenthesisedList (fileIds), nullptr);

            if (humanReadableName.isNotEmpty())
                v.setProperty ("name", String (humanReadableName), nullptr);

            v.setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, nullptr);

            owner.addObject (v);

            return v;
        }

        bool shouldCreatePList() const
        {
            auto fileType = getTargetFileType();
            return (fileType == executable && type != ConsoleApp) || fileType == pluginBundle || fileType == macOSAppex;
        }

        //==============================================================================
        bool shouldAddEntitlements() const
        {
            if (owner.isPushNotificationsEnabled()
             || owner.isAppGroupsEnabled()
             || owner.isAppSandboxEnabled()
             || owner.isHardenedRuntimeEnabled()
             || owner.isNetworkingMulticastEnabled()
             || (owner.isiOS() && owner.isiCloudPermissionsEnabled()))
                return true;

            if (owner.project.isAudioPluginProject()
                && ((owner.isOSX() && type == Target::AudioUnitv3PlugIn)
                    || (owner.isiOS() && type == Target::StandalonePlugIn && owner.getProject().shouldEnableIAA())))
                return true;

            return false;
        }

        String getBundleIdentifier() const
        {
            auto exporterBundleIdentifier = owner.exporterBundleIdentifierValue.get().toString();
            auto bundleIdentifier = exporterBundleIdentifier.isNotEmpty() ? exporterBundleIdentifier
                                                                          : owner.project.getBundleIdentifierString();

            if (xcodeBundleIDSubPath.isNotEmpty())
            {
                auto bundleIdSegments = StringArray::fromTokens (bundleIdentifier, ".", StringRef());

                jassert (bundleIdSegments.size() > 0);
                bundleIdentifier += String (".") + bundleIdSegments[bundleIdSegments.size() - 1] + xcodeBundleIDSubPath;
            }

            return bundleIdentifier;
        }

        StringPairArray getConfigPreprocessorDefs (const XcodeBuildConfiguration& config) const
        {
            StringPairArray defines;

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

            if (owner.isInAppPurchasesEnabled())
                defines.set ("JUCE_IN_APP_PURCHASES", "1");

            if (owner.iOS && owner.isContentSharingEnabled())
                defines.set ("JUCE_CONTENT_SHARING", "1");

            if (owner.isPushNotificationsEnabled())
                defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");

            return mergePreprocessorDefs (defines, owner.getAllPreprocessorDefs (config, type));
        }

        //==============================================================================
        StringPairArray getTargetSettings (const XcodeBuildConfiguration& config) const
        {
            StringPairArray s;

            if (type == AggregateTarget && ! owner.isiOS())
            {
                // the aggregate target needs to have the deployment target set for
                // pre-/post-build scripts
                s.set ("MACOSX_DEPLOYMENT_TARGET", config.getMacOSDeploymentTargetString());
                s.set ("SDKROOT", "macosx" + config.getMacOSBaseSDKString());

                return s;
            }

            s.set ("PRODUCT_NAME", owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString (type == UnityPlugIn)).quoted());
            s.set ("PRODUCT_BUNDLE_IDENTIFIER", getBundleIdentifier());

            auto arch = (! owner.isiOS() && type == Target::AudioUnitv3PlugIn) ? macOSArch_64Bit
                                                                               : config.getMacOSArchitectureString();

            const auto archString = [&]() -> const char*
            {
                if (arch == macOSArch_Native)           return "\"$(NATIVE_ARCH_ACTUAL)\"";
                if (arch == macOSArch_32BitUniversal)   return "\"$(ARCHS_STANDARD_32_BIT)\"";
                if (arch == macOSArch_64BitUniversal)   return "\"$(ARCHS_STANDARD_32_64_BIT)\"";
                if (arch == macOSArch_64Bit)            return "\"$(ARCHS_STANDARD_64_BIT)\"";

                return nullptr;
            }();

            if (archString != nullptr)
                s.set ("ARCHS", archString);

            if (! owner.isiOS())
            {
                const auto validArchs = owner.getValidArchs();

                if (! validArchs.isEmpty())
                {
                    const auto join = [] (const Array<var>& range)
                    {
                        return std::accumulate (range.begin(),
                                                range.end(),
                                                String(),
                                                [] (String str, const var& v) { return str + v.toString() + " "; }).trim().quoted();
                    };

                    s.set ("VALID_ARCHS", join (validArchs));

                    auto excludedArchs = owner.getAllArchs();
                    excludedArchs.removeIf ([&validArchs] (const auto& a) { return validArchs.contains (a); });

                    s.set ("EXCLUDED_ARCHS", join (excludedArchs));
                }
            }

            auto headerPaths = getHeaderSearchPaths (config);

            auto mtlHeaderPaths = headerPaths;

            for (auto& path : mtlHeaderPaths)
                path = path.unquoted();

            s.set ("MTL_HEADER_SEARCH_PATHS", "\"" + mtlHeaderPaths.joinIntoString (" ") + "\"");

            headerPaths.add ("\"$(inherited)\"");
            s.set ("HEADER_SEARCH_PATHS", indentParenthesisedList (headerPaths, 1));
            s.set ("USE_HEADERMAP", String (static_cast<bool> (config.exporter.settings.getProperty ("useHeaderMap")) ? "YES" : "NO"));

            auto frameworksToSkip = [this]() -> String
            {
                const String openGLFramework (owner.iOS ? "OpenGLES" : "OpenGL");

                if (owner.xcodeFrameworks.contains (openGLFramework))
                    return openGLFramework;

                return {};
            }();

            if (frameworksToSkip.isNotEmpty())
                s.set ("VALIDATE_WORKSPACE_SKIPPED_SDK_FRAMEWORKS", frameworksToSkip);

            auto frameworkSearchPaths = getFrameworkSearchPaths (config);

            if (! frameworkSearchPaths.isEmpty())
                s.set ("FRAMEWORK_SEARCH_PATHS", String ("(") + frameworkSearchPaths.joinIntoString (", ") + ", \"$(inherited)\")");

            s.set ("GCC_OPTIMIZATION_LEVEL", config.getGCCOptimisationFlag());

            if (config.shouldUsePrecompiledHeaderFile())
            {
                s.set ("GCC_PRECOMPILE_PREFIX_HEADER", "YES");

                auto pchFileContent = config.getPrecompiledHeaderFileContent();

                if (pchFileContent.isNotEmpty())
                {
                    auto pchFilename = config.getPrecompiledHeaderFilename() + ".h";

                    build_tools::writeStreamToFile (owner.getTargetFolder().getChildFile (pchFilename),
                                                    [&] (MemoryOutputStream& mo) { mo << pchFileContent; });

                    s.set ("GCC_PREFIX_HEADER", pchFilename);
                }
            }

            if (shouldCreatePList())
            {
                s.set ("INFOPLIST_FILE", infoPlistFile.getFileName());

                if (owner.getPListPrefixHeaderString().isNotEmpty())
                    s.set ("INFOPLIST_PREFIX_HEADER", owner.getPListPrefixHeaderString());

                s.set ("INFOPLIST_PREPROCESS", (owner.isPListPreprocessEnabled() ? String ("YES") : String ("NO")));

                auto plistDefs = parsePreprocessorDefs (config.getPListPreprocessorDefinitionsString());
                StringArray defsList;

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

                    if (value.isNotEmpty())
                        def << "=" << value.replace ("\"", "\\\\\\\"");

                    defsList.add ("\"" + def + "\"");
                }

                if (defsList.size() > 0)
                    s.set ("INFOPLIST_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));
            }

            if (config.isLinkTimeOptimisationEnabled())
                s.set ("LLVM_LTO", "YES");

            if (config.isFastMathEnabled())
                s.set ("GCC_FAST_MATH", "YES");

            auto recommendedWarnings = config.getRecommendedCompilerWarningFlags();
            recommendedWarnings.cpp.addArray (recommendedWarnings.common);

            struct XcodeWarningFlags
            {
                const StringArray& flags;
                const String variable;
            };

            for (const auto& xcodeFlags : { XcodeWarningFlags { recommendedWarnings.common, "OTHER_CFLAGS" },
                                            XcodeWarningFlags { recommendedWarnings.cpp,    "OTHER_CPLUSPLUSFLAGS" } })
            {
                auto flags = (xcodeFlags.flags.joinIntoString (" ")
                                 + " " + owner.getExtraCompilerFlagsString()).trim();
                flags = owner.replacePreprocessorTokens (config, flags);

                if (flags.isNotEmpty())
                    s.set (xcodeFlags.variable, flags.quoted());
            }

            auto installPath = getInstallPathForConfiguration (config);

            if (installPath.startsWith ("~"))
                installPath = installPath.replace ("~", "$(HOME)");

            if (installPath.isNotEmpty())
            {
                s.set ("INSTALL_PATH", installPath.quoted());

                if (type == Target::SharedCodeTarget)
                    s.set ("SKIP_INSTALL", "YES");

                if (! owner.embeddedFrameworkIDs.isEmpty())
                    s.set ("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks @executable_path/../Frameworks\"");

                if (xcodeCopyToProductInstallPathAfterBuild)
                {
                    s.set ("DEPLOYMENT_LOCATION", "YES");
                    s.set ("DSTROOT", "/");
                }
            }

            if (getTargetFileType() == pluginBundle)
            {
                s.set ("LIBRARY_STYLE", "Bundle");
                s.set ("WRAPPER_EXTENSION", xcodeBundleExtension.substring (1));
                s.set ("GENERATE_PKGINFO_FILE", "YES");
            }

            if (xcodeOtherRezFlags.isNotEmpty())
                s.set ("OTHER_REZFLAGS", "\"" + xcodeOtherRezFlags + "\"");

            String configurationBuildDir ("$(PROJECT_DIR)/build/$(CONFIGURATION)");

            if (config.getTargetBinaryRelativePathString().isNotEmpty())
            {
                // a target's position can either be defined via installPath + xcodeCopyToProductInstallPathAfterBuild
                // (= for audio plug-ins) or using a custom binary path (for everything else), but not both (= conflict!)
                jassert (! xcodeCopyToProductInstallPathAfterBuild);

                build_tools::RelativePath binaryPath (config.getTargetBinaryRelativePathString(),
                                                      build_tools::RelativePath::projectFolder);

                configurationBuildDir = expandPath (binaryPath.rebased (owner.projectFolder,
                                                                        owner.getTargetFolder(),
                                                                        build_tools::RelativePath::buildTargetFolder)
                                                              .toUnixStyle());
            }

            s.set ("CONFIGURATION_BUILD_DIR", addQuotesIfRequired (configurationBuildDir));

            if (owner.isHardenedRuntimeEnabled())
                s.set ("ENABLE_HARDENED_RUNTIME", "YES");

            String gccVersion ("com.apple.compilers.llvm.clang.1_0");

            if (owner.iOS)
            {
                s.set ("ASSETCATALOG_COMPILER_APPICON_NAME", "AppIcon");

                if (! owner.shouldAddStoryboardToProject())
                    s.set ("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME", "LaunchImage");
            }
            else
            {
                s.set ("MACOSX_DEPLOYMENT_TARGET", config.getMacOSDeploymentTargetString());
            }

            s.set ("GCC_VERSION", gccVersion);
            s.set ("CLANG_LINK_OBJC_RUNTIME", "NO");

            auto codeSigningIdentity = owner.getCodeSigningIdentity (config);
            s.set (owner.iOS ? "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"" : "CODE_SIGN_IDENTITY",
                   codeSigningIdentity.quoted());

            if (codeSigningIdentity.isNotEmpty())
            {
                s.set ("PROVISIONING_PROFILE_SPECIFIER", "\"\"");

                if (! owner.isUsingDefaultSigningIdentity (config))
                    s.set ("CODE_SIGN_STYLE", "Manual");
            }

            if (owner.getDevelopmentTeamIDString().isNotEmpty())
                s.set ("DEVELOPMENT_TEAM", owner.getDevelopmentTeamIDString());

            if (shouldAddEntitlements())
                s.set ("CODE_SIGN_ENTITLEMENTS", getEntitlementsFilename().quoted());

            {
                auto cppStandard = owner.project.getCppStandardString();

                if (cppStandard == "latest")
                    cppStandard = owner.project.getLatestNumberedCppStandardString();

                s.set ("CLANG_CXX_LANGUAGE_STANDARD", (String (owner.shouldUseGNUExtensions() ? "gnu++"
                                                                                              : "c++") + cppStandard).quoted());
            }

            s.set ("CLANG_CXX_LIBRARY", "\"libc++\"");

            s.set ("COMBINE_HIDPI_IMAGES", "YES");

            {
                StringArray linkerFlags, librarySearchPaths;
                getLinkerSettings (config, linkerFlags, librarySearchPaths);

                if (linkerFlags.size() > 0)
                    s.set ("OTHER_LDFLAGS", linkerFlags.joinIntoString (" ").quoted());

                librarySearchPaths.addArray (config.getLibrarySearchPaths());
                librarySearchPaths = getCleanedStringArray (librarySearchPaths);

                if (librarySearchPaths.size() > 0)
                {
                    StringArray libPaths;
                    libPaths.add ("\"$(inherited)\"");

                    for (auto& p : librarySearchPaths)
                        libPaths.add ("\"\\\"" + p + "\\\"\"");

                    s.set ("LIBRARY_SEARCH_PATHS", indentParenthesisedList (libPaths, 1));
                }
            }

            if (config.isDebug())
            {
                s.set ("COPY_PHASE_STRIP", "NO");
                s.set ("GCC_DYNAMIC_NO_PIC", "NO");
            }
            else
            {
                s.set ("GCC_GENERATE_DEBUGGING_SYMBOLS", "NO");
                s.set ("DEAD_CODE_STRIPPING", "YES");
            }

            if (type != Target::SharedCodeTarget && type != Target::StaticLibrary && type != Target::DynamicLibrary
                && config.isStripLocalSymbolsEnabled())
            {
                s.set ("STRIPFLAGS", "\"-x\"");
                s.set ("DEPLOYMENT_POSTPROCESSING", "YES");
                s.set ("SEPARATE_STRIP", "YES");
            }

            StringArray defsList;

            const auto defines = getConfigPreprocessorDefs (config);

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

                defsList.add ("\"" + def + "\"");
            }

            s.set ("GCC_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));

            StringArray customFlags;
            customFlags.addTokens (config.getCustomXcodeFlagsString(), ",", "\"'");
            customFlags.removeEmptyStrings();

            for (auto flag : customFlags)
            {
                s.set (flag.upToFirstOccurrenceOf ("=", false, false).trim(),
                       flag.fromFirstOccurrenceOf ("=", false, false).trim().quoted());
            }

            return s;
        }

        String getInstallPathForConfiguration (const XcodeBuildConfiguration& config) const
        {
            switch (type)
            {
                case GUIApp:            return "$(HOME)/Applications";
                case ConsoleApp:        return "/usr/bin";
                case VSTPlugIn:         return config.isPluginBinaryCopyStepEnabled() ? config.getVSTBinaryLocationString() : String();
                case VST3PlugIn:        return config.isPluginBinaryCopyStepEnabled() ? config.getVST3BinaryLocationString() : String();
                case AudioUnitPlugIn:   return config.isPluginBinaryCopyStepEnabled() ? config.getAUBinaryLocationString() : String();
                case RTASPlugIn:        return config.isPluginBinaryCopyStepEnabled() ? config.getRTASBinaryLocationString() : String();
                case AAXPlugIn:         return config.isPluginBinaryCopyStepEnabled() ? config.getAAXBinaryLocationString() : String();
                case UnityPlugIn:       return config.isPluginBinaryCopyStepEnabled() ? config.getUnityPluginBinaryLocationString() : String();
                case SharedCodeTarget:  return owner.isiOS() ? "@executable_path/Frameworks" : "@executable_path/../Frameworks";
                case StaticLibrary:
                case DynamicLibrary:
                case AudioUnitv3PlugIn:
                case StandalonePlugIn:
                case AggregateTarget:
                case unspecified:
                default:                return {};
            }
        }

        //==============================================================================
        void getLinkerSettings (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths) const
        {
            if (getTargetFileType() == pluginBundle)
                flags.add (owner.isiOS() ? "-bitcode_bundle" : "-bundle");

            if (type != Target::SharedCodeTarget)
            {
                Array<build_tools::RelativePath> extraLibs;

                addExtraLibsForTargetType (config, extraLibs);

                for (auto& lib : extraLibs)
                {
                    flags.add (getLinkerFlagForLib (lib.getFileNameWithoutExtension()));
                    librarySearchPaths.add (owner.getSearchPathForStaticLibrary (lib));
                }

                if (owner.project.isAudioPluginProject())
                {
                    if (owner.getTargetOfType (Target::SharedCodeTarget) != nullptr)
                    {
                        auto productName = getStaticLibbedFilename (owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString()));

                        build_tools::RelativePath sharedCodelib (productName, build_tools::RelativePath::buildTargetFolder);
                        flags.add (getLinkerFlagForLib (sharedCodelib.getFileNameWithoutExtension()));
                    }
                }

                flags.add (owner.getExternalLibraryFlags (config));

                auto libs = owner.xcodeLibs;
                libs.addArray (xcodeLibs);

                for (auto& l : libs)
                    flags.add (getLinkerFlagForLib (l));
            }

            flags.add (owner.replacePreprocessorTokens (config, owner.getExtraLinkerFlagsString()));
            flags = getCleanedStringArray (flags);
        }

        //==========================================================================
        void writeInfoPlistFile() const
        {
            if (! shouldCreatePList())
                return;

            build_tools::PlistOptions options;

            options.type                             = type;
            options.executableName                   = "${EXECUTABLE_NAME}";
            options.bundleIdentifier                 = getBundleIdentifier();
            options.applicationCategory              = owner.getApplicationCategoryString();
            options.plistToMerge                     = owner.getPListToMergeString();
            options.iOS                              = owner.iOS;
            options.microphonePermissionEnabled      = owner.isMicrophonePermissionEnabled();
            options.microphonePermissionText         = owner.getMicrophonePermissionsTextString();
            options.cameraPermissionEnabled          = owner.isCameraPermissionEnabled();
            options.cameraPermissionText             = owner.getCameraPermissionTextString();
            options.bluetoothPermissionEnabled       = owner.isBluetoothPermissionEnabled();
            options.bluetoothPermissionText          = owner.getBluetoothPermissionTextString();
            options.sendAppleEventsPermissionEnabled = owner.isSendAppleEventsPermissionEnabled();
            options.sendAppleEventsPermissionText    = owner.getSendAppleEventsPermissionTextString();
            options.shouldAddStoryboardToProject     = owner.shouldAddStoryboardToProject();
            options.iconFile                         = owner.iconFile;
            options.projectName                      = owner.projectName;
            options.marketingVersion                 = owner.project.getVersionString();
            options.currentProjectVersion            = owner.getBuildNumber();
            options.companyCopyright                 = owner.project.getCompanyCopyrightString();
            options.allPreprocessorDefs              = owner.getAllPreprocessorDefs();
            options.documentExtensions               = owner.getDocumentExtensionsString();
            options.fileSharingEnabled               = owner.isFileSharingEnabled();
            options.documentBrowserEnabled           = owner.isDocumentBrowserEnabled();
            options.statusBarHidden                  = owner.isStatusBarHidden();
            options.requiresFullScreen               = owner.requiresFullScreen();
            options.backgroundAudioEnabled           = owner.isBackgroundAudioEnabled();
            options.backgroundBleEnabled             = owner.isBackgroundBleEnabled();
            options.pushNotificationsEnabled         = owner.isPushNotificationsEnabled();
            options.enableIAA                        = owner.project.shouldEnableIAA();
            options.IAAPluginName                    = owner.project.getIAAPluginName();
            options.pluginManufacturerCode           = owner.project.getPluginManufacturerCodeString();
            options.IAATypeCode                      = owner.project.getIAATypeCode();
            options.pluginCode                       = owner.project.getPluginCodeString();
            options.iPhoneScreenOrientations         = owner.getiPhoneScreenOrientations();
            options.iPadScreenOrientations           = owner.getiPadScreenOrientations();

            options.storyboardName = [&]
            {
                const auto customLaunchStoryboard = owner.getCustomLaunchStoryboardString();

                if (customLaunchStoryboard.isEmpty())
                    return owner.getDefaultLaunchStoryboardName();

                return customLaunchStoryboard.fromLastOccurrenceOf ("/", false, false)
                                             .upToLastOccurrenceOf (".storyboard", false, false);
            }();

            options.pluginName                      = owner.project.getPluginNameString();
            options.pluginManufacturer              = owner.project.getPluginManufacturerString();
            options.pluginDescription               = owner.project.getPluginDescriptionString();
            options.pluginAUExportPrefix            = owner.project.getPluginAUExportPrefixString();
            options.auMainType                      = owner.project.getAUMainTypeString();
            options.isAuSandboxSafe                 = owner.project.isAUSandBoxSafe();
            options.isPluginSynth                   = owner.project.isPluginSynth();
            options.suppressResourceUsage           = owner.getSuppressPlistResourceUsage();

            options.write (infoPlistFile);
        }

        //==============================================================================
        void addShellScriptBuildPhase (const String& phaseName, const String& script)
        {
            if (script.trim().isNotEmpty())
            {
                auto v = addBuildPhase ("PBXShellScriptBuildPhase", {});
                v.setProperty (Ids::name, phaseName, nullptr);
                v.setProperty ("alwaysOutOfDate", 1, nullptr);
                v.setProperty ("shellPath", "/bin/sh", nullptr);
                v.setProperty ("shellScript", script.replace ("\\", "\\\\")
                                                    .replace ("\"", "\\\"")
                                                    .replace ("\r\n", "\\n")
                                                    .replace ("\n", "\\n"), nullptr);
            }
        }

        void addCopyFilesPhase (const String& phaseName, const StringArray& files, XcodeCopyFilesDestinationIDs dst)
        {
            auto v = addBuildPhase ("PBXCopyFilesBuildPhase", files, phaseName);
            v.setProperty ("dstPath", "", nullptr);
            v.setProperty ("dstSubfolderSpec", (int) dst, nullptr);
        }

        //==============================================================================
        void sanitiseAndEscapeSearchPaths (const BuildConfiguration& config, StringArray& paths) const
        {
            paths = getCleanedStringArray (paths);

            for (auto& path : paths)
            {
                path = owner.replacePreprocessorTokens (config, expandPath (path));

                if (path.containsChar (' '))
                    path = "\"\\\"" + path + "\\\"\""; // crazy double quotes required when there are spaces..
                else
                    path = "\"" + path + "\"";
            }
        }

        StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
        {
            StringArray paths (owner.extraSearchPaths);
            paths.addArray (config.getHeaderSearchPaths());
            paths.addArray (getTargetExtraHeaderSearchPaths());

            if (owner.project.getEnabledModules().isModuleEnabled ("juce_audio_plugin_client"))
            {
                // Needed to compile .r files
                paths.add (owner.getModuleFolderRelativeToProject ("juce_audio_plugin_client")
                                .rebased (owner.projectFolder, owner.getTargetFolder(), build_tools::RelativePath::buildTargetFolder)
                                .toUnixStyle());
            }

            sanitiseAndEscapeSearchPaths (config, paths);
            return paths;
        }

        StringArray getFrameworkSearchPaths (const BuildConfiguration& config) const
        {
            auto paths = getSearchPathsFromString (owner.getFrameworkSearchPathsString());
            sanitiseAndEscapeSearchPaths (config, paths);
            return paths;
        }

    private:
        //==============================================================================
        void addExtraAudioUnitTargetSettings()
        {
            xcodeOtherRezFlags = "-d ppc_$ppc -d i386_$i386 -d ppc64_$ppc64 -d x86_64_$x86_64 -d arm64_$arm64"
                                 " -I /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Versions/A/Headers"
                                 " -I \\\"$(DEVELOPER_DIR)/Extras/CoreAudio/AudioUnits/AUPublic/AUBase\\\""
                                 " -I \\\"$(DEVELOPER_DIR)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/AudioUnit.framework/Headers\\\"";

            xcodeFrameworks.addArray ({ "AudioUnit", "CoreAudioKit" });
        }

        void addExtraAudioUnitv3PlugInTargetSettings()
        {
            xcodeFrameworks.addArray ({ "AVFoundation", "CoreAudioKit" });

            if (owner.isOSX())
                xcodeFrameworks.add ("AudioUnit");
        }

        void addExtraLibsForTargetType  (const BuildConfiguration& config, Array<build_tools::RelativePath>& extraLibs) const
        {
            if (type == AAXPlugIn)
            {
                auto aaxLibsFolder = build_tools::RelativePath (owner.getAAXPathString(), build_tools::RelativePath::projectFolder).getChildFile ("Libs");

                String libraryPath (config.isDebug() ? "Debug" : "Release");
                libraryPath += "/libAAXLibrary_libcpp.a";

                extraLibs.add   (aaxLibsFolder.getChildFile (libraryPath));
            }
            else if (type == RTASPlugIn)
            {
                build_tools::RelativePath rtasFolder (owner.getRTASPathString(), build_tools::RelativePath::projectFolder);

                extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Debug/libPluginLibrary.a"));
                extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Release/libPluginLibrary.a"));
            }
        }

        StringArray getTargetExtraHeaderSearchPaths() const
        {
            StringArray targetExtraSearchPaths;

            if (type == RTASPlugIn)
            {
                build_tools::RelativePath rtasFolder (owner.getRTASPathString(), build_tools::RelativePath::projectFolder);

                targetExtraSearchPaths.add ("$(DEVELOPER_DIR)/Headers/FlatCarbon");
                targetExtraSearchPaths.add ("$(SDKROOT)/Developer/Headers/FlatCarbon");

                static const char* p[] = { "AlturaPorts/TDMPlugIns/PlugInLibrary/Controls",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/CoreClasses",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/DSPClasses",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/EffectClasses",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/MacBuild",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/Meters",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses/Interfaces",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/RTASP_Adapt",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/Utilities",
                    "AlturaPorts/TDMPlugIns/PlugInLibrary/ViewClasses",
                    "AlturaPorts/TDMPlugIns/DSPManager/**",
                    "AlturaPorts/TDMPlugIns/SupplementalPlugInLib/Encryption",
                    "AlturaPorts/TDMPlugIns/SupplementalPlugInLib/GraphicsExtensions",
                    "AlturaPorts/TDMPlugIns/common/**",
                    "AlturaPorts/TDMPlugIns/common/PI_LibInterface",
                    "AlturaPorts/TDMPlugIns/PACEProtection/**",
                    "AlturaPorts/TDMPlugIns/SignalProcessing/**",
                    "AlturaPorts/OMS/Headers",
                    "AlturaPorts/Fic/Interfaces/**",
                    "AlturaPorts/Fic/Source/SignalNets",
                    "AlturaPorts/DSIPublicInterface/PublicHeaders",
                    "DAEWin/Include",
                    "AlturaPorts/DigiPublic/Interfaces",
                    "AlturaPorts/DigiPublic",
                    "AlturaPorts/NewFileLibs/DOA",
                    "AlturaPorts/NewFileLibs/Cmn",
                    "xplat/AVX/avx2/avx2sdk/inc",
                    "xplat/AVX/avx2/avx2sdk/utils" };

                for (auto* path : p)
                    owner.addProjectPathToBuildPathList (targetExtraSearchPaths, rtasFolder.getChildFile (path));
            }

            return targetExtraSearchPaths;
        }

        //==============================================================================
        const XcodeProjectExporter& owner;

        Target& operator= (const Target&) = delete;
    };

    mutable StringArray xcodeFrameworks;
    StringArray xcodeLibs;

private:
    //==============================================================================
    static String expandPath (const String& path)
    {
        if (! build_tools::isAbsolutePath (path))  return "$(SRCROOT)/" + path;
        if (path.startsWithChar ('~'))             return "$(HOME)" + path.substring (1);

        return path;
    }

    static String addQuotesIfRequired (const String& s)
    {
        return s.containsAnyOf (" $") ? s.quoted() : s;
    }

    File getProjectBundle() const                 { return getTargetFolder().getChildFile (project.getProjectFilenameRootString()).withFileExtension (".xcodeproj"); }

    //==============================================================================
    void createObjects() const
    {
        prepareTargets();

        // Must be called before adding embedded frameworks, as we want to
        // embed any frameworks found in subprojects.
        addSubprojects();

        addFrameworks();

        addCustomResourceFolders();
        addPlistFileReferences();

        if (iOS && ! projectType.isStaticLibrary())
        {
            addXcassets();

            if (shouldAddStoryboardToProject())
            {
                auto customLaunchStoryboard = getCustomLaunchStoryboardString();

                if (customLaunchStoryboard.isEmpty())
                    writeDefaultLaunchStoryboardFile();
                else if (getProject().getProjectFolder().getChildFile (customLaunchStoryboard).existsAsFile())
                    addLaunchStoryboardFileReference (build_tools::RelativePath (customLaunchStoryboard, build_tools::RelativePath::projectFolder)
                                                          .rebased (getProject().getProjectFolder(), getTargetFolder(), build_tools::RelativePath::buildTargetFolder));
            }
        }
        else
        {
            addNibFiles();
        }

        addIcons();
        addBuildConfigurations();

        addProjectConfigList (createID ("__projList"));

        {
            StringArray topLevelGroupIDs;

            addFilesAndGroupsToProject (topLevelGroupIDs);
            addBuildPhases();
            addExtraGroupsToProject (topLevelGroupIDs);

            addGroup (createID ("__mainsourcegroup"), "Source", topLevelGroupIDs);
        }

        addProjectObject();
        removeMismatchedXcuserdata();
    }

    void prepareTargets() const
    {
        for (auto* target : targets)
        {
            target->addDependencies();

            if (target->type == XcodeTarget::AggregateTarget)
                continue;

            target->addMainBuildProduct();

            auto targetName = String (target->getName());
            auto fileID = createID (targetName + "__targetbuildref");
            auto fileRefID = createID ("__productFileID" + targetName);

            ValueTree v (fileID + " /* " + targetName + " */");
            v.setProperty ("isa", "PBXBuildFile", nullptr);
            v.setProperty ("fileRef", fileRefID, nullptr);

            target->mainBuildProductID = fileID;

            addObject (v);
        }
    }

    void addPlistFileReferences() const
    {
        for (auto* target : targets)
        {
            if (target->type == XcodeTarget::AggregateTarget)
                continue;

            if (target->shouldCreatePList())
            {
                build_tools::RelativePath plistPath (target->infoPlistFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
                addFileReference (plistPath.toUnixStyle());
                resourceFileRefs.add (createFileRefID (plistPath));
            }
        }
    }

    void addNibFiles() const
    {
        build_tools::writeStreamToFile (menuNibFile, [&] (MemoryOutputStream& mo)
        {
            mo.write (BinaryData::RecentFilesMenuTemplate_nib, BinaryData::RecentFilesMenuTemplate_nibSize);
        });

        build_tools::RelativePath menuNibPath (menuNibFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
        addFileReference (menuNibPath.toUnixStyle());
        resourceIDs.add (addBuildFile (FileOptions().withRelativePath (menuNibPath)));
        resourceFileRefs.add (createFileRefID (menuNibPath));
    }

    void addIcons() const
    {
        if (iconFile.exists())
        {
            build_tools::RelativePath iconPath (iconFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
            addFileReference (iconPath.toUnixStyle());
            resourceIDs.add (addBuildFile (FileOptions().withRelativePath (iconPath)));
            resourceFileRefs.add (createFileRefID (iconPath));
        }
    }

    void addBuildConfigurations() const
    {
        for (ConstConfigIterator config (*this); config.next();)
        {
            auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);
            StringArray settingsLines;
            auto configSettings = getProjectSettings (xcodeConfig);
            auto keys = configSettings.getAllKeys();
            keys.sort (false);

            for (auto& key : keys)
                settingsLines.add (key + " = " + configSettings[key]);

            addProjectConfig (config->getName(), settingsLines);
        }
    }

    void addFilesAndGroupsToProject (StringArray& topLevelGroupIDs) const
    {
        for (auto* target : targets)
            if (target->shouldAddEntitlements())
                addEntitlementsFile (*target);

        for (auto& group : getAllGroups())
        {
            if (group.getNumChildren() > 0)
            {
                auto groupID = addProjectItem (group);

                if (groupID.isNotEmpty())
                    topLevelGroupIDs.add (groupID);
            }
        }
    }

    void addExtraGroupsToProject (StringArray& topLevelGroupIDs) const
    {
        {
            auto resourcesGroupID = createID ("__resources");
            addGroup (resourcesGroupID, "Resources", resourceFileRefs);
            topLevelGroupIDs.add (resourcesGroupID);
        }

        {
            auto frameworksGroupID = createID ("__frameworks");
            addGroup (frameworksGroupID, "Frameworks", frameworkFileIDs);
            topLevelGroupIDs.add (frameworksGroupID);
        }

        {
            auto productsGroupID = createID ("__products");
            addGroup (productsGroupID, "Products", buildProducts);
            topLevelGroupIDs.add (productsGroupID);
        }

        if (! subprojectFileIDs.isEmpty())
        {
            auto subprojectLibrariesGroupID = createID ("__subprojects");
            addGroup (subprojectLibrariesGroupID, "Subprojects", subprojectFileIDs);
            topLevelGroupIDs.add (subprojectLibrariesGroupID);
        }
    }

    void addBuildPhases() const
    {
        // add build phases
        for (auto* target : targets)
        {
            if (target->type != XcodeTarget::AggregateTarget)
                buildProducts.add (createID (String ("__productFileID") + String (target->getName())));

            for (ConstConfigIterator config (*this); config.next();)
            {
                auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);

                auto configSettings = target->getTargetSettings (xcodeConfig);
                StringArray settingsLines;
                auto keys = configSettings.getAllKeys();
                keys.sort (false);

                for (auto& key : keys)
                    settingsLines.add (key + " = " + configSettings.getValue (key, "\"\""));

                target->addTargetConfig (config->getName(), settingsLines);
            }

            addConfigList (*target, createID (String ("__configList") + target->getName()));

            target->addShellScriptBuildPhase ("Pre-build script", getPreBuildScript());

            if (target->type != XcodeTarget::AggregateTarget)
            {
                auto skipAUv3 = (target->type == XcodeTarget::AudioUnitv3PlugIn && ! shouldDuplicateAppExResourcesFolder());

                if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget && ! skipAUv3)
                    target->addBuildPhase ("PBXResourcesBuildPhase", resourceIDs);

                auto rezFiles = rezFileIDs;
                rezFiles.addArray (target->rezFileIDs);

                if (rezFiles.size() > 0)
                    target->addBuildPhase ("PBXRezBuildPhase", rezFiles);

                auto sourceFiles = target->sourceIDs;

                if (target->type == XcodeTarget::SharedCodeTarget
                     || (! project.isAudioPluginProject()))
                    sourceFiles.addArray (sourceIDs);

                target->addBuildPhase ("PBXSourcesBuildPhase", sourceFiles);

                if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget)
                    target->addBuildPhase ("PBXFrameworksBuildPhase", target->frameworkIDs);
            }

            target->addShellScriptBuildPhase ("Post-build script", getPostBuildScript());

            if (project.isAudioPluginProject() && project.shouldBuildAUv3()
                && project.shouldBuildStandalonePlugin() && target->type == XcodeTarget::StandalonePlugIn)
                embedAppExtension();

            if (project.isAudioPluginProject() && project.shouldBuildUnityPlugin()
                && target->type == XcodeTarget::UnityPlugIn)
                embedUnityScript();

            addTargetObject (*target);
        }
    }

    void embedAppExtension() const
    {
        if (auto* standaloneTarget = getTargetOfType (XcodeTarget::StandalonePlugIn))
        {
            if (auto* auv3Target   = getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
            {
                StringArray files;
                files.add (auv3Target->mainBuildProductID);
                standaloneTarget->addCopyFilesPhase ("Embed App Extensions", files, kPluginsFolder);
            }
        }
    }

    void embedUnityScript() const
    {
        if (auto* unityTarget = getTargetOfType (XcodeTarget::UnityPlugIn))
        {
            build_tools::RelativePath scriptPath (getProject().getGeneratedCodeFolder().getChildFile (getProject().getUnityScriptName()),
                                                  getTargetFolder(),
                                                  build_tools::RelativePath::buildTargetFolder);

            auto path = scriptPath.toUnixStyle();
            auto refID = addFileReference (path);
            auto fileID = addBuildFile (FileOptions().withPath (path)
                                                     .withFileRefID (refID));

            resourceIDs.add (fileID);
            resourceFileRefs.add (refID);

            unityTarget->addCopyFilesPhase ("Embed Unity Script", fileID, kResourcesFolder);
        }
    }

    //==============================================================================
    XcodeTarget* getTargetOfType (build_tools::ProjectType::Target::Type type) const
    {
        for (auto& target : targets)
            if (target->type == type)
                return target;

        return nullptr;
    }

    void addTargetObject (XcodeTarget& target) const
    {
        auto targetName = target.getName();

        auto targetID = target.getID();
        ValueTree v (targetID);
        v.setProperty ("isa", target.type == XcodeTarget::AggregateTarget ? "PBXAggregateTarget" : "PBXNativeTarget", nullptr);
        v.setProperty ("buildConfigurationList", createID (String ("__configList") + targetName), nullptr);

        v.setProperty ("buildPhases", indentParenthesisedList (target.buildPhaseIDs), nullptr);

        if (target.type != XcodeTarget::AggregateTarget)
            v.setProperty ("buildRules", indentParenthesisedList ({}), nullptr);

        StringArray allDependencyIDs { subprojectDependencyIDs };
        allDependencyIDs.addArray (target.dependencyIDs);
        v.setProperty ("dependencies", indentParenthesisedList (allDependencyIDs), nullptr);

        v.setProperty (Ids::name, target.getXcodeSchemeName(), nullptr);
        v.setProperty ("productName", projectName, nullptr);

        if (target.type != XcodeTarget::AggregateTarget)
        {
            v.setProperty ("productReference", createID (String ("__productFileID") + targetName), nullptr);

            jassert (target.xcodeProductType.isNotEmpty());
            v.setProperty ("productType", target.xcodeProductType, nullptr);
        }

        targetIDs.add (targetID);
        addObject (v);
    }

    void createIconFile() const
    {
        const auto icons = getIcons();

        if (! build_tools::asArray (icons).isEmpty())
        {
            iconFile = getTargetFolder().getChildFile ("Icon.icns");
            build_tools::writeMacIcon (icons, iconFile);
        }
    }

    void writeWorkspaceSettings() const
    {
        const auto settingsFile = getProjectBundle().getChildFile ("project.xcworkspace")
                                                    .getChildFile ("xcshareddata")
                                                    .getChildFile ("WorkspaceSettings.xcsettings");

        if (shouldUseLegacyBuildSystem())
        {
            build_tools::writeStreamToFile (settingsFile, [this] (MemoryOutputStream& mo)
            {
                mo.setNewLineString (getNewLineString());

                mo << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"                 << newLine
                   << "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << newLine
                   << "<plist version=\"1.0\">"                                    << newLine
                   << "<dict>"                                                     << newLine
                   << "\t" << "<key>BuildSystemType</key>"                         << newLine
                   << "\t" << "<string>Original</string>"                          << newLine
                   << "\t" << "<key>DisableBuildSystemDeprecationWarning</key>"    << newLine
                   << "\t" << "<true/>"                                            << newLine
                   << "\t" << "<key>DisableBuildSystemDeprecationDiagnostic</key>" << newLine
                   << "\t" << "<true/>"                                            << newLine
                   << "</dict>"                                                    << newLine
                   << "</plist>"                                                   << newLine;
            });
        }
        else
        {
            settingsFile.deleteFile();
        }
    }

    void writeInfoPlistFiles() const
    {
        for (auto& target : targets)
           target->writeInfoPlistFile();
    }

    // Delete .rsrc files in folder but don't follow sym-links
    void deleteRsrcFiles (const File& folder) const
    {
        for (const auto& di : RangedDirectoryIterator (folder, false, "*", File::findFilesAndDirectories))
        {
            const auto& entry = di.getFile();

            if (! entry.isSymbolicLink())
            {
                if (entry.existsAsFile() && entry.getFileExtension().toLowerCase() == ".rsrc")
                    entry.deleteFile();
                else if (entry.isDirectory())
                    deleteRsrcFiles (entry);
            }
        }
    }

    static String getLinkerFlagForLib (String library)
    {
        if (library.substring (0, 3) == "lib")
            library = library.substring (3);

        return "-l" + library.replace (" ", "\\\\ ").replace ("\"", "\\\\\"").replace ("\'", "\\\\\'").upToLastOccurrenceOf (".", false, false);
    }

    String getSearchPathForStaticLibrary (const build_tools::RelativePath& library) const
    {
        auto searchPath = library.toUnixStyle().upToLastOccurrenceOf ("/", false, false);

        if (! library.isAbsolute())
        {
            auto srcRoot = rebaseFromProjectFolderToBuildTarget (build_tools::RelativePath (".", build_tools::RelativePath::projectFolder)).toUnixStyle();

            if (srcRoot.endsWith ("/."))      srcRoot = srcRoot.dropLastCharacters (2);
            if (! srcRoot.endsWithChar ('/')) srcRoot << '/';

            searchPath = srcRoot + searchPath;
        }

        return expandPath (searchPath);
    }

    bool isUsingDefaultSigningIdentity (const XcodeBuildConfiguration& config) const
    {
        return config.getCodeSignIdentityString().isEmpty() && getDevelopmentTeamIDString().isNotEmpty();
    }

    String getCodeSigningIdentity (const XcodeBuildConfiguration& config) const
    {
        if (isUsingDefaultSigningIdentity (config))
            return iOS ? "iPhone Developer" : "Mac Developer";

        const auto identity = config.getCodeSignIdentityString();
        return identity.isNotEmpty() ? identity : "-";
    }

    StringPairArray getProjectSettings (const XcodeBuildConfiguration& config) const
    {
        StringPairArray s;

        s.set ("ALWAYS_SEARCH_USER_PATHS", "NO");
        s.set ("ENABLE_STRICT_OBJC_MSGSEND", "YES");
        s.set ("GCC_C_LANGUAGE_STANDARD", "c11");
        s.set ("GCC_NO_COMMON_BLOCKS", "YES");
        s.set ("GCC_MODEL_TUNING", "G5");
        s.set ("GCC_WARN_ABOUT_RETURN_TYPE", "YES");
        s.set ("GCC_WARN_CHECK_SWITCH_STATEMENTS", "YES");
        s.set ("GCC_WARN_UNUSED_VARIABLE", "YES");
        s.set ("GCC_WARN_MISSING_PARENTHESES", "YES");
        s.set ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR", "YES");
        s.set ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF", "YES");
        s.set ("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES");
        s.set ("GCC_WARN_UNDECLARED_SELECTOR", "YES");
        s.set ("GCC_WARN_UNINITIALIZED_AUTOS", "YES");
        s.set ("GCC_WARN_UNUSED_FUNCTION", "YES");
        s.set ("CLANG_ENABLE_OBJC_WEAK", "YES");
        s.set ("CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING", "YES");
        s.set ("CLANG_WARN_BOOL_CONVERSION", "YES");
        s.set ("CLANG_WARN_COMMA", "YES");
        s.set ("CLANG_WARN_CONSTANT_CONVERSION", "YES");
        s.set ("CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS", "YES");
        s.set ("CLANG_WARN_EMPTY_BODY", "YES");
        s.set ("CLANG_WARN_ENUM_CONVERSION", "YES");
        s.set ("CLANG_WARN_INFINITE_RECURSION", "YES");
        s.set ("CLANG_WARN_INT_CONVERSION", "YES");
        s.set ("CLANG_WARN_NON_LITERAL_NULL_CONVERSION", "YES");
        s.set ("CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF", "YES");
        s.set ("CLANG_WARN_OBJC_LITERAL_CONVERSION", "YES");
        s.set ("CLANG_WARN_RANGE_LOOP_ANALYSIS", "YES");
        s.set ("CLANG_WARN_STRICT_PROTOTYPES", "YES");
        s.set ("CLANG_WARN_SUSPICIOUS_MOVE", "YES");
        s.set ("CLANG_WARN_UNREACHABLE_CODE", "YES");
        s.set ("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES");
        s.set ("WARNING_CFLAGS", "\"-Wreorder\"");
        s.set ("GCC_INLINES_ARE_PRIVATE_EXTERN", projectType.isStaticLibrary() ? "NO" : "YES");

        // GCC_SYMBOLS_PRIVATE_EXTERN only takes effect if ENABLE_TESTABILITY is off
        s.set ("ENABLE_TESTABILITY", "NO");
        s.set ("GCC_SYMBOLS_PRIVATE_EXTERN", "YES");

        if (config.isDebug())
        {
            if (config.getMacOSArchitectureString() == macOSArch_Default)
                s.set ("ONLY_ACTIVE_ARCH", "YES");
        }

        s.set (iOS ? "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"" : "CODE_SIGN_IDENTITY",
               getCodeSigningIdentity (config).quoted());

        if (iOS)
        {
            s.set ("SDKROOT", "iphoneos" + config.getiOSBaseSDKString());
            s.set ("TARGETED_DEVICE_FAMILY", getDeviceFamilyString().quoted());
            s.set ("IPHONEOS_DEPLOYMENT_TARGET", config.getiOSDeploymentTargetString());
        }
        else
        {
            s.set ("SDKROOT", "macosx" + config.getMacOSBaseSDKString());
        }

        s.set ("ZERO_LINK", "NO");

        if (xcodeCanUseDwarf)
            s.set ("DEBUG_INFORMATION_FORMAT", "dwarf");

        s.set ("PRODUCT_NAME", replacePreprocessorTokens (config, config.getTargetBinaryNameString()).quoted());

        return s;
    }

    template<typename AddFrameworkFn>
    void addFrameworkList (const String& frameworksString, AddFrameworkFn&& addFrameworkFn) const
    {
        auto frameworks = StringArray::fromTokens (frameworksString, "\n\r", "\"'");
        frameworks.trim();

        for (auto& framework : frameworks)
        {
            auto frameworkID = addFrameworkFn (framework);

            for (auto& target : targets)
            {
                target->frameworkIDs.add (frameworkID);
                target->frameworkNames.add (framework);
            }
        }
    }

    void addFrameworks() const
    {
        if (! projectType.isStaticLibrary())
        {
            if (isInAppPurchasesEnabled())
                xcodeFrameworks.addIfNotAlreadyThere ("StoreKit");

            if (iOS)
            {
                if (isPushNotificationsEnabled())
                    xcodeFrameworks.addIfNotAlreadyThere ("UserNotifications");

                if (project.getEnabledModules().isModuleEnabled ("juce_video")
                    && project.isConfigFlagEnabled ("JUCE_USE_CAMERA", false))
                {
                    xcodeFrameworks.addIfNotAlreadyThere ("ImageIO");
                }
            }

            xcodeFrameworks.addTokens (getExtraFrameworksString(), ",;", "\"'");
            xcodeFrameworks.trim();

            auto s = xcodeFrameworks;

            for (auto& target : targets)
                s.addArray (target->xcodeFrameworks);

            if (! project.getConfigFlag ("JUCE_QUICKTIME").get())
                s.removeString ("QuickTime");

            s.trim();
            s.removeDuplicates (true);
            s.sort (true);

            // When building against the 10.15 SDK we need to make sure the
            // AudioUnit framework is linked before the AudioToolbox framework.
            auto audioUnitIndex = s.indexOf ("AudioUnit", false, 1);

            if (audioUnitIndex != -1)
            {
                s.remove (audioUnitIndex);
                s.insert (0, "AudioUnit");
            }

            for (auto& framework : s)
            {
                auto frameworkID = addFramework (framework);

                // find all the targets that are referring to this object
                for (auto& target : targets)
                {
                    if (xcodeFrameworks.contains (framework) || target->xcodeFrameworks.contains (framework))
                    {
                        target->frameworkIDs.add (frameworkID);
                        target->frameworkNames.add (framework);
                    }
                }
            }
        }

        addFrameworkList (getExtraCustomFrameworksString(),
                          [this] (const String& framework) { return addCustomFramework (framework); });

        addFrameworkList (getEmbeddedFrameworksString(),
                          [this] (const String& framework)
                          {
                              auto frameworkId = addEmbeddedFramework (framework);
                              embeddedFrameworkIDs.add (frameworkId);

                              return frameworkId;
                          });

        if (! embeddedFrameworkIDs.isEmpty())
            for (auto& target : targets)
                target->addCopyFilesPhase ("Embed Frameworks", embeddedFrameworkIDs, kFrameworksFolder);
    }

    void addCustomResourceFolders() const
    {
        StringArray folders;

        folders.addTokens (getCustomResourceFoldersString(), ":", "");
        folders.trim();
        folders.removeEmptyStrings();

        for (auto& crf : folders)
            addCustomResourceFolder (crf);
    }

    void addSubprojects() const
    {
        auto subprojectLines = StringArray::fromLines (getSubprojectsString());
        subprojectLines.removeEmptyStrings (true);

        struct SubprojectInfo
        {
            String path;
            StringArray buildProducts;
        };

        std::vector<SubprojectInfo> subprojects;

        for (auto& line : subprojectLines)
        {
            String subprojectPath (line.upToFirstOccurrenceOf (":", false, false));

            if (! subprojectPath.endsWith (".xcodeproj"))
                subprojectPath << ".xcodeproj";

            StringArray requestedBuildProducts (StringArray::fromTokens (line.fromFirstOccurrenceOf (":", false, false), ",;|", "\"'"));
            requestedBuildProducts.trim();
            subprojects.push_back ({ subprojectPath, requestedBuildProducts });
        }

        for (const auto& subprojectInfo : subprojects)
        {
            auto subprojectFile = getTargetFolder().getChildFile (subprojectInfo.path);

            if (! subprojectFile.isDirectory())
                continue;

            auto availableBuildProducts = XcodeProjectParser::parseBuildProducts (subprojectFile);

            if (! subprojectInfo.buildProducts.isEmpty())
            {
                auto newEnd = std::remove_if (availableBuildProducts.begin(), availableBuildProducts.end(),
                                              [&subprojectInfo] (const XcodeProjectParser::BuildProduct& item)
                                              {
                                                  return ! subprojectInfo.buildProducts.contains (item.name);
                                              });
                availableBuildProducts.erase (newEnd, availableBuildProducts.end());
            }

            if (availableBuildProducts.empty())
                continue;

            auto subprojectPath = build_tools::RelativePath (subprojectFile,
                                                             getTargetFolder(),
                                                             build_tools::RelativePath::buildTargetFolder).toUnixStyle();

            auto subprojectFileType = getFileType (subprojectPath);
            auto subprojectFileID = addFileOrFolderReference (subprojectPath, "<group>", subprojectFileType);
            subprojectFileIDs.add (subprojectFileID);

            StringArray productIDs;

            for (auto& buildProduct : availableBuildProducts)
            {
                auto buildProductFileType = getFileType (buildProduct.path);

                auto dependencyProxyID = addContainerItemProxy (subprojectFileID, buildProduct.name, "1");
                auto dependencyID = addTargetDependency (dependencyProxyID, buildProduct.name);
                subprojectDependencyIDs.add (dependencyID);

                auto containerItemProxyReferenceID = addContainerItemProxy (subprojectFileID, buildProduct.name, "2");
                auto proxyID = addReferenceProxy (containerItemProxyReferenceID, buildProduct.path, buildProductFileType);
                productIDs.add (proxyID);

                if (StringArray { "archive.ar", "compiled.mach-o.dylib", "wrapper.framework" }.contains (buildProductFileType))
                {
                    auto buildFileID = addBuildFile (FileOptions().withPath (buildProduct.path)
                                                                  .withFileRefID (proxyID)
                                                                  .withInhibitWarningsEnabled (true));

                    for (auto& target : targets)
                        target->frameworkIDs.add (buildFileID);

                    if (buildProductFileType == "wrapper.framework")
                    {
                        auto fileID = createID (subprojectPath + "_" + buildProduct.path + "_framework_buildref");

                        ValueTree v (fileID + " /* " + buildProduct.path + " */");
                        v.setProperty ("isa", "PBXBuildFile", nullptr);
                        v.setProperty ("fileRef", proxyID, nullptr);
                        v.setProperty ("settings", "{ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);

                        addObject (v);

                        embeddedFrameworkIDs.add (fileID);
                    }
                }
            }

            auto productGroupID = createFileRefID (subprojectFile.getFullPathName() + "_products");
            addGroup (productGroupID, "Products", productIDs);

            subprojectReferences.add ({ productGroupID, subprojectFileID });
        }
    }

    void addXcassets() const
    {
        auto customXcassetsPath = getCustomXcassetsFolderString();

        if (customXcassetsPath.isEmpty())
            addDefaultXcassetsFolders();
        else
            addCustomResourceFolder (customXcassetsPath, "folder.assetcatalog");
    }

    void addCustomResourceFolder (String folderPathRelativeToProjectFolder, const String fileType = "folder") const
    {
        auto folderPath = build_tools::RelativePath (folderPathRelativeToProjectFolder, build_tools::RelativePath::projectFolder)
                                       .rebased (projectFolder, getTargetFolder(), build_tools::RelativePath::buildTargetFolder)
                                       .toUnixStyle();

        auto fileRefID = createFileRefID (folderPath);

        addFileOrFolderReference (folderPath, "<group>", fileType);

        resourceIDs.add (addBuildFile (FileOptions().withPath (folderPath)
                                                    .withFileRefID (fileRefID)));

        resourceFileRefs.add (createFileRefID (folderPath));
    }

    //==============================================================================
    void writeProjectFile (OutputStream& output) const
    {
        output << "// !$*UTF8*$!\n{\n"
                  "\tarchiveVersion = 1;\n"
                  "\tclasses = {\n\t};\n"
                  "\tobjectVersion = 46;\n"
                  "\tobjects = {\n";

        StringArray objectTypes;

        for (auto it : objects)
            objectTypes.add (it.getType().toString());

        objectTypes.sort (false);

        for (const auto& objectType : objectTypes)
        {
            auto objectsWithType = objects.getChildWithName (objectType);
            auto requiresSingleLine = objectType == "PBXBuildFile" || objectType == "PBXFileReference";

            output << "\n/* Begin " << objectType << " section */\n";

            for (const auto& o : objectsWithType)
            {
                auto label = [&o]() -> String
                {
                    if (auto* objName = o.getPropertyPointer ("name"))
                        return " /* " + objName->toString() + " */";

                    return {};
                }();

                output << "\t\t" << o.getType().toString() << label << " = {";

                if (! requiresSingleLine)
                    output << "\n";

                for (int j = 0; j < o.getNumProperties(); ++j)
                {
                    auto propertyName = o.getPropertyName (j);
                    auto val = o.getProperty (propertyName).toString();

                    if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-@~\r\n\\#%^`*")
                                            && ! (val.trimStart().startsWithChar ('(')
                                                    || val.trimStart().startsWithChar ('{'))))
                        val = "\"" + val + "\"";

                    auto content = propertyName.toString() + " = " + val + ";";

                    if (requiresSingleLine)
                        content = content + " ";
                    else
                        content = "\t\t\t" + content + "\n";

                    output << content;
                }

                if (! requiresSingleLine)
                    output << "\t\t";

                output << "};\n";
            }

            output << "/* End " << objectType << " section */\n";
        }

        output << "\t};\n\trootObject = " << createID ("__root") << " /* Project object */;\n}\n";
    }

    String addFileReference (String pathString, String fileType = {}) const
    {
        String sourceTree ("SOURCE_ROOT");
        build_tools::RelativePath path (pathString, build_tools::RelativePath::unknown);

        if (pathString.startsWith ("${"))
        {
            sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
            pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
        }
        else if (path.isAbsolute())
        {
            sourceTree = "<absolute>";
        }

        return addFileOrFolderReference (pathString, sourceTree, fileType.isEmpty() ? getFileType (pathString) : fileType);
    }

    String addFileOrFolderReference (const String& pathString, String sourceTree, String fileType) const
    {
        auto fileRefID = createFileRefID (pathString);
        auto filename = build_tools::RelativePath (pathString, build_tools::RelativePath::unknown).getFileName();

        ValueTree v (fileRefID + " /* " + filename + " */");
        v.setProperty ("isa", "PBXFileReference", nullptr);
        v.setProperty ("lastKnownFileType", fileType, nullptr);
        v.setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), nullptr);
        v.setProperty ("path", pathString, nullptr);
        v.setProperty ("sourceTree", sourceTree, nullptr);

        addObject (v);

        return fileRefID;
    }

    String addContainerItemProxy (const String& subprojectID, const String& itemName, const String& proxyType) const
    {
        auto uniqueString = subprojectID + "_" + itemName + "_" + proxyType;
        auto objectID = createFileRefID (uniqueString);

        ValueTree v (objectID + " /* PBXContainerItemProxy */");
        v.setProperty ("isa", "PBXContainerItemProxy", nullptr);
        v.setProperty ("containerPortal", subprojectID, nullptr);
        v.setProperty ("proxyType", proxyType, nullptr);
        v.setProperty ("remoteGlobalIDString", createFileRefID (uniqueString + "_global"), nullptr);
        v.setProperty ("remoteInfo", itemName, nullptr);

        addObject (v);

        return objectID;
    }

    String addTargetDependency (const String& proxyID, const String& itemName) const
    {
        auto objectID = createFileRefID (proxyID + "_" + itemName + "_PBXTargetDependency");

        ValueTree v (objectID);
        v.setProperty ("isa", "PBXTargetDependency", nullptr);
        v.setProperty ("name", itemName, nullptr);
        v.setProperty ("targetProxy", proxyID, nullptr);

        addObject (v);

        return objectID;
    }

    String addReferenceProxy (const String& remoteRef, const String& path, const String& fileType) const
    {
        auto objectID = createFileRefID (remoteRef + "_" + path);

        ValueTree v (objectID + " /* " + path + " */");
        v.setProperty ("isa", "PBXReferenceProxy", nullptr);
        v.setProperty ("fileType", fileType, nullptr);
        v.setProperty ("path", path, nullptr);
        v.setProperty ("remoteRef", remoteRef, nullptr);
        v.setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);

        addObject (v);

        return objectID;
    }

private:
    struct FileOptions
    {
        FileOptions& withPath (const String& p)                             { path = p;                  return *this; }
        FileOptions& withRelativePath (const build_tools::RelativePath& p)  { path = p.toUnixStyle();    return *this; }
        FileOptions& withFileRefID (const String& fid)                      { fileRefID = fid;           return *this; }
        FileOptions& withCompilerFlags (const String& f)                    { compilerFlags = f;         return *this; }
        FileOptions& withCompilationEnabled (bool e)                        { compile = e;               return *this; }
        FileOptions& withAddToBinaryResourcesEnabled (bool e)               { addToBinaryResources = e;  return *this; }
        FileOptions& withAddToXcodeResourcesEnabled (bool e)                { addToXcodeResources = e;   return *this; }
        FileOptions& withInhibitWarningsEnabled (bool e)                    { inhibitWarnings = e;       return *this; }
        FileOptions& withSkipPCHEnabled (bool e)                            { skipPCH = e;               return *this; }
        FileOptions& withXcodeTarget (XcodeTarget* t)                       { xcodeTarget = t;           return *this; }

        String path;
        String fileRefID;
        String compilerFlags;
        bool compile = false;
        bool addToBinaryResources = false;
        bool addToXcodeResources = false;
        bool inhibitWarnings = false;
        bool skipPCH = false;
        XcodeTarget* xcodeTarget = nullptr;
    };

    static String getFileType (const String& filePath)
    {
        build_tools::RelativePath file (filePath, build_tools::RelativePath::unknown);

        if (file.hasFileExtension (cppFileExtensions))      return "sourcecode.cpp.cpp";
        if (file.hasFileExtension (".mm"))                  return "sourcecode.cpp.objcpp";
        if (file.hasFileExtension (".m"))                   return "sourcecode.c.objc";
        if (file.hasFileExtension (".c"))                   return "sourcecode.c.c";
        if (file.hasFileExtension (headerFileExtensions))   return "sourcecode.c.h";
        if (file.hasFileExtension (asmFileExtensions))      return "sourcecode.c.asm";
        if (file.hasFileExtension (".framework"))           return "wrapper.framework";
        if (file.hasFileExtension (".jpeg;.jpg"))           return "image.jpeg";
        if (file.hasFileExtension ("png;gif"))              return "image" + file.getFileExtension();
        if (file.hasFileExtension ("html;htm"))             return "text.html";
        if (file.hasFileExtension ("xml;zip;wav"))          return "file" + file.getFileExtension();
        if (file.hasFileExtension ("txt;rtf"))              return "text" + file.getFileExtension();
        if (file.hasFileExtension ("plist"))                return "text.plist.xml";
        if (file.hasFileExtension ("entitlements"))         return "text.plist.xml";
        if (file.hasFileExtension ("app"))                  return "wrapper.application";
        if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
        if (file.hasFileExtension ("xcodeproj"))            return "wrapper.pb-project";
        if (file.hasFileExtension ("a"))                    return "archive.ar";
        if (file.hasFileExtension ("dylib"))                return "compiled.mach-o.dylib";
        if (file.hasFileExtension ("xcassets"))             return "folder.assetcatalog";

        return "file" + file.getFileExtension();
    }

    String addFile (const FileOptions& opts) const
    {
        auto refID = addFileReference (opts.path);

        if (opts.compile || opts.addToXcodeResources)
        {
            auto fileID = addBuildFile (FileOptions (opts).withFileRefID (refID));

            if (opts.addToXcodeResources)
            {
                resourceIDs.add (fileID);
                resourceFileRefs.add (refID);
            }
        }

        return refID;
    }

    String addBuildFile (const FileOptions& opts) const
    {
        auto fileID = createID (opts.path + "buildref");
        auto filename = build_tools::RelativePath (opts.path, build_tools::RelativePath::unknown).getFileName();

        if (opts.compile)
        {
            if (opts.xcodeTarget != nullptr)
                opts.xcodeTarget->sourceIDs.add (fileID);
            else
                sourceIDs.add (fileID);
        }

        ValueTree v (fileID + " /* " + filename + " */");
        v.setProperty ("isa", "PBXBuildFile", nullptr);
        auto fileRefID = opts.fileRefID.isEmpty() ? createFileRefID (opts.path)
                                                  : opts.fileRefID;
        v.setProperty ("fileRef", fileRefID, nullptr);

        auto compilerFlags = [&opts]
        {
            return (opts.compilerFlags
                    + (opts.inhibitWarnings ? " -w" : String())
                    + (opts.skipPCH ? " -D" + BuildConfiguration::getSkipPrecompiledHeaderDefine() : String())).trim();
        }();

        if (compilerFlags.isNotEmpty())
            v.setProperty ("settings", "{ COMPILER_FLAGS = \"" + compilerFlags + "\"; }", nullptr);

        addObject (v);

        return fileID;
    }

    String addRezFile (const Project::Item& projectItem, const build_tools::RelativePath& path) const
    {
        auto refID = addFileReference (path.toUnixStyle());

        if (projectItem.isModuleCode())
        {
            if (auto* xcodeTarget = getTargetOfType (getProject().getTargetTypeFromFilePath (projectItem.getFile(), false)))
            {
                auto rezFileID = addBuildFile (FileOptions().withRelativePath (path)
                                                            .withFileRefID (refID)
                                                            .withXcodeTarget (xcodeTarget));

                xcodeTarget->rezFileIDs.add (rezFileID);

                return refID;
            }
        }

        return {};
    }

    void addEntitlementsFile (XcodeTarget& target) const
    {
        build_tools::EntitlementOptions options;

        options.type                            = target.type;
        options.isiOS                           = isiOS();
        options.isAudioPluginProject            = project.isAudioPluginProject();
        options.shouldEnableIAA                 = project.shouldEnableIAA();
        options.isiCloudPermissionsEnabled      = isiCloudPermissionsEnabled();
        options.isPushNotificationsEnabled      = isPushNotificationsEnabled();
        options.isAppGroupsEnabled              = isAppGroupsEnabled();
        options.isHardenedRuntimeEnabled        = isHardenedRuntimeEnabled();
        options.isAppSandboxEnabled             = isAppSandboxEnabled();
        options.isAppSandboxInhertianceEnabled  = isAppSandboxInhertianceEnabled();
        options.isNetworkingMulticastEnabled    = isNetworkingMulticastEnabled();
        options.appGroupIdString                = getAppGroupIdString();
        options.hardenedRuntimeOptions          = getHardenedRuntimeOptions();
        options.appSandboxOptions               = getAppSandboxOptions();

        const auto entitlementsFile = getTargetFolder().getChildFile (target.getEntitlementsFilename());
        build_tools::overwriteFileIfDifferentOrThrow (entitlementsFile, options.getEntitlementsFileContent());

        build_tools::RelativePath entitlementsPath (entitlementsFile, getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
        addFile (FileOptions().withRelativePath (entitlementsPath));
    }

    String addProjectItem (const Project::Item& projectItem) const
    {
        if (modulesGroup != nullptr && projectItem.getParent() == *modulesGroup)
            return addFileReference (rebaseFromProjectFolderToBuildTarget (getModuleFolderRelativeToProject (projectItem.getName())).toUnixStyle(),
                                     "folder");

        if (projectItem.isGroup())
        {
            StringArray childIDs;
            for (int i = 0; i < projectItem.getNumChildren(); ++i)
            {
                auto child = projectItem.getChild (i);

                auto childID = addProjectItem (child);

                if (childID.isNotEmpty() && ! child.shouldBeAddedToXcodeResources())
                    childIDs.add (childID);
            }

            if (childIDs.isEmpty())
                return {};

            return addGroup (projectItem, childIDs);
        }

        if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (*this))
        {
            auto itemPath = projectItem.getFilePath();
            build_tools::RelativePath path;

            if (itemPath.startsWith ("${") || build_tools::isAbsolutePath (itemPath))
                path = build_tools::RelativePath (itemPath, build_tools::RelativePath::unknown);
            else
                path = build_tools::RelativePath (projectItem.getFile(), getTargetFolder(), build_tools::RelativePath::buildTargetFolder);

            if (path.hasFileExtension (".r"))
                return addRezFile (projectItem, path);

            XcodeTarget* xcodeTarget = nullptr;
            if (projectItem.isModuleCode() && projectItem.shouldBeCompiled())
                xcodeTarget = getTargetOfType (project.getTargetTypeFromFilePath (projectItem.getFile(), false));

            return addFile (FileOptions().withRelativePath (path)
                                         .withCompilerFlags (compilerFlagSchemesMap[projectItem.getCompilerFlagSchemeString()].get())
                                         .withCompilationEnabled (projectItem.shouldBeCompiled())
                                         .withAddToBinaryResourcesEnabled (projectItem.shouldBeAddedToBinaryResources())
                                         .withAddToXcodeResourcesEnabled (projectItem.shouldBeAddedToXcodeResources())
                                         .withInhibitWarningsEnabled (projectItem.shouldInhibitWarnings())
                                         .withSkipPCHEnabled (isPCHEnabledForAnyConfigurations() && projectItem.shouldSkipPCH())
                                         .withXcodeTarget (xcodeTarget));
        }

        return {};
    }

    String addFramework (const String& frameworkName) const
    {
        auto path = frameworkName;
        auto isRelativePath = path.startsWith ("../");

        if (! build_tools::isAbsolutePath (path) && ! isRelativePath)
            path = "System/Library/Frameworks/" + path;

        if (! path.endsWithIgnoreCase (".framework"))
            path << ".framework";

        auto fileRefID = createFileRefID (path);

        addFileReference (((build_tools::isAbsolutePath (frameworkName) || isRelativePath) ? "" : "${SDKROOT}/") + path);
        frameworkFileIDs.add (fileRefID);

        return addBuildFile (FileOptions().withPath (path)
                                          .withFileRefID (fileRefID));
    }

    String addCustomFramework (String frameworkPath) const
    {
        if (! frameworkPath.endsWithIgnoreCase (".framework"))
            frameworkPath << ".framework";

        auto fileRefID = createFileRefID (frameworkPath);

        auto fileType = getFileType (frameworkPath);
        addFileOrFolderReference (frameworkPath, "<group>", fileType);

        frameworkFileIDs.add (fileRefID);

        return addBuildFile (FileOptions().withPath (frameworkPath)
                                          .withFileRefID (fileRefID));
    }

    String addEmbeddedFramework (const String& path) const
    {
        auto fileRefID = createFileRefID (path);
        auto filename = build_tools::RelativePath (path, build_tools::RelativePath::unknown).getFileName();

        auto fileType = getFileType (path);
        addFileOrFolderReference (path, "<group>", fileType);

        auto fileID = createID (path + "buildref");

        ValueTree v (fileID + " /* " + filename + " */");
        v.setProperty ("isa", "PBXBuildFile", nullptr);
        v.setProperty ("fileRef", fileRefID, nullptr);
        v.setProperty ("settings", "{ ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);

        addObject (v);

        frameworkFileIDs.add (fileRefID);

        return fileID;
    }

    void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs) const
    {
        ValueTree v (groupID);
        v.setProperty ("isa", "PBXGroup", nullptr);
        v.setProperty ("children", indentParenthesisedList (childIDs), nullptr);
        v.setProperty (Ids::name, groupName, nullptr);
        v.setProperty ("sourceTree", "<group>", nullptr);

        addObject (v);
    }

    String addGroup (const Project::Item& item, StringArray& childIDs) const
    {
        auto groupName = item.getName();
        auto groupID = getIDForGroup (item);
        addGroup (groupID, groupName, childIDs);
        return groupID;
    }

    void addProjectConfig (const String& configName, const StringArray& buildSettings) const
    {
        ValueTree v (createID ("projectconfigid_" + configName));
        v.setProperty ("isa", "XCBuildConfiguration", nullptr);
        v.setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
        v.setProperty (Ids::name, configName, nullptr);

        addObject (v);
    }

    void addConfigList (XcodeTarget& target, const String& listID) const
    {
        ValueTree v (listID);
        v.setProperty ("isa", "XCConfigurationList", nullptr);
        v.setProperty ("buildConfigurations", indentParenthesisedList (target.configIDs), nullptr);
        v.setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
        v.setProperty ("defaultConfigurationName", getConfiguration (0)->getName(), nullptr);

        addObject (v);
    }

    void addProjectConfigList (const String& listID) const
    {
        auto buildConfigs = objects.getChildWithName ("XCBuildConfiguration");
        jassert (buildConfigs.isValid());

        StringArray configIDs;

        for (const auto& child : buildConfigs)
            configIDs.add (child.getType().toString());

        ValueTree v (listID);
        v.setProperty ("isa", "XCConfigurationList", nullptr);
        v.setProperty ("buildConfigurations", indentParenthesisedList (configIDs), nullptr);
        v.setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
        v.setProperty ("defaultConfigurationName", getConfiguration (0)->getName(), nullptr);

        addObject (v);
    }

    void addProjectObject() const
    {
        ValueTree v (createID ("__root"));
        v.setProperty ("isa", "PBXProject", nullptr);
        v.setProperty ("attributes", indentBracedList (getProjectObjectAttributes()), nullptr);
        v.setProperty ("buildConfigurationList", createID ("__projList"), nullptr);
        v.setProperty ("compatibilityVersion", "Xcode 3.2", nullptr);
        v.setProperty ("hasScannedForEncodings", (int) 0, nullptr);
        v.setProperty ("knownRegions", indentParenthesisedList ({ "en", "Base" }), nullptr);
        v.setProperty ("mainGroup", createID ("__mainsourcegroup"), nullptr);
        v.setProperty ("projectDirPath", "\"\"", nullptr);

        if (! subprojectReferences.isEmpty())
        {
            StringArray projectReferences;

            for (auto& reference : subprojectReferences)
                projectReferences.add (indentBracedList ({ "ProductGroup = " + reference.productGroup, "ProjectRef = " + reference.projectRef }, 1));

            v.setProperty ("projectReferences", indentParenthesisedList (projectReferences), nullptr);
        }

        v.setProperty ("projectRoot", "\"\"", nullptr);

        v.setProperty ("targets", indentParenthesisedList (targetIDs), nullptr);

        addObject (v);
    }

    //==============================================================================
    void removeMismatchedXcuserdata() const
    {
        if (shouldKeepCustomXcodeSchemes())
            return;

        auto xcuserdata = getProjectBundle().getChildFile ("xcuserdata");

        if (! xcuserdata.exists())
            return;

        if (! xcuserdataMatchesTargets (xcuserdata))
        {
            xcuserdata.deleteRecursively();
            getProjectBundle().getChildFile ("xcshareddata").getChildFile ("xcschemes").deleteRecursively();
            getProjectBundle().getChildFile ("project.xcworkspace").deleteRecursively();
        }
    }

    bool xcuserdataMatchesTargets (const File& xcuserdata) const
    {
        for (auto& plist : xcuserdata.findChildFiles (File::findFiles, true, "xcschememanagement.plist"))
            if (! xcschemeManagementPlistMatchesTargets (plist))
                return false;

        return true;
    }

    static StringArray parseNamesOfTargetsFromPlist (const XmlElement& dictXML)
    {
        for (auto* schemesKey : dictXML.getChildWithTagNameIterator ("key"))
        {
            if (schemesKey->getAllSubText().trim().equalsIgnoreCase ("SchemeUserState"))
            {
                if (auto* dict = schemesKey->getNextElement())
                {
                    if (dict->hasTagName ("dict"))
                    {
                        StringArray names;

                        for (auto* key : dict->getChildWithTagNameIterator ("key"))
                            names.add (key->getAllSubText().upToLastOccurrenceOf (".xcscheme", false, false).trim());

                        names.sort (false);
                        return names;
                    }
                }
            }
        }

        return {};
    }

    StringArray getNamesOfTargets() const
    {
        StringArray names;

        for (auto& target : targets)
            names.add (target->getXcodeSchemeName());

        names.sort (false);
        return names;
    }

    bool xcschemeManagementPlistMatchesTargets (const File& plist) const
    {
        if (auto xml = parseXML (plist))
            if (auto* dict = xml->getChildByName ("dict"))
                return parseNamesOfTargetsFromPlist (*dict) == getNamesOfTargets();

        return false;
    }

    StringArray getProjectObjectAttributes() const
    {
        std::map<String, String> attributes;

        attributes["LastUpgradeCheck"] = "1310";
        attributes["ORGANIZATIONNAME"] = getProject().getCompanyNameString().quoted();

        if (projectType.isGUIApplication() || projectType.isAudioPlugin())
        {
            StringArray targetAttributes;

            for (auto& target : targets)
                targetAttributes.add (target->getTargetAttributes());

            attributes["TargetAttributes"] = indentBracedList (targetAttributes, 1);
        }

        StringArray result;

        for (const auto& attrib : attributes)
            result.add (attrib.first + " = " + attrib.second);

        return result;
    }

    //==============================================================================
    void writeDefaultLaunchStoryboardFile() const
    {
        const auto storyboardFile = getTargetFolder().getChildFile (getDefaultLaunchStoryboardName() + ".storyboard");

        build_tools::writeStreamToFile (storyboardFile, [&] (MemoryOutputStream& mo)
        {
            mo << String (BinaryData::LaunchScreen_storyboard);
        });

        addLaunchStoryboardFileReference (build_tools::RelativePath (storyboardFile,
                                                                     getTargetFolder(),
                                                                     build_tools::RelativePath::buildTargetFolder));
    }

    void addLaunchStoryboardFileReference (const build_tools::RelativePath& relativePath) const
    {
        auto path = relativePath.toUnixStyle();

        auto refID  = addFileReference (path);
        auto fileID = addBuildFile (FileOptions().withPath (path)
                                                 .withFileRefID (refID));

        resourceIDs.add (fileID);
        resourceFileRefs.add (refID);
    }

    void addDefaultXcassetsFolders() const
    {
        const auto assetsPath = build_tools::createXcassetsFolderFromIcons (getIcons(),
                                                                            getTargetFolder(),
                                                                            project.getProjectFilenameRootString());
        addFileReference (assetsPath.toUnixStyle());
        resourceIDs.add (addBuildFile (FileOptions().withRelativePath (assetsPath)));
        resourceFileRefs.add (createFileRefID (assetsPath));
    }

    //==============================================================================
    static String indentBracedList        (const StringArray& list, int depth = 0) { return indentList (list, '{', '}', ";", depth, true); }
    static String indentParenthesisedList (const StringArray& list, int depth = 0) { return indentList (list, '(', ')', ",", depth, false); }

    static String indentList (StringArray list, char openBracket, char closeBracket, const String& separator, int extraTabs, bool shouldSort)
    {
        auto content = [extraTabs, shouldSort, &list, &separator]() -> String
        {
            if (list.isEmpty())
                return "";

            if (shouldSort)
                list.sort (true);

            auto tabs = String::repeatedString ("\t", extraTabs + 4);
            return tabs + list.joinIntoString (separator + "\n" + tabs) + separator + "\n";
        }();

        return openBracket + String ("\n")
            + content
            + String::repeatedString ("\t", extraTabs + 3) + closeBracket;
    }

    String createID (String rootString) const
    {
        if (rootString.startsWith ("${"))
            rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);

        rootString += project.getProjectUIDString();

        return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
    }

    String createFileRefID (const build_tools::RelativePath& path) const { return createFileRefID (path.toUnixStyle()); }
    String createFileRefID (const String& path) const                    { return createID ("__fileref_" + path); }
    String getIDForGroup (const Project::Item& item) const               { return createID (item.getID()); }

    bool shouldFileBeCompiledByDefault (const File& file) const override
    {
        return file.hasFileExtension (sourceFileExtensions);
    }

    //==============================================================================
    void updateOldOrientationSettings()
    {
        jassert (iOS);

        StringArray orientationSettingStrings { getSetting (Ids::iPhoneScreenOrientation).getValue().toString(),
                                                getSetting (Ids::iPadScreenOrientation).getValue().toString() };

        for (int i = 0; i < 2; ++i)
        {
            auto& settingsString = orientationSettingStrings[i];

            if (settingsString.isNotEmpty())
            {
                Array<var> orientations;

                if (settingsString.contains ("portrait"))   orientations.add ("UIInterfaceOrientationPortrait");
                if (settingsString.contains ("landscape"))  orientations.addArray ({ "UIInterfaceOrientationLandscapeLeft",
                                                                                     "UIInterfaceOrientationLandscapeRight" });

                if (! orientations.isEmpty())
                {
                    if (i == 0)
                        iPhoneScreenOrientationValue = orientations;
                    else
                        iPadScreenOrientationValue = orientations;
                }
            }
        }
    }

    void addObject (ValueTree data) const
    {
        if (auto* type = data.getPropertyPointer ("isa"))
        {
            auto objs = objects.getOrCreateChildWithName (type->toString(), nullptr);
            auto objectID = data.getType();
            auto numChildren = objs.getNumChildren();

            for (int i = 0; i < numChildren; ++i)
            {
                auto obj = objs.getChild (i);
                auto childID = obj.getType();

                if (objectID < childID)
                {
                    objs.addChild (data, i, nullptr);
                    return;
                }

                if (objectID == childID)
                {
                    jassert (obj.isEquivalentTo (data));
                    return;
                }
            }

            objs.appendChild (data, nullptr);
            return;
        }

        jassertfalse;
    }

    //==============================================================================
    friend class CLionProjectExporter;

    bool xcodeCanUseDwarf;
    OwnedArray<XcodeTarget> targets;

    mutable ValueTree objects { "objects" };

    mutable StringArray resourceIDs, sourceIDs, targetIDs, frameworkFileIDs, embeddedFrameworkIDs,
                        rezFileIDs, resourceFileRefs, subprojectFileIDs, subprojectDependencyIDs;

    struct SubprojectReferenceInfo
    {
        String productGroup, projectRef;
    };

    mutable Array<SubprojectReferenceInfo> subprojectReferences;
    mutable File menuNibFile, iconFile;
    mutable StringArray buildProducts;

    const bool iOS;

    ValueWithDefault applicationCategoryValue,
                     customPListValue, pListPrefixHeaderValue, pListPreprocessValue,
                     subprojectsValue,
                     validArchsValue,
                     extraFrameworksValue, frameworkSearchPathsValue, extraCustomFrameworksValue, embeddedFrameworksValue,
                     postbuildCommandValue, prebuildCommandValue,
                     duplicateAppExResourcesFolderValue, iosDeviceFamilyValue, iPhoneScreenOrientationValue,
                     iPadScreenOrientationValue, customXcodeResourceFoldersValue, customXcassetsFolderValue,
                     appSandboxValue, appSandboxInheritanceValue, appSandboxOptionsValue,
                     hardenedRuntimeValue, hardenedRuntimeOptionsValue,
                     microphonePermissionNeededValue, microphonePermissionsTextValue,
                     cameraPermissionNeededValue, cameraPermissionTextValue,
                     bluetoothPermissionNeededValue, bluetoothPermissionTextValue,
                     sendAppleEventsPermissionNeededValue, sendAppleEventsPermissionTextValue,
                     uiFileSharingEnabledValue, uiSupportsDocumentBrowserValue, uiStatusBarHiddenValue, uiRequiresFullScreenValue, documentExtensionsValue, iosInAppPurchasesValue,
                     iosContentSharingValue, iosBackgroundAudioValue, iosBackgroundBleValue, iosPushNotificationsValue, iosAppGroupsValue, iCloudPermissionsValue,
                     networkingMulticastValue, iosDevelopmentTeamIDValue, iosAppGroupsIDValue, keepCustomXcodeSchemesValue, useHeaderMapValue, customLaunchStoryboardValue,
                     exporterBundleIdentifierValue, suppressPlistResourceUsageValue, useLegacyBuildSystemValue, buildNumber;

    JUCE_DECLARE_NON_COPYABLE (XcodeProjectExporter)
};