bobview 1.10.0

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

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use bob::{Macros, Source};
use eframe::egui::{self, Id, Pos2, Rect, Vec2};
use parking_lot::Mutex;
use pv::PvManager;

use crate::chrome::{self, Chrome, UiScale};
use crate::icons::{self, Icon};
use crate::layout::{self, Geometry, Layout, TrendLayout, WindowLayout, Zoom};
use crate::pvmenu;
use crate::selection;
use crate::style;
use crate::tree::{self, Navigator};
use crate::trend::Trend;
use crate::view::{LaunchKey, Origin, View, ViewCx, WindowKey, window_title};
use crate::widgets::{self, Request};
use archiveview::ArchiverClient;

#[derive(Clone, Debug, PartialEq)]
pub struct Location {
    pub source: Source,
    pub macros: Macros,
}

impl Location {
    /// The same display with the same effective macros, however they were
    /// layered (see `effective`).
    pub(crate) fn same_display(&self, other: &Location) -> bool {
        self.source == other.source && self.effective() == other.effective()
    }

    /// The macros that tell this display apart, later definitions winning.
    /// A BOY display's `$(DID)` is left out: one opened in a window of its
    /// own is given a fresh one whatever a link passes (the id of the
    /// display the link is on).
    pub(crate) fn effective(&self) -> std::collections::BTreeMap<&str, &str> {
        let opi = self
            .source
            .to_string()
            .to_ascii_lowercase()
            .ends_with(".opi");
        self.macros
            .iter()
            .filter(|(k, _)| !(opi && *k == "DID"))
            .collect()
    }
}

pub struct BobApp {
    pvs: PvManager,
    /// What repaints each window (main, display and trend) for its PVs.
    repaints: HashMap<egui::ViewportId, Arc<Repaint>>,
    /// The main window's display.
    main: View,
    /// Where the main window is, for saving a layout.
    geometry: Geometry,
    /// The display windows other than the main one, and the number the
    /// next one's id is made from.
    windows: Vec<DisplayWindow>,
    next_window: u64,
    /// Pin mode: a link in a pinned window opens its display in the viewer
    /// (the unpinned window used last) or a new window; one in an unpinned
    /// window navigates in place.
    main_pinned: bool,
    main_used: Used,
    /// When the main window was pinned, by `clock` (0: from the start).
    main_pinned_at: u64,
    /// Counts the windows' uses, to find the one used last.
    clock: u64,
    /// Displays can have native windows of their own (see `can_multi_window`).
    can_windows: bool,
    /// The layout last loaded or saved, which Save saves to.
    layout_name: Option<String>,
    /// A layout to load once the controls' scale has settled (and the
    /// monitors are known).
    pending_layout: Option<(Layout, Option<String>)>,
    /// The monitors, in desktop points, when the window system says, and
    /// when they were last asked for (seconds since start).
    monitors: Vec<Rect>,
    #[cfg_attr(
        target_arch = "wasm32",
        expect(dead_code, reason = "a browser has one window")
    )]
    monitors_at: Option<f64>,
    /// Where the main window is on the desktop, to open windows beside it.
    main_frame: Option<Frame>,
    /// The main window's place and size from a layout, and when (input
    /// time) the wait for them began, until it has them or `RESTORE_WAIT`
    /// has passed: a window manager that sized it before moving it may have
    /// cut it to the monitor it was on.
    restoring: Option<(Geometry, Option<f64>)>,
    settings: layout::Settings,
    /// The Save as… dialog, when open.
    save_as: Option<SaveAs>,
    home: Option<Location>,
    show_open: bool,
    /// The tree of the displays the main window's links to, its width as
    /// last drawn (0 when hidden), and whether its toolbar button has just
    /// shown or hidden it.
    tree: Navigator,
    tree_width: f32,
    tree_toggled: bool,
    /// Touch mode: finger-sized controls and no windows of their own
    /// (switched on by the first touch).
    touch: bool,
    /// The PV details dialog, and the window it was asked for in.
    details: Option<(WindowKey, pvmenu::Details)>,
    /// The saved layouts, for the toolbar's menus.
    layouts: LayoutList,
    /// Open trend windows, and the id the next one gets.
    trends: Vec<Trend>,
    next_trend: u64,
    /// Where trends fetch history from; none for live only.
    archiver: Option<ArchiverClient>,
    /// Displays named by command actions, worked out on threads.
    launched: (
        std::sync::mpsc::Sender<Launched>,
        std::sync::mpsc::Receiver<Launched>,
    ),
    chrome: Chrome,
    /// Where a copied PV name also goes, for a middle-click to paste.
    primary: Box<dyn selection::Primary>,
    /// Reads the primary selection for a middle-click on a trend, on a
    /// thread of its own, made by `make_reader` at the first such click.
    /// Neither where there is no primary selection, nor in snapshots.
    reader: Option<selection::Reader<SelectionRead>>,
    make_reader: Option<selection::MakeRead>,
    /// Middle-clicks on trends so far, to number them.
    clicks: u64,
}

/// A read of the primary selection for a middle-click on a trend: the
/// trend's id, the click's number, and where on the trend it landed.
type SelectionRead = (u64, u64, archiveview::plot::MiddleClick);

/// Repaints one window when a PV it shows changes, at most ~10 times a
/// second, asking once per pass of the window: egui keeps a record of every
/// request until the window's next pass, and passes stop while the desktop
/// is locked.
struct Repaint {
    ctx: egui::Context,
    viewport: egui::ViewportId,
    /// Set by a PV update that has asked, cleared by the window's next pass.
    asked: AtomicBool,
}

impl Repaint {
    fn new(ctx: &egui::Context, viewport: egui::ViewportId) -> Arc<Self> {
        Arc::new(Self {
            ctx: ctx.clone(),
            viewport,
            asked: AtomicBool::new(false),
        })
    }

    /// The notifier to tag the window's PVs with (see `PvManager::tagged`).
    fn notifier(self: &Arc<Self>) -> pv::Notifier {
        let this = self.clone();
        Arc::new(move || {
            if !this.asked.swap(true, Ordering::Relaxed) {
                repaint_after(&this.ctx, this.viewport, Duration::from_millis(100));
            }
        })
    }

    /// The window's pass begins: before its PVs are read, so a later update
    /// asks again.
    fn begin(&self) {
        self.asked.store(false, Ordering::Relaxed);
    }
}

/// Repaint the window `viewport` after `delay`: the main window, where
/// windows are drawn inside it.
fn repaint_after(ctx: &egui::Context, viewport: egui::ViewportId, delay: Duration) {
    let viewport = if ctx.embed_viewports() {
        egui::ViewportId::ROOT
    } else {
        viewport
    };
    ctx.request_repaint_after_for(delay, viewport);
}

/// A command action's result, tagged with where it was started (its window
/// and whether ctrl was held) and the display it was started on.
struct Launched {
    key: LaunchKey,
    origin: Origin,
    shown: u64,
    target: Option<Location>,
}

/// The saved layouts' names, read when a menu listing them opens and after
/// a save or delete, not on every frame it is open.
#[derive(Default)]
struct LayoutList {
    names: Vec<String>,
    /// The (main window's) frame they were last listed on.
    frame: Option<u64>,
}

impl LayoutList {
    fn get(&mut self, ctx: &egui::Context) -> Vec<String> {
        let frame = ctx.cumulative_frame_nr();
        if self.frame.is_none_or(|f| f + 1 < frame) {
            self.names = layout::list();
        }
        self.frame = Some(frame);
        self.names.clone()
    }

    /// Read them again next time.
    fn refresh(&mut self) {
        self.frame = None;
    }
}

/// A display in a native window of its own, opened by a link or
/// from a layout.
struct DisplayWindow {
    /// Stable for the window's life: made from a counter, never reused.
    id: egui::ViewportId,
    view: View,
    /// The size and place it is created with.
    builder: egui::ViewportBuilder,
    /// Size the window to the next display shown: not when a layout gave
    /// its size.
    fit_next: bool,
    /// Show the display toolbar (Ctrl+T, the chevron or the context menu).
    toolbar: bool,
    /// Where the window is, for saving a layout.
    geometry: Geometry,
    /// Where it is on the desktop, to open windows beside it.
    frame: Option<Frame>,
    /// The window it was opened from, to be placed beside again once it
    /// has been sized to its display.
    beside: Option<Frame>,
    pinned: bool,
    /// When it was pinned, by the application's clock.
    pinned_at: u64,
    used: Used,
    close: bool,
}

/// Where a window is on the desktop, in desktop points: its outer rectangle,
/// and how much bigger that is than its inside (the title bar and borders).
#[derive(Clone, Copy, Debug, PartialEq)]
struct Frame {
    outer: Rect,
    border: Vec2,
}

/// Where a window `size` inside (in desktop points) goes beside the window
/// at `origin`, clear of it and of the `pinned` windows (the one pinned last
/// first). The places tried are beside the window pinned last, so a row of
/// small windows grows beside a big one, then beside `origin`, then beside
/// each other pinned window: to its right (top edges level), below it (left
/// edges level), to its left and above it, each slid along that side to
/// stay on the monitor that window is most on.
/// The first that fits on its monitor clear of them all wins; else the one
/// that covers them least, or over `origin` on the side with more room.
fn beside(origin: Frame, pinned: &[Rect], size: Vec2, monitors: &[Rect]) -> Option<Pos2> {
    let monitor = |r: &Rect| {
        monitors
            .iter()
            .max_by(|a, b| overlap(a, r).total_cmp(&overlap(b, r)))
            .copied()
    };
    let o = origin.outer;
    let m = monitor(&o)?;
    let outer = size + origin.border;
    let clear: Vec<Rect> = std::iter::once(o).chain(pinned.iter().copied()).collect();
    let anchors = pinned.first().into_iter().chain(&clear);
    let mut places = Vec::new();
    for a in anchors {
        let Some(m) = monitor(a) else { continue };
        let x = a.min.x.min(m.max.x - outer.x).max(m.min.x);
        let y = a.min.y.min(m.max.y - outer.y).max(m.min.y);
        let sides = [
            Pos2::new(a.max.x, y),
            Pos2::new(x, a.max.y),
            Pos2::new(a.min.x - outer.x, y),
            Pos2::new(x, a.min.y - outer.y),
        ];
        places.extend(
            sides
                .into_iter()
                .filter(|p| m.contains_rect(Rect::from_min_size(*p, outer))),
        );
    }
    let covered = |p: &Pos2| {
        let r = Rect::from_min_size(*p, outer);
        clear.iter().map(|c| overlap(c, &r)).sum::<f32>()
    };
    if let Some(p) = places.iter().find(|p| covered(p) == 0.0) {
        return Some(*p);
    }
    let over = if m.max.x - o.max.x >= o.min.x - m.min.x {
        m.max.x - outer.x
    } else {
        m.min.x
    };
    let y = o.min.y.min(m.max.y - outer.y).max(m.min.y);
    places.push(Pos2::new(over.max(m.min.x), y));
    // The first of those that cover them least.
    places
        .into_iter()
        .min_by(|a, b| covered(a).total_cmp(&covered(b)))
}

/// The monitors and the pinned windows, for placing a display window.
struct Desk {
    monitors: Vec<Rect>,
    pinned: Vec<(WindowKey, Rect)>,
}

impl Desk {
    /// The pinned windows other than `id`.
    fn clear_of(&self, id: egui::ViewportId) -> Vec<Rect> {
        self.pinned
            .iter()
            .filter(|(key, _)| *key != WindowKey::Child(id))
            .map(|(_, r)| *r)
            .collect()
    }
}

/// The area two rectangles share.
fn overlap(a: &Rect, b: &Rect) -> f32 {
    let i = a.intersect(*b);
    if i.is_positive() { i.area() } else { 0.0 }
}

/// When a window was last used (focused, opened or unpinned), by the
/// application's clock, for the viewer to be the unpinned window used last.
#[derive(Clone, Copy, Debug, Default)]
struct Used {
    focused: bool,
    at: u64,
}

impl Used {
    /// Whether the window has the focus: used when it gains it.
    fn focus(&mut self, focused: bool, clock: &mut u64) {
        if focused && !self.focused {
            self.touch(clock);
        }
        self.focused = focused;
    }

    fn touch(&mut self, clock: &mut u64) {
        *clock += 1;
        self.at = *clock;
    }
}

/// The Save as… dialog: the name typed, and whether replacing the layout
/// of that name has been asked about.
#[derive(Default)]
struct SaveAs {
    name: String,
    confirm: bool,
}

/// Where a link's display is shown.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Route {
    /// In the window the link is in, which keeps its history.
    InPlace,
    /// Raise the window already showing it.
    Raise(WindowKey),
    /// In the viewer, which keeps its history, raised.
    Viewer(WindowKey),
    /// A new window.
    NewWindow,
}

/// Where a link from `origin` goes, whatever its target, since most links
/// are `replace`. Ctrl+click navigates in place, as every link does where
/// displays have no `windows` of their own. Otherwise a display already
/// open with the same macros is raised (`showing`), or shown again in place
/// when that is the link's own window; shift+click opens a new
/// window; a link in an unpinned window navigates in place, and one in a
/// `pinned` window opens in the `viewer`, or a new window when every window
/// is pinned.
fn route(
    windows: bool,
    origin: Origin,
    pinned: bool,
    showing: Option<WindowKey>,
    viewer: Option<WindowKey>,
) -> Route {
    if !windows || origin.ctrl {
        return Route::InPlace;
    }
    match (showing, viewer) {
        // Shown again, with fresh PVs, as a Refresh button wants.
        (Some(window), _) if window == origin.window => Route::InPlace,
        (Some(window), _) => Route::Raise(window),
        _ if origin.shift => Route::NewWindow,
        _ if !pinned => Route::InPlace,
        (None, Some(window)) => Route::Viewer(window),
        (None, None) => Route::NewWindow,
    }
}

impl BobApp {
    pub fn new(
        ctx: &egui::Context,
        start: Option<Location>,
        zoom: Option<f32>,
        ui_scale: UiScale,
    ) -> Self {
        style::install_fonts(ctx);
        ctx.set_theme(egui::Theme::Light);
        // The controls' zoom is ours (see `chrome`), not ctrl+plus/minus.
        ctx.options_mut(|o| o.zoom_with_keyboard = false);

        // No notifier for every PV: each window's PVs repaint only it.
        let pvs = PvManager::new();
        let repaint = Repaint::new(ctx, egui::ViewportId::ROOT);
        let mut main = View::new(&pvs.tagged(repaint.notifier()), zoom);
        main.open_path = start
            .as_ref()
            .map(|l| l.source.to_string())
            .unwrap_or_default();
        let mut app = Self {
            pvs,
            repaints: HashMap::from([(egui::ViewportId::ROOT, repaint)]),
            main,
            geometry: Geometry::default(),
            windows: Vec::new(),
            next_window: 0,
            main_pinned: true,
            main_used: Used::default(),
            main_pinned_at: 0,
            clock: 0,
            can_windows: !cfg!(target_arch = "wasm32"),
            layout_name: None,
            pending_layout: None,
            monitors: Vec::new(),
            monitors_at: None,
            main_frame: None,
            restoring: None,
            settings: layout::Settings::load(),
            save_as: None,
            home: start.clone(),
            show_open: start.is_none(),
            tree: Navigator::default(),
            tree_width: 0.0,
            tree_toggled: false,
            touch: false,
            details: None,
            layouts: LayoutList::default(),
            trends: Vec::new(),
            next_trend: 0,
            archiver: None,
            launched: std::sync::mpsc::channel(),
            chrome: Chrome::new(ui_scale),
            primary: selection::system(),
            reader: None,
            make_reader: selection::system_reader(),
            clicks: 0,
        };
        if let Some(loc) = start {
            app.main.show(loc);
        }
        app
    }

