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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Camera orbit/zoom, light move/position/reset, and HDR environment-map load/clear
//! callback wiring.
//!
//! Split out of `gui::mod` purely to keep that module (already sizeable) from growing
//! further -- same reasoning as `gui::detail`/`gui::search`/`gui::remote`.

use crate::{
    MainWindow, SettingsModel, SolidPreviewModel, ViewportModel,
    bridge::render_thread::{RenderContext, load_env_map},
    gui::{
        env_map_status_text, show_toast,
        solid_preview::preview_state::{CameraPose, SolidPreviewState},
    },
    settings::SettingsPersister,
};
use indicatrix_solid::preview::StoneGeometryBuf;
use slint::{ComponentHandle, SharedString};
use std::{
    f32::consts::FRAC_PI_2,
    sync::{Arc, Mutex},
};

/// Re-issues `ctx`'s current `active_planes` at its (just-updated) camera pose to
/// `preview_state`, sized to the Solid viewport's own logical size --
/// camera-follow only (same
/// planes, new pose), never a re-solve. A no-op while nothing has been solved
/// into the shared viewport yet (`active_planes` empty), matching
/// `gui::editor::view::refresh_viewport`'s own "no design, no planes" contract.
///
/// Picks which viewport's own view-mode to redraw at, and whether to bother at all:
/// - Live Render tab (`ui.get_render_view_tab() == 0`): always Solid (`view_mode` 0,
///   forced -- see [`resubmit_live_solid`]'s own doc comment for why this must never
///   leak the Edit tab's `SolidPreviewModel.view_mode`), and ONLY when that tab's own
///   `ViewportModel.live_view_mode` is actually `0` (Solid) -- a camera drag while the
///   Live tab is showing the path-traced image has no solid on screen to redraw, so
///   this is a no-op rather than wasted background work.
/// - Edit tab (`render_view_tab != 0`): the Edit tab's own `SolidPreviewModel.
///   view_mode`, unconditionally -- unchanged from before `live_view_mode` existed
///   (the Solid viewport's camera-follow always ran regardless of which of its four
///   modes was showing, so it was already up to date the moment the user switched to
///   it).
///
/// Also forwards `ctx.design_gear` (the currently loaded design's gear tooth
/// count/reference angle) so a Diagram-mode (`view_mode` 3) camera drag shows THIS
/// design's gear wheel -- via [`SolidPreviewState::request_redraw_with_gear`],
/// not the plain `request_redraw` -- rather than whatever gear info a previous
/// editor replan happened to leave in the worker's own `DiagramMemory`, which is
/// unrelated once the currently viewed design was loaded some other way (e.g. from
/// the library, never replanned through the editor). See
/// `bridge::render_thread::RenderContext::design_gear`'s doc comment for the full
/// list of writers that keep it in sync with `active_planes`.
///
/// Sizes to the Live Render tab's OWN `SolidPreviewModel.
/// live_viewport_width`/`live_viewport_height` while `on_live_tab`, never the Edit
/// tab's `viewport_width`/`viewport_height`: `gem_viewport.slint` and
/// `solid_viewport.slint` each drive their own pair of properties, keeping one
/// viewport's resize from silently overwriting the other's pending redraw size.
///
/// Both dimensions are scaled by `ui.window().scale_factor()` so the solid
/// rasterizer/diagram renderer produce a HiDPI-correct (physical-pixel) raster
/// instead of a logical-pixel one Slint then has to upscale blurrily. The matching
/// conversion on the input side multiplies the pointer's LOGICAL hover/click
/// position by the same factor to reach the physical pixel it names in the pick
/// buffer; it lives in `solid_preview::diagram_wiring` for the diagram and in
/// `gui::editor::callbacks::tier_actions` for the solid view.
pub(in crate::gui) fn resubmit_at_current_pose(
    ui: &MainWindow,
    ctx: &RenderContext,
    preview_state: &SolidPreviewState,
) {
    if ctx.active_planes.is_empty() {
        return;
    }
    let on_live_tab = ui.get_render_view_tab() == 0;
    if on_live_tab && ui.global::<ViewportModel>().get_live_view_mode() != 0 {
        return;
    }
    let view_mode = if on_live_tab {
        0
    } else {
        ui.global::<SolidPreviewModel>().get_view_mode() as u8
    };
    let stone = active_stone(ctx);
    let scale = ui.window().scale_factor();
    let size = if on_live_tab {
        (
            (ui.global::<SolidPreviewModel>().get_live_viewport_width() * scale) as u32,
            (ui.global::<SolidPreviewModel>().get_live_viewport_height() * scale) as u32,
        )
    } else {
        let viewport_size = (
            (ui.global::<SolidPreviewModel>().get_viewport_width() * scale) as u32,
            (ui.global::<SolidPreviewModel>().get_viewport_height() * scale) as u32,
        );
        // Path-traced/Both letterbox the traced image to `ctx.width`/
        // `ctx.height`'s own aspect ratio (`solid_viewport.slint`'s
        // `image-fit: contain`) whenever it differs from the viewport's --
        // `contained_request_size`'s own doc comment.
        contained_request_size(view_mode, viewport_size, (ctx.width, ctx.height))
    };
    let pose = CameraPose {
        yaw: ctx.yaw,
        pitch: ctx.pitch,
        distance: ctx.distance,
    };
    if on_live_tab {
        // The Live Render tab shows the committed design only: a Slice tier that is not
        // kept yet is an Edit-tab preview (see `request_redraw_committed_geometry`).
        preview_state.request_redraw_committed_geometry(
            stone,
            pose,
            size,
            view_mode,
            ctx.design_gear,
        );
    } else {
        preview_state.request_redraw_geometry(stone, pose, size, view_mode, ctx.design_gear);
    }
}

