re_viewer_context 0.32.0-alpha.1

Rerun viewer state that is shared with the viewer's code components.
Documentation
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
use re_entity_db::{EntityDb, InstancePath};
use re_log_types::{ComponentPath, DataPath, EntityPath, EntryId, TableId};
use re_sdk_types::blueprint::components::VisualizerInstructionId;

use crate::{BlueprintId, ContainerId, Contents, ViewId};
use crate::{blueprint_id::ViewIdRegistry, open_url::EXAMPLES_ORIGIN};

/// `Item` state for a dataresult interaction, i.e. when hovering or selecting an item in a view's data results.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DataResultInteractionAddress {
    /// The view in which the interaction happened.
    pub view_id: ViewId,

    /// The instance path of the entity or instance that is being interacted with.
    ///
    /// Note that this may be an individual instance or the entire entity if the instance index is [`re_log_types::Instance::ALL`].
    pub instance_path: InstancePath,

    /// Optional visualizer instruction id through which we're interacting with this data-result.
    ///
    /// This can be used for more fine grained highlights.
    /// If not present, we generally assume we're interacting with the dataresult as a whole.
    pub visualizer: Option<VisualizerInstructionId>,
}

impl DataResultInteractionAddress {
    /// Creates a new address for an entity path (all instances, no visualizer).
    pub fn from_entity_path(view_id: ViewId, entity_path: EntityPath) -> Self {
        Self {
            view_id,
            instance_path: InstancePath::entity_all(entity_path),
            visualizer: None,
        }
    }

    /// Returns a new address that refers to the entire entity (all instances),
    /// preserving the view and visualizer.
    pub fn as_entity_all(&self) -> Self {
        Self {
            view_id: self.view_id,
            instance_path: InstancePath::entity_all(self.instance_path.entity_path.clone()),
            visualizer: self.visualizer,
        }
    }
}

/// One "thing" in the UI.
///
/// This is the granularity of what is selectable and hoverable.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Item {
    /// Select a specific application, to see which recordings and blueprints are loaded for it.
    AppId(re_log_types::ApplicationId),

    /// A place where data comes from, e.g. the path to a .rrd or a gRPC URL.
    DataSource(re_log_channel::LogSource),

    /// A recording (or blueprint)
    StoreId(re_log_types::StoreId),

    /// A table (i.e. a dataframe)
    TableId(TableId),

    /// An entity or instance from the chunk store.
    InstancePath(InstancePath),

    /// A component of an entity from the chunk store.
    ComponentPath(ComponentPath),

    /// A viewport container.
    Container(ContainerId),

    /// A viewport view.
    View(ViewId),

    /// An entity or instance in the context of a view's data results.
    DataResult(DataResultInteractionAddress),

    /// An entry within a Redap server's hierarchy: dataset, table, or folder (group).
    RedapEntry {
        origin: re_uri::Origin,
        kind: RedapEntryKind,
    },

    /// A Redap server.
    RedapServer(re_uri::Origin),
}

/// The kind of node addressed by [`Item::RedapEntry`].
///
/// Dataset-vs-table distinction lives at the data layer (authoritative: the server) rather than
/// here — at this level the entry is identified by [`EntryId`] only.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RedapEntryKind {
    /// A concrete entry (table or dataset), identified by its [`EntryId`].
    Entry(EntryId),

    /// A folder (group) in the server's dataset hierarchy, identified by a
    /// dot-separated path prefix (e.g. `"project.subdir"`).
    Folder(String),
}

impl RedapEntryKind {
    /// Returns the [`EntryId`] if this kind refers to a concrete entry.
    pub fn entry_id(&self) -> Option<EntryId> {
        match self {
            Self::Entry(id) => Some(*id),
            Self::Folder(_) => None,
        }
    }
}

impl Item {
    /// The example page / welcome screen
    pub fn welcome_page() -> Self {
        Self::RedapServer(EXAMPLES_ORIGIN.clone())
    }

    pub fn redap_origin(&self) -> Option<&re_uri::Origin> {
        match self {
            Self::RedapServer(origin) | Self::RedapEntry { origin, .. } => Some(origin),
            _ => None,
        }
    }