    /// Refuse every write to a PV (see [`pv::PvManager::set_read_only`]).
    #[cfg_attr(
        target_arch = "wasm32",
        expect(dead_code, reason = "a browser's PVs come from the server's policy")
    )]
    pub fn set_read_only(&mut self, on: bool) {
        self.pvs.set_read_only(on);
    }

    /// Put copied PV names on `primary` instead of the desktop's primary
    /// selection.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn set_primary(&mut self, primary: Box<dyn selection::Primary>) {
        self.primary = primary;
    }

    /// Read the primary selection, for a middle-click on a trend, through
    /// `make` (on a thread of its own), or never with `None`.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn set_selection_reader(&mut self, make: Option<selection::MakeRead>) {
        self.reader = None;
        self.make_reader = make;
    }

    /// Answer the trends' middle-clicks from the primary selection: ask
    /// for it for a new click, hand each answer to its trend, and give up
    /// on a click whose answer is slow; and make text selected in a
    /// trend's search box the primary selection. Called after any trend
    /// is drawn.
    fn trend_selections(&mut self, ctx: &egui::Context) {
        let now = web_time::Instant::now();
        for trend in &mut self.trends {
            // Taken where there is no selection too, and dropped.
            let Some(click) = trend.take_middle_click() else {
                continue;
            };
            if self.reader.is_none()
                && let Some(make) = self.make_reader.take()
            {
                let ctx = ctx.clone();
                let wake = move |&(id, ..): &SelectionRead| {
                    repaint_after(&ctx, trend_viewport(id), Duration::ZERO);
                };
                self.reader = Some(selection::Reader::spawn(make, wake));
            }
            if let Some(reader) = &self.reader {
                self.clicks += 1;
                reader.read((trend.id, self.clicks, click));
                trend.reading(self.clicks, now);
                // To time it out, if no answer has come by then.
                let wait = crate::trend::SELECTION_WAIT + Duration::from_millis(50);
                repaint_after(ctx, trend_viewport(trend.id), wait);
            }
        }
        // Before the answers: one that came after the wait (a frame came
        // late) is too late, as one coming later still would be.
        for trend in &mut self.trends {
            if trend.time_out_reading(now) {
                repaint_after(ctx, trend_viewport(trend.id), Duration::ZERO);
            }
        }
        if let Some(reader) = &self.reader {
            while let Some(((id, n, click), text)) = reader.answer() {
                if let Some(trend) = self.trends.iter_mut().find(|t| t.id == id) {
                    trend.selected(n, click, text);
                    repaint_after(ctx, trend_viewport(id), Duration::ZERO);
                }
            }
        }
        for trend in &mut self.trends {
            // Text selected in its search box, once steady, as standalone
            // archiveview does.
            match trend.take_search_selection(now) {
                (Some(text), _) => {
                    if let Err(e) = self.primary.set(&text) {
                        log::debug!("no primary selection: {e}");
                    }
                }
                (None, Some(wait)) => repaint_after(ctx, trend_viewport(trend.id), wait),
                (None, None) => {}
            }
        }
    }

    /// Fetch the trends' history from `archiver`, or none (live only),
    /// remembering it in the settings for later runs if `remember`.
    pub fn set_archiver(&mut self, archiver: Option<ArchiverClient>, remember: bool) {
        let outgoing = self.archiver.as_ref().map(ArchiverClient::base);
        if remember
            && self
                .settings
                .remember_archiver(archiver.as_ref().map(ArchiverClient::base), outgoing)
        {
            self.settings.save();
        }
        self.archiver = archiver;
        for t in &mut self.trends {
            t.set_archiver(self.archiver.as_ref(), &self.settings.recent_archivers);
        }
    }

    /// The user switched archivers in a trend's pill: switch every trend,
    /// remember it, and repaint the other trend windows to fetch again.
    fn switch_archiver(&mut self, ctx: &egui::Context, archiver: Option<ArchiverClient>) {
        log::info!(
            "trend history from {}",
            archiver
                .as_ref()
                .map_or("no archiver", ArchiverClient::base)
        );
        self.set_archiver(archiver, true);
        for t in &self.trends {
            repaint_after(ctx, trend_viewport(t.id), Duration::ZERO);
        }
    }

    /// A trend window of `names`, with the next id.
    fn new_trend(&mut self, ctx: &egui::Context, names: &[String]) -> Trend {
        let pvs = self.pvs_for(ctx, trend_viewport(self.next_trend));
        let archiver = self.archiver.clone();
        let trend = Trend::new(
            self.next_trend,
            names,
            &pvs,
            archiver,
            &self.settings.recent_archivers,
        );
        self.next_trend += 1;
        trend
    }

    /// Restore `layout` (saved as `name`) once the window is up.
    #[cfg_attr(
        target_arch = "wasm32",
        expect(dead_code, reason = "a browser has one window")
    )]
    pub fn restore_layout(&mut self, layout: Layout, name: Option<String>) {
        if layout.windows.iter().any(|w| w.main) {
            self.show_open = false;
        }
        self.pending_layout = Some((layout, name));
    }

    /// The PVs for the display or trend in the window `viewport`, which
    /// repaint only that window.
    fn pvs_for(&mut self, ctx: &egui::Context, viewport: egui::ViewportId) -> PvManager {
        let repaint = self
            .repaints
            .entry(viewport)
            .or_insert_with(|| Repaint::new(ctx, viewport));
        self.pvs.tagged(repaint.notifier())
    }

    /// The window `viewport`'s pass begins (see `Repaint::begin`).
    fn begin_pass(&self, viewport: egui::ViewportId) {
        if let Some(r) = self.repaints.get(&viewport) {
            r.begin();
        }
    }

    /// The view drawn in `window`, unless that window has closed.
    fn view_mut(&mut self, window: WindowKey) -> Option<&mut View> {
        match window {
            WindowKey::Main => Some(&mut self.main),
            WindowKey::Child(id) => self
                .windows
                .iter_mut()
                .find(|w| w.id == id && !w.close)
                .map(|w| &mut w.view),
        }
    }

    /// Where `window` is on the desktop, when the window system says.
    fn frame(&self, window: WindowKey) -> Option<Frame> {
        match window {
            WindowKey::Main => self.main_frame,
            WindowKey::Child(id) => self.windows.iter().find(|w| w.id == id)?.frame,
        }
    }

    /// Where the pinned windows are on the desktop, those the window system
    /// says, the one pinned last first.
    fn pinned_frames(&self) -> Vec<(WindowKey, Rect)> {
        let main = self
            .main_frame
            .filter(|_| self.main_pinned)
            .map(|f| (WindowKey::Main, f.outer, self.main_pinned_at));
        let children = self
            .windows
            .iter()
            .filter(|w| w.pinned && !w.close)
            .filter_map(|w| Some((WindowKey::Child(w.id), w.frame?.outer, w.pinned_at)));
        let mut pinned: Vec<_> = main.into_iter().chain(children).collect();
        pinned.sort_by_key(|(_, _, at)| std::cmp::Reverse(*at));
        pinned.into_iter().map(|(key, r, _)| (key, r)).collect()
    }

    /// The monitors, in desktop points: those the window system lists, else
    /// the main window's.
    fn monitors(&self, ctx: &egui::Context) -> Vec<Rect> {
        if !self.monitors.is_empty() {
            return self.monitors.clone();
        }
        let zoom = ctx.zoom_factor();
        ctx.input(|i| i.viewport().monitor_size)
            .map(|m| vec![Rect::from_min_size(Pos2::ZERO, m * zoom)])
            .unwrap_or_default()
    }

    /// Whether `window` is pinned.
    fn pinned(&self, window: WindowKey) -> bool {
        match window {
            WindowKey::Main => self.main_pinned,
            WindowKey::Child(id) => self.windows.iter().any(|w| w.id == id && w.pinned),
        }
    }

    /// The viewer: the unpinned window used last, if any.
    fn viewer(&self) -> Option<WindowKey> {
        let main = (!self.main_pinned).then_some((WindowKey::Main, self.main_used.at));
        let children = self
            .windows
            .iter()
            .filter(|w| !w.close && !w.pinned)
            .map(|w| (WindowKey::Child(w.id), w.used.at));
        // Of those used at once, the newest.
        main.into_iter()
            .chain(children)
            .max_by_key(|(_, at)| *at)
            .map(|(window, _)| window)
    }

    /// The window showing `loc` (the same display and macros, see
    /// `View::shows`), if any.
    fn showing(&self, loc: &Location) -> Option<WindowKey> {
        if self.main.shows(loc) {
            return Some(WindowKey::Main);
        }
        self.windows
            .iter()
            .find(|w| !w.close && w.view.shows(loc))
            .map(|w| WindowKey::Child(w.id))
    }

    /// Show `loc`, from a link in `origin`'s window: in place, in the
    /// viewer or in a window of its own (see `route`).
    fn follow(&mut self, ctx: &egui::Context, origin: Origin, loc: Location, target: &str) {
        let pinned = self.pinned(origin.window);
        // The link's own window first: another may show the display too.
        let own = self.view_mut(origin.window).is_some_and(|v| v.shows(&loc));
        let showing = if own {
            Some(origin.window)
        } else {
            self.showing(&loc)
        };
        let viewer = self.viewer();
        match route(self.can_windows, origin, pinned, showing, viewer) {
            // The display it shows: read again, as a Refresh button wants,
            // without adding to Back.
            Route::InPlace if own => {
                log::info!("reload {} ({target})", loc.source);
                if let Some(view) = self.view_mut(origin.window) {
                    view.reload();
                }
            }
            Route::InPlace => {
                log::info!("open {} ({target})", loc.source);
                if let Some(view) = self.view_mut(origin.window) {
                    view.open(loc);
                }
            }
            Route::Raise(window) => {
                log::info!("raise {}", loc.source);
                raise(ctx, window);
            }
            Route::Viewer(window) => {
                log::info!("open {} (viewer)", loc.source);
                if let Some(view) = self.view_mut(window) {
                    view.open(loc);
                }
                // Sized to its new display and placed beside the link's
                // window again, as a new window is (not the main window).
                let frame = self.frame(origin.window).filter(|_| !on_wayland());
                if let Some(w) = self
                    .windows
                    .iter_mut()
                    .find(|w| WindowKey::Child(w.id) == window)
                {
                    w.fit_next = true;
                    w.beside = frame;
                }
                raise(ctx, window);
            }
            Route::NewWindow => {
                log::info!("open {} (new window)", loc.source);
                let window = self.open_window(ctx, loc, Geometry::default(), false, false);
                self.place_beside(ctx, window, origin.window);
            }
        }
    }

    /// Open `loc` in a new display window, at `geometry` when known, else
    /// sized to the display at 100% (within the monitor). Unpinned, it is
    /// the viewer, as the window used last.
    fn open_window(
        &mut self,
        ctx: &egui::Context,
        loc: Location,
        geometry: Geometry,
        toolbar: bool,
        pinned: bool,
    ) -> WindowKey {
        let id = egui::ViewportId::from_hash_of(("display", self.next_window));
        self.next_window += 1;
        let mut view = View::new(&self.pvs_for(ctx, id), None);
        view.show(loc);
        // In desktop points: egui's are scaled by its zoom factor.
        let zoom = ctx.zoom_factor();
        let size = geometry.size.map(|s| s / zoom).or_else(|| {
            let monitor = ctx.input(|i| i.viewport().monitor_size);
            let display = view.natural_size(zoom)?;
            Some(chrome::window_size(display, CHILD_STATUS, monitor))
        });
        let mut builder = egui::ViewportBuilder::default()
            .with_app_id("bobview")
            .with_inner_size(size.unwrap_or(chrome::DEFAULT_WINDOW / zoom))
            .with_min_inner_size([160.0, 100.0]);
        if let Some(pos) = geometry.position {
            builder = builder.with_position(Pos2::ZERO + pos.to_vec2() / zoom);
        }
        let mut used = Used::default();
        used.touch(&mut self.clock);
        // From a layout, pinned in the order it lists them.
        let pinned_at = if pinned { used.at } else { 0 };
        self.windows.push(DisplayWindow {
            id,
            view,
            builder,
            fit_next: geometry.size.is_none(),
            toolbar,
            geometry,
            frame: None,
            beside: None,
            pinned,
            pinned_at,
            used,
            close: false,
        });
        WindowKey::Child(id)
    }

    /// Place the new display `window` beside the `origin` window it was
    /// opened from, and again once it has been sized to its display. Not on
    /// Wayland, where the compositor places windows.
    fn place_beside(&mut self, ctx: &egui::Context, window: WindowKey, origin: WindowKey) {
        let Some(frame) = self.frame(origin).filter(|_| !on_wayland()) else {
            return;
        };
        let monitors = self.monitors(ctx);
        let pinned: Vec<Rect> = self
            .pinned_frames()
            .into_iter()
            .filter(|(key, _)| *key != window)
            .map(|(_, r)| r)
            .collect();
        let zoom = ctx.zoom_factor();
        let Some(w) = self
            .windows
            .iter_mut()
            .find(|w| WindowKey::Child(w.id) == window)
        else {
            return;
        };
        let size = w
            .builder
            .inner_size
            .unwrap_or(chrome::DEFAULT_WINDOW / zoom)
            * zoom;
        if let Some(pos) = beside(frame, &pinned, size, &monitors) {
            w.builder = w
                .builder
                .clone()
                .with_position(Pos2::ZERO + pos.to_vec2() / zoom);
        }
        w.beside = Some(frame);
    }

    /// Whether a display, or one named by a command action, is still being
    /// worked out.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn is_loading(&self) -> bool {
        self.main.is_loading()
            || self.windows.iter().any(|w| w.view.is_loading())
            || crate::screen::building()
            || self.trends.iter().any(Trend::is_loading)
    }

    /// Run a command action on a thread, so a slow launcher script or file
    /// system doesn't freeze the window, and open the display it names in
    /// `origin`'s window, as a link there would. A command already in
    /// flight is ignored.
    #[cfg(not(target_arch = "wasm32"))]
    fn launch(
        &mut self,
        ctx: &egui::Context,
        origin: Origin,
        base: Option<Source>,
        dir: Option<Source>,
        cmd: String,
    ) {
        let tx = self.launched.0.clone();
        let Some(view) = self.view_mut(origin.window) else {
            return;
        };
        let key = (
            base.as_ref().map(|s| s.to_string()),
            dir.as_ref().map(|s| s.to_string()),
            cmd.clone(),
        );
        if view.launching.contains(&key) {
            return;
        }
        view.launching.push(key.clone());
        let (ctx, shown) = (ctx.clone(), view.shown);
        std::thread::spawn(move || {
            let target = match crate::launch::command_target(base.as_ref(), dir, &cmd) {
                Some((file, macros)) => {
                    let source = Source::File(file);
                    log::info!("open {source} (window) from '{cmd}'");
                    Some(Location { source, macros })
                }
                None => {
                    log::warn!("command '{cmd}' is not supported");
                    None
                }
            };
            tx.send(Launched {
                key,
                origin,
                shown,
                target,
            })
            .ok();
            // The main window's pass polls for it; on this thread
            // `request_repaint` is whichever window is being drawn.
            ctx.request_repaint_of(egui::ViewportId::ROOT);
        });
    }

    /// A browser runs no commands.
    #[cfg(target_arch = "wasm32")]
    fn launch(
        &mut self,
        _: &egui::Context,
        _: Origin,
        _: Option<Source>,
        _: Option<Source>,
        cmd: String,
    ) {
        log::warn!("command '{cmd}' is not run in a browser");
    }

    /// Open the displays named by finished command actions, unless the user
    /// has since moved to another display or closed the window.
    fn poll_launched(&mut self, ctx: &egui::Context) {
        while let Ok(done) = self.launched.1.try_recv() {
            let Some(view) = self.view_mut(done.origin.window) else {
                continue;
            };
            view.launching.retain(|k| *k != done.key);
            let current = done.shown == view.shown;
            match done.target {
                Some(loc) if current => self.follow(ctx, done.origin, loc, "window"),
                Some(loc) => log::info!("drop {}: the display has changed", loc.source),
                None => {}
            }
        }
    }

    fn toolbar(&mut self, ui: &mut egui::Ui) {
        // One row whatever the width, so a window sized to the display shows
        // it near 100%: navigation, zoom and the panels on the left, the
        // display's name in the middle (elided when there is no room), the
        // window's pin, layouts and a menu of the rest on the right. A narrow
        // window (a phone) keeps Back, Home, the zoom and Fit, and moves the
        // rest into the menu.
        let compact = ui.available_width() < chrome::FULL_TOOLBAR_WIDTH;
        let windows = self.can_windows;
        let was_pinned = self.main_pinned;
        let mut action = None;
        let mut actual_size = false;
        let mut all_windows = None;
        let others = !self.windows.is_empty() || !self.trends.is_empty();
        ui.spacing_mut().button_padding = Vec2::new(10.0, 6.0);
        ui.spacing_mut().item_spacing.x = 8.0;
        // Every item is as tall as a framed group (single buttons in an
        // invisible frame), all along the top of the row, so they line up.
        let button = icons::height(ui);
        ui.spacing_mut().interact_size.y = button;
        let row = Vec2::new(ui.available_width(), icons::group_height(ui));
        let along = egui::Layout::left_to_right(egui::Align::Min);
        ui.allocate_ui_with_layout(row, along, |ui| {
            let view = &mut self.main;
            icons::group(ui, true, |ui| {
                let back = icons::button(ui, Icon::Back, false, !view.back.is_empty())
                    .on_hover_text("Back (Alt+←)");
                self.chrome.button = back.rect.height();
                if back.clicked() {
                    view.go_back();
                }
                if !compact
                    && icons::button(ui, Icon::Forward, false, !view.forward.is_empty())
                        .on_hover_text("Forward (Alt+→)")
                        .clicked()
                {
                    view.go_forward();
                }
                if icons::button(ui, Icon::Home, false, self.home.is_some())
                    .on_hover_text("Home")
                    .clicked()
                    && let Some(home) = self.home.clone()
                {
                    view.open(home);
                }
                if !compact
                    && icons::button(ui, Icon::Reload, false, true)
                        .on_hover_text("Reload (Ctrl+R)")
                        .clicked()
                {
                    view.reload();
                }
            });
            icons::group(ui, true, |ui| {
                if !compact
                    && icons::button(ui, Icon::ZoomOut, false, true)
                        .on_hover_text("Zoom out")
                        .clicked()
                {
                    view.zoom_by(1.0 / 1.25);
                }
                let readout = egui::Button::new(format!("{:.0}%", view.zoom * 100.0))
                    .min_size(Vec2::new(56.0, button));
                actual_size = ui
                    .add(readout)
                    .on_hover_text("Actual size: 100%, and the window sized to fit the display")
                    .clicked();
                if !compact
                    && icons::button(ui, Icon::ZoomIn, false, true)
                        .on_hover_text("Zoom in")
                        .clicked()
                {
                    view.zoom_by(1.25);
                }
                if ui
                    .add(egui::Button::selectable(view.fit, "Fit").min_size(Vec2::new(0.0, button)))
                    .on_hover_text("Fit the display to the window")
                    .clicked()
                {
                    view.fit = !view.fit;
                }
            });
            if !compact {
                icons::group(ui, false, |ui| {
                    if icons::button(ui, Icon::Navigator, self.tree.open, true)
                        .on_hover_text(NAVIGATOR_HELP)
                        .clicked()
                    {
                        self.tree.open = !self.tree.open;
                        self.tree_toggled = true;
                    }
                    if icons::button(ui, Icon::Open, self.show_open, true)
                        .on_hover_text("Open a display file")
                        .clicked()
                    {
                        self.show_open = !self.show_open;
                    }
                });
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
                let menu = icons::group(ui, false, |ui| icons::button(ui, Icon::Menu, false, true))
                    .on_hover_text("More");
                egui::Popup::menu(&menu).show(|ui| {
                    if compact {
                        if ui
                            .add_enabled(!view.forward.is_empty(), egui::Button::new("Forward"))
                            .clicked()
                        {
                            view.go_forward();
                        }
                        if ui.button("Reload").clicked() {
                            view.reload();
                        }
                        if ui.button("Zoom in").clicked() {
                            view.zoom_by(1.25);
                        }
                        if ui.button("Zoom out").clicked() {
                            view.zoom_by(1.0 / 1.25);
                        }
                        ui.separator();
                        if ui.checkbox(&mut self.tree.open, "Navigator").changed() {
                            self.tree_toggled = true;
                        }
                        ui.checkbox(&mut self.show_open, "Open…");
                    }
                    let mut auto_size = self.chrome.auto_size;
                    if ui
                        .checkbox(&mut auto_size, "Auto-size window")
                        .on_hover_text("Resize the window to fit each display opened")
                        .changed()
                    {
                        toggle_auto_size(&mut self.chrome);
                    }
                    ui.separator();
                    all_windows = window_items(ui, others);
                    if windows {
                        ui.separator();
                        if compact {
                            ui.checkbox(&mut self.main_pinned, "Pinned")
                                .on_hover_text(PIN_HELP);
                            ui.menu_button("Load layout", |ui| {
                                action =
                                    layout_list(ui, self.layout_name.as_deref(), &mut self.layouts);
                            });
                        }
                        action = layout_menu(
                            ui,
                            self.layout_name.as_deref(),
                            &mut self.settings,
                            &mut self.layouts,
                        )
                        .or(action.take());
                    }
                });
                if windows && !compact {
                    icons::group(ui, false, |ui| {
                        egui::ComboBox::from_id_salt("layout")
                            .selected_text(
                                self.layout_name.as_deref().map_or("Layout", layout::label),
                            )
                            .show_ui(ui, |ui| {
                                action =
                                    layout_list(ui, self.layout_name.as_deref(), &mut self.layouts);
                            })
                            .response
                            .on_hover_text("Load a saved layout");
                    });
                    let pin = icons::group(ui, false, |ui| {
                        icons::button(ui, Icon::Pin, self.main_pinned, true)
                    });
                    if pin.on_hover_text(PIN_HELP).clicked() {
                        self.main_pinned = !self.main_pinned;
                    }
                }
                if let Some(s) = &view.screen {
                    // The rest of the row, the name centred in it.
                    let rest = Vec2::new(ui.available_width(), icons::group_height(ui));
                    let centred =
                        egui::Layout::centered_and_justified(egui::Direction::LeftToRight);
                    ui.allocate_ui_with_layout(rest, centred, |ui| {
                        ui.add(egui::Label::new(egui::RichText::new(&s.title).strong()).truncate())
                            .on_hover_text(&s.title);
                    });
                }
            });
        });
        if let Some(req) = all_windows {
            let origin = Origin {
                window: WindowKey::Main,
                ctrl: false,
                shift: false,
            };
            self.request(ui.ctx(), origin, req);
        }
        // Actual size: 100%, and the window (with the navigator) sized to it.
        if actual_size {
            self.main.fit = false;
            self.main.zoom = 1.0;
            self.chrome.fit_window();
        }
        if was_pinned && !self.main_pinned {
            self.main_used.touch(&mut self.clock);
        }
        if !was_pinned && self.main_pinned {
            self.clock += 1;
            self.main_pinned_at = self.clock;
        }
        if let Some(action) = action {
            self.layout_action(action);
            // A layout loads on the next frame.
            ui.ctx().request_repaint();
        }
    }

    /// Load, save or delete a layout, as the toolbar asked.
    fn layout_action(&mut self, action: LayoutAction) {
        let done = match action {
            LayoutAction::Load(name) => layout::load(&name).map(|l| {
                self.pending_layout = Some((l, Some(name)));
            }),
            LayoutAction::Save(name) => self.save_layout(&name),
            LayoutAction::SaveAs => {
                self.save_as = Some(SaveAs {
                    name: self.layout_name.clone().unwrap_or_default(),
                    confirm: false,
                });
                Ok(())
            }
            LayoutAction::Delete(name) => layout::delete(&name).map(|()| {
                self.layouts.refresh();
                log::info!("deleted layout {name}");
                if self.layout_name.as_deref() == Some(name.as_str()) {
                    self.layout_name = None;
                }
            }),
        };
        if let Err(e) = done {
            log::error!("{e}");
        }
    }

    /// The open windows as a layout.
    fn layout(&self) -> Layout {
        let mut windows = Vec::new();
        if let Some(loc) = self.main.saved_location() {
            let mut w = WindowLayout::new(loc, self.geometry);
            w.main = true;
            w.pinned = Some(self.main_pinned);
            w.tree = self.tree.open;
            w.zoom = Some(Zoom::new(self.main.fit, self.main.zoom));
            windows.push(w);
        }
        for dw in self.windows.iter().filter(|w| !w.close) {
            if let Some(loc) = dw.view.saved_location() {
                let mut w = WindowLayout::new(loc, dw.geometry);
                w.toolbar = dw.toolbar;
                w.pinned = Some(dw.pinned);
                windows.push(w);
            }
        }
        let trends: Vec<TrendLayout> = self
            .trends
            .iter()
            .map(|t| TrendLayout::new(t.view(), t.geometry))
            .collect();
        // On X11 a window not drawn yet has no position either.
        let unplaced = windows.iter().any(|w| w.position.is_none())
            || trends.iter().any(|t| t.position.is_none());
        if on_wayland() && unplaced {
            positions_unknown();
        }
        Layout::new(windows, trends)
    }

    fn save_layout(&mut self, name: &str) -> Result<(), String> {
        layout::save(name, &self.layout())?;
        self.layouts.refresh();
        self.layout_name = Some(name.trim().to_string());
        Ok(())
    }

    /// Once the main window is where a layout put it, ask again for the
    /// layout's size if it hasn't that: a window manager may have cut it to
    /// fit the monitor the window started on.
    fn finish_restoring(&mut self, ctx: &egui::Context) {
        let Some((want, since)) = self.restoring else {
            return;
        };
        // One that never gets there (kept on screen, fullscreen, tiled) is
        // given up, so a later move across that place doesn't resize it.
        // The wait begins on the first frame after the layout was applied,
        // not in it: that frame loads every display, which may take a while.
        let time = ctx.input(|i| i.time);
        let since = since.unwrap_or(time);
        self.restoring = Some((want, Some(since)));
        if time - since > RESTORE_WAIT {
            self.restoring = None;
            return;
        }
        let (Some(size), Some(now)) = (want.size, self.geometry.size) else {
            return;
        };
        let near = |a: Vec2, b: Vec2| (a - b).length() < 2.0;
        let there = match (want.position, self.geometry.position) {
            (Some(p), Some(q)) => near(p.to_vec2(), q.to_vec2()),
            // The window system doesn't say (Wayland): once it has moved.
            _ => true,
        };
        if !there {
            return;
        }
        self.restoring = None;
        if !near(size, now) {
            log::info!("the main window is {now:?}, not {size:?}: resizing it");
            ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size / ctx.zoom_factor()));
        }
    }

    /// Close the display windows and open those of `layout`; the main
    /// window moves, takes the layout's size and shows its display.
    fn apply_layout(&mut self, ctx: &egui::Context, layout: Layout, name: Option<String>) {
        // Positions are kept when on a monitor: those the window system
        // lists, else the main window's.
        let zoom = ctx.zoom_factor();
        let monitors = self.monitors(ctx);
        self.windows.clear();
        self.restoring = None;
        for w in &layout.windows {
            let geometry = w.geometry(&monitors);
            if w.position.is_some() && geometry.position.is_none() {
                log::info!("{}: its saved position is off screen", w.display);
            }
            let loc = w.location();
            if !w.main {
                self.open_window(ctx, loc, geometry, w.toolbar, layout.pinned(w));
                continue;
            }
            log::debug!(
                "restore the main window: size {:?}, position {:?}, navigator {}",
                geometry.size,
                geometry.position,
                if w.tree { "shown" } else { "hidden" }
            );
            // Moved before it is sized: a window manager keeps a window
            // within the monitor it is on, and a new window starts on the
            // first, which may be smaller than the one it is going to.
            if let Some(pos) = geometry.position {
                ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(
                    Pos2::ZERO + pos.to_vec2() / zoom,
                ));
            }
            if let Some(size) = geometry.size {
                ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size / zoom));
                self.chrome.hold_size();
            }
            self.restoring = geometry.size.map(|_| (geometry, None));
            if let Some(z) = &w.zoom {
                self.main.fit = z.factor().is_none();
                self.main.zoom = z.factor().unwrap_or(self.main.zoom);
            }
            if self.home.is_none() {
                self.home = Some(loc.clone());
            }
            self.show_open = false;
            self.main_pinned = layout.pinned(w);
            self.tree.open = w.tree;
            self.main.open(loc);
        }
        self.trends.clear();
        for t in &layout.trends {
            let mut trend = self.new_trend(ctx, &[]);
            trend.set_view(&t.view());
            trend.place = t.geometry(&monitors);
            self.trends.push(trend);
        }
        let placed = layout.windows.iter().any(|w| w.position.is_some())
            || layout.trends.iter().any(|t| t.position.is_some());
        if placed && on_wayland() {
            positions_unknown();
        }
        self.layout_name = name;
    }

    /// The Save as… dialog: a name, and a question before replacing a
    /// layout.
    fn save_as_window(&mut self, ui: &mut egui::Ui) {
        let Some(dialog) = self.save_as.as_mut() else {
            return;
        };
        let mut open = true;
        let mut save = None;
        egui::Window::new("Save layout as")
            .open(&mut open)
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, Vec2::ZERO)
            .show(ui.ctx(), |ui| {
                let name = dialog.name.trim().to_string();
                if dialog.confirm {
                    ui.label(format!("Replace the layout {name}?"));
                    ui.horizontal(|ui| {
                        if ui.button("Replace").clicked() {
                            save = Some(name);
                        }
                        if ui.button("Cancel").clicked() {
                            dialog.confirm = false;
                        }
                    });
                    return;
                }
                let edit = ui.text_edit_singleline(&mut dialog.name);
                let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
                let valid = layout::valid_name(&name);
                let clicked = ui.add_enabled(valid, egui::Button::new("Save")).clicked();
                if valid && (clicked || enter) {
                    if layout::exists(&name) {
                        dialog.confirm = true;
                    } else {
                        save = Some(name);
                    }
                }
            });
        if let Some(name) = save {
            if let Err(e) = self.save_layout(&name) {
                log::error!("{e}");
            }
            open = false;
        }
        if !open {
            self.save_as = None;
        }
    }

    fn open_panel(&mut self, ui: &mut egui::Ui) {
        let mut chosen = None;
        let path = &mut self.main.open_path;
        ui.horizontal(|ui| {
            ui.label("File or URL:");
            let edit = ui.add(egui::TextEdit::singleline(&mut *path).desired_width(f32::INFINITY));
            if edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
                chosen = Some(crate::fetch::user_named(path));
            }
        });
        // Nothing to list for a URL (an empty path lists nothing).
        let dir = match Source::parse(path) {
            Source::Url(_) => PathBuf::new(),
            Source::File(path) if bob::project::locate(&path).is_dir() => path,
            Source::File(path) => path
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from(".")),
        };
        egui::ScrollArea::vertical()
            // Leave most of a short (landscape phone) window to the display.
            .max_height(200f32.min(ui.ctx().content_rect().height() * 0.35))
            .show(ui, |ui| {
                if let Some(parent) = dir.parent()
                    && ui.button("📁 ..").clicked()
                {
                    *path = format!("{}/", parent.display());
                }
                for (entry, is_dir) in list_dir(&dir) {
                    let name = entry
                        .file_name()
                        .unwrap_or_default()
                        .to_string_lossy()
                        .to_string();
                    if is_dir {
                        if ui.button(format!("📁 {name}")).clicked() {
                            *path = format!("{}/", entry.display());
                        }
                    } else if ui.button(format!("🗋 {name}")).clicked() {
                        chosen = Some(Source::File(entry));
                    }
                }
            });
        if let Some(source) = chosen {
            self.show_open = false;
            if self.home.is_none() {
                self.home = Some(Location {
                    source: source.clone(),
                    macros: Macros::default(),
                });
            }
            self.main.open(Location {
                source,
                macros: Macros::default(),
            });
        }
    }
}