/// The stone `ctx` currently holds -- planes, concave tools and each tool's
/// `(tier, placement)` -- as the owning geometry a camera-follow redraw carries.
///
/// The planes go through the same `(normal, -d)` flip the preview has always used, so a
/// planar stone is the request it always was; the tools ride along unchanged, which is
/// what stops a camera drag from redrawing a concave design as its flat hull.
fn active_stone(ctx: &RenderContext) -> StoneGeometryBuf {
    StoneGeometryBuf {
        planes: ctx.active_planes.as_ref().clone(),
        tools: ctx.active_tools.as_ref().clone(),
        placements: ctx.active_placements.clone(),
    }
}

/// Shrinks `viewport_size` to the rectangle Slint's `image-fit: contain` draws
/// `render_size` into.
///
/// `solid_viewport.slint`'s Path-traced/Both `Image` elements (`ViewportModel.
/// render_image`, `SolidPreviewModel.edges_image`) are both `image-fit: contain`
/// against a `render_size` (the configured render resolution, `RenderContext::
/// width`/`height`) that is independent of the viewport's own logical size --
/// with a render resolution wider than the viewport (a common pairing: 1920x1080
/// against a docked ~1.2-1.5 aspect Edit viewport), `contain` fits the image's
/// WIDTH and letterboxes it top/bottom, drawn SMALLER than a solid/edges raster
/// still requested at the viewport's raw, un-letterboxed size. The edges overlay
/// then reads as larger than the render it is supposed to trace, and a click
/// lands on the visible (letterboxed) gem while indexing a pick buffer sized to
/// the viewport's own full rectangle. Requesting the solid/edges raster at THIS
/// function's output size instead keeps every pixel of the request inside the
/// same rectangle the traced image actually occupies on screen.
///
/// Used only for `view_mode` `1` (Path-traced) and `2` (Both) -- Solid (`0`) and
/// Diagram (`3`) never show `render_image` at all, so the viewport's own raw
/// size is already correct for them, returned unchanged (also returned unchanged
/// if either dimension is `0`, i.e. nothing to divide by, or nothing requested
/// yet).
///
/// `gui::editor::view::scaled_viewport_size`'s own callers
/// (`refresh_viewport`, `submit_preview_replan`) compute
/// the SAME viewport-sized request independently, for the post-edit/post-solve
/// path this function's own caller (`resubmit_at_current_pose`) does not cover.
/// They need the identical treatment: read `SolidPreviewModel.view_mode` and
/// `render_ctx.width`/`height` at the call site and pass the result through this
/// function (or an equivalent copy) before calling `request_replan`/
/// `request_redraw_with_gear`, or the misregistration this fixes for a camera
/// drag/zoom/view-mode switch will still reappear immediately after the next
/// edit or Solve.
#[must_use]
pub(in crate::gui) fn contained_request_size(
    view_mode: u8,
    viewport_size: (u32, u32),
    render_size: (u32, u32),
) -> (u32, u32) {
    if !matches!(view_mode, 1 | 2) {
        return viewport_size;
    }
    let (viewport_width, viewport_height) = viewport_size;
    let (render_width, render_height) = render_size;
    if viewport_width == 0 || viewport_height == 0 || render_width == 0 || render_height == 0 {
        return viewport_size;
    }
    let viewport_aspect = viewport_width as f32 / viewport_height as f32;
    let render_aspect = render_width as f32 / render_height as f32;
    if render_aspect > viewport_aspect {
        // The traced image is wider than the viewport -- `contain` fits its
        // width and shrinks its height.
        let height = (viewport_width as f32 / render_aspect).round().max(1.0) as u32;
        (viewport_width, height)
    } else {
        // The traced image is taller/narrower than the viewport -- `contain`
        // fits its height and shrinks its width. Already the on-screen size
        // whenever `render_aspect <= viewport_aspect`, so this branch is a near
        // no-op in that case beyond rounding.
        let width = (viewport_height as f32 * render_aspect).round().max(1.0) as u32;
        (width, viewport_height)
    }
}