    pub fn view_id(&self) -> Option<BlueprintId<ViewIdRegistry>> {
        match self {
            Self::AppId(_)
            | Self::DataSource(_)
            | Self::StoreId(_)
            | Self::TableId(_)
            | Self::InstancePath(_)
            | Self::ComponentPath(_)
            | Self::Container(_)
            | Self::RedapEntry { .. }
            | Self::RedapServer(_) => None,
            Self::View(view_id) => Some(*view_id),
            Self::DataResult(data_result) => Some(data_result.view_id),
        }
    }

    pub fn entity_path(&self) -> Option<&EntityPath> {
        match self {
            Self::AppId(_)
            | Self::TableId(_)
            | Self::DataSource(_)
            | Self::View(_)
            | Self::Container(_)
            | Self::StoreId(_)
            | Self::RedapServer(_)
            | Self::RedapEntry { .. } => None,

            Self::ComponentPath(component_path) => Some(&component_path.entity_path),

            Self::InstancePath(instance_path) => Some(&instance_path.entity_path),
            Self::DataResult(data_result) => Some(&data_result.instance_path.entity_path),
        }
    }

    /// Is this item compatible with the given [`crate::Route`]?
    ///
    /// For example, a recording or redap entry that belongs to a different
    /// route than the currently active one is incompatible.
    pub fn is_compatible_with_route(&self, route: &crate::Route) -> bool {
        if let Self::StoreId(store_id) = self
            && let Some(route_recording_id) = route.recording_id()
            && store_id != route_recording_id
        {
            return false;
        }

        if let Some(origin) = self.redap_origin()
            && let Some(route_origin) = route.item().as_ref().and_then(|item| item.redap_origin())
            && origin != route_origin
        {
            return false;
        }

        true
    }

    /// Converts this item to a data path if possible.
    pub fn to_data_path(&self) -> Option<DataPath> {
        match self {
            Self::AppId(_)
            | Self::TableId(_)
            | Self::DataSource(_)
            | Self::View(_)
            | Self::Container(_)
            | Self::StoreId(_)
            | Self::RedapServer(_)
            | Self::RedapEntry { .. } => None,

            Self::ComponentPath(component_path) => Some(DataPath {
                entity_path: component_path.entity_path.clone(),
                instance: None,
                component: Some(component_path.component),
            }),

            Self::InstancePath(instance_path) => Some(DataPath {
                entity_path: instance_path.entity_path.clone(),
                instance: Some(instance_path.instance),
                component: None,
            }),
            Self::DataResult(data_result) => Some(DataPath {
                entity_path: data_result.instance_path.entity_path.clone(),
                instance: Some(data_result.instance_path.instance),
                component: None,
            }),
        }
    }
}

impl From<ViewId> for Item {
    #[inline]
    fn from(view_id: ViewId) -> Self {
        Self::View(view_id)
    }
}

impl From<ComponentPath> for Item {
    #[inline]
    fn from(component_path: ComponentPath) -> Self {
        Self::ComponentPath(component_path)
    }
}

impl From<EntityPath> for Item {
    #[inline]
    fn from(entity_path: EntityPath) -> Self {
        Self::InstancePath(InstancePath::from(entity_path))
    }
}

impl From<InstancePath> for Item {
    #[inline]
    fn from(instance_path: InstancePath) -> Self {
        Self::InstancePath(instance_path)
    }
}

impl From<re_uri::EntryUri> for Item {
    fn from(uri: re_uri::EntryUri) -> Self {
        Self::RedapEntry {
            origin: uri.origin,
            kind: RedapEntryKind::Entry(uri.entry_id),
        }
    }
}

impl From<Contents> for Item {
    #[inline]
    fn from(contents: Contents) -> Self {
        match contents {
            Contents::Container(container_id) => Self::Container(container_id),
            Contents::View(view_id) => Self::View(view_id),
        }
    }
}

impl std::str::FromStr for Item {
    type Err = re_log_types::PathParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let DataPath {
            entity_path,
            instance,
            component,
        } = DataPath::from_str(s)?;

        match (instance, component) {
            (Some(instance), Some(_component_descriptor)) => {
                // TODO(emilk): support selecting a specific component of a specific instance.
                Err(re_log_types::PathParseError::UnexpectedInstance(instance))
            }
            (Some(instance), None) => Ok(Self::InstancePath(InstancePath::instance(
                entity_path,
                instance,
            ))),
            (None, Some(component)) => Ok(Self::ComponentPath(ComponentPath {
                entity_path,
                component,
            })),
            (None, None) => Ok(Self::InstancePath(InstancePath::entity_all(entity_path))),
        }
    }
}