/// Turn Auto-size on or off; turning it on sizes the window to the
/// current display straight away.
fn toggle_auto_size(chrome: &mut Chrome) {
    chrome.auto_size = !chrome.auto_size;
    if chrome.auto_size {
        chrome.display_changed();
    }
}

/// The status line's height in a display window, in points, for sizing a
/// new one before it is drawn.
const CHILD_STATUS: f32 = 24.0;

/// Whether displays can have native windows of their own: not in a browser
/// or where there's only one native window, nor on a touch or small screen
/// (a phone).
fn can_multi_window(ctx: &egui::Context, touch: bool) -> bool {
    let zoom = ctx.zoom_factor();
    let small = ctx.input(|i| chrome::small_screen(i.viewport(), zoom));
    !cfg!(target_arch = "wasm32") && !ctx.embed_viewports() && !touch && !small
}

/// How long (seconds) the main window has to reach a layout's place before
/// `finish_restoring` gives up on it.
const RESTORE_WAIT: f64 = 2.0;

/// What the navigator shows.
const NAVIGATOR_HELP: &str = "Navigator: a tree of the displays the home display links to, \
     and those they link to. Click one to open it as a link would (shift and ctrl too).";

/// What a window's pin does.
const PIN_HELP: &str = "Pinned: links open their displays in the unpinned window used last, \
     or a new one (shift+click: a new window, ctrl+click: in place). \
     Unpinned: links open in place. \
     A display already open in another window is raised.";

/// What the main toolbar's layout controls ask for.
enum LayoutAction {
    Load(String),
    Save(String),
    SaveAs,
    Delete(String),
}

/// The saved layouts, to load one.
fn layout_list(
    ui: &mut egui::Ui,
    current: Option<&str>,
    layouts: &mut LayoutList,
) -> Option<LayoutAction> {
    let names = layouts.get(ui.ctx());
    if names.is_empty() {
        ui.weak("No saved layouts");
    }
    let mut action = None;
    for name in names {
        if ui
            .selectable_label(current == Some(name.as_str()), &name)
            .clicked()
        {
            action = Some(LayoutAction::Load(name));
        }
    }
    action
}

/// The menu's layout items: save, save as, delete, and saving the default
/// on exit.
fn layout_menu(
    ui: &mut egui::Ui,
    current: Option<&str>,
    settings: &mut layout::Settings,
    layouts: &mut LayoutList,
) -> Option<LayoutAction> {
    let mut action = None;
    let save = match current {
        Some(name) => format!("Save layout {}", layout::label(name)),
        None => "Save layout".to_string(),
    };
    if ui
        .add_enabled(current.is_some(), egui::Button::new(save))
        .clicked()
        && let Some(name) = current
    {
        action = Some(LayoutAction::Save(name.to_string()));
    }
    if ui.button("Save layout as…").clicked() {
        action = Some(LayoutAction::SaveAs);
    }
    if ui.button("Save as default").clicked() {
        action = Some(LayoutAction::Save(layout::DEFAULT.to_string()));
    }
    ui.menu_button("Delete layout", |ui| {
        let names = layouts.get(ui.ctx());
        if names.is_empty() {
            ui.weak("No saved layouts");
        }
        for name in names {
            if ui.button(&name).clicked() {
                action = Some(LayoutAction::Delete(name));
            }
        }
    });
    if ui
        .checkbox(&mut settings.save_default_on_exit, "Save default on exit")
        .changed()
    {
        settings.save();
    }
    action
}

/// Whether windows are on Wayland, which won't let a client place them.
fn on_wayland() -> bool {
    !cfg!(target_arch = "wasm32")
        && std::env::var_os("WAYLAND_DISPLAY").is_some_and(|d| !d.is_empty())
}