// The orbit clamp (`orbit_distance_bounds`), the "Fit" distance
// (`fit_distance_for_radius`) and the pitch wrap (`wrap_pitch`) moved to
// `indicatrix_solid::preview::camera` (shared with the web app's Solid view);
// re-exported here at their old paths. This module's tests below stay as their
// pins.
pub(in crate::gui) use indicatrix_solid::preview::camera::{
    fit_distance_for_radius, orbit_distance_bounds, wrap_pitch,
};

/// The Live Render tab's own solid-raster redraw: identical to
/// [`resubmit_at_current_pose`]'s Live-tab branch, except it never checks
/// `ViewportModel.live_view_mode` first -- every call site here already knows the
/// solid image is (about to become) visible before calling this (a library
/// selection while already in Solid mode, or `live_view_mode` itself just flipping to
/// `0`), so re-checking would be redundant. ALWAYS forces `view_mode` `0` (Solid
/// raster): the Live Render tab shows only the flat-shaded raster, never the Edit
/// tab's own Path-traced/Both/Diagram choice (`SolidPreviewModel.view_mode`), which
/// must not leak across tabs -- two independent viewports sharing one worker/one
/// `SolidPreviewState`, each entitled to its own mode.
///
/// Called from: `gui::library::diagram_list::setup_diagram_selection_and_export_callbacks`/
/// `gui::library::detail::apply_design_record_to_ui` (a library selection lands while
/// the Live tab is already in Solid mode -- the planes `apply_reconstructed_planes`
/// just wrote need an immediate redraw, not a wait for the next camera drag), and
/// `gui::mod`'s `on_live_view_mode_changed` handler (switching INTO Solid mode itself
/// must show something immediately, not wait for a drag).
///
/// Always sizes to the Live Render tab's OWN `SolidPreviewModel.
/// live_viewport_width`/`live_viewport_height` (never the Edit tab's
/// `viewport_width`/`viewport_height` -- see [`resubmit_at_current_pose`]'s doc
/// comment), scaled by `ui.window().scale_factor()` for a HiDPI-correct raster.
pub(in crate::gui) fn resubmit_live_solid(
    ui: &MainWindow,
    ctx: &RenderContext,
    preview_state: &SolidPreviewState,
) {
    if ctx.active_planes.is_empty() {
        return;
    }
    let stone = active_stone(ctx);
    let scale = ui.window().scale_factor();
    let size = (
        (ui.global::<SolidPreviewModel>().get_live_viewport_width() * scale) as u32,
        (ui.global::<SolidPreviewModel>().get_live_viewport_height() * scale) as u32,
    );
    // Committed planes only: the Slice tool's provisional tier is an Edit-tab preview.
    preview_state.request_redraw_committed_geometry(
        stone,
        CameraPose {
            yaw: ctx.yaw,
            pitch: ctx.pitch,
            distance: ctx.distance,
        },
        size,
        0,
        ctx.design_gear,
    );
}

