indicatrix-cut 0.7.2

Desktop faceting-design editor: library browsing, spectral 3D rendering, material retargeting, and a solid inspection view.
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
//! Organizing an existing local design: ignore/un-ignore, rename, shape edit, and
//! delete -- the "Organize" half of `gui::library::local` (see this group's own
//! `mod.rs`); import and export live in their own sibling modules.

use super::helpers::refresh_after_library_change;
use crate::{
    LibraryModel, MainWindow,
    bridge::{
        library::source::LibrarySource,
        render_thread::{PlanesOwner, RenderContext},
    },
    gui::show_toast,
};
use indicatrix::geometry::cuts::StandardGemCuts;
use indicatrix_vault::{db::sqlite::Database, model::metadata_update::MetadataUpdate};
use slint::{ComponentHandle, Model, SharedString};
use std::sync::{Arc, Mutex};

/// Wires the per-design "Ignore"/"Un-ignore" context-menu toggle --
/// `diagram_list.slint`'s `ContextMenuArea`, alongside "Generate Previews"/"Compute
/// Tilt Curves". Refuses outright while a remote library is being browsed, same
/// reasoning as [`setup_rename_callback`]'s own doc comment: `Database::set_diagram_ignored`
/// is a local-database write, and the remote library protocol has no write request for
/// it even if this wanted to send one.
pub fn setup_ignore_toggle_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_ignore = Arc::clone(db);
    let source_ignore = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>()
        .on_toggle_ignored(move |id: i32| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_ignore
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(
                    &ui,
                    "Switch to the local library to ignore a design.",
                    "error",
                );
                return;
            }
            // The currently-visible list already carries whether this row is ignored
            // (`DiagramItem.ignored`, populated by `gui::library::search::fetch_diagram_list` --
            // see that function's own doc comment for how, since
            // `indicatrix_vault::model::entry::DiagramListItem` itself has no such field).
            // Reading it back off the list avoids a database round trip just to answer
            // "is this currently ignored" before flipping it. A row not found in the
            // currently-visible list (a stale click racing a refresh) falls back to
            // `true` -- ignoring is the more common direction this action is used for,
            // and a mistaken ignore is one more click to undo.
            let currently_ignored = ui
                .global::<LibraryModel>()
                .get_diagram_list()
                .iter()
                .find(|item| item.id == id)
                .is_some_and(|item| item.ignored);
            let new_ignored = !currently_ignored;
            let result = {
                let db = db_ignore
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                db.set_diagram_ignored(i64::from(id), new_ignored)
            };
            match result {
                Ok(()) => {
                    show_toast(
                        &ui,
                        if new_ignored {
                            "Design ignored."
                        } else {
                            "Design un-ignored."
                        },
                        "success",
                    );
                    refresh_after_library_change(&ui, &db_ignore, &source_ignore);
                }
                Err(e) => show_toast(&ui, &format!("Failed to update ignored flag: {e}"), "error"),
            }
        });
}

/// Wires the per-design "Exclude from planner"/"Include in planner" context-menu toggle
/// (`diagram_list.slint`, beside "Ignore"). The mark only keeps the design out of the
/// Rough Planner's candidate set; unlike "Ignore" the design stays in the list and in
/// every other batch. Refuses outright while a remote library is being browsed, same
/// reasoning as [`setup_ignore_toggle_callback`]: `Database::set_planner_excluded` is a
/// local-database write and the remote library protocol has no request for it.
///
/// After the write the library list is refreshed (the row's "not planned" marker and the
/// menu wording follow the database) and the planner window, when it exists, re-reads its
/// excluded-designs list and counts through `rough_plan::exclusions_changed`.
pub fn setup_planner_exclusion_toggle_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_exclude = Arc::clone(db);
    let source_exclude = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>()
        .on_toggle_planner_excluded(move |id: i32| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_exclude
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(
                    &ui,
                    "Switch to the local library to change which designs are planned.",
                    "error",
                );
                return;
            }
            // The visible row already carries the current state (`DiagramItem.
            // planner_excluded`) and the title the toast quotes, so no database round
            // trip is needed to answer "is this excluded now". A row missing from the
            // visible list (a stale click racing a refresh) counts as not excluded, so
            // the click excludes it, which is the direction this item is mostly used
            // for and costs one more click to undo.
            let shown = ui
                .global::<LibraryModel>()
                .get_diagram_list()
                .iter()
                .find(|item| item.id == id);
            let new_excluded = !shown.as_ref().is_some_and(|item| item.planner_excluded);
            let title = shown.map_or_else(|| format!("#{id}"), |item| item.title.to_string());
            let result = {
                let db = db_exclude
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                db.set_planner_excluded(i64::from(id), new_excluded)
            };
            match result {
                Ok(()) => {
                    let message = if new_excluded {
                        format!("Excluded \"{title}\" from the rough planner.")
                    } else {
                        format!("\"{title}\" can be planned again.")
                    };
                    show_toast(&ui, &message, "success");
                    refresh_after_library_change(&ui, &db_exclude, &source_exclude);
                    crate::gui::rough_plan::exclusions_changed();
                }
                Err(e) => show_toast(
                    &ui,
                    &format!("Failed to change the planner exclusion: {e}"),
                    "error",
                ),
            }
        });
}