/// Say, once, that window positions are not known or can't be set.
fn positions_unknown() {
    static SAID: std::sync::Once = std::sync::Once::new();
    SAID.call_once(|| {
        log::info!(
            "window positions are left to the compositor on Wayland \
             (start bobview with WAYLAND_DISPLAY= to use XWayland, which keeps them)"
        );
    });
}

/// Display files (`.bob`, `.opi`) and subdirectories of `dir`, directories
/// first. The linked folders of an Eclipse project in `dir` are listed as
/// directories, and those are listed as if they were where they are linked.
fn list_dir(dir: &Path) -> Vec<(PathBuf, bool)> {
    let real = bob::project::locate(dir);
    let mut out: Vec<(PathBuf, bool)> = std::fs::read_dir(&real)
        .map(|rd| {
            rd.filter_map(Result::ok)
                .map(|e| (dir.join(e.file_name()), e.path().is_dir()))
                .filter(|(p, d)| {
                    let hidden = p
                        .file_name()
                        .is_some_and(|n| n.to_string_lossy().starts_with('.'));
                    let display = p.extension().is_some_and(|x| x == "bob" || x == "opi");
                    !hidden && (*d || display)
                })
                .collect()
        })
        .unwrap_or_default();
    for (name, _) in bob::project::links(&real).unwrap_or_default() {
        let link = dir.join(name);
        if !out.iter().any(|(p, _)| *p == link) {
            out.push((link, true));
        }
    }
    out.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    out
}

/// bobview as eframe runs it: the application behind one lock, so that each
/// display and trend window is drawn in a pass of its own (a deferred
/// viewport), redrawn only for its own input and its own PVs, not in the
/// main window's pass. eframe draws the windows one after another on one
/// thread, so their passes never wait for each other.
pub struct App(Arc<Mutex<BobApp>>);

/// A window the main window's pass keeps open, drawn in a pass of its own.
#[derive(Clone, Copy)]
enum Child {
    Display(egui::ViewportId),
    Trend(u64),
}

impl App {
    pub fn new(app: BobApp) -> Self {
        Self(Arc::new(Mutex::new(app)))
    }

    /// The main window's pass, which keeps the other windows open.
    pub fn draw(&self, ui: &mut egui::Ui) {
        let children = self.0.lock().draw_main(ui);
        // Not under the lock: where windows are embedded egui runs each
        // window's pass at once, inside this one, and that takes the lock.
        for (id, builder, child) in children {
            let app = self.0.clone();
            ui.ctx()
                .show_viewport_deferred(id, builder, move |ui, class| match child {
                    Child::Display(id) => app.lock().display_pass(ui, id, class),
                    Child::Trend(id) => app.lock().trend_pass(ui, id, class),
                });
        }
    }
}

impl eframe::App for App {
    /// Run at the start of every pass of the main window, including those
    /// eframe runs without `ui` while every window is hidden.
    fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.0.lock().begin_pass(egui::ViewportId::ROOT);
    }

    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
        #[cfg(not(target_arch = "wasm32"))]
        self.0.lock().find_monitors(ui, frame);
        #[cfg(target_arch = "wasm32")]
        let _ = frame;
        self.draw(ui);
    }

    fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
        self.0.lock().on_exit();
    }
}

/// What a window's pass can change that other windows draw: the windows
/// open and their titles (which the main window keeps), what each display
/// window shows (in the navigator, and the window itself when the change
/// came from another), and the window the PV details dialog is in.
#[derive(PartialEq)]
struct Shape {
    main: u64,
    /// Each display window: its id, `View::shown`, title and whether it
    /// is closing.
    windows: Vec<(egui::ViewportId, u64, String, bool)>,
    trends: Vec<(u64, String)>,
    details: Option<WindowKey>,
}

impl BobApp {
    /// A layout's positions are checked against the monitors as they are
    /// when it is loaded; new windows are placed within them, asked for
    /// every few seconds (a laptop is docked).
    #[cfg(not(target_arch = "wasm32"))]
    fn find_monitors(&mut self, ui: &egui::Ui, frame: &eframe::Frame) {
        let now = ui.input(|i| i.time);
        if (self.pending_layout.is_some() || self.monitors_at.is_none_or(|t| now - t > 3.0))
            && let Some(window) = frame.winit_window()
        {
            self.monitors_at = Some(now);
            // Desktop points, as egui's (times its zoom factor).
            let scale = window.scale_factor() as f32;
            self.monitors = window
                .available_monitors()
                .map(|m| {
                    let (pos, size) = (m.position(), m.size());
                    Rect::from_min_size(
                        Pos2::new(pos.x as f32, pos.y as f32) / scale,
                        Vec2::new(size.width as f32, size.height as f32) / scale,
                    )
                })
                .collect();
        }
    }

    fn on_exit(&mut self) {
        if !self.settings.save_default_on_exit {
            return;
        }
        let layout = self.layout();
        if let Some(main) = layout.windows.iter().find(|w| w.main) {
            log::debug!(
                "save the default layout: main window size {:?}, position {:?}, navigator {}",
                main.size,
                main.position,
                if main.tree { "shown" } else { "hidden" }
            );
        }
        if let Err(e) = layout::save(layout::DEFAULT, &layout) {
            log::error!("{e}");
        }
    }

    fn shape(&self) -> Shape {
        Shape {
            main: self.main.shown,
            windows: self
                .windows
                .iter()
                .map(|w| (w.id, w.view.shown, self.child_title(w), w.close))
                .collect(),
            trends: self.trend_titles(),
            details: self.details.as_ref().map(|(w, _)| *w),
        }
    }

    /// After a pass of the window `drawn`, repaint the other windows that
    /// draw what it changed (see `Shape`). Where windows are embedded the
    /// main window's pass draws them all.
    fn repaint_changed(&self, ctx: &egui::Context, before: &Shape, drawn: egui::ViewportId) {
        if ctx.embed_viewports() {
            return;
        }
        let after = self.shape();
        if after == *before {
            return;
        }
        let repaint = |id: egui::ViewportId| {
            if id != drawn {
                ctx.request_repaint_of(id);
            }
        };
        // It keeps the windows open, titles them and shows the navigator: a
        // window opened from another opens on its next pass.
        repaint(egui::ViewportId::ROOT);
        for (id, shown, ..) in &after.windows {
            if before
                .windows
                .iter()
                .any(|(b, s, ..)| b == id && s != shown)
            {
                repaint(*id);
            }
        }
        for (id, title) in &after.trends {
            if before.trends.iter().any(|(b, t)| b == id && t != title) {
                repaint(trend_viewport(*id));
            }
        }
        if after.details != before.details
            && let Some(window) = after.details
        {
            repaint(viewport(window));
        }
    }

    /// A display window's title: its display's, marked when pinned.
    fn child_title(&self, w: &DisplayWindow) -> String {
        w.view.screen.as_ref().map_or_else(
            || "bobview".to_string(),
            |s| window_title(&s.title, w.pinned && self.can_windows),
        )
    }

    /// The open trend windows, (id, title), for a PV's context menu.
    fn trend_titles(&self) -> Vec<(u64, String)> {
        self.trends.iter().map(|t| (t.id, t.title())).collect()
    }
}

impl BobApp {
    /// Draw everything in one pass, where windows are embedded (snapshots).
    #[cfg_attr(
        target_arch = "wasm32",
        expect(dead_code, reason = "a browser takes no snapshots")
    )]
    pub fn draw(&mut self, ui: &mut egui::Ui) {
        let children = self.draw_main(ui);
        debug_assert!(
            children.is_empty(),
            "windows to draw in passes of their own"
        );
    }

    /// The main window's pass, and where windows are embedded the others
    /// too; else the display and trend windows to keep open, each drawn in
    /// a pass of its own.
    fn draw_main(
        &mut self,
        ui: &mut egui::Ui,
    ) -> Vec<(egui::ViewportId, egui::ViewportBuilder, Child)> {
        let ctx = ui.ctx().clone();
        let embedded = ctx.embed_viewports();
        let before = self.shape();
        // Here as well as in `logic`, for snapshots and tests.
        self.begin_pass(egui::ViewportId::ROOT);
        self.main.poll_loading(&ctx);
        self.poll_launched(&ctx);
        if !self.touch && ui.input(|i| i.any_touches()) {
            self.touch = true;
        }
        widgets::touch_targets(ui.ctx(), self.touch);
        self.can_windows = can_multi_window(&ctx, self.touch);
        self.main_used
            .focus(ui.input(|i| i.focused), &mut self.clock);
        self.chrome.begin(ui.ctx());
        // Before a layout is applied, so the wait for one applied this
        // frame begins on the next, after this frame's loading.
        self.geometry = geometry(ui);
        self.finish_restoring(&ctx);
        // Once the controls' scale has settled, as positions and sizes
        // depend on it.
        if self.chrome.settled()
            && let Some((layout, name)) = self.pending_layout.take()
        {
            self.apply_layout(&ctx, layout, name);
        }
        if shortcuts(ui, &mut self.main).close {
            ctx.send_viewport_cmd(egui::ViewportCommand::Close);
        }
        self.main_frame = frame(ui);
        self.main
            .update_title(ui.ctx(), self.main_pinned && self.can_windows);
        let toolbar = egui::Panel::top("toolbar").show(ui, |ui| self.toolbar(ui));
        self.chrome.toolbar = toolbar.response.rect.height();
        let mut panels = self.chrome.toolbar;
        if self.show_open {
            panels += egui::Panel::top("open")
                .show(ui, |ui| self.open_panel(ui))
                .response
                .rect
                .height();
        }

        let (side, clicked) = self.navigator(ui);
        // Shown or hidden from the toolbar, the navigator widens or narrows
        // the window, so the display keeps its size and zoom.
        let grow = side - std::mem::replace(&mut self.tree_width, side);
        if std::mem::take(&mut self.tree_toggled) && grow != 0.0 {
            self.resize_main_by(&ctx, Vec2::new(grow, 0.0));
        }

        let trends = self.trend_titles();
        let vcx = ViewCx {
            window: WindowKey::Main,
            touch: self.touch,
            trends: &trends,
        };
        let drawn = self.main.draw(ui, &vcx);
        self.chrome.panels = panels + drawn.status;

        // A new display (not a reload, which keeps the size the user gave
        // the window) sizes the window to show it at 100% (or the fixed zoom).
        if std::mem::take(&mut self.main.new_display) {
            self.chrome.display_changed();
        }
        let display = self.main.natural_size(ui.ctx().zoom_factor());
        self.chrome
            .end(ui.ctx(), display.map(|d| d + Vec2::new(side, 0.0)));
        if let Some(clicked) = clicked {
            self.open_from_tree(&ctx, clicked);
        }

        let mut requests = drawn.requests;
        if embedded {
            requests.extend(self.embedded_windows(&ctx, &trends));
        }
        for (origin, req) in requests {
            self.request(ui.ctx(), origin, req);
        }
        // A dialog goes with its window.
        let closed = |w: WindowKey| match w {
            WindowKey::Main => false,
            WindowKey::Child(id) => !self.windows.iter().any(|dw| dw.id == id && !dw.close),
        };
        if self.details.as_ref().is_some_and(|(w, _)| closed(*w)) {
            self.details = None;
        }
        details_dialog(ui.ctx(), WindowKey::Main, &mut self.details);
        self.save_as_window(ui);
        let mut children = Vec::new();
        if embedded {
            self.embedded_trends(&ctx);
        }
        self.trend_selections(&ctx);
        if !embedded {
            // After this pass's requests, which may open or close some.
            children = self.display_viewports();
            children.extend(self.trend_viewports(&ctx));
        }
        // The windows still open keep what repaints them.
        let (windows, trends) = (&self.windows, &self.trends);
        let open = |id: &egui::ViewportId| {
            *id == egui::ViewportId::ROOT
                || windows.iter().any(|w| w.id == *id)
                || trends.iter().any(|t| trend_viewport(t.id) == *id)
        };
        self.repaints.retain(|id, _| open(id));
        self.repaint_changed(&ctx, &before, egui::ViewportId::ROOT);
        children
    }

    /// Make the main window `by` points bigger (or smaller), within its
    /// monitor, unless it is maximized or full screen.
    fn resize_main_by(&self, ctx: &egui::Context, by: Vec2) {
        let info = ctx.input(|i| i.viewport().clone());
        if !chrome::can_resize(&info, ctx.zoom_factor()) {
            return;
        }
        let Some(inner) = info.inner_rect else {
            return;
        };
        let mut size = inner.size() + by;
        if let Some(monitor) = info.monitor_size {
            size = size.min(monitor);
        }
        log::debug!(
            "resize the window from {:?} to {size:?} for the navigator",
            inner.size()
        );
        ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size));
    }

    /// The navigator beside the main window's display, when shown: its
    /// width, and the node clicked. Its root is the home display.
    fn navigator(&mut self, ui: &mut egui::Ui) -> (f32, Option<tree::Clicked>) {
        let root = self.home.clone().or_else(|| self.main.current.clone());
        let Some(root) = root.filter(|_| self.tree.open) else {
            return (0.0, None);
        };
        // Shown in bold by the same test a click makes (see `View::shows`).
        let (main, windows) = (&self.main, &self.windows);
        let here = |loc: &Location| {
            std::iter::once(main)
                .chain(windows.iter().filter(|w| !w.close).map(|w| &w.view))
                .any(|v| v.shows(loc))
        };
        let panel = egui::Panel::left("navigator")
            .resizable(true)
            .default_size(220.0)
            .show(ui, |ui| self.tree.ui(ui, &root, &here));
        (panel.response.rect.width(), panel.inner)
    }

    /// Open what a navigator node names, as a link in the main window would;
    /// the display the main window shows is not opened again.
    fn open_from_tree(&mut self, ctx: &egui::Context, clicked: tree::Clicked) {
        let origin = Origin {
            window: WindowKey::Main,
            ctrl: clicked.ctrl,
            shift: clicked.shift,
        };
        match clicked.target {
            // The main window's own display (shown bold) is left as it is,
            // its PVs connected, whatever the modifiers.
            tree::Target::Display(loc) if self.main.shows(&loc) => {}
            tree::Target::Display(loc) => self.follow(ctx, origin, loc, "navigator"),
            tree::Target::Command {
                base,
                directory,
                command,
            } => self.launch(ctx, origin, base, directory, command),
        }
    }

    /// Act on a request from a widget in `origin`'s window.
    fn request(&mut self, ctx: &egui::Context, origin: Origin, req: Request) {
        let window = origin.window;
        match req {
            Request::Open {
                source,
                macros,
                target,
            } => self.follow(ctx, origin, Location { source, macros }, &target),
            Request::Copy(text) => {
                log::debug!("copy {text}");
                ctx.copy_text(text.clone());
                if let Err(e) = self.primary.set(&text) {
                    log::debug!("no primary selection: {e}");
                }
                let now = ctx.input(|i| i.time);
                if let Some(view) = self.view_mut(window) {
                    view.copied(text, now);
                }
                ctx.request_repaint();
            }
            Request::Details(details) => {
                self.details = Some((window, details));
                ctx.request_repaint();
            }
            Request::Trend(names) => {
                log::info!("trend {}", names.join(", "));
                let trend = self.new_trend(ctx, &names);
                self.trends.push(trend);
            }
            Request::TrendAdd(id, names) => {
                if let Some(trend) = self.trends.iter_mut().find(|t| t.id == id) {
                    log::info!("add {} to trend {id}", names.join(", "));
                    trend.extend(&names);
                    raise_trend(ctx, id);
                }
            }
            Request::Command {
                base,
                directory,
                command,
            } => self.launch(ctx, origin, base, directory, command),
            // Exit in a display window closes it; the main window goes back
            // first, as one window used to.
            Request::Close => match window {
                WindowKey::Main if !self.main.back.is_empty() => self.main.go_back(),
                WindowKey::Main => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
                WindowKey::Child(id) => {
                    if let Some(w) = self.windows.iter_mut().find(|w| w.id == id) {
                        w.close = true;
                    }
                }
            },
            Request::RaiseAll => {
                for w in &self.windows {
                    raise(ctx, WindowKey::Child(w.id));
                }
                for t in &self.trends {
                    raise_trend(ctx, t.id);
                }
                raise(ctx, WindowKey::Main);
                // The window asking stays on top.
                if window != WindowKey::Main {
                    raise(ctx, window);
                }
            }
            Request::CloseOthers => {
                log::info!("close all other windows");
                for w in &mut self.windows {
                    w.close |= WindowKey::Child(w.id) != window;
                }
                self.trends.clear();
            }
            Request::Webpage(url) => open_webpage(&url),
        }
    }

    /// Each display window in a window inside this one, where there's only
    /// one native window. Returns the requests their widgets made.
    fn embedded_windows(
        &mut self,
        ctx: &egui::Context,
        trends: &[(u64, String)],
    ) -> Vec<(Origin, Request)> {
        let mut requests = Vec::new();
        // Closed by Exit since they were last drawn.
        self.windows.retain(|w| !w.close);
        let titles: Vec<String> = self.windows.iter().map(|w| self.child_title(w)).collect();
        let desk = Desk {
            monitors: self.monitors(ctx),
            pinned: self.pinned_frames(),
        };
        for (w, title) in self.windows.iter_mut().zip(titles) {
            if let Some(r) = self.repaints.get(&w.id) {
                r.begin();
            }
            w.view.poll_loading(ctx);
            let key = WindowKey::Child(w.id);
            let vcx = ViewCx {
                window: key,
                touch: self.touch,
                trends,
            };
            let mut open = true;
            egui::Window::new(&title)
                .id(display_window_id(w.id))
                .open(&mut open)
                .collapsible(false)
                .default_size(Vec2::new(640.0, 420.0))
                .show(ctx, |ui| {
                    requests.extend(child_ui(
                        ui,
                        w,
                        &self.home,
                        &vcx,
                        None,
                        &mut self.clock,
                        &desk,
                    ));
                });
            details_dialog(ctx, key, &mut self.details);
            w.close |= !open;
        }
        self.windows.retain(|w| !w.close);
        requests
    }

    /// Each trend in a window inside this one, where there's only one
    /// native window (the browser, snapshots).
    fn embedded_trends(&mut self, ctx: &egui::Context) {
        let screen = ctx.content_rect();
        let repaints = &self.repaints;
        let mut switched = None;
        self.trends.retain_mut(|trend| {
            if let Some(r) = repaints.get(&trend_viewport(trend.id)) {
                r.begin();
            }
            let mut open = true;
            // Each new window a little below and right of the one before.
            let step = (trend.id % 8) as f32 * 24.0;
            let size = TREND_SIZE.min(screen.size() * 0.9);
            egui::Window::new(trend.title())
                .id(trend_window_id(trend.id))
                .open(&mut open)
                .collapsible(false)
                .default_pos(screen.left_top() + Vec2::new(40.0, 60.0) + Vec2::splat(step))
                .default_size(size)
                .show(ctx, |ui| trend.ui(ui));
            if trend.take_archiver_change() {
                switched = Some(trend.archiver().cloned());
            }
            open
        });
        if let Some(archiver) = switched {
            self.switch_archiver(ctx, archiver);
        }
    }

    /// The display windows to keep open, each in its own native window
    /// until it is closed.
    fn display_viewports(&mut self) -> Vec<(egui::ViewportId, egui::ViewportBuilder, Child)> {
        // Closed by Exit or Ctrl+W since they were last drawn.
        self.windows.retain(|w| !w.close);
        self.windows
            .iter()
            .map(|w| {
                let builder = w.builder.clone().with_title(self.child_title(w));
                (w.id, builder, Child::Display(w.id))
            })
            .collect()
    }

    /// The trend windows to keep open, each in its own native window until
    /// it is closed.
    fn trend_viewports(
        &self,
        ctx: &egui::Context,
    ) -> Vec<(egui::ViewportId, egui::ViewportBuilder, Child)> {
        // In desktop points: egui's are scaled by its zoom factor.
        let zoom = ctx.zoom_factor();
        self.trends
            .iter()
            .map(|trend| {
                // The window manager places it, unless a layout says where;
                // Wayland won't let us.
                let size = trend.place.size.map_or(TREND_SIZE, |s| s / zoom);
                let mut builder = egui::ViewportBuilder::default()
                    .with_title(trend.title())
                    .with_app_id("bobview")
                    .with_inner_size(size)
                    .with_min_inner_size([400.0, 280.0]);
                if let Some(pos) = trend.place.position {
                    builder = builder.with_position(Pos2::ZERO + pos.to_vec2() / zoom);
                }
                (trend_viewport(trend.id), builder, Child::Trend(trend.id))
            })
            .collect()
    }

    /// The display window `id`'s own pass: it polls its display, and acts
    /// on its widgets' requests at once.
    fn display_pass(
        &mut self,
        ui: &mut egui::Ui,
        id: egui::ViewportId,
        class: egui::ViewportClass,
    ) {
        let ctx = ui.ctx().clone();
        let before = self.shape();
        // Closed since the main window's last pass, which lets it go.
        let Some(i) = self.windows.iter().position(|w| w.id == id && !w.close) else {
            return;
        };
        self.begin_pass(id);
        let trends = self.trend_titles();
        let desk = Desk {
            monitors: self.monitors(&ctx),
            pinned: self.pinned_frames(),
        };
        let key = WindowKey::Child(id);
        let vcx = ViewCx {
            window: key,
            touch: self.touch,
            trends: &trends,
        };
        // No native windows after all: a window in the main one.
        let native =
            (class != egui::ViewportClass::EmbeddedWindow).then_some(self.chrome.auto_size);
        let w = &mut self.windows[i];
        w.view.poll_loading(&ctx);
        let requests = child_ui(ui, w, &self.home, &vcx, native, &mut self.clock, &desk);
        details_dialog(&ctx, key, &mut self.details);
        // Closing the window drops its view, and its PVs with it.
        if ui.input(|i| i.viewport().close_requested()) {
            w.close = true;
        }
        for (origin, req) in requests {
            self.request(&ctx, origin, req);
        }
        self.repaint_changed(&ctx, &before, id);
    }

    /// The trend `id`'s window's own pass.
    fn trend_pass(&mut self, ui: &mut egui::Ui, id: u64, class: egui::ViewportClass) {
        let ctx = ui.ctx().clone();
        let before = self.shape();
        let Some(i) = self.trends.iter().position(|t| t.id == id) else {
            return;
        };
        self.begin_pass(trend_viewport(id));
        let trend = &mut self.trends[i];
        if class == egui::ViewportClass::EmbeddedWindow {
            // No native windows after all: a window in the main one, which
            // can't be closed.
            trend.ui(ui);
        } else {
            trend.geometry = geometry(ui);
            egui::CentralPanel::default().show(ui, |ui| trend.ui(ui));
            // Closing the window drops the trend, and its PVs with it.
            if ui.input(|i| i.viewport().close_requested()) {
                self.trends.remove(i);
            }
        }
        self.trend_selections(&ctx);
        if let Some(trend) = self.trends.get_mut(i).filter(|t| t.id == id)
            && trend.take_archiver_change()
        {
            let archiver = trend.archiver().cloned();
            self.switch_archiver(&ctx, archiver);
        }
        self.repaint_changed(&ctx, &before, trend_viewport(id));
    }
}