/// Wires `ViewportModel.on_light_move`/`on_light_pos_changed`, persisting the
/// result through the debounced `settings_store` exactly like every other pose
/// callback in this module. Split out of [`setup_camera_and_lighting_callbacks`]
/// purely to keep that function under clippy's function-length lint (the
/// `mesh_bounding_radius` clamp added there pushed it over the limit) -- these two
/// callbacks are otherwise unrelated to the camera pose/distance ones that stayed
/// behind.
fn setup_light_callbacks(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    settings_store: &Arc<SettingsPersister>,
) {
    let render_ctx_light = render_ctx.clone();
    let settings_store_light = settings_store.clone();
    ui.global::<ViewportModel>()
        .on_light_move(move |dx: f32, dy: f32| {
            let (light_yaw, light_pitch) = {
                let mut ctx = RenderContext::lock(&render_ctx_light);
                ctx.light_yaw = dx.mul_add(0.01, ctx.light_yaw);
                ctx.light_pitch = dy.mul_add(0.01, ctx.light_pitch).clamp(0.15, 1.55);
                ctx.dirty = true;
                (ctx.light_yaw, ctx.light_pitch)
            };
            settings_store_light.update(|s| {
                s.settings.light_yaw_deg = light_yaw.to_degrees();
                s.settings.light_pitch_deg = light_pitch.to_degrees();
            });
        });

    let render_ctx_light_pos = render_ctx.clone();
    let settings_store_light_pos = settings_store.clone();
    ui.global::<ViewportModel>()
        .on_light_pos_changed(move |yaw_deg: f32, pitch_deg: f32| {
            {
                let mut ctx = RenderContext::lock(&render_ctx_light_pos);
                ctx.light_yaw = yaw_deg.to_radians();
                ctx.light_pitch = pitch_deg.to_radians().clamp(0.15, 1.55);
                ctx.dirty = true;
            }
            settings_store_light_pos.update(|s| {
                s.settings.light_yaw_deg = yaw_deg;
                s.settings.light_pitch_deg = pitch_deg;
            });
        });
}

/// `ViewportModel.set_view`: `0` = Front (girdle edge-on, index 0 towards the
/// viewer), `1` = Top (straight down onto the table, the batch previews' own top
/// pose), `2` = Bottom, `3` = Left, `4` = Right (the commonest inspection for
/// windowing), and `5` = Fit, which uniquely leaves the CURRENT
/// orbit angle alone and only recomputes `distance` from the live mesh's own
/// bounding radius (`mesh_bounding_radius`) via [`fit_distance_for_radius`], so a
/// cutter who has orbited to an awkward angle can recover a usable framing
/// without also losing the angle they were inspecting. Every other kind resets
/// yaw to a canonical angle; distance and lighting stay untouched for those.
/// Both viewports' pose pills call this same callback.
fn setup_set_view_callback(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    settings_store: &Arc<SettingsPersister>,
    preview_state: &Arc<SolidPreviewState>,
    mesh_bounding_radius: &Arc<Mutex<f64>>,
) {
    let render_ctx = render_ctx.clone();
    let settings_store = settings_store.clone();
    let preview_state = Arc::clone(preview_state);
    let mesh_bounding_radius = Arc::clone(mesh_bounding_radius);
    let ui_weak = ui.as_weak();
    ui.global::<ViewportModel>().on_set_view(move |kind: i32| {
        let Some(ui) = ui_weak.upgrade() else {
            return;
        };
        let mut ctx = RenderContext::lock(&render_ctx);
        if kind == 5 {
            let radius = *mesh_bounding_radius.lock().unwrap();
            let (min, max) = orbit_distance_bounds(radius);
            ctx.distance = fit_distance_for_radius(radius).clamp(min, max);
        } else {
            let (yaw, pitch) = match kind {
                1 => (0.0, FRAC_PI_2),  // Top
                2 => (0.0, -FRAC_PI_2), // Bottom
                3 => (-FRAC_PI_2, 0.0), // Left
                4 => (FRAC_PI_2, 0.0),  // Right
                _ => (0.0, 0.0),        // Front, and any unrecognized kind
            };
            ctx.yaw = yaw;
            ctx.pitch = pitch;
        }
        ctx.dirty = true;
        resubmit_at_current_pose(&ui, &ctx, &preview_state);
        let (yaw, pitch, distance) = (ctx.yaw, ctx.pitch, ctx.distance);
        drop(ctx);
        settings_store.update(|s| {
            s.settings.camera_yaw = yaw;
            s.settings.camera_pitch = pitch;
            s.settings.camera_distance = distance;
        });
    });
}

