indicatrix-cut 0.7.1

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
//! The compare surfaces' Slint wiring: the entry callbacks on `MainWindow`'s own
//! `CompareModel`, opening a session on the pop-out window or the Retarget dialog's
//! embedded pane, the view callbacks both share, and Keep/Discard/Close.
//!
//! The surfaces, the one live session and frame delivery live in [`super::host`];
//! this module decides WHICH surface a request opens on:
//!
//! - "Compare…", the Optimize tab and the snapshot table open the pop-out window;
//! - the Retarget dialog asks for its embedded pane (`open_retarget_embedded`) after
//!   every solve -- unless the session was popped out into the window, in which case
//!   the window is refreshed instead and the pane keeps saying so;
//! - there is only ever ONE live session: opening replaces it, wherever it was.
//!
//! When the pop-out window of a Retarget session is closed (Close, Discard or the
//! titlebar X) while the dialog is still open, the pane takes the session back.

use super::{
    host::{self, NewLive, POPPED_OUT_STATUS, Surface, SurfaceHandle, TRACED_DEBOUNCE},
    metrics::SessionMetrics,
    origins::{self, KeepGuard, OpenRequest, VariantSide},
    render,
    session::{self, CompareOrigin, CompareSession, Renderer},
};
use crate::{
    CompareModel, CompareWindow, EditorModel, HelpModel, MainWindow, RetargetModel, ViewportModel,
    bridge::render_thread::RenderContext,
    gui::{
        editor::{callbacks, state::EditorState, view::SolidLastSolved},
        show_toast,
        solid_preview::preview_state::{CameraPose, SolidPreviewState},
        tutorial_events::raise,
    },
};
use indicatrix::optics::LightingPreset;
use indicatrix_editor::guide::solving_events::COMPARE_WINDOW_OPENED;
use slint::{ComponentHandle, Image, ModelRc, SharedString, VecModel, Weak};
use std::{
    cell::RefCell,
    rc::Rc,
    sync::{Arc, Mutex, PoisonError},
    time::Duration,
};
use tracing::warn;

/// The editor handles Keep/Discard need, captured once.
#[derive(Clone)]
pub(super) struct CompareDeps {
    /// The main window.
    pub(super) ui: Weak<MainWindow>,
    /// The editor state (read only here -- Keep goes through the Apply handlers).
    pub(super) state: Rc<RefCell<EditorState>>,
    /// The render context (custom materials, the live camera pose).
    pub(super) render_ctx: Arc<Mutex<RenderContext>>,
    /// The shared solid viewport, for Retarget's Discard revert.
    pub(super) preview_state: Arc<SolidPreviewState>,
    /// The shared solve cache, for Retarget's Discard revert.
    pub(super) solid_last_solved: SolidLastSolved,
}

thread_local! {
    /// The entry handles, kept for the places that open a comparison without a
    /// `CompareModel` callback of their own (the Variants view). UI-thread-only.
    static ENTRY_DEPS: RefCell<Option<CompareDeps>> = const { RefCell::new(None) };
    /// The "Compare against" picker index the frames on screen were built for, so a refused
    /// picker change can put the ComboBox back. UI-thread-only.
    static SHOWN_REFERENCE_INDEX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
}

/// Closes the compare window and the embedded pane if they are open -- called
/// wherever the main window hides, so a leftover compare window never keeps the
/// event loop (and the process) alive after the main window is gone.
pub(in crate::gui) fn close_compare_window() {
    host::close_embedded_session();
    host::close_window(true);
}

/// The Retarget dialog is still open after its popped-out session went away: the
/// pane takes the (current) proposal back.
fn restore_embedded_if_open(ui: &MainWindow) {
    if ui.global::<RetargetModel>().get_is_open() {
        ui.global::<CompareModel>().invoke_open_retarget_embedded();
    }
}

/// Closes the window session (`hide` is `false` from the titlebar close, which
/// hides the window itself) and, for a Retarget session, hands it back to the
/// dialog's pane.
fn close_window_and_restore(deps: &CompareDeps, hide: bool) {
    let origin = host::close_window(hide);
    if origin == Some(CompareOrigin::Retarget)
        && let Some(ui) = deps.ui.upgrade()
    {
        restore_embedded_if_open(&ui);
    }
}