/// Wires up the detail header's inline rename (pencil icon -> `rename_diagram`).
///
/// Refuses outright while a remote library is being browsed: the selected entry id in
/// that case names a row in the REMOTE server's catalogue, not this process's local
/// database, and the library protocol is read-only in any case (see
/// `indicatrix_net::library`'s module doc comment -- there is no write request to send even
/// if this wanted to act on the remote row instead). Renaming a LOCAL row while
/// browsing remote is not offered either -- the visible list, and so the selection,
/// is the remote one.
pub fn setup_rename_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_rename = Arc::clone(db);
    let source_rename = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>()
        .on_rename_diagram(move |new_title: SharedString| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_rename
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(
                    &ui,
                    "Switch to the local library to rename a design.",
                    "error",
                );
                return;
            }
            let entry_id = ui.global::<LibraryModel>().get_selected_entry_id();
            if entry_id < 0 {
                return;
            }
            let result = {
                let db = db_rename
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                db.rename_diagram_entry(i64::from(entry_id), &new_title)
            };
            match result {
                Ok(()) => {
                    let mut detail = ui.global::<LibraryModel>().get_current_detail();
                    detail.title = new_title;
                    ui.global::<LibraryModel>().set_current_detail(detail);
                    show_toast(&ui, "Renamed.", "success");
                    refresh_after_library_change(&ui, &db_rename, &source_rename);
                }
                Err(e) => show_toast(&ui, &format!("Rename failed: {e}"), "error"),
            }
        });
}

/// Sets `entry_id`'s shape to `new_shape`, called by [`setup_set_shape_callback`].
///
/// Edits exactly one column. `Database::update_diagram_metadata` issues a narrow
/// `UPDATE diagram_details SET ...` naming only the fields handed to it, so every
/// other column keeps whatever it already held -- unlike
/// `Database::save_diagram_detail`, which fully REPLACES a design's detail row and
/// would therefore zero anything the caller failed to carry across.
///
/// The rest of the [`MetadataUpdate`] below is read straight back out of the design's
/// current record and passed through unchanged, so the net effect is `shape` and
/// nothing else. The record carries each stored double as the shortest text that parses
/// back to exactly that double, so the numbers survive the trip to the last digit.
/// In particular the proportions are NOT recomputed: they are measured
/// data (see `super::import::apply_measured_metadata`, which derives them once at
/// import from the design's own geometry), and re-deriving them on an unrelated shape
/// edit would be both wasted work and a chance to disagree with the stored value.
fn set_diagram_shape(db: &Database, entry_id: i64, new_shape: &str) -> Result<(), String> {
    let full = db
        .get_diagram_full(entry_id)
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "Diagram detail not found.".to_string())?;

    let update = MetadataUpdate {
        shape: Some(new_shape.to_string()),
        // Everything below is this design's existing value, round-tripped unchanged.
        designer_info: full.designer_info,
        refractive_index: full.refractive_index,
        index_gear: full.index_gear,
        facets_count: full.facets_count,
        symmetry_order: full.symmetry_order,
        mirror_symmetry: full.mirror_symmetry,
        lw_ratio: full.lw_ratio,
        hw_ratio: full.hw_ratio,
        cw_ratio: full.cw_ratio,
        pw_ratio: full.pw_ratio,
        volume: full.volume,
    };
    db.update_diagram_metadata(entry_id, &update)
        .map_err(|e| e.to_string())
}