/// The PV details dialog, when asked for in `window`: drawn in that window.
fn details_dialog(
    ctx: &egui::Context,
    window: WindowKey,
    details: &mut Option<(WindowKey, pvmenu::Details)>,
) {
    if details.as_ref().is_some_and(|(w, _)| *w == window) {
        details_window(ctx, details);
    }
}

fn details_window(ctx: &egui::Context, details: &mut Option<(WindowKey, pvmenu::Details)>) {
    let mut open = details.is_some();
    if let Some((_, d)) = details.as_ref() {
        egui::Window::new("PV details")
            .open(&mut open)
            .collapsible(false)
            .anchor(egui::Align2::CENTER_CENTER, Vec2::ZERO)
            .show(ctx, |ui| pvmenu::details_ui(ui, d));
    }
    if !open {
        *details = None;
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn open_webpage(url: &str) {
    if let Err(e) = std::process::Command::new("xdg-open").arg(url).spawn() {
        log::warn!("cannot open {url}: {e}");
    }
}

#[cfg(target_arch = "wasm32")]
fn open_webpage(url: &str) {
    if let Some(w) = web_sys::window()
        && w.open_with_url_and_target(url, "_blank").is_err()
    {
        log::warn!("cannot open {url}");
    }
}

/// The native window that `window` is.
fn viewport(window: WindowKey) -> egui::ViewportId {
    match window {
        WindowKey::Main => egui::ViewportId::ROOT,
        WindowKey::Child(id) => id,
    }
}

/// The display window `id` inside the main one, where windows are embedded.
fn display_window_id(id: egui::ViewportId) -> Id {
    Id::new(("display window", id))
}

/// The menu items acting on all of bobview's windows, enabled when there
/// are `others` than the main one; the request of the one clicked.
fn window_items(ui: &mut egui::Ui, others: bool) -> Option<Request> {
    let raise = ui
        .add_enabled(others, egui::Button::new("Bring all windows to front"))
        .clicked();
    let close = ui
        .add_enabled(others, egui::Button::new("Close all other windows"))
        .on_hover_text("Close every display and trend window but the main one and this one")
        .clicked();
    if raise {
        Some(Request::RaiseAll)
    } else if close {
        Some(Request::CloseOthers)
    } else {
        None
    }
}

/// Bring `window` to the front, as a link to its display is followed.
fn raise(ctx: &egui::Context, window: WindowKey) {
    match window {
        WindowKey::Child(id) if ctx.embed_viewports() => ctx.move_to_top(egui::LayerId::new(
            egui::Order::Middle,
            display_window_id(id),
        )),
        _ => ctx.send_viewport_cmd_to(viewport(window), egui::ViewportCommand::Focus),
    }
}

/// Where the window being drawn is, in desktop points (egui's times its
/// zoom factor); None where the window system doesn't say.
fn geometry(ui: &egui::Ui) -> Geometry {
    let zoom = ui.ctx().zoom_factor();
    ui.input(|i| {
        let info = i.viewport();
        Geometry {
            position: info.outer_rect.map(|r| Pos2::ZERO + r.min.to_vec2() * zoom),
            size: info.inner_rect.map(|r| r.size() * zoom),
        }
    })
}

/// Where the window being drawn is on the desktop (see `Frame`); None where
/// the window system doesn't say.
fn frame(ui: &egui::Ui) -> Option<Frame> {
    let zoom = ui.ctx().zoom_factor();
    ui.input(|i| {
        let info = i.viewport();
        let (outer, inner) = (info.outer_rect?, info.inner_rect?);
        Some(Frame {
            outer: Rect::from_min_size(
                Pos2::ZERO + outer.min.to_vec2() * zoom,
                outer.size() * zoom,
            ),
            border: (outer.size() - inner.size()) * zoom,
        })
    })
}

/// What the keyboard shortcuts ask of the window beyond its view.
#[derive(Default)]
struct Shortcuts {
    close: bool,
    toolbar: bool,
}

/// The shortcuts every window has: Ctrl+R reloads, Alt+Left and Alt+Right go
/// back and forward, Ctrl+W closes the window and Ctrl+T shows or hides a
/// display window's toolbar.
fn shortcuts(ui: &egui::Ui, view: &mut View) -> Shortcuts {
    use egui::{Key, Modifiers};
    // Not while typing in the window (focus is as the last frame left it):
    // there Ctrl+W deletes a word and Alt+arrows move by word.
    if ui.ctx().text_edit_focused() {
        return Shortcuts::default();
    }
    ui.input_mut(|i| {
        if i.consume_key(Modifiers::COMMAND, Key::R) {
            view.reload();
        }
        if i.consume_key(Modifiers::ALT, Key::ArrowLeft) {
            view.go_back();
        }
        if i.consume_key(Modifiers::ALT, Key::ArrowRight) {
            view.go_forward();
        }
        Shortcuts {
            close: i.consume_key(Modifiers::COMMAND, Key::W),
            toolbar: i.consume_key(Modifiers::COMMAND, Key::T),
        }
    })
}

/// A display window's contents: its toolbar when shown, the display, the
/// chevron that shows or hides the toolbar and the context menu on the
/// display's background. `native` is Some(auto-size) in a native window,
/// which is sized to each new display (only the first unless auto-size).
fn child_ui(
    ui: &mut egui::Ui,
    w: &mut DisplayWindow,
    home: &Option<Location>,
    vcx: &ViewCx,
    native: Option<bool>,
    clock: &mut u64,
    desk: &Desk,
) -> Vec<(Origin, Request)> {
    if native.is_some() {
        w.used.focus(ui.input(|i| i.focused), clock);
        let keys = shortcuts(ui, &mut w.view);
        w.close |= keys.close;
        w.toolbar ^= keys.toolbar;
    }
    let mut panels = 0.0;
    if w.toolbar {
        panels += egui::Panel::top(Id::new(("toolbar", w.id)))
            .show(ui, |ui| display_toolbar(ui, &mut w.view, home))
            .response
            .rect
            .height();
    }
    let mut drawn = w.view.draw(ui, vcx);
    panels += drawn.status;
    if let Some(background) = &drawn.background {
        background.context_menu(|ui| {
            let label = if w.toolbar {
                "Hide toolbar"
            } else {
                "Show toolbar"
            };
            if ui.button(label).clicked() {
                w.toolbar = !w.toolbar;
            }
            if ui.button("Close").clicked() {
                w.close = true;
            }
            ui.separator();
            if let Some(req) = window_items(ui, true) {
                let origin = Origin {
                    window: WindowKey::Child(w.id),
                    ctrl: false,
                    shift: false,
                };
                drawn.requests.push((origin, req));
            }
        });
    }
    let Some(auto_size) = native else {
        w.view.new_display = false;
        return drawn.requests;
    };
    corner(ui, w, clock);
    w.geometry = geometry(ui);
    w.frame = frame(ui);
    // Sized to a new display at 100%, within the monitor, once the window
    // knows its monitor; then the display fits the window as it is resized.
    let info = ui.input(|i| i.viewport().clone());
    if w.view.new_display && info.monitor_size.is_some() {
        w.view.new_display = false;
        let zoom = ui.ctx().zoom_factor();
        let display = w.view.natural_size(zoom);
        // One that failed to load leaves a window not yet sized to be
        // sized to the next.
        let fit = w.fit_next;
        w.fit_next = auto_size || fit && display.is_none();
        // Taken with the display it was for, sized or not (the window may
        // be maximized, or the display failed), so it can't move the window
        // later.
        let origin = w.beside.take();
        if fit
            && chrome::can_resize(&info, zoom)
            && let Some(display) = display
        {
            let size = chrome::window_size(display, panels, info.monitor_size);
            let inner = ui.input(|i| i.content_rect().size());
            if (size - inner).length() >= 1.0 {
                ui.ctx()
                    .send_viewport_cmd(egui::ViewportCommand::InnerSize(size));
            }
            // Beside the window it was opened from, at its new size.
            if let Some(origin) = origin
                && let Some(pos) = beside(origin, &desk.clear_of(w.id), size * zoom, &desk.monitors)
            {
                ui.ctx()
                    .send_viewport_cmd(egui::ViewportCommand::OuterPosition(
                        Pos2::ZERO + pos.to_vec2() / zoom,
                    ));
            }
        }
    }
    drawn.requests
}

/// Small buttons in the top-right corner while the pointer is over the
/// window, drawn over the display so they take no room: Back (while the
/// toolbar is hidden), the pin, and a chevron that shows or hides the
/// toolbar.
fn corner(ui: &egui::Ui, w: &mut DisplayWindow, clock: &mut u64) {
    if !ui.input(|i| i.pointer.has_pointer()) {
        return;
    }
    egui::Area::new(Id::new(("chevron", w.id)))
        .order(egui::Order::Foreground)
        .anchor(egui::Align2::RIGHT_TOP, Vec2::new(-4.0, 4.0))
        .show(ui.ctx(), |ui| {
            ui.spacing_mut().item_spacing.x = 3.0;
            ui.horizontal(|ui| {
                if !w.toolbar {
                    let enabled = !w.view.back.is_empty();
                    let resp = corner_button(ui, false, enabled);
                    corner_glyph(ui, &resp, Icon::Back);
                    if resp.on_hover_text("Back (Alt+←)").clicked() {
                        w.view.go_back();
                    }
                }
                let resp = corner_button(ui, w.pinned, true);
                corner_glyph(ui, &resp, Icon::Pin);
                if resp.on_hover_text(PIN_HELP).clicked() {
                    w.pinned = !w.pinned;
                    // Unpinned, it is the viewer; pinned, new windows go
                    // beside it.
                    if w.pinned {
                        *clock += 1;
                        w.pinned_at = *clock;
                    } else {
                        w.used.touch(clock);
                    }
                }
                let resp = corner_button(ui, false, true);
                let visuals = ui.style().interact(&resp);
                // ⌄ to show the toolbar, ⌃ to hide it (drawn: the fonts have no ⌄).
                let c = resp.rect.center();
                let (dx, dy) = (5.0, if w.toolbar { -2.5 } else { 2.5 });
                ui.painter().line(
                    vec![
                        c + Vec2::new(-dx, -dy),
                        c + Vec2::new(0.0, dy),
                        c + Vec2::new(dx, -dy),
                    ],
                    visuals.fg_stroke,
                );
                let tip = if w.toolbar {
                    "Hide the toolbar (Ctrl+T)"
                } else {
                    "Show the toolbar (Ctrl+T)"
                };
                if resp.on_hover_text(tip).clicked() {
                    w.toolbar = !w.toolbar;
                }
            });
        });
}

/// One of the `corner` buttons, its background drawn: highlighted when
/// `selected`, inert unless `enabled`.
fn corner_button(ui: &mut egui::Ui, selected: bool, enabled: bool) -> egui::Response {
    let sense = if enabled {
        egui::Sense::click()
    } else {
        egui::Sense::hover()
    };
    let (rect, resp) = ui.allocate_exact_size(Vec2::new(22.0, 16.0), sense);
    let fill = if selected {
        ui.visuals().selection.bg_fill
    } else {
        ui.style().interact(&resp).weak_bg_fill
    };
    ui.painter().rect_filled(rect, 3.0, fill);
    resp
}

/// A `corner` button's icon, faded when the button is disabled.
fn corner_glyph(ui: &egui::Ui, resp: &egui::Response, icon: Icon) {
    let color = if resp.sense.senses_click() {
        ui.style().interact(resp).fg_stroke.color
    } else {
        ui.visuals().weak_text_color()
    };
    icon.paint(ui.painter(), resp.rect, 12.0, color);
}

/// A display window's toolbar: navigation, reload and zoom. The window and
/// layout controls stay on the main window.
fn display_toolbar(ui: &mut egui::Ui, view: &mut View, home: &Option<Location>) {
    ui.horizontal(|ui| {
        if ui
            .add_enabled(!view.back.is_empty(), egui::Button::new("◀"))
            .on_hover_text("Back")
            .clicked()
        {
            view.go_back();
        }
        if ui
            .add_enabled(!view.forward.is_empty(), egui::Button::new("▶"))
            .on_hover_text("Forward")
            .clicked()
        {
            view.go_forward();
        }
        if ui.button("⟳").on_hover_text("Reload").clicked() {
            view.reload();
        }
        ui.separator();
        if ui.button("−").clicked() {
            view.zoom_by(1.0 / 1.25);
        }
        if ui.selectable_label(view.fit, "Fit").clicked() {
            view.fit = !view.fit;
        }
        if ui.button("+").clicked() {
            view.zoom_by(1.25);
        }
        ui.label(format!("{:.0}%", view.zoom * 100.0));
        ui.separator();
        if ui
            .add_enabled(home.is_some(), egui::Button::new("⌂"))
            .on_hover_text("Home")
            .clicked()
            && let Some(home) = home.clone()
        {
            view.open(home);
        }
    });
}

/// A new trend window's size, in points.
const TREND_SIZE: Vec2 = Vec2::new(760.0, 480.0);

/// The native window of the trend `id`.
fn trend_viewport(id: u64) -> egui::ViewportId {
    egui::ViewportId::from_hash_of(("trend", id))
}

/// The trend `id`'s window inside the main one, where windows are embedded.
fn trend_window_id(id: u64) -> Id {
    Id::new(("trend", id))
}

/// Bring the trend `id`'s window to the front, as a PV is added to it.
fn raise_trend(ctx: &egui::Context, id: u64) {
    if ctx.embed_viewports() {
        ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, trend_window_id(id)));
    } else {
        ctx.send_viewport_cmd_to(trend_viewport(id), egui::ViewportCommand::Focus);
    }
}