/// "Keep after": re-checks that the originating feature would still commit what
/// was compared, closes the window, then invokes that feature's OWN Apply handler
/// (`RetargetModel.apply()` / `EditorModel.optimize_apply()`), so undo, dirty and
/// generation bookkeeping are exactly the Apply button's.
fn on_keep(deps: &CompareDeps) {
    let Some(ui) = deps.ui.upgrade() else {
        return;
    };
    let Some(guard) = host::keep_guard() else {
        return;
    };
    let still_current = {
        let Ok(st) = deps.state.try_borrow() else {
            return;
        };
        origins::guard_still_matches(&guard, &ui, &st, &deps.render_ctx)
    };
    if !still_current {
        show_toast(
            &ui,
            "The change you compared is no longer the pending one -- open Compare again to \
             see the current one.",
            "warning",
        );
        return;
    }
    host::close_window(true);
    match guard {
        KeepGuard::Retarget(_) => ui.global::<RetargetModel>().invoke_apply(),
        KeepGuard::Optimize { .. } => ui.global::<EditorModel>().invoke_optimize_apply(),
        KeepGuard::Snapshot | KeepGuard::Variants => {}
    }
}

/// "Discard": closes the window and turns the originating feature's viewport
/// ghost off -- Retarget's through the dialog's own revert, Optimize's "Preview"
/// checkbox through its own toggle handler (and a serial bump the inspector watches
/// to untick the box). The pending proposal/result itself stays, so the cutter can
/// adjust it and compare again.
fn on_discard(deps: &CompareDeps) {
    let origin = host::close_window(true);
    let Some(ui) = deps.ui.upgrade() else {
        return;
    };
    match origin {
        Some(CompareOrigin::Retarget) => {
            if let Ok(st) = deps.state.try_borrow() {
                callbacks::discard_retarget_preview(
                    &ui,
                    &deps.render_ctx,
                    &deps.preview_state,
                    &deps.solid_last_solved,
                    &st,
                );
            }
            restore_embedded_if_open(&ui);
        }
        Some(CompareOrigin::Optimize) => {
            let model = ui.global::<CompareModel>();
            model.set_optimize_preview_reset_serial(
                model.get_optimize_preview_reset_serial().wrapping_add(1),
            );
            ui.global::<EditorModel>()
                .invoke_optimize_preview_toggled(false);
        }
        Some(CompareOrigin::Snapshot | CompareOrigin::Variants) | None => {}
    }
}

/// Registers the view callbacks both surfaces share on `model`: orbit, zoom, reset,
/// the drag release rule, and the layout, renderer and size switches. Each acts only
/// while the live session sits on `surface`.
fn register_view_callbacks(model: &CompareModel<'_>, surface: Surface) {
    model.on_orbit(move |dx, dy| {
        host::change_pose(surface, |pose, _| session::orbit(pose, dx, dy));
    });
    model.on_zoom(move |delta| {
        host::change_pose(surface, |pose, radius| session::zoom(pose, delta, radius));
    });
    model.on_reset_pose(move || {
        host::change_pose(surface, |_, radius| session::default_pose(radius));
    });
    model.on_drag_begin(move || host::set_drag(surface, true));
    model.on_drag_end(move || host::set_drag(surface, false));
    // The slot size changes with the layout; `size_changed` follows on its own. The
    // selected renderer is re-read from the UI (its one source of truth) so the layout
    // switch keeps rendering -- and, when traced, tracing -- in the highlighted mode.
    model.on_mode_changed(move |_| {
        let Some(handle) = host::handle(surface) else {
            return;
        };
        let renderer = Renderer::from_index(handle.with_model(|model| model.get_renderer_index()));
        if host::layout_switched(surface, renderer) {
            host::request_frames(TRACED_DEBOUNCE);
        }
    });
    model.on_renderer_changed(move |index| {
        if host::set_renderer(surface, Renderer::from_index(index)) {
            host::request_frames(Duration::ZERO);
        }
    });
    model.on_size_changed(move |width, height| {
        let Some(handle) = host::handle(surface) else {
            return;
        };
        let size = render::pixel_size(width, height, handle.scale_factor());
        if host::set_size(surface, size) {
            host::request_frames(TRACED_DEBOUNCE);
        }
    });
}

