-
Notifications
You must be signed in to change notification settings - Fork 388
/
Copy pathapp.rs
1310 lines (1111 loc) · 47.1 KB
/
app.rs
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
use web_time::Instant;
use re_data_source::{DataSource, FileContents};
use re_data_store::store_db::StoreDb;
use re_log_types::{FileSource, LogMsg, StoreKind};
use re_renderer::WgpuResourcePoolStatistics;
use re_smart_channel::{ReceiveSet, SmartChannelSource};
use re_ui::{toasts, UICommand, UICommandSender};
use re_viewer_context::{
command_channel, AppOptions, CommandReceiver, CommandSender, ComponentUiRegistry,
DynSpaceViewClass, PlayState, SpaceViewClassRegistry, SpaceViewClassRegistryError,
StoreContext, SystemCommand, SystemCommandSender,
};
use crate::{
app_blueprint::AppBlueprint,
background_tasks::BackgroundTasks,
store_hub::{StoreHub, StoreHubStats},
viewer_analytics::ViewerAnalytics,
AppState,
};
// ----------------------------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum TimeControlCommand {
TogglePlayPause,
StepBack,
StepForward,
Restart,
Follow,
}
// ----------------------------------------------------------------------------
/// Settings set once at startup (e.g. via command-line options) and not serialized.
#[derive(Clone)]
pub struct StartupOptions {
pub memory_limit: re_memory::MemoryLimit,
pub persist_state: bool,
/// Whether or not the app is running in the context of a Jupyter Notebook.
pub is_in_notebook: bool,
/// Set to identify the web page the viewer is running on.
#[cfg(target_arch = "wasm32")]
pub location: Option<eframe::Location>,
/// Take a screenshot of the app and quit.
/// We use this to generate screenshots of our exmples.
#[cfg(not(target_arch = "wasm32"))]
pub screenshot_to_path_then_quit: Option<std::path::PathBuf>,
/// Set the screen resolution in logical points.
#[cfg(not(target_arch = "wasm32"))]
pub resolution_in_points: Option<[f32; 2]>,
pub skip_welcome_screen: bool,
}
impl Default for StartupOptions {
fn default() -> Self {
Self {
memory_limit: re_memory::MemoryLimit::default(),
persist_state: true,
is_in_notebook: false,
#[cfg(target_arch = "wasm32")]
location: None,
#[cfg(not(target_arch = "wasm32"))]
screenshot_to_path_then_quit: None,
#[cfg(not(target_arch = "wasm32"))]
resolution_in_points: None,
skip_welcome_screen: false,
}
}
}
// ----------------------------------------------------------------------------
#[cfg(not(target_arch = "wasm32"))]
const MIN_ZOOM_FACTOR: f32 = 0.2;
#[cfg(not(target_arch = "wasm32"))]
const MAX_ZOOM_FACTOR: f32 = 4.0;
/// The Rerun Viewer as an [`eframe`] application.
pub struct App {
build_info: re_build_info::BuildInfo,
startup_options: StartupOptions,
ram_limit_warner: re_memory::RamLimitWarner,
pub(crate) re_ui: re_ui::ReUi,
screenshotter: crate::screenshotter::Screenshotter,
#[cfg(not(target_arch = "wasm32"))]
profiler: re_tracing::Profiler,
/// Listens to the local text log stream
text_log_rx: std::sync::mpsc::Receiver<re_log::LogMsg>,
component_ui_registry: ComponentUiRegistry,
rx: ReceiveSet<LogMsg>,
#[cfg(target_arch = "wasm32")]
open_files_promise: Option<poll_promise::Promise<Vec<re_data_source::FileContents>>>,
/// 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>,
/// Toast notifications.
toasts: toasts::Toasts,
memory_panel: crate::memory_panel::MemoryPanel,
memory_panel_open: bool,
style_panel_open: bool,
pub(crate) latest_queue_interest: 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,
analytics: ViewerAnalytics,
/// All known space view types.
space_view_class_registry: SpaceViewClassRegistry,
}
impl App {
/// Create a viewer that receives new log messages over time
pub fn new(
build_info: re_build_info::BuildInfo,
app_env: &crate::AppEnvironment,
startup_options: StartupOptions,
re_ui: re_ui::ReUi,
storage: Option<&dyn eframe::Storage>,
) -> Self {
re_tracing::profile_function!();
let (logger, text_log_rx) = re_log::ChannelLogger::new(re_log::LevelFilter::Info);
if re_log::add_boxed_logger(Box::new(logger)).is_err() {
// This can happen when `rerun` crate users call `spawn`. TODO(emilk): make `spawn` spawn a new process.
re_log::debug!(
"re_log not initialized - we won't see any log messages as GUI notifications"
);
}
let state: AppState = if startup_options.persist_state {
storage
.and_then(|storage| {
// This re-implements: `eframe::get_value` so we can customize the warning message.
// TODO(#2849): More thorough error-handling.
storage.get_string(eframe::APP_KEY).and_then(|value| {
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()
};
let mut analytics = ViewerAnalytics::new(&startup_options);
analytics.on_viewer_started(&build_info, app_env);
let mut space_view_class_registry = SpaceViewClassRegistry::default();
if let Err(err) =
populate_space_view_class_registry_with_builtin(&mut space_view_class_registry)
{
re_log::error!(
"Failed to populate Space View type registry with built-in Space Views: {}",
err
);
}
#[allow(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(screenshot_path);
}
let (command_sender, command_receiver) = command_channel();
let component_ui_registry = re_data_ui::create_component_ui_registry();
Self {
build_info,
startup_options,
ram_limit_warner: re_memory::RamLimitWarner::warn_at_fraction_of_max(0.75),
re_ui,
screenshotter,
#[cfg(not(target_arch = "wasm32"))]
profiler: Default::default(),
text_log_rx,
component_ui_registry,
rx: Default::default(),
#[cfg(target_arch = "wasm32")]
open_files_promise: Default::default(),
state,
background_tasks: Default::default(),
store_hub: Some(StoreHub::new()),
toasts: toasts::Toasts::new(),
memory_panel: Default::default(),
memory_panel_open: false,
style_panel_open: false,
latest_queue_interest: web_time::Instant::now(), // TODO(emilk): `Instant::MIN` when we have our own `Instant` that supports it.
frame_time_history: egui::util::History::new(1..100, 0.5),
command_sender,
command_receiver,
cmd_palette: Default::default(),
space_view_class_registry,
analytics,
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn set_profiler(&mut self, profiler: re_tracing::Profiler) {
self.profiler = profiler;
}
pub fn build_info(&self) -> &re_build_info::BuildInfo {
&self.build_info
}
pub fn re_ui(&self) -> &re_ui::ReUi {
&self.re_ui
}
pub fn app_options(&self) -> &AppOptions {
self.state.app_options()
}
pub fn app_options_mut(&mut self) -> &mut AppOptions {
self.state.app_options_mut()
}
pub fn is_screenshotting(&self) -> bool {
self.screenshotter.is_screenshotting()
}
pub fn add_receiver(&mut self, rx: re_smart_channel::Receiver<LogMsg>) {
// Make sure we wake up when a message is sent.
#[cfg(not(target_arch = "wasm32"))]
let rx = crate::wake_up_ui_thread_on_each_msg(rx, self.re_ui.egui_ctx.clone());
self.rx.add(rx);
}
pub fn msg_receive_set(&self) -> &ReceiveSet<LogMsg> {
&self.rx
}
/// Adds a new space view class to the viewer.
pub fn add_space_view_class<T: DynSpaceViewClass + Default + 'static>(
&mut self,
) -> Result<(), SpaceViewClassRegistryError> {
self.space_view_class_registry.add_class::<T>()
}
fn check_keyboard_shortcuts(&self, egui_ctx: &egui::Context) {
if let Some(cmd) = UICommand::listen_for_kb_shortcut(egui_ctx) {
self.command_sender.send_ui(cmd);
}
}
fn run_pending_system_commands(&mut self, store_hub: &mut StoreHub, egui_ctx: &egui::Context) {
while let Some(cmd) = self.command_receiver.recv_system() {
self.run_system_command(cmd, store_hub, egui_ctx);
}
}
fn run_pending_ui_commands(
&mut self,
frame: &mut eframe::Frame,
egui_ctx: &egui::Context,
app_blueprint: &AppBlueprint<'_>,
store_context: Option<&StoreContext<'_>>,
) {
while let Some(cmd) = self.command_receiver.recv_ui() {
self.run_ui_command(frame, egui_ctx, app_blueprint, store_context, cmd);
}
}
#[allow(clippy::unused_self)]
fn run_system_command(
&mut self,
cmd: SystemCommand,
store_hub: &mut StoreHub,
egui_ctx: &egui::Context,
) {
match cmd {
SystemCommand::SetRecordingId(recording_id) => {
store_hub.set_recording_id(recording_id);
}
SystemCommand::CloseRecordingId(recording_id) => {
store_hub.remove_recording_id(&recording_id);
}
SystemCommand::LoadDataSource(data_source) => {
let egui_ctx = self.re_ui.egui_ctx.clone();
// On native, `add_receiver` spawns a thread that wakes up the ui thread
// on any new message. On web we cannot spawn threads, so instead we need
// to supply a waker that is called when new messages arrive in background tasks
let waker = Box::new(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));
});
match data_source.stream(Some(waker)) {
Ok(rx) => {
self.add_receiver(rx);
}
Err(err) => {
re_log::error!("Failed to open data source: {}", re_error::format(err));
}
}
}
SystemCommand::LoadStoreDb(store_db) => {
let store_id = store_db.store_id().clone();
store_hub.insert_recording(store_db);
store_hub.set_recording_id(store_id);
}
SystemCommand::ResetViewer => self.reset(store_hub, egui_ctx),
SystemCommand::UpdateBlueprint(blueprint_id, updates) => {
let blueprint_db = store_hub.store_db_mut(&blueprint_id);
for row in updates {
match blueprint_db.add_data_row(&row) {
Ok(()) => {}
Err(err) => {
re_log::warn_once!("Failed to store blueprint delta: {err}");
}
}
}
}
}
}
fn run_ui_command(
&mut self,
_frame: &mut eframe::Frame,
_egui_ctx: &egui::Context,
app_blueprint: &AppBlueprint<'_>,
store_context: Option<&StoreContext<'_>>,
cmd: UICommand,
) {
match cmd {
#[cfg(not(target_arch = "wasm32"))]
UICommand::Save => {
save(self, store_context, None);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::SaveSelection => {
save(
self,
store_context,
self.state.loop_selection(store_context),
);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::Open => {
for file_path in open_file_dialog_native() {
self.command_sender
.send_system(SystemCommand::LoadDataSource(DataSource::FilePath(
FileSource::FileDialog,
file_path,
)));
}
}
#[cfg(target_arch = "wasm32")]
UICommand::Open => {
let egui_ctx = _egui_ctx.clone();
self.open_files_promise = Some(poll_promise::Promise::spawn_local(async move {
let file = async_open_rrd_dialog().await;
egui_ctx.request_repaint(); // Wake ui thread
file
}));
}
UICommand::CloseCurrentRecording => {
let cur_rec = store_context
.and_then(|ctx| ctx.recording)
.map(|rec| rec.store_id());
if let Some(cur_rec) = cur_rec {
self.command_sender
.send_system(SystemCommand::CloseRecordingId(cur_rec.clone()));
}
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::Quit => {
_frame.close();
}
UICommand::ResetViewer => self.command_sender.send_system(SystemCommand::ResetViewer),
#[cfg(not(target_arch = "wasm32"))]
UICommand::OpenProfiler => {
self.profiler.start();
}
UICommand::ToggleMemoryPanel => {
self.memory_panel_open ^= true;
}
UICommand::ToggleBlueprintPanel => {
app_blueprint.toggle_blueprint_panel(&self.command_sender);
}
UICommand::ToggleSelectionPanel => {
app_blueprint.toggle_selection_panel(&self.command_sender);
}
UICommand::ToggleTimePanel => app_blueprint.toggle_time_panel(&self.command_sender),
#[cfg(debug_assertions)]
UICommand::ToggleStylePanel => {
self.style_panel_open ^= true;
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ToggleFullscreen => {
_frame.set_fullscreen(!_frame.info().window_info.fullscreen);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomIn => {
self.app_options_mut().zoom_factor += 0.1;
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomOut => {
self.app_options_mut().zoom_factor -= 0.1;
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ZoomReset => {
self.app_options_mut().zoom_factor = 1.0;
}
UICommand::SelectionPrevious => {
let state = &mut self.state;
if let Some(rec_cfg) = store_context
.and_then(|ctx| ctx.recording)
.map(|rec| rec.store_id())
.and_then(|rec_id| state.recording_config_mut(rec_id))
{
rec_cfg.selection_state.select_previous();
}
}
UICommand::SelectionNext => {
let state = &mut self.state;
if let Some(rec_cfg) = store_context
.and_then(|ctx| ctx.recording)
.map(|rec| rec.store_id())
.and_then(|rec_id| state.recording_config_mut(rec_id))
{
rec_cfg.selection_state.select_next();
}
}
UICommand::ToggleCommandPalette => {
self.cmd_palette.toggle();
}
UICommand::PlaybackTogglePlayPause => {
self.run_time_control_command(store_context, TimeControlCommand::TogglePlayPause);
}
UICommand::PlaybackFollow => {
self.run_time_control_command(store_context, TimeControlCommand::Follow);
}
UICommand::PlaybackStepBack => {
self.run_time_control_command(store_context, TimeControlCommand::StepBack);
}
UICommand::PlaybackStepForward => {
self.run_time_control_command(store_context, TimeControlCommand::StepForward);
}
UICommand::PlaybackRestart => {
self.run_time_control_command(store_context, TimeControlCommand::Restart);
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::ScreenshotWholeApp => {
self.screenshotter.request_screenshot();
}
#[cfg(not(target_arch = "wasm32"))]
UICommand::PrintDatastore => {
if let Some(ctx) = store_context {
if let Some(recording) = ctx.recording {
let table = recording.store().to_data_table();
match table {
Ok(table) => {
println!("{table}");
}
Err(err) => {
println!("{err}");
}
}
}
}
}
}
}
fn run_time_control_command(
&mut self,
store_context: Option<&StoreContext<'_>>,
command: TimeControlCommand,
) {
let Some(store_db) = store_context.as_ref().and_then(|ctx| ctx.recording) else {
return;
};
let rec_id = store_db.store_id();
let Some(rec_cfg) = self.state.recording_config_mut(rec_id) else {
return;
};
let time_ctrl = &mut rec_cfg.time_ctrl;
let times_per_timeline = store_db.times_per_timeline();
match command {
TimeControlCommand::TogglePlayPause => {
time_ctrl.toggle_play_pause(times_per_timeline);
}
TimeControlCommand::Follow => {
time_ctrl.set_play_state(times_per_timeline, PlayState::Following);
}
TimeControlCommand::StepBack => {
time_ctrl.step_time_back(times_per_timeline);
}
TimeControlCommand::StepForward => {
time_ctrl.step_time_fwd(times_per_timeline);
}
TimeControlCommand::Restart => {
time_ctrl.restart(times_per_timeline);
}
}
}
fn memory_panel_ui(
&mut self,
ui: &mut egui::Ui,
gpu_resource_stats: &WgpuResourcePoolStatistics,
store_stats: &StoreHubStats,
) {
let frame = egui::Frame {
fill: ui.visuals().panel_fill,
..self.re_ui.bottom_panel_frame()
};
egui::TopBottomPanel::bottom("memory_panel")
.default_height(300.0)
.resizable(true)
.frame(frame)
.show_animated_inside(ui, self.memory_panel_open, |ui| {
self.memory_panel.ui(
ui,
self.re_ui(),
&self.startup_options.memory_limit,
gpu_resource_stats,
store_stats,
);
});
}
fn style_panel_ui(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
egui::SidePanel::left("style_panel")
.default_width(300.0)
.resizable(true)
.frame(self.re_ui.top_panel_frame())
.show_animated_inside(ui, self.style_panel_open, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
ctx.settings_ui(ui);
});
});
}
/// Top-level ui function.
///
/// Shows the viewer ui.
fn ui(
&mut self,
egui_ctx: &egui::Context,
frame: &mut eframe::Frame,
app_blueprint: &AppBlueprint<'_>,
gpu_resource_stats: &WgpuResourcePoolStatistics,
store_context: Option<&StoreContext<'_>>,
store_stats: &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(egui_ctx, |ui| {
paint_background_fill(ui);
crate::ui::mobile_warning_ui(&self.re_ui, ui);
crate::ui::top_panel(
app_blueprint,
store_context,
ui,
frame,
self,
gpu_resource_stats,
);
self.memory_panel_ui(ui, gpu_resource_stats, store_stats);
self.style_panel_ui(egui_ctx, ui);
if let Some(store_view) = store_context {
static EMPTY_STORE_DB: once_cell::sync::Lazy<StoreDb> =
once_cell::sync::Lazy::new(|| {
StoreDb::new(re_log_types::StoreId::from_string(
StoreKind::Recording,
"<EMPTY>".to_owned(),
))
});
// We want the regular UI as soon as a blueprint is available (or, rather, an
// app ID is set). If no recording is available, we use a default, empty one.
// Note that EMPTY_STORE_DB is *not* part of the list of available recordings
// (StoreContext::alternate_recordings), which means that it's not displayed in
// the recordings UI.
let store_db = if let Some(store_db) = store_view.recording {
store_db
} else {
&EMPTY_STORE_DB
};
// TODO(andreas): store the re_renderer somewhere else.
let egui_renderer = {
let render_state = frame.wgpu_render_state().unwrap();
&mut render_state.renderer.write()
};
if let Some(render_ctx) = egui_renderer
.callback_resources
.get_mut::<re_renderer::RenderContext>()
{
render_ctx.begin_frame();
self.state.show(
app_blueprint,
ui,
render_ctx,
store_db,
store_view,
&self.re_ui,
&self.component_ui_registry,
&self.space_view_class_registry,
&self.rx,
&self.command_sender,
);
render_ctx.before_submit();
}
} else {
// This is part of the loading vs. welcome screen UI logic. The loading screen
// is displayed when no app ID is set. This is e.g. the initial state for the
// web demos.
crate::ui::loading_ui(ui, &self.rx);
}
});
}
/// 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(re_log::LogMsg { level, target, msg }) = self.text_log_rx.try_recv() {
let is_rerun_crate = target.starts_with("rerun") || target.starts_with("re_");
if !is_rerun_crate {
continue;
}
let kind = match level {
re_log::Level::Error => toasts::ToastKind::Error,
re_log::Level::Warn => toasts::ToastKind::Warning,
re_log::Level::Info => toasts::ToastKind::Info,
re_log::Level::Debug | re_log::Level::Trace => {
continue; // too spammy
}
};
self.toasts.add(toasts::Toast {
kind,
text: msg,
options: toasts::ToastOptions::with_ttl_in_seconds(4.0),
});
}
}
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.try_recv() {
let msg = match msg.payload {
re_smart_channel::SmartMessagePayload::Msg(msg) => msg,
re_smart_channel::SmartMessagePayload::Quit(err) => {
if let Some(err) = err {
re_log::warn!("Data source {} has left unexpectedly: {err}", msg.source);
} else {
re_log::debug!("Data source {} has left", msg.source);
}
continue;
}
};
let store_id = msg.store_id();
let is_new_store = matches!(&msg, LogMsg::SetStoreInfo(_msg));
let store_db = store_hub.store_db_mut(store_id);
if store_db.data_source.is_none() {
store_db.data_source = Some((*channel_source).clone());
}
if let Err(err) = store_db.add(&msg) {
re_log::error!("Failed to add incoming msg: {err}");
};
if is_new_store && store_db.store_kind() == StoreKind::Recording {
// Do analytics after ingesting the new message,
// because thats when the `store_db.store_info` is set,
// which we use in the analytics call.
self.analytics.on_open_recording(store_db);
}
// 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.
if let LogMsg::SetStoreInfo(msg) = &msg {
match msg.info.store_id.kind {
StoreKind::Recording => {
re_log::debug!("Opening a new recording: {:?}", msg.info);
store_hub.set_recording_id(store_id.clone());
}
StoreKind::Blueprint => {
re_log::debug!("Opening a new blueprint: {:?}", msg.info);
store_hub.set_blueprint_for_app_id(
store_id.clone(),
msg.info.application_id.clone(),
);
}
}
}
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
}
}
}
fn purge_memory_if_needed(&mut self, store_hub: &mut StoreHub) {
re_tracing::profile_function!();
fn format_limit(limit: Option<i64>) -> String {
if let Some(bytes) = limit {
format_bytes(bytes as _)
} else {
"∞".to_owned()
}
}
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 {}, dropping oldest data.",
format_limit(limit.limit)
);
let fraction_to_purge = (minimum_fraction_to_purge + 0.2).clamp(0.25, 1.0);
re_log::trace!("RAM limit: {}", format_limit(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)
);
}
store_hub.purge_fraction_of_ram(fraction_to_purge);
self.state.cache.purge_memory();
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)
{
re_log::debug!(
"Freed up {} ({:.1}%)",
format_bytes(counted_diff as _),
100.0 * counted_diff as f32 / counted_before as f32
);
}
self.memory_panel.note_memory_purge();
}
}
/// Reset the viewer to how it looked the first time you ran it.
fn reset(&mut self, store_hub: &mut StoreHub, egui_ctx: &egui::Context) {
self.state = Default::default();
store_hub.clear_blueprint();
// Keep the style:
let style = egui_ctx.style();
egui_ctx.memory_mut(|mem| *mem = Default::default());
egui_ctx.set_style((*style).clone());
}
pub fn recording_db(&self) -> Option<&StoreDb> {
self.store_hub
.as_ref()
.and_then(|store_hub| store_hub.current_recording())
}
fn handle_dropping_files(&mut self, egui_ctx: &egui::Context) {
preview_files_being_dropped(egui_ctx);
let dropped_files = egui_ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
for file in dropped_files {
if let Some(bytes) = file.bytes {
// This is what we get on Web.
self.command_sender
.send_system(SystemCommand::LoadDataSource(DataSource::FileContents(
FileSource::DragAndDrop,
FileContents {
name: file.name.clone(),
bytes: bytes.clone(),
},
)));
continue;
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(path) = file.path {
self.command_sender
.send_system(SystemCommand::LoadDataSource(DataSource::FilePath(
FileSource::DragAndDrop,
path,
)));
}
}
}
/// This function will create an empty blueprint whenever the welcome screen should be
/// displayed.
///
/// The welcome screen can be displayed only when a blueprint is available (and no recording is
/// loaded). This function implements the heuristic which determines when the welcome screen
/// should show up.
fn should_show_welcome_screen(&mut self, store_hub: &StoreHub) -> bool {
// Don't show the welcome screen if we have actual data to display.
if store_hub.current_recording().is_some() || store_hub.selected_application_id().is_some()
{
return false;
}
// Don't show the welcome screen if the `--skip-welcome-screen` flag was used (e.g. by the
// Python SDK), until some data has been loaded and shown. This way, we *still* show the
// welcome screen when the user closes all recordings after, e.g., running a Python example.
if self.startup_options.skip_welcome_screen && !store_hub.was_recording_active() {
return false;
}
let sources = self.rx.sources();
if sources.is_empty() {
return true;
}
// Here, we use the type of Receiver as a proxy for which kind of workflow the viewer is
// being used in.
for source in sources {
match &*source {
// No need for a welcome screen - data is coming soon!
SmartChannelSource::File(_) | SmartChannelSource::RrdHttpStream { .. } => {
return false;
}
// The workflows associated with these sources typically do not require showing the
// welcome screen until after some recording have been loaded and then closed.
SmartChannelSource::RrdWebEventListener
| SmartChannelSource::Sdk
| SmartChannelSource::WsClient { .. } => {}
// This might be the trickiest case. When running the bare executable, we want to show
// the welcome screen (default, "new user" workflow). There are other case using Tcp
// where it's not the case, including Python/C++ SDKs and possibly other, advanced used,
// scenarios. In this cases, `--skip-welcome-screen` should be used.
SmartChannelSource::TcpServer { .. } => {
return true;
}
}
}
false
}
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
[0.0; 4] // transparent so we can get rounded corners when doing [`re_ui::CUSTOM_WINDOW_DECORATIONS`]
}
fn save(&mut self, storage: &mut dyn eframe::Storage) {
if self.startup_options.persist_state {
// Save the app state
eframe::set_value(storage, eframe::APP_KEY, &self.state);
// Save the blueprints
// TODO(#2579): implement web-storage for blueprints as well
if let Some(hub) = &mut self.store_hub {
match hub.gc_and_persist_app_blueprints() {
Ok(f) => f,
Err(err) => {
re_log::error!("Saving blueprints failed: {err}");
}
};
}
}
}
fn update(&mut self, egui_ctx: &egui::Context, frame: &mut eframe::Frame) {
let frame_start = Instant::now();
// Temporarily take the `StoreHub` out of the Viewer so it doesn't interfere with mutability
let mut store_hub = self.store_hub.take().unwrap();
#[cfg(not(target_arch = "wasm32"))]
if let Some(resolution_in_points) = self.startup_options.resolution_in_points.take() {
frame.set_window_size(resolution_in_points.into());
}
#[cfg(not(target_arch = "wasm32"))]
if self.screenshotter.update(egui_ctx, frame).quit {
frame.close();
return;
}
if self.startup_options.memory_limit.limit.is_none() {
// 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(promise) = &self.open_files_promise {
if let Some(files) = promise.ready() {