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
use re_chunk_store::LatestAtQuery;
use re_entity_db::{external::re_query::LatestAtResults, EntityDb};
use re_log_types::EntityPath;
use re_types::{
    external::arrow2, Archetype, ArchetypeName, ComponentBatch, ComponentName, DeserializationError,
};
use re_viewer_context::{
    external::re_entity_db::EntityTree, ComponentFallbackError, ComponentFallbackProvider,
    QueryContext, SpaceViewId, SpaceViewSystemExecutionError, ViewerContext,
};

#[derive(thiserror::Error, Debug)]
pub enum ViewPropertyQueryError {
    #[error(transparent)]
    SerializationError(#[from] re_types::DeserializationError),

    #[error(transparent)]
    ComponentFallbackError(#[from] ComponentFallbackError),
}

impl From<ViewPropertyQueryError> for SpaceViewSystemExecutionError {
    fn from(val: ViewPropertyQueryError) -> Self {
        match val {
            ViewPropertyQueryError::SerializationError(err) => err.into(),
            ViewPropertyQueryError::ComponentFallbackError(err) => err.into(),
        }
    }
}

/// Utility for querying view properties.
pub struct ViewProperty {
    /// Entity path in the blueprint store where all components of this view property archetype are
    /// stored.
    pub blueprint_store_path: EntityPath,

    archetype_name: ArchetypeName,
    component_names: Vec<ComponentName>,
    query_results: LatestAtResults,
    blueprint_query: LatestAtQuery,
}

impl ViewProperty {
    /// Query a specific view property for a given view.
    pub fn from_archetype<A: Archetype>(
        blueprint_db: &EntityDb,
        blueprint_query: &LatestAtQuery,
        view_id: SpaceViewId,
    ) -> Self {
        Self::from_archetype_impl(
            blueprint_db,
            blueprint_query.clone(),
            view_id,
            A::name(),
            A::all_components().as_ref(),
        )
    }

    fn from_archetype_impl(
        blueprint_db: &EntityDb,
        blueprint_query: LatestAtQuery,
        space_view_id: SpaceViewId,
        archetype_name: ArchetypeName,
        component_names: &[ComponentName],
    ) -> Self {
        let blueprint_store_path =
            entity_path_for_view_property(space_view_id, blueprint_db.tree(), archetype_name);

        let query_results = blueprint_db.latest_at(
            &blueprint_query,
            &blueprint_store_path,
            component_names.iter().copied(),
        );

        Self {
            blueprint_store_path,
            archetype_name,
            query_results,
            component_names: component_names.to_vec(),
            blueprint_query,
        }
    }

    /// Get the value of a specific component or its fallback if the component is not present.
    // TODO(andreas): Unfortunately we can't use TypedComponentFallbackProvider here because it may not be implemented for all components of interest.
    // This sadly means that there's a bit of unnecessary back and forth between arrow array and untyped that could be avoided otherwise.
    pub fn component_or_fallback<C: re_types::Component + Default>(
        &self,
        ctx: &ViewerContext<'_>,
        fallback_provider: &dyn ComponentFallbackProvider,
        view_state: &dyn re_viewer_context::SpaceViewState,
    ) -> Result<C, ViewPropertyQueryError> {
        self.component_array_or_fallback::<C>(ctx, fallback_provider, view_state)?
            .into_iter()
            .next()
            .ok_or(ComponentFallbackError::UnexpectedEmptyFallback.into())
    }

    /// Get the component array for a given type or its fallback if the component is not present or empty.
    pub fn component_array_or_fallback<C: re_types::Component + Default>(
        &self,
        ctx: &ViewerContext<'_>,
        fallback_provider: &dyn ComponentFallbackProvider,
        view_state: &dyn re_viewer_context::SpaceViewState,
    ) -> Result<Vec<C>, ViewPropertyQueryError> {
        let component_name = C::name();
        C::from_arrow(
            self.component_or_fallback_raw(ctx, component_name, fallback_provider, view_state)
                .as_ref(),
        )
        .map_err(|err| err.into())
    }

    /// Get a single component or None, not using any fallbacks.
    #[inline]
    pub fn component_or_empty<C: re_types::Component>(
        &self,
    ) -> Result<Option<C>, DeserializationError> {
        self.component_array()
            .map(|v| v.and_then(|v| v.into_iter().next()))
    }

    /// Get the component array for a given type, not using any fallbacks.
    pub fn component_array<C: re_types::Component>(
        &self,
    ) -> Result<Option<Vec<C>>, DeserializationError> {
        let component_name = C::name();
        self.component_raw(component_name)
            .map(|raw| C::from_arrow(raw.as_ref()))
            .transpose()
    }

    /// Get the component array for a given type or an empty array, not using any fallbacks.
    pub fn component_array_or_empty<C: re_types::Component>(
        &self,
    ) -> Result<Vec<C>, DeserializationError> {
        self.component_array()
            .map(|value| value.unwrap_or_default())
    }

    pub fn component_row_id(&self, component_name: ComponentName) -> Option<re_chunk::RowId> {
        self.query_results
            .get(&component_name)
            .and_then(|unit| unit.row_id())
    }

    pub fn component_raw(
        &self,
        component_name: ComponentName,
    ) -> Option<Box<dyn arrow2::array::Array>> {
        self.query_results
            .get(&component_name)
            .and_then(|unit| unit.component_batch_raw(&component_name))
    }

    fn component_or_fallback_raw(
        &self,
        ctx: &ViewerContext<'_>,
        component_name: ComponentName,
        fallback_provider: &dyn ComponentFallbackProvider,
        view_state: &dyn re_viewer_context::SpaceViewState,
    ) -> Box<dyn arrow2::array::Array> {
        if let Some(value) = self.component_raw(component_name) {
            if value.len() > 0 {
                return value;
            }
        }
        fallback_provider.fallback_for(&self.query_context(ctx, view_state), component_name)
    }

    /// Save change to a blueprint component.
    pub fn save_blueprint_component(
        &self,
        ctx: &ViewerContext<'_>,
        components: &dyn ComponentBatch,
    ) {
        ctx.save_blueprint_component(&self.blueprint_store_path, components);
    }

    /// Clears a blueprint component.
    pub fn clear_blueprint_component<C: re_types::Component>(&self, ctx: &ViewerContext<'_>) {
        ctx.clear_blueprint_component_by_name(&self.blueprint_store_path, C::name());
    }

    /// Resets a blueprint component to the value it had in the default blueprint.
    pub fn reset_blueprint_component<C: re_types::Component>(&self, ctx: &ViewerContext<'_>) {
        ctx.reset_blueprint_component_by_name(&self.blueprint_store_path, C::name());
    }

    /// Resets all components to the values they had in the default blueprint.
    pub fn reset_all_components(&self, ctx: &ViewerContext<'_>) {
        // Don't use `self.query_results.components.keys()` since it may already have some components missing since they didn't show up in the query.
        for &component_name in &self.component_names {
            ctx.reset_blueprint_component_by_name(&self.blueprint_store_path, component_name);
        }
    }

    /// Resets all components to empty values, i.e. the fallback.
    pub fn reset_all_components_to_empty(&self, ctx: &ViewerContext<'_>) {
        for &component_name in self.query_results.components.keys() {
            ctx.clear_blueprint_component_by_name(&self.blueprint_store_path, component_name);
        }
    }

    /// Returns whether any property is non-empty.
    pub fn any_non_empty(&self) -> bool {
        self.query_results.components.keys().any(|name| {
            self.component_raw(*name)
                .map_or(false, |raw| !raw.is_empty())
        })
    }

    /// Create a query context for this view property.
    pub fn query_context<'a>(
        &'a self,
        viewer_ctx: &'a ViewerContext<'_>,
        view_state: &'a dyn re_viewer_context::SpaceViewState,
    ) -> QueryContext<'a> {
        QueryContext {
            viewer_ctx,
            target_entity_path: &self.blueprint_store_path,
            archetype_name: Some(self.archetype_name),
            query: &self.blueprint_query,
            view_state,
            view_ctx: None,
        }
    }
}

/// Entity path in the blueprint store where all components of the given view property archetype are
/// stored.
pub fn entity_path_for_view_property(
    space_view_id: SpaceViewId,
    _blueprint_entity_tree: &EntityTree,
    archetype_name: ArchetypeName,
) -> EntityPath {
    // TODO(andreas,jleibs):
    // We want to search the subtree for occurrences of the property archetype here.
    // Only if none is found we make up a new (standardized) path.
    // There's some nuances to figure out what happens when we find the archetype several times.
    // Also, we need to specify what it means to "find" the archetype (likely just matching the indicator?).
    let space_view_blueprint_path = space_view_id.as_entity_path();

    // Use short_name instead of full_name since full_name has dots and looks too much like an indicator component.
    space_view_blueprint_path.join(&EntityPath::from_single_string(archetype_name.short_name()))
}