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
use std::collections::BTreeMap;
use std::sync::Arc;

use egui_extras::{Column, TableRow};
use itertools::{Either, Itertools};

use re_chunk_store::{ChunkStore, LatestAtQuery, RangeQuery};
use re_log_types::{ResolvedTimeRange, StoreKind, TimeType, TimeZone, Timeline, TimelineName};
use re_ui::{list_item, UiExt as _};
use re_viewer_context::ViewerContext;

use crate::chunk_list_mode::{ChunkListMode, ChunkListQueryMode};
use crate::chunk_ui::ChunkUi;
use crate::sort::{sortable_column_header_ui, SortColumn, SortDirection};

/// Any column that can be sorted.
#[derive(Default, Clone, Copy, PartialEq)]
enum ChunkListColumn {
    #[default]
    ChunkId,
    EntityPath,
    RowCount,
    Timeline(TimelineName),
}

type ChunkListSortColumn = SortColumn<ChunkListColumn>;

impl ChunkListColumn {
    pub(crate) fn ui(&self, ui: &mut egui::Ui, sort_column: &mut ChunkListSortColumn) {
        match self {
            Self::ChunkId => sortable_column_header_ui(self, ui, sort_column, "Chunk ID"),
            Self::EntityPath => sortable_column_header_ui(self, ui, sort_column, "Entity"),
            Self::RowCount => sortable_column_header_ui(self, ui, sort_column, "# rows"),
            Self::Timeline(timeline_name) => {
                sortable_column_header_ui(self, ui, sort_column, timeline_name.as_str());
            }
        }
    }
}

/// Browser UI for [`re_chunk_store::ChunkStore`].
pub struct DatastoreUi {
    store_kind: StoreKind,
    focused_chunk: Option<ChunkUi>,

    chunk_list_mode: ChunkListMode,

    chunk_list_sort_column: ChunkListSortColumn,

    // filters
    entity_path_filter: String,
    component_filter: String,
}

impl Default for DatastoreUi {
    fn default() -> Self {
        Self {
            store_kind: StoreKind::Recording,
            focused_chunk: None,
            chunk_list_mode: ChunkListMode::default(),
            chunk_list_sort_column: ChunkListSortColumn::default(),
            entity_path_filter: String::new(),
            component_filter: String::new(),
        }
    }
}

impl DatastoreUi {
    /// Show the ui.
    pub fn ui(
        &mut self,
        ctx: &ViewerContext<'_>,
        ui: &mut egui::Ui,
        datastore_ui_active: &mut bool,
        time_zone: TimeZone,
    ) {
        egui::Frame {
            inner_margin: egui::Margin::same(5.0),
            ..Default::default()
        }
        .show(ui, |ui| {
            let exit_focused_chunk = if let Some(focused_chunk) = &mut self.focused_chunk {
                focused_chunk.ui(ui, time_zone)
            } else {
                self.chunk_store_ui(
                    ui,
                    match self.store_kind {
                        StoreKind::Recording => ctx.recording_engine(),
                        StoreKind::Blueprint => ctx.blueprint_engine(),
                    }
                    .store(),
                    datastore_ui_active,
                    time_zone,
                );

                false
            };

            if exit_focused_chunk {
                self.focused_chunk = None;
            }
        });
    }