/// A PV's name as a user would type it: no `ca://` prefix, and no type or
/// initial value for a local PV (`loc://x`, not `loc://x<VDouble>(1.5)`).
pub(crate) fn plain_name(name: &pv::PvName) -> String {
    match name.scheme {
        pv::Scheme::Ca => name.base().to_string(),
        pv::Scheme::Formula | pv::Scheme::Unsupported => name.to_string(),
        _ => {
            let full = name.to_string();
            let prefix = &full[..full.len() - name.pv.len()];
            format!("{prefix}{}", name.base())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::plain_name;
    use pv::PvName;

    #[test]
    fn lists_displays_and_project_links() {
        let tmp = std::env::temp_dir().join(format!("bobview-list-{}", std::process::id()));
        let (real, proj) = (tmp.join("real"), tmp.join("proj"));
        std::fs::create_dir_all(real.join("sub")).unwrap();
        std::fs::create_dir_all(&proj).unwrap();
        for f in ["a.opi", "b.bob", "c.txt"] {
            std::fs::write(real.join(f), "").unwrap();
        }
        std::fs::write(
            proj.join(".project"),
            format!(
                "<projectDescription><linkedResources><link><name>m</name><location>{}</location></link></linkedResources></projectDescription>",
                real.display()
            ),
        )
        .unwrap();
        // Compared as paths, which take `/` as a separator on Windows too.
        let names = |dir: &std::path::Path| -> Vec<(std::path::PathBuf, bool)> {
            super::list_dir(dir)
                .into_iter()
                .map(|(p, d)| (p.strip_prefix(&tmp).unwrap().to_path_buf(), d))
                .collect()
        };
        assert_eq!(names(&proj), [("proj/m".into(), true)]);
        assert_eq!(
            names(&proj.join("m")),
            [
                ("proj/m/sub".into(), true),
                ("proj/m/a.opi".into(), false),
                ("proj/m/b.bob".into(), false)
            ]
        );
        std::fs::remove_dir_all(&tmp).unwrap();
    }

    #[test]
    fn launches_once_and_drops_stale_results() {
        use super::{BobApp, Launched, Location, Origin, WindowKey};
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), crate::chrome::UiScale::Auto);
        // A double click runs the command once, and counts as loading.
        let main = Origin {
            window: WindowKey::Main,
            ..Origin::default()
        };
        app.launch(&ctx, main, None, None, "no-such-launcher".into());
        app.launch(&ctx, main, None, None, "no-such-launcher".into());
        assert_eq!(app.main.launching.len(), 1);
        // The main view's own loading: app.is_loading() also counts tab
        // builds of other tests running at the same time.
        assert!(app.main.is_loading());
        while app.main.is_loading() {
            std::thread::sleep(std::time::Duration::from_millis(5));
            app.poll_launched(&ctx);
        }
        // A result from before the display changed is dropped.
        let loc = Location {
            source: bob::Source::File("/no/such.bob".into()),
            macros: Default::default(),
        };
        let key = (None, None, "x".to_string());
        app.main.launching.push(key.clone());
        let stale = app.main.shown;
        app.main.shown += 1;
        app.launched
            .0
            .send(Launched {
                key,
                origin: main,
                shown: stale,
                target: Some(loc.clone()),
            })
            .unwrap();
        app.poll_launched(&ctx);
        assert!(app.main.current.is_none() && !app.main.is_loading());
        // In the pinned main window a ctrl+clicked command opens in place,
        // as a ctrl+clicked link does.
        app.launched
            .0
            .send(Launched {
                key: (None, None, "y".to_string()),
                origin: Origin { ctrl: true, ..main },
                shown: app.main.shown,
                target: Some(loc.clone()),
            })
            .unwrap();
        app.poll_launched(&ctx);
        assert!(app.windows.is_empty());
        assert_eq!(app.main.current, Some(loc));
    }

    #[test]
    fn links_route_by_pin_modifier_and_open_windows() {
        use super::{Origin, Route, WindowKey, route};
        let child = WindowKey::Child(eframe::egui::ViewportId::from_hash_of("x"));
        let viewer = WindowKey::Child(eframe::egui::ViewportId::from_hash_of("v"));
        let plain = Origin::default();
        let ctrl = Origin {
            ctrl: true,
            ..plain
        };
        let shift = Origin {
            shift: true,
            ..plain
        };
        // No windows of their own: always in place, whatever is open.
        assert_eq!(route(false, plain, true, None, None), Route::InPlace);
        assert_eq!(route(false, shift, true, Some(child), None), Route::InPlace);
        // From a pinned window: the viewer, else a new window.
        assert_eq!(
            route(true, plain, true, None, Some(viewer)),
            Route::Viewer(viewer)
        );
        assert_eq!(route(true, plain, true, None, None), Route::NewWindow);
        // From an unpinned window: in place.
        assert_eq!(
            route(true, plain, false, None, Some(viewer)),
            Route::InPlace
        );
        // Shift+click: a new window, whatever the pin.
        assert_eq!(
            route(true, shift, false, None, Some(viewer)),
            Route::NewWindow
        );
        assert_eq!(
            route(true, shift, true, None, Some(viewer)),
            Route::NewWindow
        );
        // A display already open is raised, with or without shift.
        for (origin, pinned) in [(plain, true), (plain, false), (shift, true)] {
            assert_eq!(
                route(true, origin, pinned, Some(child), Some(viewer)),
                Route::Raise(child)
            );
        }
        let from_child = Origin {
            window: child,
            ..plain
        };
        assert_eq!(
            route(true, from_child, true, Some(WindowKey::Main), None),
            Route::Raise(WindowKey::Main)
        );
        // A link to the display its own window shows: shown again in place,
        // as a Refresh button wants.
        for (origin, pinned) in [(plain, true), (plain, false), (shift, true)] {
            assert_eq!(
                route(true, origin, pinned, Some(WindowKey::Main), Some(viewer)),
                Route::InPlace
            );
        }
        assert_eq!(
            route(true, from_child, true, Some(child), None),
            Route::InPlace
        );
        // Ctrl+click navigates in place, even to a display already open.
        assert_eq!(
            route(true, ctrl, true, Some(child), Some(viewer)),
            Route::InPlace
        );
    }

    #[test]
    fn new_windows_open_beside_their_origin_then_below() {
        use super::{Frame, beside};
        use eframe::egui::{Pos2, Rect, Vec2};
        let beside_alone = |o, size, monitors: &[Rect]| beside(o, &[], size, monitors);
        let left = Rect::from_min_size(Pos2::ZERO, Vec2::new(1920.0, 1080.0));
        let right = Rect::from_min_size(Pos2::new(1920.0, 0.0), Vec2::new(1920.0, 1080.0));
        let at = |x: f32, y: f32, w: f32| Frame {
            outer: Rect::from_min_size(Pos2::new(x, y), Vec2::new(w, 600.0)),
            border: Vec2::new(0.0, 30.0),
        };
        let size = Vec2::new(800.0, 500.0);
        // To the right, top edges level.
        assert_eq!(
            beside_alone(at(100.0, 50.0, 600.0), size, &[left]),
            Some(Pos2::new(700.0, 50.0))
        );
        // No room on the right: to the left.
        assert_eq!(
            beside_alone(at(1000.0, 50.0, 600.0), size, &[left]),
            Some(Pos2::new(200.0, 50.0))
        );
        // Room on neither side: on the side with more room (left), over it.
        assert_eq!(
            beside_alone(at(300.0, 50.0, 1400.0), size, &[left]),
            Some(Pos2::new(0.0, 50.0))
        );
        // Kept on the monitor the window is on, and above its bottom.
        assert_eq!(
            beside_alone(at(2100.0, 900.0, 600.0), size, &[left, right]),
            Some(Pos2::new(2700.0, 550.0))
        );
        assert_eq!(
            beside_alone(at(3000.0, 0.0, 600.0), size, &[left, right]),
            Some(Pos2::new(2200.0, 0.0))
        );
        // No room on the right: below, left edges level, slid back onto
        // the monitor when it would go off it; above when only that fits.
        let short = |x: f32, y: f32, w: f32| Frame {
            outer: Rect::from_min_size(Pos2::new(x, y), Vec2::new(w, 300.0)),
            border: Vec2::new(0.0, 30.0),
        };
        assert_eq!(
            beside_alone(short(1000.0, 0.0, 600.0), size, &[left]),
            Some(Pos2::new(1000.0, 300.0))
        );
        assert_eq!(
            beside_alone(short(1300.0, 0.0, 600.0), size, &[left]),
            Some(Pos2::new(1120.0, 300.0))
        );
        assert_eq!(
            beside_alone(short(300.0, 600.0, 1400.0), size, &[left]),
            Some(Pos2::new(300.0, 70.0))
        );
        // No monitors known: no place.
        assert_eq!(beside_alone(at(0.0, 0.0, 600.0), size, &[]), None);

        // Beside the window pinned last, clear of the others: a row of
        // small windows grows beside a big one.
        let tall = Rect::from_min_size(Pos2::ZERO, Vec2::new(1920.0, 1200.0));
        let main = at(0.0, 0.0, 600.0);
        let small = Vec2::new(300.0, 270.0);
        let first = Rect::from_min_size(Pos2::new(600.0, 0.0), Vec2::new(300.0, 300.0));
        assert_eq!(
            beside(main, &[first], small, &[tall]),
            Some(Pos2::new(900.0, 0.0))
        );
        // No room beside it: below it, and failing that beside the others.
        let right_of_main = Rect::from_min_size(Pos2::new(600.0, 0.0), Vec2::new(800.0, 600.0));
        let below_main = Rect::from_min_size(Pos2::new(0.0, 600.0), Vec2::new(600.0, 600.0));
        assert_eq!(
            beside(main, &[right_of_main], size, &[tall]),
            Some(Pos2::new(600.0, 600.0))
        );
        let bottom = Rect::from_min_size(Pos2::new(0.0, 600.0), Vec2::new(1920.0, 600.0));
        assert_eq!(
            beside(main, &[bottom], size, &[tall]),
            Some(Pos2::new(600.0, 0.0))
        );
        assert_eq!(
            beside(main, &[right_of_main, below_main], size, &[tall]),
            Some(Pos2::new(600.0, 600.0))
        );
        // Nowhere clear: where it covers them least.
        let rest = Rect::from_min_size(Pos2::new(600.0, 600.0), Vec2::new(1320.0, 600.0));
        let far = Rect::from_min_size(Pos2::new(1400.0, 0.0), Vec2::new(520.0, 600.0));
        let pos = beside(main, &[right_of_main, below_main, rest, far], size, &[tall]);
        assert!(
            pos.is_some_and(|p| tall.contains_rect(Rect::from_min_size(p, size + main.border)))
        );
    }

    #[test]
    fn same_display_compares_effective_macros() {
        use super::Location;
        use bob::{Macros, Source};
        let loc = |pairs: &[(&str, &str)]| Location {
            source: Source::parse("a.bob"),
            macros: Macros::from_pairs(pairs.iter().copied()),
        };
        let flat = loc(&[("P", "X"), ("R", "1")]);
        assert!(flat.same_display(&loc(&[("R", "0"), ("P", "X"), ("R", "1")])));
        assert!(!flat.same_display(&loc(&[("P", "X"), ("R", "2")])));
        let other = Location {
            source: Source::parse("b.bob"),
            ..flat.clone()
        };
        assert!(!flat.same_display(&other));
        // A BOY display's `$(DID)` is its own, whatever the link passed.
        let opi = |pairs: &[(&str, &str)]| Location {
            source: Source::parse("a.opi"),
            ..loc(pairs)
        };
        assert!(opi(&[("P", "X"), ("DID", "DID_1")]).same_display(&opi(&[("P", "X")])));
        assert!(!opi(&[("P", "X"), ("DID", "DID_1")]).same_display(&opi(&[("P", "Y")])));
        assert!(!loc(&[("DID", "1")]).same_display(&loc(&[("DID", "2")])));
    }

    #[test]
    fn requests_act_on_their_own_window() {
        use super::{BobApp, Location, Origin, WindowKey};
        use crate::widgets::Request;
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), crate::chrome::UiScale::Auto);
        let display = |name: &str| Location {
            source: bob::Source::File(format!("/no/such/{name}.bob").into()),
            macros: bob::Macros::from_pairs([("P", name)]),
        };
        let open = |app: &mut BobApp, origin: Origin, loc: Location| {
            let req = Request::Open {
                source: loc.source,
                macros: loc.macros,
                target: "replace".into(),
            };
            app.request(&ctx, origin, req);
        };
        let plain = |window| Origin {
            window,
            ..Origin::default()
        };
        let ctrl = |window| Origin {
            window,
            ctrl: true,
            shift: false,
        };
        let shift = |window| Origin {
            window,
            ctrl: false,
            shift: true,
        };
        let main = WindowKey::Main;
        let current = |app: &BobApp, i: usize| app.windows[i].view.current.clone();
        // Ctrl+click in the pinned main window navigates it.
        open(&mut app, ctrl(main), display("a"));
        assert_eq!(app.main.current, Some(display("a")));

        // A link opens a new window, the viewer, and again raises it.
        open(&mut app, plain(main), display("b"));
        assert_eq!(app.windows.len(), 1);
        let first = WindowKey::Child(app.windows[0].id);
        open(&mut app, plain(main), display("b"));
        assert_eq!(app.windows.len(), 1);
        // The same display with other macros goes to the viewer, which keeps
        // its history.
        let mut other = display("b");
        other.macros = bob::Macros::from_pairs([("P", "c")]);
        open(&mut app, plain(main), other.clone());
        assert_eq!(app.windows.len(), 1);
        assert_eq!(current(&app, 0), Some(other.clone()));
        assert_eq!(app.windows[0].view.back, [display("b")]);
        // Shift+click opens a new window, which becomes the viewer.
        open(&mut app, shift(main), display("d"));
        assert_eq!(app.windows.len(), 2);
        let second = WindowKey::Child(app.windows[1].id);
        open(&mut app, plain(main), display("e"));
        assert_eq!(current(&app, 1), Some(display("e")));
        assert_eq!(current(&app, 0), Some(other));
        // A link in an unpinned window navigates it.
        open(&mut app, plain(first), display("f"));
        assert_eq!(current(&app, 0), Some(display("f")));
        // Pinned, a window is no longer the viewer: the other one is.
        app.windows[1].pinned = true;
        open(&mut app, plain(main), display("g"));
        assert_eq!(current(&app, 0), Some(display("g")));
        // A link in a pinned window goes to the viewer too.
        open(&mut app, plain(second), display("h"));
        assert_eq!(current(&app, 0), Some(display("h")));
        assert_eq!(current(&app, 1), Some(display("e")));
        // Every window pinned: a link opens a new one.
        app.windows[0].pinned = true;
        open(&mut app, plain(main), display("i"));
        assert_eq!(app.windows.len(), 3);
        // Ctrl+click in a pinned window navigates it.
        open(&mut app, ctrl(second), display("j"));
        assert_eq!(current(&app, 1), Some(display("j")));
        // The main window unpinned (in its toolbar) is the viewer, as the
        // window used last.
        app.main_pinned = false;
        app.main_used.touch(&mut app.clock);
        open(&mut app, plain(second), display("k"));
        assert_eq!(app.main.current, Some(display("k")));
        // Where displays have no windows of their own, every link is in place.
        app.can_windows = false;
        open(&mut app, shift(second), display("l"));
        assert_eq!(current(&app, 1), Some(display("l")));
        assert_eq!(app.windows.len(), 3);

        // Exit closes a display window even when it has history.
        app.request(&ctx, plain(second), Request::Close);
        assert!(app.view_mut(second).is_none());
        // The main window still goes back first.
        app.request(&ctx, plain(main), Request::Close);
        assert_eq!(app.main.current, Some(display("a")));

        // Closing all other windows keeps the main one and the one asking.
        let open_windows = |app: &BobApp| app.windows.iter().filter(|w| !w.close).count();
        assert_eq!(open_windows(&app), 2);
        app.request(&ctx, plain(first), Request::CloseOthers);
        assert_eq!(open_windows(&app), 1);
        assert!(app.view_mut(first).is_some());
        app.request(&ctx, plain(main), Request::CloseOthers);
        assert_eq!(open_windows(&app), 0);
        assert_eq!(app.main.current, Some(display("a")));
    }

    #[test]
    fn a_link_to_its_own_windows_display_reloads_it() {
        use super::{BobApp, Location, Origin, WindowKey};
        use crate::tree::{Clicked, Target};
        use crate::widgets::Request;
        // Following a link to the display shown reloads it, clearing the
        // fetch cache.
        let _cache = crate::fetch::tests::CACHE_USERS.lock();
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), crate::chrome::UiScale::Auto);
        let display = |name: &str| Location {
            source: bob::Source::File(format!("/no/such/{name}.bob").into()),
            macros: bob::Macros::from_pairs([("P", name)]),
        };
        let open = |app: &mut BobApp, window, ctrl, loc: Location| {
            let req = Request::Open {
                source: loc.source,
                macros: loc.macros,
                target: "replace".into(),
            };
            let origin = Origin {
                window,
                ctrl,
                shift: false,
            };
            app.request(&ctx, origin, req);
        };
        let main = WindowKey::Main;
        // The main window and a child both show a; the child came from b.
        open(&mut app, main, true, display("a"));
        open(&mut app, main, false, display("b"));
        let child = WindowKey::Child(app.windows[0].id);
        open(&mut app, child, true, display("a"));
        assert_eq!(app.windows[0].view.back, [display("b")]);
        // The child's link to a reloads the child, not raising the main
        // window, and adds nothing to Back however often it is pressed.
        let shown = (app.main.shown, app.windows[0].view.shown);
        open(&mut app, child, false, display("a"));
        open(&mut app, child, false, display("a"));
        assert_eq!(app.windows[0].view.current, Some(display("a")));
        assert_eq!(app.windows[0].view.back, [display("b")]);
        assert_eq!(app.windows[0].view.shown, shown.1 + 2);
        assert_eq!(app.main.shown, shown.0);
        assert_eq!(app.windows.len(), 1);
        // The main window's from its own link too.
        open(&mut app, main, false, display("a"));
        assert!(app.main.back.is_empty());
        assert_eq!(app.main.shown, shown.0 + 1);

        // A navigator click on the main window's display leaves it be.
        for (ctrl, shift) in [(false, false), (true, false), (false, true)] {
            app.open_from_tree(
                &ctx,
                Clicked {
                    target: Target::Display(display("a")),
                    ctrl,
                    shift,
                },
            );
        }
        assert_eq!(app.main.shown, shown.0 + 1);
        assert!(app.main.back.is_empty());
        assert_eq!(app.windows.len(), 1);
    }

    #[test]
    fn a_link_to_its_own_display_counts_the_displays_own_macros() {
        use super::{BobApp, Location, Origin, WindowKey};
        use crate::widgets::Request;
        let dir = std::env::temp_dir().join(format!("bobview-own-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("own.bob");
        std::fs::write(
            &file,
            r#"<display version="2.0.0"><name>Own</name><macros><X>1</X></macros></display>"#,
        )
        .unwrap();
        let at = |pairs: &[(&str, &str)]| Location {
            source: bob::Source::File(file.clone()),
            macros: bob::Macros::from_pairs(pairs.iter().copied()),
        };
        // Following a link to the display shown reloads it, clearing the
        // fetch cache.
        let _cache = crate::fetch::tests::CACHE_USERS.lock();
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), crate::chrome::UiScale::Auto);
        let open = |app: &mut BobApp, ctrl, loc: Location| {
            let req = Request::Open {
                source: loc.source,
                macros: loc.macros,
                target: "replace".into(),
            };
            let origin = Origin {
                window: WindowKey::Main,
                ctrl,
                shift: false,
            };
            app.request(&ctx, origin, req);
        };
        open(&mut app, true, at(&[("P", "a")]));
        // Showing a display waits only briefly for its build thread.
        wait_loaded(&ctx, &mut app.main);
        assert!(app.main.screen.is_some());
        let shown = app.main.shown;
        // Its link has the display's own macros too: reloaded in place, in
        // the pinned main window, not opened in a new one.
        open(&mut app, false, at(&[("X", "1"), ("P", "a")]));
        wait_loaded(&ctx, &mut app.main);
        std::fs::remove_dir_all(&dir).ok();
        assert!(app.main.back.is_empty());
        assert_eq!(app.main.shown, shown + 1);
        assert!(app.windows.is_empty());
    }

    #[test]
    fn plain_names_drop_the_ca_prefix_and_type() {
        let t = |n: &str| plain_name(&PvName::parse(n));
        assert_eq!(t("loc://t1<VDouble>(1.5)"), "loc://t1");
        assert_eq!(t("ca://BL01T:X"), "BL01T:X");
        assert_eq!(t("BL01T:X"), "BL01T:X");
        assert_eq!(t("pva://BL01T:Y"), "pva://BL01T:Y");
        // A formula and an unknown PV type keep their whole text.
        assert_eq!(t("=(pv(\"X\") < 5)"), "=(pv(\"X\") < 5)");
        assert_eq!(t("sys://time"), "sys://time");
    }

    /// Poll `view` until its display has loaded, which takes as long as its
    /// build thread does under load.
    fn wait_loaded(ctx: &eframe::egui::Context, view: &mut crate::view::View) {
        let until = std::time::Instant::now() + std::time::Duration::from_secs(20);
        while view.is_loading() {
            assert!(std::time::Instant::now() < until, "never loaded");
            std::thread::sleep(std::time::Duration::from_millis(5));
            view.poll_loading(ctx);
        }
    }

    /// Draw `frames` frames of `app` in a window of `size` points, as a
    /// window manager would: the window takes the sizes the app asks for.
    fn run(
        ctx: &eframe::egui::Context,
        app: &mut super::BobApp,
        size: &mut eframe::egui::Vec2,
        frames: usize,
    ) {
        use eframe::egui::{self, Pos2, Rect, Vec2};
        let monitor = Vec2::new(1920.0, 1080.0);
        // Past `frames`, keep drawing while this app's displays still load:
        // under load the build threads can take longer than the frames do.
        let until = std::time::Instant::now() + std::time::Duration::from_secs(20);
        let mut drawn = 0;
        while drawn < frames
            || (std::time::Instant::now() < until
                && (app.main.is_loading() || app.windows.iter().any(|w| w.view.is_loading())))
        {
            drawn += 1;
            let zoom = ctx.zoom_factor();
            let screen = Rect::from_min_size(Pos2::ZERO, *size / zoom);
            let mut input = egui::RawInput {
                screen_rect: Some(screen),
                ..Default::default()
            };
            let info = input.viewports.entry(egui::ViewportId::ROOT).or_default();
            info.native_pixels_per_point = Some(1.0);
            info.inner_rect = Some(screen);
            info.outer_rect = Some(screen);
            info.monitor_size = Some(monitor / zoom);
            let mut output = ctx.run_ui(input, |ui| app.draw(ui));
            output.textures_delta.clear();
            if let Some(vp) = output.viewport_output.get(&egui::ViewportId::ROOT) {
                for cmd in &vp.commands {
                    if let egui::ViewportCommand::InnerSize(s) = cmd {
                        *size = (*s * zoom).round().min(monitor);
                    }
                }
            }
            // Displays load, and the navigator reads them, on threads.
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    /// Records what a copy puts on the primary selection.
    struct FakePrimary(std::sync::Arc<parking_lot::Mutex<Vec<String>>>);

    impl crate::selection::Primary for FakePrimary {
        fn set(&mut self, text: &str) -> Result<(), String> {
            self.0.lock().push(text.to_string());
            Ok(())
        }
    }

    /// A primary selection a test fills.
    struct FakeRead(Option<String>);

    impl crate::selection::ReadPrimary for FakeRead {
        fn get(&mut self) -> Option<String> {
            self.0.clone()
        }
    }

    /// A primary selection whose owner answers only when the test says.
    struct SlowRead(std::sync::mpsc::Receiver<()>);

    impl crate::selection::ReadPrimary for SlowRead {
        fn get(&mut self) -> Option<String> {
            self.0.recv().ok();
            Some("LATE:PV".into())
        }
    }

    #[test]
    fn a_selection_answering_after_the_wait_is_dropped() {
        use super::BobApp;
        use crate::chrome::UiScale;
        use eframe::egui::{self, Event, Modifiers, PointerButton, Pos2};
        let ctx = egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), UiScale::Fixed(1.0));
        let req = crate::widgets::Request::Trend(vec!["LATE:A".into()]);
        app.request(&ctx, super::Origin::default(), req);
        let mut size = crate::chrome::DEFAULT_WINDOW;
        run(&ctx, &mut app, &mut size, 5);
        let plot = ctx
            .memory(|m| m.area_rect(super::trend_window_id(0)))
            .expect("the trend is drawn")
            .center();
        let (answer, wait) = std::sync::mpsc::channel();
        app.set_selection_reader(Some(Box::new(move || Box::new(SlowRead(wait)))));
        let press = |pressed| Event::PointerButton {
            pos: plot,
            button: PointerButton::Middle,
            pressed,
            modifiers: Modifiers::NONE,
        };
        for events in [
            vec![Event::PointerMoved(plot)],
            vec![press(true)],
            vec![press(false)],
        ] {
            let input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
                events,
                ..Default::default()
            };
            ctx.run_ui(input, |ui| app.draw(ui)).textures_delta.clear();
        }
        assert!(app.trends[0].is_reading(), "asked for the selection");
        // No frame until past the wait, and the answer is in by then.
        std::thread::sleep(crate::trend::SELECTION_WAIT);
        answer.send(()).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(200));
        run(&ctx, &mut app, &mut size, 2);
        assert!(!app.trends[0].is_reading());
        assert_eq!(
            app.trends[0].names(),
            ["LATE:A"],
            "the late answer is dropped"
        );
        let (text, error) = app.trends[0].notice().unwrap();
        assert!(error && text.contains("Could not read"), "{text}");
    }

    #[test]
    fn a_middle_click_on_a_trend_adds_the_selected_pvs() {
        use super::BobApp;
        use crate::chrome::UiScale;
        use eframe::egui::{self, Event, Modifiers, PointerButton, Pos2};
        let ctx = egui::Context::default();
        let mut app = BobApp::new(&ctx, None, Some(1.0), UiScale::Fixed(1.0));
        let req = crate::widgets::Request::Trend(vec!["loc://mid_a(0)".into()]);
        app.request(&ctx, super::Origin::default(), req);
        let mut size = crate::chrome::DEFAULT_WINDOW;
        run(&ctx, &mut app, &mut size, 5);
        // The middle of the trend's window: its plot.
        let plot = ctx
            .memory(|m| m.area_rect(super::trend_window_id(0)))
            .expect("the trend is drawn")
            .center();
        let mut middle_click = |app: &mut BobApp, selected: Option<&str>| {
            let fake = FakeRead(selected.map(str::to_string));
            app.set_selection_reader(Some(Box::new(move || Box::new(fake))));
            let press = |pressed| Event::PointerButton {
                pos: plot,
                button: PointerButton::Middle,
                pressed,
                modifiers: Modifiers::NONE,
            };
            for events in [
                vec![Event::PointerMoved(plot)],
                vec![press(true)],
                vec![press(false)],
            ] {
                let input = egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
                    events,
                    ..Default::default()
                };
                ctx.run_ui(input, |ui| app.draw(ui)).textures_delta.clear();
            }
            assert!(app.trends[0].is_reading(), "asked for the selection");
            let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while app.trends[0].is_reading() {
                assert!(std::time::Instant::now() < until, "never answered");
                std::thread::sleep(std::time::Duration::from_millis(5));
                run(&ctx, app, &mut size, 1);
            }
            // The next frame says what the paste did.
            run(&ctx, app, &mut size, 1);
        };
        middle_click(&mut app, Some("MID:B MID:C, INFO:root:x"));
        assert_eq!(app.trends[0].names(), ["loc://mid_a(0)", "MID:B", "MID:C"]);
        assert_eq!(app.trends[0].notice(), Some(("Added 2 PVs", false)));
        // Nothing selected, or no PVs: nothing added, and it says so.
        middle_click(&mut app, None);
        assert_eq!(app.trends[0].names().len(), 3);
        let (text, error) = app.trends[0].notice().unwrap();
        assert!(error && text.contains("empty"), "{text}");
        middle_click(&mut app, Some("just some words"));
        assert_eq!(app.trends[0].names().len(), 3);
        let (text, error) = app.trends[0].notice().unwrap();
        assert!(error && text.contains("No PV names"), "{text}");
        // With no primary selection (snapshots, Windows, macOS) a
        // middle-click does nothing.
        app.set_selection_reader(None);
        let press = |pressed| Event::PointerButton {
            pos: plot,
            button: PointerButton::Middle,
            pressed,
            modifiers: Modifiers::NONE,
        };
        for events in [vec![press(true)], vec![press(false)]] {
            let input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
                events,
                ..Default::default()
            };
            ctx.run_ui(input, |ui| app.draw(ui)).textures_delta.clear();
        }
        assert!(!app.trends[0].is_reading());
        assert_eq!(app.trends[0].names().len(), 3);
    }

    #[test]
    fn a_middle_click_copies_the_pv_name_to_both_selections() {
        use super::{BobApp, Location};
        use crate::chrome::UiScale;
        use eframe::egui::{self, Event, Modifiers, OutputCommand, PointerButton, Pos2};
        let dir = std::env::temp_dir().join(format!("bobview-copy-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("copy.bob");
        // One big widget, so a click in the middle of the window hits it.
        std::fs::write(
            &file,
            "<display><macros><P>copy_t</P></macros><widget type=\"textupdate\">\
             <width>600</width><height>300</height>\
             <pv_name>loc://$(P)&lt;VDouble&gt;(1)</pv_name></widget></display>",
        )
        .unwrap();
        let display = Location {
            source: bob::Source::File(file),
            macros: bob::Macros::default(),
        };
        let ctx = egui::Context::default();
        let mut app = BobApp::new(&ctx, Some(display), Some(1.0), UiScale::Fixed(1.0));
        let primary = std::sync::Arc::new(parking_lot::Mutex::new(Vec::new()));
        app.primary = Box::new(FakePrimary(primary.clone()));
        let mut size = crate::chrome::DEFAULT_WINDOW;
        run(&ctx, &mut app, &mut size, 5);

        let pos = Pos2::new(300.0, 200.0);
        let mut copied = Vec::new();
        for button in [PointerButton::Primary, PointerButton::Middle] {
            let press = |pressed| Event::PointerButton {
                pos,
                button,
                pressed,
                modifiers: Modifiers::NONE,
            };
            for events in [
                vec![Event::PointerMoved(pos)],
                vec![press(true)],
                vec![press(false)],
            ] {
                let input = egui::RawInput {
                    screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
                    events,
                    ..Default::default()
                };
                let out = ctx.run_ui(input, |ui| app.draw(ui));
                copied.extend(
                    out.platform_output
                        .commands
                        .into_iter()
                        .filter_map(|c| match c {
                            OutputCommand::CopyText(t) => Some(t),
                            _ => None,
                        }),
                );
            }
            // A plain click copies nothing.
            if button == PointerButton::Primary {
                assert!(copied.is_empty() && primary.lock().is_empty());
            }
        }
        assert_eq!(copied, ["loc://copy_t"]);
        assert_eq!(*primary.lock(), ["loc://copy_t"]);
        assert!(app.main.copied.is_some());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_saved_navigator_is_restored_with_its_room() {
        use super::{BobApp, Location};
        use crate::chrome::UiScale;
        let display = Location {
            source: bob::Source::File(
                std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                    .join("../../tests/displays/index.bob"),
            ),
            macros: bob::Macros::default(),
        };
        // Open the display: the window takes its size.
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, Some(display), None, UiScale::Fixed(1.0));
        let mut size = crate::chrome::DEFAULT_WINDOW;
        run(&ctx, &mut app, &mut size, 40);
        let alone = size;
        // Show the navigator: the window widens by it.
        app.tree.open = true;
        app.tree_toggled = true;
        run(&ctx, &mut app, &mut size, 20);
        let with_tree = size;
        assert!(with_tree.x > alone.x + 100.0, "{alone:?} -> {with_tree:?}");
        // Saved and restored: the same size, the navigator shown.
        let layout = app.layout();
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, None, UiScale::Fixed(1.0));
        app.restore_layout(layout, Some("default".into()));
        let mut size = crate::chrome::DEFAULT_WINDOW;
        run(&ctx, &mut app, &mut size, 60);
        assert!(app.tree.open);
        assert_eq!(size, with_tree);
    }

    #[test]
    fn a_restored_window_cut_to_its_first_monitor_is_sized_again() {
        use super::BobApp;
        use crate::layout::Geometry;
        use eframe::egui::{Pos2, Vec2};
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, None, crate::chrome::UiScale::Fixed(1.0));
        // The layout's place reached, but the width cut to a 1200 wide
        // monitor the window started on.
        app.restoring = Some((
            Geometry {
                position: Some(Pos2::ZERO),
                size: Some(Vec2::new(1471.0, 900.0)),
            },
            None,
        ));
        let mut size = Vec2::new(1200.0, 900.0);
        run(&ctx, &mut app, &mut size, 3);
        assert_eq!(size, Vec2::new(1471.0, 900.0));
        assert!(app.restoring.is_none());
    }

    #[test]
    fn a_restored_window_that_never_gets_there_is_left_alone() {
        use super::{BobApp, RESTORE_WAIT};
        use crate::layout::Geometry;
        use eframe::egui::{Pos2, Vec2};
        let ctx = eframe::egui::Context::default();
        let mut app = BobApp::new(&ctx, None, None, crate::chrome::UiScale::Fixed(1.0));
        // Kept away from the layout's place (by the window manager, or
        // fullscreen): not sized while it waits, then given up.
        app.restoring = Some((
            Geometry {
                position: Some(Pos2::new(500.0, 300.0)),
                size: Some(Vec2::new(1471.0, 900.0)),
            },
            None,
        ));
        let mut size = Vec2::new(1200.0, 900.0);
        run(&ctx, &mut app, &mut size, 3);
        assert!(app.restoring.is_some());
        // Frames are 1/60 s apart when the input gives no time.
        let frames = (RESTORE_WAIT * 60.0) as usize + 10;
        run(&ctx, &mut app, &mut size, frames);
        assert!(app.restoring.is_none());
        assert_eq!(size, Vec2::new(1200.0, 900.0));
    }

    /// Runs [`super::App`] as eframe does with native windows: each window's
    /// pass runs on its own, when a repaint was asked of it (by the repaint
    /// callback eframe sets) or it has input, the display and trend windows
    /// through the callbacks the main window's pass registered. Time is
    /// simulated, so a delayed repaint runs as soon as nothing comes first.
    struct Desktop {
        ctx: eframe::egui::Context,
        app: super::App,
        /// When each window has asked to be repainted, in simulated seconds.
        asked: std::sync::Arc<parking_lot::Mutex<std::collections::HashMap<ViewportId, f64>>>,
        windows: std::collections::HashMap<ViewportId, std::sync::Arc<Callback>>,
        /// Passes run of each window since the last `count`.
        passes: std::collections::HashMap<ViewportId, usize>,
        time: f64,
        /// The time, for the repaint callback.
        clock: std::sync::Arc<parking_lot::Mutex<f64>>,
    }

    type Callback = eframe::egui::viewport::DeferredViewportUiCallback;
    use eframe::egui::ViewportId;

    impl Desktop {
        fn new(start: super::Location) -> Self {
            let ctx = eframe::egui::Context::default();
            ctx.set_embed_viewports(false);
            let asked = std::sync::Arc::new(parking_lot::Mutex::new(std::collections::HashMap::<
                ViewportId,
                f64,
            >::new()));
            let app =
                super::BobApp::new(&ctx, Some(start), None, crate::chrome::UiScale::Fixed(1.0));
            let mut desk = Self {
                ctx,
                app: super::App::new(app),
                asked,
                windows: Default::default(),
                passes: Default::default(),
                time: 0.0,
                clock: Default::default(),
            };
            let (asked, clock) = (desk.asked.clone(), desk.clock.clone());
            desk.ctx.set_request_repaint_callback(move |info| {
                let due = *clock.lock() + info.delay.as_secs_f64().min(1e6);
                let mut asked = asked.lock();
                let at = asked.entry(info.viewport_id).or_insert(due);
                *at = at.min(due);
            });
            desk.pass(ViewportId::ROOT, Vec::new());
            desk
        }

        /// Where each window is on the desktop: side by side.
        fn rect(id: ViewportId) -> eframe::egui::Rect {
            use eframe::egui::{Pos2, Rect, Vec2};
            let i = if id == ViewportId::ROOT {
                0.0
            } else {
                1.0 + (id.0.value() % 7) as f32
            };
            Rect::from_min_size(Pos2::new(i * 10.0, i * 10.0), Vec2::new(500.0, 400.0))
        }

        /// One pass of the window `id`, with `events` as its input.
        fn pass(&mut self, id: ViewportId, events: Vec<eframe::egui::Event>) {
            use eframe::egui;
            let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, Self::rect(id).size());
            let mut input = egui::RawInput {
                viewport_id: id,
                screen_rect: Some(screen),
                time: Some(self.time),
                events,
                ..Default::default()
            };
            for vp in std::iter::once(ViewportId::ROOT).chain(self.windows.keys().copied()) {
                let info = input.viewports.entry(vp).or_default();
                info.parent = (vp != ViewportId::ROOT).then_some(ViewportId::ROOT);
                info.native_pixels_per_point = Some(1.0);
                info.inner_rect = Some(Self::rect(vp));
                info.outer_rect = Some(Self::rect(vp));
                info.monitor_size = Some(egui::Vec2::new(1920.0, 1080.0));
            }
            *self.clock.lock() = self.time;
            self.asked.lock().remove(&id);
            let mut output = if id == ViewportId::ROOT {
                self.ctx.run_ui(input, |ui| self.app.draw(ui))
            } else {
                let Some(cb) = self.windows.get(&id).cloned() else {
                    return;
                };
                self.ctx.run_ui(input, |ui| cb(ui))
            };
            output.textures_delta.clear();
            *self.passes.entry(id).or_default() += 1;
            // The windows still open, a new one drawn at once.
            let open: Vec<ViewportId> = output.viewport_output.keys().copied().collect();
            self.windows.retain(|vp, _| open.contains(vp));
            for (vp, out) in output.viewport_output {
                if let Some(cb) = out.viewport_ui_cb
                    && self.windows.insert(vp, cb).is_none()
                {
                    self.asked.lock().insert(vp, self.time);
                }
            }
        }

        /// Run the passes asked for until none is due within half a second
        /// (a trend scrolls once a second).
        fn settle(&mut self) {
            for _ in 0..2000 {
                let next = {
                    let asked = self.asked.lock();
                    asked.values().copied().fold(f64::INFINITY, f64::min)
                };
                if next > self.time + 0.5 {
                    return;
                }
                self.time = self.time.max(next);
                // The main window first, as it opens and closes the others.
                let mut due: Vec<ViewportId> = self
                    .asked
                    .lock()
                    .iter()
                    .filter(|(_, at)| **at <= self.time)
                    .map(|(id, _)| *id)
                    .collect();
                due.sort_by_key(|id| *id != ViewportId::ROOT);
                for id in due {
                    self.pass(id, Vec::new());
                }
                // A frame's time; displays load, and images are read, on
                // threads.
                std::thread::sleep(std::time::Duration::from_millis(1));
                self.time += 1.0 / 60.0;
            }
            panic!("the windows never stop repainting");
        }

        /// The passes of each window since the last call.
        fn count(&mut self) -> std::collections::HashMap<ViewportId, usize> {
            std::mem::take(&mut self.passes)
        }

        /// The display windows, in the order they opened.
        fn children(&self) -> Vec<ViewportId> {
            self.app.0.lock().windows.iter().map(|w| w.id).collect()
        }
    }

    /// A display of a text update on each PV of `pvs`, and an action button
    /// over its top left that opens `link`.
    fn pv_display(dir: &std::path::Path, name: &str, pvs: &[&str], link: &str) -> super::Location {
        let mut widgets = String::new();
        for (i, pv) in pvs.iter().enumerate() {
            widgets += &format!(
                r#"<widget type="textupdate" version="2.0.0"><name>t{i}</name><pv_name>{pv}</pv_name><x>10</x><y>{}</y><width>100</width><height>20</height></widget>"#,
                60 + 30 * i
            );
        }
        let file = dir.join(format!("{name}.bob"));
        std::fs::write(
            &file,
            format!(
                r#"<display version="2.0.0"><name>{name}</name><width>200</width><height>150</height>
<widget type="action_button" version="3.0.0"><name>link</name><actions><action type="open_display"><file>{link}</file><target>replace</target></action></actions><x>0</x><y>0</y><width>200</width><height>50</height></widget>
{widgets}</display>"#
            ),
        )
        .unwrap();
        super::Location {
            source: bob::Source::File(file),
            macros: bob::Macros::default(),
        }
    }

    /// The main window showing M, and display windows showing A and B,
    /// opened from it; A and B both show the PV `shared`.
    fn three_windows(tag: &str) -> (Desktop, std::path::PathBuf) {
        let dir = std::env::temp_dir().join(format!("bobview-{tag}-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let pv = |n: &str| format!("loc://{tag}_{n}(0)");
        let m = pv_display(&dir, "m", &[&pv("m")], "c.bob");
        let a = pv_display(&dir, "a", &[&pv("a"), &pv("shared")], "c.bob");
        let b = pv_display(&dir, "b", &[&pv("b"), &pv("shared")], "c.bob");
        pv_display(&dir, "c", &[&pv("c")], "a.bob");
        pv_display(&dir, "m2", &[&pv("m2")], "a.bob");
        let mut desk = Desktop::new(m);
        desk.settle();
        for loc in [a, b] {
            let origin = super::Origin {
                window: super::WindowKey::Main,
                ctrl: false,
                shift: true,
            };
            let req = crate::widgets::Request::Open {
                source: loc.source,
                macros: loc.macros,
                target: "replace".into(),
            };
            desk.app.0.lock().request(&desk.ctx, origin, req);
        }
        desk.asked.lock().insert(ViewportId::ROOT, desk.time);
        desk.settle();
        assert_eq!(desk.children().len(), 2);
        assert_eq!(
            desk.windows.len(),
            2,
            "each display window drawn on its own"
        );
        (desk, dir)
    }

    #[test]
    fn the_pointer_in_one_window_redraws_only_that_window() {
        use eframe::egui::{Event, Pos2};
        let (mut desk, dir) = three_windows("pointer");
        let [a, b] = desk.children()[..] else {
            unreachable!()
        };
        desk.count();
        for i in 0..20 {
            let pos = Pos2::new(100.0 + i as f32 * 5.0, 200.0);
            desk.pass(a, vec![Event::PointerMoved(pos)]);
            desk.settle();
        }
        let passes = desk.count();
        std::fs::remove_dir_all(&dir).ok();
        assert!(passes.get(&a).is_some_and(|n| *n >= 20), "{passes:?}");
        assert_eq!(passes.get(&ViewportId::ROOT), None, "{passes:?}");
        assert_eq!(passes.get(&b), None, "{passes:?}");
    }

    #[test]
    fn a_pv_change_repaints_only_the_windows_showing_it() {
        let (mut desk, dir) = three_windows("pvchange");
        let [a, b] = desk.children()[..] else {
            unreachable!()
        };
        let pvs = desk.app.0.lock().pvs.clone();
        let write = |desk: &mut Desktop, name: &str, value: &str| {
            desk.count();
            pvs.subscribe(&format!("loc://pvchange_{name}(0)"))
                .write(value);
            desk.settle();
            desk.count()
        };
        let passes = write(&mut desk, "a", "1");
        assert!(passes.contains_key(&a), "{passes:?}");
        assert!(
            !passes.contains_key(&b) && !passes.contains_key(&ViewportId::ROOT),
            "{passes:?}"
        );
        let passes = write(&mut desk, "shared", "1");
        assert!(
            passes.contains_key(&a) && passes.contains_key(&b),
            "{passes:?}"
        );
        assert!(!passes.contains_key(&ViewportId::ROOT), "{passes:?}");
        let passes = write(&mut desk, "m", "1");
        assert!(passes.contains_key(&ViewportId::ROOT), "{passes:?}");
        assert!(
            !passes.contains_key(&a) && !passes.contains_key(&b),
            "{passes:?}"
        );
        // Many changes at once: still a few passes, not one each.
        desk.count();
        for i in 0..50 {
            pvs.subscribe("loc://pvchange_a(0)").write(i.to_string());
        }
        desk.settle();
        let passes = desk.count();
        assert!(passes.get(&a).is_some_and(|n| *n <= 3), "{passes:?}");
        // A trend window is one too.
        let origin = super::Origin::default();
        let req = crate::widgets::Request::Trend(vec!["loc://pvchange_b(0)".into()]);
        desk.app.0.lock().request(&desk.ctx, origin, req);
        desk.asked.lock().insert(ViewportId::ROOT, desk.time);
        desk.settle();
        let trend = super::trend_viewport(0);
        assert!(desk.windows.contains_key(&trend));
        let passes = write(&mut desk, "b", "2");
        assert!(
            passes.contains_key(&b) && passes.contains_key(&trend),
            "{passes:?}"
        );
        assert!(
            !passes.contains_key(&a) && !passes.contains_key(&ViewportId::ROOT),
            "{passes:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn windows_opened_or_changed_from_another_are_drawn() {
        use eframe::egui::{Event, Modifiers, PointerButton, Pos2};
        let (mut desk, dir) = three_windows("opened");
        let [a, b] = desk.children()[..] else {
            unreachable!()
        };
        // Shift+click A's link: a new window, which the main window opens on
        // its next pass.
        let pos = Pos2::new(10.0, 10.0);
        let click = |pressed| Event::PointerButton {
            pos,
            button: PointerButton::Primary,
            pressed,
            modifiers: Modifiers::SHIFT,
        };
        desk.count();
        let shift = Event::ModifiersChanged(Modifiers::SHIFT);
        desk.pass(a, vec![shift, Event::PointerMoved(pos), click(true)]);
        desk.pass(a, vec![click(false)]);
        desk.pass(a, vec![Event::ModifiersChanged(Modifiers::NONE)]);
        desk.settle();
        let passes = desk.count();
        let children = desk.children();
        assert_eq!(children.len(), 3, "{passes:?}");
        let c = children[2];
        assert!(desk.windows.contains_key(&c), "the new window is open");
        assert!(
            passes.contains_key(&ViewportId::ROOT) && passes.contains_key(&c),
            "{passes:?}"
        );
        assert!(!passes.contains_key(&b), "{passes:?}");

        // The main window's link goes to the viewer, C, which is repainted
        // to show it, from the main window's pass (a finished command).
        let to = |name: &str| super::Location {
            source: bob::Source::File(dir.join(format!("{name}.bob"))),
            macros: bob::Macros::default(),
        };
        {
            let app = desk.app.0.lock();
            let done = super::Launched {
                key: (None, None, "x".into()),
                origin: super::Origin::default(),
                shown: app.main.shown,
                target: Some(to("a")),
            };
            app.launched.0.send(done).unwrap();
        }
        // A was raised: it shows that display already.
        desk.asked.lock().insert(ViewportId::ROOT, desk.time);
        desk.settle();
        let passes = desk.count();
        assert!(!passes.contains_key(&b), "{passes:?}");
        // Now one no window shows.
        {
            let app = desk.app.0.lock();
            let done = super::Launched {
                key: (None, None, "y".into()),
                origin: super::Origin::default(),
                shown: app.main.shown,
                target: Some(to("m2")),
            };
            app.launched.0.send(done).unwrap();
        }
        desk.asked.lock().insert(ViewportId::ROOT, desk.time);
        desk.settle();
        let passes = desk.count();
        let app = desk.app.0.lock();
        let viewer = app
            .windows
            .iter()
            .find(|w| w.view.current == Some(to("m2")));
        let viewer = viewer.map(|w| w.id).expect("shown in the viewer");
        assert!(passes.contains_key(&viewer), "{passes:?}");
        assert!(!passes.contains_key(&b) || viewer == b, "{passes:?}");
        drop(app);

        // Ctrl+W in a window: the main window lets it go.
        let ctrl_w = Event::Key {
            key: eframe::egui::Key::W,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: Modifiers::COMMAND,
        };
        desk.pass(c, vec![ctrl_w]);
        desk.settle();
        assert_eq!(desk.children().len(), 2);
        assert!(!desk.windows.contains_key(&c));
        std::fs::remove_dir_all(&dir).ok();
    }
}