/// Registers the window's own callbacks -- once, when the window is created.
fn register_window_callbacks(window: &CompareWindow, deps: &CompareDeps) {
    let model = window.global::<CompareModel>();
    register_view_callbacks(&model, Surface::Window);
    let keep_deps = deps.clone();
    model.on_keep(move || on_keep(&keep_deps));
    let discard_deps = deps.clone();
    model.on_discard(move || on_discard(&discard_deps));
    let close_deps = deps.clone();
    model.on_close(move || close_window_and_restore(&close_deps, true));
    // "Compare against": re-opens the Optimize comparison on the same surface; the refresh
    // path keeps the frames and carries the camera (`open_session`'s pose hand-over).
    let reference_deps = deps.clone();
    let reference_window = window.as_weak();
    model.on_reference_changed(move |index| {
        if host::live_kind() != Some((Surface::Window, CompareOrigin::Optimize)) {
            return;
        }
        let reference = origins::Reference::from_index(index);
        let refused = std::cell::Cell::new(false);
        // `open_from` already toasts the reason for a refused request.
        open_from(&reference_deps, Surface::Window, |_, st, render_ctx| {
            let request = origins::optimize_request(st, render_ctx, reference);
            refused.set(request.is_err());
            request
        });
        // The frames did not change, so the picker goes back to the entry they belong to.
        if refused.get()
            && let Some(window) = reference_window.upgrade()
        {
            let shown = SHOWN_REFERENCE_INDEX.with(std::cell::Cell::get);
            window.global::<CompareModel>().set_reference_index(shown);
        }
    });
    // The metrics strip's tilt average (the Retarget dialog's pane has no strip).
    model.on_tilt_requested(|| host::start_tilt(Surface::Window));
    model.on_tilt_cancelled(|| host::cancel_tilt(Surface::Window));
    // The window's "?" button: its own `HelpModel` instance hands the topic to the main window,
    // which owns the help window.
    let help_ui = deps.ui.clone();
    window.global::<HelpModel>().on_open_topic(move |topic| {
        let Some(ui) = help_ui.upgrade() else {
            return;
        };
        if let Err(message) = crate::gui::help::open_topic(&ui, topic.as_str()) {
            show_toast(&ui, &message, "error");
        }
    });
    // The titlebar X is "Close": the proposal stays pending, nothing is reverted.
    let x_deps = deps.clone();
    window.window().on_close_requested(move || {
        close_window_and_restore(&x_deps, false);
        slint::CloseRequestResponse::HideWindow
    });
}

/// The window, created (and its callbacks registered) on first use.
fn ensure_window(deps: &CompareDeps) -> Option<CompareWindow> {
    if let Some(existing) = host::window() {
        return Some(existing);
    }
    let window = match CompareWindow::new() {
        Ok(window) => window,
        Err(error) => {
            warn!("Could not create the compare window: {error}");
            return None;
        }
    };
    // Starts in the current palette (high contrast) and follows later changes.
    crate::gui::preferences::bind_compare_window_theme(&window);
    register_window_callbacks(&window, deps);
    host::store_window(&window);
    Some(window)
}

/// The live viewport's camera pose -- the first view of a session that has no
/// previous session to continue from.
fn viewport_pose(deps: &CompareDeps) -> CameraPose {
    let ctx = deps
        .render_ctx
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    CameraPose {
        yaw: ctx.yaw,
        pitch: ctx.pitch,
        distance: ctx.distance,
    }
}

/// A session moves from the pane to the window: the window starts with the layout
/// and renderer the pane was showing.
fn carry_view_settings(window: &SurfaceHandle) {
    let Some(pane) = host::handle(Surface::Embedded) else {
        return;
    };
    let (mode, renderer) =
        pane.with_model(|model| (model.get_mode_index(), model.get_renderer_index()));
    window.with_model(|model| {
        model.set_mode_index(mode);
        model.set_renderer_index(renderer);
    });
}