/// Wires up camera orbit/zoom, light move/position, and reset-camera callbacks. Each
/// also feeds the debounced `settings_store` so camera pose and light position survive
/// a restart. Split out of `run_gui` purely to keep that function under
/// clippy's function-length lint.
///
/// `preview_state` is the solid-inspection preview controller -- dragging or
/// zooming the Live Render viewport also moves the Solid viewport's shared
/// camera (yaw/pitch/distance), so both `on_camera_orbit`/`on_camera_zoom` below
/// re-issue the last solved plane set at the new pose (see
/// `resubmit_at_current_pose`) while still holding `render_ctx`'s lock.
pub(in crate::gui) fn setup_camera_and_lighting_callbacks(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    settings_store: &Arc<SettingsPersister>,
    preview_state: &Arc<SolidPreviewState>,
    mesh_bounding_radius: &Arc<Mutex<f64>>,
) {
    let render_ctx_orbit = render_ctx.clone();
    let settings_store_orbit = settings_store.clone();
    let preview_state_orbit = Arc::clone(preview_state);
    let ui_weak_orbit = ui.as_weak();
    ui.global::<ViewportModel>()
        .on_camera_orbit(move |dx: f32, dy: f32| {
            let Some(ui) = ui_weak_orbit.upgrade() else {
                return;
            };
            let (yaw, pitch) = {
                let mut ctx = RenderContext::lock(&render_ctx_orbit);
                // Horizontal drag is INVERTED relative to vertical: dragging right turns
                // the stone's right side toward the viewer, as though the hand were on the
                // gem rather than on the camera. Vertical keeps its sign, which already
                // reads correctly -- the two axes genuinely want opposite conventions here,
                // so the asymmetry is deliberate, not a stray sign.
                ctx.yaw = dx.mul_add(-0.008, ctx.yaw);
                ctx.pitch = wrap_pitch(dy.mul_add(0.008, ctx.pitch));
                ctx.dirty = true;
                resubmit_at_current_pose(&ui, &ctx, &preview_state_orbit);
                (ctx.yaw, ctx.pitch)
            };
            settings_store_orbit.update(|s| {
                s.settings.camera_yaw = yaw;
                s.settings.camera_pitch = pitch;
            });
        });

    let render_ctx_zoom = render_ctx.clone();
    let settings_store_zoom = settings_store.clone();
    let preview_state_zoom = Arc::clone(preview_state);
    let mesh_bounding_radius_zoom = Arc::clone(mesh_bounding_radius);
    let ui_weak_zoom = ui.as_weak();
    ui.global::<ViewportModel>()
        .on_camera_zoom(move |delta: f32| {
            let Some(ui) = ui_weak_zoom.upgrade() else {
                return;
            };
            let distance = {
                let mut ctx = RenderContext::lock(&render_ctx_zoom);
                // The clamp is sized to the CURRENT solid's own bounding radius
                // rather than a fixed `[1.2, 8.0]` range --
                // `orbit_distance_bounds`'s own doc comment.
                let radius = *mesh_bounding_radius_zoom.lock().unwrap();
                let (min, max) = orbit_distance_bounds(radius);
                ctx.distance = delta.mul_add(-0.002, ctx.distance).clamp(min, max);
                ctx.dirty = true;
                resubmit_at_current_pose(&ui, &ctx, &preview_state_zoom);
                ctx.distance
            };
            settings_store_zoom.update(|s| s.settings.camera_distance = distance);
        });

    setup_light_callbacks(ui, render_ctx, settings_store);

    setup_set_view_callback(
        ui,
        render_ctx,
        settings_store,
        preview_state,
        mesh_bounding_radius,
    );

    let render_ctx_reset = render_ctx.clone();
    let settings_store_reset = settings_store.clone();
    let preview_state_reset = Arc::clone(preview_state);
    let ui_weak_reset = ui.as_weak();
    ui.global::<ViewportModel>().on_reset_camera(move || {
        let Some(ui) = ui_weak_reset.upgrade() else {
            return;
        };
        {
            let mut ctx = RenderContext::lock(&render_ctx_reset);
            ctx.yaw = 0.60;
            ctx.pitch = 0.45;
            ctx.distance = 2.4;
            ctx.light_yaw = 0.85;
            ctx.light_pitch = crate::settings::model::DEFAULT_LIGHT_PITCH_DEG.to_radians();
            ctx.dirty = true;
            // Immediately resubmits at the new pose so both viewports (the Edit
            // tab's Solid preview and, when it is showing the solid raster, the
            // Live Render tab) show the reset pose right away, rather than
            // continuing to display the old pose until some unrelated trigger (a
            // camera drag, a view-mode switch) happens to redraw next.
            resubmit_at_current_pose(&ui, &ctx, &preview_state_reset);
            // Explicit: releases the `RenderContext` mutex before
            // `settings_store_reset.update` below, rather than leaving it held
            // until this block's closing brace.
            drop(ctx);
        }
        settings_store_reset.update(|s| {
            s.settings.camera_yaw = 0.60;
            s.settings.camera_pitch = 0.45;
            s.settings.camera_distance = 2.4;
            s.settings.light_yaw_deg = 0.85_f32.to_degrees();
            s.settings.light_pitch_deg = 0.95_f32.to_degrees();
        });
    });
}

