indicatrix-cut 0.2.0

Desktop faceting-design editor: library browsing, spectral 3D rendering, material retargeting, and a solid inspection view.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use crate::{
    DiagramItem, LibraryModel, MainWindow,
    bridge::library::source::{self as library_source, LibrarySource},
    settings::WorkerSettings,
};
use anyhow::Result;
use indicatrix_net::library::{
    DesignSummary, LibraryRequest, LibraryResponse, PerformanceAggregateWire, PerformanceBoundWire,
    PerformanceFilterWire, PerformanceMetricWire, RangeFilterWire,
};
use indicatrix_vault::{
    db::sqlite::Database,
    model::{
        entry::DiagramListItem,
        filter::RangeFilter,
        performance::{
            PerformanceAggregate, PerformanceBound, PerformanceFilter, PerformanceMetric,
        },
    },
};
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use std::sync::{Arc, Mutex};
use tracing::error;

/// A slider value that sits exactly on its data-bounds edge means "not filtering on
/// this side" -- returns `None` so `search_diagrams` skips the predicate entirely
/// (which also means rows with no value at all for that attribute stay visible, same
/// as the unfiltered "All" state of the existing shape/gear dropdowns). Any other
/// value is an active bound.
fn active_bound(value: f32, bound_edge: f32) -> Option<f64> {
    let moved_off_edge = (value - bound_edge).abs() >= 1e-6;
    moved_off_edge.then_some(f64::from(value))
}

/// Builds the `RangeFilter` to hand to `search_diagrams`.
///
/// Reads the four range-filter sliders' current min/max values, the RI centre+
/// tolerance filter, the "show ignored" toggle, and every active tilt-performance
/// filter row off `ui`. See `active_bound` for what makes a min/max bound "active"
/// versus effectively unset.
#[must_use]
pub fn read_range_filter(ui: &MainWindow) -> RangeFilter {
    RangeFilter {
        ri_min: active_bound(
            ui.global::<LibraryModel>().get_ri_filter_min(),
            ui.global::<LibraryModel>().get_ri_bounds_min(),
        ),
        ri_max: active_bound(
            ui.global::<LibraryModel>().get_ri_filter_max(),
            ui.global::<LibraryModel>().get_ri_bounds_max(),
        ),
        lw_min: active_bound(
            ui.global::<LibraryModel>().get_lw_filter_min(),
            ui.global::<LibraryModel>().get_lw_bounds_min(),
        ),
        lw_max: active_bound(
            ui.global::<LibraryModel>().get_lw_filter_max(),
            ui.global::<LibraryModel>().get_lw_bounds_max(),
        ),
        volume_min: active_bound(
            ui.global::<LibraryModel>().get_volume_filter_min(),
            ui.global::<LibraryModel>().get_volume_bounds_min(),
        ),
        volume_max: active_bound(
            ui.global::<LibraryModel>().get_volume_filter_max(),
            ui.global::<LibraryModel>().get_volume_bounds_max(),
        ),
        facets_min: active_bound(
            ui.global::<LibraryModel>().get_facets_filter_min(),
            ui.global::<LibraryModel>().get_facets_bounds_min(),
        )
        .map(|v| v.round() as i64),
        facets_max: active_bound(
            ui.global::<LibraryModel>().get_facets_filter_max(),
            ui.global::<LibraryModel>().get_facets_bounds_max(),
        )
        .map(|v| v.round() as i64),
        // A separate RI band, `[center - tolerance, center + tolerance]`, composing
        // with `ri_min`/`ri_max` above by intersection -- see
        // `RangeFilter::ri_tolerance`'s doc comment. `None` whenever the panel's
        // toggle is off, same convention as `active_bound`.
        ri_tolerance: ui
            .global::<LibraryModel>()
            .get_ri_tolerance_enabled()
            .then(|| {
                (
                    f64::from(ui.global::<LibraryModel>().get_ri_tolerance_center()),
                    f64::from(ui.global::<LibraryModel>().get_ri_tolerance_value()),
                )
            }),
        performance: read_performance_filters(ui),
        include_ignored: ui.global::<LibraryModel>().get_show_ignored(),
    }
}