impl std::fmt::Debug for Item {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AppId(app_id) => app_id.fmt(f),
            Self::TableId(table_id) => table_id.fmt(f),
            Self::DataSource(data_source) => data_source.fmt(f),
            Self::StoreId(store_id) => store_id.fmt(f),
            Self::ComponentPath(s) => s.fmt(f),
            Self::View(s) => write!(f, "{s:?}"),
            Self::InstancePath(path) => write!(f, "{path}"),
            Self::DataResult(data_result) => {
                write!(
                    f,
                    "({:?}, {})",
                    data_result.view_id, data_result.instance_path
                )
            }
            Self::Container(tile_id) => write!(f, "(tile: {tile_id:?})"),
            Self::RedapEntry { origin, kind } => match kind {
                RedapEntryKind::Entry(id) => write!(f, "RedapEntry({origin}, {id})"),
                RedapEntryKind::Folder(path_prefix) => {
                    write!(f, "RedapFolder({origin}, {path_prefix})")
                }
            },
            Self::RedapServer(server) => write!(f, "{server}"),
        }
    }
}

impl Item {
    pub fn kind(&self) -> &'static str {
        match self {
            Self::AppId(_) => "Application",
            Self::TableId(_) => "Table",
            Self::DataSource(_) => "Data source",
            Self::StoreId(store_id) => match store_id.kind() {
                re_log_types::StoreKind::Recording => "Recording ID",
                re_log_types::StoreKind::Blueprint => "Blueprint ID",
            },
            Self::InstancePath(instance_path) => instance_path.kind(),
            Self::ComponentPath(_) => "Entity component",
            Self::View(_) => "View",
            Self::Container(_) => "Container",
            Self::DataResult(data_result) => {
                if data_result.instance_path.instance.is_specific() {
                    "Data result instance"
                } else {
                    "Data result entity"
                }
            }
            Self::RedapEntry { kind, .. } => match kind {
                RedapEntryKind::Entry(_) => "Redap entry",
                RedapEntryKind::Folder(_) => "Redap folder",
            },
            Self::RedapServer(_) => "Redap server",
        }
    }
}

/// If the given item refers to the first element of an instance with a single element, resolve to a unindexed entity path.
pub fn resolve_mono_instance_path_item(
    entity_db: &EntityDb,
    query: &re_chunk_store::LatestAtQuery,
    item: &Item,
) -> Item {
    // Resolve to entity path if there's only a single instance.
    match item {
        Item::InstancePath(instance_path) => {
            Item::InstancePath(resolve_mono_instance_path(entity_db, query, instance_path))
        }
        Item::DataResult(data_result) => Item::DataResult(DataResultInteractionAddress {
            instance_path: resolve_mono_instance_path(entity_db, query, &data_result.instance_path),
            ..data_result.clone()
        }),
        Item::AppId(_)
        | Item::TableId(_)
        | Item::DataSource(_)
        | Item::StoreId(_)
        | Item::ComponentPath(_)
        | Item::View(_)
        | Item::Container(_)
        | Item::RedapEntry { .. }
        | Item::RedapServer(_) => item.clone(),
    }
}

/// If the given path refers to the first element of an instance with a single element, resolve to a unindexed entity path.
pub fn resolve_mono_instance_path(
    entity_db: &EntityDb,
    query: &re_chunk_store::LatestAtQuery,
    instance: &re_entity_db::InstancePath,
) -> re_entity_db::InstancePath {
    re_tracing::profile_function!();

    if instance.instance.get() == 0 {
        let engine = entity_db.storage_engine();

        // NOTE: While we normally frown upon direct queries to the datastore, `all_components` is fine.
        let Some(components) = engine
            .store()
            .all_components_on_timeline(&query.timeline(), &instance.entity_path)
        else {
            // No components at all, return unindexed entity.
            return re_entity_db::InstancePath::entity_all(instance.entity_path.clone());
        };

        #[expect(clippy::iter_over_hash_type)]
        for component in components {
            if let Some(array) = engine
                .cache()
                .latest_at(query, &instance.entity_path, [component])
                .component_batch_raw(component)
                && array.len() > 1
            {
                return instance.clone();
            }
        }

        // All instances had only a single element or less, resolve to unindexed entity.
        return re_entity_db::InstancePath::entity_all(instance.entity_path.clone());
    }

    instance.clone()
}