/// Mirrors `ViewportModel.camera_drag_begin`/`camera_drag_end` (both viewports' orbit
/// and light drags) into `RenderContext::camera_drag_held` -- see that field's doc
/// comment. Nothing else changes here: the per-move
/// restart in `on_camera_orbit`/`on_light_move` IS the interactive preview and stays.
pub(in crate::gui) fn setup_camera_drag_callbacks(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
) {
    let render_ctx_begin = render_ctx.clone();
    ui.global::<ViewportModel>().on_camera_drag_begin(move || {
        RenderContext::lock(&render_ctx_begin).camera_drag_held = true;
    });

    let render_ctx_end = render_ctx.clone();
    ui.global::<ViewportModel>().on_camera_drag_end(move || {
        RenderContext::lock(&render_ctx_end).camera_drag_held = false;
    });
}

/// Wires up the HDR environment-map load/clear callbacks. Path is a plain typed text
/// field (`settings_dialog.slint`'s "Environment Map (HDR)" section) with no native
/// picker of its own -- unlike `gui::library::setup_import_callback`'s `.asc`
/// pickers, which go through `gui::pickers`. Split out of
/// `run_gui` purely to keep that function under clippy's function-length lint.
pub(in crate::gui) fn setup_environment_map_callbacks(
    ui: &MainWindow,
    render_ctx: &Arc<Mutex<RenderContext>>,
    settings_store: &Arc<SettingsPersister>,
) {
    let render_ctx_load = render_ctx.clone();
    let settings_store_load = settings_store.clone();
    let ui_weak_load = ui.as_weak();
    ui.global::<SettingsModel>()
        .on_load_env_map(move |raw_path: SharedString| {
            let Some(ui) = ui_weak_load.upgrade() else {
                return;
            };
            let path = raw_path.to_string();
            // `load_env_map` never panics -- a missing, unreadable, or malformed file
            // returns `Err` and `RenderContext::env_map`/the settings file are left exactly
            // as they were (see that function's doc comment).
            match load_env_map(&path) {
                Ok(map) => {
                    let status = env_map_status_text(&map, &path);
                    {
                        let mut ctx = RenderContext::lock(&render_ctx_load);
                        ctx.env_map = Some(map);
                        ctx.dirty = true;
                    }
                    settings_store_load.update(|s| s.settings.env_map_path.clone_from(&path));
                    ui.global::<SettingsModel>()
                        .set_env_map_status(status.clone().into());
                    ui.global::<SettingsModel>().set_env_map_loaded(true);
                    // The cutter's own choice is the newest word on the map: a decode of the
                    // design's saved map still on its way must not land over it, and "Use
                    // this lighting for this design" stores this map.
                    super::design_lighting::env_map_chosen();
                    // The GPU megakernel has its own `env_mode` for `HdrMap` and
                    // renders it directly (see `render_thread::mod`'s module doc
                    // comment), so there is no CPU-only restriction to warn about
                    // here.
                    show_toast(&ui, &status, "info");
                }
                Err(err) => {
                    show_toast(
                        &ui,
                        &format!("Could not load HDR environment: {err}"),
                        "error",
                    );
                }
            }
        });

    let render_ctx_clear = render_ctx.clone();
    let settings_store_clear = settings_store.clone();
    let ui_weak_clear = ui.as_weak();
    ui.global::<SettingsModel>().on_clear_env_map(move || {
        let Some(ui) = ui_weak_clear.upgrade() else {
            return;
        };
        {
            let mut ctx = RenderContext::lock(&render_ctx_clear);
            ctx.env_map = None;
            ctx.dirty = true;
        }
        settings_store_clear.update(|s| s.settings.env_map_path.clear());
        ui.global::<SettingsModel>()
            .set_env_map_status(String::new().into());
        ui.global::<SettingsModel>().set_env_map_loaded(false);
        // Clearing is a choice too: a decode still on its way must not bring a map back.
        super::design_lighting::env_map_chosen();
        show_toast(
            &ui,
            "Cleared HDR environment; back to the studio rig.",
            "info",
        );
    });

    // Native file-open picker for `env_map_path` ("Browse..." in
    // `settings_dialog.slint`) -- fills the field, doesn't load anything itself;
    // `on_load_env_map` above still does that, unchanged, whichever way the path got
    // typed in. Filtered to exactly `.hdr`: the only format `EnvironmentMap::from_hdr_file`
    // (crates/indicatrix/src/renderer/env_map.rs) decodes, via `image::ImageFormat::Hdr`.
    // `env_map_path` is simply left unchanged when the user cancels.
    //
    // `pick_hdr_file` is void (`ui/models/settings.slint`): Slint has no way to
    // await a value-returning callback, so `settings_dialog.slint`'s click handler
    // just fires it, the dialog itself runs off the UI thread through
    // `gui::pickers::pick`, and this closure pushes the chosen path into
    // `env_map_path` from the completion continuation once the picker returns.
    let ui_weak_pick_hdr = ui.as_weak();
    ui.global::<SettingsModel>()
        .on_pick_hdr_file(move |current: SharedString| {
            use crate::gui::pickers::{PickerFilter, PickerKind, PickerRequest, pick};

            let Some(ui) = ui_weak_pick_hdr.upgrade() else {
                return;
            };
            let starting_dir = crate::gui::starting_dir_from_picker_field(current.as_str());
            let request = PickerRequest {
                kind: PickerKind::OpenFile,
                title: None,
                filters: vec![PickerFilter {
                    label: "Radiance HDR".to_string(),
                    extensions: vec!["hdr".to_string()],
                }],
                default_file_name: None,
                starting_dir,
            };
            pick(&ui, request, |ui, picked| {
                if let Some(path) = picked {
                    ui.global::<SettingsModel>()
                        .set_env_map_path(path.display().to_string().into());
                }
            });
        });
}