/// Reads `ui.global::<LibraryModel>().get_performance_filters()` (the tilt-performance filter panel's rows,
/// `PerformanceFilterRow` -- see that Slint struct's doc comment for the index<->enum
/// mapping this function applies) and builds the `Vec<PerformanceFilter>`
/// `read_range_filter` embeds in the `RangeFilter` it returns.
///
/// Every row is validated through `PerformanceFilter::new` rather than hand-built:
/// `filter_panel.slint`'s radius slider is already bounded to `0.0..=90.0`, so
/// rejection should never actually happen in practice, but this is still the one
/// boundary where a raw `tilt_radius_deg` becomes a real `PerformanceFilter`. A
/// rejected row is dropped from the query (never silently clamped into range) and
/// reported through `ui.set_status_message`.
fn read_performance_filters(ui: &MainWindow) -> Vec<PerformanceFilter> {
    let rows = ui.global::<LibraryModel>().get_performance_filters();
    let mut filters = Vec::with_capacity(rows.row_count());
    let mut rejected = 0usize;
    for row in rows.iter() {
        let metric = match row.metric_index {
            0 => PerformanceMetric::Brilliance,
            1 => PerformanceMetric::Extinction,
            _ => PerformanceMetric::Windowing,
        };
        let bound = if row.bound_index == 0 {
            PerformanceBound::AtMost(row.threshold_pct)
        } else {
            PerformanceBound::AtLeast(row.threshold_pct)
        };
        let aggregate = if row.aggregate_index == 0 {
            PerformanceAggregate::Worst
        } else {
            PerformanceAggregate::Mean
        };
        match PerformanceFilter::new(metric, bound, row.tilt_radius_deg, aggregate) {
            Ok(filter) => filters.push(filter),
            Err(_) => rejected += 1,
        }
    }
    if rejected > 0 {
        ui.global::<LibraryModel>().set_status_message(
            format!(
                "{rejected} tilt-performance filter(s) had an invalid tilt radius and were \
                 ignored."
            )
            .into(),
        );
    }
    filters
}

/// Dispatches to [`refresh_diagram_list`] or a background remote search.
///
/// Every search/filter callback in this crate calls this instead of `refresh_diagram_list`
/// directly and doesn't itself need to know which source is active.
pub fn refresh_diagram_list_via_source(
    ui: &MainWindow,
    db_mutex: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
    search: &str,
    shape_filter: &str,
    gear_filter: &str,
) {
    let current = source
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone();
    match current {
        LibrarySource::Local => {
            refresh_diagram_list(ui, db_mutex, search, shape_filter, gear_filter);
        }
        LibrarySource::Remote(worker) => {
            refresh_diagram_list_remote(ui, worker, search, shape_filter, gear_filter);
        }
    }
}

/// The remote counterpart of [`refresh_diagram_list`]: one `LibraryRequest::Search`
/// against `worker`, off the UI thread. Shares the same 1000-result cap as the local
/// query -- both are ultimately backed by `Database::search_diagrams`. `pub(crate)`,
/// not private: also called directly from `gui::library_remote` right after a source
/// switch succeeds, when the caller already has the `WorkerSettings` in hand and can
/// skip `refresh_diagram_list_via_source`'s `LibrarySource` re-check.
pub(crate) fn refresh_diagram_list_remote(
    ui: &MainWindow,
    worker: WorkerSettings,
    search: &str,
    shape_filter: &str,
    gear_filter: &str,
) {
    let clean_shape = if shape_filter == "All Shapes" {
        "All".to_string()
    } else {
        shape_filter.to_string()
    };
    let clean_gear = if gear_filter == "All Gears" {
        "All".to_string()
    } else {
        gear_filter.to_string()
    };
    let range = to_range_wire(&read_range_filter(ui));
    let request = LibraryRequest::Search {
        query: search.to_string(),
        shape_filter: clean_shape,
        gear_filter: clean_gear,
        range,
    };
    library_source::spawn_library_request(
        ui.as_weak(),
        worker,
        request,
        |ui, result| match result {
            Ok(LibraryResponse::SearchResults {
                items,
                excluded_for_missing_curves,
            }) => {
                let total = items.len();
                let slint_items: Vec<DiagramItem> = items.iter().map(to_diagram_item).collect();
                ui.global::<LibraryModel>()
                    .set_diagram_list(ModelRc::new(VecModel::from(slint_items)));
                ui.global::<LibraryModel>().set_total_count(total as i32);
                // `DesignSummary::ignored` and this reply's `excluded_for_missing_curves`
                // let a remote-sourced list drive the same ignored-row styling and
                // missing-curves notice the local path (`refresh_diagram_list` below)
                // already does. `cast_possible_truncation` is workspace-`allow`ed for
                // this `u32 as i32`, matching every other numeric cast into a Slint
                // `int` property in this file.
                ui.global::<LibraryModel>()
                    .set_performance_excluded_count(excluded_for_missing_curves as i32);
            }
            Ok(_) => {
                ui.global::<LibraryModel>()
                    .set_status_message("Unexpected reply searching the remote library.".into());
            }
            Err(e) => {
                error!("Remote search failed: {e}");
                ui.global::<LibraryModel>()
                    .set_status_message(format!("Remote search failed: {e}").into());
            }
        },
    );
}