/// Builds the shape picker's option list and the index within it that matches
/// `current` (the selected design's own `shape`, `None`/empty for an unclassified
/// import). Called from `gui::library::detail::load_diagram_detail` every time a LOCAL
/// design is opened, so the dropdown always reflects this design and the library's
/// present vocabulary.
///
/// `Database::get_unique_shapes` already unions the seeded `DEFAULT_SHAPES` with
/// every distinct scraped value actually present, alphabetically -- this only adds
/// one more thing: if `current` itself isn't in that union for some reason (should be
/// rare -- it would mean this design's own `shape` value was written by something
/// other than `save_diagram_detail`/the seeded vocabulary), it's inserted too, so
/// opening the picker can never silently drop the design's existing value out of the
/// list before the user has touched anything.
pub fn build_shape_picker_options(
    db: &Database,
    current: Option<&str>,
) -> (Vec<SharedString>, i32) {
    let mut shapes = db.get_unique_shapes().unwrap_or_default();
    let current = current.unwrap_or("").trim();
    if !current.is_empty() && !shapes.iter().any(|s| s == current) {
        shapes.push(current.to_string());
        shapes.sort();
    }
    let index = if current.is_empty() {
        -1
    } else {
        shapes
            .iter()
            .position(|s| s == current)
            .map_or(-1, |i| i as i32)
    };
    (shapes.into_iter().map(SharedString::from).collect(), index)
}

/// Wires up the detail header's shape picker (pencil icon next to the "Shape:" chip,
/// same idiom as [`setup_rename_callback`]'s title pencil) -> `set_shape`.
///
/// Refuses outright while a remote library is being browsed -- see
/// `setup_rename_callback`'s own doc comment; `detail_header.slint` additionally only
/// shows the pencil for `root.detail.is_local`, so this guard is a backstop, not the
/// only thing standing between a remote-sourced id and the local database.
pub fn setup_set_shape_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_shape = Arc::clone(db);
    let source_shape = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>()
        .on_set_shape(move |new_shape: SharedString| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_shape
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(
                    &ui,
                    "Switch to the local library to change a design's shape.",
                    "error",
                );
                return;
            }
            let entry_id = ui.global::<LibraryModel>().get_selected_entry_id();
            if entry_id < 0 {
                return;
            }
            let result = {
                let db = db_shape
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                set_diagram_shape(&db, i64::from(entry_id), new_shape.as_str())
            };
            match result {
                Ok(()) => {
                    let mut detail = ui.global::<LibraryModel>().get_current_detail();
                    detail.shape = new_shape;
                    ui.global::<LibraryModel>().set_current_detail(detail);
                    show_toast(&ui, "Shape updated.", "success");
                    refresh_after_library_change(&ui, &db_shape, &source_shape);
                }
                Err(e) => show_toast(&ui, &format!("Shape update failed: {e}"), "error"),
            }
        });
}

/// Wires up the "Add tag..." context-menu entry (`diagram_list.slint`)
/// -> `add_tag_to_entry`. Creates the tag if it doesn't already exist
/// (case-insensitively) and attaches it to `entry_id` -- see
/// `Database::add_tag_to_entry`'s own doc comment for the exact create-or-reuse
/// rule. A blank name (whitespace-only) is rejected with a toast rather than
/// silently creating an empty tag.
///
/// Refuses outright while a remote library is being browsed, same reasoning as
/// [`setup_rename_callback`]'s own doc comment.
pub fn setup_add_tag_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_tag = Arc::clone(db);
    let source_tag = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>().on_add_tag_to_entry(
        move |entry_id: i32, tag_name: SharedString| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_tag
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(&ui, "Switch to the local library to tag a design.", "error");
                return;
            }
            let result = {
                let db = db_tag
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                db.add_tag_to_entry(i64::from(entry_id), tag_name.as_str())
            };
            match result {
                Ok(tag) => {
                    show_toast(&ui, &format!("Tagged \"{}\".", tag.name), "success");
                    refresh_after_library_change(&ui, &db_tag, &source_tag);
                }
                Err(e) => show_toast(&ui, &format!("Failed to add tag: {e}"), "error"),
            }
        },
    );
}

/// Wires up a tag chip's remove control (`diagram_list.slint`) -> `remove_tag_from_entry`.
/// Takes the tag's NAME rather than its id -- the card only ever carries
/// `DiagramItem.tags: [string]` (see `gui::library::diagram_list::
/// sync_tag_vocabulary_to_ui`'s own doc comment for why the Slint side never
/// handles a tag id directly), so this resolves the name to an id via
/// `Database::tag_id_by_name` itself. A name that no longer resolves (the tag was
/// deleted from elsewhere between the chip rendering and this click) is a silent
/// no-op, not an error -- there is nothing left to remove.
///
/// Refuses outright while a remote library is being browsed, same reasoning as
/// [`setup_rename_callback`]'s own doc comment.
pub fn setup_remove_tag_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
) {
    let db_untag = Arc::clone(db);
    let source_untag = Arc::clone(source);
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>().on_remove_tag_from_entry(
        move |entry_id: i32, tag_name: SharedString| {
            let Some(ui) = ui_weak.upgrade() else {
                return;
            };
            if source_untag
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_remote()
            {
                show_toast(
                    &ui,
                    "Switch to the local library to untag a design.",
                    "error",
                );
                return;
            }
            let result = {
                let db = db_untag
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                match db.tag_id_by_name(tag_name.as_str()) {
                    Ok(Some(tag_id)) => db.remove_tag_from_entry(i64::from(entry_id), tag_id),
                    Ok(None) => Ok(()),
                    Err(e) => Err(e),
                }
            };
            match result {
                Ok(()) => refresh_after_library_change(&ui, &db_untag, &source_untag),
                Err(e) => show_toast(&ui, &format!("Failed to remove tag: {e}"), "error"),
            }
        },
    );
}