#[cfg(test)]
mod tests {
    use super::{contained_request_size, fit_distance_for_radius, orbit_distance_bounds};

    // --- contained_request_size ---

    #[test]
    fn solid_and_diagram_modes_are_untouched() {
        // Only Path-traced (1) and Both (2) show `render_image` at all --
        // Solid (0) and Diagram (3) must keep the viewport's own raw size.
        for mode in [0, 3] {
            assert_eq!(
                contained_request_size(mode, (900, 500), (1920, 1080)),
                (900, 500)
            );
        }
    }

    #[test]
    fn wider_render_than_viewport_shrinks_height_to_the_letterboxed_rectangle() {
        // A 1920x1080 (16:9) render in a 900x700 (~1.29) viewport: `contain`
        // fits the width and shrinks the height, exactly matching what
        // `solid_viewport.slint`'s `image-fit: contain` draws on screen.
        let (width, height) = contained_request_size(2, (900, 700), (1920, 1080));
        assert_eq!(width, 900);
        assert_eq!(height, 506);
    }

    #[test]
    fn narrower_render_than_viewport_is_already_the_on_screen_size() {
        // A 4:3 render in a wider viewport: `contain` fits the height here and the
        // two layers already agree pixel-for-pixel, so this is a no-op beyond
        // reproducing the exact viewport height.
        let (width, height) = contained_request_size(1, (900, 500), (640, 480));
        assert_eq!(height, 500);
        assert_eq!(width, 667);
    }