/// Maps a local [`RangeFilter`] onto the wire [`RangeFilterWire`] a remote
/// [`LibraryRequest::Search`]/`SearchPage` carries; `apps/indicatrix-worker`'s
/// `serve::library::from_range_wire` is the other half of this pair. Not `const`:
/// mapping `performance` element-wise needs an allocation.
fn to_range_wire(range: &RangeFilter) -> RangeFilterWire {
    RangeFilterWire {
        ri_min: range.ri_min,
        ri_max: range.ri_max,
        lw_min: range.lw_min,
        lw_max: range.lw_max,
        volume_min: range.volume_min,
        volume_max: range.volume_max,
        facets_min: range.facets_min,
        facets_max: range.facets_max,
        ri_tolerance: range.ri_tolerance,
        include_ignored: range.include_ignored,
        performance: range
            .performance
            .iter()
            .map(to_performance_filter_wire)
            .collect(),
    }
}

const fn to_performance_filter_wire(filter: &PerformanceFilter) -> PerformanceFilterWire {
    let metric = match filter.metric {
        PerformanceMetric::Brilliance => PerformanceMetricWire::Brilliance,
        PerformanceMetric::Extinction => PerformanceMetricWire::Extinction,
        PerformanceMetric::Windowing => PerformanceMetricWire::Windowing,
    };
    let bound = match filter.bound {
        PerformanceBound::AtMost(t) => PerformanceBoundWire::AtMost(t),
        PerformanceBound::AtLeast(t) => PerformanceBoundWire::AtLeast(t),
    };
    let aggregate = match filter.aggregate {
        PerformanceAggregate::Worst => PerformanceAggregateWire::Worst,
        PerformanceAggregate::Mean => PerformanceAggregateWire::Mean,
    };
    PerformanceFilterWire {
        metric,
        bound,
        tilt_radius_deg: filter.tilt_radius_deg,
        aggregate,
    }
}

/// Reads [`DesignSummary::ignored`] straight off the row, giving a remote-sourced row
/// the same ignored flag a local-sourced
/// [`indicatrix_vault::model::entry::DiagramListItem::ignored`] already carries.
pub(crate) fn to_diagram_item(item: &DesignSummary) -> DiagramItem {
    DiagramItem {
        id: item.entry_id as i32,
        title: item.title.clone().into(),
        shape: item.shape.clone().unwrap_or_default().into(),
        gear: item.index_gear.clone().unwrap_or_default().into(),
        facets: item.facets_count.clone().unwrap_or_default().into(),
        designer: item.designer_info.clone().unwrap_or_default().into(),
        lw_ratio: item.lw_ratio.clone().unwrap_or_default().into(),
        ri: item.refractive_index.clone().unwrap_or_default().into(),
        ignored: item.ignored,
    }
}

/// One row [`fetch_diagram_list`] returns: the plain catalogue row plus whether it is
/// currently marked ignored.
pub struct DiagramListRow {
    pub item: DiagramListItem,
    /// `true` iff this row is a currently-ignored design being shown because
    /// `RangeFilter::include_ignored` is on. Always `false` while that toggle is off --
    /// an ignored row can't reach this struct in that case, since it's excluded by the
    /// query itself.
    pub ignored: bool,
}

/// [`fetch_diagram_list`]'s full result.
///
/// The rows, the catalogue's total design count
/// (unrelated to how many matched), and how many otherwise-matching designs a
/// currently-active tilt-performance filter excluded for having no computed curves at
/// all -- see
/// `indicatrix_vault::model::filter::PerformanceSearchResult::excluded_for_missing_curves`'s
/// doc comment for what that count does and doesn't include.
pub struct FetchedDiagramList {
    pub rows: Vec<DiagramListRow>,
    pub total: usize,
    pub excluded_for_missing_curves: usize,
}