/// The surface `old` was on is no longer the live one: empties it, the window
/// hidden, the pane saying where its session went.
fn retire_previous_surface(old: Option<Surface>, new: Surface) {
    match (old, new) {
        (Some(Surface::Window), Surface::Embedded) => {
            host::close_window(true);
        }
        (Some(Surface::Embedded), Surface::Window) => {
            if let Some(pane) = host::handle(Surface::Embedded) {
                host::reset_surface(&pane, POPPED_OUT_STATUS);
            }
        }
        _ => {}
    }
}

/// The handle to open a session on: the window is created on first use.
fn target_handle(deps: &CompareDeps, surface: Surface) -> Option<SurfaceHandle> {
    match surface {
        Surface::Window => ensure_window(deps).map(SurfaceHandle::Window),
        Surface::Embedded => host::handle(surface),
    }
}

/// Opens (or re-targets) `surface` on `request`: shows it at once with a
/// "Solving…" status, and solves both sides on a background thread -- a real
/// design can take seconds to solve, which must never freeze the UI. Replaces the
/// live session wherever it was; a session continuing on the same or another
/// surface keeps its camera. The optical figures are measured under `lighting`, the
/// viewport's lighting preset at the time of the request.
fn open_session(
    deps: &CompareDeps,
    surface: Surface,
    request: OpenRequest,
    lighting: LightingPreset,
) {
    let Some(target) = target_handle(deps, surface) else {
        return;
    };
    if surface == Surface::Window
        && host::live_kind().is_some_and(|(live, _)| live == Surface::Embedded)
    {
        carry_view_settings(&target);
    }
    let OpenRequest {
        reference,
        origin,
        guard,
        before,
        after,
    } = request;
    let scale = target.scale_factor();
    // A refresh on the same surface keeps the previous frames on screen until the
    // new ones land, rather than flashing the pane empty on every re-solve.
    let refresh = host::live_kind().is_some_and(|(live, _)| live == surface);
    let (renderer, size_px) = target.with_model(|model| {
        model.set_before_label(before.label.clone().into());
        model.set_after_label(after.label.clone().into());
        if !refresh {
            model.set_before_image(Image::default());
            model.set_after_image(Image::default());
            model.set_overlay_image(Image::default());
            host::clear_strip(&model);
        }
        model.set_reference_available(reference.original_label.is_some());
        model.set_reference_options(ModelRc::new(VecModel::from(
            origins::reference_options(&reference)
                .into_iter()
                .map(SharedString::from)
                .collect::<Vec<_>>(),
        )));
        model.set_reference_index(reference.selected.index());
        SHOWN_REFERENCE_INDEX.with(|cell| cell.set(reference.selected.index()));
        model.set_can_keep(false);
        model.set_show_keep_discard(origin.offers_keep());
        model.set_split_fraction(session::clamp_split_fraction(model.get_split_fraction()));
        (
            Renderer::from_index(model.get_renderer_index()),
            render::pixel_size(model.get_image_width(), model.get_image_height(), scale),
        )
    });
    let (id, old) = host::replace_live(NewLive {
        surface,
        origin,
        guard,
        renderer,
        size_px,
    });
    let pose = old
        .as_ref()
        .and_then(host::LiveSession::pose)
        .or_else(host::take_retained_pose)
        .unwrap_or_else(|| viewport_pose(deps));
    host::seed_pose(id, pose);
    retire_previous_surface(old.as_ref().map(host::LiveSession::surface), surface);
    // The replaced session (workers, timer) is dropped with the cell released.
    drop(old);
    target.with_model(|model| {
        model.set_status(host::solving_status(renderer).into());
        model.set_is_open(true);
        model.set_embedded_open(surface == Surface::Embedded);
    });
    if let SurfaceHandle::Window(window) = &target
        && let Err(error) = window.show()
    {
        warn!("Could not show the compare window: {error}");
        host::close_window(false);
        return;
    }
    if matches!(target, SurfaceHandle::Window(_))
        && let Some(ui) = deps.ui.upgrade()
    {
        raise(&ui, COMPARE_WINDOW_OPENED);
    }
    let spawned = std::thread::Builder::new()
        .name("compare-solve".to_string())
        .spawn(move || {
            let session = CompareSession::build(before, after, origin, pose);
            let metrics = SessionMetrics::measure(&session, lighting);
            let _ = slint::invoke_from_event_loop(move || {
                host::on_session_built(id, session, metrics);
            });
        });
    if let Err(error) = spawned {
        warn!("Could not start the compare solve thread: {error}");
    }
}