    fn chunk_store_ui(
        &mut self,
        ui: &mut egui::Ui,
        chunk_store: &ChunkStore,
        datastore_ui_active: &mut bool,
        time_zone: TimeZone,
    ) {
        let should_copy_chunk = self.chunk_store_info_ui(ui, chunk_store, datastore_ui_active);

        // Each of these must be a column that contains the corresponding time range.
        let all_timelines = chunk_store.all_timelines();

        self.chunk_list_mode.ui(ui, chunk_store, time_zone);

        //
        // Collect chunks based on query mode
        //

        let chunk_iterator = match &self.chunk_list_mode {
            ChunkListMode::All => Either::Left(chunk_store.iter_chunks().map(Arc::clone)),
            ChunkListMode::Query {
                timeline,
                entity_path,
                component_name,
                query: ChunkListQueryMode::LatestAt(at),
                ..
            } => Either::Right(
                chunk_store
                    .latest_at_relevant_chunks(
                        &LatestAtQuery::new(*timeline, *at),
                        entity_path,
                        *component_name,
                    )
                    .into_iter(),
            ),
            ChunkListMode::Query {
                timeline,
                entity_path,
                component_name,
                query: ChunkListQueryMode::Range(range),
                ..
            } => Either::Right(
                chunk_store
                    .range_relevant_chunks(
                        &RangeQuery::new(*timeline, *range),
                        entity_path,
                        *component_name,
                    )
                    .into_iter(),
            ),
        };

        //
        // Filters
        //

        ui.horizontal(|ui| {
            ui.spacing_mut().text_edit_width = 120.0;

            ui.label("Filter:").on_hover_text(
                "Filter the chunk list by entity path and/or component. Filtering is \
                case-insensitive text-based.",
            );
            ui.label("entity:");
            ui.text_edit_singleline(&mut self.entity_path_filter);

            ui.label("component:");
            ui.text_edit_singleline(&mut self.component_filter);

            if ui.small_icon_button(&re_ui::icons::CLOSE).clicked() {
                self.entity_path_filter = String::new();
                self.component_filter = String::new();
            }
        });

        let chunk_iterator = if self.entity_path_filter.is_empty() {
            Either::Left(chunk_iterator)
        } else {
            let entity_path_filter = self.entity_path_filter.to_lowercase();
            Either::Right(chunk_iterator.filter(move |chunk| {
                chunk
                    .entity_path()
                    .to_string()
                    .to_lowercase()
                    .contains(&entity_path_filter)
            }))
        };

        let chunk_iterator = if self.component_filter.is_empty() {
            Either::Left(chunk_iterator)
        } else {
            let component_filter = self.component_filter.to_lowercase();
            Either::Right(chunk_iterator.filter(move |chunk| {
                chunk
                    .components()
                    .keys()
                    .any(|name| name.short_name().to_lowercase().contains(&component_filter))
            }))
        };

        let mut chunks = chunk_iterator.collect_vec();

        //
        // Sort
        //

        match &self.chunk_list_sort_column.column {
            ChunkListColumn::ChunkId => {} // already sorted by row IDs
            ChunkListColumn::EntityPath => {
                chunks.sort_by_key(|chunk| chunk.entity_path().to_string());
            }
            ChunkListColumn::RowCount => chunks.sort_by_key(|chunk| chunk.num_rows()),
            ChunkListColumn::Timeline(timeline_name) => chunks.sort_by_key(|chunk| {
                chunk
                    .timelines()
                    .iter()
                    .find(|(timeline, _)| timeline.name() == timeline_name)
                    .map_or(re_log_types::TimeInt::MIN, |(_, time_column)| {
                        time_column.time_range().min()
                    })
            }),
        }

        if self.chunk_list_sort_column.direction == SortDirection::Descending {
            chunks.reverse();
        }

        //
        // Copy to clipboard
        //

        if should_copy_chunk {
            //TODO(#7282): make sure the output is not dependant on the parent terminal's width
            let s = chunks.iter().map(|chunk| chunk.to_string()).join("\n\n");
            ui.output_mut(|o| o.copied_text = s);
        }

        //
        // Table
        //

        let header_ui = |mut row: TableRow<'_, '_>| {
            row.col(|ui| {
                ChunkListColumn::ChunkId.ui(ui, &mut self.chunk_list_sort_column);
            });

            row.col(|ui| {
                ChunkListColumn::EntityPath.ui(ui, &mut self.chunk_list_sort_column);
            });

            row.col(|ui| {
                ChunkListColumn::RowCount.ui(ui, &mut self.chunk_list_sort_column);
            });

            for timeline in &all_timelines {
                row.col(|ui| {
                    ChunkListColumn::Timeline(*timeline.name())
                        .ui(ui, &mut self.chunk_list_sort_column);
                });
            }

            row.col(|ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);

                ui.strong("Components");
            });
        };

        let row_ui = |mut row: TableRow<'_, '_>| {
            let chunk = &chunks[row.index()];

            row.col(|ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);

                if ui.button(chunk.id().to_string()).clicked() {
                    self.focused_chunk = Some(ChunkUi::new(chunk));
                }
            });

            row.col(|ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);

                ui.label(chunk.entity_path().to_string());
            });

            row.col(|ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);

                ui.label(chunk.num_rows().to_string());
            });

            let timeline_ranges = chunk
                .timelines()
                .iter()
                .map(|(timeline, time_column)| (timeline, time_column.time_range()))
                .collect::<BTreeMap<_, _>>();

            for timeline in &all_timelines {
                row.col(|ui| {
                    ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);

                    if let Some(time_range) = timeline_ranges.get(timeline) {
                        ui.label(format_time_range(timeline, time_range, time_zone));
                    } else {
                        ui.label("-");
                    };
                });
            }

            row.col(|ui| {
                ui.label(
                    chunk
                        .components()
                        .keys()
                        .map(|name| name.short_name())
                        .join(", "),
                );
            });
        };

        egui::ScrollArea::horizontal()
            .auto_shrink([false, false])
            .show(ui, |ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);

                let table_builder = egui_extras::TableBuilder::new(ui)
                    .id_salt(chunk_store.id())
                    .columns(
                        Column::auto_with_initial_suggestion(200.0).clip(true),
                        4 + all_timelines.len(),
                    )
                    .resizable(true)
                    .vscroll(true)
                    .auto_shrink([false, false])
                    .striped(true);

                table_builder
                    .header(re_ui::DesignTokens::table_line_height(), header_ui)
                    .body(|body| {
                        body.rows(
                            re_ui::DesignTokens::table_line_height(),
                            chunks.len(),
                            row_ui,
                        );
                    });
            });
    }

    // copy the (filtered) chunks to clipboard if this returns true
    fn chunk_store_info_ui(
        &mut self,
        ui: &mut egui::Ui,
        chunk_store: &ChunkStore,
        datastore_ui_active: &mut bool,
    ) -> bool {
        let mut should_copy_chunks = false;

        ui.horizontal(|ui| {
            ui.selectable_toggle(|ui| {
                ui.selectable_value(&mut self.store_kind, StoreKind::Recording, "Recording")
                    .on_hover_text("Display the current recording's data store");
                ui.selectable_value(&mut self.store_kind, StoreKind::Blueprint, "Blueprint")
                    .on_hover_text("Display the current recording's blueprint store");
            });

            if ui
                .button("Close")
                .on_hover_text("Close the datastore browser")
                .clicked()
            {
                *datastore_ui_active = false;
            }

            if ui
                .button("Copy")
                .on_hover_text("Copy the currently listed chunks as text")
                .clicked()
            {
                should_copy_chunks = true;
            }
        });

        list_item::list_item_scope(ui, "chunk store info", |ui| {
            let stats = chunk_store.stats().total();
            ui.list_item_collapsible_noninteractive_label("Info", false, |ui| {
                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Store ID")
                        .value_text(chunk_store.id().to_string()),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Chunk count")
                        .value_text(stats.num_chunks.to_string()),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Heap size")
                        .value_text(re_format::format_bytes(stats.total_size_bytes as f64)),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Rows").value_text(stats.num_rows.to_string()),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Events")
                        .value_text(stats.num_events.to_string()),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Generation")
                        .value_text(format!("{:?}", chunk_store.generation())),
                );
            });

            ui.list_item_collapsible_noninteractive_label("Config", false, |ui| {
                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Enable changelog")
                        .value_bool(chunk_store.config().enable_changelog),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Chunk max byte").value_text(
                        re_format::format_bytes(chunk_store.config().chunk_max_bytes as f64),
                    ),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Chunk max rows")
                        .value_text(re_format::format_uint(chunk_store.config().chunk_max_rows)),
                );

                ui.list_item_flat_noninteractive(
                    list_item::PropertyContent::new("Chunk max rows (unsorted)").value_text(
                        re_format::format_uint(chunk_store.config().chunk_max_rows_if_unsorted),
                    ),
                );
            });
        });

        should_copy_chunks
    }
}

fn format_time_range(
    timeline: &Timeline,
    time_range: &ResolvedTimeRange,
    time_zone: TimeZone,
) -> String {
    if time_range.min() == time_range.max() {
        timeline.typ().format(time_range.min(), time_zone)
    } else {
        format!(
            "{} ({})",
            timeline.format_time_range(time_range, time_zone),
            match timeline.typ() {
                TimeType::Time => {
                    format!(
                        "{}s",
                        re_format::format_f64(
                            (time_range.max().as_f64() - time_range.min().as_f64())
                                / 1_000_000_000.0
                        )
                    )
                }
                TimeType::Sequence => {
                    format!("{} ticks", re_format::format_uint(time_range.abs_length()))
                }
            }
        )
    }
}