/// The `Database` read half of [`refresh_diagram_list`].
///
/// Has no `ui` dependency beyond the already-resolved `range` -- split out so
/// `gui::library`'s post-import/rename/delete/shape-change refresh can run this on a
/// background thread (re-running an unfiltered search against a several-thousand-design
/// catalogue synchronously on the UI thread is itself a perceptible freeze) and only
/// marshal the cheap [`apply_diagram_list_to_ui`] step back onto the UI thread. Every
/// other caller (search box edits, filter slider drags) stays on the synchronous
/// [`refresh_diagram_list`] below, which a filter that must feel immediate as you type
/// actually needs.
///
/// # Errors
///
/// Returns an error if `Database::search_diagrams_with_performance_exclusions` fails (a
/// bad filter combination, or the connection itself). `get_total_count`'s own failure
/// is tolerated instead (`unwrap_or(items.len())` below).
pub fn fetch_diagram_list(
    db_mutex: &Arc<Mutex<Database>>,
    search: &str,
    shape_filter: &str,
    gear_filter: &str,
    range: &RangeFilter,
) -> Result<FetchedDiagramList> {
    let clean_shape = if shape_filter == "All Shapes" {
        "All"
    } else {
        shape_filter
    };
    let clean_gear = if gear_filter == "All Gears" {
        "All"
    } else {
        gear_filter
    };

    // Scoped so the guard drops before this returns: this runs on a background thread
    // where any extra time holding the database lock is time a UI-thread callback can
    // block on it.
    let (rows, total, excluded_for_missing_curves) = {
        let db = db_mutex
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let result =
            db.search_diagrams_with_performance_exclusions(search, clean_shape, clean_gear, range)?;
        let total = db.get_total_count().unwrap_or(result.items.len());

        // `ignored` is read straight off the row (`DiagramListItem::ignored`).
        let rows: Vec<DiagramListRow> = result
            .items
            .into_iter()
            .map(|item| {
                let ignored = item.ignored;
                DiagramListRow { item, ignored }
            })
            .collect();
        // Explicit: moving the results into the tuple needs no lock, and the UI
        // thread may be waiting on this same mutex.
        drop(db);
        (rows, total, result.excluded_for_missing_curves)
    };
    Ok(FetchedDiagramList {
        rows,
        total,
        excluded_for_missing_curves,
    })
}

/// The `ui.set_*` half of [`refresh_diagram_list`] -- see [`fetch_diagram_list`]'s doc
/// comment for why these are split.
pub fn apply_diagram_list_to_ui(ui: &MainWindow, fetched: FetchedDiagramList) {
    let slint_items: Vec<DiagramItem> = fetched
        .rows
        .into_iter()
        .map(|row| DiagramItem {
            id: row.item.id as i32,
            title: row.item.title.into(),
            shape: row.item.shape.unwrap_or_default().into(),
            gear: row.item.index_gear.unwrap_or_default().into(),
            facets: row.item.facets_count.unwrap_or_default().into(),
            designer: row.item.designer_info.unwrap_or_default().into(),
            lw_ratio: row.item.lw_ratio.unwrap_or_default().into(),
            ri: row.item.refractive_index.unwrap_or_default().into(),
            ignored: row.ignored,
        })
        .collect();

    ui.global::<LibraryModel>()
        .set_diagram_list(ModelRc::new(VecModel::from(slint_items)));
    ui.global::<LibraryModel>()
        .set_total_count(fetched.total as i32);
    // Counts designs within one query's result set (`SEARCH_RESULT_CAP`-bounded,
    // currently 1000), nowhere near `i32::MAX`.
    ui.global::<LibraryModel>()
        .set_performance_excluded_count(fetched.excluded_for_missing_curves as i32);
}

pub fn refresh_diagram_list(
    ui: &MainWindow,
    db_mutex: &Arc<Mutex<Database>>,
    search: &str,
    shape_filter: &str,
    gear_filter: &str,
) {
    let range = read_range_filter(ui);
    match fetch_diagram_list(db_mutex, search, shape_filter, gear_filter, &range) {
        Ok(fetched) => apply_diagram_list_to_ui(ui, fetched),
        Err(e) => {
            error!("Failed to search diagrams: {:?}", e);
            ui.global::<LibraryModel>()
                .set_status_message(format!("Error searching database: {e}").into());
        }
    }
}