/// Wires up the detail header's delete confirm -> `delete_diagram`: removes the
/// entry (cascading to its detail/angle-settings/attached-files rows, see
/// `Database::delete_diagram_entry`) and clears the now-stale detail/3D-viewport
/// state.
///
/// Refuses outright while a remote library is being browsed -- see
/// `setup_rename_callback`'s own doc comment; the same reasoning applies verbatim
/// (and matters even more here, since a mistaken delete against the wrong local row by
/// a remote-sourced id would be destructive, not just cosmetically wrong).
pub fn setup_delete_callback(
    ui: &MainWindow,
    db: &Arc<Mutex<Database>>,
    source: &Arc<Mutex<LibrarySource>>,
    render_ctx: &Arc<Mutex<RenderContext>>,
) {
    let db_delete = Arc::clone(db);
    let source_delete = Arc::clone(source);
    let render_ctx_delete = render_ctx.clone();
    let ui_weak = ui.as_weak();
    ui.global::<LibraryModel>().on_delete_diagram(move || {
        let Some(ui) = ui_weak.upgrade() else {
            return;
        };
        if source_delete
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .is_remote()
        {
            show_toast(
                &ui,
                "Switch to the local library to delete a design.",
                "error",
            );
            return;
        }
        let entry_id = ui.global::<LibraryModel>().get_selected_entry_id();
        if entry_id < 0 {
            return;
        }
        let result = {
            let db = db_delete
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            db.delete_diagram_entry(i64::from(entry_id))
        };
        match result {
            Ok(()) => {
                // This design is genuinely gone, not merely filtered out
                // of the current list -- see
                // `crate::gui::library::detail::clear_current_detail_display`'s own doc
                // comment for the (narrower) case that function was pulled out for.
                crate::gui::library::detail::clear_current_detail_display(&ui);
                {
                    let mut ctx = render_ctx_delete
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    // Only reset the traced geometry when the deleted row is the
                    // one whose planes are actually loaded -- resetting unconditionally
                    // would throw away an unrelated design being edited in the viewport.
                    let owns_deleted_row = matches!(
                        ctx.planes_owner,
                        PlanesOwner::Catalogue { entry_id: owned } if owned == i64::from(entry_id)
                    );
                    if owns_deleted_row {
                        ctx.claim_active_planes(
                            std::sync::Arc::new(StandardGemCuts::standard_round_brilliant()),
                            None,
                            PlanesOwner::Builtin,
                        );
                        ctx.dirty = true;
                    }
                }
                show_toast(&ui, "Diagram deleted.", "info");
                refresh_after_library_change(&ui, &db_delete, &source_delete);
            }
            Err(e) => show_toast(&ui, &format!("Delete failed: {e}"), "error"),
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gui::library::local::helpers::test_support::{open_temp_db, temp_db_path_for_test};
    use indicatrix_vault::model::detail::FacetingDiagramDetail;

    /// `set_diagram_shape` must edit `shape` and NOTHING else.
    ///
    /// `indicatrix-vault` already proves `update_diagram_metadata` writes only the
    /// columns it is handed; this proves the wiring on THIS side hands it all of them.
    /// Omitting one field from the `MetadataUpdate` literal would compile fine and
    /// silently blank that column on every shape edit -- the kind of data loss a
    /// narrow, explicit `UPDATE` is designed to prevent.
    #[test]
    fn set_diagram_shape_changes_only_the_shape() {
        let path = temp_db_path_for_test("set_shape");
        let db_arc = open_temp_db(&path);
        let db = db_arc.lock().expect("lock temp db");

        let entry = indicatrix_vault::model::entry::FacetingDiagramEntry {
            title: "Shape edit probe".to_string(),
            url: "local://shape_probe.asc".to_string(),
            design_id: String::new(),
        };
        let detail = FacetingDiagramDetail {
            refractive_index: Some("1.762".to_string()),
            index_gear: Some("96".to_string()),
            facets_count: Some("57".to_string()),
            symmetry_order: Some("8".to_string()),
            mirror_symmetry: Some(true),
            lw_ratio: Some("1.234".to_string()),
            hw_ratio: Some("0.617".to_string()),
            cw_ratio: Some("0.145".to_string()),
            pw_ratio: Some("0.431".to_string()),
            volume: Some("0.187".to_string()),
            designer_info: Some("Somebody; Some Journal".to_string()),
            shape: Some("Oval".to_string()),
            ..FacetingDiagramDetail::default()
        };
        let entry_id = db
            .save_diagram_entry(&entry, indicatrix_vault::local::LOCAL_SOURCE_ID)
            .expect("save entry");
        db.save_diagram_detail(&detail, entry_id)
            .expect("save detail");

        set_diagram_shape(&db, entry_id, "Cushion").expect("set shape");

        let after = db
            .get_diagram_full(entry_id)
            .expect("read back")
            .expect("row exists");
        assert_eq!(after.shape.as_deref(), Some("Cushion"), "shape must change");
        // Every other field must be exactly what it was; `pw_ratio`/`cw_ratio`/
        // `hw_ratio`/`symmetry_order`/`mirror_symmetry` are the load-bearing
        // assertions here since a narrow `UPDATE` must preserve every column it
        // wasn't asked to change.
        assert_eq!(after.refractive_index.as_deref(), Some("1.762"));
        assert_eq!(after.index_gear.as_deref(), Some("96"));
        assert_eq!(after.facets_count.as_deref(), Some("57"));
        assert_eq!(after.symmetry_order.as_deref(), Some("8"));
        assert_eq!(after.mirror_symmetry, Some(true));
        assert_eq!(after.lw_ratio.as_deref(), Some("1.234"));
        assert_eq!(after.hw_ratio.as_deref(), Some("0.617"));
        assert_eq!(after.cw_ratio.as_deref(), Some("0.145"));
        assert_eq!(after.pw_ratio.as_deref(), Some("0.431"));
        assert_eq!(after.volume.as_deref(), Some("0.187"));
        assert_eq!(
            after.designer_info.as_deref(),
            Some("Somebody; Some Journal")
        );

        drop(db);
        drop(db_arc);
        std::fs::remove_file(&path).ok();
    }

    /// The round trip behind a shape edit must not change a stored ratio by even its
    /// last digit. The record used to be read through `CAST(real AS TEXT)`, which keeps
    /// 15 significant digits, so `0.30000000000000004` came back as `0.3` and the
    /// edit wrote that back.
    #[test]
    fn set_diagram_shape_keeps_every_digit_of_a_stored_double() {
        let path = temp_db_path_for_test("set_shape_digits");
        let db_arc = open_temp_db(&path);
        let db = db_arc.lock().expect("lock temp db");

        let entry = indicatrix_vault::model::entry::FacetingDiagramEntry {
            title: "Digits probe".to_string(),
            url: "local://digits_probe.asc".to_string(),
            design_id: String::new(),
        };
        let entry_id = db
            .save_diagram_entry(&entry, indicatrix_vault::local::LOCAL_SOURCE_ID)
            .expect("save entry");
        db.save_diagram_detail(&FacetingDiagramDetail::default(), entry_id)
            .expect("save detail");
        // Both need 17 significant digits: 0.1 + 0.2, and 1 + 2^-52.
        let update = MetadataUpdate {
            shape: Some("Oval".to_string()),
            lw_ratio: Some("0.30000000000000004".to_string()),
            refractive_index: Some("1.0000000000000002".to_string()),
            ..MetadataUpdate::default()
        };
        db.update_diagram_metadata(entry_id, &update)
            .expect("store the doubles");

        let before = db
            .get_diagram_full(entry_id)
            .expect("read back")
            .expect("row exists");
        assert_eq!(before.lw_ratio.as_deref(), Some("0.30000000000000004"));
        assert_eq!(
            before.refractive_index.as_deref(),
            Some("1.0000000000000002")
        );

        set_diagram_shape(&db, entry_id, "Cushion").expect("set shape");

        let after = db
            .get_diagram_full(entry_id)
            .expect("read back")
            .expect("row exists");
        assert_eq!(after.shape.as_deref(), Some("Cushion"));
        assert_eq!(after.lw_ratio, before.lw_ratio);
        assert_eq!(after.refractive_index, before.refractive_index);

        drop(db);
        drop(db_arc);
        std::fs::remove_file(&path).ok();
    }
}