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
//! Project management and build utilities for `WaterUI` CLI.
use cargo_toml::Manifest as CargoManifest;
use futures_util::FutureExt as _;
use futures_util::future::{BoxFuture, Shared};
use tracing::info;
use crate::build::{BuildProgress, RustLinkage};
use crate::framework::{
FrameworkChannel, ResolvedFramework, validate_local_cli, validate_resolved_cli,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpenMode {
Full,
PreviewBuild,
}
/// What `cargo metadata` reports about the tree a project builds in.
///
/// Resolved once per [`Project`] and shared by everything that needs it, so
/// one `cargo metadata` run serves the target directory and the lockfile.
#[derive(Debug, Clone)]
struct CargoLayout {
target_dir: PathBuf,
/// Root of the Cargo workspace the project belongs to — the project itself
/// when it is not a workspace member. This is where its `Cargo.lock` lives.
workspace_root: PathBuf,
}
enum CargoResolution {
Local,
Locked,
Update,
}
fn spawn_cargo_layout_resolution(
current_dir: &Path,
framework: Option<ResolvedFramework>,
local: bool,
) -> Shared<BoxFuture<'static, Result<CargoLayout, String>>> {
let current_dir = current_dir.to_path_buf();
let mode = if local {
CargoResolution::Local
} else if framework.is_some() {
CargoResolution::Locked
} else {
CargoResolution::Update
};
smol::spawn(async move {
resolve_cargo_layout(¤t_dir, framework, mode)
.await
.map_err(|error| error.to_string())
})
.boxed()
.shared()
}
/// Represents a `WaterUI` project with its manifest and crate information.
#[derive(Debug, Clone)]
pub struct Project {
root: PathBuf,
manifest: Manifest,
crate_name: CrateName,
cargo_layout: Shared<BoxFuture<'static, Result<CargoLayout, String>>>,
linked_packages: Arc<async_lock::OnceCell<Result<BTreeMap<String, String>, String>>>,
enabled_features: Arc<async_lock::OnceCell<Result<BTreeSet<String>, String>>>,
managed_backends_root: PathBuf,
}
impl Project {
/// Select or update a framework channel and persist its exact dependency selection.
///
/// # Errors
/// Returns an error when resolution, native-project merging, or dependency verification fails.
pub async fn select_channel(
path: impl AsRef<Path>,
channel: FrameworkChannel,
) -> eyre::Result<Self> {
let path = smol::fs::canonicalize(path.as_ref()).await?;
let water_path = path.join("Water.toml");
let cargo_path = path.join("Cargo.toml");
let mut water: toml_edit::DocumentMut =
smol::fs::read_to_string(&water_path).await?.parse()?;
let previous: Manifest = toml::from_str(&water.to_string())?;
let mut cargo: toml_edit::DocumentMut =
smol::fs::read_to_string(&cargo_path).await?.parse()?;
let crate_name = CrateName::try_from(
cargo["package"]["name"]
.as_str()
.ok_or_else(|| eyre::eyre!("channel selection requires a project Cargo.toml"))?,
)
.map_err(|error| eyre::eyre!(error))?;
let (framework, lockfile) = ResolvedFramework::resolve(channel).await?;
// A configured backend whose scaffold packages the target channel
// withholds could never be regenerated — refuse the switch before a
// manifest is rewritten.
for (configured, backend) in [
(previous.backends.gtk4().is_some(), TargetBackend::Gtk4),
(
previous.backends.hydrolysis().is_some(),
TargetBackend::Hydrolysis,
),
(previous.backends.winui().is_some(), TargetBackend::WinUi),
(previous.backends.esp32().is_some(), TargetBackend::Dew),
] {
if configured {
for package in backend.scaffold_packages() {
framework.require_distributable(package)?;
}
}
}
let mut next = previous.clone();
next.waterui_path = None;
next.framework = Some(framework.clone());
let mut updates =
templates::framework_updates(&path, &previous, &next, &crate_name).await?;
framework.update_manifest(&mut cargo, &templates::project_patches(&path, &previous)?)?;
water.remove("waterui_path");
water["framework"] =
toml_edit::Item::Table(toml_edit::ser::to_document(&framework)?.into_table());
updates.push((water_path, water.to_string().into_bytes()));
updates.push((cargo_path, cargo.to_string().into_bytes()));
if let Some(lockfile) = lockfile {
updates.push((
path.join("Cargo.lock"),
framework.cargo_lock(&lockfile)?.to_string().into_bytes(),
));
updates.push((path.join("Water.lock"), lockfile));
}
let mut updates: Vec<_> = updates
.into_iter()
.map(|(file, contents)| (file, Some(contents)))
.collect();
if channel == FrameworkChannel::Stable
&& previous
.framework
.as_ref()
.is_some_and(|previous| previous.channel() != Some(FrameworkChannel::Stable))
{
updates.push((path.join("Water.lock"), None));
}
apply_channel_selection(&path, framework, updates).await?;
Self::open_for_preview_build(path).await.map_err(Into::into)
}
/// Run the `WaterUI` project on the specified device.
///
/// This method handles building, packaging, and running the project.
///
/// # Arguments
/// - `backend`: The backend to use for building and packaging
/// - `platform`: The target platform to build for
/// - `device`: The device to run on
///
/// # Errors
/// - If any step in the build, package, or run process fails.
pub async fn run<B: Backend, D: Device>(
&self,
backend: &B,
platform: TargetPlatform,
device: D,
) -> Result<Running, FailToRun> {
self.run_with_options(backend, platform, device, RunOptions::new(), None)
.await
}
/// Run the `WaterUI` project with explicit run options.
///
/// This allows callers (like preview) to inject extra environment variables.
/// `progress`, when given, receives cargo compile events from both the
/// library build and the packaging pass's asset-manifest compile.
///
/// # Errors
/// Returns an error if building, packaging, or launching the app fails.
pub async fn run_with_options<B: Backend, D: Device>(
&self,
backend: &B,
platform: TargetPlatform,
device: D,
run_options: RunOptions,
progress: Option<BuildProgress>,
) -> Result<Running, FailToRun> {
let mut build_options = BuildOptions::development(BuildProfile::Debug);
if let Some(progress) = &progress {
build_options = build_options.with_progress(progress.clone());
}
// Build rust library for the target platform
backend
.build(self, platform, build_options)
.await
.map_err(FailToRun::Build)?;
let mut package_options = PackageOptions::development();
if let Some(progress) = progress {
package_options = package_options.with_progress(progress);
}
// Package the build artifacts for the target platform
let artifact = backend
.package(self, platform, package_options)
.await
.map_err(FailToRun::Package)?;
Self::run_packaged(device, artifact, run_options).await
}
/// Run the Android backend for the specific target ABI of the device.
///
/// This is required because Android packaging is ABI-dependent (e.g., `x86_64` emulator vs
/// `arm64-v8a` physical device).
///
/// `build_options` decides the Rust runtime linkage: a support app that
/// `dlopen`s `WaterUI` modules (the preview app) must pass
/// [`BuildOptions::with_dynamic_module_loading`] so the shared runtime is
/// built and packaged; a standalone app links it in.
///
/// # Errors
/// Returns an error if building, packaging, or launching the Android app fails.
pub async fn run_android_with_options<D: Device + AndroidAbiProvider>(
&self,
_backend: &AndroidBackend,
device: D,
run_options: RunOptions,
build_options: BuildOptions,
progress: Option<BuildProgress>,
) -> Result<Running, FailToRun> {
let abi = device.android_abi();
self.browser_runtime_plan(TargetPlatform::Android, TargetBackend::Android)
.await
.map_err(FailToRun::Build)?;
AndroidPlatform::clean_jni_libs(self)
.await
.map_err(FailToRun::Build)?;
let mut build_options = build_options;
if let Some(progress) = &progress {
build_options = build_options.with_progress(progress.clone());
}
AndroidPlatform::new(abi)
.build(self, build_options)
.await
.map_err(FailToRun::Build)?;
let mut package_options = PackageOptions::development();
if let Some(progress) = progress {
package_options = package_options.with_progress(progress);
}
let artifact = AndroidPlatform::package_with_abis(self, package_options, &[abi])
.await
.map_err(FailToRun::Package)?;
Self::run_packaged(device, artifact, run_options).await
}
async fn run_packaged<D: Device>(
device: D,
artifact: Artifact,
run_options: RunOptions,
) -> Result<Running, FailToRun> {
info!("Running on device");
let running = device
.run(&crate::toolchain::Host::current(), artifact, run_options)
.await?;
Ok(running)
}
/// Get the root path of the project.
///
/// Same as the directory containing `Water.toml`.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// Get the target directory for Rust build artifacts.
///
/// # Errors
///
/// Returns an error when Cargo metadata cannot resolve the target directory.
pub async fn target_dir(&self) -> eyre::Result<PathBuf> {
Ok(self.cargo_layout().await?.target_dir)
}
/// The lockfile the application builds against.
///
/// The workspace `Cargo.lock` when the project is a workspace member,
/// otherwise the project's own. It need not exist yet: a project that has
/// never been resolved has none.
///
/// # Errors
///
/// Returns an error when Cargo metadata cannot resolve the workspace.
pub async fn lockfile_path(&self) -> eyre::Result<PathBuf> {
Ok(self.cargo_layout().await?.workspace_root.join("Cargo.lock"))
}
async fn cargo_layout(&self) -> eyre::Result<CargoLayout> {
self.cargo_layout
.clone()
.await
.map_err(|error| eyre::eyre!(error))
}
/// Resolve the Cargo target directory every generated backend crate builds into.
///
/// The directory is shared by every project on the machine — one
/// `~/.water/build_cache/target` subtree — because Cargo already keys each
/// compiled unit by target triple, resolved features, and profile: a second
/// project's build reuses the dependency graph the first one compiled
/// instead of cold-building it, the way sccache-equipped machines behave.
/// The shared root sits beside the per-project managed containers rather
/// than inside one: generated backend sources are deleted and regenerated
/// whenever the CLI's scaffold templates change, while compiled artifacts
/// do not become stale for that reason — keeping them together meant one
/// CLI upgrade discarded the compiled dependency graph of every project on
/// the machine.
///
/// One directory serves every backend, platform, and feature set of a
/// linkage: switching backends only rebuilds the units the two graphs do
/// not share — measured on an example app, over 80% of the Apple FFI graph
/// resolves identically to the Hydrolysis graph and is reused as-is.
/// Builds must therefore agree on everything Cargo hashes into every unit —
/// pass an explicit `--target` and keep final-artifact link flags out of
/// `RUSTFLAGS` (see `RustBuild::with_final_rustc_arg`) — or two variants
/// sharing this directory re-fingerprint each other's entire dependency
/// graph on every switch.
///
/// Linkage is the one axis Cargo cannot separate: shared-runtime development
/// builds carry `-Cprefer-dynamic -Crpath` in `RUSTFLAGS` and static packaging
/// builds carry none, so each linkage keeps its own directory instead of the two
/// variants invalidating each other whenever a developer alternates `water run`
/// and `water package`.
///
/// # Errors
///
/// Returns an error when the shared build-cache directory cannot be resolved.
pub async fn water_target_dir(&self, linkage: RustLinkage) -> eyre::Result<PathBuf> {
let variant = match linkage {
RustLinkage::SharedRuntime => "shared",
RustLinkage::Static => "static",
};
Ok(crate::water_dir::shared_target_dir().await?.join(variant))
}
/// Resolve an isolated target directory for a backend built by a different Rust
/// toolchain.
///
/// Cargo hashes the compiler into every unit fingerprint, so a backend that pins
/// its own toolchain (ESP32's Espressif Rust fork) would invalidate the host
/// units of [`Self::water_target_dir`] on every switch if it shared the directory.
///
/// # Errors
///
/// Returns an error when the shared build-cache directory cannot be resolved.
pub async fn toolchain_target_dir(&self, toolchain: &str) -> eyre::Result<PathBuf> {
Ok(crate::water_dir::shared_target_dir()
.await?
.join(format!("toolchain-{toolchain}")))
}
/// Resolve the target directory the project's host-side rlib builds into.
///
/// `build_host_rlib` compiles the user crate for the host to read its
/// `waterui_meta_*` symbols. That compile shares the dependency graph with
/// every other project's host build, so it lives beside the backend
/// variants in the shared target root rather than in the project's own
/// `target/`.
///
/// # Errors
///
/// Returns an error when the shared build-cache directory cannot be resolved.
pub async fn host_target_dir(&self) -> eyre::Result<PathBuf> {
crate::water_dir::shared_host_target_dir().await
}
/// Get the backends configured for the project.
#[must_use]
pub const fn backends(&self) -> &Backends {
&self.manifest.backends
}
/// Get the crate name of the project.
#[must_use]
pub const fn crate_name(&self) -> &CrateName {
&self.crate_name
}
/// Get configured or default FFI crate name for app mode.
///
/// The default is tagged with this project's root — see
/// [`generated_crate_name`]; an explicit `[crates]` override is verbatim.
#[must_use]
pub fn ffi_crate_name(&self) -> CrateName {
self.app_crate_overrides()
.and_then(|crates| crates.ffi.clone())
.unwrap_or_else(|| generated_crate_name(&self.crate_name, "ffi", &self.root))
}
/// Get configured preview wrapper crate name for preview dylib builds.
#[must_use]
pub fn preview_ffi_crate_name(&self) -> CrateName {
generated_crate_name(&self.crate_name, "preview-ffi", &self.root)
}
/// Get the crate root path used to build preview dylibs.
#[must_use]
pub fn preview_dylib_crate_path(&self, workspace_root: &Path) -> PathBuf {
self.preview_ffi_crate_path(workspace_root)
}
/// Get the crate name used to build preview dylibs.
#[must_use]
pub fn preview_dylib_crate_name(&self) -> CrateName {
self.preview_ffi_crate_name()
}
/// Get configured or default GTK backend crate name for app mode.
#[must_use]
pub fn gtk_backend_crate_name(&self) -> CrateName {
self.app_crate_overrides()
.and_then(|crates| crates.gtk.clone())
.unwrap_or_else(|| generated_crate_name(&self.crate_name, "gtk4", &self.root))
}
/// Get configured or default hydrolysis backend crate name for app mode.
#[must_use]
pub fn hydrolysis_backend_crate_name(&self) -> CrateName {
self.app_crate_overrides()
.and_then(|crates| crates.hydrolysis.clone())
.unwrap_or_else(|| generated_crate_name(&self.crate_name, "hydrolysis", &self.root))
}
/// Get configured or default `WinUI` backend crate name for app mode.
#[must_use]
pub fn winui_backend_crate_name(&self) -> CrateName {
self.app_crate_overrides()
.and_then(|crates| crates.winui.clone())
.unwrap_or_else(|| generated_crate_name(&self.crate_name, "winui", &self.root))
}
/// Get the generated ESP32 firmware harness crate name.
#[must_use]
pub fn esp32_backend_crate_name(&self) -> CrateName {
generated_crate_name(&self.crate_name, "esp32", &self.root)
}
/// Get the crate name of the generated experimental TUI launcher.
#[must_use]
pub fn tui_backend_crate_name(&self) -> CrateName {
generated_crate_name(&self.crate_name, "tui", &self.root)
}
/// The executable name a packaged backend binary ships under: the
/// configured `[crates]` override verbatim, or `<crate>-<suffix>` when
/// the crate is generated.
///
/// [`generated_crate_name`]'s project-root tag exists to keep a shared
/// Cargo target directory unambiguous; it is internal to the build and
/// must never name a shipped executable.
fn shipped_backend_binary_name(
&self,
suffix: &str,
configured: Option<&CrateName>,
) -> CrateName {
configured
.cloned()
.unwrap_or_else(|| self.crate_name.with_suffix(suffix))
}
/// The executable name the packaged GTK4 binary ships under.
#[must_use]
pub fn gtk4_binary_name(&self) -> CrateName {
self.shipped_backend_binary_name(
"gtk4",
self.app_crate_overrides()
.and_then(|crates| crates.gtk.as_ref()),
)
}
/// The executable name the packaged hydrolysis binary ships under.
#[must_use]
pub fn hydrolysis_binary_name(&self) -> CrateName {
self.shipped_backend_binary_name(
"hydrolysis",
self.app_crate_overrides()
.and_then(|crates| crates.hydrolysis.as_ref()),
)
}
/// The executable name the packaged `WinUI` binary ships under.
#[must_use]
pub fn winui_binary_name(&self) -> CrateName {
self.shipped_backend_binary_name(
"winui",
self.app_crate_overrides()
.and_then(|crates| crates.winui.as_ref()),
)
}
/// The name the packaged ESP32 firmware image ships under.
#[must_use]
pub fn esp32_binary_name(&self) -> CrateName {
self.shipped_backend_binary_name("esp32", None)
}
/// Get package type declared in `Water.toml`.
#[must_use]
pub const fn package_type(&self) -> PackageType {
self.manifest.package.package_type
}
/// Returns true when this project is a playground project.
#[must_use]
pub fn is_playground(&self) -> bool {
self.package_type() == PackageType::Playground
}
/// Get the Apple backend configuration if available.
#[must_use]
pub const fn apple_backend(&self) -> Option<&AppleBackend> {
self.manifest.backends.apple()
}
/// Get the full path to a backend directory.
///
/// Returns `project.root() / backends.path / B::DEFAULT_PATH`.
#[must_use]
pub fn backend_path<B: Backend>(&self) -> PathBuf {
self.managed_backends_root.join(B::DEFAULT_PATH)
}
/// Get the relative path to a backend directory from project root.
///
/// Returns `backends.path / B::DEFAULT_PATH`.
#[must_use]
pub fn backend_relative_path<B: Backend>(&self) -> PathBuf {
self.manifest.backends.path().join(B::DEFAULT_PATH)
}
/// Get the full path to the managed native FFI companion crate.
#[must_use]
pub fn ffi_crate_path(&self) -> PathBuf {
self.managed_backends_root.join("ffi")
}
/// Directory name this project's preview module occupies inside a workspace.
#[must_use]
pub fn preview_module_member_path(&self) -> PathBuf {
Path::new(crate::templates::PREVIEW_MODULES_DIR)
.join(self.preview_ffi_crate_name().to_string())
}
/// Get the full path to the managed preview-only companion crate.
///
/// The crate lives inside the support runtime's workspace rather than this
/// project's build cache, because a preview module and the runtime it is
/// loaded into must come out of one Cargo resolution to agree on the
/// `-C metadata` hash mangled into every symbol.
#[must_use]
pub fn preview_ffi_crate_path(&self, workspace_root: &Path) -> PathBuf {
workspace_root.join(self.preview_module_member_path())
}
/// Get the relative path to the managed native FFI companion crate from project root.
#[must_use]
pub fn ffi_crate_relative_path(&self) -> PathBuf {
self.manifest.backends.path().join("ffi")
}
/// Get the Android backend configuration if available.
#[must_use]
pub const fn android_backend(&self) -> Option<&AndroidBackend> {
self.manifest.backends.android()
}
/// Get the GTK4 backend configuration if available.
#[must_use]
pub const fn gtk4_backend(&self) -> Option<&crate::gtk4::backend::Gtk4Backend> {
self.manifest.backends.gtk4()
}
/// Get the hydrolysis backend configuration if available.
#[must_use]
pub const fn hydrolysis_backend(
&self,
) -> Option<&crate::hydrolysis::backend::HydrolysisBackend> {
self.manifest.backends.hydrolysis()
}
/// Get the `WinUI` backend configuration if available.
#[must_use]
pub const fn winui_backend(&self) -> Option<&crate::winui::backend::WinUiBackend> {
self.manifest.backends.winui()
}
/// Get the ESP32 backend configuration if available.
#[must_use]
pub const fn esp32_backend(&self) -> Option<&crate::esp32::backend::Esp32Backend> {
self.manifest.backends.esp32()
}
/// Get the manifest of the project.
#[must_use]
pub const fn manifest(&self) -> &Manifest {
&self.manifest
}
/// The framework this project resolves generated code against — the
/// channel selection `Water.toml` records, or the checkout `waterui_path`
/// names.
///
/// # Errors
///
/// Returns an error when the manifest records no framework source, or the
/// local checkout's framework facts cannot be read.
pub async fn resolved_framework(&self) -> eyre::Result<ResolvedFramework> {
ResolvedFramework::for_manifest(self.manifest(), &self.root).await
}
/// Assert the selected framework channel distributes every scaffold
/// package `backend` links — the git-pinned experimental set `stable`
/// withholds. Runs before the backend writes a file, so a withheld
/// package fails the init with the channel fix rather than partway
/// through the generated tree.
async fn require_distributable_backend(
&self,
backend: TargetBackend,
) -> Result<(), crate::backend::FailToInitBackend> {
let packages = backend.scaffold_packages();
if packages.is_empty() {
return Ok(());
}
let framework = self
.resolved_framework()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
for package in packages {
framework
.require_distributable(package)
.map_err(crate::backend::FailToInitBackend::Config)?;
}
Ok(())
}
/// Returns whether the packaged application links `package_name`.
///
/// Development-only and build-only dependencies are excluded because they
/// do not become part of the packaged application. The resolved graph is
/// cached so backend regeneration and scaffolding share one Cargo metadata
/// resolution.
///
/// # Errors
///
/// Returns an error when Cargo cannot resolve the application graph or
/// omits a package referenced by that graph.
pub async fn links_runtime_package(&self, package_name: &str) -> eyre::Result<bool> {
let project_root = self.root.clone();
let cargo_layout = self.cargo_layout.clone();
let packages = self
.linked_packages
.get_or_init(|| async move {
cargo_layout.await?;
resolve_linked_runtime_packages(project_root, false)
.await
.map_err(|error| error.to_string())
})
.await;
match packages {
Ok(packages) => Ok(packages.contains_key(package_name)),
Err(error) => Err(eyre::eyre!(error.clone())),
}
}
/// Whether the application's graph turns on the standard `WebView`
/// component.
///
/// The signal is a `webview` feature enabled inside the application's own
/// subtree — the facade's `webview` feature, or an engine crate's `webview`
/// hookup — resolved by `cargo tree --edges features`. The
/// `waterui-webview` *package* cannot be the signal: engines link it for
/// the shared asset-server types a `ChromiumPage` answers over CDP
/// (#586), so its presence no longer means the component is used.
///
/// # Errors
///
/// Returns an error when Cargo cannot resolve the application graph or
/// omits a package referenced by that graph.
pub async fn uses_standard_webview(&self) -> eyre::Result<bool> {
let project_root = self.root.clone();
let cargo_layout = self.cargo_layout.clone();
let features = self
.enabled_features
.get_or_init(|| async move {
cargo_layout.await?;
resolve_enabled_features(project_root, false)
.await
.map_err(|error| error.to_string())
})
.await;
match features {
Ok(features) => Ok(features.contains("webview")),
Err(error) => Err(eyre::eyre!(error.clone())),
}
}
/// Resolve and validate the standard `WebView` engine for a build.
///
/// The application's own dependency graph is the selection: linking
/// `waterui-browser-cef` or `waterui-browser-wpe` picks that engine, and an
/// app that links neither uses whatever web engine the target platform
/// bridges. Nothing in `Water.toml` names an engine, because nothing else
/// could keep the packaged runtime and the code that loads it in step.
///
/// Returns `None` when no `webview` feature is enabled in the
/// application's graph, so an engine crate reaching the graph through some
/// other component never adds a `WebView` runtime to the package on its
/// own.
///
/// # Errors
///
/// Returns an error when Cargo metadata cannot be resolved, when the
/// application links two engines at once, or when the selected engine is
/// unsupported for the requested platform and backend.
pub async fn resolved_webview_backend(
&self,
platform: TargetPlatform,
backend: TargetBackend,
) -> eyre::Result<Option<ResolvedWebViewBackend>> {
if !self.uses_standard_webview().await? {
return Ok(None);
}
let engine = self.linked_browser_engine().await?;
engine
.unwrap_or(ResolvedWebViewBackend::System)
.validate(platform, backend)
.map(Some)
.map_err(Into::into)
}
/// The browser engine crate the application links, if any.
///
/// # Errors
///
/// Returns an error when Cargo metadata cannot be resolved, or when the
/// application links more than one engine — two engines cannot both draw
/// one `WebView`, and the second `install` would fail at startup.
pub async fn linked_browser_engine(&self) -> eyre::Result<Option<ResolvedWebViewBackend>> {
let cef = self.links_runtime_package("waterui-browser-cef").await?;
let wpe = self.links_runtime_package("waterui-browser-wpe").await?;
match (cef, wpe) {
(true, true) => eyre::bail!(
"the application links both waterui-browser-cef and waterui-browser-wpe; \
exactly one browser engine can draw a WebView"
),
(true, false) => Ok(Some(ResolvedWebViewBackend::Cef)),
(false, true) => Ok(Some(ResolvedWebViewBackend::Wpe)),
(false, false) => Ok(None),
}
}
/// Whether the generated backend manifests declare the CEF subprocess
/// helper `[[bin]]`.
///
/// This is the manifest's own predicate: the helper exists only when the
/// application links the CEF engine crate, while a `waterui-chromium`
/// link alone does not declare it. Builds and packaging that touch the
/// helper must gate on this rather than
/// [`BrowserRuntimePlan::requires_cef`], which is wider — it also turns
/// on for chromium — and would request a bin target Cargo never
/// received.
///
/// # Errors
///
/// Returns an error when Cargo metadata cannot be resolved or the
/// application links two engines at once.
pub async fn declares_cef_helper(&self) -> eyre::Result<bool> {
Ok(crate::project_types::declares_cef_helper(
self.linked_browser_engine().await?,
))
}
/// Resolves and validates every embedded browser runtime linked by the application.
///
/// # Errors
///
/// Returns an error when standard `WebView` or Chromium is unsupported for
/// the requested platform and backend.
pub async fn browser_runtime_plan(
&self,
platform: TargetPlatform,
backend: TargetBackend,
) -> eyre::Result<BrowserRuntimePlan> {
let webview = self.resolved_webview_backend(platform, backend).await?;
let chromium = self.links_runtime_package("waterui-chromium").await?;
if chromium && !cef_is_supported(platform, backend) {
eyre::bail!(
"waterui-chromium requires CEF, which is unsupported for platform {platform:?} \
with backend {backend:?}"
);
}
Ok(BrowserRuntimePlan { webview, chromium })
}
/// Get the bundle identifier of the project.
#[must_use]
pub const fn bundle_identifier(&self) -> &BundleIdentifier {
&self.manifest.package.bundle_identifier
}
/// Get the assets directory path relative to project root.
#[must_use]
pub fn assets_path(&self) -> &str {
&self.manifest.package.assets_path
}
/// Get the full path to the assets directory.
#[must_use]
pub fn assets_dir(&self) -> PathBuf {
self.root.join(&self.manifest.package.assets_path)
}
/// Clean build artifacts for the project using the specified backend.
///
/// # Errors
///
/// Returns an error if cleaning fails.
pub async fn clean<B: Backend>(
&self,
backend: &B,
platform: TargetPlatform,
) -> Result<(), eyre::Report> {
backend.clean(self, platform).await
}
/// Clean all build artifacts for the project.
///
/// This cleans:
/// - Rust target directory
/// - Apple build artifacts (if backend configured)
/// - Android build artifacts (if backend configured)
/// - GTK4 build artifacts (if backend configured)
///
/// # Errors
///
/// Returns an error if any cleaning operation fails.
pub async fn clean_all(&self) -> Result<(), eyre::Report> {
use crate::{
android::platform::clean_android, apple::platform::clean_apple,
esp32::platform::clean_esp32, gtk4::platform::clean_gtk4,
hydrolysis::platform::clean_hydrolysis, winui::platform::clean_winui,
};
if self.is_playground() {
crate::water_dir::remove_project_build_cache(self.root()).await?;
// Compiled artifacts live in the per-user shared target directory
// and outlive any single project, so they stay. What remains to
// sweep here is the `water-backends` subtree older CLI layouts
// left under the project's own Cargo target directory — never the
// user's other compiled artifacts.
let water_backends_root = self.target_dir().await?.join("water-backends");
if water_backends_root.exists() {
smol::fs::remove_dir_all(&water_backends_root).await?;
}
return Ok(());
}
// Clean Rust target directory
let target_dir = self.target_dir().await?;
if target_dir.exists() {
smol::fs::remove_dir_all(&target_dir).await?;
}
// Clean Apple backend if configured
if self.apple_backend().is_some() {
clean_apple(self).await?;
}
// Clean Android backend if configured
if self.android_backend().is_some() {
clean_android(self).await?;
}
// Clean GTK4 backend if configured
if self.gtk4_backend().is_some() || (self.is_playground() && cfg!(target_os = "linux")) {
clean_gtk4(self).await?;
}
// Clean hydrolysis backend if configured
if self.hydrolysis_backend().is_some() || self.is_playground() {
clean_hydrolysis(self).await?;
}
// Clean `WinUI` backend if configured
if self.winui_backend().is_some() || (self.is_playground() && cfg!(target_os = "windows")) {
clean_winui(self).await?;
}
// Clean ESP32 backend if configured
if self.esp32_backend().is_some() {
clean_esp32(self).await?;
}
let ffi_target_dir = self.ffi_crate_path().join("target");
if ffi_target_dir.exists() {
smol::fs::remove_dir_all(&ffi_target_dir).await?;
}
Ok(())
}
/// Package the project for the specified platform.
///
/// # Errors
///
/// Returns an error if packaging fails.
pub async fn package<B: Backend>(
&self,
backend: &B,
platform: TargetPlatform,
options: PackageOptions,
) -> Result<Artifact, eyre::Report> {
backend.package(self, platform, options).await
}
fn app_crate_overrides(&self) -> Option<&AppCrates> {
self.manifest.app.as_ref()?.crates.as_ref()
}
}
/// Errors that can occur when opening a `WaterUI` project.
#[derive(Debug, thiserror::Error)]
pub enum FailToOpenProject {
/// Failed to open the Water.toml manifest.
#[error("Failed to open project manifest: {0}")]
Manifest(FailToOpenManifest),
/// Failed to read the Cargo.toml file.
#[error("Failed to read Cargo.toml: {0}")]
CargoManifest(cargo_toml::Error),
/// Failed to get Cargo metadata.
#[error("Failed to get Cargo metadata: {0}")]
TargetDirError(#[from] cargo_metadata::Error),
/// The selected framework could not be validated for this CLI.
#[error("Framework compatibility check failed: {0}")]
Framework(eyre::Report),
/// The project's `[patch]` tables could not be brought in line with the
/// local checkout's.
#[error("Failed to refresh the [patch] tables from the local checkout: {0}")]
LocalPatches(eyre::Report),
/// Missing crate name in Cargo.toml.
#[error("Invalid Cargo.toml: missing crate name")]
MissingCrateName,
/// Crate name in Cargo.toml is invalid.
#[error("Invalid Cargo.toml crate name: {0}")]
InvalidCrateName(String),
/// Project permissions are not allowed in non-playground projects.
#[error("Project permissions are not allowed in non-playground projects")]
PermissionsNotAllowedInNonPlayground,
/// Backend-project configuration is not allowed in playground manifests.
#[error(
"Backend project configuration is not allowed in playground projects \
([backends.esp32] device settings and `backend_path` source \
selections are the exceptions)"
)]
BackendsNotAllowedInPlayground,
/// Failed to initialize backend for playground project.
#[error("Failed to initialize backend: {0}")]
BackendInit(#[from] crate::backend::FailToInitBackend),
/// Failed to manage the global build cache directory.
#[error("Failed to prepare managed build cache: {0}")]
BuildCache(#[from] eyre::Report),
}
/// Errors that can occur when creating a new `WaterUI` project.
#[derive(Debug, thiserror::Error)]
pub enum FailToCreateProject {
/// Failed to resolve a coherent framework distribution.
#[error("Failed to resolve framework: {0}")]
Framework(eyre::Report),
/// The project directory already exists.
#[error("Directory already exists: {0}")]
DirectoryExists(PathBuf),
/// The directory is already a `WaterUI` project.
#[error("{0} is already a WaterUI project (Water.toml exists)")]
AlreadyProject(PathBuf),
/// The directory already contains a Cargo manifest that scaffolding
/// would overwrite.
#[error(
"{0} already contains a Cargo.toml; merge the generated scaffold manually or remove it first"
)]
CargoManifestExists(PathBuf),
/// Failed to create project directory.
#[error("Failed to create directory: {0}")]
CreateDir(std::io::Error),
/// Failed to scaffold project files.
#[error("Failed to scaffold project: {0}")]
Scaffold(std::io::Error),
/// Failed to save manifest.
#[error("Failed to save manifest: {0}")]
SaveManifest(#[from] FailToSaveManifest),
/// Failed to get Cargo metadata.
#[error("Failed to get Cargo metadata: {0}")]
TargetDirError(#[from] cargo_metadata::Error),
/// Failed to resolve the managed build cache path.
#[error("Failed to resolve managed build cache: {0}")]
BuildCache(#[from] eyre::Report),
/// Failed to initialize git repository.
#[error("Failed to initialize git repository: {0}")]
GitInit(std::io::Error),
/// Failed to check git repository status.
#[error("Failed to check git repository status: {0}")]
GitStatus(std::io::Error),
}
/// Options for creating a new `WaterUI` project.
#[derive(Debug, Clone)]
pub struct CreateOptions {
/// Application display name (e.g., "Water Example").
pub name: String,
/// Bundle identifier (e.g., "dev.waterui.waterexample").
pub bundle_identifier: BundleIdentifier,
/// Package type for the project.
pub package_type: PackageType,
/// Path to local `WaterUI` repository for development.
pub waterui_path: Option<PathBuf>,
/// Framework channel, mutually exclusive with a local source path and a
/// manifest file.
pub channel: Option<FrameworkChannel>,
/// A certified `framework.json` on disk, mutually exclusive with a channel
/// and a local source path: the project pins the channel and revision the
/// manifest declares.
pub framework_manifest: Option<PathBuf>,
/// An already-resolved framework selection — how a support app inherits
/// the host project's framework exactly. Mutually exclusive with every
/// resolving source above.
pub framework: Option<ResolvedFramework>,
/// Author name for Cargo.toml.
pub author: String,
/// The backends the caller will scaffold after creation: each one's
/// scaffold packages are held against the resolved channel before a
/// file is written, so a package the channel withholds — the git-pinned
/// experimental set — fails the create rather than the backend init.
pub backends: Vec<TargetBackend>,
/// The declared web frontend: `Some` generates the `include_web!` root
/// view and writes `[web] package_manager`.
pub web: Option<WebScaffold>,
}
/// How `create`/`init` wires a declared web frontend into the scaffold.
#[derive(Debug, Clone)]
pub struct WebScaffold {
/// The package manager written to `[web] package_manager`.
pub package_manager: web::PackageManager,
/// The `include_web!` argument: `"web"` for the conventional layout, or a
/// path relative to the project root for a frontend referenced in place.
pub include_arg: String,
}
impl CreateOptions {
fn crate_name(&self) -> Result<CrateName, FailToCreateProject> {
let name = self
.name
.chars()
.map(|character| {
if character.is_alphanumeric() {
character.to_ascii_lowercase()
} else {
'_'
}
})
.collect::<String>();
CrateName::try_from(name).map_err(|error| {
FailToCreateProject::Scaffold(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
error,
))
})
}
/// The framework the scaffold resolves against — always resolved: a
/// channel's certified release, a manifest file's, a caller-supplied
/// selection, or the checkout `waterui_path` names. A checkout's framework
/// is a filesystem source, so it is never persisted into `Water.toml`;
/// `waterui_path` itself is the record.
async fn resolve_framework(&mut self) -> eyre::Result<(ResolvedFramework, Option<Vec<u8>>)> {
let selected = [
self.waterui_path.is_some(),
self.channel.is_some(),
self.framework_manifest.is_some(),
self.framework.is_some(),
]
.into_iter()
.filter(|selected| *selected)
.count();
if selected > 1 {
eyre::bail!(
"a framework channel, a local source path, a framework manifest, \
and a resolved framework are mutually exclusive"
);
}
if let Some(path) = &self.waterui_path {
// `dunce`, not `std`'s canonicalize: on Windows the standard one
// returns an extended-length path (`\\?\C:\…`), and a scaffolded
// manifest that carries it as a dependency `path` is one Cargo
// refuses to parse ("invalid path url").
let path = path.clone();
let root = unblock(move || dunce::canonicalize(path)).await?;
self.waterui_path = Some(root.clone());
return Ok((ResolvedFramework::for_local_checkout(&root).await?, None));
}
if let Some(path) = &self.framework_manifest {
return ResolvedFramework::resolve_manifest(path).await;
}
if let Some(framework) = &self.framework {
return Ok((framework.clone(), None));
}
ResolvedFramework::resolve(self.channel.unwrap_or_default()).await
}
}
impl Project {
async fn scaffold_ffi_companion(&self) -> Result<(), crate::backend::FailToInitBackend> {
let manifest = self.manifest();
let app_name = manifest
.package
.name
.chars()
.filter(|c| c.is_alphanumeric())
.collect::<String>();
let webview_enabled = self
.uses_standard_webview()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
let chromium_enabled = self
.links_runtime_package("waterui-chromium")
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
let browser_engine = self
.linked_browser_engine()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
let framework = self
.resolved_framework()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
let ctx = TemplateContext::for_project_manifest(
manifest,
self.crate_name().clone(),
app_name,
&framework,
)
.with_backend_project_path(self.ffi_crate_path())
.with_project_root_path(self.root.clone())
.with_webview_enabled(webview_enabled)
.with_chromium_enabled(chromium_enabled)
.with_browser_engine(browser_engine);
templates::ffi::scaffold(&self.ffi_crate_path(), &ctx, &self.ffi_crate_name())
.await
.map_err(crate::backend::FailToInitBackend::Io)?;
let lockfile = self
.lockfile_path()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
templates::ffi::seed_lockfile(&self.ffi_crate_path(), &lockfile)
.await
.map_err(crate::backend::FailToInitBackend::Io)
}
/// Scaffold this project's preview module inside `workspace_root`.
///
/// # Errors
///
/// Returns an error when the generated crate cannot be written.
pub async fn scaffold_preview_ffi_companion(
&self,
workspace_root: &Path,
) -> Result<PathBuf, crate::backend::FailToInitBackend> {
let manifest = self.manifest();
let app_name = manifest
.package
.name
.chars()
.filter(|c| c.is_alphanumeric())
.collect::<String>();
let framework = self
.resolved_framework()
.await
.map_err(crate::backend::FailToInitBackend::Config)?;
let ctx = TemplateContext::for_project_manifest(
manifest,
self.crate_name().clone(),
app_name,
&framework,
)
.with_backend_project_path(self.preview_ffi_crate_path(workspace_root))
.with_project_root_path(self.root.clone());
let crate_path = self.preview_ffi_crate_path(workspace_root);
templates::preview_ffi::scaffold(&crate_path, &ctx, &self.preview_ffi_crate_name())
.await
.map_err(crate::backend::FailToInitBackend::Io)?;
Ok(crate_path)
}
async fn remove_ffi_companion_if_unused(&self) -> eyre::Result<()> {
if self.apple_backend().is_some() || self.android_backend().is_some() {
return Ok(());
}
let ffi_path = self.ffi_crate_path();
if ffi_path.exists() {
smol::fs::remove_dir_all(&ffi_path).await?;
}
Ok(())
}
/// Create a new `WaterUI` project at the specified path.
///
/// This creates the project directory, scaffolds root files (Cargo.toml, src/lib.rs),
/// and saves the Water.toml manifest. Use `init_apple_backend()` and `init_android_backend()`
/// to scaffold platform backends after creation.
///
/// # Errors
/// - `FailToCreateProject::DirectoryExists`: If the directory already exists.
/// - `FailToCreateProject::CreateDir`: If creating the directory fails.
/// - `FailToCreateProject::Scaffold`: If scaffolding files fails.
/// - `FailToCreateProject::SaveManifest`: If saving the manifest fails.
pub async fn create(
path: impl AsRef<Path>,
options: CreateOptions,
) -> Result<Self, FailToCreateProject> {
let path = path.as_ref().to_path_buf();
// Check if directory already exists
if path.exists() {
return Err(FailToCreateProject::DirectoryExists(path));
}
Self::scaffold_project(path, options).await
}
/// Initialize a `WaterUI` project inside an existing directory
/// (`water init`): the same scaffold as [`Project::create`] without the
/// directory-creation step.
///
/// # Errors
/// - `FailToCreateProject::AlreadyProject`: If `Water.toml` already exists.
/// - `FailToCreateProject::CargoManifestExists`: If `Cargo.toml` already
/// exists and would be overwritten.
/// - the [`Project::create`] scaffold errors.
pub async fn init(
path: impl AsRef<Path>,
options: CreateOptions,
) -> Result<Self, FailToCreateProject> {
let path = path.as_ref().to_path_buf();
if path.join("Water.toml").exists() {
return Err(FailToCreateProject::AlreadyProject(path));
}
if path.join("Cargo.toml").exists() {
return Err(FailToCreateProject::CargoManifestExists(path));
}
Self::scaffold_project(path, options).await
}
async fn scaffold_project(
path: PathBuf,
mut options: CreateOptions,
) -> Result<Self, FailToCreateProject> {
// Derive crate name from display name
let crate_name = options.crate_name()?;
let (framework, lockfile) = options
.resolve_framework()
.await
.map_err(FailToCreateProject::Framework)?;
// A backend whose scaffold packages the channel withholds cannot be
// scaffolded at all — reject before a single file lands.
for backend in &options.backends {
for package in backend.scaffold_packages() {
framework
.require_distributable(package)
.map_err(FailToCreateProject::Framework)?;
}
}
// Framework validation precedes directory creation so a rejected
// local checkout leaves nothing behind; on `init` the directory
// already exists and this is a no-op.
smol::fs::create_dir_all(&path)
.await
.map_err(FailToCreateProject::CreateDir)?;
// Build template context for root files
let ctx = TemplateContext::for_create_options(&options, crate_name.clone(), &framework);
// The assets root is derived once and shared with both the scaffold and
// the manifest, so the created directory and `Water.toml` cannot disagree.
let assets_path = default_assets_path();
// Scaffold root files (Cargo.toml, src/lib.rs, .gitignore, assets/README.md)
templates::root::scaffold(&path, &ctx, &assets_path)
.await
.map_err(FailToCreateProject::Scaffold)?;
// `.mcp.json` lets MCP clients launched in the project root find
// `water mcp` without any user configuration.
crate::mcp::ensure_mcp_json(&path)
.await
.map_err(FailToCreateProject::Scaffold)?;
if let Some(lockfile) = lockfile {
let contents = ctx
.framework
.cargo_lock(&lockfile)
.map_err(FailToCreateProject::Framework)?
.to_string();
smol::fs::write(path.join("Water.lock"), lockfile)
.await
.map_err(FailToCreateProject::Scaffold)?;
smol::fs::write(path.join("Cargo.lock"), contents)
.await
.map_err(FailToCreateProject::Scaffold)?;
}
// Build manifest
let mut backends = Backends::default();
if options.package_type == PackageType::App {
backends.set_path("backends");
}
let manifest = Manifest {
package: Package {
package_type: options.package_type,
name: options.name.clone(),
bundle_identifier: options.bundle_identifier.clone(),
assets_path,
accessory: false,
},
backends,
waterui_path: options
.waterui_path
.as_ref()
.map(|p| p.display().to_string()),
// A local checkout's framework is a filesystem source — never
// persisted; `waterui_path` above is the record.
framework: framework.channel().is_some().then_some(framework),
permissions: BTreeMap::default(),
app: None,
theme: None,
launch: None,
web: options.web.as_ref().map(|scaffold| web::WebConfig {
package_manager: scaffold.package_manager,
}),
};
// Save Water.toml
manifest.save(&path).await?;
// Initialize git repository if not already in one
Self::ensure_git_init(&path).await?;
let managed_backends_root = if options.package_type == PackageType::Playground {
crate::water_dir::project_build_cache_dir(&path)
.await
.map_err(FailToCreateProject::BuildCache)?
} else {
path.join(manifest.backends.path())
};
let cargo_layout = if let Some(framework) = &manifest.framework {
let layout =
resolve_cargo_layout(&path, Some(framework.clone()), CargoResolution::Update)
.await
.map_err(FailToCreateProject::Framework)?;
futures_util::future::ready(Ok::<CargoLayout, String>(layout))
.boxed()
.shared()
} else {
spawn_cargo_layout_resolution(&path, None, true)
};
Ok(Self {
root: path,
manifest,
crate_name,
cargo_layout,
linked_packages: Arc::new(async_lock::OnceCell::new()),
enabled_features: Arc::new(async_lock::OnceCell::new()),
managed_backends_root,
})
}
/// Ensure the project is initialized with git.
///
/// Checks if the project directory is already part of a git repository.
/// If not, initializes a new git repository.
async fn ensure_git_init(path: &Path) -> Result<(), FailToCreateProject> {
// Check if already in a git repository
let mut cmd = Command::new("git");
let is_in_git = command(&mut cmd)
.args(["rev-parse", "--git-dir"])
.current_dir(path)
.output()
.await
.map_err(FailToCreateProject::GitStatus)?
.status
.success();
if !is_in_git {
// Initialize a new git repository
let mut cmd = Command::new("git");
command(&mut cmd)
.args(["init"])
.current_dir(path)
.status()
.await
.map_err(FailToCreateProject::GitInit)?;
}
Ok(())
}
/// Initialize the Apple backend for this project.
///
/// This scaffolds the Apple backend files and updates the manifest.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_apple_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::backend::Backend;
let backend = AppleBackend::init(self).await?;
self.scaffold_ffi_companion().await?;
self.manifest.backends.set_apple(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Initialize the Android backend for this project.
///
/// This scaffolds the Android backend files and updates the manifest.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_android_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::backend::Backend;
let backend = AndroidBackend::init(self).await?;
self.scaffold_ffi_companion().await?;
self.manifest.backends.set_android(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Initialize the GTK4 backend for an existing project.
///
/// Creates necessary files/folders for the GTK4 backend under `backend_path::<Gtk4Backend>()`.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_gtk4_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::{backend::Backend, gtk4::backend::Gtk4Backend};
self.require_distributable_backend(TargetBackend::Gtk4)
.await?;
if !cfg!(target_os = "linux") {
return Err(crate::backend::FailToInitBackend::Io(
std::io::Error::other("GTK4 backend is only supported on Linux hosts"),
));
}
let backend = Gtk4Backend::init(self).await?;
self.manifest.backends.set_gtk4(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Initialize the hydrolysis backend for an existing project.
///
/// Creates necessary files/folders for the hydrolysis backend under
/// `backend_path::<HydrolysisBackend>()`.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_hydrolysis_backend(
&mut self,
) -> Result<(), crate::backend::FailToInitBackend> {
use crate::{backend::Backend, hydrolysis::backend::HydrolysisBackend};
self.require_distributable_backend(TargetBackend::Hydrolysis)
.await?;
let backend = HydrolysisBackend::init(self).await?;
self.manifest.backends.set_hydrolysis(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
// The Hydrolysis backend is what `water mcp` drives, so adding it is
// what makes the project MCP-servable; the file is user-owned and
// only written when absent.
crate::mcp::ensure_mcp_json(&self.root).await?;
Ok(())
}
/// Initialize the `WinUI` backend for an existing project.
///
/// Creates necessary files/folders for the `WinUI` backend under `backend_path::<WinUiBackend>()`.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_winui_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::{backend::Backend, winui::backend::WinUiBackend};
self.require_distributable_backend(TargetBackend::WinUi)
.await?;
if !cfg!(target_os = "windows") {
return Err(crate::backend::FailToInitBackend::Io(
std::io::Error::other("WinUI backend is only supported on Windows hosts"),
));
}
let backend = WinUiBackend::init(self).await?;
self.manifest.backends.set_winui(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Initialize the ESP32 backend for an existing project.
///
/// Creates necessary files/folders for the ESP32 firmware harness under
/// `backend_path::<Esp32Backend>()`.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_esp32_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::{backend::Backend, esp32::backend::Esp32Backend};
self.require_distributable_backend(TargetBackend::Dew)
.await?;
let backend = Esp32Backend::init(self).await?;
self.manifest.backends.set_esp32(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Select the ESP32 target chip, persisting it to `Water.toml`.
///
/// The chip is the single source of truth for the ESP32 backend's target
/// triple, QEMU model, and firmware parameters. Selecting a platform such
/// as `esp32c3` calls this so the generated harness and build target follow
/// the platform. No-ops (and skips the manifest write) when the configured
/// chip already matches.
///
/// # Errors
/// Returns an error if saving the manifest fails.
pub async fn set_esp32_chip(
&mut self,
chip: crate::esp32::chip::Esp32Chip,
) -> eyre::Result<()> {
let current = self.esp32_backend().cloned().unwrap_or_default();
if current.chip() == chip.id() {
return Ok(());
}
self.manifest.backends.set_esp32(current.with_chip(chip));
self.save_manifest().await
}
/// Remove Apple backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_apple_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.apple_backend() {
let path = backend.project_path().to_path_buf();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_apple();
self.remove_ffi_companion_if_unused().await?;
self.save_manifest().await
}
/// Remove Android backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_android_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.android_backend() {
let path = backend.project_path().clone();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_android();
self.remove_ffi_companion_if_unused().await?;
self.save_manifest().await
}
/// Remove GTK4 backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_gtk4_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.gtk4_backend() {
let path = backend.project_path().clone();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_gtk4();
self.save_manifest().await
}
/// Remove `WinUI` backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_winui_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.winui_backend() {
let path = backend.project_path().clone();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_winui();
self.save_manifest().await
}
/// Remove hydrolysis backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_hydrolysis_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.hydrolysis_backend() {
let path = backend.project_path().clone();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_hydrolysis();
self.save_manifest().await
}
/// Remove ESP32 backend configuration and generated files.
///
/// # Errors
/// Returns an error if deleting files or saving manifest fails.
pub async fn remove_esp32_backend(&mut self) -> eyre::Result<()> {
if let Some(backend) = self.esp32_backend() {
let path = backend.project_path().clone();
self.remove_backend_relative_dir(&path).await?;
}
self.manifest.backends.clear_esp32();
self.save_manifest().await
}
/// Open a `WaterUI` project located at the specified path.
///
/// This loads both the `Water.toml` manifest and the `Cargo.toml` file.
/// For playground projects, backends are automatically initialized if not configured.
///
/// # Errors
/// - `FailToOpenProject::Manifest`: If there was an error opening the `Water.toml` manifest.
/// - `FailToOpenProject::CargoManifest`: If there was an error reading the `Cargo.toml` file.
/// - `FailToOpenProject::MissingCrateName`: If the crate name is missing in `Cargo.toml`.
pub async fn open(path: impl AsRef<Path>) -> Result<Self, FailToOpenProject> {
Self::open_with_mode(path, OpenMode::Full).await
}
/// Open a project for preview dylib builds without initializing native app backends.
///
/// Playground preview dylib builds only need the managed preview wrapper crate. Native
/// backend initialization is reserved for support app projects that actually launch apps.
///
/// # Errors
/// - `FailToOpenProject::Manifest`: If there was an error opening the `Water.toml` manifest.
/// - `FailToOpenProject::CargoManifest`: If there was an error reading the `Cargo.toml` file.
/// - `FailToOpenProject::MissingCrateName`: If the crate name is missing in `Cargo.toml`.
pub async fn open_for_preview_build(path: impl AsRef<Path>) -> Result<Self, FailToOpenProject> {
Self::open_with_mode(path, OpenMode::PreviewBuild).await
}
/// Make a local-checkout project's `[patch]` tables the checkout's.
///
/// Cargo applies `[patch]` only from the workspace it builds, so a project
/// on a `waterui_path` carries a copy of the checkout's tables, and the
/// copy has to follow the checkout: a fork pin moves, an entry is added or
/// dropped, and a project scaffolded earlier would otherwise build a graph
/// the checkout no longer produces, silently. The manifest is rewritten
/// only when the tables differ, so an up-to-date project stays untouched.
///
/// A project that is itself a member of the checkout's workspace — every
/// example and playground in this repository — needs no copy, because the
/// tables Cargo reads are the checkout's own. Writing one anyway put a
/// `[patch.crates-io]` table into a member manifest, where Cargo ignores it
/// and says so on every single build.
async fn refresh_local_patches(project_root: &Path, waterui_path: &Path) -> eyre::Result<()> {
let project_root = project_root.to_path_buf();
let waterui_path = waterui_path.to_path_buf();
unblock(move || {
let checkout = project_root.join(&waterui_path);
let patch_root = templates::patch_manifest_dir(&project_root)?;
if same_directory(&patch_root, &checkout)? {
return Ok(());
}
if !same_directory(&patch_root, &project_root)? {
// Cargo reads `[patch]` from `patch_root` and nothing this
// function writes into the project could change that, so the
// honest move is to say which manifest the tables belong in
// rather than write a copy that is read by nobody.
eyre::bail!(
"This project is a member of the Cargo workspace at {}, so Cargo reads \
[patch] from {} and ignores any copy here. Move the WaterUI checkout's \
[patch] tables — the ones in {} — into that workspace manifest, or take \
the project out of that workspace.",
patch_root.display(),
patch_root.join("Cargo.toml").display(),
checkout.join("Cargo.toml").display(),
);
}
let cargo_path = project_root.join("Cargo.toml");
let text = std::fs::read_to_string(&cargo_path)?;
let current = CargoManifest::from_slice(text.as_bytes())?.patch;
let next = templates::local_framework_patches(&project_root, &waterui_path)?;
if current == next {
return Ok(());
}
let mut document: toml_edit::DocumentMut = text.parse()?;
crate::framework::rewrite_patch_tables(&mut document, ¤t, &next)?;
std::fs::write(&cargo_path, document.to_string())?;
info!(
path = %cargo_path.display(),
"Refreshed the [patch] tables from the local checkout"
);
Ok(())
})
.await
}
#[allow(clippy::too_many_lines)]
async fn open_with_mode(
path: impl AsRef<Path>,
open_mode: OpenMode,
) -> Result<Self, FailToOpenProject> {
use crate::backend::Backend;
let total_start = std::time::Instant::now();
let path = path.as_ref().to_path_buf();
let manifest_start = std::time::Instant::now();
let manifest = Manifest::open(path.join("Water.toml"))
.await
.map_err(FailToOpenProject::Manifest)?;
if let Some(framework) = &manifest.framework {
framework
.validate_cli()
.map_err(FailToOpenProject::Framework)?;
}
if let Some(local) = &manifest.waterui_path {
validate_local_cli(&path.join(local))
.await
.map_err(FailToOpenProject::Framework)?;
Self::refresh_local_patches(&path, Path::new(local))
.await
.map_err(FailToOpenProject::LocalPatches)?;
}
info!(
path = %path.display(),
open_mode = ?open_mode,
elapsed_ms = manifest_start.elapsed().as_millis(),
"Project::open loaded Water.toml"
);
let cargo_path = path.join("Cargo.toml");
let cargo_manifest_start = std::time::Instant::now();
let cargo_manifest = unblock(move || CargoManifest::from_path(cargo_path))
.await
.map_err(FailToOpenProject::CargoManifest)?;
info!(
path = %path.display(),
open_mode = ?open_mode,
elapsed_ms = cargo_manifest_start.elapsed().as_millis(),
"Project::open loaded Cargo.toml"
);
let crate_name = cargo_manifest
.package
.map(|p| p.name)
.ok_or(FailToOpenProject::MissingCrateName)
.and_then(|value| {
CrateName::try_from(value).map_err(FailToOpenProject::InvalidCrateName)
})?;
let is_playground = manifest.package.package_type == PackageType::Playground;
// Check that permissions are only set for playground projects
if !is_playground && !manifest.permissions.is_empty() {
return Err(FailToOpenProject::PermissionsNotAllowedInNonPlayground);
}
// Playgrounds delegate backend projects to the CLI, so backend
// scaffolding configuration is rejected. Two kinds of entries are
// exceptions: `[backends.esp32]`, which is device configuration
// (chip, panel geometry, bundled fonts) only the app author can
// supply while its harness still lives in the managed build cache,
// and `backend_path`, which selects where a backend's runtime source
// comes from without configuring a project.
if is_playground && manifest.backends.configures_backend_projects() {
return Err(FailToOpenProject::BackendsNotAllowedInPlayground);
}
let cargo_layout = spawn_cargo_layout_resolution(
&path,
manifest.framework.clone(),
manifest.waterui_path.is_some(),
);
cargo_layout
.clone()
.await
.map_err(|error| FailToOpenProject::Framework(eyre::eyre!(error)))?;
let managed_backends_root = if is_playground {
let build_cache_start = std::time::Instant::now();
let root = crate::water_dir::ensure_project_build_cache(&path)
.await
.map_err(FailToOpenProject::BuildCache)?;
info!(
path = %path.display(),
open_mode = ?open_mode,
elapsed_ms = build_cache_start.elapsed().as_millis(),
"Project::open ensured project build cache"
);
root
} else {
path.join(manifest.backends.path())
};
let mut project = Self {
root: path,
manifest,
crate_name,
cargo_layout,
linked_packages: Arc::new(async_lock::OnceCell::new()),
enabled_features: Arc::new(async_lock::OnceCell::new()),
managed_backends_root,
};
// For playground projects, auto-initialize backends
// Always re-scaffold templates on each run to pick up manifest changes (e.g., permissions)
// Build cache (build/, .gradle/, DerivedData/) is preserved since scaffold only writes template files
//
// Skip backend initialization when:
// 1. Running inside Xcode's sandboxed build script phase (WATERUI_SKIP_RUST_BUILD=1)
// 2. Running inside any sandbox (sandbox-exec sets __XCODE_BUILT_PRODUCTS_DIR_PATHS or similar)
// 3. Xcode is the current build tool (ACTION env var is set by Xcode)
let skip_backend_init = std::env::var("WATERUI_SKIP_RUST_BUILD")
.is_ok_and(|value| value == "1")
|| std::env::var("ACTION").is_ok() // Xcode sets this during builds
|| std::env::var("XCODE_PRODUCT_BUILD_VERSION").is_ok();
if is_playground && !skip_backend_init && open_mode == OpenMode::Full {
let apple_backend_start = std::time::Instant::now();
let apple_backend = AppleBackend::init(&project)
.await
.map_err(FailToOpenProject::BackendInit)?;
info!(
path = %project.root.display(),
elapsed_ms = apple_backend_start.elapsed().as_millis(),
"Project::open initialized Apple backend"
);
project.manifest.backends.set_apple(apple_backend);
let android_backend_start = std::time::Instant::now();
let android_backend = AndroidBackend::init(&project)
.await
.map_err(FailToOpenProject::BackendInit)?;
info!(
path = %project.root.display(),
elapsed_ms = android_backend_start.elapsed().as_millis(),
"Project::open initialized Android backend"
);
project.manifest.backends.set_android(android_backend);
let ffi_companion_start = std::time::Instant::now();
project
.scaffold_ffi_companion()
.await
.map_err(FailToOpenProject::BackendInit)?;
info!(
path = %project.root.display(),
elapsed_ms = ffi_companion_start.elapsed().as_millis(),
"Project::open scaffolded native ffi companion"
);
}
if !is_playground
&& !skip_backend_init
&& open_mode == OpenMode::Full
&& (project.apple_backend().is_some() || project.android_backend().is_some())
{
let ffi_companion_start = std::time::Instant::now();
project
.scaffold_ffi_companion()
.await
.map_err(FailToOpenProject::BackendInit)?;
info!(
path = %project.root.display(),
elapsed_ms = ffi_companion_start.elapsed().as_millis(),
"Project::open refreshed native ffi companion"
);
}
info!(
path = %project.root.display(),
open_mode = ?open_mode,
elapsed_ms = total_start.elapsed().as_millis(),
"Project::open completed"
);
Ok(project)
}
}
impl Project {
async fn save_manifest(&self) -> eyre::Result<()> {
self.manifest.save(&self.root).await.map_err(Into::into)
}
async fn remove_backend_relative_dir(&self, relative_path: &Path) -> eyre::Result<()> {
let backend_path = self.managed_backends_root.join(relative_path);
if backend_path.exists() {
smol::fs::remove_dir_all(&backend_path).await?;
}
Ok(())
}
}
async fn apply_channel_selection(
root: &Path,
framework: ResolvedFramework,
updates: Vec<(PathBuf, Option<Vec<u8>>)>,
) -> eyre::Result<()> {
let mut previous = BTreeMap::new();
for file in updates
.iter()
.map(|(file, _)| file.clone())
.chain([root.join("Cargo.lock")])
{
let contents = match smol::fs::read(&file).await {
Ok(contents) => Some(contents),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
previous.insert(file, contents);
}
let result = async {
for (file, contents) in &updates {
write_channel_file(file, contents.as_deref()).await?;
}
resolve_cargo_layout(root, Some(framework), CargoResolution::Update).await?;
Ok(())
}
.await;
if let Err(error) = result {
for (file, contents) in previous {
write_channel_file(&file, contents.as_deref())
.await
.map_err(|restore| {
eyre::eyre!("{error}; could not restore {}: {restore}", file.display())
})?;
}
return Err(error);
}
Ok(())
}
async fn write_channel_file(path: &Path, contents: Option<&[u8]>) -> std::io::Result<()> {
match contents {
Some(contents) => smol::fs::write(path, contents).await,
None => match smol::fs::remove_file(path).await {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
result => result,
},
}
}
async fn resolve_cargo_layout(
current_dir: &Path,
framework: Option<ResolvedFramework>,
mode: CargoResolution,
) -> eyre::Result<CargoLayout> {
let root = current_dir.to_path_buf();
let metadata = unblock(move || {
let mut command = cargo_metadata::MetadataCommand::new();
command.current_dir(root);
match mode {
CargoResolution::Local => {
command.no_deps();
}
CargoResolution::Locked => {
command.other_options(vec!["--locked".to_string()]);
}
CargoResolution::Update => {}
}
command.exec()
})
.await?;
validate_resolved_cli(&metadata)?;
if let Some(framework) = framework
&& framework.channel() != Some(FrameworkChannel::Stable)
{
let lockfile = smol::fs::read(current_dir.join("Water.lock")).await?;
framework.validate_dependencies(&metadata, &lockfile)?;
}
Ok(CargoLayout {
target_dir: metadata.target_directory.into_std_path_buf(),
workspace_root: metadata.workspace_root.into_std_path_buf(),
})
}
/// Run `cargo tree` for the application package rooted at `project_root`'s
/// manifest, over the given edge kinds, and return the `{p}`-formatted tree.
///
/// `locked` passes `--locked` to the resolve: trees that are read-only input —
/// the shared pinned-framework checkout — must fail loudly on a stale
/// committed lockfile instead of letting cargo rewrite it in place.
async fn cargo_tree(project_root: &Path, edges: &str, locked: bool) -> eyre::Result<String> {
// `dunce`, not `std::fs::canonicalize`: on Windows the standard one returns
// an extended-length path (`\\?\D:\...`), while `cargo metadata` reports the
// plain one, so comparing the two never matched and the package below was
// always "omitted" (part of #152). Canonicalize before invoking metadata,
// not just on the looked-up side: metadata echoes the manifest path it is
// given, so under a symlinked `TMPDIR` (`/var` → `/private/var` on macOS)
// a non-canonical input can never match what metadata reports.
let application_manifest = dunce::canonicalize(project_root.join("Cargo.toml"))?;
let metadata_manifest = application_manifest.clone();
let metadata = unblock(move || {
let mut command = cargo_metadata::MetadataCommand::new();
command.no_deps().manifest_path(metadata_manifest);
if locked {
command.other_options(vec!["--locked".to_string()]);
}
command.exec()
})
.await?;
let root = metadata
.packages
.iter()
.find(|package| package.manifest_path.as_std_path() == application_manifest)
.ok_or_else(|| {
eyre::eyre!(
"Cargo metadata omitted the application package at {}",
application_manifest.display()
)
})?;
let package_spec = root.id.to_string();
let mut tree = Command::new("cargo");
tree.arg("tree")
.arg("--manifest-path")
.arg(&application_manifest)
.arg("--package")
.arg(package_spec)
.arg("--edges")
.arg(edges)
.arg("--prefix")
.arg("none")
.arg("--format")
.arg("{p}")
.current_dir(project_root);
if locked {
tree.arg("--locked");
}
let output = tree.output().await?;
if !output.status.success() {
return Err(eyre::eyre!(
"failed to resolve runtime dependency graph for {}: {}",
application_manifest.display(),
String::from_utf8_lossy(&output.stderr).trim()
));
}
String::from_utf8(output.stdout)
.map_err(|error| eyre::eyre!("Cargo runtime dependency graph is not UTF-8: {error}"))
}
async fn resolve_linked_runtime_packages(
project_root: PathBuf,
locked: bool,
) -> eyre::Result<BTreeMap<String, String>> {
let tree = cargo_tree(&project_root, "normal", locked).await?;
let mut linked = BTreeMap::new();
for package in tree.lines() {
let name = package
.split_ascii_whitespace()
.next()
.ok_or_else(|| eyre::eyre!("Cargo emitted an empty runtime dependency entry"))?;
linked.insert(name.to_string(), package.to_string());
}
Ok(linked)
}
/// Feature names turned on inside the application's subtree. With `--edges
/// features`, `cargo tree` reports each enabled feature as a
/// `<package> feature "<name>"` node; only the names are kept, since the
/// question asked of this set is always "is a feature named X enabled".
async fn resolve_enabled_features(
project_root: PathBuf,
locked: bool,
) -> eyre::Result<BTreeSet<String>> {
let tree = cargo_tree(&project_root, "features", locked).await?;
let mut features = BTreeSet::new();
for node in tree.lines() {
if let Some(feature) = node
.split_once(" feature \"")
.and_then(|(_, rest)| rest.strip_suffix('"'))
{
features.insert(feature.to_string());
}
}
Ok(features)
}
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::Arc,
};
use serde::{Deserialize, Serialize};
use smol::{fs::read_to_string, process::Command, unblock};
use waterui_assets_planner::{LaunchConfig, ThemeConfig};
use crate::{
android::{backend::AndroidBackend, device::AndroidAbiProvider, platform::AndroidPlatform},
apple::backend::AppleBackend,
backend::{Backend, Backends},
build::{BuildOptions, BuildProfile},
device::{Artifact, Device, FailToRun, RunOptions, Running},
platform::{PackageOptions, TargetBackend, TargetPlatform},
project_types::{BundleIdentifier, CrateName, PermissionKey, generated_crate_name},
templates::{self, TemplateContext},
utils::command,
web,
};
/// Configuration for a `WaterUI` project persisted to `Water.toml`.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Manifest {
/// Package information.
pub package: Package,
/// Backend configurations for various platforms.
#[serde(default, skip_serializing_if = "Backends::is_empty")]
pub backends: Backends,
/// Web engine selected for the standard `WebView` component.
/// Path to local `WaterUI` repository for dev mode.
/// When set, all backends will use this path instead of the published versions.
#[serde(skip_serializing_if = "Option::is_none")]
pub waterui_path: Option<String>,
/// Exact framework and backend selection, resolved only by explicit version operations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub framework: Option<ResolvedFramework>,
/// Permission configuration for playground projects.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub permissions: BTreeMap<PermissionKey, PermissionEntry>,
/// App-only configuration.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app: Option<AppConfig>,
/// Cross-platform app theme slots.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub theme: Option<ThemeConfig>,
/// The launch screen shown until the app's first frame.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub launch: Option<LaunchConfig>,
/// Web-frontend toolchain declarations (`[web]`); only the CLI reads this.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub web: Option<web::WebConfig>,
}
/// Permission entry for playground projects.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PermissionEntry {
enable: bool,
/// Explain why this permission is needed.
description: String,
}
impl PermissionEntry {
/// Create an enabled permission entry with the given rationale.
#[must_use]
pub fn enabled(description: impl Into<String>) -> Self {
Self {
enable: true,
description: description.into(),
}
}
/// Check if this permission is enabled.
#[must_use]
pub const fn is_enabled(&self) -> bool {
self.enable
}
/// Get the description of why this permission is needed.
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
}
/// Errors that can occur when opening a `Water.toml` manifest file.
#[derive(Debug, thiserror::Error)]
pub enum FailToOpenManifest {
/// Failed to read the manifest file from the filesystem.
#[error("Failed to read manifest file: {0}")]
ReadError(std::io::Error),
/// The manifest file is invalid or malformed.
#[error("Invalid manifest file: {0}")]
InvalidManifest(toml::de::Error),
/// The manifest file was not found at the specified path.
#[error("Manifest file not found at the specified path")]
NotFound,
}
/// Errors that can occur when saving a `Water.toml` manifest file.
#[derive(Debug, thiserror::Error)]
pub enum FailToSaveManifest {
/// Failed to serialize the manifest to TOML.
#[error("Failed to serialize manifest: {0}")]
Serialize(toml::ser::Error),
/// Failed to write the manifest file to disk.
#[error("Failed to write manifest file: {0}")]
Write(std::io::Error),
}
impl Manifest {
/// Open and parse a `Water.toml` manifest file from the specified path.
///
/// # Errors
/// - `FailToOpenManifest::ReadError`: If there was an error reading the file.
/// - `FailToOpenManifest::InvalidManifest`: If the file contents are not valid TOML.
/// - `FailToOpenManifest::NotFound`: If the file does not exist at the specified path.
pub async fn open(path: impl AsRef<Path>) -> Result<Self, FailToOpenManifest> {
let path = path.as_ref();
let result = read_to_string(path).await;
match result {
Ok(c) => toml::from_str(&c).map_err(FailToOpenManifest::InvalidManifest),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(FailToOpenManifest::NotFound),
Err(e) => Err(FailToOpenManifest::ReadError(e)),
}
}
/// Save the manifest to a `Water.toml` file at the specified directory.
///
/// # Errors
/// - If there was an error serializing the manifest to TOML.
/// - If there was an error writing the file.
pub async fn save(&self, dir: impl AsRef<Path>) -> Result<(), FailToSaveManifest> {
let path = dir.as_ref().join("Water.toml");
let content = toml::to_string_pretty(self).map_err(FailToSaveManifest::Serialize)?;
smol::fs::write(&path, content)
.await
.map_err(FailToSaveManifest::Write)
}
/// Create a new `Manifest` with the specified package information.
#[must_use]
pub fn new(package: Package) -> Self {
Self {
package,
backends: Backends::default(),
waterui_path: None,
framework: None,
permissions: BTreeMap::default(),
app: None,
theme: None,
launch: None,
web: None,
}
}
}
/// The engine that draws this application's standard `WebView`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedWebViewBackend {
/// Platform-provided `WebView`.
System,
/// Bundled WPE `WebKit` runtime.
Wpe,
/// Bundled Chromium Embedded Framework runtime.
Cef,
}
/// Browser engines that must be staged for one resolved application graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserRuntimePlan {
/// Standard `WebView` engine, when `waterui-webview` is linked.
pub webview: Option<ResolvedWebViewBackend>,
/// Whether the independent full Chromium component is linked.
pub chromium: bool,
}
impl BrowserRuntimePlan {
/// Returns whether this application requires a packaged CEF runtime and
/// subprocess helper.
#[must_use]
pub const fn requires_cef(self) -> bool {
self.chromium || matches!(self.webview, Some(ResolvedWebViewBackend::Cef))
}
}
impl ResolvedWebViewBackend {
/// Return whether this engine can be hosted by a platform and backend pair.
#[must_use]
pub const fn supports(self, platform: TargetPlatform, backend: TargetBackend) -> bool {
match self {
Self::System => matches!(
(platform, backend),
(
TargetPlatform::MacOS,
TargetBackend::Apple | TargetBackend::Hydrolysis
) | (
TargetPlatform::IOS
| TargetPlatform::IOSSimulator
| TargetPlatform::VisionOS
| TargetPlatform::VisionOSSimulator,
TargetBackend::Apple
) | (TargetPlatform::Android, TargetBackend::Android)
| (TargetPlatform::Linux, TargetBackend::Gtk4)
| (TargetPlatform::Web, TargetBackend::Hydrolysis)
),
Self::Wpe => {
matches!(platform, TargetPlatform::Linux)
&& matches!(backend, TargetBackend::Gtk4 | TargetBackend::Hydrolysis)
}
Self::Cef => cef_is_supported(platform, backend),
}
}
/// Returns this engine, or an error naming what cannot host it.
///
/// # Errors
///
/// Returns an error when this platform and backend pair cannot host the
/// engine the application selected.
pub const fn validate(
self,
platform: TargetPlatform,
backend: TargetBackend,
) -> Result<Self, UnsupportedWebViewBackend> {
if self.supports(platform, backend) {
Ok(self)
} else {
Err(UnsupportedWebViewBackend {
resolved: self,
platform,
backend,
})
}
}
/// Stable lowercase name used for Cargo features, runtime manifests, and diagnostics.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Wpe => "wpe",
Self::Cef => "cef",
}
}
}
const fn cef_is_supported(platform: TargetPlatform, backend: TargetBackend) -> bool {
!matches!(backend, TargetBackend::Dew)
&& matches!(
platform,
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows
)
}
/// Error returned for an unsupported `WebView` engine/platform/backend combination.
#[derive(Debug, thiserror::Error)]
#[error(
"this application's WebView engine resolves to {resolved:?}, which is unsupported for \
platform {platform:?} with backend {backend:?}. The engine follows the application's \
dependencies: link waterui-browser-cef or waterui-browser-wpe to select one, or \
neither to use the engine this platform bridges."
)]
pub struct UnsupportedWebViewBackend {
resolved: ResolvedWebViewBackend,
platform: TargetPlatform,
backend: TargetBackend,
}
/// App-specific configuration in `Water.toml`.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct AppConfig {
/// Optional crate name overrides.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crates: Option<AppCrates>,
}
/// Crate name overrides for app mode.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct AppCrates {
/// Optional override crate name for generated FFI crate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ffi: Option<CrateName>,
/// Optional override crate name for generated GTK backend crate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gtk: Option<CrateName>,
/// Optional override crate name for generated hydrolysis backend crate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hydrolysis: Option<CrateName>,
/// Optional override crate name for generated `WinUI` backend crate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub winui: Option<CrateName>,
}
/// `[package]` section in `Water.toml`.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Package {
/// Type of the package (e.g., "app").
#[serde(rename = "type")]
pub package_type: PackageType,
/// Human-readable name of the application (e.g., "Water Demo").
pub name: String,
/// Bundle identifier for the application (e.g., "dev.waterui.waterdemo").
pub bundle_identifier: BundleIdentifier,
/// Path to assets directory relative to project root. Defaults to "assets".
#[serde(
default = "default_assets_path",
skip_serializing_if = "is_default_assets_path"
)]
pub assets_path: String,
/// Whether to build as an accessory (headless) app on macOS.
#[serde(default, skip_serializing_if = "is_false")]
pub accessory: bool,
}
/// Reads the `package.name` of a project's `Cargo.toml` — the crate name the
/// generated backends and preview symbols build on.
///
/// Lighter than [`Project::open`]: this only parses the manifest, so callers
/// that need just the crate name (the `water preview`/`water mcp` entry
/// points) do not pay for a full project open.
///
/// # Errors
/// Returns an error if `Cargo.toml` cannot be read or has no `package.name`.
pub async fn read_project_crate_name(project_path: &Path) -> eyre::Result<String> {
let cargo_toml = project_path.join("Cargo.toml");
let cargo_content = smol::fs::read_to_string(&cargo_toml).await?;
let cargo: toml::Table = cargo_content.parse()?;
cargo
.get("package")
.and_then(|p| p.get("name"))
.and_then(|n| n.as_str())
.map(ToString::to_string)
.ok_or_else(|| eyre::eyre!("Could not find package name in Cargo.toml"))
}
/// Whether two paths name the same directory on disk.
///
/// Compared after canonicalization, because the two sides come from different
/// places — one walked up from the project, one joined from a relative
/// `waterui_path` — and `examples/filter/../..` is the repository root however
/// it is spelled.
fn same_directory(left: &Path, right: &Path) -> std::io::Result<bool> {
Ok(std::fs::canonicalize(left)? == std::fs::canonicalize(right)?)
}
fn default_assets_path() -> String {
"assets".to_string()
}
fn is_default_assets_path(path: &str) -> bool {
path == "assets"
}
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_false(value: &bool) -> bool {
!*value
}
/// Package type indicating what kind of project this is.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PackageType {
/// A standalone application with platform-specific backends.
#[default]
App,
/// A playground project for quick experimentation.
/// Platform projects are created in a temporary directory.
Playground,
}
#[cfg(test)]
mod channel_tests {
use super::*;
#[test]
fn local_framework_requirement_is_checked_before_project_io() {
smol::block_on(async {
let directory = tempfile::tempdir().unwrap();
let framework_root = directory.path().join("framework");
let project_root = directory.path().join("consumer");
smol::fs::create_dir(&framework_root).await.unwrap();
let mut minimum: cargo_toml::SemVer = env!("CARGO_PKG_VERSION").parse().unwrap();
minimum.major += 1;
let mut metadata = toml::toml! {
[package.metadata.waterui]
minimum-cli-version = "0.1.4"
android-min-api-level = 26
};
metadata["package"]["metadata"]["waterui"]["minimum-cli-version"] =
toml::Value::String(minimum.to_string());
smol::fs::write(
framework_root.join("Cargo.toml"),
toml::to_string(&metadata).unwrap(),
)
.await
.unwrap();
let bundle_identifier =
BundleIdentifier::try_from("dev.waterui.compatibility").unwrap();
let options = CreateOptions {
name: "Compatibility".into(),
bundle_identifier: bundle_identifier.clone(),
package_type: PackageType::Playground,
waterui_path: Some(framework_root),
channel: None,
framework_manifest: None,
framework: None,
author: String::new(),
backends: Vec::new(),
web: None,
};
let error = Project::create(&project_root, options)
.await
.unwrap_err()
.to_string();
assert!(error.contains(&format!("requires waterui-cli >= {minimum}")));
assert!(error.contains(&format!(
"cargo install waterui-cli --git {} --locked",
env!("CARGO_PKG_REPOSITORY")
)));
assert!(!project_root.exists());
smol::fs::create_dir(&project_root).await.unwrap();
let mut manifest = Manifest::new(Package {
name: "Compatibility".into(),
bundle_identifier,
package_type: PackageType::Playground,
assets_path: default_assets_path(),
accessory: false,
});
manifest.waterui_path = Some("../framework".into());
manifest.save(&project_root).await.unwrap();
let error = Project::open_for_preview_build(&project_root)
.await
.unwrap_err()
.to_string();
assert!(error.contains(&format!("requires waterui-cli >= {minimum}")));
assert!(!project_root.join("Cargo.lock").exists());
});
}
#[test]
fn failed_channel_selection_preserves_project_files() {
smol::block_on(async {
let directory = tempfile::tempdir().unwrap();
let root = directory.path();
let originals = [
("Cargo.toml", b"original manifest".as_slice()),
("Cargo.lock", b"original dependency lock".as_slice()),
("Water.toml", b"original project configuration".as_slice()),
];
for (name, contents) in originals {
smol::fs::write(root.join(name), contents).await.unwrap();
}
let updates = ["Cargo.toml", "Cargo.lock", "Water.toml", "Water.lock"]
.into_iter()
.map(|name| (root.join(name), Some(b"invalid selected manifest".to_vec())))
.collect();
assert!(
apply_channel_selection(
root,
crate::framework::test_fixtures::stable_framework(),
updates
)
.await
.is_err()
);
for (name, contents) in originals {
assert_eq!(smol::fs::read(root.join(name)).await.unwrap(), contents);
}
assert!(!root.join("Water.lock").exists());
});
}
}
#[cfg(test)]
mod webview_backend_tests {
use super::{
ResolvedWebViewBackend, TargetBackend, TargetPlatform, resolve_enabled_features,
resolve_linked_runtime_packages,
};
/// An application that links no engine crate uses whatever the platform
/// bridges, and the bridge is not everywhere: Linux outside GTK has none, so
/// such a build is refused with an explanation instead of producing a
/// contentless web view at runtime.
#[test]
fn the_platform_bridge_is_the_selection_without_an_engine_crate() {
assert_eq!(
ResolvedWebViewBackend::System
.validate(TargetPlatform::MacOS, TargetBackend::Hydrolysis)
.expect("macOS Hydrolysis bridges WKWebView"),
ResolvedWebViewBackend::System
);
assert_eq!(
ResolvedWebViewBackend::System
.validate(TargetPlatform::Linux, TargetBackend::Gtk4)
.expect("GTK bridges WebKitGTK"),
ResolvedWebViewBackend::System
);
assert!(
ResolvedWebViewBackend::System
.validate(TargetPlatform::Linux, TargetBackend::Hydrolysis)
.is_err()
);
assert!(
ResolvedWebViewBackend::System
.validate(TargetPlatform::Windows, TargetBackend::Hydrolysis)
.is_err()
);
}
#[test]
fn unsupported_engine_combinations_fail_before_build() {
assert!(
ResolvedWebViewBackend::Wpe
.validate(TargetPlatform::MacOS, TargetBackend::Hydrolysis)
.is_err()
);
assert!(
ResolvedWebViewBackend::Cef
.validate(TargetPlatform::Android, TargetBackend::Android)
.is_err()
);
assert_eq!(
ResolvedWebViewBackend::Cef
.validate(TargetPlatform::MacOS, TargetBackend::Apple)
.expect("CEF must compose with the native Apple renderer on macOS"),
ResolvedWebViewBackend::Cef
);
}
#[test]
fn cef_is_available_to_every_non_dew_backend_on_desktop_platforms() {
for backend in [
TargetBackend::Apple,
TargetBackend::Android,
TargetBackend::Gtk4,
TargetBackend::Hydrolysis,
] {
for platform in [
TargetPlatform::MacOS,
TargetPlatform::Linux,
TargetPlatform::Windows,
] {
assert_eq!(
ResolvedWebViewBackend::Cef
.validate(platform, backend)
.expect("CEF availability must not depend on the WaterUI backend"),
ResolvedWebViewBackend::Cef
);
}
}
}
#[test]
fn cef_rejects_dew_and_platforms_without_cef_distributions() {
for platform in [
TargetPlatform::MacOS,
TargetPlatform::Linux,
TargetPlatform::Windows,
] {
assert!(
ResolvedWebViewBackend::Cef
.validate(platform, TargetBackend::Dew)
.is_err()
);
}
for (platform, backend) in [
(TargetPlatform::Android, TargetBackend::Android),
(TargetPlatform::IOS, TargetBackend::Apple),
(TargetPlatform::Web, TargetBackend::Hydrolysis),
] {
assert!(
ResolvedWebViewBackend::Cef
.validate(platform, backend)
.is_err()
);
}
}
/// The engine is read out of the application's own graph, so the examples
/// are the test: the CEF `WebView` example links `waterui-browser-cef` and
/// the shared system-`WebView` example links no engine at all. The
/// examples live in the framework repository — this crate builds against a
/// pinned `water-rs/waterui` revision, and the test clones it on demand.
#[test]
#[ignore = "clones the pinned framework revision"]
fn runtime_graph_is_scoped_to_the_selected_application() {
let repository = crate::pinned_framework::checkout();
let chromium = smol::block_on(resolve_linked_runtime_packages(
repository.join("examples/chromium"),
true,
))
.expect("Chromium example runtime graph must resolve");
assert!(
chromium.contains_key("waterui-chromium"),
"Chromium example graph: {chromium:#?}"
);
// The Chromium example links the engine it draws through, and nothing
// else: no second engine, and no `waterui` facade `webview` feature.
assert!(
chromium.contains_key("waterui-browser-cef"),
"Chromium example graph: {chromium:#?}"
);
assert!(
!chromium.contains_key("waterui-browser-wpe"),
"Chromium example graph: {chromium:#?}"
);
// A Chromium-only application shows no standard `WebView`, so
// `webview_enabled` must be false for it: the Apple scaffold reads this
// graph to decide whether to link the `WaterUICefWebView` framework.
// The `waterui-webview` package is present — `waterui-chromium` links
// it for the shared asset-server types — so the signal is the `webview`
// feature, which nothing in this subtree turns on.
assert!(
chromium.contains_key("waterui-webview"),
"waterui-chromium shares the webview asset-server types: {chromium:#?}"
);
let chromium_features = smol::block_on(resolve_enabled_features(
repository.join("examples/chromium"),
true,
))
.expect("Chromium example feature graph must resolve");
assert!(
!chromium_features.contains("webview"),
"a Chromium-only application must not enable the standard WebView \
component: {chromium_features:#?}"
);
let webview = smol::block_on(resolve_linked_runtime_packages(
repository.join("examples/webview"),
true,
))
.expect("WebView example runtime graph must resolve");
assert!(
webview.contains_key("waterui-webview"),
"WebView example graph: {webview:#?}"
);
let webview_features = smol::block_on(resolve_enabled_features(
repository.join("examples/webview"),
true,
))
.expect("WebView example feature graph must resolve");
assert!(
webview_features.contains("webview"),
"the WebView example enables the facade `webview` feature: {webview_features:#?}"
);
assert!(
!webview.contains_key("waterui-browser-cef"),
"WebView example graph: {webview:#?}"
);
assert!(
!webview.contains_key("waterui-chromium"),
"WebView example graph: {webview:#?}"
);
let cef_webview = smol::block_on(resolve_linked_runtime_packages(
repository.join("examples/webview-cef"),
true,
))
.expect("CEF WebView example runtime graph must resolve");
assert!(
cef_webview.contains_key("waterui-browser-cef"),
"CEF WebView example graph: {cef_webview:#?}"
);
assert!(
!cef_webview.contains_key("waterui-browser-wpe"),
"CEF WebView example graph: {cef_webview:#?}"
);
}
/// The `map` capability — the Apple `MapKit` bridge's `-DWATERUI_MAP`, and
/// the FFI's `map` feature — is read off the application's own graph, the
/// same way the browser engine is. `waterui-map` is a component crate an
/// application depends on directly; no facade feature announces it any
/// more, so linking it is what the capability has to see. The examples
/// live in the framework repository — this crate builds against a pinned
/// `water-rs/waterui` revision, and the test clones it on demand.
#[test]
#[ignore = "clones the pinned framework revision"]
fn the_map_capability_is_read_from_the_application_graph() {
let repository = crate::pinned_framework::checkout();
let map = smol::block_on(resolve_linked_runtime_packages(
repository.join("examples/map"),
true,
))
.expect("map example runtime graph must resolve");
assert!(
map.contains_key("waterui-map"),
"map example graph: {map:#?}"
);
let webview = smol::block_on(resolve_linked_runtime_packages(
repository.join("examples/webview"),
true,
))
.expect("WebView example runtime graph must resolve");
assert!(
!webview.contains_key("waterui-map"),
"an application that shows no map must not carry the map stack: {webview:#?}"
);
}
}
#[cfg(test)]
mod scaffold_tests {
use std::path::Path;
use super::{BundleIdentifier, CreateOptions, PackageType, Project, TargetBackend};
/// The documented `assets!` workflow requires the assets root to exist: the
/// planner walks it recursively, so a missing directory fails the first
/// `assets!` call. `water create` must therefore produce it, tracked, and at
/// exactly the path the generated `Water.toml` declares.
#[test]
fn create_scaffolds_the_assets_directory_declared_by_the_manifest() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path().join("water-example");
let project = smol::block_on(Project::create(
&root,
CreateOptions {
name: "Water Example".to_string(),
bundle_identifier: BundleIdentifier::try_from("dev.waterui.waterexample")
.expect("bundle identifier"),
package_type: PackageType::Playground,
waterui_path: None,
channel: None,
framework_manifest: None,
// A channel resolution would fetch the newest release from
// GitHub; a unit test resolves a fixture in place instead.
framework: Some(crate::framework::test_fixtures::stable_framework()),
author: "Lexo Liu".to_string(),
backends: Vec::new(),
web: None,
},
))
.expect("project creation must succeed");
let assets = project.assets_dir();
assert!(
assets.is_dir(),
"the assets root {} must exist after `water create`",
assets.display()
);
assert_eq!(
assets,
root.join(project.assets_path()),
"the scaffolded directory must be the one the manifest declares"
);
assert!(
assets.join("README.md").is_file(),
"a tracked file keeps the assets directory present in git"
);
}
/// `stable` withholds the git-pinned experimental scaffold packages, so a
/// backend whose generated crate links one — GTK4, `WinUI`, Dew — must fail
/// `create` before a file lands, naming the package and the channel fix
/// rather than dying partway through the backend's own scaffold.
#[test]
fn create_rejects_backends_whose_packages_stable_withholds() {
for backend in [
TargetBackend::Gtk4,
TargetBackend::WinUi,
TargetBackend::Dew,
] {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path().join("water-example");
let error = smol::block_on(Project::create(
&root,
CreateOptions {
name: "Water Example".to_string(),
bundle_identifier: BundleIdentifier::try_from("dev.waterui.waterexample")
.expect("bundle identifier"),
package_type: PackageType::App,
waterui_path: None,
channel: None,
framework_manifest: None,
framework: Some(crate::framework::test_fixtures::stable_framework()),
author: "Lexo Liu".to_string(),
backends: vec![backend],
web: None,
},
))
.expect_err("a withheld scaffold package must reject create");
let error = error.to_string();
for package in backend.scaffold_packages() {
assert!(error.contains(package), "{error}");
}
assert!(error.contains("stable"), "{error}");
assert!(error.contains("--channel dev"), "{error}");
assert!(
!root.exists(),
"the rejection precedes any file write: {error}"
);
}
}
/// Generated crate names carry the project-root tag that keeps a shared
/// Cargo target directory unambiguous; the names packaged binaries ship
/// under drop it — a checkout path must never appear in a shipped
/// executable name.
#[test]
fn shipped_binary_names_drop_the_project_root_tag() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path().join("water-example");
let project = smol::block_on(Project::create(
&root,
CreateOptions {
name: "Water Example".to_string(),
bundle_identifier: BundleIdentifier::try_from("dev.waterui.waterexample")
.expect("bundle identifier"),
package_type: PackageType::Playground,
waterui_path: None,
channel: None,
framework_manifest: None,
framework: Some(crate::framework::test_fixtures::stable_framework()),
author: "Lexo Liu".to_string(),
backends: Vec::new(),
web: None,
},
))
.expect("project creation must succeed");
for (shipped, tagged) in [
(project.gtk4_binary_name(), project.gtk_backend_crate_name()),
(
project.hydrolysis_binary_name(),
project.hydrolysis_backend_crate_name(),
),
(
project.winui_binary_name(),
project.winui_backend_crate_name(),
),
(
project.esp32_binary_name(),
project.esp32_backend_crate_name(),
),
] {
assert!(
tagged.as_str().starts_with(&format!("{shipped}-")),
"the build name must be the shipped name plus the tag: {tagged}"
);
assert_eq!(
tagged.as_str().len() - shipped.as_str().len(),
9,
"the tag is a dash plus eight hex digits: {tagged}"
);
}
}
/// Packaged executables stage under the project's own managed backend
/// directory — `dist/<platform>/<profile>` below `backend_path` — so
/// two projects sharing a crate name, most often two worktrees of one
/// project, never write the same shipped path the way the shared Cargo
/// profile directory made them.
#[test]
fn same_named_projects_stage_packaged_binaries_under_their_own_backends() {
let dir = tempfile::tempdir().expect("temp dir");
let create = |root: &Path| {
smol::block_on(Project::create(
root,
CreateOptions {
name: "Water Example".to_string(),
bundle_identifier: BundleIdentifier::try_from("dev.waterui.waterexample")
.expect("bundle identifier"),
package_type: PackageType::App,
waterui_path: None,
channel: None,
framework_manifest: None,
framework: Some(crate::framework::test_fixtures::stable_framework()),
author: "Lexo Liu".to_string(),
backends: Vec::new(),
web: None,
},
))
.expect("project creation must succeed")
};
let first = create(&dir.path().join("one/demo"));
let second = create(&dir.path().join("two/demo"));
let staged = |project: &Project| {
crate::platforming::packaging::dist_dir(
&project.backend_path::<crate::hydrolysis::backend::HydrolysisBackend>(),
"linux",
Some("release"),
)
.join(project.hydrolysis_binary_name().as_str())
};
let first_staged = staged(&first);
let second_staged = staged(&second);
assert_ne!(
first_staged, second_staged,
"same-named projects must not stage the same shipped path"
);
for (project, staged) in [(&first, &first_staged), (&second, &second_staged)] {
assert!(
staged.starts_with(
project.backend_path::<crate::hydrolysis::backend::HydrolysisBackend>()
),
"{} must live under the project's own managed backend directory",
staged.display()
);
}
}
}
#[cfg(test)]
mod local_patch_tests {
use std::path::Path;
use super::Project;
/// A project on a `waterui_path` mirrors the checkout's `[patch]` tables
/// every time it opens: entries the checkout dropped disappear, moved ones
/// follow, and a project already in line is left byte-for-byte alone.
#[test]
fn a_local_checkout_project_follows_the_checkouts_patch_tables() {
let directory = tempfile::tempdir().expect("temp dir");
let checkout = directory.path().join("waterui");
std::fs::create_dir_all(&checkout).expect("checkout dir");
std::fs::write(
checkout.join("Cargo.toml"),
include_str!("../../tests/fixtures/local_checkout_patches.toml"),
)
.expect("checkout manifest");
let app = directory.path().join("app");
std::fs::create_dir_all(&app).expect("project dir");
let cargo_path = app.join("Cargo.toml");
std::fs::write(
&cargo_path,
"[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\nwaterui = { path = \"../waterui\" }\n\n[patch.crates-io]\nwaterui-core = { path = \"../elsewhere/core\" }\nstale = { path = \"../elsewhere/stale\" }\n",
)
.expect("project manifest");
smol::block_on(Project::refresh_local_patches(
&app,
Path::new("../waterui"),
))
.expect("tables refresh");
let refreshed = std::fs::read_to_string(&cargo_path).expect("refreshed manifest");
let manifest = cargo_toml::Manifest::from_str(&refreshed).expect("manifest parses");
let crates_io = &manifest.patch["crates-io"];
let cargo_toml::Dependency::Detailed(core) = &crates_io["waterui-core"] else {
panic!("the core patch is a path dependency");
};
assert_eq!(core.path.as_deref(), Some("../waterui/core"));
assert!(!crates_io.contains_key("stale"));
assert!(crates_io.contains_key("vello"));
assert!(refreshed.starts_with("[package]"));
smol::block_on(Project::refresh_local_patches(
&app,
Path::new("../waterui"),
))
.expect("second refresh");
assert_eq!(
std::fs::read_to_string(&cargo_path).expect("manifest after the second refresh"),
refreshed
);
}
/// A project inside the checkout's own workspace — every example in this
/// repository — is already governed by the checkout's tables, so nothing is
/// copied into the member manifest, where Cargo would ignore it and warn on
/// every build.
#[test]
fn a_member_of_the_checkouts_workspace_keeps_its_manifest() {
let directory = tempfile::tempdir().expect("temp dir");
let checkout = directory.path().join("waterui");
let app = checkout.join("examples/app");
std::fs::create_dir_all(&app).expect("project dir");
std::fs::write(
checkout.join("Cargo.toml"),
include_str!("../../tests/fixtures/local_checkout_patches.toml"),
)
.expect("checkout manifest");
let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\nwaterui = { path = \"../..\" }\n";
let cargo_path = app.join("Cargo.toml");
std::fs::write(&cargo_path, manifest).expect("project manifest");
smol::block_on(Project::refresh_local_patches(&app, Path::new("../..")))
.expect("tables refresh");
assert_eq!(
std::fs::read_to_string(&cargo_path).expect("manifest after the refresh"),
manifest
);
}
/// A project inside someone else's workspace cannot carry the tables at all:
/// Cargo reads them from that workspace root. Saying which manifest they
/// belong in beats writing a copy that is read by nobody.
#[test]
fn a_member_of_a_foreign_workspace_is_told_where_the_tables_belong() {
let directory = tempfile::tempdir().expect("temp dir");
let checkout = directory.path().join("waterui");
std::fs::create_dir_all(&checkout).expect("checkout dir");
std::fs::write(
checkout.join("Cargo.toml"),
include_str!("../../tests/fixtures/local_checkout_patches.toml"),
)
.expect("checkout manifest");
let workspace = directory.path().join("their-workspace");
let app = workspace.join("app");
std::fs::create_dir_all(&app).expect("project dir");
std::fs::write(
workspace.join("Cargo.toml"),
"[workspace]\nmembers = [\"app\"]\n",
)
.expect("workspace manifest");
let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\nwaterui = { path = \"../../waterui\" }\n";
let cargo_path = app.join("Cargo.toml");
std::fs::write(&cargo_path, manifest).expect("project manifest");
let error = smol::block_on(Project::refresh_local_patches(
&app,
Path::new("../../waterui"),
))
.expect_err("a copy here would be ignored");
let message = error.to_string();
assert!(message.contains("their-workspace"), "{message}");
assert_eq!(
std::fs::read_to_string(&cargo_path).expect("manifest after the refusal"),
manifest
);
}
}