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
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
use std::str::FromStr as _;
use std::sync::Arc;
use anyhow::Context as _;
use egui::{FocusDirection, Key};
use itertools::Itertools as _;
use re_auth::credentials::CredentialsProvider as _;
use re_build_info::CrateVersion;
use re_byte_size::{MemUsageTree, MemUsageTreeCapture, NamedMemUsageTree};
use re_capabilities::MainThreadToken;
use re_chunk::TimelineName;
use re_data_source::{AuthErrorHandler, FileContents, LogDataSource};
use re_entity_db::InstancePath;
use re_entity_db::entity_db::EntityDb;
use re_log::debug_assert;
use re_log_channel::{
DataSourceMessage, DataSourceUiCommand, LogReceiver, LogReceiverSet, LogSource,
};
use re_log_types::{
ApplicationId, FileSource, LogMsg, RecordingId, StoreId, StoreKind, TableMsg, TimelinePoint,
};
use re_redap_client::ConnectionRegistryHandle;
use re_renderer::WgpuResourcePoolStatistics;
use re_sdk_types::blueprint::components::{LoopMode, PlayState};
use re_sdk_types::external::uuid;
use re_ui::{ContextExt as _, UICommand, UICommandSender as _, UiExt as _, notifications};
use re_viewer_context::open_url::{OpenUrlOptions, ViewerOpenUrl, combine_with_base_url};
use re_viewer_context::store_hub::{BlueprintPersistence, StoreHub, StoreHubStats};
use re_viewer_context::{
ActiveStoreContext, AppBlueprintCtx, AppOptions, AsyncRuntimeHandle, AuthContext,
CommandReceiver, CommandSender, ComponentUiRegistry, EditRedapServerModalCommand,
FallbackProviderRegistry, Item, MoveDirection, MoveSpeed, NeedsRepaint, RecordingOrTable,
Route, StorageContext, SystemCommand, SystemCommandSender as _, TableStore, TimeControlCommand,
ViewClass, ViewClassRegistry, ViewClassRegistryError, command_channel, sanitize_file_name,
};
use crate::AppState;
use crate::app_blueprint::{AppBlueprint, PanelStateOverrides};
use crate::app_state::WelcomeScreenState;
use crate::background_tasks::BackgroundTasks;
use crate::event::ViewerEventDispatcher;
use crate::latency_tracker::ServerLatencyTrackers;
use crate::startup_options::StartupOptions;
// ----------------------------------------------------------------------------
/// Storage key used to store the last run Rerun version.
///
/// This is then used to detect if the user has recently upgraded Rerun.
const RERUN_VERSION_KEY: &str = "rerun.version";
const REDAP_TOKEN_KEY: &str = "rerun.redap_token";
#[cfg(not(target_arch = "wasm32"))]
const MIN_ZOOM_FACTOR: f32 = 0.2;
#[cfg(not(target_arch = "wasm32"))]
const MAX_ZOOM_FACTOR: f32 = 5.0;
#[cfg(target_arch = "wasm32")]
struct PendingFilePromise {
recommended_store_id: Option<StoreId>,
force_store_info: bool,
promise: poll_promise::Promise<Vec<re_data_source::FileContents>>,
}
/// The Rerun Viewer as an [`eframe`] application.
pub struct App {
#[allow(clippy::allow_attributes, dead_code)] // Unused on wasm32
main_thread_token: MainThreadToken,
build_info: re_build_info::BuildInfo,
app_env: crate::AppEnvironment,
startup_options: StartupOptions,
start_time: web_time::Instant,
ram_limit_warner: re_memory::RamLimitWarner,
pub(crate) egui_ctx: egui::Context,
screenshotter: crate::screenshotter::Screenshotter,
texture_readback: crate::texture_readback::TextureReadbacks,
#[cfg(target_arch = "wasm32")]
pub(crate) popstate_listener: Option<crate::web_history::PopstateListener>,
#[cfg(not(target_arch = "wasm32"))]
profiler: re_tracing::Profiler,
/// Listens to the local text log stream
text_log_rx: crossbeam::channel::Receiver<re_log::LogMsg>,
component_ui_registry: ComponentUiRegistry,
component_fallback_registry: FallbackProviderRegistry,
rx_log: LogReceiverSet,
#[cfg(target_arch = "wasm32")]
open_files_promise: Option<PendingFilePromise>,
/// What is serialized
pub(crate) state: AppState,
/// Pending background tasks, e.g. files being saved.
pub(crate) background_tasks: BackgroundTasks,
/// Interface for all recordings and blueprints
pub(crate) store_hub: Option<StoreHub>,
/// Notification panel.
pub(crate) notifications: notifications::NotificationUi,
memory_panel: crate::memory_panel::MemoryPanel,
memory_panel_open: bool,
egui_debug_panel_open: bool,
/// Last time the latency was deemed interesting.
///
/// Note that initializing with an "old" `Instant` won't work reliably cross platform
/// since `Instant`'s counter may start at program start.
pub(crate) latest_latency_interest: Option<web_time::Instant>,
/// Measures how long a frame takes to paint
pub(crate) frame_time_history: egui::util::History<f32>,
/// Commands to run at the end of the frame.
pub command_sender: CommandSender,
command_receiver: CommandReceiver,
cmd_palette: re_ui::CommandPalette,
/// All known view types.
view_class_registry: ViewClassRegistry,
pub(crate) panel_state_overrides_active: bool,
pub(crate) panel_state_overrides: PanelStateOverrides,
reflection: re_types_core::reflection::Reflection,
/// External interactions with the Viewer host (JS, custom egui app, notebook, etc.).
pub event_dispatcher: Option<ViewerEventDispatcher>,
connection_registry: ConnectionRegistryHandle,
pub(crate) server_latency_trackers: ServerLatencyTrackers,
/// The async runtime that should be used for all asynchronous operations.
///
/// Using the global tokio runtime should be avoided since:
/// * we don't have a tokio runtime on web
/// * we want the user to have full control over the runtime,
/// and not expect that a global runtime exists.
async_runtime: AsyncRuntimeHandle,
}
impl App {
pub fn new(
main_thread_token: MainThreadToken,
build_info: re_build_info::BuildInfo,
app_env: crate::AppEnvironment,
startup_options: StartupOptions,
creation_context: &eframe::CreationContext<'_>,
connection_registry: Option<ConnectionRegistryHandle>,
tokio_runtime: AsyncRuntimeHandle,
) -> Self {
Self::with_commands(
main_thread_token,
build_info,
app_env,
startup_options,
creation_context,
connection_registry,
tokio_runtime,
crate::register_text_log_receiver(),
command_channel(),
)
}
/// Create a viewer that receives new log messages over time
#[expect(clippy::too_many_arguments)]
pub fn with_commands(
main_thread_token: MainThreadToken,
build_info: re_build_info::BuildInfo,
app_env: crate::AppEnvironment,
startup_options: StartupOptions,
creation_context: &eframe::CreationContext<'_>,
connection_registry: Option<ConnectionRegistryHandle>,
tokio_runtime: AsyncRuntimeHandle,
text_log_rx: crossbeam::channel::Receiver<re_log::LogMsg>,
command_channel: (CommandSender, CommandReceiver),
) -> Self {
re_tracing::profile_function!();
let connection_registry = connection_registry
.unwrap_or_else(re_redap_client::ConnectionRegistry::new_with_stored_credentials);
// Only subscribe to auth changes and load credentials if we're supposed to use stored credentials.
// This prevents tests from being affected by stored credentials on the developer's machine.
if connection_registry.should_use_stored_credentials() {
let command_sender = command_channel.0.clone();
re_auth::credentials::subscribe_auth_changes(move |user| {
command_sender.send_system(SystemCommand::OnAuthChanged(user.map(|user| {
AuthContext {
email: user.email,
org_name: user.org_name,
}
})));
});
// Call get_token once so the auth state is initialized.
tokio_runtime.spawn_future(async move {
re_auth::credentials::CliCredentialsProvider::new()
.get_token()
.await
.ok();
});
}
if connection_registry.should_use_stored_credentials()
&& let Some(storage) = creation_context.storage
&& let Some(tokens) = eframe::get_value(storage, REDAP_TOKEN_KEY)
{
connection_registry.load_tokens(tokens);
}
let mut state: AppState = if startup_options.persist_state {
creation_context.storage
.and_then(|storage| {
// This re-implements: `eframe::get_value` so we can customize the warning message.
// TODO(#2849): More thorough error-handling.
let value = storage.get_string(eframe::APP_KEY)?;
match ron::from_str(&value) {
Ok(value) => Some(value),
Err(err) => {
re_log::warn!("Failed to restore application state. This is expected if you have just upgraded Rerun versions.");
re_log::debug!("Failed to decode RON for app state: {err}");
None
}
}
})
.unwrap_or_default()
} else {
AppState::default()
};
if startup_options.persist_state {
// Check if the user has recently upgraded Rerun.
if let Some(storage) = creation_context.storage {
let current_version = build_info.version;
let previous_version: Option<CrateVersion> =
storage.get_string(RERUN_VERSION_KEY).and_then(|version| {
// `CrateVersion::try_parse` is `const` (for good reasons), and needs a `&'static str`.
// In order to accomplish this, we need to leak the string here.
let version = Box::leak(version.into_boxed_str());
CrateVersion::try_parse(version).ok()
});
if previous_version
.is_none_or(|previous_version| previous_version < CrateVersion::new(0, 24, 0))
{
re_log::debug!(
"Upgrading from {} to {}.",
previous_version.map_or_else(|| "<unknown>".to_owned(), |v| v.to_string()),
current_version
);
// We used to have Dark as the hard-coded theme preference. Let's change that!
creation_context
.egui_ctx
.options_mut(|o| o.theme_preference = egui::ThemePreference::System);
}
}
}
if let Some(video_decoder_hw_acceleration) = startup_options.video_decoder_hw_acceleration {
state.app_options.video.hw_acceleration = video_decoder_hw_acceleration;
}
if app_env.is_test() {
// Disable certain labels/warnings/etc that would be flaky or not CI-runner-agnostic in snapshot tests.
state.app_options.show_metrics = false;
}
let reflection = re_sdk_types::reflection::generate_reflection().unwrap_or_else(|err| {
re_log::error!(
"Failed to create list of serialized default values for components: {err}"
);
Default::default()
});
let mut component_fallback_registry =
re_component_fallbacks::create_component_fallback_registry();
let view_class_registry = crate::default_views::create_view_class_registry(
&reflection,
&state.app_options,
&mut component_fallback_registry,
)
.unwrap_or_else(|err| {
re_log::error!("Failed to create view class registry: {err}");
Default::default()
});
#[allow(clippy::allow_attributes, unused_mut, clippy::needless_update)]
// false positive on web
let mut screenshotter = crate::screenshotter::Screenshotter::default();
#[cfg(not(target_arch = "wasm32"))]
if let Some(screenshot_path) = startup_options.screenshot_to_path_then_quit.clone() {
screenshotter.screenshot_to_path_then_quit(&creation_context.egui_ctx, screenshot_path);
}
let (command_sender, command_receiver) = command_channel;
let mut component_ui_registry = re_component_ui::create_component_ui_registry();
re_data_ui::register_component_uis(&mut component_ui_registry);
let (_adapter_backend, _device_tier) = creation_context.wgpu_render_state.as_ref().map_or(
(
wgpu::Backend::Noop,
re_renderer::device_caps::DeviceCapabilityTier::Limited,
),
|render_state| {
let egui_renderer = render_state.renderer.read();
let render_ctx = egui_renderer
.callback_resources
.get::<re_renderer::RenderContext>();
(
render_state.adapter.get_info().backend,
render_ctx.map_or(
re_renderer::device_caps::DeviceCapabilityTier::Limited,
|ctx| ctx.device_caps().tier,
),
)
},
);
#[cfg(feature = "analytics")]
if let Some(analytics) = re_analytics::Analytics::global_or_init() {
use crate::viewer_analytics::event;
analytics.record(event::identify(
analytics.config(),
build_info.clone(),
&app_env,
));
analytics.record(event::viewer_started(
&app_env,
&creation_context.egui_ctx,
_adapter_backend,
_device_tier,
));
}
let panel_state_overrides = startup_options.panel_state_overrides;
let event_dispatcher = startup_options
.on_event
.clone()
.map(ViewerEventDispatcher::new);
if !state.redap_servers.is_empty() {
command_sender.send_ui(UICommand::ExpandBlueprintPanel);
}
creation_context.egui_ctx.on_end_pass(
"remove copied text formatting",
Arc::new(|ctx| {
ctx.output_mut(|o| {
for command in &mut o.commands {
if let egui::output::OutputCommand::CopyText(text) = command {
*text = re_format::remove_number_formatting(text);
}
}
});
}),
);
{
// This is a workaround consuming the space and arrow keys so we can use them as timeline shortcuts.
// Egui's built in behavior is to interact with focus, and we don't want that.
// TODO(emilk/egui#7899): allow consuming events before egui uses them to move keyboard focus.
// TODO(emilk/egui#7659): allow disabling certain egui shortcuts.
let command_sender = command_sender.clone();
creation_context.egui_ctx.on_begin_pass(
"rerun-kb-shortcuts",
Arc::new(move |ctx| {
// egui has already listened for arrow keys before this point,
// so in order for the arrow keys to NOT move the focus, we need to
// undo that focus change here:
let reset_focus_direction = ctx.input_mut(|i| {
i.key_pressed(Key::ArrowLeft) || i.key_pressed(Key::ArrowRight)
});
if reset_focus_direction {
ctx.memory_mut(|mem| {
mem.move_focus(FocusDirection::None);
});
}
// Consumes the used shortcut (including the "space" key):
if let Some(cmd) = UICommand::listen_for_kb_shortcut(ctx) {
command_sender.send_ui(cmd);
}
}),
);
}
Self {
main_thread_token,
build_info,
app_env,
startup_options,
start_time: web_time::Instant::now(),
ram_limit_warner: re_memory::RamLimitWarner::warn_at_fraction_of_max(0.75),
egui_ctx: creation_context.egui_ctx.clone(),
screenshotter,
texture_readback: Default::default(),
#[cfg(target_arch = "wasm32")]
popstate_listener: None,
#[cfg(not(target_arch = "wasm32"))]
profiler: Default::default(),
text_log_rx,
component_ui_registry,
component_fallback_registry,
rx_log: Default::default(),
#[cfg(target_arch = "wasm32")]
open_files_promise: Default::default(),
state,
background_tasks: Default::default(),
store_hub: Some(StoreHub::new(
blueprint_loader(),
&crate::app_blueprint::setup_welcome_screen_blueprint,
)),
notifications: notifications::NotificationUi::new(creation_context.egui_ctx.clone()),
memory_panel: Default::default(),
memory_panel_open: false,
egui_debug_panel_open: false,
latest_latency_interest: None,
frame_time_history: egui::util::History::new(1..100, 0.5),
command_sender,
command_receiver,
cmd_palette: Default::default(),
view_class_registry,
panel_state_overrides_active: true,
panel_state_overrides,
reflection,
event_dispatcher,
connection_registry,
server_latency_trackers: ServerLatencyTrackers::default(),
async_runtime: tokio_runtime,
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn set_profiler(&mut self, profiler: re_tracing::Profiler) {
self.profiler = profiler;
}
pub fn connection_registry(&self) -> &ConnectionRegistryHandle {
&self.connection_registry
}
pub fn set_examples_manifest_url(&mut self, url: String) {
re_log::info!("Using manifest_url={url:?}");
self.state.set_examples_manifest_url(&self.egui_ctx, url);
}
pub fn build_info(&self) -> &re_build_info::BuildInfo {
&self.build_info
}
pub fn startup_options(&self) -> &StartupOptions {
&self.startup_options
}
pub fn app_options(&self) -> &AppOptions {
self.state.app_options()
}
pub fn reflection(&self) -> &re_types_core::reflection::Reflection {
&self.reflection
}
pub fn app_options_mut(&mut self) -> &mut AppOptions {
self.state.app_options_mut()
}
pub fn app_env(&self) -> &crate::AppEnvironment {
&self.app_env
}
/// The active recording [`StoreId`], if any, derived from the current [`Route`].
pub fn active_recording_id(&self) -> Option<&StoreId> {
self.state.active_recording_id()
}
/// Open a content URL in the viewer.
pub fn open_url_or_file(&self, url: &str) {
match ViewerOpenUrl::parse_with_options(
url,
&re_data_source::FromUriOptions {
accept_extensionless_http: true,
..Default::default()
},
) {
Ok(url) => {
url.open(
&self.egui_ctx,
&OpenUrlOptions {
follow: false,
select_redap_source_when_loaded: true,
show_loader: true,
},
&self.command_sender,
);
}
Err(err) => {
if err.to_string().contains(url) {
re_log::error!("{err}");
} else {
re_log::error!(?url, "Failed to open URL: {err}");
}
}
}
}
pub fn is_screenshotting(&self) -> bool {
self.screenshotter.is_screenshotting()
}
#[expect(clippy::needless_pass_by_ref_mut)]
pub fn add_log_receiver(&mut self, rx: LogReceiver) {
re_log::debug!("Adding new log receiver: {}", rx.source());
// Make sure we wake up when a new message is available:
rx.set_waker({
let egui_ctx = self.egui_ctx.clone();
move || {
// Spend a few more milliseconds decoding incoming messages,
// then trigger a repaint (https://github.com/rerun-io/rerun/issues/963):
egui_ctx.request_repaint_after(std::time::Duration::from_millis(10));
}
});
// Add unknown redap servers.
//
// Otherwise we end up in a situation where we have a data from an unknown server,
// which is unnecessary and can get us into a strange ui state.
if let LogSource::RedapGrpcStream { uri, .. } = rx.source() {
self.command_sender
.send_system(SystemCommand::AddRedapServer(uri.origin.clone()));
}
self.rx_log.add(rx);
}
/// Update the active [`re_viewer_context::TimeControl`]. And if the blueprint inspection
/// panel is open, also open that time control.
fn move_time(&mut self) {
if let Some(store_hub) = &self.store_hub
&& let Some(store_id) = self.active_recording_id()
&& let Some(blueprint) = store_hub.active_blueprint_for_app(store_id.application_id())
{
let default_blueprint = store_hub.default_blueprint_for_app(store_id.application_id());
let blueprint_query = self
.state
.get_blueprint_query_for_viewer(blueprint)
.unwrap_or_else(|| {
re_chunk::LatestAtQuery::latest(re_viewer_context::blueprint_timeline())
});
let bp_ctx = AppBlueprintCtx {
command_sender: &self.command_sender,
current_blueprint: blueprint,
default_blueprint,
blueprint_query,
};
let stable_dt = self.egui_ctx.input(|i| i.stable_dt);
if let Some(recording) = store_hub.entity_db(store_id) {
// Are we still connected to the data source for the current store?
let more_data_is_streaming_in =
recording.data_source.as_ref().is_some_and(|store_source| {
self.rx_log
.sources()
.iter()
.any(|s| s.as_ref() == store_source)
});
let time_ctrl = self.state.time_control_mut(recording, &bp_ctx);
// The state diffs are used to trigger callbacks if they are configured.
// If there's no active recording, we should not trigger any callbacks, but since there's an active recording here,
// we want to diff state changes.
let response = time_ctrl.update(
recording,
&re_viewer_context::TimeControlUpdateParams {
stable_dt,
more_data_is_streaming_in,
is_buffering: recording.is_buffering(),
should_diff_state: true,
},
Some(&bp_ctx),
);
if response.needs_repaint == NeedsRepaint::Yes {
self.egui_ctx.request_repaint();
}
handle_time_ctrl_event(recording, self.event_dispatcher.as_ref(), &response);
}
if self.app_options().inspect_blueprint_timeline {
// We ignore most things from the time control response for the blueprint but still
// need to repaint if requested.
let re_viewer_context::TimeControlResponse {
needs_repaint,
playing_change: _,
timeline_change: _,
time_change: _,
} = self.state.blueprint_time_control.update(
bp_ctx.current_blueprint,
&re_viewer_context::TimeControlUpdateParams {
stable_dt,
more_data_is_streaming_in: true,
is_buffering: false,
should_diff_state: false,
},
None::<&AppBlueprintCtx<'_>>,
);
if needs_repaint == NeedsRepaint::Yes {
self.egui_ctx.request_repaint();
}
let undo_state = self
.state
.blueprint_undo_state
.entry(blueprint.store_id().clone())
.or_default();
// Apply changes to the blueprint time to the undo-state:
if self.state.blueprint_time_control.play_state() == PlayState::Following {
undo_state.redo_all();
} else if let Some(time) = self.state.blueprint_time_control.time_int() {
undo_state.set_redo_time(time);
}
}
}
}
pub fn msg_receive_set(&self) -> &LogReceiverSet {
&self.rx_log
}
/// Adds a new view class to the viewer.
pub fn add_view_class<T: ViewClass + Default + 'static>(
&mut self,
) -> Result<(), ViewClassRegistryError> {
self.view_class_registry.add_class::<T>(
&self.reflection,
&self.state.app_options,
&mut self.component_fallback_registry,
)
}
/// Extends an already registered view class with additional systems (visualizers, context systems, fallbacks, etc.).
///
/// **WARNING:** Many parts of the viewer assume that all views & visualizers are registered before the first frame is rendered.
/// Doing so later in the application life cycle may cause unexpected behavior.
pub fn extend_view_class(
&mut self,
view_class: re_sdk_types::ViewClassIdentifier,
register_fn: impl FnOnce(
&mut re_viewer_context::ViewSystemRegistrator<'_>,
) -> Result<(), ViewClassRegistryError>,
) -> Result<(), ViewClassRegistryError> {
self.view_class_registry.extend_class(
view_class,
&self.reflection,
&self.state.app_options,
&mut self.component_fallback_registry,
register_fn,
)
}
fn run_pending_system_commands(&mut self, store_hub: &mut StoreHub, egui_ctx: &egui::Context) {
re_tracing::profile_function!();
while let Some((from_where, cmd)) = self.command_receiver.recv_system() {
self.run_system_command(from_where, cmd, store_hub, egui_ctx);
}
}
fn run_pending_ui_commands(
&mut self,
egui_ctx: &egui::Context,
app_blueprint: &AppBlueprint<'_>,
storage_context: &StorageContext<'_>,
store_context: Option<&ActiveStoreContext<'_>>,
route: &Route,
) {
re_tracing::profile_function!();
while let Some(cmd) = self.command_receiver.recv_ui() {
self.run_ui_command(
egui_ctx,
app_blueprint,
storage_context,
store_context,
route,
cmd,
);
}
}
/// If we're on web and use web history this updates the
/// web address bar and updates history.
///
/// Otherwise this updates the viewer tracked history.
fn update_history(&mut self, store_hub: &StoreHub) {
if !self.startup_options().web_history_enabled() {
self.update_viewer_history(store_hub);
} else {
// We don't want to spam the web history API with changes, because
// otherwise it will start complaining about it being an insecure
// operation.
//
// This is a kind of hacky way to fix that: If there are currently any
// inputs, don't update the web address bar. This works for most cases
// because you need to hold down pointer to aggressively scrub, need to
// hold down key inputs to quickly step through the timeline.
#[cfg(target_arch = "wasm32")]
if !self.egui_ctx.egui_is_using_pointer()
&& self
.egui_ctx
.input(|input| !input.any_touches() && input.keys_down.is_empty())
{
self.update_web_history(store_hub);
}
}
}
/// Updates the viewer tracked history
fn update_viewer_history(&mut self, store_hub: &StoreHub) {
let route = self.state.navigation.current();
let time_ctrl = route
.recording_id()
.and_then(|id| self.state.time_control(id));
let selection = self.state.selection_state.selected_items();
let Ok(url) = ViewerOpenUrl::from_context_expanded(store_hub, route, time_ctrl, selection)
else {
return;
};
self.state.history.update_current_url(url);
}
/// Updates the web address and web history.
#[cfg(target_arch = "wasm32")]
fn update_web_history(&self, store_hub: &StoreHub) {
let route = self.state.navigation.current();
let time_ctrl = route
.recording_id()
.and_then(|id| self.state.time_control(id));
let selection = self.state.selection_state.selected_items();
let Ok(url) = ViewerOpenUrl::from_context_expanded(store_hub, route, time_ctrl, selection)
.map(|mut url| {
// We don't want to update the url while playing, so we use the last paused time.
if let Some(fragment) = url.fragment_mut() {
fragment.when = time_ctrl.and_then(|time_ctrl| {
Some((
*time_ctrl.timeline_name(),
re_log_types::TimeCell {
typ: time_ctrl.time_type()?,
value: time_ctrl.last_paused_time()?.floor().into(),
},
))
});
}
url
})
// History entries expect the url parameter, not the full url, therefore don't pass a base url.
.and_then(|url| url.sharable_url(None))
else {
return;
};
re_log::trace!("Updating navigation bar");
use crate::web_history::{HistoryEntry, HistoryExt as _, history};
use crate::web_tools::JsResultExt as _;
/// Returns the url without the fragment
fn strip_fragment(url: &str) -> &str {
// Split by url code for '#', which is used for fragments.
url.rsplit_once("%23").map_or(url, |(url, _)| url)
}
if let Some(history) = history().ok_or_log_js_error() {
let current_entry = history.current_entry().ok_or_log_js_error().flatten();
let new_entry = HistoryEntry::new(url);
if Some(&new_entry) != current_entry.as_ref() {
// If only the fragment has changed, we replace history instead of pushing it.
if current_entry
.and_then(|entry| {
Some((
entry.to_query_string().ok_or_log_js_error()?,
new_entry.to_query_string().ok_or_log_js_error()?,
))
})
.is_some_and(|(current, new)| strip_fragment(¤t) == strip_fragment(&new))
{
history.replace_entry(new_entry).ok_or_log_js_error();
} else {
history.push_entry(new_entry).ok_or_log_js_error();
}
}
}
}
fn run_system_command(
&mut self,
sent_from: &std::panic::Location<'_>, // Who sent this command? Useful for debugging!
cmd: SystemCommand,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
) {
re_tracing::profile_function!(cmd.debug_name());
match cmd {
SystemCommand::TimeControlCommands {
store_id,
time_commands,
} => {
match store_id.kind() {
StoreKind::Recording => {
store_hub.load_blueprint_and_caches(&store_id, &self.view_class_registry); // Ensure caches and blueprints
let route = Route::LocalRecording {
recording_id: store_id.clone(),
};
let (storage_ctx, store_ctx) = store_hub.read_context(&route); // Materialize the target blueprint on-demand
let target_blueprint = store_ctx.blueprint;
let blueprint_query =
self.state.blueprint_query_for_viewer(target_blueprint);
let blueprint_ctx = AppBlueprintCtx {
command_sender: &self.command_sender,
current_blueprint: target_blueprint,
default_blueprint: storage_ctx
.hub
.default_blueprint_for_app(store_id.application_id()),
blueprint_query,
};
let time_ctrl = self
.state
.time_control_mut(store_ctx.recording, &blueprint_ctx);
let response = time_ctrl.handle_time_commands(
Some(&blueprint_ctx),
store_ctx.recording,
&time_commands,
);
if response.needs_repaint == NeedsRepaint::Yes {
self.egui_ctx.request_repaint();
}
handle_time_ctrl_event(
store_ctx.recording,
self.event_dispatcher.as_ref(),
&response,
);
}
StoreKind::Blueprint => {
if let Some(target_store) = store_hub.store_bundle().get(&store_id) {
let blueprint_ctx: Option<&AppBlueprintCtx<'_>> = None;
let response = self.state.blueprint_time_control.handle_time_commands(
blueprint_ctx,
target_store,
&time_commands,
);
if response.needs_repaint == NeedsRepaint::Yes {
self.egui_ctx.request_repaint();
}
}
}
}
}
SystemCommand::SetUrlFragment { store_id, fragment } => {
// This adds new system commands, which will be handled later in the loop.
self.go_to_dataset_data(store_id, fragment);
}
SystemCommand::CopyViewerUrl(url) => {
if cfg!(target_arch = "wasm32") {
match combine_with_base_url(
self.startup_options.web_viewer_base_url().as_ref(),
[url],
) {
Ok(url) => {
self.copy_text(url);
}
Err(err) => {
re_log::error!("{err}");
}
}
} else {
self.copy_text(url);
}
}
SystemCommand::ActivateApp(app_id) => {
store_hub.load_persisted_blueprints_for_app(&app_id);
if let Some(recording_id) = store_hub.earliest_recording_for_app(&app_id) {
store_hub.load_blueprint_and_caches(&recording_id, &self.view_class_registry);
self.state
.navigation
.replace(Route::LocalRecording { recording_id });
} else {
// TODO(RR-3713): show a blueprint for it anyway
re_log::warn_once!("Can't switch app-id - we have no recording for it");
// If we can't go where we want to go, then go nowhere.
}
}
SystemCommand::CloseApp(app_id) => {
store_hub.close_app(&app_id);
}
SystemCommand::CloseRecordingOrTable(entry) => {
// TODO(#9464): Find a better successor here.
let data_source = match &entry {
RecordingOrTable::Recording { store_id } => {
store_hub.entity_db_entry(store_id).data_source.clone()
}
RecordingOrTable::Table { .. } => None,
};
if let Some(data_source) = data_source {
// Only certain sources should be closed.
#[expect(clippy::match_same_arms)]
let should_close = match &data_source {
// Specific files should stop streaming when closing them.
LogSource::File { .. } => true,
// Specific HTTP streams should stop streaming when closing them.
LogSource::HttpStream { .. } => true,
// Specific GRPC streams should stop streaming when closing them.
// TODO(#10967): We still stream in some data after that.
LogSource::RedapGrpcStream { .. } => true,
// Don't close generic connections (like to an SDK) that may feed in different recordings over time.
LogSource::RrdWebEvent
| LogSource::JsChannel { .. }
| LogSource::Sdk
| LogSource::Stdin
| LogSource::MessageProxy(_) => false,
};
if should_close {
self.rx_log.retain(|r| r.source() != &data_source);
}
}
store_hub.remove(&entry);
}
SystemCommand::CloseAllEntries => {
self.state.navigation.reset();
store_hub.clear_entries();
// Stop receiving into the old recordings.
// This is most important when going back to the example screen by using the "Back"
// button in the browser, and there is still a connection downloading an .rrd.
// That's the case of `LogSource::HttpStream`.
// TODO(emilk): exactly what things get kept and what gets cleared?
self.rx_log.retain(|r| match r.source() {
LogSource::File { .. } | LogSource::HttpStream { .. } => false,
LogSource::JsChannel { .. }
| LogSource::RrdWebEvent
| LogSource::Sdk
| LogSource::RedapGrpcStream { .. }
| LogSource::MessageProxy { .. }
| LogSource::Stdin => true,
});
}
SystemCommand::AddReceiver(rx) => {
re_log::debug!("Received AddReceiver");
self.add_log_receiver(rx);
}
SystemCommand::SetRoute(new_route) => {
if &new_route == self.state.navigation.current() {
return;
}
// Suppress loading screen if we're loading a recording that's already loaded, even if only partially.
if let Route::Loading(source) = &new_route
&& let Some(re_uri::RedapUri::DatasetData(dataset_uri)) = source.redap_uri()
&& store_hub
.store_bundle()
.entity_dbs()
.any(|db| db.store_id() == &dataset_uri.store_id())
{
return;
}
if let Some(recording_id) = new_route.recording_id() {
store_hub.load_blueprint_and_caches(recording_id, &self.view_class_registry);
}
if matches!(new_route, Route::Loading(_)) {
self.state
.selection_state
.set_selection(re_viewer_context::ItemCollection::default());
}
self.state.navigation.replace(new_route);
egui_ctx.request_repaint(); // Make sure we actually see the new mode.
}
SystemCommand::OpenSettings => {
self.state.navigation.replace(Route::Settings {
previous: Box::new(self.state.navigation.current().clone()),
});
#[cfg(feature = "analytics")]
re_analytics::record(|| re_analytics::event::SettingsOpened {});
}
SystemCommand::OpenChunkStoreBrowser {
store_id,
selected_chunk,
} => match self.state.navigation.current() {
Route::ChunkStoreBrowser {
store_id: current_store_id,
previous,
..
} => {
self.state.navigation.replace(Route::ChunkStoreBrowser {
// History/share URLs may carry an explicit store; otherwise keep
// using the current chunk browser store context.
store_id: store_id.or_else(|| current_store_id.clone()),
selected_chunk,
previous: previous.clone(),
});
}
current => {
self.state.navigation.replace(Route::ChunkStoreBrowser {
store_id: store_id.or_else(|| current.recording_id().cloned()),
selected_chunk,
previous: Box::new(current.clone()),
});
}
},
SystemCommand::ResetRoute => {
self.state.navigation.reset();
egui_ctx.request_repaint(); // Make sure we actually see the new mode.
}
SystemCommand::AddRedapServer(origin) => {
if origin == *re_redap_browser::EXAMPLES_ORIGIN {
return;
}
if self.state.redap_servers.has_server(&origin) {
return;
}
self.state.redap_servers.add_server(origin.clone());
if self.state.navigation.current().recording_id().is_none() {
self.state.navigation.replace(Route::RedapServer(origin));
}
self.command_sender.send_ui(UICommand::ExpandBlueprintPanel);
}
SystemCommand::EditRedapServerModal(command) => {
self.state.redap_servers.open_edit_server_modal(command);
}
SystemCommand::LoadDataSource(data_source) => {
self.load_data_source(store_hub, egui_ctx, &data_source);
}
SystemCommand::ResetViewer => self.reset_viewer(store_hub, egui_ctx),
SystemCommand::ClearActiveBlueprintAndEnableHeuristics => {
re_log::debug!("Clear and generate new blueprint");
store_hub.clear_active_blueprint_and_generate(self.state.navigation.current());
egui_ctx.request_repaint(); // Many changes take a frame delay to show up.
}
SystemCommand::ClearActiveBlueprint => {
// By clearing the blueprint the default blueprint will be restored
// at the beginning of the next frame.
re_log::debug!("Reset blueprint to default");
store_hub.clear_active_blueprint(self.state.navigation.current());
egui_ctx.request_repaint(); // Many changes take a frame delay to show up.
}
SystemCommand::AppendToStore(store_id, chunks) => {
re_log::trace!(
"{}:{} Update {} entities: {}",
sent_from.file(),
sent_from.line(),
store_id.kind(),
chunks.iter().map(|c| c.entity_path()).join(", ")
);
let db = store_hub.entity_db_entry(&store_id);
// No need to clear undo buffer if we're just appending static data.
//
// It would be nice to be able to undo edits to a recording, but
// we haven't implemented that yet.
if store_id.is_blueprint() && chunks.iter().any(|c| !c.is_static()) {
self.state
.blueprint_undo_state
.entry(store_id.clone())
.or_default()
.clear_redo_buffer(db);
if self.app_options().inspect_blueprint_timeline {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id,
time_commands: vec![TimeControlCommand::SetPlayState(
PlayState::Following,
)],
});
}
}
for chunk in chunks {
match db.add_chunk(&Arc::new(chunk)) {
Ok(_store_events) => {}
Err(err) => {
re_log::warn_once!("Failed to append chunk: {err}");
}
}
}
}
SystemCommand::UndoBlueprint { blueprint_id } => {
let inspect_blueprint_timeline = self.app_options().inspect_blueprint_timeline;
let blueprint_db = store_hub.entity_db_entry(&blueprint_id);
let undo_state = self
.state
.blueprint_undo_state
.entry(blueprint_id.clone())
.or_default();
undo_state.undo(blueprint_db);
// Update blueprint inspector timeline.
if inspect_blueprint_timeline {
if let Some(redo_time) = undo_state.redo_time() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: blueprint_id,
time_commands: vec![
TimeControlCommand::SetPlayState(PlayState::Paused),
TimeControlCommand::SetTime(redo_time.into()),
],
});
} else {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: blueprint_id,
time_commands: vec![TimeControlCommand::SetPlayState(
PlayState::Following,
)],
});
}
}
}
SystemCommand::RedoBlueprint { blueprint_id } => {
let inspect_blueprint_timeline = self.app_options().inspect_blueprint_timeline;
let undo_state = self
.state
.blueprint_undo_state
.entry(blueprint_id.clone())
.or_default();
undo_state.redo();
// Update blueprint inspector timeline.
if inspect_blueprint_timeline {
if let Some(redo_time) = undo_state.redo_time() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: blueprint_id,
time_commands: vec![
TimeControlCommand::SetPlayState(PlayState::Paused),
TimeControlCommand::SetTime(redo_time.into()),
],
});
} else {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: blueprint_id,
time_commands: vec![TimeControlCommand::SetPlayState(
PlayState::Following,
)],
});
}
}
}
SystemCommand::DropEntity(blueprint_id, entity_path) => {
let blueprint_db = store_hub.entity_db_entry(&blueprint_id);
blueprint_db.drop_entity_path_recursive(&entity_path);
}
#[cfg(debug_assertions)]
SystemCommand::EnableInspectBlueprintTimeline(show) => {
self.app_options_mut().inspect_blueprint_timeline = show;
}
SystemCommand::SetSelection(set) => {
if let Some(item) = set.selection.single_item() {
// If the selected item has its own page, switch to it.
if let Some(route) = Route::from_item(item) {
if let Route::LocalRecording { recording_id } = &route {
store_hub
.load_blueprint_and_caches(recording_id, &self.view_class_registry);
}
self.state.navigation.replace(route);
}
}
self.state.selection_state.set_selection(set);
egui_ctx.request_repaint(); // Make sure we actually see the new selection.
}
SystemCommand::SetFocus(item) => {
self.state.focused_item = Some(item);
}
SystemCommand::ShowNotification(notification) => {
self.notifications.add(notification);
}
SystemCommand::ReadbackAndSaveTexture(texture_readback_id) => {
self.texture_readback.push(texture_readback_id);
}
#[cfg(not(target_arch = "wasm32"))]
SystemCommand::FileSaver(file_saver) => {
if let Err(err) = self.background_tasks.spawn_file_saver(file_saver) {
re_log::error!("Failed to save file: {err}");
}
}
SystemCommand::OnAuthChanged(auth) => {
self.state.auth_state = auth;
}
SystemCommand::SetAuthCredentials {
access_token,
email,
} => {
let credentials =
match re_auth::oauth::Credentials::try_new(access_token, None, email) {
Ok(credentials) => credentials,
Err(err) => {
re_log::error!("Failed to create credentials: {err}");
return;
}
};
if let Err(err) = credentials.ensure_stored() {
re_log::error!("Failed to store credentials: {err}");
}
}
SystemCommand::Logout => {
let signed_out_url = self
.startup_options
.login
.as_ref()
.map(|l| l.signed_out_url.as_str());
match re_auth::oauth::clear_credentials(signed_out_url) {
Ok(Some(outcome)) => {
// Open the WorkOS logout URL to also end the browser session.
// This opens in a new tab/window so the viewer state is preserved.
// WorkOS clears its session cookies and redirects to /signed-out.
egui_ctx.open_url(egui::output::OpenUrl {
url: outcome.logout_url,
new_tab: true,
});
}
Ok(None) => {
re_log::debug!("No session to logout from");
}
Err(err) => {
re_log::error!("Failed to logout: {err}");
}
}
let logged_out_origins = self.state.redap_servers.logout();
// Close any open recordings that came from the logged-out servers.
store_hub.retain_recordings(|db| {
let Some(data_source) = &db.data_source else {
return true;
};
match data_source {
LogSource::RedapGrpcStream { uri, .. } => {
!logged_out_origins.contains(&uri.origin)
}
_ => true,
}
});
// Also stop receiving data from those servers.
self.rx_log.retain(|r| match r.source() {
LogSource::RedapGrpcStream { uri, .. } => {
!logged_out_origins.contains(&uri.origin)
}
_ => true,
});
}
SystemCommand::SaveScreenshot { target, view_id } => {
if let Some(view_id) = view_id {
// Screenshot a specific view
if let Some(view_info) = self.egui_ctx.memory_mut(|mem| {
mem.caches
.cache::<re_viewer_context::ViewRectPublisher>()
.get(&view_id)
.cloned()
}) {
let re_viewer_context::PublishedViewInfo { name, rect } = view_info;
let rect = rect.shrink(2.5); // Hacky: Shrink so we don't accidentally include the border of the view.
if !rect.is_positive() {
re_log::warn!("View too small for a screenshot");
return;
}
self.egui_ctx
.send_viewport_cmd(egui::ViewportCommand::Screenshot(
egui::UserData::new(re_viewer_context::ScreenshotInfo {
ui_rect: Some(rect),
pixels_per_point: self.egui_ctx.pixels_per_point(),
name,
target,
}),
));
} else {
re_log::warn!("View {view_id} not found for screenshot");
}
} else {
// Screenshot the entire viewer
self.egui_ctx
.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(
re_viewer_context::ScreenshotInfo {
ui_rect: None,
pixels_per_point: self.egui_ctx.pixels_per_point(),
name: "screenshot".to_owned(),
target,
},
)));
}
// Screenshot commands may be triggered from receiving messages over the network, so we may not actually do any painting right now.
// Make sure we do at least once, so the screenshot gets saved out.
self.egui_ctx.request_repaint();
// TODO(#12481): Depending on the platform we a request repaint alone isn't enough to wake up the viewer.
// For now we do a focus switch but this isn't ideal since it breaks the flow of programmatic screenshot taking.
self.egui_ctx
.send_viewport_cmd(egui::ViewportCommand::Focus);
}
}
}
pub fn auth_error_handler(sender: CommandSender) -> AuthErrorHandler {
Arc::new(move |url, _err| {
sender.send_system(SystemCommand::EditRedapServerModal(
EditRedapServerModalCommand {
origin: url.origin.clone(),
open_on_success: Some(url.to_string()),
title: Some("Authenticate to see this recording".to_owned()),
},
));
})
}
/// Loads a data source into the viewer.
///
/// Tries to detect whether the datasource is already present (either still streaming in or already loaded),
/// and if so, will not load the data again.
/// Instead, it will only perform any kind of selection/mode-switching operations associated with loading the given data source.
///
/// Note that we *do not* change the route here _unconditionally_.
/// For instance if the datasource is a blueprint for a dataset that may be loaded later,
/// we don't want to switch out to it while the user browses a server.
fn load_data_source(
&mut self,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
data_source: &LogDataSource,
) {
re_tracing::profile_function!();
// Check if we've already loaded this data source and should just switch to it.
//
// Go through all sources that are still loading and those that are already in the store_hub.
// (if we look only at the one from the store_hub, we might miss those that haven't hit it yet)
let active_sources = self.rx_log.sources();
// Only consider recordings for dedup, not blueprints.
// Blueprints loaded alongside a recording share the same `data_source`,
// but they should not prevent re-opening a closed recording.
let store_sources = store_hub
.store_bundle()
.recordings()
.filter_map(|db| db.data_source.as_ref());
let mut all_sources = store_sources.chain(active_sources.iter().map(|s| s.as_ref()));
match data_source {
LogDataSource::HttpUrl { url, follow } => {
let new_source = LogSource::HttpStream {
url: url.to_string(),
follow: *follow,
};
if all_sources.any(|source| source.is_same_ignoring_uri_fragments(&new_source)) {
if let Some(entity_db) = store_hub.find_recording_store_by_source(&new_source) {
if *follow {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: entity_db.store_id().clone(),
time_commands: vec![TimeControlCommand::SetPlayState(
PlayState::Following,
)],
});
}
let store_id = entity_db.store_id().clone();
debug_assert!(store_id.is_recording()); // `find_recording_store_by_source` should have filtered for recordings rather than blueprints.
drop(all_sources);
self.make_store_active_and_highlight(store_hub, egui_ctx, &store_id);
}
return;
}
}
#[cfg(not(target_arch = "wasm32"))]
LogDataSource::FilePath { path, follow, .. } => {
let new_source = LogSource::File {
path: path.clone(),
follow: *follow,
};
if all_sources.any(|source| source.is_same_ignoring_uri_fragments(&new_source)) {
drop(all_sources);
self.try_make_recording_from_source_active(egui_ctx, store_hub, &new_source);
return;
}
}
LogDataSource::FileContents(_file_source, _file_contents) => {
// For raw file contents we currently can't determine whether we're already receiving them.
}
#[cfg(not(target_arch = "wasm32"))]
LogDataSource::Stdin => {
let new_source = LogSource::Stdin;
if all_sources.any(|source| source.is_same_ignoring_uri_fragments(&new_source)) {
drop(all_sources);
self.try_make_recording_from_source_active(egui_ctx, store_hub, &new_source);
return;
}
}
LogDataSource::RedapDatasetSegment {
uri,
select_when_loaded,
} => {
let new_source = LogSource::RedapGrpcStream {
uri: uri.clone(),
select_when_loaded: *select_when_loaded,
};
if all_sources.any(|source| source.is_same_ignoring_uri_fragments(&new_source)) {
// We're already receiving from the exact same data source!
// But we still should select if requested according to the fragments if any.
if *select_when_loaded {
// First make the recording itself active.
// `go_to_dataset_data` may override the selection again, but this is important regardless,
// since `go_to_dataset_data` does not change the active recording.
drop(all_sources);
self.make_store_active_and_highlight(store_hub, egui_ctx, &uri.store_id());
}
// Note that applying the fragment changes the per-recording settings like the active time cursor.
// Therefore, we apply it even when `select_when_loaded` is false.
self.go_to_dataset_data(uri.store_id(), uri.fragment.clone());
return;
}
}
LogDataSource::RedapProxy(uri) => {
let new_source = LogSource::MessageProxy(uri.clone());
if all_sources.any(|source| source.is_same_ignoring_uri_fragments(&new_source)) {
drop(all_sources);
self.try_make_recording_from_source_active(egui_ctx, store_hub, &new_source);
return;
}
}
}
let sender = self.command_sender.clone();
let stream = data_source
.clone()
.stream(Self::auth_error_handler(sender), &self.connection_registry);
#[cfg(feature = "analytics")]
if let Some(analytics) = re_analytics::Analytics::global_or_init() {
let data_source_analytics = data_source.analytics();
analytics.record(re_analytics::event::LoadDataSource {
source_type: data_source_analytics.source_type,
file_extension: data_source_analytics.file_extension,
file_source: data_source_analytics.file_source,
started_successfully: stream.is_ok(),
});
}
match stream {
Ok(rx) => self.add_log_receiver(rx),
Err(err) => {
re_log::error!("Failed to open data source: {}", re_error::format(err));
}
}
}
/// Applies a fragment.
///
/// Does *not* switch the active recording.
fn go_to_dataset_data(&self, store_id: StoreId, fragment: re_uri::Fragment) {
let re_uri::Fragment {
selection,
when,
time_selection,
} = fragment;
if let Some(selection) = selection {
let re_log_types::DataPath {
entity_path,
instance,
component,
} = selection;
let item = if let Some(component) = component {
Item::from(re_log_types::ComponentPath::new(entity_path, component))
} else if let Some(instance) = instance {
Item::from(InstancePath::instance(entity_path, instance))
} else {
Item::from(entity_path)
};
self.command_sender
.send_system(SystemCommand::set_selection(item.clone()));
}
let mut time_commands = Vec::new();
if let Some(time_selection) = time_selection {
time_commands.push(TimeControlCommand::SetActiveTimeline(
*time_selection.timeline.name(),
));
time_commands.push(TimeControlCommand::SetTimeSelection(time_selection.range));
time_commands.push(TimeControlCommand::SetLoopMode(LoopMode::Selection));
}
if let Some((timeline, timecell)) = when {
time_commands.push(TimeControlCommand::SetActiveTimeline(timeline));
time_commands.push(TimeControlCommand::SetPlayState(PlayState::Paused));
time_commands.push(TimeControlCommand::SetTime(timecell.value.into()));
}
if !time_commands.is_empty() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id,
time_commands,
});
}
}
fn run_ui_command(
&mut self,
egui_ctx: &egui::Context,
app_blueprint: &AppBlueprint<'_>,
storage_context: &StorageContext<'_>,
store_context: Option<&ActiveStoreContext<'_>>,
route: &Route,
cmd: UICommand,
) {
let mut force_store_info = false;
let active_store_id = store_context
.map(|ctx| ctx.recording_store_id().clone())
// Don't redirect data to the welcome screen.
.filter(|store_id| store_id.application_id() != StoreHub::welcome_screen_app_id())
.unwrap_or_else(|| {
// If we don't have any application ID to recommend (which means we are on the welcome screen),
// then just generate a new one using a UUID.
let application_id = ApplicationId::random();
// NOTE: We don't override blueprints' store IDs anyhow, so it is sound to assume that
// this can only be a recording.
let recording_id = RecordingId::random();
// We're creating a recording just-in-time, directly from the viewer.
// We need those store infos or the data will just be silently ignored.
force_store_info = true;
StoreId::recording(application_id, recording_id)
});
match cmd {
UICommand::SaveRecording => {
#[cfg(target_arch = "wasm32")] // Web
{
if let Err(err) = save_active_recording(self, store_context, None) {
re_log::error!("Failed to save recording: {err}");
}
}
#[cfg(not(target_arch = "wasm32"))] // Native
{
let mut selected_stores = vec![];
for item in self.state.selection_state.selected_items().iter_items() {
match item {
Item::AppId(selected_app_id) => {
for recording in storage_context.bundle.recordings() {
if recording.application_id() == selected_app_id {
selected_stores.push(recording.store_id().clone());
}
}
}
Item::StoreId(store_id) => {
selected_stores.push(store_id.clone());
}
_ => {}
}
}
let selected_stores = selected_stores
.iter()
.filter_map(|store_id| storage_context.bundle.get(store_id))
.collect_vec();
if selected_stores.is_empty() {
if let Err(err) = save_active_recording(self, store_context, None) {
re_log::error!("Failed to save recording: {err}");
}
} else if selected_stores.len() == 1 {
// Common case: saving a single recording.
// In this case we want the user to be able to pick a file name (not just a folder):
if let Err(err) = save_recording(self, selected_stores[0], None) {
re_log::error!("Failed to save recording: {err}");
}
} else {
// Save all selected recordings to a folder:
if let Some(folder) = rfd::FileDialog::new()
.set_title("Save recordings to folder")
.pick_folder()
{
self.save_many_recordings(&selected_stores, &folder);
} else {
re_log::info!("No folder selected - recordings not saved.");
}
}
}
}
UICommand::SaveRecordingSelection => {
if let Err(err) = save_active_recording(
self,
store_context,
self.state.loop_selection(store_context),
) {
re_log::error!("Failed to save recording: {err}");
}
}
UICommand::SaveBlueprint => {
if let Err(err) = save_blueprint(self, store_context) {
re_log::error!("Failed to save blueprint: {err}");
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::Open => {
for file_path in open_file_dialog_native(self.main_thread_token) {
self.command_sender
.send_system(SystemCommand::LoadDataSource(LogDataSource::FilePath {
file_source: FileSource::FileDialog {
recommended_store_id: None,
force_store_info,
},
path: file_path,
follow: false,
}));
}
}
#[cfg(target_arch = "wasm32")]
UICommand::Open => {
let egui_ctx = egui_ctx.clone();
let promise = poll_promise::Promise::spawn_local(async move {
let file = async_open_rrd_dialog().await;
egui_ctx.request_repaint(); // Wake ui thread
file
});
self.open_files_promise = Some(PendingFilePromise {
recommended_store_id: None,
force_store_info,
promise,
});
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::Import => {
for file_path in open_file_dialog_native(self.main_thread_token) {
self.command_sender
.send_system(SystemCommand::LoadDataSource(LogDataSource::FilePath {
file_source: FileSource::FileDialog {
recommended_store_id: Some(active_store_id.clone()),
force_store_info,
},
path: file_path,
follow: false,
}));
}
}
#[cfg(target_arch = "wasm32")]
UICommand::Import => {
let egui_ctx = egui_ctx.clone();
let promise = poll_promise::Promise::spawn_local(async move {
let file = async_open_rrd_dialog().await;
egui_ctx.request_repaint(); // Wake ui thread
file
});
self.open_files_promise = Some(PendingFilePromise {
recommended_store_id: Some(active_store_id.clone()),
force_store_info,
promise,
});
}
UICommand::OpenUrl => {
self.state.open_url_modal.open();
}
UICommand::CloseCurrentRecording => {
let cur_rec = store_context.map(|ctx| ctx.recording.store_id());
if let Some(cur_rec) = cur_rec {
self.command_sender
.send_system(SystemCommand::CloseRecordingOrTable(cur_rec.clone().into()));
}
}
UICommand::CloseAllEntries => {
self.command_sender
.send_system(SystemCommand::CloseAllEntries);
}
UICommand::NextRecording => {
self.state
.recording_panel
.send_command(re_recording_panel::RecordingPanelCommand::SelectNextRecording);
}
UICommand::PreviousRecording => {
self.state.recording_panel.send_command(
re_recording_panel::RecordingPanelCommand::SelectPreviousRecording,
);
}
UICommand::NavigateBack => {
if let Some(url) = self.state.history.go_back() {
url.clone().open(
egui_ctx,
&OpenUrlOptions {
follow: true,
select_redap_source_when_loaded: true,
show_loader: true,
},
&self.command_sender,
);
}
}
UICommand::NavigateForward => {
if let Some(url) = self.state.history.go_forward() {
url.clone().open(
egui_ctx,
&OpenUrlOptions {
follow: true,
select_redap_source_when_loaded: true,
show_loader: true,
},
&self.command_sender,
);
}
}
UICommand::Undo => {
if let Some(store_context) = store_context {
let blueprint_id = store_context.blueprint.store_id().clone();
self.command_sender
.send_system(SystemCommand::UndoBlueprint { blueprint_id });
}
}
UICommand::Redo => {
if let Some(store_context) = store_context {
let blueprint_id = store_context.blueprint.store_id().clone();
self.command_sender
.send_system(SystemCommand::RedoBlueprint { blueprint_id });
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::Quit => {
egui_ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
UICommand::OpenWebHelp => {
egui_ctx.open_url(egui::output::OpenUrl {
url: "https://www.rerun.io/docs/getting-started/navigating-the-viewer"
.to_owned(),
new_tab: true,
});
}
UICommand::OpenRerunDiscord => {
egui_ctx.open_url(egui::output::OpenUrl {
url: "https://discord.gg/PXtCgFBSmH".to_owned(),
new_tab: true,
});
}
UICommand::ResetViewer => self.command_sender.send_system(SystemCommand::ResetViewer),
UICommand::ClearActiveBlueprint => {
self.command_sender
.send_system(SystemCommand::ClearActiveBlueprint);
}
UICommand::ClearActiveBlueprintAndEnableHeuristics => {
self.command_sender
.send_system(SystemCommand::ClearActiveBlueprintAndEnableHeuristics);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::OpenProfiler => {
self.profiler.start();
}
UICommand::ToggleMemoryPanel => {
self.memory_panel_open ^= true;
}
UICommand::TogglePanelStateOverrides => {
self.panel_state_overrides_active ^= true;
}
UICommand::ToggleTopPanel => {
app_blueprint.toggle_top_panel(&self.command_sender);
}
UICommand::ToggleBlueprintPanel => {
app_blueprint.toggle_blueprint_panel(&self.command_sender);
}
UICommand::ExpandBlueprintPanel => {
if !app_blueprint.blueprint_panel_state().is_expanded() {
app_blueprint.toggle_blueprint_panel(&self.command_sender);
}
}
UICommand::ToggleSelectionPanel => {
app_blueprint.toggle_selection_panel(&self.command_sender);
}
UICommand::ExpandSelectionPanel => {
if !app_blueprint.selection_panel_state().is_expanded() {
app_blueprint.toggle_selection_panel(&self.command_sender);
}
}
UICommand::ToggleTimePanel => app_blueprint.toggle_time_panel(&self.command_sender),
UICommand::ToggleChunkStoreBrowser => match self.state.navigation.current() {
Route::ChunkStoreBrowser { previous, .. } => {
self.state.navigation.replace((**previous).clone());
}
current => {
self.state.navigation.replace(Route::ChunkStoreBrowser {
store_id: current.recording_id().cloned(),
selected_chunk: None,
previous: Box::new(current.clone()),
});
}
},
#[cfg(debug_assertions)]
UICommand::ToggleBlueprintInspectionPanel => {
self.app_options_mut().inspect_blueprint_timeline ^= true;
}
#[cfg(debug_assertions)]
UICommand::ToggleEguiDebugPanel => {
self.egui_debug_panel_open ^= true;
}
UICommand::ToggleFullscreen => {
self.toggle_fullscreen();
}
UICommand::Settings => {
self.command_sender.send_system(SystemCommand::OpenSettings);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomIn => {
let mut zoom_factor = egui_ctx.zoom_factor();
zoom_factor += 0.1;
zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR);
zoom_factor = (zoom_factor * 10.).round() / 10.;
egui_ctx.set_zoom_factor(zoom_factor);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomOut => {
let mut zoom_factor = egui_ctx.zoom_factor();
zoom_factor -= 0.1;
zoom_factor = zoom_factor.clamp(MIN_ZOOM_FACTOR, MAX_ZOOM_FACTOR);
zoom_factor = (zoom_factor * 10.).round() / 10.;
egui_ctx.set_zoom_factor(zoom_factor);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomReset => {
egui_ctx.set_zoom_factor(1.0);
}
UICommand::ToggleCommandPalette => {
self.cmd_palette.toggle();
}
UICommand::PlaybackTogglePlayPause => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::TogglePlayPause],
});
}
}
UICommand::PlaybackFollow => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::SetPlayState(
PlayState::Following,
)],
});
}
}
UICommand::PlaybackStepBack => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::StepTimeBack],
});
}
}
UICommand::PlaybackStepForward => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::StepTimeForward],
});
}
}
UICommand::PlaybackBack => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::Move {
direction: MoveDirection::Back,
speed: MoveSpeed::Normal,
}],
});
}
}
UICommand::PlaybackForward => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::Move {
direction: MoveDirection::Forward,
speed: MoveSpeed::Normal,
}],
});
}
}
UICommand::PlaybackBackFast => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::Move {
direction: MoveDirection::Back,
speed: MoveSpeed::Fast,
}],
});
}
}
UICommand::PlaybackForwardFast => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::Move {
direction: MoveDirection::Forward,
speed: MoveSpeed::Fast,
}],
});
}
}
UICommand::PlaybackBeginning => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::MoveBeginning],
});
}
}
UICommand::PlaybackEnd => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::MoveEnd],
});
}
}
UICommand::PlaybackRestart => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::Restart],
});
}
}
UICommand::PlaybackSpeed(speed) => {
if let Some(store_id) = route.recording_id() {
self.command_sender
.send_system(SystemCommand::TimeControlCommands {
store_id: store_id.clone(),
time_commands: vec![TimeControlCommand::SetSpeed(speed.0.0)],
});
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ScreenshotWholeApp => {
self.screenshotter.request_screenshot(egui_ctx);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::PrintChunkStore => {
if let Some(ctx) = store_context {
let text = format!("{}", ctx.recording.storage_engine().store());
egui_ctx.copy_text(text.clone());
println!("{text}");
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::PrintBlueprintStore => {
if let Some(ctx) = store_context {
let text = format!("{}", ctx.blueprint.storage_engine().store());
egui_ctx.copy_text(text.clone());
println!("{text}");
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::PrintPrimaryCache => {
if let Some(ctx) = store_context {
let text = format!("{:?}", ctx.recording.storage_engine().cache());
egui_ctx.copy_text(text.clone());
println!("{text}");
}
}
#[cfg(debug_assertions)]
UICommand::ResetEguiMemory => {
egui_ctx.memory_mut(|mem| *mem = Default::default());
// re-apply style, which is lost when resetting memory
re_ui::apply_style_and_install_loaders(egui_ctx);
}
UICommand::Share => {
let selection = self.state.selection_state.selected_items();
let rec_cfg = route
.recording_id()
.and_then(|id| self.state.time_controls.get(id));
if let Err(err) =
self.state
.share_modal
.open(storage_context.hub, route, rec_cfg, selection)
{
re_log::error!("Cannot share link to current screen: {err}");
}
}
UICommand::CopyDirectLink => {
match ViewerOpenUrl::from_route(storage_context.hub, route) {
Ok(url) => self.run_copy_link_command(&url),
Err(err) => re_log::error!("{err}"),
}
}
UICommand::CopyTimeSelectionLink => {
match ViewerOpenUrl::from_route(storage_context.hub, route) {
Ok(mut url) => {
if let Some(fragment) = url.fragment_mut() {
let time_ctrl = route
.recording_id()
.and_then(|id| self.state.time_control(id));
if let Some(time_ctrl) = &time_ctrl
&& let Some(time_selection) = time_ctrl.time_selection()
&& let Some(timeline) = time_ctrl.timeline()
{
fragment.time_selection = Some(re_uri::TimeSelection {
timeline: *timeline,
range: time_selection.to_int(),
});
} else {
re_log::warn!("No timeline selection to copy");
}
} else {
re_log::warn!(
"The current recording doesn't support sharing a time range"
);
}
self.run_copy_link_command(&url);
}
Err(err) => re_log::error!("{err}"),
}
}
#[cfg(target_arch = "wasm32")]
UICommand::RestartWithWebGl => {
if crate::web_tools::set_url_parameter_and_refresh("renderer", "webgl").is_err() {
re_log::error!("Failed to set URL parameter `renderer=webgl` & refresh page.");
}
}
#[cfg(target_arch = "wasm32")]
UICommand::RestartWithWebGpu => {
if crate::web_tools::set_url_parameter_and_refresh("renderer", "webgpu").is_err() {
re_log::error!("Failed to set URL parameter `renderer=webgpu` & refresh page.");
}
}
UICommand::CopyEntityHierarchy => {
self.copy_entity_hierarchy_to_clipboard(egui_ctx, store_context);
}
UICommand::AddRedapServer => {
self.state.redap_servers.open_add_server_modal();
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn save_many_recordings(&mut self, stores: &[&EntityDb], folder: &std::path::Path) {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use re_log::ResultExt as _;
use tap::Pipe as _;
re_tracing::profile_function!();
let num_stores = stores.len();
let any_error = Arc::new(AtomicBool::new(false));
let num_remaining = Arc::new(AtomicUsize::new(stores.len()));
re_log::info!("Saving {num_stores} recordings to {}…", folder.display());
for store in stores {
let messages = store.to_messages(None).collect_vec();
let file_name = if let Some(rec_name) = store
.recording_info_property::<re_sdk_types::components::Name>(
re_sdk_types::archetypes::RecordingInfo::descriptor_name().component,
) {
rec_name.to_string()
} else {
format!("{}-{}", store.application_id(), store.recording_id())
}
.pipe(|name| sanitize_file_name(&name))
.pipe(|stem| format!("{stem}.rrd"));
let file_path = folder.join(file_name.clone());
let any_error = any_error.clone();
let num_remaining = num_remaining.clone();
let folder = folder.display().to_string();
self.background_tasks
.spawn_threaded_promise(file_name, move || {
let res = crate::saving::encode_to_file(
re_build_info::CrateVersion::LOCAL,
&file_path,
messages.into_iter(),
);
if res.is_err() {
any_error.store(true, Ordering::Relaxed);
}
let num_remaining = num_remaining.fetch_sub(1, Ordering::Relaxed) - 1;
if num_remaining == 0 {
if any_error.load(Ordering::Relaxed) {
re_log::error!("Some recordings failed to save.");
} else {
re_log::info!("{num_stores} recordings successfully saved to {folder}");
}
}
res
})
.ok_or_log_error_once();
}
}
fn run_copy_link_command(&mut self, content_url: &ViewerOpenUrl) {
let base_url = self.startup_options.web_viewer_base_url();
match content_url.sharable_url(base_url.as_ref()) {
Ok(url) => {
self.copy_text(url);
}
Err(err) => {
re_log::error!("{err}");
}
}
}
/// Copies text to the clipboard, and gives a notification about it.
fn copy_text(&mut self, url: String) {
self.notifications
.success(format!("Copied {url:?} to clipboard"));
self.egui_ctx.copy_text(url);
}
fn copy_entity_hierarchy_to_clipboard(
&mut self,
egui_ctx: &egui::Context,
store_context: Option<&ActiveStoreContext<'_>>,
) {
let Some(entity_db) = store_context.as_ref().map(|ctx| ctx.recording) else {
re_log::warn!("Could not copy entity hierarchy: No active recording");
return;
};
let mut hierarchy_text = String::new();
// Add application ID and recording ID header
hierarchy_text.push_str(&format!(
"Application ID: {}\nRecording ID: {}\n\n",
entity_db.application_id(),
entity_db.recording_id()
));
hierarchy_text.push_str(&entity_db.format_with_components());
if hierarchy_text.is_empty() {
hierarchy_text = "(no entities)".to_owned();
}
egui_ctx.copy_text(hierarchy_text.clone());
self.notifications
.success("Copied entity hierarchy with schema to clipboard".to_owned());
}
fn memory_panel_ui(
&mut self,
ui: &mut egui::Ui,
gpu_resource_stats: &WgpuResourcePoolStatistics,
mem_usage_tree: Option<NamedMemUsageTree>,
store_stats: Option<&StoreHubStats>,
) {
let frame = egui::Frame {
fill: ui.visuals().panel_fill,
..ui.tokens().bottom_panel_frame()
};
egui::Panel::bottom("memory_panel")
.default_size(300.0)
.resizable(true)
.frame(frame)
.show_animated_inside(ui, self.memory_panel_open, |ui| {
self.memory_panel.ui(
ui,
&self.startup_options.memory_limit,
mem_usage_tree,
gpu_resource_stats,
store_stats,
);
});
}
fn egui_debug_panel_ui(&self, ui: &mut egui::Ui) {
let egui_ctx = ui.ctx().clone();
egui::Panel::left("style_panel")
.default_size(300.0)
.resizable(true)
.frame(ui.tokens().top_panel_frame())
.show_animated_inside(ui, self.egui_debug_panel_open, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
if ui
.button("request_discard")
.on_hover_text("Request a second layout pass. Just for testing.")
.clicked()
{
ui.request_discard("testing");
}
egui::CollapsingHeader::new("egui settings")
.default_open(false)
.show(ui, |ui| {
egui_ctx.settings_ui(ui);
});
egui::CollapsingHeader::new("egui inspection")
.default_open(false)
.show(ui, |ui| {
egui_ctx.inspection_ui(ui);
});
});
});
}
/// Top-level ui function.
///
/// Shows the viewer ui.
#[expect(clippy::too_many_arguments)]
fn ui_impl(
&mut self,
ui: &mut egui::Ui,
frame: &eframe::Frame,
app_blueprint: &AppBlueprint<'_>,
gpu_resource_stats: &WgpuResourcePoolStatistics,
store_context: &ActiveStoreContext<'_>,
storage_context: &StorageContext<'_>,
mem_usage_tree: Option<NamedMemUsageTree>,
store_stats: Option<&StoreHubStats>,
) {
let mut main_panel_frame = egui::Frame::default();
if re_ui::CUSTOM_WINDOW_DECORATIONS {
// Add some margin so that we can later paint an outline around it all.
main_panel_frame.inner_margin = 1.0.into();
}
egui::CentralPanel::default()
.frame(main_panel_frame)
.show_inside(ui, |ui| {
paint_background_fill(ui);
crate::ui::mobile_warning_ui(ui);
crate::ui::top_panel(
frame,
self,
app_blueprint,
Some(store_context),
storage_context.hub,
gpu_resource_stats,
ui,
);
self.memory_panel_ui(ui, gpu_resource_stats, mem_usage_tree, store_stats);
self.egui_debug_panel_ui(ui);
let egui_renderer = &mut frame
.wgpu_render_state()
.expect("Failed to get frame render state")
.renderer
.write();
if let Some(render_ctx) = egui_renderer
.callback_resources
.get_mut::<re_renderer::RenderContext>()
{
render_ctx.begin_frame(); // This may actually be called multiple times per egui frame, if we have a multi-pass layout frame.
// In some (rare) circumstances we run two egui passes in a single frame.
// This happens on call to `egui::Context::request_discard`.
let is_start_of_new_frame = ui.current_pass_index() == 0;
if is_start_of_new_frame {
self.state.redap_servers.on_frame_start(
&self.connection_registry,
&self.async_runtime,
&self.egui_ctx,
self.startup_options.login_enabled(),
);
}
let mut startup_options = self.startup_options.clone();
self.texture_readback.poll_and_save_texture_readbacks(
render_ctx,
ui,
&self.command_sender,
);
self.state.show(
&self.app_env,
&mut startup_options,
app_blueprint,
ui,
render_ctx,
store_context,
storage_context,
&self.reflection,
&self.component_ui_registry,
&self.component_fallback_registry,
&self.view_class_registry,
&self.rx_log,
&self.command_sender,
&WelcomeScreenState {
hide_examples: self.startup_options.hide_welcome_screen,
opacity: self.welcome_screen_opacity(ui),
},
self.event_dispatcher.as_ref(),
&self.connection_registry,
&self.async_runtime,
);
self.startup_options = startup_options;
render_ctx.before_submit();
self.show_text_logs_as_notifications();
}
});
if self.app_options().show_notification_toasts {
self.notifications.show_toasts(ui);
}
}
/// Show recent text log messages to the user as toast notifications.
fn show_text_logs_as_notifications(&mut self) {
re_tracing::profile_function!();
while let Ok(message) = self.text_log_rx.try_recv() {
self.notifications.add_log(message);
}
}
fn receive_messages(&mut self, store_hub: &mut StoreHub, egui_ctx: &egui::Context) {
re_tracing::profile_function!();
let start = web_time::Instant::now();
while let Some((channel_source, msg)) = self.rx_log.try_recv() {
re_log::trace!("Received a message from {channel_source:?}"); // Used by `test_ui_wakeup` test app!
let msg = match msg.payload {
re_log_channel::SmartMessagePayload::Msg(msg) => msg,
re_log_channel::SmartMessagePayload::Flush { on_flush_done } => {
re_tracing::profile_scope!("on_flush_done");
on_flush_done();
continue;
}
re_log_channel::SmartMessagePayload::Quit(err) => {
if let Some(err) = err {
re_log::warn!(
"Data source has left unexpectedly: {err}, source: {}",
msg.source
);
} else {
re_log::debug!("Data source {} has finished", msg.source);
}
continue;
}
};
// We centralize "new store" detection and `data_source` attachment here, so that the `on_new_store`
// side effects (like `set_opened(true)` for `OpenAndSelect`) fire regardless of which message type
// happens to come first.
let msg_store_id = match &msg {
DataSourceMessage::RrdManifest(store_id, _)
| DataSourceMessage::RrdManifestComplete(store_id) => Some(store_id.clone()),
DataSourceMessage::LogMsg(log_msg) => Some(log_msg.store_id().clone()),
DataSourceMessage::TableMsg(_) | DataSourceMessage::UiCommand(_) => None,
};
let maybe_new_store = msg_store_id
.as_ref()
.filter(|sid| !store_hub.store_bundle().contains(sid));
if let Some(sid) = &msg_store_id {
let entity_db = store_hub.entity_db_entry(sid);
if entity_db.data_source.is_none() {
entity_db.data_source = Some((*channel_source).clone());
}
}
match msg {
DataSourceMessage::RrdManifest(store_id, rrd_manifest) => {
let entity_db = store_hub.entity_db_entry(&store_id);
let store_events = entity_db.add_rrd_manifest_message(rrd_manifest);
if let Some((entity_db, cache)) =
store_hub.entity_db_and_cache(&store_id, &self.view_class_registry)
{
cache.on_store_events(&store_events, entity_db);
}
}
DataSourceMessage::RrdManifestComplete(store_id) => {
let entity_db = store_hub.entity_db_entry(&store_id);
entity_db.mark_rrd_manifest_complete();
}
DataSourceMessage::LogMsg(msg) => {
self.receive_log_msg(&msg, store_hub, egui_ctx, &channel_source);
}
DataSourceMessage::TableMsg(table) => {
self.receive_table_msg(store_hub, egui_ctx, table);
}
DataSourceMessage::UiCommand(ui_command) => {
self.receive_data_source_ui_command(ui_command, &channel_source);
}
}
// Handle any action that is triggered by a new store _after_ processing the message
// that caused it.
if let Some(sid) = &maybe_new_store {
self.on_new_store(egui_ctx, sid, &channel_source, store_hub);
}
if start.elapsed() > web_time::Duration::from_millis(10) {
egui_ctx.request_repaint(); // make sure we keep receiving messages asap
break; // don't block the main thread for too long
}
}
// Run pending system commands in case any of the messages resulted in additional commands.
// This avoid further frame delays on these commands.
self.run_pending_system_commands(store_hub, egui_ctx);
}
/// There is logic duplicated between this and [`Self::prefetch_chunks`].
/// Make sure they are kept in sync!
fn receive_log_msg(
&mut self,
msg: &LogMsg,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
channel_source: &LogSource,
) {
re_tracing::profile_function!();
let store_id = msg.store_id();
if store_hub.is_active_blueprint(store_id) {
// TODO(#5514): handle loading of active blueprints.
re_log::warn_once!(
"Loading a blueprint {store_id:?} that is active. See https://github.com/rerun-io/rerun/issues/5514 for details."
);
}
// NOTE: store materialization, `data_source` attachment, and the `on_new_store`
// dispatch are handled in `receive_messages` so that they also fire for stores first
// introduced by `RrdManifest` / `RrdManifestComplete` messages.
let entity_db = store_hub.entity_db_entry(store_id);
let was_empty = entity_db.num_physical_chunks() == 0;
let entity_db_add_result = entity_db.add_log_msg(msg);
match entity_db_add_result {
Ok(store_events) => {
self.process_store_events_for_db(store_hub, store_id, &store_events);
}
Err(err) => {
re_log::error_once!("Failed to add incoming msg: {err}");
}
}
// Need to reborrow as read-only since we passed store_hub as mutable earlier.
let entity_db = store_hub
.entity_db(store_id)
.expect("Just queried it mutable and that was fine.");
// Note: some of the logic above is duplicated in `fn prefetch_chunks`.
// Make sure they are kept in sync!
let is_empty = entity_db.num_physical_chunks() == 0;
if was_empty && !is_empty {
// Hack: we cannot go to a specific timeline or entity until we know about it.
// Now we _hopefully_ do. The `LogMsg` could also belong to the blueprint, so
// we need to check for that as well.
if let LogSource::RedapGrpcStream { uri, .. } = channel_source
&& &uri.store_id() == store_id
{
self.go_to_dataset_data(uri.store_id(), uri.fragment.clone());
}
}
#[expect(clippy::match_same_arms)]
match &msg {
LogMsg::SetStoreInfo(_) => {
// Causes a new store typically. But that's handled below via `on_new_store`.
}
LogMsg::ArrowMsg(_, _) => {
// Handled by `EntityDb::add`.
}
LogMsg::BlueprintActivationCommand(cmd) => match store_id.kind() {
StoreKind::Recording => {
re_log::debug!(
"Unexpected `BlueprintActivationCommand` message for {store_id:?}"
);
}
StoreKind::Blueprint => {
if let Some(info) = entity_db.store_info() {
re_log::trace!(
"Activating blueprint that was loaded from {channel_source}"
);
let app_id = info.application_id().clone();
if cmd.make_default {
store_hub
.set_default_blueprint_for_app(store_id)
.unwrap_or_else(|err| {
re_log::warn!("Failed to make blueprint default: {err}");
});
}
if cmd.make_active {
store_hub
.set_cloned_blueprint_active_for_app(store_id)
.unwrap_or_else(|err| {
re_log::warn!("Failed to make blueprint active: {err}");
});
// Switch to this app, e.g. on drag-and-drop of a blueprint file
if self.state.navigation.current().app_id() != Some(&app_id) {
// Switch to this app:
store_hub.load_persisted_blueprints_for_app(&app_id);
if let Some(recording_id) =
store_hub.earliest_recording_for_app(&app_id)
{
store_hub.load_blueprint_and_caches(
&recording_id,
&self.view_class_registry,
);
self.state
.selection_state
.set_selection(Item::StoreId(recording_id.clone()));
self.state
.navigation
.replace(Route::LocalRecording { recording_id });
} else {
// TODO(RR-3713): show a blueprint for it anyway
re_log::debug_once!(
"Received BlueprintActivationCommand for app '{app_id}', but we have no recording for it"
);
}
}
// If the viewer is in the background, tell the user that it has received something new.
egui_ctx.send_viewport_cmd(
egui::ViewportCommand::RequestUserAttention(
egui::UserAttentionType::Informational,
),
);
}
} else {
re_log::warn!(
"Got ActivateStore message without first receiving a SetStoreInfo"
);
}
}
},
}
}
fn process_store_events_for_db(
&self,
store_hub: &mut StoreHub,
store_id: &StoreId,
store_events: &[re_chunk_store::ChunkStoreEvent],
) {
re_tracing::profile_function!();
// Keep all caches up to date, even if they're in the background.
// This ensures that when we switch to a different recording, the caches are already valid.
if let Some((entity_db, cache)) =
store_hub.entity_db_and_cache(store_id, &self.view_class_registry)
{
cache.on_store_events(store_events, entity_db);
}
self.validate_loaded_events(store_events);
}
fn receive_table_msg(
&self,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
table: TableMsg,
) {
re_tracing::profile_function!();
let TableMsg { id, data } = table;
// TODO(grtlr): For now we don't append anything to existing stores and always replace.
// TODO(ab): When we actually append to existing table, we will have to clear the UI
// cache by calling `DataFusionTableWidget::clear_state`.
let store = TableStore::default();
if let Err(err) = store.add_record_batch(data) {
re_log::error!("Failed to load table {id}: {err}");
} else {
if store_hub.insert_table_store(id.clone(), store).is_some() {
re_log::debug!("Overwritten table store with id: `{id}`");
} else {
re_log::debug!("Inserted table store with id: `{id}`");
}
self.command_sender
.send_system(SystemCommand::set_selection(
re_viewer_context::Item::TableId(id),
));
// If the viewer is in the background, tell the user that it has received something new.
egui_ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(
egui::UserAttentionType::Informational,
));
}
}
fn on_new_store(
&mut self,
egui_ctx: &egui::Context,
store_id: &StoreId,
channel_source: &LogSource,
store_hub: &mut StoreHub,
) {
if channel_source.select_when_loaded() {
// Set the recording-id after potentially creating the store in the hub.
// This ordering is important because the `StoreHub` internally
// updates the app-id when changing the recording.
match store_id.kind() {
StoreKind::Recording => {
re_log::trace!("Opening a new recording: '{store_id:?}'");
self.make_store_active_and_highlight(store_hub, egui_ctx, store_id);
}
StoreKind::Blueprint => {
// We wait with activating blueprints until they are fully loaded,
// so that we don't run heuristics on half-loaded blueprints.
// Otherwise on a mixed connection (SDK sending both blueprint and recording)
// the blueprint won't be activated until the whole _recording_ has finished loading.
}
}
}
let entity_db = store_hub.entity_db_entry(store_id);
let is_example = entity_db.store_class().is_example();
if cfg!(target_arch = "wasm32") && !self.startup_options.is_in_notebook && !is_example {
use std::sync::Once;
static ONCE: Once = Once::new();
ONCE.call_once(|| {
// Tell the user there is a faster native viewer they can use instead of the web viewer:
let notification = re_ui::notifications::Notification::new(
re_ui::notifications::NotificationLevel::Tip, "For better performance, try the native Rerun Viewer!").with_link(
re_ui::Link {
text: "Install…".into(),
url: "https://rerun.io/docs/overview/installing-rerun/viewer#installing-the-viewer".into(),
}
)
.no_toast()
.permanent_dismiss_id(egui::Id::new("install_native_viewer_prompt"));
self.command_sender
.send_system(SystemCommand::ShowNotification(notification));
});
}
if entity_db.store_kind() == StoreKind::Recording {
#[cfg(feature = "analytics")]
if let Some(analytics) = re_analytics::Analytics::global_or_init()
&& let Some(event) =
crate::viewer_analytics::event::open_recording(&self.app_env, entity_db)
{
analytics.record(event);
}
if let Some(event_dispatcher) = self.event_dispatcher.as_ref() {
event_dispatcher.on_recording_open(entity_db);
}
}
}
fn receive_data_source_ui_command(
&self,
ui_command: DataSourceUiCommand,
channel_source: &LogSource,
) {
re_tracing::profile_function!();
match ui_command {
DataSourceUiCommand::SetUrlFragment { store_id, fragment } => {
match re_uri::Fragment::from_str(&fragment) {
Ok(fragment) => {
self.command_sender
.send_system(SystemCommand::SetUrlFragment { store_id, fragment });
}
Err(err) => {
re_log::warn!(
"Failed to parse fragment received from {channel_source:?}: {err}"
);
}
}
}
DataSourceUiCommand::SaveScreenshot { file_path, view_id } => {
let view_id = if let Some(view_id) = view_id {
if let Ok(view_id) = uuid::Uuid::parse_str(&view_id) {
Some(view_id.into())
} else {
re_log::error!(
"Failed to parse view id from {view_id:?}. Expected a UUID."
);
return;
}
} else {
None
};
self.command_sender
.send_system(SystemCommand::SaveScreenshot {
target: re_viewer_context::ScreenshotTarget::SaveToPath(file_path),
view_id,
});
}
}
}
/// Makes the first recording store active that is found for a given data source if any.
fn try_make_recording_from_source_active(
&mut self,
egui_ctx: &egui::Context,
store_hub: &mut StoreHub,
new_source: &LogSource,
) {
if let Some(entity_db) = store_hub.find_recording_store_by_source(new_source) {
let store_id = entity_db.store_id().clone();
debug_assert!(store_id.is_recording()); // `find_recording_store_by_source` should have filtered for recordings rather than blueprints.
self.make_store_active_and_highlight(store_hub, egui_ctx, &store_id);
}
}
/// Makes the given store active and request user attention if Rerun in the background.
fn make_store_active_and_highlight(
&mut self,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
store_id: &StoreId,
) {
if store_id.is_blueprint() {
re_log::warn!(
"Can't make a blueprint active: {store_id:?}. This is likely a bug in Rerun."
);
return;
}
store_hub.load_blueprint_and_caches(store_id, &self.view_class_registry);
self.state.navigation.replace(Route::LocalRecording {
recording_id: store_id.clone(),
});
// Also select the new recording:
self.command_sender
.send_system(SystemCommand::set_selection(
re_viewer_context::Item::StoreId(store_id.clone()),
));
// If the viewer is in the background, tell the user that it has received something new.
egui_ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(
egui::UserAttentionType::Informational,
));
}
/// After loading some data; check if the loaded data makes sense.
fn validate_loaded_events(&self, store_events: &[re_chunk_store::ChunkStoreEvent]) {
re_tracing::profile_function!();
for event in store_events {
let Some(chunk) = event.delta_chunk() else {
continue;
};
// For speed, we don't care about the order of the following log statements, so we silence this warning
for component_descr in chunk.components().component_descriptors() {
if let Some(archetype_name) = component_descr.archetype {
if let Some(archetype) = self.reflection.archetypes.get(&archetype_name) {
for &view_type in archetype.view_types {
if !cfg!(feature = "map_view") && view_type == "MapView" {
re_log::warn_once!(
"Found map-related archetype, but viewer was not compiled with the `map_view` feature."
);
}
}
} else {
re_log::trace_once!("Unknown archetype: {archetype_name}");
}
}
}
}
}
fn purge_memory_if_needed(&mut self, store_hub: &mut StoreHub) {
re_tracing::profile_function!();
use re_format::format_bytes;
use re_memory::MemoryUse;
let limit = self.startup_options.memory_limit;
let mem_use_before = MemoryUse::capture();
if let Some(minimum_fraction_to_purge) = limit.is_exceeded_by(&mem_use_before) {
re_log::info_once!("Reached memory limit of {limit}. Freeing up data…");
let fraction_to_purge = (minimum_fraction_to_purge + 0.2).clamp(0.25, 1.0);
re_log::trace!("RAM limit: {limit}");
if let Some(resident) = mem_use_before.resident {
re_log::trace!("Resident: {}", format_bytes(resident as _),);
}
if let Some(counted) = mem_use_before.counted {
re_log::trace!("Counted: {}", format_bytes(counted as _));
}
re_tracing::profile_scope!("pruning");
if let Some(counted) = mem_use_before.counted {
re_log::trace!(
"Attempting to purge {:.1}% of used RAM ({})…",
100.0 * fraction_to_purge,
format_bytes(counted as f64 * fraction_to_purge as f64)
);
}
let active_recording_id = self.active_recording_id();
let time_cursor_for = |store_id: &StoreId| -> Option<TimelinePoint> {
let time_ctrl = self.state.time_controls.get(store_id)?;
Some((*time_ctrl.timeline()?, time_ctrl.time_int()?).into())
};
store_hub.purge_fraction_of_ram(
fraction_to_purge,
active_recording_id,
&time_cursor_for,
);
let mem_use_after = MemoryUse::capture();
let freed_memory = mem_use_before - mem_use_after;
if let (Some(counted_before), Some(counted_diff)) =
(mem_use_before.counted, freed_memory.counted)
&& 0 < counted_diff
{
re_log::debug!(
"GC result: -{} (-{:.1}%).",
format_bytes(counted_diff as _),
100.0 * counted_diff as f32 / counted_before as f32
);
}
if store_hub.store_bundle().recordings().count() == 1 {
// We're in a unique spot to accurately estimate how much
// EXTRA memory we use, beyond the raw chunks of memory.
// This is the true overhead of all book-keeping and unaccounted memory.
// This is the (currently) unevictable memory!
if let Some(current_mem_use) = mem_use_after.counted.or(mem_use_after.resident)
&& let Some(entity_db) = store_hub.store_bundle_mut().recordings_mut().next()
{
entity_db.estimated_application_overhead_bytes =
Some(current_mem_use - entity_db.byte_size_of_physical_chunks());
}
}
self.memory_panel.note_memory_purge();
}
}
/// Reset the viewer to how it looked the first time you ran it.
fn reset_viewer(&mut self, store_hub: &mut StoreHub, egui_ctx: &egui::Context) {
self.state = Default::default();
store_hub.clear_all_cloned_blueprints();
// Reset egui:
egui_ctx.memory_mut(|mem| *mem = Default::default());
// Restore style:
re_ui::apply_style_and_install_loaders(egui_ctx);
if let Err(err) = crate::reset_viewer_persistence() {
re_log::warn!("Failed to reset viewer: {err}");
}
}
pub fn recording_db(&self) -> Option<&EntityDb> {
let store_hub = self.store_hub.as_ref()?;
let recording_id = self.active_recording_id()?;
store_hub.entity_db(recording_id)
}
// NOTE: Relying on `self` is dangerous, as this is called during a time where some internal
// fields may have been temporarily `take()`n out. Keep this a static method.
fn handle_dropping_files(
egui_ctx: &egui::Context,
command_sender: &CommandSender,
route: &Route,
) {
#![allow(clippy::allow_attributes, clippy::needless_continue)] // false positive, depending on target_arch
preview_files_being_dropped(egui_ctx);
let dropped_files = egui_ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
if dropped_files.is_empty() {
return;
}
egui_ctx.request_repaint();
let mut force_store_info = false;
for file in dropped_files {
let active_store_id = route
.recording_id()
.cloned()
// Don't redirect data to the welcome screen.
.filter(|store_id| store_id.application_id() != StoreHub::welcome_screen_app_id())
.unwrap_or_else(|| {
// When we're on the welcome screen, there is no recording ID to recommend.
// But we want one, otherwise multiple things being dropped simultaneously on the
// welcome screen would end up in different recordings!
// If we don't have any application ID to recommend (which means we are on the welcome screen),
// then we use the file path as the application ID or the file name if there is no path (on web builds).
let application_id = file
.path
.clone()
.map(|p| ApplicationId::from(p.display().to_string()))
.unwrap_or_else(|| ApplicationId::from(file.name.clone()));
// NOTE: We don't override blueprints' store IDs anyhow, so it is sound to assume that
// this can only be a recording.
let recording_id = RecordingId::random();
// We're creating a recording just-in-time, directly from the viewer.
// We need those store infos or the data will just be silently ignored.
force_store_info = true;
StoreId::recording(application_id, recording_id)
});
if let Some(bytes) = file.bytes {
// This is what we get on Web.
command_sender.send_system(SystemCommand::LoadDataSource(
LogDataSource::FileContents(
FileSource::DragAndDrop {
recommended_store_id: Some(active_store_id.clone()),
force_store_info,
},
FileContents {
name: file.name.clone(),
bytes: bytes.clone(),
},
),
));
continue;
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(path) = file.path {
command_sender.send_system(SystemCommand::LoadDataSource(
LogDataSource::FilePath {
file_source: FileSource::DragAndDrop {
recommended_store_id: Some(active_store_id.clone()),
force_store_info,
},
path,
follow: false,
},
));
}
}
}
fn should_fade_in_welcome_screen(&self) -> bool {
if let Some(expect_data_soon) = self.startup_options.expect_data_soon {
return expect_data_soon;
}
// The reason for the fade-in is to avoid the welcome screen
// flickering quickly before receiving some data.
// So: if we expect data very soon, we do a fade-in.
for source in self.rx_log.sources() {
match &*source {
LogSource::File { .. }
| LogSource::HttpStream { .. }
| LogSource::RedapGrpcStream { .. }
| LogSource::Stdin
| LogSource::RrdWebEvent
| LogSource::Sdk
| LogSource::JsChannel { .. } => {
return true; // We expect data soon, so fade-in
}
LogSource::MessageProxy { .. } => {
// We start a gRPC server by default in native rerun, i.e. when just running `rerun`,
// and in that case fading in the welcome screen would be slightly annoying.
// However, we also use the gRPC server for sending data from the logging SDKs
// when they call `spawn()`, and in that case we really want to fade in the welcome screen.
// Therefore `spawn()` uses the special `--expect-data-soon` flag
// (handled earlier in this function), so here we know we are in the other case:
// a user calling `rerun` in their terminal (don't fade in).
}
}
}
false // No special sources (or no sources at all), so don't fade in
}
/// Handle fading in the welcome screen, if we should.
fn welcome_screen_opacity(&self, egui_ctx: &egui::Context) -> f32 {
if self.should_fade_in_welcome_screen() {
// The reason for this delay is to avoid the welcome screen
// flickering quickly before receiving some data.
// The only time it has for that is between the call to `spawn` and sending the recording info,
// which should happen _right away_, so we only need a small delay.
// Why not skip the wlecome screen completely when we expect the data?
// Because maybe the data never comes.
let sec_since_first_shown = self.start_time.elapsed().as_secs_f32();
let opacity = egui::remap_clamp(sec_since_first_shown, 0.4..=0.6, 0.0..=1.0);
if opacity < 1.0 {
egui_ctx.request_repaint();
}
opacity
} else {
1.0
}
}
pub(crate) fn toggle_fullscreen(&self) {
#[cfg(not(target_arch = "wasm32"))]
{
let fullscreen = self
.egui_ctx
.input(|i| i.viewport().fullscreen.unwrap_or(false));
self.egui_ctx
.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!fullscreen));
}
#[cfg(target_arch = "wasm32")]
{
if let Some(options) = &self.startup_options.fullscreen_options {
// Tell JS to toggle fullscreen.
if let Err(err) = options.on_toggle.call0() {
re_log::error!("{}", crate::web_tools::string_from_js_value(err));
}
}
}
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn is_fullscreen_allowed(&self) -> bool {
self.startup_options.fullscreen_options.is_some()
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn is_fullscreen_mode(&self) -> bool {
if let Some(options) = &self.startup_options.fullscreen_options {
// Ask JS if fullscreen is on or not.
match options.get_state.call0() {
Ok(v) => return v.is_truthy(),
Err(err) => re_log::error_once!("{}", crate::web_tools::string_from_js_value(err)),
}
}
false
}
#[allow(clippy::allow_attributes, clippy::needless_pass_by_ref_mut)] // False positive on wasm
fn process_screenshot_result(
&mut self,
image: &Arc<egui::ColorImage>,
user_data: &egui::UserData,
) {
use re_viewer_context::ScreenshotInfo;
if let Some(info) = user_data
.data
.as_ref()
.and_then(|data| data.downcast_ref::<ScreenshotInfo>())
{
let ScreenshotInfo {
ui_rect,
pixels_per_point,
name,
target,
} = (*info).clone();
let rgba = if let Some(ui_rect) = ui_rect {
Arc::new(image.region(&ui_rect, Some(pixels_per_point)))
} else {
image.clone()
};
match target {
re_viewer_context::ScreenshotTarget::CopyToClipboard => {
self.egui_ctx.copy_image((*rgba).clone());
}
re_viewer_context::ScreenshotTarget::SaveToPathFromFileDialog => {
use image::ImageEncoder as _;
let mut png_bytes: Vec<u8> = Vec::new();
if let Err(err) = image::codecs::png::PngEncoder::new(&mut png_bytes)
.write_image(
rgba.as_raw(),
rgba.width() as u32,
rgba.height() as u32,
image::ExtendedColorType::Rgba8,
)
{
re_log::error!("Failed to encode screenshot as PNG: {err}");
} else {
let file_name = format!("{name}.png");
self.command_sender.save_file_dialog(
self.main_thread_token,
&file_name,
"Save screenshot".to_owned(),
png_bytes,
);
}
}
re_viewer_context::ScreenshotTarget::SaveToPath(file_path) => {
#[cfg(not(target_arch = "wasm32"))]
{
let rgba = rgba.clone();
let Some(rgba_image) = image::RgbaImage::from_vec(
rgba.width() as _,
rgba.height() as _,
bytemuck::pod_collect_to_vec(&rgba.pixels),
) else {
re_log::error!("Failed to create image from screenshot data");
return;
};
// Convert to RGB8 so it works with JPG and other formats that don't support alpha.
// (There's nothing interesting in the alpha channel anyways.)
let rgb_image = image::DynamicImage::ImageRgba8(rgba_image).to_rgb8();
match rgb_image.save(&file_path) {
Ok(()) => {
re_log::info!("Saved screenshot to {file_path:?}");
}
Err(err) => {
re_log::error!(?file_path, "Failed to save screenshot: {err}");
// Image library has the bad habit of creating the file even when it fails e.g. due to unsupported format. Remove it again.
std::fs::remove_file(&file_path).ok();
}
}
}
#[cfg(target_arch = "wasm32")]
{
re_log::error!(
"Saving screenshots to a path is not supported on web. Attempted to save to: {file_path:?}"
);
}
}
}
} else {
#[cfg(not(target_arch = "wasm32"))] // no full-app screenshotting on web
self.screenshotter.save(&self.egui_ctx, image);
}
}
/// Receive in-transit chunks (previously prefetched):
fn receive_fetched_chunks(&self, store_hub: &mut StoreHub) {
re_tracing::profile_function!();
let store_ids: Vec<_> = store_hub
.store_bundle()
.recordings()
.map(|db| db.store_id().clone())
.collect();
for store_id in store_ids {
let db = store_hub.entity_db_entry(&store_id);
if cfg!(debug_assertions) && db.can_fetch_chunks_from_redap() {
re_tracing::profile_scope!("debug-sanity-check");
let storage_engine = db.storage_engine();
let store = storage_engine.store();
#[expect(clippy::iter_over_hash_type)] // sanity checks don't care about order
for missing_chunk_id in store.tracked_chunk_ids().missing_virtual {
let roots = store.find_root_chunks(&missing_chunk_id);
debug_assert!(!roots.is_empty(), "Missing chunk has no roots");
let all_roots_are_fully_loaded = roots.iter().all(|root_id| {
let root_info = db.rrd_manifest_index().root_chunk_info(root_id);
if let Some(root_info) = root_info {
root_info.is_fully_loaded()
} else {
re_log::debug_warn_once!("Failed to find root chunk");
false
}
});
if all_roots_are_fully_loaded {
re_log::warn_once!(
"A chunk was reported missing, but all its roots are marked as fully loaded."
);
re_log::debug_once!(
"Missing: {missing_chunk_id}, roots: {roots:?}, Chunk lineage: {}",
store.format_lineage(&missing_chunk_id)
);
}
}
}
if db.can_fetch_chunks_from_redap() {
re_tracing::profile_scope!("recording");
let mut store_events = Vec::new();
for chunk in db
.rrd_manifest_index_mut()
.chunk_requests_mut()
.receive_finished(self.egui_ctx.time())
{
match db.add_chunk(&std::sync::Arc::new(chunk)) {
Ok(events) => {
store_events.extend(events);
}
Err(err) => {
re_log::warn_once!("add_chunk failed: {err}");
}
}
}
self.process_store_events_for_db(store_hub, &store_id, &store_events);
// Need to reborrow since we pass `&mut store_hub` above.
let db = store_hub.entity_db_entry(&store_id);
// Note: some of the logic above is duplicated in `fn receive_log_msg`.
// Make sure they are kept in sync!
// We cancel right after resoliving (above), so that
// we give each fetch as much time as possible to finish.
db.rrd_manifest_index_mut()
.cancel_outdated_requests(self.egui_ctx.time());
if db.rrd_manifest_index_mut().chunk_requests().has_pending() {
self.egui_ctx.request_repaint(); // check back for more
}
}
}
}
/// Prefetch chunks for the open recording (stream from server)
///
/// There is logic duplicated between this and [`Self::receive_log_msg`].
/// Make sure they are kept in sync!
fn prefetch_chunks(&self, store_hub: &mut StoreHub) {
re_tracing::profile_function!();
let active_recording_id = self.active_recording_id();
// Even if we wanted, we cannot get rid of this overhead
let unpurgable_cache_size = active_recording_id
.and_then(|id| store_hub.store_caches(id))
.map_or(0, |caches| caches.memory_use_after_last_purge());
const APP_OVERHEAD_BYTES: u64 = 300_000_000;
const FIXED_FRACTION_OVERHEAD: f32 = 0.10;
const FALLBACK_FIXED_FRACTION_OVERHEAD: f32 = 0.20;
// Prefetch new chunks for the active recording (if any):
let active_recording = active_recording_id.and_then(|active_recording_id| {
store_hub.store_bundle_mut().get_mut(active_recording_id)
});
let mut memory_limit = if let Some(active_recording) = active_recording {
if active_recording.is_downloading_first_part_of_manifest() {
// We need at least ONE part of the manifest, but
// as soon as we have one part we start prefetching chunks
return;
}
// What is our memory budget for this recording?
// If need be, we can evict all other recordings and their caches.
// There is some fixed overhead in the process that we cannot purge.
// This includes things like fonts, icons, etc.
// We also want some headroom for spikes.
let overhead = active_recording
.estimated_application_overhead_bytes
.unwrap_or(APP_OVERHEAD_BYTES + unpurgable_cache_size);
// Leave some extra headroom (beyond the fixed overhead) for
// * secondary indices
// * failures in our accounting
let fixed_fraction_overhead = if active_recording
.estimated_application_overhead_bytes
.is_some()
{
FIXED_FRACTION_OVERHEAD // We have a good estimate, so we need less headroom
} else {
FALLBACK_FIXED_FRACTION_OVERHEAD
};
let memory_budget = self.startup_options.memory_limit.saturating_sub(overhead);
let memory_budget = memory_budget.split(fixed_fraction_overhead).1;
if memory_budget == re_memory::MemoryLimit::ZERO {
re_log::warn_once!("Very little memory budget left for active recording.");
}
// eprintln!("Memory budget for active recording: {memory_budget}");
let time_ctrl = self.state.time_controls.get(active_recording.store_id());
crate::prefetch_chunks::prefetch_chunks_for_recording(
&self.egui_ctx,
// If we can't afford at least this much for data, then what is even the point?
memory_budget.at_least(100_000_000),
active_recording,
time_ctrl,
self.connection_registry(),
);
memory_budget
} else {
// No recording is open, use the memory limit with some memory left for the app.
self.startup_options
.memory_limit
.saturating_sub(APP_OVERHEAD_BYTES + unpurgable_cache_size)
.split(FALLBACK_FIXED_FRACTION_OVERHEAD)
.1
};
let active_recording = active_recording_id
.and_then(|active_recording_id| store_hub.store_bundle().get(active_recording_id));
// Fetch background recordings if we have space for them.
if active_recording.is_none_or(|rec| !rec.can_load_more()) {
re_tracing::profile_scope!("fetch_background_recordings");
const BACKGROUND_HEADROOM_FRACTION: f32 = 0.2;
const RECORDING_HEADROOM_BYTES: u64 = 10_000_000;
// Leave a good amount of extra headroom for downloading background
// recordings.
memory_limit = memory_limit.split(BACKGROUND_HEADROOM_FRACTION).1;
// Subtract all already loaded physical chunks from the memory limit.
for recording in store_hub.store_bundle().recordings() {
if recording.is_downloading_first_part_of_manifest() {
// If any are downloading manifest, don't prefetch background recordings.
memory_limit = re_memory::MemoryLimit::ZERO;
break;
}
let fixed_fraction_overhead =
if recording.estimated_application_overhead_bytes.is_some() {
FIXED_FRACTION_OVERHEAD // We have a good estimate, so we need less headroom
} else {
FALLBACK_FIXED_FRACTION_OVERHEAD
};
let size = recording.byte_size_of_physical_chunks()
+ recording.estimated_application_overhead_bytes.unwrap_or(0);
let estimated_size = ((1.0 + fixed_fraction_overhead as f64) * size as f64) as u64
+ RECORDING_HEADROOM_BYTES;
memory_limit = memory_limit.saturating_sub(estimated_size);
if memory_limit == re_memory::MemoryLimit::ZERO {
break;
}
}
if memory_limit != re_memory::MemoryLimit::ZERO {
for recording in store_hub.store_bundle_mut().recordings_mut() {
// This means we skip the active recording, since we're only
// in this block to begin with if there is no active recording
// or the active recording cannot load more.
if !recording.can_load_more() {
continue;
}
// For this stores memory limit, add back the size of all physical chunks
// since that's considered in `prefetch_chunks_for_recording`.
let memory_limit =
memory_limit.saturating_add(recording.byte_size_of_physical_chunks());
if memory_limit
.checked_sub(recording.rrd_manifest_index().full_uncompressed_size())
.is_none()
{
// Continue if this recording doesn't fit, smaller ones
// might.
continue;
}
let time_ctrl = self.state.time_controls.get(recording.store_id());
crate::prefetch_chunks::prefetch_chunks_for_recording(
&self.egui_ctx,
memory_limit,
recording,
time_ctrl,
&self.connection_registry,
);
// Only prefetch for one at a time.
break;
}
}
}
}
}
#[cfg(target_arch = "wasm32")]
fn blueprint_loader() -> BlueprintPersistence {
// TODO(#2579): implement persistence for web
BlueprintPersistence {
loader: None,
saver: None,
validator: Some(Box::new(crate::blueprint::is_valid_blueprint)),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn blueprint_loader() -> BlueprintPersistence {
use re_entity_db::StoreBundle;
fn load_blueprint_from_disk(app_id: &ApplicationId) -> anyhow::Result<Option<StoreBundle>> {
let blueprint_path = crate::saving::default_blueprint_path(app_id)?;
if !blueprint_path.exists() {
return Ok(None);
}
re_log::debug!("Trying to load blueprint for {app_id} from {blueprint_path:?}");
if let Some(bundle) = crate::loading::load_blueprint_file(&blueprint_path) {
for store in bundle.entity_dbs() {
if store.store_kind() == StoreKind::Blueprint
&& !crate::blueprint::is_valid_blueprint(store)
{
re_log::warn_once!(
"Blueprint for {app_id} at {blueprint_path:?} appears invalid - will ignore. This is expected if you have just upgraded Rerun versions."
);
return Ok(None);
}
}
Ok(Some(bundle))
} else {
Ok(None)
}
}
#[cfg(not(target_arch = "wasm32"))]
fn save_blueprint_to_disk(app_id: &ApplicationId, blueprint: &EntityDb) -> anyhow::Result<()> {
let blueprint_path = crate::saving::default_blueprint_path(app_id)?;
let messages = blueprint.to_messages(None);
let rrd_version = blueprint
.store_info()
.and_then(|info| info.store_version)
.unwrap_or(re_build_info::CrateVersion::LOCAL);
// TODO(jleibs): Should we push this into a background thread? Blueprints should generally
// be small & fast to save, but maybe not once we start adding big pieces of user data?
crate::saving::encode_to_file(rrd_version, &blueprint_path, messages)?;
re_log::debug!("Saved blueprint for {app_id} to {blueprint_path:?}");
Ok(())
}
BlueprintPersistence {
loader: Some(Box::new(load_blueprint_from_disk)),
saver: Some(Box::new(save_blueprint_to_disk)),
validator: Some(Box::new(crate::blueprint::is_valid_blueprint)),
}
}
impl eframe::App for App {
fn clear_color(&self, visuals: &egui::Visuals) -> [f32; 4] {
if re_ui::CUSTOM_WINDOW_DECORATIONS {
[0.; 4] // transparent
} else if visuals.dark_mode {
[0., 0., 0., 1.]
} else {
[1., 1., 1., 1.]
}
}
fn save(&mut self, storage: &mut dyn eframe::Storage) {
if !self.startup_options.persist_state {
return;
}
re_tracing::profile_function!();
storage.set_string(RERUN_VERSION_KEY, self.build_info.version.to_string());
// Save the app state
eframe::set_value(storage, eframe::APP_KEY, &self.state);
eframe::set_value(
storage,
REDAP_TOKEN_KEY,
&self.connection_registry.dump_tokens(),
);
// Save the blueprints
// TODO(#2579): implement web-storage for blueprints as well
if let Some(hub) = &mut self.store_hub {
if self.state.app_options.blueprint_gc {
hub.gc_blueprints(&self.state.blueprint_undo_state);
}
if let Err(err) = hub.save_app_blueprints() {
re_log::error!("Saving blueprints failed: {err}");
}
} else {
re_log::error!("Could not save blueprints: the store hub is not available");
}
}
/// Called before each call to `ui`, but ALSO when the app is
/// hidden (occluded, minimized, …) if something has called `request_repaint`.
///
/// We put things here that are unrelated to the UI,
/// and that we still want to happen if the application is hidden.
fn logic(&mut self, egui_ctx: &egui::Context, _frame: &mut eframe::Frame) {
// Temporarily take the `StoreHub` out of the Viewer so it doesn't interfere with mutability
let mut store_hub = self
.store_hub
.take()
.expect("Failed to take store hub from the Viewer");
{
// Respect memory budget:
self.purge_memory_if_needed(&mut store_hub); // Call BEFORE `begin_frame_caches`
if self.app_options().blueprint_gc {
store_hub.gc_blueprints(&self.state.blueprint_undo_state);
}
}
{
// Download/ingest data:
self.receive_messages(&mut store_hub, egui_ctx);
self.receive_fetched_chunks(&mut store_hub);
self.prefetch_chunks(&mut store_hub);
}
self.run_pending_system_commands(&mut store_hub, egui_ctx);
{
// We also need to check for Ui commands, especially `UiCommand::Quit`.
let route = self.state.navigation.current().clone();
let (storage_context, store_context) = store_hub.read_context(&route);
let blueprint_query = self
.state
.blueprint_query_for_viewer(store_context.blueprint);
let app_blueprint = AppBlueprint::new(
Some(store_context.blueprint),
&blueprint_query,
egui_ctx,
self.panel_state_overrides_active
.then_some(self.panel_state_overrides),
);
self.run_pending_ui_commands(
egui_ctx,
&app_blueprint,
&storage_context,
Some(&store_context),
&route,
);
}
self.state.cleanup(&store_hub);
// Return the `StoreHub` to the Viewer so we have it on the next frame
self.store_hub = Some(store_hub);
}
/// Called when application need to be repainted
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
#[cfg(all(not(target_arch = "wasm32"), feature = "perf_telemetry_tracy"))]
re_perf_telemetry::external::tracing_tracy::client::frame_mark();
if let Some(seconds) = frame.info().cpu_usage {
self.frame_time_history.add(ui.input(|i| i.time), seconds);
}
// NOTE: Memory stats can be very costly to compute, so only do so if the memory panel is opened.
let mem_usage_tree = self
.memory_panel_open
.then(|| re_byte_size::NamedMemUsageTree::new("App", self.capture_mem_usage_tree()));
#[cfg(target_arch = "wasm32")]
if self.startup_options.enable_history {
// Handle pressing the back/forward mouse buttons explicitly, since eframe catches those.
let back_pressed = ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Extra1));
let fwd_pressed = ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Extra2));
if back_pressed {
crate::web_history::go_back();
}
if fwd_pressed {
crate::web_history::go_forward();
}
}
self.server_latency_trackers
.update(&self.connection_registry);
// We move the time at the very start of the frame,
// so that we always show the latest data when we're in "follow" mode.
self.move_time();
// Temporarily take the `StoreHub` out of the Viewer so it doesn't interfere with mutability
let mut store_hub = self
.store_hub
.take()
.expect("Failed to take store hub from the Viewer");
// Update data source order so it's based on opening order.
store_hub.update_data_source_order(&self.rx_log.sources());
#[cfg(not(target_arch = "wasm32"))]
if let Some(resolution_in_points) = self.startup_options.resolution_in_points.take() {
ui.send_viewport_cmd(egui::ViewportCommand::InnerSize(
resolution_in_points.into(),
));
}
#[cfg(not(target_arch = "wasm32"))]
if self.screenshotter.update(ui).quit {
ui.send_viewport_cmd(egui::ViewportCommand::Close);
return;
}
if self.startup_options.memory_limit.is_unlimited() {
// we only warn about high memory usage if the user hasn't specified a limit
self.ram_limit_warner.update();
}
#[cfg(target_arch = "wasm32")]
if let Some(PendingFilePromise {
recommended_store_id,
force_store_info,
promise,
}) = &self.open_files_promise
&& let Some(files) = promise.ready()
{
for file in files {
self.command_sender
.send_system(SystemCommand::LoadDataSource(LogDataSource::FileContents(
FileSource::FileDialog {
recommended_store_id: recommended_store_id.clone(),
force_store_info: *force_store_info,
},
file.clone(),
)));
}
self.open_files_promise = None;
}
// NOTE: GPU resource stats are cheap to compute so we always do.
let gpu_resource_stats = {
re_tracing::profile_scope!("gpu_resource_stats");
let egui_renderer = frame
.wgpu_render_state()
.expect("Failed to get frame render state")
.renderer
.read();
let render_ctx = egui_renderer
.callback_resources
.get::<re_renderer::RenderContext>()
.expect("Failed to get render context");
// Query statistics before begin_frame as this might be more accurate if there's resources that we recreate every frame.
render_ctx.gpu_resources.statistics()
};
// NOTE: Store and caching stats are very costly to compute: only do so if the memory panel
// is opened.
let store_stats = self.memory_panel_open.then(|| store_hub.stats());
// do early, before doing too many allocations
self.memory_panel
.update(&gpu_resource_stats, store_stats.as_ref());
self.purge_memory_if_needed(&mut store_hub); // Call BEFORE `begin_frame_caches`
// In some (rare) circumstances we run two egui passes in a single frame.
// This happens on call to `egui::Context::request_discard`.
let is_start_of_new_frame = ui.current_pass_index() == 0;
if is_start_of_new_frame {
// IMPORTANT: only call this once per FRAME even if we run multiple passes.
// Otherwise we might incorrectly evict something that was invisible in the first (discarded) pass.
store_hub.begin_frame_caches(); // Call AFTER `purge_memory_if_needed`
}
file_saver_progress_ui(ui, &mut self.background_tasks); // toasts for background file saver
// Make sure some app is active
// Must be called before `read_context` below.
if let Route::Loading(source) = self.state.navigation.current() {
if !self.msg_receive_set().contains(source) {
// The stream finished and may have produced a recording without triggering
// automatic navigation. So we try that before defaulting to showing the
// Welcome screen.
let loaded_recording = store_hub
.find_recording_store_by_source(source)
.map(|db| db.store_id().clone());
if let Some(store_id) = loaded_recording {
re_log::debug!("Stream completed, navigating to loaded recording {store_id:?}");
store_hub.load_blueprint_and_caches(&store_id, &self.view_class_registry);
self.state.navigation.replace(Route::LocalRecording {
recording_id: store_id,
});
} else {
re_log::debug!("No recording found from loading source, resetting navigation");
self.state.navigation.reset();
}
}
} else if !matches!(
self.state.navigation.current(),
Route::ChunkStoreBrowser { .. }
) {
// If the current route points to a stale recording, find a new valid state.
let route_is_valid = self
.state
.navigation
.current()
.recording_id()
.is_none_or(|recording_id| store_hub.entity_db(recording_id).is_some());
if !route_is_valid {
let any_other_app_id: Option<ApplicationId> = store_hub
.store_bundle()
.entity_dbs()
.map(|db| db.application_id())
.filter(|app_id| *app_id != StoreHub::welcome_screen_app_id())
.min()
.cloned();
if let Some(app_id) = any_other_app_id {
store_hub.load_persisted_blueprints_for_app(&app_id);
if let Some(recording_id) = store_hub.earliest_recording_for_app(&app_id) {
store_hub
.load_blueprint_and_caches(&recording_id, &self.view_class_registry);
self.state
.selection_state
.set_selection(Item::StoreId(recording_id.clone()));
self.state
.navigation
.replace(Route::LocalRecording { recording_id });
} else {
self.state.navigation.reset();
}
} else {
self.state.navigation.reset();
}
}
}
{
let (storage_context, store_context) =
store_hub.read_context(self.state.navigation.current());
let blueprint_query = self
.state
.blueprint_query_for_viewer(store_context.blueprint);
let app_blueprint = AppBlueprint::new(
Some(store_context.blueprint),
&blueprint_query,
ui,
self.panel_state_overrides_active
.then_some(self.panel_state_overrides),
);
self.ui_impl(
ui,
frame,
&app_blueprint,
&gpu_resource_stats,
&store_context,
&storage_context,
mem_usage_tree,
store_stats.as_ref(),
);
if re_ui::CUSTOM_WINDOW_DECORATIONS {
// Paint the main window frame on top of everything else
paint_native_window_frame(ui);
}
if let Some(cmd) = self
.cmd_palette
.show(ui, &crate::open_url_description::command_palette_parse_url)
{
match cmd {
re_ui::CommandPaletteAction::UiCommand(cmd) => {
self.command_sender.send_ui(cmd);
}
re_ui::CommandPaletteAction::OpenUrl(url_desc) => {
match ViewerOpenUrl::parse_with_options(
&url_desc.url,
&re_data_source::FromUriOptions {
accept_extensionless_http: true,
..Default::default()
},
) {
Ok(url) => {
url.open(
ui,
&OpenUrlOptions {
follow: false,
select_redap_source_when_loaded: true,
show_loader: true,
},
&self.command_sender,
);
}
Err(err) => {
re_log::warn!("{err}");
}
}
// Note that we can't use `ui.open_url(egui::OpenUrl::same_tab(uri))` here because..
// * the url redirect in `check_for_clicked_hyperlinks` wouldn't be hit
// * we don't actually want to open any URLs in the browser here ever, only ever into the current viewer
}
}
}
let route = self.state.navigation.current().clone();
Self::handle_dropping_files(ui, &self.command_sender, &route);
// Run pending commands last (so we don't have to wait for a repaint before they are run):
self.run_pending_ui_commands(
ui,
&app_blueprint,
&storage_context,
Some(&store_context),
&route,
);
}
self.run_pending_system_commands(&mut store_hub, ui);
self.update_history(&store_hub);
// Return the `StoreHub` to the Viewer so we have it on the next frame
self.store_hub = Some(store_hub);
{
// Check for returned screenshots:
let screenshots: Vec<_> = ui.input(|i| {
i.raw
.events
.iter()
.filter_map(|event| {
if let egui::Event::Screenshot {
image, user_data, ..
} = event
{
Some((image.clone(), user_data.clone()))
} else {
None
}
})
.collect()
});
for (image, user_data) in screenshots {
self.process_screenshot_result(&image, &user_data);
}
}
}
#[cfg(target_arch = "wasm32")]
fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
Some(&mut *self)
}
}
fn paint_background_fill(ui: &egui::Ui) {
// This is required because the streams view (time panel)
// has rounded top corners, which leaves a gap.
// So we fill in that gap (and other) here.
// Of course this does some over-draw, but we have to live with that.
let tokens = ui.tokens();
ui.painter().rect_filled(
ui.max_rect().shrink(0.5),
tokens.native_window_corner_radius(),
ui.visuals().panel_fill,
);
}
fn paint_native_window_frame(egui_ctx: &egui::Context) {
let tokens = egui_ctx.tokens();
let painter = egui::Painter::new(
egui_ctx.clone(),
egui::LayerId::new(egui::Order::TOP, egui::Id::new("native_window_frame")),
egui::Rect::EVERYTHING,
);
painter.rect_stroke(
egui_ctx.content_rect(),
tokens.native_window_corner_radius(),
egui_ctx.tokens().native_frame_stroke,
egui::StrokeKind::Inside,
);
}
fn preview_files_being_dropped(egui_ctx: &egui::Context) {
use egui::{Align2, Id, LayerId, Order, TextStyle};
// Preview hovering files:
if !egui_ctx.input(|i| i.raw.hovered_files.is_empty()) {
use std::fmt::Write as _;
let mut text = "Drop to load:\n".to_owned();
egui_ctx.input(|input| {
for file in &input.raw.hovered_files {
if let Some(path) = &file.path {
write!(text, "\n{}", path.display()).ok();
} else if !file.mime.is_empty() {
write!(text, "\n{}", file.mime).ok();
}
}
});
let painter =
egui_ctx.layer_painter(LayerId::new(Order::Foreground, Id::new("file_drop_target")));
let screen_rect = egui_ctx.content_rect();
painter.rect_filled(
screen_rect,
0.0,
egui_ctx
.global_style()
.visuals
.extreme_bg_color
.gamma_multiply_u8(192),
);
painter.text(
screen_rect.center(),
Align2::CENTER_CENTER,
text,
TextStyle::Body.resolve(&egui_ctx.global_style()),
egui_ctx.global_style().visuals.strong_text_color(),
);
}
}
// ----------------------------------------------------------------------------
fn file_saver_progress_ui(egui_ctx: &egui::Context, background_tasks: &mut BackgroundTasks) {
if background_tasks.is_file_save_in_progress() {
// There's already a file save running in the background.
if let Some(res) = background_tasks.poll_file_saver_promise() {
// File save promise has returned.
match res {
Ok(path) => {
re_log::info!("File saved to {path:?}."); // this will also show a notification the user
}
Err(err) => {
re_log::error!("{err}"); // this will also show a notification the user
}
}
} else {
// File save promise is still running in the background.
// NOTE: not a toast, want something a bit more discreet here.
egui::Window::new("file_saver_spin")
.anchor(egui::Align2::RIGHT_BOTTOM, egui::Vec2::ZERO)
.title_bar(false)
.enabled(false)
.auto_sized()
.show(egui_ctx, |ui| {
ui.horizontal(|ui| {
ui.loading_indicator("Writing file to disk");
ui.label("Writing file to disk…");
})
});
}
}
}
/// [This may only be called on the main thread](https://docs.rs/rfd/latest/rfd/#macos-non-windowed-applications-async-and-threading).
#[cfg(not(target_arch = "wasm32"))]
fn open_file_dialog_native(_: crate::MainThreadToken) -> Vec<std::path::PathBuf> {
re_tracing::profile_function!();
let supported: Vec<_> = if re_data_loader::iter_external_loaders().len() == 0 {
re_data_loader::supported_extensions().collect()
} else {
vec![]
};
let mut dialog = rfd::FileDialog::new();
// If there's at least one external loader registered, then literally anything goes!
if !supported.is_empty() {
dialog = dialog.add_filter("Supported files", &supported);
}
dialog.pick_files().unwrap_or_default()
}
#[cfg(target_arch = "wasm32")]
async fn async_open_rrd_dialog() -> Vec<re_data_source::FileContents> {
let supported: Vec<_> = re_data_loader::supported_extensions().collect();
let files = rfd::AsyncFileDialog::new()
.add_filter("Supported files", &supported)
.pick_files()
.await
.unwrap_or_default();
let mut file_contents = Vec::with_capacity(files.len());
for file in files {
let file_name = file.file_name();
re_log::debug!("Reading {file_name}…");
let bytes = file.read().await;
re_log::debug!(
"{file_name} was {}",
re_format::format_bytes(bytes.len() as _)
);
file_contents.push(re_data_source::FileContents {
name: file_name,
bytes: bytes.into(),
});
}
file_contents
}
fn save_active_recording(
app: &mut App,
store_context: Option<&ActiveStoreContext<'_>>,
loop_selection: Option<(TimelineName, re_log_types::AbsoluteTimeRangeF)>,
) -> anyhow::Result<()> {
let Some(entity_db) = store_context.as_ref().map(|view| view.recording) else {
// NOTE: Can only happen if saving through the command palette.
anyhow::bail!("No recording data to save");
};
save_recording(app, entity_db, loop_selection)
}
fn save_recording(
app: &mut App,
entity_db: &EntityDb,
loop_selection: Option<(TimelineName, re_log_types::AbsoluteTimeRangeF)>,
) -> anyhow::Result<()> {
let rrd_version = entity_db
.store_info()
.and_then(|info| info.store_version)
.unwrap_or(re_build_info::CrateVersion::LOCAL);
let file_name = if let Some(recording_name) = entity_db
.recording_info_property::<re_sdk_types::components::Name>(
re_sdk_types::archetypes::RecordingInfo::descriptor_name().component,
) {
format!("{}.rrd", sanitize_file_name(&recording_name))
} else {
"data.rrd".to_owned()
};
let title = if loop_selection.is_some() {
"Save loop selection"
} else {
"Save recording"
};
save_entity_db(
app,
rrd_version,
file_name,
title.to_owned(),
entity_db.to_messages(loop_selection),
)
}
fn save_blueprint(
app: &mut App,
store_context: Option<&ActiveStoreContext<'_>>,
) -> anyhow::Result<()> {
let Some(store_context) = store_context else {
anyhow::bail!("No blueprint to save");
};
re_tracing::profile_function!();
let rrd_version = store_context
.blueprint
.store_info()
.and_then(|info| info.store_version)
.unwrap_or(re_build_info::CrateVersion::LOCAL);
// We change the recording id to a new random one,
// otherwise when saving and loading a blueprint file, we can end up
// in a situation where the store_id we're loading is the same as the currently active one,
// which mean they will merge in a strange way.
// This is also related to https://github.com/rerun-io/rerun/issues/5295
let new_store_id = store_context
.blueprint
.store_id()
.clone()
.with_recording_id(RecordingId::random());
let mut saved_blueprint = store_context
.blueprint
.clone_with_new_id(new_store_id)
.context("Cloning current blueprint")?;
if let Some(undo_state) = app
.state
.blueprint_undo_state
.get(store_context.blueprint.store_id())
{
// We don't actually want to edit the undo state when saving,
// just clear the redo-buffer section of what we save.
undo_state.clone().clear_redo_buffer(&mut saved_blueprint);
}
let messages = saved_blueprint.to_messages(None);
let file_name = format!(
"{}.rbl",
crate::saving::sanitize_app_id(store_context.application_id())
);
let title = "Save blueprint";
save_entity_db(app, rrd_version, file_name, title.to_owned(), messages)
}
// TODO(emilk): unify this with `ViewerContext::save_file_dialog`
#[allow(clippy::allow_attributes, clippy::needless_pass_by_ref_mut)] // `app` is only used on native
#[allow(clippy::unnecessary_wraps)] // cannot return error on web
fn save_entity_db(
#[allow(clippy::allow_attributes, unused_variables)] app: &mut App, // only used on native
rrd_version: CrateVersion,
file_name: String,
title: String,
messages: impl Iterator<Item = re_chunk::ChunkResult<LogMsg>>,
) -> anyhow::Result<()> {
re_tracing::profile_function!();
// TODO(#6984): Ideally we wouldn't collect at all and just stream straight to the
// encoder from the store.
//
// From a memory usage perspective this isn't too bad though: the data within is still
// refcounted straight from the store in any case.
//
// It just sucks latency-wise.
let messages = messages.collect::<Vec<_>>();
// Web
#[cfg(target_arch = "wasm32")]
{
wasm_bindgen_futures::spawn_local(async move {
if let Err(err) =
async_save_dialog(rrd_version, &file_name, &title, messages.into_iter()).await
{
re_log::error!("File saving failed: {err}");
}
});
}
// Native
#[cfg(not(target_arch = "wasm32"))]
{
let path = {
re_tracing::profile_scope!("file_dialog");
rfd::FileDialog::new()
.set_file_name(file_name)
.set_title(title)
.save_file()
};
if let Some(path) = path {
app.background_tasks.spawn_file_saver(move || {
crate::saving::encode_to_file(rrd_version, &path, messages.into_iter())?;
Ok(path)
})?;
}
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
async fn async_save_dialog(
rrd_version: CrateVersion,
file_name: &str,
title: &str,
messages: impl Iterator<Item = re_chunk::ChunkResult<LogMsg>>,
) -> anyhow::Result<()> {
use anyhow::Context as _;
let file_handle = rfd::AsyncFileDialog::new()
.set_file_name(file_name)
.set_title(title)
.save_file()
.await;
let Some(file_handle) = file_handle else {
return Ok(()); // aborted
};
let options = re_log_encoding::rrd::EncodingOptions::PROTOBUF_COMPRESSED;
let mut bytes = Vec::new();
re_log_encoding::Encoder::encode_into(rrd_version, options, messages, &mut bytes)?;
file_handle.write(&bytes).await.context("Failed to save")
}
/// Propagates [`re_viewer_context::TimeControlResponse`] to [`ViewerEventDispatcher`].
fn handle_time_ctrl_event(
recording: &EntityDb,
events: Option<&ViewerEventDispatcher>,
response: &re_viewer_context::TimeControlResponse,
) {
let Some(events) = events else {
return;
};
if let Some(playing) = response.playing_change {
events.on_play_state_change(recording, playing);
}
if let Some((timeline, time)) = response.timeline_change {
events.on_timeline_change(recording, timeline, time);
}
if let Some(time) = response.time_change {
events.on_time_update(recording, time);
}
}
impl MemUsageTreeCapture for App {
fn capture_mem_usage_tree(&self) -> MemUsageTree {
re_tracing::profile_function!();
let mut node = re_byte_size::MemUsageNode::default();
node.add("state", self.state.capture_mem_usage_tree());
node.add("rx_log", self.rx_log.capture_mem_usage_tree());
node.add("store_hub", self.store_hub.capture_mem_usage_tree());
node.into_tree()
}
}