    #[test]
    fn zero_sized_input_is_returned_unchanged_rather_than_dividing_by_zero() {
        assert_eq!(contained_request_size(2, (0, 500), (1920, 1080)), (0, 500));
        assert_eq!(contained_request_size(2, (900, 500), (0, 1080)), (900, 500));
    }

    #[test]
    fn equal_aspect_ratios_pass_through_unchanged() {
        assert_eq!(
            contained_request_size(2, (1920, 1080), (1920, 1080)),
            (1920, 1080)
        );
    }

    // --- orbit_distance_bounds ---

    #[test]
    fn default_bounding_radius_reproduces_the_old_fixed_clamp() {
        // 1.5 is `DEFAULT_MESH_BOUNDING_RADIUS` -- the common case must
        // keep the exact `[1.2, 8.0]` clamp behavior.
        let (min, max) = orbit_distance_bounds(1.5);
        assert!((min - 1.2).abs() < 1e-6, "got {min}");
        assert!((max - 8.0).abs() < 1e-6, "got {max}");
    }

    #[test]
    fn a_larger_mesh_gets_a_wider_clamp() {
        let (small_min, small_max) = orbit_distance_bounds(1.5);
        let (large_min, large_max) = orbit_distance_bounds(4.5);
        assert!(large_min > small_min);
        assert!(large_max > small_max);
    }

    #[test]
    fn a_zero_radius_never_collapses_the_clamp_to_a_single_point() {
        let (min, max) = orbit_distance_bounds(0.0);
        assert!(min > 0.0);
        assert!(max > min);
    }

    // --- fit_distance_for_radius ---

    #[test]
    fn fit_distance_grows_with_the_bounding_radius() {
        assert!(fit_distance_for_radius(3.0) > fit_distance_for_radius(1.5));
    }

    #[test]
    fn fit_distance_stays_within_the_matching_orbit_clamp() {
        // The "Fit" pose (`setup_set_view_callback`) always clamps its own
        // result through `orbit_distance_bounds` of the SAME radius -- this
        // confirms that combination lands inside a sensible range rather than,
        // say, the unclamped `fit_distance_for_radius` output being clamped
        // down to something that no longer frames the mesh at all.
        let radius = 1.5_f64;
        let (min, max) = orbit_distance_bounds(radius);
        let fit = fit_distance_for_radius(radius).clamp(min, max);
        assert!(fit >= min && fit <= max);
    }
}