/// Builds `origin`'s request from the live editor state and opens it on `surface`,
/// or reports why there is nothing to compare: a toast for the window, the pane's
/// own status line for the embedded pane (which refreshes unasked).
fn open_from(
    deps: &CompareDeps,
    surface: Surface,
    build: impl FnOnce(
        &MainWindow,
        &EditorState,
        &Arc<Mutex<RenderContext>>,
    ) -> Result<OpenRequest, String>,
) {
    let Some(ui) = deps.ui.upgrade() else {
        return;
    };
    let request = {
        // A writer mid-edit holds the state: skip this click rather than panic.
        let Ok(st) = deps.state.try_borrow() else {
            return;
        };
        build(&ui, &st, &deps.render_ctx)
    };
    let lighting =
        LightingPreset::from_index(ui.global::<ViewportModel>().get_selected_lighting_index());
    match request {
        Ok(request) => open_session(deps, surface, request, lighting),
        Err(reason) if surface == Surface::Embedded => host::drop_embedded(&reason),
        Err(reason) => show_toast(&ui, &reason, "info"),
    }
}

/// The Retarget dialog's pane (re)opens on the current proposal -- on the window
/// instead when this Retarget session has been popped out into it.
fn open_retarget_embedded(deps: &CompareDeps) {
    let surface = if host::live_kind() == Some((Surface::Window, CompareOrigin::Retarget)) {
        Surface::Window
    } else {
        Surface::Embedded
    };
    open_from(deps, surface, origins::retarget_request);
}

/// Opens the pop-out window on two designs from the Variants view.
///
/// `first` goes on the before side and `second` on the after side. View only (no Keep or
/// Discard). Does nothing before [`setup_entry_callbacks`] has run.
pub(in crate::gui::editor) fn open_variants_compare(
    ui: &MainWindow,
    first: VariantSide,
    second: VariantSide,
) {
    let Some(deps) = ENTRY_DEPS.with(|cell| cell.borrow().clone()) else {
        return;
    };
    let lighting =
        LightingPreset::from_index(ui.global::<ViewportModel>().get_selected_lighting_index());
    let request = origins::variants_request(&deps.render_ctx, first, second);
    open_session(&deps, Surface::Window, request, lighting);
}

/// Wires `MainWindow`'s own `CompareModel` instance: the three pop-out entry points
/// (the Retarget dialog's and the Optimize tab's "Compare…" buttons and the snapshot
/// table's "Compare visually…"), and the embedded pane's view callbacks and
/// open/close handlers.
pub(super) fn setup_entry_callbacks(ui: &MainWindow, deps: &CompareDeps) {
    host::set_main_window(ui);
    ENTRY_DEPS.with(|cell| *cell.borrow_mut() = Some(deps.clone()));
    let model = ui.global::<CompareModel>();
    let retarget_deps = deps.clone();
    model.on_open_retarget(move || {
        open_from(&retarget_deps, Surface::Window, origins::retarget_request);
    });
    let optimize_deps = deps.clone();
    model.on_open_optimize(move || {
        open_from(&optimize_deps, Surface::Window, |_, st, render_ctx| {
            origins::optimize_request(st, render_ctx, origins::Reference::Current)
        });
    });
    let snapshot_deps = deps.clone();
    model.on_open_snapshot(move || {
        open_from(&snapshot_deps, Surface::Window, |_, st, render_ctx| {
            origins::snapshot_request(st, render_ctx)
        });
    });
    register_view_callbacks(&model, Surface::Embedded);
    let embedded_deps = deps.clone();
    model.on_open_retarget_embedded(move || open_retarget_embedded(&embedded_deps));
    model.on_close_embedded(host::close_embedded_session);
}