From a36a577c3b8e308cdac60067be0b9520da94b152 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 03:35:55 +0100 Subject: [PATCH] cargo fmt --all --- apps/lightcraft/src/main.rs | 15 +- crates/ui-egui/src/app/completion.rs | 193 +++++++++--- crates/ui-egui/src/app/control.rs | 52 +++- crates/ui-egui/src/app/frame.rs | 11 +- crates/ui-egui/src/app/shell.rs | 68 +++-- crates/ui-egui/src/control.rs | 44 ++- crates/ui-egui/src/dialogs.rs | 142 ++++----- crates/ui-egui/src/dialogs/cull.rs | 7 +- .../ui-egui/src/dialogs/cull_wave110_tests.rs | 6 +- crates/ui-egui/src/dialogs/export/core.rs | 5 +- crates/ui-egui/src/dialogs/import/body.rs | 18 +- crates/ui-egui/src/dialogs/import/tags.rs | 3 +- crates/ui-egui/src/dialogs/keymap.rs | 23 +- .../src/dialogs/keymap_external155_tests.rs | 8 +- .../src/dialogs/label_names_flow_tests.rs | 48 +-- crates/ui-egui/src/dialogs/merge.rs | 106 +++++-- .../ui-egui/src/dialogs/merge_sdk155_tests.rs | 17 +- .../src/dialogs/print_template_flow_tests.rs | 3 +- crates/ui-egui/src/dialogs/print_view.rs | 12 +- .../src/dialogs/rules_editor/controls.rs | 3 +- .../ui-egui/src/dialogs/settings/controls.rs | 45 +-- .../ui-egui/src/dialogs/settings/display.rs | 18 +- .../ui-egui/src/dialogs/settings/general.rs | 13 +- crates/ui-egui/src/dialogs/settings/import.rs | 13 +- .../src/dialogs/settings/slide_overlays.rs | 48 +-- .../src/dialogs/settings/slide_titles.rs | 5 +- ...ow_export_launcher_candidate_flow_tests.rs | 12 - .../src/dialogs/updates_external155_tests.rs | 12 +- crates/ui-egui/src/dialogs/updates_ui.rs | 7 +- crates/ui-egui/src/docking.rs | 4 +- crates/ui-egui/src/headless/tests.rs | 45 ++- crates/ui-egui/src/i18n.rs | 5 +- crates/ui-egui/src/menus/menubar.rs | 6 +- crates/ui-egui/src/panels/bottombar.rs | 26 +- .../src/panels/bottombar/pick_flow_tests.rs | 6 +- .../bottombar/sort_popup_external_20261119.rs | 91 +++--- .../src/panels/compare_external155_tests.rs | 32 +- crates/ui-egui/src/panels/denoise.rs | 2 - .../src/panels/denoise_queue_actions_tests.rs | 43 ++- crates/ui-egui/src/panels/detail.rs | 2 +- crates/ui-egui/src/panels/detail/filmstrip.rs | 257 ++++++++-------- crates/ui-egui/src/panels/detail/host.rs | 10 +- crates/ui-egui/src/panels/detail/masks.rs | 6 +- crates/ui-egui/src/panels/edit/curve.rs | 124 ++++---- .../edit/curve_preset_workflow_tests.rs | 43 ++- .../src/panels/edit/curve_reset_menu_tests.rs | 31 +- crates/ui-egui/src/panels/edit/grading.rs | 13 +- .../edit/grading_wheel_eye_port_tests.rs | 10 +- crates/ui-egui/src/panels/edit/histogram.rs | 51 ++-- crates/ui-egui/src/panels/edit/lens_blur.rs | 15 +- .../lens_blur_controls_external155_tests.rs | 1 - .../ui-egui/src/panels/edit/light_controls.rs | 18 +- crates/ui-egui/src/panels/edit/mixer.rs | 10 +- crates/ui-egui/src/panels/edit/sliders.rs | 4 +- .../panels/edit/soft_proof_wave155_tests.rs | 54 +++- .../panels/empty_library_action_port_tests.rs | 37 ++- crates/ui-egui/src/panels/filterbar.rs | 7 +- crates/ui-egui/src/panels/filterbar/tests.rs | 1 - .../filterbar_actions_external155_tests.rs | 21 +- crates/ui-egui/src/panels/grid.rs | 4 +- crates/ui-egui/src/panels/keyword_list.rs | 6 +- crates/ui-egui/src/panels/keywording.rs | 41 +-- crates/ui-egui/src/panels/keywording/add.rs | 1 - crates/ui-egui/src/panels/left/albums.rs | 11 +- .../src/panels/left/date_filter_flow_tests.rs | 7 +- crates/ui-egui/src/panels/left/dates.rs | 2 - crates/ui-egui/src/panels/left/folders.rs | 12 +- crates/ui-egui/src/panels/left/local.rs | 4 +- crates/ui-egui/src/panels/left/rows.rs | 12 +- crates/ui-egui/src/panels/left/sections.rs | 17 +- crates/ui-egui/src/panels/library_problem.rs | 80 ++--- .../mask_component_actions_flow_tests.rs | 1 - crates/ui-egui/src/panels/mask_controls.rs | 28 +- crates/ui-egui/src/panels/mask_effects.rs | 10 +- crates/ui-egui/src/panels/masking.rs | 28 +- crates/ui-egui/src/panels/notices.rs | 124 ++++---- crates/ui-egui/src/panels/person.rs | 28 +- crates/ui-egui/src/panels/presets.rs | 8 +- ...profile_group_headers_external155_tests.rs | 114 +++++-- .../src/panels/profile_tile_favorite_tests.rs | 279 +++++++++++++----- crates/ui-egui/src/panels/profiles.rs | 111 +++++-- crates/ui-egui/src/panels/right/crop.rs | 5 +- .../crop_checkboxes_external155_tests.rs | 20 +- .../panels/right/crop_overlay_flow_tests.rs | 9 +- crates/ui-egui/src/panels/right/history.rs | 96 +++--- .../panels/right/history_sdk_action_tests.rs | 182 +++++++++--- crates/ui-egui/src/panels/right/info.rs | 17 +- .../src/panels/right/info_copyright_tests.rs | 10 +- crates/ui-egui/src/panels/right/keywords.rs | 107 ++++--- .../right/remove_controls_flow_tests.rs | 6 +- crates/ui-egui/src/panels/strip.rs | 121 ++++---- .../src/panels/tests_named_person_actions.rs | 15 +- crates/ui-egui/src/panels/topbar.rs | 3 +- .../src/panels/unnamed_faces_port_tests.rs | 86 ++++-- crates/ui-egui/src/shortcuts.rs | 20 +- crates/ui-egui/src/tests.rs | 8 +- crates/ui-egui/src/tests/guided_guides.rs | 15 +- crates/ui-egui/src/tests/library_problem.rs | 9 +- crates/ui-egui/src/tests/panels.rs | 4 +- crates/ui-egui/src/tests/port_screenshots.rs | 28 +- crates/ui-egui/src/tests/rating.rs | 7 +- crates/ui-egui/src/tests/real_journey.rs | 249 +++------------- crates/ui-egui/src/widgets.rs | 9 +- crates/ui-egui/src/widgets/album_picker.rs | 12 +- crates/ui-egui/src/widgets/date_picker.rs | 3 +- crates/ui-egui/src/widgets/rating.rs | 7 +- crates/ui-egui/src/widgets/slider.rs | 18 +- crates/ui-egui/src/widgets/tests_hit_area.rs | 4 +- crates/ui-egui/src/widgets/text_button.rs | 1 - crates/ui-egui/src/widgets/text_field.rs | 7 +- crates/ui-egui/tests/it/docking_workflows.rs | 19 +- crates/ui-egui/tests/it/landmarks.rs | 36 ++- crates/ui-egui/tests/it/local_places.rs | 12 +- crates/ui-egui/tests/it/sidebar_names.rs | 36 +-- crates/ui-egui/tests/it/thumb_size_slider.rs | 12 +- 115 files changed, 2408 insertions(+), 1645 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 2cf1cf1b0a..fce1775aca 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -223,7 +223,9 @@ impl eframe::App for App { self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { - if let Some(window) = &self.2 { self.0.drain_ui_completions(&window.ctx); } + if let Some(window) = &self.2 { + self.0.drain_ui_completions(&window.ctx); + } // (a size the window was just given is remembered too) self.0.ui.window = self.1.window_at_exit(self.0.ui.window); if let Err(e) = self.1.save(&self.0) { @@ -734,7 +736,11 @@ fn native_exit_drains_the_final_owned_output_before_shutdown() { inner.install_framework(&ctx); let mut app = App(inner, PrefsWriter::default(), Some(HostWindow { ctx: ctx.clone(), textures: None }), NightlyExit::none()); for _ in 0..3 { - ctx.run_ui(egui::RawInput::default(), |ui| { app.0.logic(ui.ctx()); app.0.ui(ui); }).drop_without_applying_deltas(); + ctx.run_ui(egui::RawInput::default(), |ui| { + app.0.logic(ui.ctx()); + app.0.ui(ui); + }) + .drop_without_applying_deltas(); } app.0.widgets.clear(); // make the last pending publication observable at the actual exit seam eframe::App::on_exit(&mut app, None); @@ -744,6 +750,9 @@ fn native_exit_drains_the_final_owned_output_before_shutdown() { // Shutdown is process-global: isolate it just like the existing native on_exit tests. let output = std::process::Command::new(std::env::current_exe().unwrap()) .args(["--exact", "native_exit_drains_the_final_owned_output_before_shutdown", "--nocapture"]) - .env("LIGHTCRAFT_TEST_COMPLETION_EXIT", "1").env("LIGHTCRAFT_NO_PREFS", "1").output().unwrap(); + .env("LIGHTCRAFT_TEST_COMPLETION_EXIT", "1") + .env("LIGHTCRAFT_NO_PREFS", "1") + .output() + .unwrap(); assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stdout)); } diff --git a/crates/ui-egui/src/app/completion.rs b/crates/ui-egui/src/app/completion.rs index 01189f2f54..3ca86a78cd 100644 --- a/crates/ui-egui/src/app/completion.rs +++ b/crates/ui-egui/src/app/completion.rs @@ -1,7 +1,7 @@ //! Per-pass presentation facts only. Genuine input stays in the receiving app body. use super::LightcraftApp; -use std::sync::{Weak, atomic::AtomicU8}; use crate::{control::ClipboardFacts, panels, state::GestureFrame, widgets::WidgetHit}; +use std::sync::{Weak, atomic::AtomicU8}; pub(super) struct GestureFacts { pub now_ms: f64, @@ -15,8 +15,7 @@ pub(super) struct GestureFacts { } impl GestureFacts { pub fn ready(&self, gesture: &crate::PendingGesture) -> bool { - gesture.resolved_pass.is_none() && self.now_ms <= gesture.deadline_ms - && self.epoch > gesture.admitted_epoch && self.frame == gesture.frame + gesture.resolved_pass.is_none() && self.now_ms <= gesture.deadline_ms && self.epoch > gesture.admitted_epoch && self.frame == gesture.frame } } pub(super) struct Snapshot { @@ -40,18 +39,19 @@ pub(super) struct Completion { ready: Vec, } impl egui::Plugin for Completion { - fn debug_name(&self) -> &'static str { "lightcraft.host-completion" } + fn debug_name(&self) -> &'static str { + "lightcraft.host-completion" + } fn on_begin_pass(&mut self, ui: &mut egui::Ui) { // This instance belongs to ONE Context. Capture identity before end_pass pops a viewport. - self.stack.push(Pass { - owner: ui.ctx().viewport_id(), max_passes: ui.ctx().options(|o| o.max_passes.get()), body: None, - }); + self.stack.push(Pass { owner: ui.ctx().viewport_id(), max_passes: ui.ctx().options(|o| o.max_passes.get()), body: None }); } fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) { let Some(pass) = self.stack.pop() else { return }; let Some(mut body) = pass.body else { return }; // early return / foreign body is not a layout - if output.platform_output.requested_discard() - && output.platform_output.num_completed_passes < pass.max_passes { return; } + if output.platform_output.requested_discard() && output.platform_output.num_completed_passes < pass.max_passes { + return; + } // Earlier nested output is already valid. Count that completion, never a newer live App frame. if let Some(previous) = self.ready.last() { body.gestures.passes = previous.gestures.passes.wrapping_add(1); @@ -70,11 +70,15 @@ impl egui::Plugin for Completion { let hidden = body.hidden; self.ready.push(body); // Hidden logic has no next body. Visible input/logic drains first; exit drains the last one. - if hidden { ctx.request_repaint_of(pass.owner); } + if hidden { + ctx.request_repaint_of(pass.owner); + } } } pub(super) fn install(ctx: &egui::Context) { - if ctx.plugin_opt::().is_none() { ctx.add_plugin(Completion::default()); } + if ctx.plugin_opt::().is_none() { + ctx.add_plugin(Completion::default()); + } } impl LightcraftApp { pub(crate) fn capture_ui_completion(&mut self, ctx: &egui::Context) { @@ -87,13 +91,18 @@ impl LightcraftApp { self.synthetic_in_flight = false; let body = self.presentation_snapshot(ctx); if let Some(pass) = plugin.lock().stack.last_mut() - && pass.owner == ctx.viewport_id() { pass.body = Some(body); } + && pass.owner == ctx.viewport_id() + { + pass.body = Some(body); + } } /// Host seam: before any next App mutation, and immediately after the final headless output. pub fn drain_ui_completions(&mut self, ctx: &egui::Context) { let Some(plugin) = ctx.plugin_opt::() else { return }; let ready = std::mem::take(&mut plugin.lock().ready); - for body in ready { self.apply_ui_completion(ctx, body); } + for body in ready { + self.apply_ui_completion(ctx, body); + } } } @@ -101,7 +110,10 @@ impl LightcraftApp { mod tests { use super::Completion; use crate::{LightcraftApp, Services}; - use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; fn app(ctx: &egui::Context) -> LightcraftApp { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); app.install_framework(ctx); @@ -109,7 +121,11 @@ mod tests { app } fn raw() -> egui::RawInput { - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))), time: Some(7.0), ..Default::default() } + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))), + time: Some(7.0), + ..Default::default() + } } /// A framework text field named `name`: the paste target the host needs (an `egui` text editor holding the focus). /// `begin` asks for the focus before the field's first input. @@ -130,9 +146,8 @@ mod tests { fn marker(app: &mut LightcraftApp, name: &str) { let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(20.0, 20.0)); app.next_widgets = vec![(name.into(), rect)]; - app.next_widget_hits = vec![(name.into(), crate::widgets::WidgetHit { - id: egui::Id::unique(name), layer_id: egui::LayerId::background(), interact_rect: rect, - })]; + app.next_widget_hits = + vec![(name.into(), crate::widgets::WidgetHit { id: egui::Id::unique(name), layer_id: egui::LayerId::background(), interact_rect: rect })]; } #[test] fn genuine_input_is_visible_before_late_discard_and_empty_retry_never_replays_it() { @@ -140,10 +155,15 @@ mod tests { let mut app = app(&ctx); let effects = Arc::new(AtomicUsize::new(0)); let seen = effects.clone(); - ctx.on_end_pass("late SDK discard", Arc::new(move |ui| { - assert_eq!(seen.load(Ordering::SeqCst), 1, "effect already committed before the late hook"); - if ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("late sizing"); } - })); + ctx.on_end_pass( + "late SDK discard", + Arc::new(move |ui| { + assert_eq!(seen.load(Ordering::SeqCst), 1, "effect already committed before the late hook"); + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("late sizing"); + } + }), + ); let mut input = raw(); input.events.push(egui::Event::Text("accepted".into())); let mut passes = 0; @@ -200,7 +220,8 @@ mod tests { marker(&mut app, "own"); app.pointer_cleanup = true; app.capture_ui_completion(ui.ctx()); - }).drop_without_applying_deltas(); + }) + .drop_without_applying_deltas(); app.set_simulated_clock(Some(100000.0)); app.ui_passes = 900; app.layout_epoch = 900; @@ -229,7 +250,11 @@ mod tests { let mut app = app(&ctx); let mut input = raw(); input.viewports.entry(egui::ViewportId::ROOT).or_default().minimized = Some(true); - ctx.run_ui(input, |ui| { marker(&mut app, "hidden"); app.capture_ui_completion(ui.ctx()); }).drop_without_applying_deltas(); + ctx.run_ui(input, |ui| { + marker(&mut app, "hidden"); + app.capture_ui_completion(ui.ctx()); + }) + .drop_without_applying_deltas(); assert_eq!(app.ui_passes, 0); assert!(ctx.has_requested_repaint(), "output hook woke ordinary hidden logic"); app.logic(&ctx); @@ -245,7 +270,11 @@ mod tests { let (reply, rx) = std::sync::mpsc::channel(); app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "new-target"}), reply).unwrap(); app.ui.filmstrip = !app.ui.filmstrip; - ctx.run_ui(raw(), |ui| { marker(&mut app, "new-target"); app.capture_ui_completion(ui.ctx()); }).drop_without_applying_deltas(); + ctx.run_ui(raw(), |ui| { + marker(&mut app, "new-target"); + app.capture_ui_completion(ui.ctx()); + }) + .drop_without_applying_deltas(); app.drain_ui_completions(&ctx); let response = rx.try_recv().unwrap(); assert_eq!(response["ok"], false); @@ -275,7 +304,10 @@ mod tests { assert!(rx.try_recv().is_err(), "queueing a host command is not delivery"); let mut next = ctx.run_ui(raw(), |ui| app.capture_ui_completion(ui.ctx())); next.textures_delta.clear(); - assert!(next.viewport_output.values().all(|v| v.commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste))), "drain did not reissue a command"); + assert!( + next.viewport_output.values().all(|v| v.commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste))), + "drain did not reissue a command" + ); app.drain_ui_completions(&ctx); assert_eq!(rx.try_recv().unwrap()["ok"], true, "queue acknowledgement only, not host delivery"); } @@ -286,8 +318,10 @@ mod tests { let mut app = app(&ctx); let child = egui::ViewportId::from_hash_of("paste-child"); let (stale, stale_rx) = std::sync::mpsc::channel(); - app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), stale).unwrap(); app.pending_gestures[0].deadline_ms = 0.0; - let mut text = String::new(); let mut parent_text = String::new(); + app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), stale).unwrap(); + app.pending_gestures[0].deadline_ms = 0.0; + let mut text = String::new(); + let mut parent_text = String::new(); // both viewports' fields hold their own keyboard focus before the pass under test focus_field(&ctx, egui::ViewportId::ROOT, "parent-field", &mut parent_text); focus_field(&ctx, child, "child-field", &mut text); @@ -296,11 +330,19 @@ mod tests { let survivor = Arc::downgrade(&app.pending_gestures[1].completion); let (fence, _fence_rx) = std::sync::mpsc::channel(); app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), fence).unwrap(); - ctx.on_end_pass("nested sizing discard", Arc::new(move |ui| { - if discard && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("late parent/child sizing"); } - })); + ctx.on_end_pass( + "nested sizing discard", + Arc::new(move |ui| { + if discard && ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("late parent/child sizing"); + } + }), + ); let mut outer = ctx.run_ui(raw(), |ui| { - if ui.ctx().current_pass_index() > 0 { app.capture_ui_completion(ui.ctx()); return; } + if ui.ctx().current_pass_index() > 0 { + app.capture_ui_completion(ui.ctx()); + return; + } ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste); // unrelated parent request field(ui, "parent-field", &mut parent_text, false); app.capture_ui_completion(ui.ctx()); // SAME pending paste in BOTH real candidates @@ -308,20 +350,46 @@ mod tests { input.viewport_id = child; input.viewports.entry(child).or_default().parent = Some(egui::ViewportId::ROOT); let mut own = ctx.run_ui(input, |child_ui| { - if cancel { app.cancel_gestures_for_barrier(false, "nested prompt"); } + if cancel { + app.cancel_gestures_for_barrier(false, "nested prompt"); + } field(child_ui, "child-field", &mut text, false); child_ui.ctx().send_viewport_cmd(egui::ViewportCommand::Title("unrelated child".into())); app.capture_ui_completion(child_ui.ctx()); }); own.textures_delta.clear(); - assert_eq!(own.viewport_output.get(&child).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(), if cancel { 0 } else { 1 }); - assert!(own.viewport_output.get(&child).unwrap().commands.iter().any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "unrelated child"))); + assert_eq!( + own.viewport_output.get(&child).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(), + if cancel { 0 } else { 1 } + ); + assert!( + own.viewport_output + .get(&child) + .unwrap() + .commands + .iter() + .any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "unrelated child")) + ); assert!(own.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.is_empty(), "child output did not steal parent commands"); - if drain { app.drain_ui_completions(&ctx); } - if drain && !cancel { app.pending_gestures[0].deadline_ms += 2000.0; } + if drain { + app.drain_ui_completions(&ctx); + } + if drain && !cancel { + app.pending_gestures[0].deadline_ms += 2000.0; + } }); outer.textures_delta.clear(); - assert_eq!(outer.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(), 1); + assert_eq!( + outer + .viewport_output + .get(&egui::ViewportId::ROOT) + .unwrap() + .commands + .iter() + .filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)) + .count(), + 1 + ); app.drain_ui_completions(&ctx); assert_eq!((app.ui_passes, app.layout_epoch), (2, 2)); if cancel { @@ -332,7 +400,8 @@ mod tests { assert_eq!(app.pending_gestures[0].resolved_pass, Some(1)); assert!(Arc::ptr_eq(&survivor.upgrade().unwrap(), &app.pending_gestures[0].completion)); assert_eq!(app.pending_gestures[0].deadline_ms, if drain { 17000.0 } else { 15000.0 }); - assert_eq!(stale_rx.try_recv().unwrap()["ok"], false); assert!(rx.try_recv().is_err(), "no false failure/ack while own input remains queued"); + assert_eq!(stale_rx.try_recv().unwrap()["ok"], false); + assert!(rx.try_recv().is_err(), "no false failure/ack while own input remains queued"); } } #[test] @@ -343,9 +412,14 @@ mod tests { let mut app = app(&ctx); super::install(&other); let child = egui::ViewportId::from_hash_of("child"); - ctx.on_end_pass("discard child sizing", Arc::new(move |ui| { - if ui.ctx().viewport_id() == child && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("child sizing"); } - })); + ctx.on_end_pass( + "discard child sizing", + Arc::new(move |ui| { + if ui.ctx().viewport_id() == child && ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("child sizing"); + } + }), + ); let mut output = ctx.run_ui(raw(), |ui| { marker(&mut app, "parent"); app.capture_ui_completion(ui.ctx()); @@ -359,22 +433,47 @@ mod tests { child_ui.ctx().send_viewport_cmd(egui::ViewportCommand::Title("child-output".into())); }); nested.textures_delta.clear(); - assert!(nested.viewport_output.get(&child).unwrap().commands.iter().any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "child-output"))); + assert!( + nested + .viewport_output + .get(&child) + .unwrap() + .commands + .iter() + .any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "child-output")) + ); assert_eq!(ui.ctx().viewport_id(), egui::ViewportId::ROOT); - if drain { app.drain_ui_completions(&ctx); assert_eq!(app.ui_passes, index + 1); } + if drain { + app.drain_ui_completions(&ctx); + assert_eq!(app.ui_passes, index + 1); + } } other.run_ui(raw(), |_| {}).drop_without_applying_deltas(); }); output.textures_delta.clear(); - assert!(output.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste)), "child command was not reissued to popped parent"); + assert!( + output + .viewport_output + .get(&egui::ViewportId::ROOT) + .unwrap() + .commands + .iter() + .all(|c| !matches!(c, egui::ViewportCommand::RequestPaste)), + "child command was not reissued to popped parent" + ); let plugin = ctx.plugin::(); let mut completion = plugin.lock(); let ready = std::mem::take(&mut completion.ready); - assert_eq!(ready.iter().map(|s| s.widgets[0].0.as_str()).collect::>(), if drain { vec!["parent"] } else { vec!["child", "parent"] }); + assert_eq!( + ready.iter().map(|s| s.widgets[0].0.as_str()).collect::>(), + if drain { vec!["parent"] } else { vec!["child", "parent"] } + ); assert_eq!(ready.iter().map(|s| s.gestures.passes).collect::>(), if drain { vec![3] } else { vec![1, 2] }); assert!(completion.stack.is_empty()); assert!(other.plugin::().lock().ready.is_empty()); - completion.ready = ready; drop(completion); app.drain_ui_completions(&ctx); + completion.ready = ready; + drop(completion); + app.drain_ui_completions(&ctx); let total = if drain { 3 } else { 2 }; assert_eq!((app.ui_passes, app.layout_epoch), (total, total), "all and only valid children plus parent, across drains/discards"); } diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 7bb82ece68..32e9232de6 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,6 +1,6 @@ +use super::completion::GestureFacts; use super::{ControlResponse, GESTURE_TIMEOUT_MS, GestureFrame, LightcraftApp, MAX_PENDING_GESTURES, PendingGesture, Sender, Value}; use crate::control; -use super::completion::GestureFacts; impl LightcraftApp { /// Take the control receiver for this frame, run every queued request whose sender still @@ -81,16 +81,31 @@ impl LightcraftApp { /// completed. A changed view/document/dialog/panel state cancels instead of retargeting. pub(super) fn completion_gestures(&self, ctx: &egui::Context, epoch: u64, passes: u64) -> GestureFacts { let mut facts = GestureFacts { - now_ms: self.tick_now_ms(), frame: self.gesture_frame(), epoch, passes, + now_ms: self.tick_now_ms(), + frame: self.gesture_frame(), + epoch, + passes, deadlines: self.pending_gestures.iter().map(|gesture| (std::sync::Arc::downgrade(&gesture.completion), gesture.deadline_ms)).collect(), - clipboard: control::ClipboardFacts::capture(self, ctx), pastes: Some(Vec::new()), + clipboard: control::ClipboardFacts::capture(self, ctx), + pastes: Some(Vec::new()), }; - facts.pastes = Some(self.pending_gestures.iter().filter_map(|gesture| { - (gesture.resolved_pass.is_none() && gesture.method == "ui.clipboard" - && gesture.params.get("action").and_then(Value::as_str) == Some("paste") - && gesture.params.get("text").and_then(Value::as_str).is_none()).then(|| - (std::sync::Arc::downgrade(&gesture.completion), facts.ready(gesture) && control::check_gesture_numbers(&gesture.method, &gesture.params).is_ok())) - }).collect()); + facts.pastes = Some( + self.pending_gestures + .iter() + .filter_map(|gesture| { + (gesture.resolved_pass.is_none() + && gesture.method == "ui.clipboard" + && gesture.params.get("action").and_then(Value::as_str) == Some("paste") + && gesture.params.get("text").and_then(Value::as_str).is_none()) + .then(|| { + ( + std::sync::Arc::downgrade(&gesture.completion), + facts.ready(gesture) && control::check_gesture_numbers(&gesture.method, &gesture.params).is_ok(), + ) + }) + }) + .collect(), + ); facts } pub(crate) fn resolve_pending_gestures(&mut self, ctx: &egui::Context) { @@ -107,8 +122,11 @@ impl LightcraftApp { let mut keep = Vec::with_capacity(gestures.len()); for mut gesture in gestures.drain(..) { // Allocation identity survives earlier removals; never undo a later progress refresh. - let Some((_, deadline)) = facts.deadlines.iter().find(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))) else { - keep.push(gesture); continue; // admitted after this body: wait for its own captured layout + let Some((_, deadline)) = + facts.deadlines.iter().find(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))) + else { + keep.push(gesture); + continue; // admitted after this body: wait for its own captured layout }; gesture.deadline_ms = gesture.deadline_ms.max(*deadline); if gesture.resolved_pass.is_some() { @@ -138,8 +156,16 @@ impl LightcraftApp { let before = self.synthetic.len(); let outcome = match &facts.pastes { None => control::gesture_events(self, ctx, &gesture.method, &gesture.params), - Some(claims) => control::gesture_events_at(self, ctx, &gesture.method, &gesture.params, - facts.clipboard, control::PasteDispatch::OwnOutput(claims.iter().any(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))))), + Some(claims) => control::gesture_events_at( + self, + ctx, + &gesture.method, + &gesture.params, + facts.clipboard, + control::PasteDispatch::OwnOutput( + claims.iter().any(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))), + ), + ), }; match outcome { Ok(outcome) => { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index ea299d1aee..d52e7d38c6 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,9 +1,9 @@ +use super::completion::Snapshot; use super::{ LightcraftApp, drop_overlay, export_task, focus_scan, import, lightroom_import, merge, monotonic_ms, panels, pick, recheck, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, }; use crate::startup; -use super::completion::Snapshot; impl LightcraftApp { /// Install/refresh fonts once and watch the device and availability caches. Setup, not input. @@ -382,11 +382,14 @@ impl LightcraftApp { pub(super) fn presentation_snapshot(&mut self, ctx: &egui::Context) -> Snapshot { Snapshot { - widgets: std::mem::take(&mut self.next_widgets), hits: std::mem::take(&mut self.next_widget_hits), - image: self.image_rect, ui_time: ctx.input(|i| i.time), + widgets: std::mem::take(&mut self.next_widgets), + hits: std::mem::take(&mut self.next_widget_hits), + image: self.image_rect, + ui_time: ctx.input(|i| i.time), hidden: ctx.input(|i| i.viewport().visible() == Some(false)), gestures: self.completion_gestures(ctx, self.layout_epoch.wrapping_add(1), self.ui_passes.wrapping_add(1)), - notice: panels::notices::capture_completion(self), library: panels::library_problem::capture_completion(self), + notice: panels::notices::capture_completion(self), + library: panels::library_problem::capture_completion(self), } } pub(super) fn apply_ui_completion(&mut self, ctx: &egui::Context, body: Snapshot) { diff --git a/crates/ui-egui/src/app/shell.rs b/crates/ui-egui/src/app/shell.rs index c854adf7df..d1010fb40b 100644 --- a/crates/ui-egui/src/app/shell.rs +++ b/crates/ui-egui/src/app/shell.rs @@ -17,7 +17,6 @@ use super::LightcraftApp; static SIZES: LazyLock> = LazyLock::new(|| Arc::new(craft::theme::AppSizes::parse_or_default(br#"{ "all": { "size.bar.title": 42, "size.rail.width": 48 } }"#))); - /// One current derived size set per context. Changes replace it rather than accumulating /// width/theme/scale entries, while an unchanged extent retains the SDK token-cache identity. fn shell_sizes(ctx: &egui::Context) -> Arc { @@ -138,8 +137,19 @@ mod intrinsic_shell_tests { /// of the source-level intrinsic formula. It compares the actual old and new drawing paths. #[test] fn shell_matches_actual_legacy_canvas_and_rail_rectangles() { - const RAIL: &[&str] = &["icon:presets", "icon:edit", "icon:crop", "icon:remove", "icon:masking", "icon:redeye", - "icon:versions", "icon:activity", "icon:more", "icon:keywords", "icon:info"]; + const RAIL: &[&str] = &[ + "icon:presets", + "icon:edit", + "icon:crop", + "icon:remove", + "icon:masking", + "icon:redeye", + "icon:versions", + "icon:activity", + "icon:more", + "icon:keywords", + "icon:info", + ]; for width in [1025.0, 1400.0] { for scale in [1.0, 1.25] { for zoom in [1.0, 1.25] { @@ -163,9 +173,7 @@ mod intrinsic_shell_tests { let b = shell_sizes(&ctx); assert!(Arc::ptr_eq(&a, &b)); } - fn capture_side(width: f32, scale: f32, zoom: f32, rtl: bool, adapted: bool) - -> (egui::Rect, Vec<(String, egui::Rect, egui::Rect)>) - { + fn capture_side(width: f32, scale: f32, zoom: f32, rtl: bool, adapted: bool) -> (egui::Rect, Vec<(String, egui::Rect, egui::Rect)>) { let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services::default()); let mut view = HeadlessView::new(); view.ctx.set_zoom_factor(zoom); @@ -183,14 +191,20 @@ mod intrinsic_shell_tests { let host_style = ui.style().clone(); AppShell::new(WindowKey::main()) .screen_mode(Bind::given(ScreenMode::Standard)) - .allow_reveal(false).edge_reveal(false).document_tabs(false) + .allow_reveal(false) + .edge_reveal(false) + .document_tabs(false) .title_bar(|ui, _cx, app| { - if craft::ui::runtime::measure::active(ui.ctx()) { return; } + if craft::ui::runtime::measure::active(ui.ctx()) { + return; + } ui.set_style(host_style.clone()); crate::panels::topbar::show(app, ui); }) .end(Slot::new("lightcraft.tools"), |ui, cx, app| { - if craft::ui::runtime::measure::active(ui.ctx()) { return; } + if craft::ui::runtime::measure::active(ui.ctx()) { + return; + } ui.set_style(host_style.clone()); if adapted { crate::panels::strip::show_in_shell(app, ui, cx.env.direction().is_rtl()); @@ -199,14 +213,32 @@ mod intrinsic_shell_tests { } }) .body(|ui, cx, _app| { - if craft::ui::runtime::measure::active(ui.ctx()) { return; } + if craft::ui::runtime::measure::active(ui.ctx()) { + return; + } body = cx.shell().expect("shell body").regions().body; - }).show(ui, &mut app); + }) + .show(ui, &mut app); }); let (rects, registered) = crate::widgets::take_registries(&view.ctx); - hits = registered.iter().filter(|(id, _)| matches!(id.as_str(), - "icon:presets" | "icon:edit" | "icon:crop" | "icon:remove" | "icon:masking" | - "icon:redeye" | "icon:versions" | "icon:activity" | "icon:more" | "icon:keywords" | "icon:info")) + hits = registered + .iter() + .filter(|(id, _)| { + matches!( + id.as_str(), + "icon:presets" + | "icon:edit" + | "icon:crop" + | "icon:remove" + | "icon:masking" + | "icon:redeye" + | "icon:versions" + | "icon:activity" + | "icon:more" + | "icon:keywords" + | "icon:info" + ) + }) .map(|(id, hit)| (id.clone(), rects.iter().find(|(name, _)| name == id).expect("registered rect").1, hit.interact_rect)) .collect(); } @@ -225,12 +257,14 @@ mod intrinsic_shell_tests { assert_eq!(new_hits, old_hits, "rectangles AND clipped interaction areas: width={width} scale={scale} zoom={zoom} rtl={rtl}"); assert_eq!((old_body.top(), old_body.bottom()), (new_body.top(), new_body.bottom())); assert!(new_body.width() >= old_body.width(), "the workspace cannot lose more width"); - if rtl { assert_eq!(old_body.right(), new_body.right()); } - else { assert_eq!(old_body.left(), new_body.left()); } + if rtl { + assert_eq!(old_body.right(), new_body.right()); + } else { + assert_eq!(old_body.left(), new_body.left()); + } } } } } } - } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 43f4e57c43..94ef9a17e9 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -692,12 +692,24 @@ impl ClipboardFacts { } Ok(()) } - pub(crate) fn append_paste(self, output: &mut egui::FullOutput, owner: egui::ViewportId, claim: &std::sync::atomic::AtomicU8, eligible: bool) -> bool { + pub(crate) fn append_paste( + self, + output: &mut egui::FullOutput, + owner: egui::ViewportId, + claim: &std::sync::atomic::AtomicU8, + eligible: bool, + ) -> bool { use std::sync::atomic::Ordering::SeqCst; // State is an output fact, NOT identity: 0 unclaimed, 1 claimed/no paste, 2 appended. - if claim.compare_exchange(0, 1, SeqCst, SeqCst).is_err() { return claim.load(SeqCst) == 2; } - if !eligible { return false; } - if self.check().is_err() { return false; } + if claim.compare_exchange(0, 1, SeqCst, SeqCst).is_err() { + return claim.load(SeqCst) == 2; + } + if !eligible { + return false; + } + if self.check().is_err() { + return false; + } let Some(viewport) = output.viewport_output.get_mut(&owner) else { return false }; viewport.commands.push(egui::ViewportCommand::RequestPaste); claim.store(2, SeqCst); @@ -723,7 +735,12 @@ pub(crate) fn gesture_events(app: &mut LightcraftApp, ctx: &egui::Context, metho } pub(crate) fn gesture_events_at( - app: &mut LightcraftApp, ctx: &egui::Context, method: &str, p: &Value, clipboard: ClipboardFacts, paste: PasteDispatch, + app: &mut LightcraftApp, + ctx: &egui::Context, + method: &str, + p: &Value, + clipboard: ClipboardFacts, + paste: PasteDispatch, ) -> Result { check_gesture_numbers(method, p)?; let s = |k: &str| p.get(k).and_then(Value::as_str); @@ -737,7 +754,11 @@ pub(crate) fn gesture_events_at( let mut at = egui::pos2(r.left() + r.width() * fx as f32, r.top() + r.height() * fy as f32); // With no point asked for, aim at the middle of the part a person can see: a row wider than its // scrolled panel, or a control half under the edge of its pane, still takes a click there. - if f("fx").is_none() && f("fy").is_none() && let Some(seen) = visible_part(ctx, widget_hit(app, id), r) && !seen.contains(at) { + if f("fx").is_none() + && f("fy").is_none() + && let Some(seen) = visible_part(ctx, widget_hit(app, id), r) + && !seen.contains(at) + { at = seen.center(); } if !fx.is_finite() || !fy.is_finite() || !at.is_finite() { @@ -848,7 +869,9 @@ pub(crate) fn gesture_events_at( // below cannot promise dispatch or delivery. With `text`, the synthetic // Event::Paste is filtered and canceled like other injected input. // The exact request's successful own-output witness already passed this one eligibility engine. - if !(matches!(paste, PasteDispatch::OwnOutput(true)) && s("action") == Some("paste") && s("text").is_none()) { clipboard.check()?; } + if !(matches!(paste, PasteDispatch::OwnOutput(true)) && s("action") == Some("paste") && s("text").is_none()) { + clipboard.check()?; + } match s("action") { Some("cut") => app.synthetic.push(egui::Event::Cut), Some("copy") => app.synthetic.push(egui::Event::Copy), @@ -856,7 +879,7 @@ pub(crate) fn gesture_events_at( Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())), None => match paste { PasteDispatch::Context => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste), - PasteDispatch::OwnOutput(true) => {}, + PasteDispatch::OwnOutput(true) => {} PasteDispatch::OwnOutput(false) => return Err("ui.clipboard: its own paste output is unavailable".into()), }, }, @@ -989,6 +1012,9 @@ mod completion_clipboard_tests { assert!(app.synthetic.is_empty()); let claim = std::sync::atomic::AtomicU8::new(0); assert!(!own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, false)); - assert!(!own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, true), "a later candidate cannot revive the earlier refused completion"); + assert!( + !own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, true), + "a later candidate cannot revive the earlier refused completion" + ); } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 654e25ac26..430a624ea5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -21,11 +21,11 @@ pub use confirm::confirm_dialog; pub use cull::{MAX_BURST_GAP, clamp_cull_burst, cull_params, fmt_gap, parse_gap}; use export::group_checklist; pub(crate) use export::preset_lzw_note; -pub use frame::{ConfirmStyle, confirm_style, list_height, prompt}; pub(crate) use frame::field_escape_closes; +pub use frame::{ConfirmStyle, confirm_style, list_height, prompt}; use frame::{ - DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, clicked_backdrop, dialog_field, escaped_field, field, fit_lists, just_opened, only_shows, - return_confirms, + DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, clicked_backdrop, dialog_field, escaped_field, field, fit_lists, just_opened, + only_shows, return_confirms, }; pub(crate) use rename::rename_preview; use rename::{person_rename_plan, rename_body, rename_keyword_body, rename_person_body}; @@ -497,7 +497,8 @@ fn shell(app: &mut LightcraftApp, host: &mut egui::Ui, blocked: bool) { let chrome_id = id.with("chrome"); let chrome = ctx.data(|d| d.get_temp::(chrome_id)).unwrap_or(DIALOG_CHROME_GUESS).max(DIALOG_CHROME_GUESS); let body_max = - if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome }.max(DIALOG_MIN_BODY); + if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome } + .max(DIALOG_MIN_BODY); // A press held from before this dialog was shown (on the dialog it replaced, or on the window under it) is not // this dialog's either: its release must not land on what this dialog put under the pointer. let shown_id = egui::Id::unique("lightcraft.dialog.shown-id"); @@ -668,7 +669,10 @@ fn shell(app: &mut LightcraftApp, host: &mut egui::Ui, blocked: bool) { ctx.data_mut(|d| d.insert_temp(grown_id, content_w)); ctx.request_repaint(); } - if !popup_was_open && settled && let Some(band) = title_bar { + if !popup_was_open + && settled + && let Some(band) = title_bar + { title_bar_handle(&ctx, band, window_rect); } // The startup dialog is recorded once it was presented, not when the logic tick picked it: a host that runs @@ -1439,12 +1443,7 @@ fn capture_time_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg } /// The body of the LabelNames dialog. -fn label_names_body( - app: &mut LightcraftApp, - ui: &mut egui::Ui, - t: &Tokens, - dlg: &mut Dialog, -) -> bool { +fn label_names_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) -> bool { let Dialog::LabelNames { names, save_as } = dlg else { return false; }; @@ -1459,28 +1458,16 @@ fn label_names_body( let mut choices = |ui: &mut egui::Ui| { for set in sets["sets"].as_array().into_iter().flatten() { let name = set["name"].as_str().unwrap_or_default(); - if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false) - .clicked() - { - candidate_names = set["names"] - .as_array() - .into_iter() - .flatten() - .map(|n| n.as_str().unwrap_or_default().to_string()) - .collect(); + if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false).clicked() { + candidate_names = set["names"].as_array().into_iter().flatten().map(|n| n.as_str().unwrap_or_default().to_string()).collect(); } } }; if craft::ui::runtime::measure::active(ui.ctx()) && !ui.is_sizing_pass() { // A context-side measuring run alone is not an egui sizing Ui. Use the // supported sizing-only presentation so no live SDK press can begin. - let mut sizing = ui.new_child( - egui::UiBuilder::new() - .max_rect(ui.available_rect_before_wrap()) - .layout(*ui.layout()) - .sizing_pass() - .invisible(), - ); + let mut sizing = + ui.new_child(egui::UiBuilder::new().max_rect(ui.available_rect_before_wrap()).layout(*ui.layout()).sizing_pass().invisible()); choices(&mut sizing); ui.advance_cursor_after_rect(sizing.min_rect()); } else { @@ -1492,29 +1479,19 @@ fn label_names_body( let colour = format!("{l:?}"); field(ui, &colour, |ui| { let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); - ui.painter() - .circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); - escaped |= label_name_field( - ui, - &format!("field:labelName-{}", colour.to_lowercase()), - &colour, - &mut candidate_names[i], - &colour, - ); + ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); + escaped |= label_name_field(ui, &format!("field:labelName-{}", colour.to_lowercase()), &colour, &mut candidate_names[i], &colour); }); } field(ui, "Save as set", |ui| { - escaped |= label_name_field( - ui, - "field:labelSetName", - "Save as set", - &mut candidate_save_as, - crate::i18n::tr("Optional name"), - ); + escaped |= label_name_field(ui, "field:labelSetName", "Save as set", &mut candidate_save_as, crate::i18n::tr("Optional name")); }); - ui.label(egui::RichText::new(crate::i18n::tr( - "Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.", - )).color(t.text_dim)); + ui.label( + egui::RichText::new(crate::i18n::tr( + "Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.", + )) + .color(t.text_dim), + ); if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { *names = candidate_names; *save_as = candidate_save_as; @@ -1522,19 +1499,10 @@ fn label_names_body( escaped } -fn label_name_field( - ui: &mut egui::Ui, - alias: &str, - label: &str, - value: &mut String, - hint: &str, -) -> bool { +fn label_name_field(ui: &mut egui::Ui, alias: &str, label: &str, value: &mut String, hint: &str) -> bool { use craft::ui::contract::{Bind, Props as _, Show as _}; use craft::ui::text::TextField; - let (rect, _) = ui.allocate_exact_size( - egui::vec2(ui.available_width().max(1.0), 24.0), - egui::Sense::hover(), - ); + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), 24.0), egui::Sense::hover()); let eligible = ui.is_enabled() && ui.is_visible() && ui.clip_rect().intersects(rect) @@ -1556,7 +1524,6 @@ fn label_name_field( eligible && shown.escaped } - /// The body of the MergeKeywords dialog. fn merge_keywords_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) { let Dialog::MergeKeywords { from, into } = dlg else { return }; @@ -1590,23 +1557,12 @@ fn merge_keywords_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, c } /// The body of the NewAlbum dialog. -fn new_album_body( - app: &mut LightcraftApp, - ui: &mut egui::Ui, - confirm: &mut bool, - dlg: &mut Dialog, -) { +fn new_album_body(app: &mut LightcraftApp, ui: &mut egui::Ui, confirm: &mut bool, dlg: &mut Dialog) { use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _}; // Respect an explicit native presentation scope without changing the // installed generic dialog's supported-SDK default. - let Dialog::NewAlbum { - name, - folder, - include_selected, - .. - } = dlg - else { + let Dialog::NewAlbum { name, folder, include_selected, .. } = dlg else { return; }; if new_album_name_field(ui, name) { @@ -1619,16 +1575,11 @@ fn new_album_body( .id_salt("albumIncludeSelected") .label(crate::i18n::tr("Include selected photos").to_owned()) .show(ui); - if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) - { + if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { *include_selected = candidate_include; } if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { - crate::widgets::register_response( - "check:albumIncludeSelected", - shown.response.rect, - &shown.response, - ); + crate::widgets::register_response("check:albumIncludeSelected", shown.response.rect, &shown.response); } } } @@ -1640,10 +1591,7 @@ fn new_album_name_field(ui: &mut egui::Ui, value: &mut String) -> bool { use craft::ui::runtime::focus::{self, FocusTarget}; use craft::ui::text::TextField; let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); - let (rect, _) = ui.allocate_exact_size( - egui::vec2(ui.available_width().max(1.0), 24.0), - egui::Sense::hover(), - ); + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), 24.0), egui::Sense::hover()); let shown = TextField::new(crate::i18n::tr("Name").to_owned(), Bind::bound(value)) .id_salt("field:albumName") .placeholder(crate::i18n::tr("Name").to_owned()) @@ -1668,7 +1616,6 @@ fn new_album_name_field(ui: &mut egui::Ui, value: &mut String) -> bool { real && ui.is_enabled() && shown.submitted } - /// The body of the PasteSettings dialog. fn paste_settings_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { let Dialog::PasteSettings { groups } = dlg else { return }; @@ -1702,7 +1649,15 @@ fn contact_sheet_body(app: &mut LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dial craft::ui::contract::Entry::new("a4".to_owned(), "A4".to_owned()), craft::ui::contract::Entry::new("letter".to_owned(), crate::i18n::tr("Letter").to_owned()), ]; - if let Some(paper) = crate::widgets::select(ui, "combo:contactSheetPaper", crate::i18n::tr("Paper"), options.paper.clone(), &entries, Some(options.paper.clone()), None) { + if let Some(paper) = crate::widgets::select( + ui, + "combo:contactSheetPaper", + crate::i18n::tr("Paper"), + options.paper.clone(), + &entries, + Some(options.paper.clone()), + None, + ) { options.paper = paper; } }); @@ -1990,7 +1945,10 @@ pub(crate) fn show_root(app: &mut LightcraftApp, root: &mut egui::Ui, blocked: b AboutLink::new(crate::i18n::tr("Source code on GitHub"), crate::links::GITHUB), AboutLink::new(crate::i18n::tr("ArtCraft — more creative apps"), crate::links::WEBSITE), ]) - .built_with(crate::i18n::tr_format!("MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", crate::theme::font_credits(app.chinese_font.is_some()))); + .built_with(crate::i18n::tr_format!( + "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", + crate::theme::font_credits(app.chinese_font.is_some()) + )); let dialog = AboutDialog::new(&info, credits::framework_credits()); let ctx = root.ctx().clone(); let (out, record) = craft::ui::runtime::inspect::record(root, egui::Id::unique("about-app-contract"), |ui| { @@ -2001,7 +1959,9 @@ pub(crate) fn show_root(app: &mut LightcraftApp, root: &mut egui::Ui, blocked: b crate::widgets::register_response("dialog:window", out.response.rect, &out.response); let ok = [crate::i18n::tr("OK"), crate::i18n::tr("Close")]; if let Some(element) = record.iter().flat_map(|record| record.elements.iter()).find(|element| { - element.component == "Button" && element.part.is_none() && element.facts.as_ref().and_then(|facts| facts.name.as_deref()).is_some_and(|name| ok.contains(&name)) + element.component == "Button" + && element.part.is_none() + && element.facts.as_ref().and_then(|facts| facts.name.as_deref()).is_some_and(|name| ok.contains(&name)) }) && let Some(response) = root.ctx().read_response(element.id) { crate::widgets::register_response("button:dialogOk", element.rect, &response); @@ -2031,7 +1991,9 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m Dialog::SmartRules { .. } => smart_rules_body(app, ui, t, close, dlg), Dialog::NewSmartAlbum { .. } => new_smart_album_body(app, ui, t, confirm, dlg), Dialog::CaptureTime { .. } => capture_time_body(app, ui, t, dlg), - Dialog::LabelNames { .. } => { *close |= label_names_body(app, ui, t, dlg); }, + Dialog::LabelNames { .. } => { + *close |= label_names_body(app, ui, t, dlg); + } Dialog::Rename { .. } => rename_body(app, ui, t, dlg), Dialog::RenamePerson { .. } => rename_person_body(app, ui, t, confirm, dlg), Dialog::RenameKeyword { .. } => rename_keyword_body(app, ui, t, confirm, dlg), @@ -2115,9 +2077,9 @@ mod new_album_port_tests; #[path = "dialogs/new_album_sdk_route_tests.rs"] mod new_album_sdk_route_tests; -#[cfg(test)] -#[path = "dialogs/label_names_flow_tests.rs"] -mod label_names_port_tests; #[cfg(test)] #[path = "dialogs/keyword_tag_options_flow_tests.rs"] mod keyword_tag_options_flow_tests; +#[cfg(test)] +#[path = "dialogs/label_names_flow_tests.rs"] +mod label_names_port_tests; diff --git a/crates/ui-egui/src/dialogs/cull.rs b/crates/ui-egui/src/dialogs/cull.rs index dd5b912594..73ca229505 100644 --- a/crates/ui-egui/src/dialogs/cull.rs +++ b/crates/ui-egui/src/dialogs/cull.rs @@ -32,11 +32,8 @@ fn number(ui: &mut egui::Ui, id: &str, label: &str, value: &mut f32, similarity: // editor remains immediately after the track for existing typed-entry clients. let width = ui.spacing().slider_width; let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 24.0), egui::Sense::hover()); - let slider = Slider::new(Bind::bound(&mut current), drag) - .id_salt((id, "track")) - .label(crate::i18n::tr(label).to_owned()) - .step(step) - .show_at(ui, rect); + let slider = + Slider::new(Bind::bound(&mut current), drag).id_salt((id, "track")).label(crate::i18n::tr(label).to_owned()).step(step).show_at(ui, rect); register(ui, &format!("slider:{id}"), &slider.response); let mut exact = Some(current); let (rect, _) = ui.allocate_exact_size(egui::vec2(68.0, 24.0), egui::Sense::hover()); diff --git a/crates/ui-egui/src/dialogs/cull_wave110_tests.rs b/crates/ui-egui/src/dialogs/cull_wave110_tests.rs index 1ed075d245..edefe5d6bc 100644 --- a/crates/ui-egui/src/dialogs/cull_wave110_tests.rs +++ b/crates/ui-egui/src/dialogs/cull_wave110_tests.rs @@ -94,7 +94,11 @@ fn production_cull_body_mounts_sdk_controls_without_clamping_typed_values() { let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("wave110-cull-probe"), |ui| { crate::dialogs::cull_body(&mut app, ui, &t, &mut dialog); }); - roles = record.iter().flat_map(|record| record.elements.iter()).filter_map(|element| element.facts.as_ref().map(|facts| facts.role.clone())).collect(); + roles = record + .iter() + .flat_map(|record| record.elements.iter()) + .filter_map(|element| element.facts.as_ref().map(|facts| facts.role.clone())) + .collect(); }); }); frame_out.textures_delta.clear(); diff --git a/crates/ui-egui/src/dialogs/export/core.rs b/crates/ui-egui/src/dialogs/export/core.rs index 19177084fb..7f15265c5a 100644 --- a/crates/ui-egui/src/dialogs/export/core.rs +++ b/crates/ui-egui/src/dialogs/export/core.rs @@ -50,7 +50,10 @@ pub(super) fn choices(ui: &mut egui let measure = |ui: &mut egui::Ui, width: f32| { let mut measuring = *value; let child = ui.new_child( - egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))).sizing_pass().invisible(), + egui::UiBuilder::new() + .max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))) + .sizing_pass() + .invisible(), ); RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut measuring)).id_salt(id).measure_in(&child, Proposal::Ideal, body) }; diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 8c7847f7d0..dca39ddd5a 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -174,7 +174,8 @@ fn preset_entries(app: &LightcraftApp, ui: &egui::Ui) -> std::sync::Arc(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) { + if let Some((_, _, entries)) = ui.data(|data| data.get_temp::(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) + { return entries; } let mut entries = vec![Entry::new(String::new(), crate::i18n::tr("None").to_owned())]; @@ -252,7 +253,10 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) // so resizing the dialog resizes the grid let below = ui.ctx().data(|m| m.get_temp::(egui::Id::unique(CONTENT_BOTTOM))); // the room left in the dialog's body below this point ([`note_body_room`]), else what the ui has - let room = ui.ctx().data(|m| m.get_temp::<(f32, f32)>(egui::Id::unique((BODY_ROOM, controls::measuring(ui))))).map(|(top, room)| top + room - ui.cursor().top()); + let room = ui + .ctx() + .data(|m| m.get_temp::<(f32, f32)>(egui::Id::unique((BODY_ROOM, controls::measuring(ui))))) + .map(|(top, room)| top + room - ui.cursor().top()); // (the room alone: a measuring run's ui may offer less height than the real run's, and the grid must be as tall // in both, or the body measures shorter than it lays out and its last rows can't be scrolled to) // (less one row gap: the body's content counts the gap after its last row, and a body a gap too tall scrolls) @@ -504,7 +508,15 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) field(ui, "Preset", |ui| { // "" is no preset; a preset that has gone shows as None until another is chosen let entries = preset_entries(app, ui); - if let Some(pid) = crate::widgets::select(ui, "combo:importPreset", crate::i18n::tr("Preset"), d.preset.clone(), entries.as_slice(), Some(crate::i18n::tr("None").to_owned()), None) { + if let Some(pid) = crate::widgets::select( + ui, + "combo:importPreset", + crate::i18n::tr("Preset"), + d.preset.clone(), + entries.as_slice(), + Some(crate::i18n::tr("None").to_owned()), + None, + ) { d.preset = pid; } }); diff --git a/crates/ui-egui/src/dialogs/import/tags.rs b/crates/ui-egui/src/dialogs/import/tags.rs index 8ffae14933..21c649c0c6 100644 --- a/crates/ui-egui/src/dialogs/import/tags.rs +++ b/crates/ui-egui/src/dialogs/import/tags.rs @@ -69,7 +69,8 @@ pub(crate) fn template_field(ui: &mut egui::Ui, name: &str, label: &str, value: use craft::ui::contract::{Bind, Props as _, Show as _}; use craft::ui::text::TextField; let live = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); - let pending = if live { ui.ctx().data_mut(|d| d.remove_temp::(edit_id.with("lc-pending-tag"))).filter(|tag| !tag.is_empty()) } else { None }; + let pending = + if live { ui.ctx().data_mut(|d| d.remove_temp::(edit_id.with("lc-pending-tag"))).filter(|tag| !tag.is_empty()) } else { None }; let width = width.min(ui.available_width()).max(1.0); let (rect, _) = ui.allocate_exact_size(egui::vec2(width, ui.spacing().interact_size.y.max(24.0)), egui::Sense::hover()); let mut field = TextField::new(label.to_owned(), Bind::bound(value)).id(edit_id).placeholder(hint.to_owned()).limit(None); diff --git a/crates/ui-egui/src/dialogs/keymap.rs b/crates/ui-egui/src/dialogs/keymap.rs index 9da1f4f7a5..fca2ae2b02 100644 --- a/crates/ui-egui/src/dialogs/keymap.rs +++ b/crates/ui-egui/src/dialogs/keymap.rs @@ -71,10 +71,8 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } }); }); - let shown = Checkbox::new(Bind::bound(&mut show_all)) - .id_salt(SHOW_ALL) - .label(crate::i18n::tr("Show commands without a shortcut").to_owned()) - .show(ui); + let shown = + Checkbox::new(Bind::bound(&mut show_all)).id_salt(SHOW_ALL).label(crate::i18n::tr("Show commands without a shortcut").to_owned()).show(ui); register(ui, "check:shortcuts.showAll", &shown.response); if !measuring(ui) { ui.data_mut(|d| { @@ -142,11 +140,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: }; ui.label(name).on_hover_text(hover); let recording = app.recording_shortcut.as_deref() == Some(b.id); - let text = if recording { - crate::i18n::tr("Press keys…").to_owned() - } else { - sc.map_or_else(|| "—".to_owned(), |sc| menu_text(sc, mac)) - }; + let text = if recording { crate::i18n::tr("Press keys…").to_owned() } else { sc.map_or_else(|| "—".to_owned(), |sc| menu_text(sc, mac)) }; // The SDK's stand-alone chord recorder is crate-private. A normal SDK Button // routes Tab, activation and Escape as intents instead of leaving raw chords // for capture(). Keep this one focus owner native until the recorder is public. @@ -154,15 +148,14 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: register(ui, format!("button:shortcut-{}", b.id), &response); if !measuring(ui) && response.clicked() { app.recording_shortcut = if recording { None } else { Some(b.id.to_string()) }; - if !recording { response.request_focus(); } + if !recording { + response.request_focus(); + } } ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; - let shown = Button::new(crate::i18n::tr("Remove shortcut").to_owned()) - .painted("×") - .id_salt(("shortcutClear", b.id)) - .enabled(sc.is_some()) - .show(ui); + let shown = + Button::new(crate::i18n::tr("Remove shortcut").to_owned()).painted("×").id_salt(("shortcutClear", b.id)).enabled(sc.is_some()).show(ui); let clicked = !measuring(ui) && shown.clicked(); let response = shown.response.on_hover_text(crate::i18n::tr("Remove shortcut")); register(ui, format!("button:shortcutClear-{}", b.id), &response); diff --git a/crates/ui-egui/src/dialogs/keymap_external155_tests.rs b/crates/ui-egui/src/dialogs/keymap_external155_tests.rs index 2ec8756f74..d7e9b4f4f3 100644 --- a/crates/ui-egui/src/dialogs/keymap_external155_tests.rs +++ b/crates/ui-egui/src/dialogs/keymap_external155_tests.rs @@ -113,13 +113,7 @@ fn keymap_external155_measuring_does_not_take_capture_or_register_controls() { app.install_framework(&ctx); app.recording_shortcut = Some("view.survey".into()); let raw = egui::RawInput { - events: vec![egui::Event::Key { - key: egui::Key::F9, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }], + events: vec![egui::Event::Key { key: egui::Key::F9, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() }; let mut output = ctx.run_ui(raw, |ui| { diff --git a/crates/ui-egui/src/dialogs/label_names_flow_tests.rs b/crates/ui-egui/src/dialogs/label_names_flow_tests.rs index 2385d76cbf..007ee2a0d8 100644 --- a/crates/ui-egui/src/dialogs/label_names_flow_tests.rs +++ b/crates/ui-egui/src/dialogs/label_names_flow_tests.rs @@ -543,54 +543,28 @@ fn label_names_actual_parent_publishes_six_enabled_sdk_text_field_owners() { for _ in 0..8 { f.safe(); f.tick += 1; - let raw = HeadlessView::raw_input( - egui::vec2(1400.0, 1000.0), - 1.0, - f64::from(f.tick) / 60.0, - vec![], - ); + let raw = HeadlessView::raw_input(egui::vec2(1400.0, 1000.0), 1.0, f64::from(f.tick) / 60.0, vec![]); let app = &mut f.app; let ctx = f.ctx.clone(); let _drain = Drain(ctx.run_ui(raw, |root| { crate::widgets::take_registries(&ctx); - let (_, recorded) = craft::ui::runtime::inspect::record( - root, - egui::Id::unique("label-names-sdk-route"), - |_| crate::dialogs::show(app, &ctx, false), - ); - elements = recorded - .map(|recording| recording.elements.clone()) - .unwrap_or_default(); + let (_, recorded) = + craft::ui::runtime::inspect::record(root, egui::Id::unique("label-names-sdk-route"), |_| crate::dialogs::show(app, &ctx, false)); + elements = recorded.map(|recording| recording.elements.clone()).unwrap_or_default(); })); crate::widgets::take_registries(&ctx); assert_eq!(document(&f.app), f.baseline); assert_eq!(f.draft(), initial_draft); f.safe(); } - let inputs = elements - .iter() - .filter(|element| element.part.is_none() && element.component.starts_with("TextField")) - .collect::>(); - assert_eq!( - inputs.len(), - 6, - "six actual SDK text input owners; records={elements:#?}" - ); + let inputs = elements.iter().filter(|element| element.part.is_none() && element.component.starts_with("TextField")).collect::>(); + assert_eq!(inputs.len(), 6, "six actual SDK text input owners; records={elements:#?}"); for name in ["Red", "Yellow", "Green", "Blue", "Purple", "Save as set"] { let owners = inputs .iter() - .filter(|element| { - element - .facts - .as_ref() - .is_some_and(|facts| facts.name.as_deref() == Some(name) && !facts.disabled) - }) + .filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref() == Some(name) && !facts.disabled)) .collect::>(); - assert_eq!( - owners.len(), - 1, - "one actual enabled SDK owner for {name}; records={elements:#?}" - ); + assert_eq!(owners.len(), 1, "one actual enabled SDK owner for {name}; records={elements:#?}"); } } @@ -617,11 +591,7 @@ fn label_names_reverse_tab_all_twelve_owners_preserves_draft_and_escapes() { assert!(f.focused(order[0])); for target in order.iter().rev() { f.key_mod(Key::Tab, Modifiers::SHIFT); - assert!( - f.focused(target), - "reverse Tab requires {target}; trace={:#?}", - f.trace - ); + assert!(f.focused(target), "reverse Tab requires {target}; trace={:#?}", f.trace); assert_eq!(f.draft(), draft); } f.key(Key::Escape); diff --git a/crates/ui-egui/src/dialogs/merge.rs b/crates/ui-egui/src/dialogs/merge.rs index ceb4d4c516..edd63a858d 100644 --- a/crates/ui-egui/src/dialogs/merge.rs +++ b/crates/ui-egui/src/dialogs/merge.rs @@ -500,7 +500,6 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog) }); } - /// Both layout systems can measure speculatively. Never publish automation hits or draft edits then. fn measuring(ui: &egui::Ui) -> bool { ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) @@ -530,17 +529,21 @@ fn choices(ui: &mut egui::Ui, id: &str, label: &str, options: &[(&str, &str)], v register(ui, format!("button:{id}-{index}"), &response); } }; - if horizontal { ui.horizontal_wrapped(members); } else { ui.vertical(members); } + if horizontal { + ui.horizontal_wrapped(members); + } else { + ui.vertical(members); + } }; // Native columns and SDK containers do not share a flow cursor. Measure in the actual column, // then mount once there, rather than filling the enclosing dialog a second time. let width = ui.available_width().max(1.0); let mut probe = value.clone(); - let child = ui.new_child(egui::UiBuilder::new() - .max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))) - .sizing_pass().invisible()); - let size = RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut probe)) - .id_salt(id).measure_in(&child, Proposal::Width(width), body); + let child = ui.new_child( + egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))).sizing_pass().invisible(), + ); + let size = + RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut probe)).id_salt(id).measure_in(&child, Proposal::Width(width), body); let (rect, _) = ui.allocate_exact_size(egui::vec2(width, size.y.max(24.0)), egui::Sense::hover()); RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(value)).id_salt(id).show_at(ui, rect, body); } @@ -549,26 +552,42 @@ fn choices(ui: &mut egui::Ui, id: &str, label: &str, options: &[(&str, &str)], v fn options(ui: &mut egui::Ui, opts: &mut MergeDialog, photo_count: usize) { let mut draft = opts.clone(); if draft.is_pano() { - choices(ui, "mergeProjection", "Projection", &[("auto", "Auto Select"), ("spherical", "Spherical"), - ("cylindrical", "Cylindrical"), ("perspective", "Perspective")], &mut draft.projection, false); + choices( + ui, + "mergeProjection", + "Projection", + &[("auto", "Auto Select"), ("spherical", "Spherical"), ("cylindrical", "Cylindrical"), ("perspective", "Perspective")], + &mut draft.projection, + false, + ); ui.add_space(4.0); let mut warp = draft.boundary_warp; - if num(ui, &BOUNDARY_WARP, &mut warp) { draft.boundary_warp = warp.round(); } + if num(ui, &BOUNDARY_WARP, &mut warp) { + draft.boundary_warp = warp.round(); + } check(ui, "check:merge.fillEdges", "Fill Edges", &mut draft.fill_edges, true); check(ui, "check:merge.autoCrop", "Auto Crop", &mut draft.auto_crop, true); ui.add_space(4.0); } if draft.is_hdr() { check(ui, "check:merge.align", "Auto Align", &mut draft.align, true); - choices(ui, "mergeDeghost", "Deghost Amount", &[("none", "None"), ("low", "Low"), ("medium", "Med"), ("high", "High")], - &mut draft.deghost, true); + choices( + ui, + "mergeDeghost", + "Deghost Amount", + &[("none", "None"), ("low", "Low"), ("medium", "Med"), ("high", "High")], + &mut draft.deghost, + true, + ); if draft.command == "merge.hdr" { let enabled = draft.deghost != "none"; check(ui, "check:merge.showOverlay", "Show Deghost Overlay", &mut draft.show_overlay, enabled); } if draft.command == "merge.hdrPanorama" { let mut bracket = f64::from(draft.bracket); - if num(ui, &BRACKET, &mut bracket) { draft.bracket = bracket.round() as u32; } + if num(ui, &BRACKET, &mut bracket) { + draft.bracket = bracket.round() as u32; + } } ui.add_space(4.0); } @@ -576,7 +595,9 @@ fn options(ui: &mut egui::Ui, opts: &mut MergeDialog, photo_count: usize) { check(ui, "check:merge.stack", "Create Stack", &mut draft.stack, true); ui.add_space(8.0); Text::new(crate::i18n::tr_format!("{} photos", photo_count)).shade(Shade::Muted).show(ui); - if !measuring(ui) { *opts = draft; } + if !measuring(ui) { + *opts = draft; + } } const BOUNDARY_WARP: lightcraft_develop::ControlSpec = lightcraft_develop::ControlSpec { @@ -605,8 +626,11 @@ const BRACKET: lightcraft_develop::ControlSpec = lightcraft_develop::ControlSpec /// Keep the product's hover Up/Down shortcut (Shift = five steps) beside the SDK's /// focused slider navigation. Text editing always owns its own arrow keys. fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: egui::Rect, track_key: egui::Id, value: &mut f64) { - if measuring(ui) || !ui.is_enabled() || !ui.rect_contains_pointer(row) - || craft::ui::runtime::focus::focused_rec(ui.ctx()).is_some_and(|focus| focus.stop.text) { + if measuring(ui) + || !ui.is_enabled() + || !ui.rect_contains_pointer(row) + || craft::ui::runtime::focus::focused_rec(ui.ctx()).is_some_and(|focus| focus.stop.text) + { return; } let (up, down, shift) = ui.input_mut(|input| { @@ -619,11 +643,16 @@ fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: eg // Settle only the matching move for this track: the app owns hovered Up/Down // (Shift = 5), while the SDK still owns other axes, editing and accessibility. use craft::ui::runtime::{focus, keys}; - if let Some(track) = ui.data(|d| d.get_temp::(track_key)).filter(|id| focus::focused_rec(ui.ctx()).is_some_and(|f| f.stop.id == *id)) { + if let Some(track) = + ui.data(|d| d.get_temp::(track_key)).filter(|id| focus::focused_rec(ui.ctx()).is_some_and(|f| f.stop.id == *id)) + { let mut intents = keys::intents_of(ui.ctx(), Some(track), false); - let took = intents.take_move_where(|mv, mods| mods.extend == shift && !mods.fine && !mods.lead - && ((up && mv == keys::NavMove::Up) || (down && mv == keys::NavMove::Down))); - if took.is_some() { keys::settle(ui.ctx(), Some(track), &intents); } + let took = intents.take_move_where(|mv, mods| { + mods.extend == shift && !mods.fine && !mods.lead && ((up && mv == keys::NavMove::Up) || (down && mv == keys::NavMove::Down)) + }); + if took.is_some() { + keys::settle(ui.ctx(), Some(track), &intents); + } } *value = crate::widgets::nudged(spec, *value, if up { 1.0 } else { -1.0 } * if shift { 5.0 } else { 1.0 }); } @@ -639,7 +668,9 @@ fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: eg let total = (remainder + dx).clamp(-10.0 * unit, 10.0 * unit); let steps = (total / unit).trunc(); ui.data_mut(|data| data.insert_temp(key, total - steps * unit)); - if steps != 0.0 { *value = crate::widgets::nudged(spec, *value, f64::from(steps)); } + if steps != 0.0 { + *value = crate::widgets::nudged(spec, *value, f64::from(steps)); + } } fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f64) -> bool { @@ -655,7 +686,9 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6 crate::panels::detail::host::Target::new(crate::i18n::tr(spec.label)).pointer_only(), ); crate::widgets::register_response(format!("sliderLabel:{}", spec.id), label.rect, &caption.response); - if caption.double_clicked() { current = spec.default; } + if caption.double_clicked() { + current = spec.default; + } } let row = egui::Rect::from_min_max(label.rect.min, egui::pos2(ui.max_rect().right(), ui.cursor().min.y + 24.0)); let track_key = ui.scope_id().with(("merge-focused-track", spec.id)); @@ -666,15 +699,20 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6 let record_id = ui.scope_id().with(("merge-track", spec.id)); let (shown, record) = craft::ui::runtime::inspect::record(ui, record_id, |ui| { Slider::new(Bind::bound(&mut current).reset(spec.default), spec.min..=spec.max) - .id_salt(("merge-slider", spec.id)).label(crate::i18n::tr(spec.label)).step(spec.step) + .id_salt(("merge-slider", spec.id)) + .label(crate::i18n::tr(spec.label)) + .step(spec.step) // LightCraft's slider keys: Shift steps five times, as the develop sliders do (`widgets::slider`). .key_policy(craft::ui::runtime::keys::ScalarKeyPolicy::new(spec.step).model_step(spec.step).shift_factor(5.0)) .show_at(ui, rect) }); // Automation fractions describe the value span, which runs between the endpoint thumb centres. - let half_thumb = record.as_ref().and_then(|record| record.hits.iter().find(|hit| { - hit.owner == shown.response.id && hit.part.is_some_and(|part| part.key == Slider::THUMB) - })).map_or(0.0, |hit| hit.bounds.width() * 0.5); + let half_thumb = record + .as_ref() + .and_then(|record| { + record.hits.iter().find(|hit| hit.owner == shown.response.id && hit.part.is_some_and(|part| part.key == Slider::THUMB)) + }) + .map_or(0.0, |hit| hit.bounds.width() * 0.5); let span = shown.response.rect.shrink2(egui::vec2(half_thumb, 0.0)); if !measuring(ui) { ui.data_mut(|d| d.insert_temp(track_key, shown.response.id)); @@ -683,8 +721,12 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6 let mut exact = Some(current); let (rect, _) = ui.allocate_exact_size(egui::vec2(64.0, 24.0), egui::Sense::hover()); let shown = NumberField::new(crate::i18n::tr(spec.label), Bind::bound(&mut exact).reset(Some(spec.default))) - .id_salt(("merge-number", spec.id)).range(spec.min..=spec.max).step(spec.step) - .snap_typed(true).commit_decimals(spec.decimals as usize).fixed_decimals(spec.decimals as usize) + .id_salt(("merge-number", spec.id)) + .range(spec.min..=spec.max) + .step(spec.step) + .snap_typed(true) + .commit_decimals(spec.decimals as usize) + .fixed_decimals(spec.decimals as usize) .show_at(ui, rect); register(ui, format!("sliderValue:{}", spec.id), &shown.response); register(ui, format!("sliderField:{}", spec.id), &shown.response); @@ -692,9 +734,13 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6 if !measuring(ui) && shown.events.iter().any(|event| matches!(event, craft::behavior::EditEvent::Cancel { .. })) { crate::widgets::take_escape(ui.ctx()); } - if let Some(exact) = exact.filter(|v| v.is_finite()) { current = exact; } + if let Some(exact) = exact.filter(|v| v.is_finite()) { + current = exact; + } }); - if !measuring(ui) { *value = current; } + if !measuring(ui) { + *value = current; + } *value != before } diff --git a/crates/ui-egui/src/dialogs/merge_sdk155_tests.rs b/crates/ui-egui/src/dialogs/merge_sdk155_tests.rs index 1fc364dfef..573d75e199 100644 --- a/crates/ui-egui/src/dialogs/merge_sdk155_tests.rs +++ b/crates/ui-egui/src/dialogs/merge_sdk155_tests.rs @@ -57,7 +57,9 @@ impl Controls { } fn settle(&mut self) { - for _ in 0..3 { self.frame(vec![]); } + for _ in 0..3 { + self.frame(vec![]); + } } fn click(&mut self, id: &str) { @@ -87,7 +89,9 @@ impl Controls { self.key(Key::Enter, Modifiers::NONE); } - fn has(&self, id: &str) -> bool { self.frames.rects.iter().any(|(name, _)| name == id) } + fn has(&self, id: &str) -> bool { + self.frames.rects.iter().any(|(name, _)| name == id) + } /// The framework convention: a pointer press activates a control without taking the keyboard, so a keyboard step /// starts from a control given the focus. @@ -219,12 +223,15 @@ fn sdk155_merge_cancel_discards_draft_and_invalid_confirm_cannot_start_or_save() app.install_framework(&frames.ctx); let opts = MergeDialog { stack: true, deghost: "high".into(), ..Default::default() }; app.ui.dialog = Some(crate::state::Dialog::Merge { opts: opts.clone() }); - for _ in 0..3 { frames.frame(vec![], |ui| crate::dialogs::show(&mut app, ui.ctx(), false)); } + for _ in 0..3 { + frames.frame(vec![], |ui| crate::dialogs::show(&mut app, ui.ctx(), false)); + } let pos = frames.rect("button:dialogCancel").center(); frames.frame(vec![Event::PointerMoved(pos)], |ui| crate::dialogs::show(&mut app, ui.ctx(), false)); for pressed in [true, false] { - frames.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], - |ui| crate::dialogs::show(&mut app, ui.ctx(), false)); + frames.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], |ui| { + crate::dialogs::show(&mut app, ui.ctx(), false) + }); } assert!(app.ui.dialog.is_none()); assert!(app.merge.final_task.is_none() && app.merge.preview_task.is_none()); diff --git a/crates/ui-egui/src/dialogs/print_template_flow_tests.rs b/crates/ui-egui/src/dialogs/print_template_flow_tests.rs index 2b399fe3a9..3c205b24ae 100644 --- a/crates/ui-egui/src/dialogs/print_template_flow_tests.rs +++ b/crates/ui-egui/src/dialogs/print_template_flow_tests.rs @@ -48,7 +48,8 @@ impl Review { crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx); app.install_framework(&ctx); - let mut this = Self { app, ctx, tick: 0, rects: vec![], hits: vec![], old_language: crate::i18n::language(), sdk_name_owner: false, covered: false }; + let mut this = + Self { app, ctx, tick: 0, rects: vec![], hits: vec![], old_language: crate::i18n::language(), sdk_name_owner: false, covered: false }; // Production command opening, not menu-enabled/selected-photo acceptance. this.app.run("dialog.print", json!({})).unwrap(); this.idle(); diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index 4aec009c42..c94347ed2d 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -270,7 +270,7 @@ fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut // `escaped` also includes Escape-reason Revert; no such programmatic path is // installed here, and this is not a general physical-key discriminator. close |= eligible && shown.escaped; - + if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() { run(app, &ctx, "print.template.save", json!({"name": pu.template_name})); } @@ -599,7 +599,15 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pri let _ = crate::widgets::menu_row(ui, ("printProfile", "icc"), None, &shown, None, true, true); } if app.services.pick_display_profile.is_some() { - pick |= crate::widgets::menu_row(ui, ("printProfile", "other"), Some("item:printProfile-other"), crate::i18n::tr("Other…"), None, false, true); + pick |= crate::widgets::menu_row( + ui, + ("printProfile", "other"), + Some("item:printProfile-other"), + crate::i18n::tr("Other…"), + None, + false, + true, + ); } }); }); diff --git a/crates/ui-egui/src/dialogs/rules_editor/controls.rs b/crates/ui-egui/src/dialogs/rules_editor/controls.rs index 4449c68aa2..8208160781 100644 --- a/crates/ui-egui/src/dialogs/rules_editor/controls.rs +++ b/crates/ui-egui/src/dialogs/rules_editor/controls.rs @@ -33,7 +33,8 @@ pub(super) fn button(ui: &mut egui::Ui, id: &str, glyph: &str, label: &str, widt /// The width [`button`] takes: at least `width`, else what its painted text needs. pub(super) fn button_width(ui: &egui::Ui, glyph: &str, label: &str, width: f32) -> f32 { - let ideal = Button::new(crate::i18n::tr(label).to_owned()).painted(crate::i18n::tr(glyph).to_owned()).measure_in(ui, craft::behavior::Proposal::Ideal).x; + let ideal = + Button::new(crate::i18n::tr(label).to_owned()).painted(crate::i18n::tr(glyph).to_owned()).measure_in(ui, craft::behavior::Proposal::Ideal).x; width.max(ideal.ceil()) } diff --git a/crates/ui-egui/src/dialogs/settings/controls.rs b/crates/ui-egui/src/dialogs/settings/controls.rs index 5421036146..533a80aa76 100644 --- a/crates/ui-egui/src/dialogs/settings/controls.rs +++ b/crates/ui-egui/src/dialogs/settings/controls.rs @@ -193,31 +193,32 @@ pub(crate) fn colour(ui: &mut egui::Ui, owner: egui::Id, name: &str, label: &str } let mut saved = false; - let _editor = Popover::new(words, Bind::bound(&mut open)).id_salt(("settings-colour-editor", name)).opened_by(&chip.response).show(ui, |ui, _| { - ui.set_min_width(240.0); - for (i, channel) in ["Red", "Green", "Blue"].into_iter().enumerate() { - let shape = Shape { label: channel, lo: 0.0, hi: 255.0, unit: "", step: 1.0, log: false }; - let steps = ui - .horizontal(|ui| { - ui.add_sized(vec2(48.0, 24.0), egui::Label::new(crate::i18n::tr(channel))); - slider(ui, owner, &format!("{name}{channel}"), &shape, f64::from(rgb[i])) - }) - .inner; - for step in steps { - match step { - Step::Begin(_) | Step::End => {} - Step::Preview(v) | Step::Save(v) => { - rgb[i] = v.round().clamp(0.0, 255.0) as u8; - saved |= matches!(step, Step::Save(_)); + let _editor = + Popover::new(words, Bind::bound(&mut open)).id_salt(("settings-colour-editor", name)).opened_by(&chip.response).show(ui, |ui, _| { + ui.set_min_width(240.0); + for (i, channel) in ["Red", "Green", "Blue"].into_iter().enumerate() { + let shape = Shape { label: channel, lo: 0.0, hi: 255.0, unit: "", step: 1.0, log: false }; + let steps = ui + .horizontal(|ui| { + ui.add_sized(vec2(48.0, 24.0), egui::Label::new(crate::i18n::tr(channel))); + slider(ui, owner, &format!("{name}{channel}"), &shape, f64::from(rgb[i])) + }) + .inner; + for step in steps { + match step { + Step::Begin(_) | Step::End => {} + Step::Preview(v) | Step::Save(v) => { + rgb[i] = v.round().clamp(0.0, 255.0) as u8; + saved |= matches!(step, Step::Save(_)); + } } } } - } - if let Some(typed) = hex_field(ui, owner, name, rgb) { - rgb = typed; - saved = true; - } - }); + if let Some(typed) = hex_field(ui, owner, name, rgb) { + rgb = typed; + saved = true; + } + }); let editing = open; ui.data_mut(|d| { d.insert_temp(open_key, open); diff --git a/crates/ui-egui/src/dialogs/settings/display.rs b/crates/ui-egui/src/dialogs/settings/display.rs index efccc70488..89f34e04a7 100644 --- a/crates/ui-egui/src/dialogs/settings/display.rs +++ b/crates/ui-egui/src/dialogs/settings/display.rs @@ -172,12 +172,9 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, if ui.is_enabled() && craft::ui::contract::clicked(&face) { open = !open; } - Menu::new(name) - .id_salt(("view-options-menu", &id)) - .values() - .opened_by(&face, Trigger::Manual) - .open(Bind::bound(&mut open)) - .show(ui, |ui, _| { + Menu::new(name).id_salt(("view-options-menu", &id)).values().opened_by(&face, Trigger::Manual).open(Bind::bound(&mut open)).show( + ui, + |ui, _| { for f in F::ALL { let key = serde_json::to_value(f).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()); @@ -193,26 +190,25 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, } } } - }); + }, + ); ui.data_mut(|data| data.insert_temp(slot, (pass, open))); if ui.is_enabled() && let Some(field) = picked { *line = field; } - } use craft::ui::buttons::Button; use craft::ui::contract::{Props as _, Show as _}; - let r = - Button::new(crate::i18n::tr("Use Defaults").to_owned()).id_salt(("view-options-defaults", n)).enabled(*lines != defaults).show(ui); + let r = Button::new(crate::i18n::tr("Use Defaults").to_owned()).id_salt(("view-options-defaults", n)).enabled(*lines != defaults).show(ui); if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { crate::widgets::register_response(format!("button:viewOptionsDefaults{n}"), r.response.rect, &r.response); if ui.is_enabled() && *lines != defaults && r.clicked() { *lines = defaults; } } - + // one Info at most shows briefly: ticking one unticks the other let info = if n == 1 { I::Basic } else { I::Exposure }; let mut briefly = app.ui.settings.loupe_info.briefly == info; diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index 94c5f05437..7cc6d3f207 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -105,12 +105,8 @@ fn library_launch_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens row(ui, t, crate::i18n::tr("At launch"), |ui| { let mut at_launch = app.ui.settings.at_launch; // Measurement/sizing may consume a native button result, but cannot change host UI state. - if choices( - ui, - "settingsAtLaunch", - &[(LaunchLibrary::Last, "Open the last library"), (LaunchLibrary::Ask, "Ask me")], - &mut at_launch, - ) && library_launch_input(ui) + if choices(ui, "settingsAtLaunch", &[(LaunchLibrary::Last, "Open the last library"), (LaunchLibrary::Ask, "Ask me")], &mut at_launch) + && library_launch_input(ui) { app.ui.settings.at_launch = at_launch; } @@ -128,10 +124,7 @@ fn library_launch_button(ui: &mut egui::Ui, alias: &str, label: &str, can: bool) use craft::ui::contract::{Props as _, Show as _}; let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); let (response, clicked) = { - let shown = craft::ui::buttons::Button::new(crate::i18n::tr(label).to_owned()) - .id_salt(alias) - .enabled(can && real) - .show(ui); + let shown = craft::ui::buttons::Button::new(crate::i18n::tr(label).to_owned()).id_salt(alias).enabled(can && real).show(ui); let clicked = shown.clicked(); (shown.response, clicked) }; diff --git a/crates/ui-egui/src/dialogs/settings/import.rs b/crates/ui-egui/src/dialogs/settings/import.rs index cddefdce5f..e4756ad08c 100644 --- a/crates/ui-egui/src/dialogs/settings/import.rs +++ b/crates/ui-egui/src/dialogs/settings/import.rs @@ -41,7 +41,8 @@ fn camera_entries(app: &LightcraftApp, ui: &egui::Ui, raw_default: &str) -> std: let generation = app.session.presets.generation(); let language = crate::i18n::language(); let cache = egui::Id::unique("settings-camera-entries"); - if let Some((_, _, entries)) = ui.data(|data| data.get_temp::(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) { + if let Some((_, _, entries)) = ui.data(|data| data.get_temp::(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) + { return entries; } let mut entries = vec![ @@ -151,7 +152,15 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) let cur = d.metadata_preset.clone().unwrap_or_default(); let mut entries = vec![craft::ui::contract::Entry::new(String::new(), crate::i18n::tr("None").to_owned())]; entries.extend(app.session.metadata_presets.iter().map(|m| craft::ui::contract::Entry::new(m.name.clone(), m.name.clone()))); - let pick = crate::widgets::select(ui, "combo:settingsMetaPreset", crate::i18n::tr("Metadata preset"), cur.clone(), &entries, Some(cur), Some(240.0)); + let pick = crate::widgets::select( + ui, + "combo:settingsMetaPreset", + crate::i18n::tr("Metadata preset"), + cur.clone(), + &entries, + Some(cur), + Some(240.0), + ); if let Some(n) = pick { let _ = app.run("library.preferences", json!({"import": {"metadataPreset": n}})); } diff --git a/crates/ui-egui/src/dialogs/settings/slide_overlays.rs b/crates/ui-egui/src/dialogs/settings/slide_overlays.rs index 7b00e88a06..29481ab269 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_overlays.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_overlays.rs @@ -189,26 +189,14 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, "Colour", |ui| colour(app, ui, "slideshowPlateColor", "Colour", p.color, &|c| plate(json!({"color": c})))); } row(ui, t, "Size", |ui| { - slider( - app, - ui, - "slideshowPlateSize", - "Size", - p.size, - Range { lo: 0.01, hi: PLATE_SIZE_MAX, unit: Unit::Percent }, - &|v| plate(json!({"size": v})), - ) + slider(app, ui, "slideshowPlateSize", "Size", p.size, Range { lo: 0.01, hi: PLATE_SIZE_MAX, unit: Unit::Percent }, &|v| { + plate(json!({"size": v})) + }) }); row(ui, t, "Opacity", |ui| { - slider( - app, - ui, - "slideshowPlateOpacity", - "Opacity", - p.opacity, - Range { lo: 0.0, hi: 1.0, unit: Unit::Percent }, - &|v| plate(json!({"opacity": v})), - ) + slider(app, ui, "slideshowPlateOpacity", "Opacity", p.opacity, Range { lo: 0.0, hi: 1.0, unit: Unit::Percent }, &|v| { + plate(json!({"opacity": v})) + }) }); placement(app, ui, t, "slideshowPlate", &p.place, true, &plate); toggle(app, ui, "slideshowPlateBehind", p.behind, "Render behind image", &|v| plate(json!({"behind": v}))); @@ -221,15 +209,9 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if toggle(app, ui, "slideshowStars", r.enabled, "Rating stars", &|v| stars(json!({"enabled": v}))) { row(ui, t, "Colour", |ui| colour(app, ui, "slideshowStarsColor", "Colour", r.color, &|c| stars(json!({"color": c})))); row(ui, t, "Size", |ui| { - slider( - app, - ui, - "slideshowStarsSize", - "Size", - r.size, - Range { lo: 0.01, hi: STAR_SIZE_MAX, unit: Unit::Percent }, - &|v| stars(json!({"size": v})), - ) + slider(app, ui, "slideshowStarsSize", "Size", r.size, Range { lo: 0.01, hi: STAR_SIZE_MAX, unit: Unit::Percent }, &|v| { + stars(json!({"size": v})) + }) }); placement(app, ui, t, "slideshowStars", &r.place, true, &stars); } @@ -250,15 +232,9 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if toggle(app, ui, "slideshowWatermark", s.show_watermark, "Watermark", &|v| json!({"showWatermark": v})) { row(ui, t, "Text", |ui| text(app, ui, "slideshowWatermarkText", &w.text, "© Your Name", &|v| wm(json!({"text": v})))); row(ui, t, "Size", |ui| { - slider( - app, - ui, - "slideshowWatermarkSize", - "Size", - w.size as f64, - Range { lo: 0.01, hi: 0.15, unit: Unit::Percent }, - &|v| wm(json!({"size": v})), - ) + slider(app, ui, "slideshowWatermarkSize", "Size", w.size as f64, Range { lo: 0.01, hi: 0.15, unit: Unit::Percent }, &|v| { + wm(json!({"size": v})) + }) }); row(ui, t, "Opacity", |ui| { slider(app, ui, "slideshowWatermarkOpacity", "Opacity", w.opacity as f64, Range { lo: 0.05, hi: 1.0, unit: Unit::Percent }, &|v| { diff --git a/crates/ui-egui/src/dialogs/settings/slide_titles.rs b/crates/ui-egui/src/dialogs/settings/slide_titles.rs index 43bbe44ccc..dda9102909 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_titles.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_titles.rs @@ -106,9 +106,8 @@ fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, value: & let mem = egui::Id::unique(("slideshow-title-field", id)); let pass = ui.ctx().cumulative_pass_nr(); // A hidden/rebound field starts from its own authoritative screen, never a stale draft. - let remembered = ui - .data(|d| d.get_temp::(mem)) - .filter(|d| d.model == value && (d.pass == pass || d.pass.checked_add(1) == Some(pass))); + let remembered = + ui.data(|d| d.get_temp::(mem)).filter(|d| d.model == value && (d.pass == pass || d.pass.checked_add(1) == Some(pass))); let mut draft = remembered.map_or_else(|| value.to_owned(), |d| d.text); let widget = format!("field:{id}"); let width = ui.available_width().clamp(80.0, 260.0); diff --git a/crates/ui-egui/src/dialogs/settings/slideshow_export_launcher_candidate_flow_tests.rs b/crates/ui-egui/src/dialogs/settings/slideshow_export_launcher_candidate_flow_tests.rs index a72984ecb4..d4e8613204 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow_export_launcher_candidate_flow_tests.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow_export_launcher_candidate_flow_tests.rs @@ -426,15 +426,3 @@ fn slideshow_launcher_sdk_11_physical_escape_cancels_parent() { fn slideshow_launcher_sdk_12_natural_tab_and_activation() { case_12_natural_tab_and_activation(false); } - - - - - - - - - - - - diff --git a/crates/ui-egui/src/dialogs/updates_external155_tests.rs b/crates/ui-egui/src/dialogs/updates_external155_tests.rs index 2f4bc56493..0424a29078 100644 --- a/crates/ui-egui/src/dialogs/updates_external155_tests.rs +++ b/crates/ui-egui/src/dialogs/updates_external155_tests.rs @@ -223,9 +223,15 @@ fn updates155_click_widget_hits_the_real_result_footer() { let mut h = Headless::new(app, [1300.0, 820.0], 1.0); let limit = Duration::from_secs(10); check(&mut h.app).unwrap(); - assert!(h.step_until(limit, |h| matches!(h.app.updates_rt.updater.status(), Status::UpToDate) - && h.app.widget_hits.iter().any(|(id, _)| id == "button:updatesOk")), "missing registered result footer"); + assert!( + h.step_until(limit, |h| matches!(h.app.updates_rt.updater.status(), Status::UpToDate) + && h.app.widget_hits.iter().any(|(id, _)| id == "button:updatesOk")), + "missing registered result footer" + ); let answer = h.request("ui.clickWidget", serde_json::json!({"id":"button:updatesOk"}), limit); assert_eq!(answer["ok"], true, "{answer}"); - assert!(h.step_until(limit, |h| !blocks_input(&h.app) && !h.app.widgets.iter().any(|(id, _)| id == "button:updatesOk")), "registered click did not dismiss the actual result"); + assert!( + h.step_until(limit, |h| !blocks_input(&h.app) && !h.app.widgets.iter().any(|(id, _)| id == "button:updatesOk")), + "registered click did not dismiss the actual result" + ); } diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index f83197592e..409b3d482c 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -339,7 +339,12 @@ fn show_web_result(ctx: &egui::Context, message: Option<&str>) -> bool { use std::cell::Cell; let dismissed = Cell::new(false); crate::dialogs::host_ui(ctx, egui::Id::unique("lightcraft.updates.host"), |ui| { - let ok = [crate::dialogs::FooterSpec { label: crate::i18n::tr("OK").to_owned(), name: "button:updatesWebOk".into(), enabled: true, primary: true }]; + let ok = [crate::dialogs::FooterSpec { + label: crate::i18n::tr("OK").to_owned(), + name: "button:updatesWebOk".into(), + enabled: true, + primary: true, + }]; let output = Dialog::new(crate::i18n::tr("LightCraft Updates").to_owned()) .id_salt("lightcraft.updates.web") .opened(Bind::given(true)) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 92bed227f7..9efc218073 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -499,7 +499,9 @@ pub(crate) fn reveal_command(app: &mut crate::LightcraftApp, id: &str) -> Result /// Check the target's actual egui layer even while a different widget owns the drag. pub(crate) fn drop_target(ui: &egui::Ui, rect: egui::Rect, pointer: Option) -> bool { pointer.is_some_and(|pos| { - rect.intersect(ui.clip_rect()).contains(pos) && ui.ctx().layer_id_at(pos) == Some(ui.layer_id()) && !under_floating_window(ui.ctx(), rect.intersect(ui.clip_rect()), pos) + rect.intersect(ui.clip_rect()).contains(pos) + && ui.ctx().layer_id_at(pos) == Some(ui.layer_id()) + && !under_floating_window(ui.ctx(), rect.intersect(ui.clip_rect()), pos) }) } diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index d6286da7e4..5446249822 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -4269,28 +4269,57 @@ fn about_dialog_tabs_show_the_credits() { let r = h.request("ui.menu.invoke", json!({"id": "app.about"}), t); assert_eq!(r["ok"], true, "{r}"); assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::About)); - let tree = |h: &Headless| craft::ui::runtime::inspect::recorded(&h.view.ctx, egui::Id::unique("about-app-contract")).expect("SDK About was painted"); + let tree = + |h: &Headless| craft::ui::runtime::inspect::recorded(&h.view.ctx, egui::Id::unique("about-app-contract")).expect("SDK About was painted"); for (tab, evidence) in [("Models", "Models"), ("Contributors", "Contributors"), ("About", "Join the ArtCraft Discord")] { - for _ in 0..5 { h.step(); } + for _ in 0..5 { + h.step(); + } let nodes = tree(&h); - let target = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.role == "Tab" && f.name.as_deref() == Some(tab) && f.interactive && !f.disabled)).unwrap_or_else(|| panic!("missing enabled SDK tab {tab}")); + let target = nodes + .elements + .iter() + .find(|node| node.facts.as_ref().is_some_and(|f| f.role == "Tab" && f.name.as_deref() == Some(tab) && f.interactive && !f.disabled)) + .unwrap_or_else(|| panic!("missing enabled SDK tab {tab}")); let at = target.rect.center(); assert_eq!(h.request("ui.click", json!({"x":at.x,"y":at.y}), t)["ok"], true); - for _ in 0..4 { h.step(); } + for _ in 0..4 { + h.step(); + } if tab == "Contributors" { // Initially the grab bag is visible. "Table" is a view selector, not the table name. let nodes = tree(&h); - let at = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("Table") && f.interactive && !f.disabled)).expect("Table view selector").rect.center(); + let at = nodes + .elements + .iter() + .find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("Table") && f.interactive && !f.disabled)) + .expect("Table view selector") + .rect + .center(); assert_eq!(h.request("ui.click", json!({"x":at.x,"y":at.y}), t)["ok"], true); - for _ in 0..4 { h.step(); } + for _ in 0..4 { + h.step(); + } } - assert!(tree(&h).elements.iter().any(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(evidence) && (tab == "About" || f.role == "Table"))), "missing content after clicking {tab}"); + assert!( + tree(&h) + .elements + .iter() + .any(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(evidence) && (tab == "About" || f.role == "Table"))), + "missing content after clicking {tab}" + ); assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::About)); } let img = h.snapshot(SETTLE); assert_eq!(img.size, [1300, 820]); let nodes = tree(&h); - let ok = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("OK") && f.interactive && !f.disabled)).expect("real SDK footer").rect.center(); + let ok = nodes + .elements + .iter() + .find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("OK") && f.interactive && !f.disabled)) + .expect("real SDK footer") + .rect + .center(); assert_eq!(h.request("ui.click", json!({"x":ok.x,"y":ok.y}), t)["ok"], true); assert!(h.step_until(t, |frame| frame.app.ui.dialog.is_none()), "SDK OK closes the application dialog"); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index dd9a3217c8..3afb3779c6 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -266,7 +266,10 @@ pub(crate) fn framework_catalogs() -> &'static std::sync::Arc static CATALOGS: OnceLock> = OnceLock::new(); CATALOGS.get_or_init(|| { let offered: Vec<&str> = Locale::ALL.iter().filter(|language| !language.catalog().is_empty()).map(|language| language.code()).collect(); - let catalogs = offered.iter().filter_map(|code| Locale::parse(code)).map(|language| (language.code().to_owned(), String::new(), craft_catalog(language))); + let catalogs = offered + .iter() + .filter_map(|code| Locale::parse(code)) + .map(|language| (language.code().to_owned(), String::new(), craft_catalog(language))); let (i18n, problems) = craft::i18n::I18n::from_owned(catalogs.collect::>(), &offered); for problem in problems { log::debug!("framework words: {problem}"); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 1adb2623f8..dfca8e766e 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -1099,7 +1099,11 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32 .collect(); // The bar is placed in its room, so the titles that do not fit go into its "…" or "Menu" title. A measuring // or sizing run must never open a menu: disabled, its titles sense nothing. - MenuBar::new(crate::i18n::tr("Main menu").to_owned(), titles).id_salt("in-window-menu-bar").keyboard(keys).enabled(!measuring(ui)).show_at(ui, room) + MenuBar::new(crate::i18n::tr("Main menu").to_owned(), titles) + .id_salt("in-window-menu-bar") + .keyboard(keys) + .enabled(!measuring(ui)) + .show_at(ui, room) }); // the titles' own width is what the bar takes of the row let used = shown.titles.width().max(0.0); diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 234f8d557f..ad0ae964b3 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -302,20 +302,20 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo let zr = dropdown_face(&mut child, "zoom", crate::i18n::tr(&zoom_label)); let mut zoom_pick = None; if !measuring(&child) { - Menu::new(crate::i18n::tr("Zoom")).id_salt("zoom-menu").values().opened_by(&zr, Trigger::Click).show(&mut child, |ui, _| { - for (label, z) in [ - ("Fit", Zoom::Fit), - ("Fill", Zoom::Fill), - ("50%", Zoom::Percent(50.0)), - ("100%", Zoom::Percent(100.0)), - ("200%", Zoom::Percent(200.0)), - ("400%", Zoom::Percent(400.0)), - ] { - if value_row(ui, ("zoom", label), crate::i18n::tr(label), app.ui.zoom == z) { - zoom_pick = Some(z); + Menu::new(crate::i18n::tr("Zoom")).id_salt("zoom-menu").values().opened_by(&zr, Trigger::Click).show(&mut child, |ui, _| { + for (label, z) in [ + ("Fit", Zoom::Fit), + ("Fill", Zoom::Fill), + ("50%", Zoom::Percent(50.0)), + ("100%", Zoom::Percent(100.0)), + ("200%", Zoom::Percent(200.0)), + ("400%", Zoom::Percent(400.0)), + ] { + if value_row(ui, ("zoom", label), crate::i18n::tr(label), app.ui.zoom == z) { + zoom_pick = Some(z); + } } - } - }); + }); } if let Some(z) = zoom_pick { app.ui.zoom = z; diff --git a/crates/ui-egui/src/panels/bottombar/pick_flow_tests.rs b/crates/ui-egui/src/panels/bottombar/pick_flow_tests.rs index b72aeedb7c..4a7d9c23c2 100644 --- a/crates/ui-egui/src/panels/bottombar/pick_flow_tests.rs +++ b/crates/ui-egui/src/panels/bottombar/pick_flow_tests.rs @@ -288,11 +288,7 @@ impl Review { for alias in ["flag:unflag", PICK, "flag:reject"] { // the three flags are framework buttons: none publishes a target in a measuring or sizing pass let expected = usize::from(!(SDK_PICK && matches!(self.pass, Pass::Measure | Pass::Sizing))); - assert_eq!( - rects.iter().filter(|(name, _)| name == alias).count(), - expected, - "only real passes publish an interactive flag target" - ); + assert_eq!(rects.iter().filter(|(name, _)| name == alias).count(), expected, "only real passes publish an interactive flag target"); } self.rects = rects.into_iter().collect(); self.hits = hits.into_iter().collect(); diff --git a/crates/ui-egui/src/panels/bottombar/sort_popup_external_20261119.rs b/crates/ui-egui/src/panels/bottombar/sort_popup_external_20261119.rs index 15ee983ede..5a2b780ff7 100644 --- a/crates/ui-egui/src/panels/bottombar/sort_popup_external_20261119.rs +++ b/crates/ui-egui/src/panels/bottombar/sort_popup_external_20261119.rs @@ -34,7 +34,11 @@ fn fixture(random: bool, held: bool) -> (LightcraftApp, PhotoId) { } #[derive(Clone, Copy)] -enum Pass { Real, Measure, Sizing } +enum Pass { + Real, + Measure, + Sizing, +} struct Frames { ctx: egui::Context, @@ -68,22 +72,21 @@ impl Frames { self.rows.clear(); self.disabled.clear(); let mut output = self.ctx.run_ui(raw, |ui| { - let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("sort-popup-test-inspection"), |ui| { - match pass { - Pass::Real => show(&mut self.app, ui), - Pass::Measure => { - let ctx = ui.ctx().clone(); - craft::ui::runtime::measure::run(&ctx, || show(&mut self.app, ui)); - } - Pass::Sizing => { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible()); - show(&mut self.app, &mut child); - } + let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("sort-popup-test-inspection"), |ui| match pass { + Pass::Real => show(&mut self.app, ui), + Pass::Measure => { + let ctx = ui.ctx().clone(); + craft::ui::runtime::measure::run(&ctx, || show(&mut self.app, ui)); + } + Pass::Sizing => { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible()); + show(&mut self.app, &mut child); } }); if let Some(record) = record { for element in &record.elements { - if element.component == "MenuItem" && element.part.is_none() + if element.component == "MenuItem" + && element.part.is_none() && let Some(name) = element.facts.as_ref().and_then(|facts| facts.name.as_ref()) && let Some(response) = ui.ctx().read_response(element.id) { @@ -100,7 +103,9 @@ impl Frames { } fn settle(&mut self) { - for _ in 0..8 { self.frame(vec![], Pass::Real); } + for _ in 0..8 { + self.frame(vec![], Pass::Real); + } } fn row(&self, label: &str) -> &Response { @@ -122,7 +127,10 @@ impl Frames { fn click_at(&mut self, pos: Pos2, long: bool) { self.frame(vec![Event::PointerMoved(pos)], Pass::Real); self.pointer(pos, true); - if long { self.time += 2.0; self.frame(vec![], Pass::Real); } + if long { + self.time += 2.0; + self.frame(vec![], Pass::Real); + } self.pointer(pos, false); self.settle(); } @@ -170,7 +178,9 @@ fn external_sort_popup_action_visibility_and_real_refresh_locator() { assert_eq!(f.rows.iter().any(|(name, _)| name == "Reshuffle"), random); assert_eq!(f.rows.iter().any(|(name, _)| name == "Refresh View"), held); assert_eq!(f.rects.iter().any(|(name, _)| name == "button:refreshView"), held); - if random { assert!(f.row("Reshuffle").interact_rect.is_positive()); } + if random { + assert!(f.row("Reshuffle").interact_rect.is_positive()); + } if held { let row = f.row("Refresh View"); let hit = f.hit("button:refreshView"); @@ -260,9 +270,10 @@ fn external_sort_popup_measure_and_native_sizing_cannot_dispatch_actions() { let before = f.snapshot(); let pos = response.interact_rect.center(); for pressed in [true, false] { - f.frame(vec![Event::PointerMoved(pos), Event::PointerButton { - pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE, - }], pass); + f.frame( + vec![Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + pass, + ); } for key in [Key::Enter, Key::Space] { f.ctx.memory_mut(|memory| memory.request_focus(response.id)); @@ -274,7 +285,6 @@ fn external_sort_popup_measure_and_native_sizing_cannot_dispatch_actions() { } } - #[test] fn library_sort_choices_change_order_direction_and_group_without_photo_edits() { let mut f = Frames::new(false, false, 1.0); @@ -290,7 +300,9 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() { ("sort:key:fileName", "File Name", json!({"key":"fileName"})), ("sort:ascending", "Ascending", json!({"ascending":true})), ] { - if !f.is_open() { f.open(); } + if !f.is_open() { + f.open(); + } let row = f.row(label).clone(); assert_eq!(f.hit(id).id, row.id); assert!(row.enabled() && row.sense.is_focusable()); @@ -303,7 +315,9 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() { assert_eq!(f.app.session.catalog.revision, revision); assert_eq!(f.app.session.undo.len(), undo); if id == "sort:key:random" { - if !f.is_open() { f.open(); } + if !f.is_open() { + f.open(); + } let dir = f.row("Ascending").clone(); assert!(f.disabled.iter().any(|name| name == "Ascending"), "a shuffle has no direction to choose: the row is disabled"); f.click_at(dir.interact_rect.center(), false); @@ -313,7 +327,6 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() { } } - #[test] fn library_sort_choices_measuring_release_is_inert_then_same_owner_changes_order() { for pass in [Pass::Measure, Pass::Sizing] { @@ -330,7 +343,9 @@ fn library_sort_choices_measuring_release_is_inert_then_same_owner_changes_order assert!(!f.hits.iter().any(|(n, _)| n.starts_with("sort:")), "measurement published a sort hit"); f.settle(); assert_eq!(f.snapshot(), before, "measuring release changed the library or replayed"); - if !f.is_open() { f.open(); } + if !f.is_open() { + f.open(); + } let recovered = f.hit(target); assert_eq!(recovered.id, hit.id); f.click_at(recovered.interact_rect.center(), false); @@ -346,17 +361,20 @@ fn compact_view_sort_changes_rating_order_without_changing_photo_selection() { let (mut oracle, _) = fixture(false, false); oracle.run("library.sort", json!({"key":"rating"})).unwrap(); let mut ready = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 700.0)).build_ui_state(move |ui, app: &mut LightcraftApp| { - if !ready { - crate::theme::install_fonts(ui.ctx()); - crate::theme::apply(ui.ctx()); - app.install_framework(ui.ctx()); - ready = true; - return; - } - let _ = take_registries(ui.ctx()); - show(app, ui); - }, app); + let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 700.0)).build_ui_state( + move |ui, app: &mut LightcraftApp| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx()); + app.install_framework(ui.ctx()); + ready = true; + return; + } + let _ = take_registries(ui.ctx()); + show(app, ui); + }, + app, + ); h.run_steps(8); assert!(h.query_by_label("Sort").is_none(), "narrow layout should not show the wide Sort opener"); h.get_by_label("View").click(); @@ -397,7 +415,8 @@ fn capture_external_sort_popup_matched_old_new() { } let _ = take_registries(ui.ctx()); show(app, ui); - }, app, + }, + app, ); harness.input_mut().max_texture_side = Some(8192); harness.run_steps(8); diff --git a/crates/ui-egui/src/panels/compare_external155_tests.rs b/crates/ui-egui/src/panels/compare_external155_tests.rs index 4fcdd577d1..fb1fc4f429 100644 --- a/crates/ui-egui/src/panels/compare_external155_tests.rs +++ b/crates/ui-egui/src/panels/compare_external155_tests.rs @@ -35,13 +35,17 @@ fn open(h: &mut Headless, photo: u64, row: &str) { // Aim at the part of this specific photo visible inside its real pane response. let name = format!("cull:{photo}"); let image = h.app.widgets.iter().find(|(key, _)| key == &name).unwrap().1; - let pane = (0..=1u8).find_map(|slot| h.view.ctx.read_response(egui::Id::unique(("cull-tile", slot, photo)))) - .expect("real pane for requested photo"); + let pane = + (0..=1u8).find_map(|slot| h.view.ctx.read_response(egui::Id::unique(("cull-tile", slot, photo)))).expect("real pane for requested photo"); let visible = pane.interact_rect.intersect(image); assert!(visible.is_positive(), "requested photo has no visible image area"); let at = visible.center(); - ask(h, "ui.clickWidget", json!({"id": name, "button": "right", - "fx": (at.x - image.left()) / image.width(), "fy": (at.y - image.top()) / image.height()})); + ask( + h, + "ui.clickWidget", + json!({"id": name, "button": "right", + "fx": (at.x - image.left()) / image.width(), "fy": (at.y - image.top()) / image.height()}), + ); assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any)); assert!(h.app.widget_hits.iter().any(|(id, _)| id == row), "real menu response registered for {row}"); } @@ -71,9 +75,7 @@ fn compare_external155_swap_real_press_release_preserves_active_pin_and_navigati h.app.synthetic.push(egui::Event::PointerMoved(at)); h.step(); for pressed in [true, false] { - h.app.synthetic.push(egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, - }); + h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); h.step(); h.step(); } @@ -148,10 +150,7 @@ fn compare_external155_clear_reference_keyboard_activation_keeps_active_selectio #[test] fn compare_external155_escape_cancels_both_menus_without_retargeting_photos() { let (mut h, ids) = setup(); - for (view, photo, row) in [ - (ViewMode::Compare, ids[0], "compare:swap"), - (ViewMode::Reference, ids[3], "compare:clearReference"), - ] { + for (view, photo, row) in [(ViewMode::Compare, ids[0], "compare:swap"), (ViewMode::Reference, ids[3], "compare:clearReference")] { h.app.ui.view = view; h.settle(WAIT); let before = snapshot(&h); @@ -174,10 +173,13 @@ fn compare_external155_disabled_real_row_does_not_activate() { let mut at = egui::Pos2::ZERO; for frame in 0..5 { let events = if frame == 2 || frame == 3 { - vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE, - }] - } else { vec![] }; + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE }, + ] + } else { + vec![] + }; let raw = HeadlessView::raw_input(egui::vec2(400.0, 200.0), 1.0, frame as f64 / 60.0, events); view.run(raw, |ui| { crate::widgets::take_registries(ui.ctx()); diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index a4ae4dcf7a..9d4426b82b 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -414,7 +414,6 @@ fn photos_queue_actions(ui: &mut egui::Ui, running: Option<(u64, u64)>, queued: }); } - /// "Denoising {photo}: {done} of {total} tiles", and how many photos wait. fn running_text(app: &LightcraftApp, status: &Value, done: u64, total: u64, queued: u64) -> String { let name = @@ -896,7 +895,6 @@ mod queue_actions_tests; #[path = "denoise_qualified_work_flow_tests.rs"] mod qualified_work_flow_tests; - #[cfg(test)] #[path = "denoise_per_photo_qualified_flow_tests.rs"] mod per_photo_qualified_flow_tests; diff --git a/crates/ui-egui/src/panels/denoise_queue_actions_tests.rs b/crates/ui-egui/src/panels/denoise_queue_actions_tests.rs index 3fb3c1ab5c..32fb8e8199 100644 --- a/crates/ui-egui/src/panels/denoise_queue_actions_tests.rs +++ b/crates/ui-egui/src/panels/denoise_queue_actions_tests.rs @@ -9,7 +9,10 @@ const QUEUE: &str = "denoise:queueAll"; const STOP: &str = "denoise:stop"; #[derive(Clone, Copy, Default)] -struct Pass { sizing: bool, measuring: bool } +struct Pass { + sizing: bool, + measuring: bool, +} struct Frames { ctx: egui::Context, @@ -36,10 +39,22 @@ impl Frames { craft::ui::install( &ctx, craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), std::sync::Arc::new(craft::window::system::NoWindows)), - ).unwrap(); + ) + .unwrap(); Self { - ctx, time: 0.0, running, queued, disabled: false, pass: Pass::default(), size: vec2(1000.0, 300.0), scale: 1.0, - commands: vec![], rects: vec![], hits: vec![], elements: vec![], nodes: vec![], + ctx, + time: 0.0, + running, + queued, + disabled: false, + pass: Pass::default(), + size: vec2(1000.0, 300.0), + scale: 1.0, + commands: vec![], + rects: vec![], + hits: vec![], + elements: vec![], + nodes: vec![], } } @@ -58,7 +73,9 @@ impl Frames { self.commands.push((command.into(), params)); }); }); - if let Some(record) = record { self.elements = record.elements.clone(); } + if let Some(record) = record { + self.elements = record.elements.clone(); + } }; if self.pass.sizing { let mut child = ui.new_child(egui::UiBuilder::new().sizing_pass().max_rect(ui.max_rect())); @@ -81,14 +98,19 @@ impl Frames { (self.rects, self.hits) = take_registries(&ctx); } - fn settle(&mut self) { for _ in 0..3 { self.frame(vec![]); } } + fn settle(&mut self) { + for _ in 0..3 { + self.frame(vec![]); + } + } fn target(&self, id: &str) -> (Rect, WidgetHit) { assert_eq!(self.rects.iter().filter(|(name, _)| name == id).count(), 1); assert_eq!(self.hits.iter().filter(|(name, _)| name == id).count(), 1); let rect = self.rects.iter().find(|(name, _)| name == id).unwrap().1; let hit = self.hits.iter().find(|(name, _)| name == id).unwrap().1; - let element = self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("real SDK response owner, not hover probe"); + let element = + self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("real SDK response owner, not hover probe"); assert_eq!(element.component, "Button"); assert_eq!(element.rect, rect); assert!(rect.is_finite() && rect.is_positive()); @@ -127,8 +149,7 @@ fn pointer(pos: Pos2, button: PointerButton, pressed: bool) -> Event { } fn expected(id: &str) -> (String, Value) { - if id == QUEUE { ("denoise.queue".into(), json!({"scope": "withAmount"})) } - else { ("denoise.cancel".into(), json!({})) } + if id == QUEUE { ("denoise.queue".into(), json!({"scope": "withAmount"})) } else { ("denoise.cancel".into(), json!({})) } } #[test] @@ -140,7 +161,9 @@ fn photos_queue_stop_visibility_is_running_or_queued_and_queue_is_always_present let busy = running.is_some() || queued > 0; assert_eq!(f.rects.iter().any(|(id, _)| id == STOP), busy); assert_eq!(f.hits.iter().any(|(id, _)| id == STOP), busy); - if busy { f.target(STOP); } + if busy { + f.target(STOP); + } assert!(f.commands.is_empty()); } } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index aa598a3673..e219168ea2 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -16,8 +16,8 @@ use crate::widgets::{register, register_geometry}; mod crop; mod filmstrip; -pub(crate) mod host; mod geometry; +pub(crate) mod host; mod info; mod lens_blur; mod look_ahead; diff --git a/crates/ui-egui/src/panels/detail/filmstrip.rs b/crates/ui-egui/src/panels/detail/filmstrip.rs index d3b7d9fdf1..9be8369eb0 100644 --- a/crates/ui-egui/src/panels/detail/filmstrip.rs +++ b/crates/ui-egui/src/panels/detail/filmstrip.rs @@ -1,4 +1,4 @@ -use super::{host, Align2, Color32, LightcraftApp, PhotoId, Pos2, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, json, pos2, register, vec2}; +use super::{Align2, Color32, LightcraftApp, PhotoId, Pos2, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, host, json, pos2, register, vec2}; /// Size of the Navigator mini map (points). const NAV_W: f32 = 180.0; @@ -79,139 +79,146 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { // a wheel notch scrolls a third of its width; see `grid::wheel_step` register(ui, "filmstrip", child.max_rect()); let wheel = crate::panels::grid::wheel_step(&child, egui::Id::unique("film-wheel"), child.max_rect(), child.max_rect().width(), true); - egui::ScrollArea::horizontal() - .id_salt("filmstrip") - .auto_shrink([false, false]) - .scroll_source(crate::panels::grid::WHEEL_OFF) - .show_viewport(&mut child, |ui, vp| { - if wheel != egui::Vec2::ZERO { - ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none()); - } - let (area, _) = ui.allocate_exact_size(vec2(ids.len() as f32 * cell_w, r.height() - 16.0), Sense::hover()); - app.film_scroll = Some(vp.left()); - for (i, id) in ids.iter().enumerate() { - let cr = Rect::from_min_size(pos2(area.left() + i as f32 * cell_w, area.top()), vec2(cell_w, area.height())); - let local = Rect::from_min_size(pos2(i as f32 * cell_w, 0.0), cr.size()); - // centred when it is (partly) off screen; a click on a visible thumbnail leaves the strip alone - if follow && Some(*id) == active && !(local.left() >= vp.left() && local.right() <= vp.right()) { - ui.scroll_to_rect(cr, Some(egui::Align::Center)); + egui::ScrollArea::horizontal().id_salt("filmstrip").auto_shrink([false, false]).scroll_source(crate::panels::grid::WHEEL_OFF).show_viewport( + &mut child, + |ui, vp| { + if wheel != egui::Vec2::ZERO { + ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none()); } - if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) { - continue; - } - let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some(); - let spoken = film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed); - let resp = host::target(ui, ("film", id.0), cr, host::Target::new(spoken).drag()); - if host::live(ui) { - crate::widgets::register_response(format!("film:{}", id.0), cr, &resp); - } - let state = app.session.selection.state_of(*id); - let p = ui.painter(); - let label = app.session.catalog.photo(*id).and_then(|ph| ph.label); - let selected = state != lightcraft_engine::SelectionState::NotSelected; - let base = if selected { - t.cell_selected - } else if resp.hovered() { - t.cell_selected.gamma_multiply(0.6) - } else { - t.canvas - }; - p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected)); - let names = app.ui.settings.film_names; - if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) { - let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name); - p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim); - p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim); - } - let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0)); - crate::panels::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8); - let thumb = app.renderer.thumb(*id); - if thumb.is_none() { - p.rect_filled(img_area, 0.0, t.skeleton); - if failed { - p.text(img_area.center(), Align2::CENTER_CENTER, "!", t.semibold(14.0), t.text); + let (area, _) = ui.allocate_exact_size(vec2(ids.len() as f32 * cell_w, r.height() - 16.0), Sense::hover()); + app.film_scroll = Some(vp.left()); + for (i, id) in ids.iter().enumerate() { + let cr = Rect::from_min_size(pos2(area.left() + i as f32 * cell_w, area.top()), vec2(cell_w, area.height())); + let local = Rect::from_min_size(pos2(i as f32 * cell_w, 0.0), cr.size()); + // centred when it is (partly) off screen; a click on a visible thumbnail leaves the strip alone + if follow && Some(*id) == active && !(local.left() >= vp.left() && local.right() <= vp.right()) { + ui.scroll_to_rect(cr, Some(egui::Align::Center)); } - } - if let Some(tex) = thumb { - let [tw, th] = tex.size; - let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32); - let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s)); - p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - crate::panels::grid::selection_ring(p, &t, fr, state); - if app.ui.settings.film_badges - && let Some(ph) = app.session.catalog.photo(*id) - { - film_badges(p, &t, fr, ph); + if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) { + continue; } - if let Some(st) = app.session.catalog.stack_of(*id) { - let collapsed = st.collapsed; - let text = - if collapsed { st.photos.len().to_string() } else { format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len()) }; - let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE); - let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0)); - // like the grid's badge: a click expands / collapses the stack - let badge = host::target( - ui, - ("film-stack-badge", id.0), - br, - host::Target::new(crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })).tooltip(if collapsed { - "Stack — click to expand" - } else { - "Stack — click to collapse" - }), - ); - if host::live(ui) { - crate::widgets::register_response(format!("filmstack:{}", id.0), br, &badge); - } - let p = ui.painter(); - let fill = if badge.hovered() { Color32::from_black_alpha(230) } else { Color32::from_black_alpha(170) }; - p.rect_filled(br, 7.5, fill); - crate::icons::paint(p, Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)), crate::icons::Icon::Stack, Color32::WHITE); - p.galley(pos2(br.min.x + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE); - if badge.clicked() { - crate::panels::grid::toggle_stack(app, ui.ctx(), *id); - } + let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some(); + let spoken = film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed); + let resp = host::target(ui, ("film", id.0), cr, host::Target::new(spoken).drag()); + if host::live(ui) { + crate::widgets::register_response(format!("film:{}", id.0), cr, &resp); } - } - if resp.clicked() { - let m = ui.input(|i| i.modifiers); - let compare = app.ui.view == crate::state::ViewMode::Compare; - let r = if compare && !m.command && !m.shift { - // Compare: the clicked photo replaces the active side (or swaps with the other one) - app.run("compare.set", json!({"id": id.0})) - } else if compare { - // ⌘/Ctrl- and Shift-clicks change the selection; the pair on screen stays (#187) - crate::panels::compare::select_with_modifier(app, *id, !m.command) + let state = app.session.selection.state_of(*id); + let p = ui.painter(); + let label = app.session.catalog.photo(*id).and_then(|ph| ph.label); + let selected = state != lightcraft_engine::SelectionState::NotSelected; + let base = if selected { + t.cell_selected + } else if resp.hovered() { + t.cell_selected.gamma_multiply(0.6) } else { - let mode = if m.command { - "toggle" - } else if m.shift { - "range" - } else { - "replace" - }; - app.run("library.select", json!({"ids": [id.0], "mode": mode})) + t.canvas }; - if compare && let Err(e) = r { - app.toast(ui.ctx(), e); + p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected)); + let names = app.ui.settings.film_names; + if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) { + let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name); + p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim); + p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim); } - } - // drag the selection to a sidebar row, as from the grid (a plain click never starts one); in - // Compare an unselected photo is dragged alone, so the pair and its active photo stay (#744). - // Only the primary button drags: a right-button drag must not replace the selection - if resp.drag_started_by(egui::PointerButton::Primary) { - if app.ui.view == crate::state::ViewMode::Compare && !app.session.selection.contains(*id) { - app.ui.dragging_photos = Some(vec![id.0]); - } else { - crate::panels::grid::begin_photo_drag(app, *id); + let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0)); + crate::panels::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8); + let thumb = app.renderer.thumb(*id); + if thumb.is_none() { + p.rect_filled(img_area, 0.0, t.skeleton); + if failed { + p.text(img_area.center(), Align2::CENTER_CENTER, "!", t.semibold(14.0), t.text); + } } + if let Some(tex) = thumb { + let [tw, th] = tex.size; + let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32); + let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s)); + p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + crate::panels::grid::selection_ring(p, &t, fr, state); + if app.ui.settings.film_badges + && let Some(ph) = app.session.catalog.photo(*id) + { + film_badges(p, &t, fr, ph); + } + if let Some(st) = app.session.catalog.stack_of(*id) { + let collapsed = st.collapsed; + let text = if collapsed { + st.photos.len().to_string() + } else { + format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len()) + }; + let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE); + let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0)); + // like the grid's badge: a click expands / collapses the stack + let badge = host::target( + ui, + ("film-stack-badge", id.0), + br, + host::Target::new(crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })).tooltip(if collapsed { + "Stack — click to expand" + } else { + "Stack — click to collapse" + }), + ); + if host::live(ui) { + crate::widgets::register_response(format!("filmstack:{}", id.0), br, &badge); + } + let p = ui.painter(); + let fill = if badge.hovered() { Color32::from_black_alpha(230) } else { Color32::from_black_alpha(170) }; + p.rect_filled(br, 7.5, fill); + crate::icons::paint( + p, + Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)), + crate::icons::Icon::Stack, + Color32::WHITE, + ); + p.galley(pos2(br.min.x + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE); + if badge.clicked() { + crate::panels::grid::toggle_stack(app, ui.ctx(), *id); + } + } + } + if resp.clicked() { + let m = ui.input(|i| i.modifiers); + let compare = app.ui.view == crate::state::ViewMode::Compare; + let r = if compare && !m.command && !m.shift { + // Compare: the clicked photo replaces the active side (or swaps with the other one) + app.run("compare.set", json!({"id": id.0})) + } else if compare { + // ⌘/Ctrl- and Shift-clicks change the selection; the pair on screen stays (#187) + crate::panels::compare::select_with_modifier(app, *id, !m.command) + } else { + let mode = if m.command { + "toggle" + } else if m.shift { + "range" + } else { + "replace" + }; + app.run("library.select", json!({"ids": [id.0], "mode": mode})) + }; + if compare && let Err(e) = r { + app.toast(ui.ctx(), e); + } + } + // drag the selection to a sidebar row, as from the grid (a plain click never starts one); in + // Compare an unselected photo is dragged alone, so the pair and its active photo stay (#744). + // Only the primary button drags: a right-button drag must not replace the selection + if resp.drag_started_by(egui::PointerButton::Primary) { + if app.ui.view == crate::state::ViewMode::Compare && !app.session.selection.contains(*id) { + app.ui.dragging_photos = Some(vec![id.0]); + } else { + crate::panels::grid::begin_photo_drag(app, *id); + } + } + // the same photo actions as the grid and loupe (Restore / Delete Permanently in Recently Deleted) + host::context_menu(ui, &resp, crate::i18n::tr("Photo"), |ui| crate::panels::grid::context_menu(app, ui, *id)); } - // the same photo actions as the grid and loupe (Restore / Delete Permanently in Recently Deleted) - host::context_menu(ui, &resp, crate::i18n::tr("Photo"), |ui| crate::panels::grid::context_menu(app, ui, *id)); - } - // Tab and focus requests keep the focused thumbnail in view - crate::panels::scroll_focus::reveal_focus(ui, egui::Id::unique("film-scroll-focus")); - }); + // Tab and focus requests keep the focused thumbnail in view + crate::panels::scroll_focus::reveal_focus(ui, egui::Id::unique("film-scroll-focus")); + }, + ); } /// What a screen reader says for a filmstrip thumbnail: the file, and why there is no picture diff --git a/crates/ui-egui/src/panels/detail/host.rs b/crates/ui-egui/src/panels/detail/host.rs index decfb35ff1..12e224d2cf 100644 --- a/crates/ui-egui/src/panels/detail/host.rs +++ b/crates/ui-egui/src/panels/detail/host.rs @@ -9,10 +9,10 @@ use std::hash::Hash; use std::ops::Deref; use craft::behavior::{Metrics, PressPhase, Sense}; -use craft::ui::contract::{Common, Component, Cx, NoValue, Outcome, PaintUi, Pointer as _, Props as _, Role, Show as _}; -use craft::ui::runtime::access::Access; -use craft::ui::menu::Menu; use craft::ui::contract::ShowContainer as _; +use craft::ui::contract::{Common, Component, Cx, NoValue, Outcome, PaintUi, Pointer as _, Props as _, Role, Show as _}; +use craft::ui::menu::Menu; +use craft::ui::runtime::access::Access; use craft::ui::style::{ComponentStyle, FocusLook, StyleCx}; use egui::{Color32, Rect, Response, Ui}; @@ -122,7 +122,8 @@ impl HostOutput { /// A secondary-button click landed on the target this pass. The SDK rewrites the response's own click flags /// (`Response::clicked` is the primary activation), so this reads egui's raw verdict for the same widget. pub fn secondary_clicked(&self) -> bool { - self.response.secondary_clicked() || self.response.ctx.read_response(self.response.id).is_some_and(|raw| raw.enabled() && raw.secondary_clicked()) + self.response.secondary_clicked() + || self.response.ctx.read_response(self.response.id).is_some_and(|raw| raw.enabled() && raw.secondary_clicked()) } /// The activation was the second press of a double click. @@ -206,7 +207,6 @@ impl<'a> Target<'a> { self.mode = Mode::Pointer; self } - } /// Show a host-painted target over `rect`, named `key` for egui. The caller registers its automation name with diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index dcd3e27645..14b2df6fce 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -1,9 +1,9 @@ use super::geometry::CanvasMap; -use crate::panels::masking::controls::Hit; use super::{ - Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, json, pos2, - register, vec2, + Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, json, pos2, register, + vec2, }; +use crate::panels::masking::controls::Hit; /// What the user did to a face box this frame. pub(super) enum RegionEdit { diff --git a/crates/ui-egui/src/panels/edit/curve.rs b/crates/ui-egui/src/panels/edit/curve.rs index 5efd9b8212..64bdb7df74 100644 --- a/crates/ui-egui/src/panels/edit/curve.rs +++ b/crates/ui-egui/src/panels/edit/curve.rs @@ -1,10 +1,10 @@ use super::histogram::preview_histogram; -use crate::panels::detail::host; use super::sliders::control; use super::{ Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricCurve, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke, Tokens, Vertex, controls, hex, json, paint, pos2, text_button, vec2, }; +use crate::panels::detail::host; // ------------------------------------------------------------------------------ tone curve @@ -428,7 +428,8 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) let builtin = current.as_ref().is_none_or(|name| all_presets(&app.session).iter().any(|p| p.builtin && &p.name == name)); let label = crate::i18n::builtin_label(current.as_deref().unwrap_or("Custom"), builtin); use craft::ui::contract::Show as _; - let face = craft::ui::buttons::Button::new(crate::i18n::tr("Point Curve preset")).painted(label.to_owned()).id_salt("curvePreset").show(ui); + let face = + craft::ui::buttons::Button::new(crate::i18n::tr("Point Curve preset")).painted(label.to_owned()).id_salt("curvePreset").show(ui); let activated = face.clicked(); let r = face.response; if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { @@ -437,74 +438,89 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) let active = ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); // Keep traversal, contextual actions and dismissal in the same SDK menu system. // A framework-owned opener is reachable from other SDK controls before the menu is open. - use craft::ui::contract::{Props as _, ShowContainer as _}; use craft::ui::contract::overlay::Trigger; + use craft::ui::contract::{Props as _, ShowContainer as _}; use craft::ui::menu::Menu; if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { // Use the button's SDK activation, not the external pointer-only press trigger. // Forget the open state after the panel stops drawing, as in Presets options. let pass = ui.ctx().cumulative_pass_nr(); let slot = r.id.with("menu-open"); - let mut open = ui.data(|d| d.get_temp::<(u64, bool)>(slot)) + let mut open = ui + .data(|d| d.get_temp::<(u64, bool)>(slot)) .filter(|(last, _)| *last == pass || last.saturating_add(1) == pass) .is_some_and(|(_, open)| open); - if active && activated { open = !open; } - Menu::new(crate::i18n::tr("Point Curve")).id_salt("curve-preset-menu").tab_exits().opened_by(&r, Trigger::Manual) - .open(craft::ui::contract::Bind::bound(&mut open)).show(ui, |ui, _| { - ui.set_min_width(180.0); - let presets = all_presets(&app.session); - let mut user_seen = false; - for p in &presets { - if !p.builtin && !user_seen { - user_seen = true; - ui.separator(); + if active && activated { + open = !open; + } + Menu::new(crate::i18n::tr("Point Curve")) + .id_salt("curve-preset-menu") + .tab_exits() + .opened_by(&r, Trigger::Manual) + .open(craft::ui::contract::Bind::bound(&mut open)) + .show(ui, |ui, _| { + ui.set_min_width(180.0); + let presets = all_presets(&app.session); + let mut user_seen = false; + for p in &presets { + if !p.builtin && !user_seen { + user_seen = true; + ui.separator(); + } + let id = format!("curvePreset:{}", p.name); + let (r, ran) = preset_item( + ui, + &id, + crate::i18n::builtin_label(&p.name, p.builtin), + Some(current.as_deref() == Some(p.name.as_str())), + active, + true, + ); + if ran { + let _ = app.run("curve.applyPreset", json!({"name": p.name})); + } + if active && !p.builtin && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { + Menu::context(crate::i18n::tr("Delete Preset"), &r).id_salt(("curve-preset-context", &p.name)).show(ui, |ui, _| { + if preset_item(ui, &format!("curvePresetDelete:{}", p.name), crate::i18n::tr("Delete Preset"), None, active, true) + .1 + { + let _ = app.run("curve.deletePreset", json!({"name":p.name})); + } + }); + } } - let id = format!("curvePreset:{}", p.name); - let (r, ran) = preset_item( + ui.separator(); + let shaped = current.as_deref() != Some("Linear"); + if preset_item(ui, "curvePresetMenu:save", crate::i18n::tr("Save Point Curve…"), None, active, shaped).1 { + crate::panels::dialogs::prompt(app, "Save Point Curve Preset", "Preset name", "", "curve.savePreset", json!({}), "name"); + } + if preset_item( ui, - &id, - crate::i18n::builtin_label(&p.name, p.builtin), - Some(current.as_deref() == Some(p.name.as_str())), + "curvePresetMenu:import", + crate::i18n::tr("Import Presets…"), + None, active, - true, - ); - if ran { - let _ = app.run("curve.applyPreset", json!({"name": p.name})); + app.services.pick_curve_preset_files.is_some(), + ) + .1 + { + let _ = app.run("file.importCurvePresets", json!({})); } - if active && !p.builtin && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { - Menu::context(crate::i18n::tr("Delete Preset"), &r).id_salt(("curve-preset-context", &p.name)).show(ui, |ui, _| { - if preset_item(ui, &format!("curvePresetDelete:{}", p.name), crate::i18n::tr("Delete Preset"), None, active, true).1 { - let _ = app.run("curve.deletePreset", json!({"name":p.name})); - } - }); + let can_export = app.services.save_curve_preset_file.is_some() && !app.session.curve_presets.is_empty(); + if preset_item(ui, "curvePresetMenu:export", crate::i18n::tr("Export Presets…"), None, active, can_export).1 { + let _ = app.run("file.exportCurvePresets", json!({})); } - } - ui.separator(); - let shaped = current.as_deref() != Some("Linear"); - if preset_item(ui, "curvePresetMenu:save", crate::i18n::tr("Save Point Curve…"), None, active, shaped).1 { - crate::panels::dialogs::prompt(app, "Save Point Curve Preset", "Preset name", "", "curve.savePreset", json!({}), "name"); - } - if preset_item( - ui, - "curvePresetMenu:import", - crate::i18n::tr("Import Presets…"), - None, - active, - app.services.pick_curve_preset_files.is_some(), - ) - .1 - { - let _ = app.run("file.importCurvePresets", json!({})); - } - let can_export = app.services.save_curve_preset_file.is_some() && !app.session.curve_presets.is_empty(); - if preset_item(ui, "curvePresetMenu:export", crate::i18n::tr("Export Presets…"), None, active, can_export).1 { - let _ = app.run("file.exportCurvePresets", json!({})); - } - if presets.iter().any(|p| !p.builtin) { - ui.label(RichText::new(crate::i18n::tr("Right-click a preset to delete it")).font(t.font(11.0)).color(t.text_dim)); + if presets.iter().any(|p| !p.builtin) { + ui.label(RichText::new(crate::i18n::tr("Right-click a preset to delete it")).font(t.font(11.0)).color(t.text_dim)); + } + }); + ui.data_mut(|d| { + if open { + d.insert_temp(slot, (pass, true)); + } else { + d.remove::<(u64, bool)>(slot); } }); - ui.data_mut(|d| { if open { d.insert_temp(slot, (pass, true)); } else { d.remove::<(u64, bool)>(slot); } }); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let r = text_button(ui, "curveReset", crate::i18n::tr("Reset"), false).on_hover_text(crate::i18n::tr( diff --git a/crates/ui-egui/src/panels/edit/curve_preset_workflow_tests.rs b/crates/ui-egui/src/panels/edit/curve_preset_workflow_tests.rs index a3abacc5b4..40d6637a61 100644 --- a/crates/ui-egui/src/panels/edit/curve_preset_workflow_tests.rs +++ b/crates/ui-egui/src/panels/edit/curve_preset_workflow_tests.rs @@ -113,7 +113,7 @@ impl PresetFrames { self.settle(); } fn menu_open(&self) -> bool { - use craft::ui::runtime::overlay::{any_open, OpenFilter}; + use craft::ui::runtime::overlay::{OpenFilter, any_open}; any_open(&self.ctx, OpenFilter::Keys) } fn open(&mut self) { @@ -190,9 +190,13 @@ fn secondary_delete_cancel_does_not_leak_to_reopened_or_builtin_preset() { key(&mut f, Key::Escape); assert_ne!(craft::ui::runtime::overlay::top(&f.ctx), Some(context), "Escape must dismiss the context menu"); // The exiting layer can still paint, but must remove its registered row after the fade. - for _ in 0..20 { f.frame(vec![]); } + for _ in 0..20 { + f.frame(vec![]); + } assert!(!f.hits.iter().any(|(name, _)| name.starts_with("curvePresetDelete:"))); - if f.menu_open() { key(&mut f, Key::Escape); } + if f.menu_open() { + key(&mut f, Key::Escape); + } assert!(!f.menu_open()); f.open(); assert!(!f.hits.iter().any(|(name, _)| name.starts_with("curvePresetDelete:"))); @@ -253,7 +257,9 @@ fn escape_dismisses_then_keyboard_reopens_and_applies_focused_preset() { assert!(f.menu_open()); let owner = f.hit("curvePreset:Medium Contrast").id; for _ in 0..3 { - if f.ctx.memory(|m| m.has_focus(owner)) { break; } + if f.ctx.memory(|m| m.has_focus(owner)) { + break; + } key(&mut f, Key::ArrowDown); } assert!(f.ctx.memory(|m| m.has_focus(owner))); @@ -294,7 +300,9 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() { let before = snapshot(&f.app); f.frame(vec![Event::PointerGone]); for _ in 0..40 { - if f.ctx.memory(|m| m.has_focus(opener)) { break; } + if f.ctx.memory(|m| m.has_focus(opener)) { + break; + } key(&mut f, Key::Tab); } assert!(f.ctx.memory(|m| m.has_focus(opener)), "Tab must reach the closed preset opener"); @@ -303,7 +311,9 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() { assert!(f.menu_open()); let row = f.hit("curvePreset:Medium Contrast").id; for _ in 0..3 { - if f.ctx.memory(|m| m.has_focus(row)) { break; } + if f.ctx.memory(|m| m.has_focus(row)) { + break; + } key(&mut f, Key::ArrowDown); } assert!(f.ctx.memory(|m| m.has_focus(row))); @@ -317,7 +327,10 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() { fn tab_direction(f: &mut PresetFrames, reverse: bool) { let modifiers = Modifiers { shift: reverse, ..Modifiers::NONE }; for pressed in [true, false] { - f.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key: Key::Tab, physical_key: Some(Key::Tab), pressed, repeat: false, modifiers }]); + f.frame(vec![ + Event::ModifiersChanged(modifiers), + Event::Key { key: Key::Tab, physical_key: Some(Key::Tab), pressed, repeat: false, modifiers }, + ]); } f.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); f.settle(); @@ -325,7 +338,9 @@ fn tab_direction(f: &mut PresetFrames, reverse: bool) { fn tab_to_opener(f: &mut PresetFrames) -> egui::Id { let owner = f.hit("dropdown:curvePreset").id; for _ in 0..40 { - if f.ctx.memory(|m| m.has_focus(owner)) { return owner; } + if f.ctx.memory(|m| m.has_focus(owner)) { + return owner; + } key(f, Key::Tab); } panic!("Tab did not reach the closed Curve opener"); @@ -354,11 +369,17 @@ fn check_curve_exit(reverse: bool, escape: bool) { assert_eq!(focus, Some(neighbor), "focus must continue to the real closed-menu neighbor"); } #[test] -fn tab_leaves_curve_menu_for_next_control_without_applying() { check_curve_exit(false, false); } +fn tab_leaves_curve_menu_for_next_control_without_applying() { + check_curve_exit(false, false); +} #[test] -fn shift_tab_leaves_curve_menu_for_previous_control_without_applying() { check_curve_exit(true, false); } +fn shift_tab_leaves_curve_menu_for_previous_control_without_applying() { + check_curve_exit(true, false); +} #[test] -fn escape_returns_to_opener_then_tab_reaches_next_control() { check_curve_exit(false, true); } +fn escape_returns_to_opener_then_tab_reaches_next_control() { + check_curve_exit(false, true); +} fn live_preset(mode: u8) { let mut f = PresetFrames::new("master"); diff --git a/crates/ui-egui/src/panels/edit/curve_reset_menu_tests.rs b/crates/ui-egui/src/panels/edit/curve_reset_menu_tests.rs index 1da6bed229..908ca8afce 100644 --- a/crates/ui-egui/src/panels/edit/curve_reset_menu_tests.rs +++ b/crates/ui-egui/src/panels/edit/curve_reset_menu_tests.rs @@ -31,8 +31,14 @@ impl CurveResetFrames { app.run("develop.curve", json!({"channel": channel, "points": [[0.0, 0.05], [0.4, 0.6], [1.0, 0.95]]})).unwrap(); } for (control, value) in [ - ("curve.shadows", 25), ("curve.darks", -20), ("curve.lights", 30), ("curve.highlights", -35), - ("curve.splitShadows", 20), ("curve.splitMid", 45), ("curve.splitHighlights", 80), ("curve.refineSaturation", 42), + ("curve.shadows", 25), + ("curve.darks", -20), + ("curve.lights", 30), + ("curve.highlights", -35), + ("curve.splitShadows", 20), + ("curve.splitMid", 45), + ("curve.splitHighlights", 80), + ("curve.refineSaturation", 42), ] { app.run("develop.set", json!({"control": control, "value": value})).unwrap(); } @@ -64,7 +70,9 @@ impl CurveResetFrames { } fn settle(&mut self) { - for _ in 0..3 { self.frame(vec![]); } + for _ in 0..3 { + self.frame(vec![]); + } } fn rect(&self, id: &str) -> Rect { @@ -140,8 +148,11 @@ fn expected_current(mut before: ToneCurve, channel: &str) -> ToneCurve { #[test] fn sdk_curve_reset_current_keeps_channel_payload_and_restores_full_settings_on_undo() { for (channel, label) in [ - ("parametric", "Reset Parametric Curve"), ("master", "Reset RGB Channel"), - ("red", "Reset Red Channel"), ("green", "Reset Green Channel"), ("blue", "Reset Blue Channel"), + ("parametric", "Reset Parametric Curve"), + ("master", "Reset RGB Channel"), + ("red", "Reset Red Channel"), + ("green", "Reset Green Channel"), + ("blue", "Reset Blue Channel"), ] { let mut f = CurveResetFrames::new(channel); let before = f.settings(); @@ -242,13 +253,19 @@ fn sdk_curve_reset_each_sizing_mode_suppresses_automation_and_commands() { let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { let mut draw = || { let mut builder = egui::UiBuilder::new().max_rect(ui.max_rect()); - if egui_sizing { builder = builder.sizing_pass(); } + if egui_sizing { + builder = builder.sizing_pass(); + } let mut child = ui.new_child(builder); assert_eq!(child.is_sizing_pass(), egui_sizing); assert_eq!(craft::ui::runtime::measure::active(child.ctx()), sdk_measure); curve_reset_menu(&mut f.app, &mut child, "parametric"); }; - if sdk_measure { craft::ui::runtime::measure::run(&ctx, draw); } else { draw(); } + if sdk_measure { + craft::ui::runtime::measure::run(&ctx, draw); + } else { + draw(); + } }); output.textures_delta.clear(); let (rects, hits) = take_registries(&ctx); diff --git a/crates/ui-egui/src/panels/edit/grading.rs b/crates/ui-egui/src/panels/edit/grading.rs index 9a97c20765..c2387fe732 100644 --- a/crates/ui-egui/src/panels/edit/grading.rs +++ b/crates/ui-egui/src/panels/edit/grading.rs @@ -51,9 +51,13 @@ fn eye_owns_pointer(ui: &egui::Ui, key: &str, eye: Rect) -> bool { return false; } let id = egui::Id::unique(("wheelEyePress", key)); - let began = ui.input(|input| input.events.iter().any(|event| matches!(event, - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if eye.contains(*pos) - ))); + let began = ui.input(|input| { + input.events.iter().any(|event| { + matches!(event, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if eye.contains(*pos) + ) + }) + }); let owned = began || ui.data(|data| data.get_temp::(id)).unwrap_or(false); let down = ui.input(|input| input.pointer.primary_down()); ui.data_mut(|data| data.insert_temp(id, owned && down)); @@ -230,7 +234,8 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings if wheel_input && resp.drag_started() { let _ = app.run("develop.beginInteraction", json!({"label": crate::i18n::tr_format!("{label} Grading", label = label)})); } - if wheel_input && (resp.dragged() || resp.clicked()) + if wheel_input + && (resp.dragged() || resp.clicked()) && let Some(q) = pointer { let (hue, sat) = grab.map_or_else(|| wheel_pick(q - c, rad, None), |g| g.pick(q - c, rad)); diff --git a/crates/ui-egui/src/panels/edit/grading_wheel_eye_port_tests.rs b/crates/ui-egui/src/panels/edit/grading_wheel_eye_port_tests.rs index 074df1f027..5953c47e29 100644 --- a/crates/ui-egui/src/panels/edit/grading_wheel_eye_port_tests.rs +++ b/crates/ui-egui/src/panels/edit/grading_wheel_eye_port_tests.rs @@ -82,9 +82,13 @@ impl Frames { self.last_eye_down = Some(hit.id); } // a button-role toggle reports its state as pressed (toggled), not selected - if let Some(node) = - ctx.accesskit_node_builder(hit.id, |n| (n.label().map(str::to_owned), n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), n.description().map(str::to_owned))) - { + if let Some(node) = ctx.accesskit_node_builder(hit.id, |n| { + ( + n.label().map(str::to_owned), + n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), + n.description().map(str::to_owned), + ) + }) { self.nodes.insert(hit.id, node); } } diff --git a/crates/ui-egui/src/panels/edit/histogram.rs b/crates/ui-egui/src/panels/edit/histogram.rs index 89303246f2..a31bb87da4 100644 --- a/crates/ui-egui/src/panels/edit/histogram.rs +++ b/crates/ui-egui/src/panels/edit/histogram.rs @@ -79,7 +79,12 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) // measuring run senses nothing. let live = crate::panels::detail::host::live(ui); let target = live.then(|| { - crate::panels::detail::host::target(ui, ("edit-histogram", id), r, crate::panels::detail::host::Target::new(crate::i18n::tr("Histogram")).drag()) + crate::panels::detail::host::target( + ui, + ("edit-histogram", id), + r, + crate::panels::detail::host::Target::new(crate::i18n::tr("Histogram")).drag(), + ) }); let resp = target.as_ref().map_or_else(|| ui.response(), |target| target.response.clone()); if let Some(target) = &target { @@ -277,29 +282,39 @@ pub(super) fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Phot let shown = device.clone().unwrap_or_else(|| cur.label().to_string()); let mut pick = false; let (_, face_rect) = ui.allocate_space(vec2(170.0, 24.0)); - let face = Button::new(crate::i18n::tr("Profile")).painted(shown).trailing_icon(DisclosureGlyph::dropdown()).id_salt("proof-space").show_at(ui, face_rect); + let face = Button::new(crate::i18n::tr("Profile")) + .painted(shown) + .trailing_icon(DisclosureGlyph::dropdown()) + .id_salt("proof-space") + .show_at(ui, face_rect); let real = !proof_measuring(ui); if real { crate::widgets::register_response("dropdown:proofProfile", face_rect, &face.response); } - Menu::new(crate::i18n::tr("Profile").to_owned()).id_salt("proof-space-menu").values().opened_by(&face.response, Trigger::Click).show(ui, |ui, _| { - let real = !proof_measuring(ui); - for s in OutputSpace::ALL { - let row = MenuItem::new(s.label().to_owned()).id_salt(("proof-space-item", s.label())).entry_checked(device.is_none() && cur == s).show(ui); - if real && row.ran { - let _ = app.run("view.softProof", json!({"space": s})); + Menu::new(crate::i18n::tr("Profile").to_owned()).id_salt("proof-space-menu").values().opened_by(&face.response, Trigger::Click).show( + ui, + |ui, _| { + let real = !proof_measuring(ui); + for s in OutputSpace::ALL { + let row = MenuItem::new(s.label().to_owned()) + .id_salt(("proof-space-item", s.label())) + .entry_checked(device.is_none() && cur == s) + .show(ui); + if real && row.ran { + let _ = app.run("view.softProof", json!({"space": s})); + } } - } - if let Some(n) = &device { - let _ = MenuItem::new(n.clone()).id_salt("proof-space-device").entry_checked(true).show(ui); - } - if app.services.pick_display_profile.is_some() { - let row = MenuItem::new(crate::i18n::tr("Other…").to_owned()).id_salt("proof-space-other").show(ui); - if real && row.ran { - pick = true; + if let Some(n) = &device { + let _ = MenuItem::new(n.clone()).id_salt("proof-space-device").entry_checked(true).show(ui); } - } - }); + if app.services.pick_display_profile.is_some() { + let row = MenuItem::new(crate::i18n::tr("Other…").to_owned()).id_salt("proof-space-other").show(ui); + if real && row.ran { + pick = true; + } + } + }, + ); if pick && let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next()) && let Err(e) = app.run("view.softProof", json!({"profile": path})) diff --git a/crates/ui-egui/src/panels/edit/lens_blur.rs b/crates/ui-egui/src/panels/edit/lens_blur.rs index ff484d88ef..86efb93cec 100644 --- a/crates/ui-egui/src/panels/edit/lens_blur.rs +++ b/crates/ui-egui/src/panels/edit/lens_blur.rs @@ -138,7 +138,14 @@ fn lens_blur_focus(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettin .values() .opened_by(&r, Trigger::Click) .show(ui, |ui, _| { - if lens_blur_focus_item(ui, "lensBlurFocus:subject", crate::i18n::tr("Subject"), chosen.is_none() && auto, enabled, parent_measuring) { + if lens_blur_focus_item( + ui, + "lensBlurFocus:subject", + crate::i18n::tr("Subject"), + chosen.is_none() && auto, + enabled, + parent_measuring, + ) { pick = Some(None); } for m in &d.masks { @@ -149,7 +156,8 @@ fn lens_blur_focus(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettin } }); } - if !lens_blur_measuring(ui) && ui.is_enabled() + if !lens_blur_measuring(ui) + && ui.is_enabled() && let Some(focus) = pick { // "Subject": the estimate again, not a fixed shape @@ -240,8 +248,7 @@ fn focus_shape_row(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_de paint_focus_shape(ui.painter(), out.response.rect.shrink(5.0), shape, colour); // A selected preset is an action when moved, but a genuine no-op while already centered. if interactive && app.session.active() == owner && out.clicked() && (!selected || b.area.is_some()) { - let _ = - app.run("develop.merge", json!({"settings": {"lens_blur": {"shape": name, "area": null}}, "label": "Lens Blur Shape"})); + let _ = app.run("develop.merge", json!({"settings": {"lens_blur": {"shape": name, "area": null}}, "label": "Lens Blur Shape"})); } } }); diff --git a/crates/ui-egui/src/panels/edit/lens_blur_controls_external155_tests.rs b/crates/ui-egui/src/panels/edit/lens_blur_controls_external155_tests.rs index 8dbb9ff604..7590b8966f 100644 --- a/crates/ui-egui/src/panels/edit/lens_blur_controls_external155_tests.rs +++ b/crates/ui-egui/src/panels/edit/lens_blur_controls_external155_tests.rs @@ -52,7 +52,6 @@ fn controls(app: &mut LightcraftApp, ui: &mut Ui, adapter: Adapter) { }); } - /// A popup is open: the previous native candidate's egui popup, or the framework menu that replaced it (a layer of /// the framework's that takes keys). fn popup_open(ctx: &egui::Context) -> bool { diff --git a/crates/ui-egui/src/panels/edit/light_controls.rs b/crates/ui-egui/src/panels/edit/light_controls.rs index 2ba26df422..22ac9b5a0b 100644 --- a/crates/ui-egui/src/panels/edit/light_controls.rs +++ b/crates/ui-egui/src/panels/edit/light_controls.rs @@ -19,9 +19,13 @@ struct Nudges { } fn available(app: &LightcraftApp) -> bool { - app.ui.right == crate::state::RightPanel::Edit && !app.ui.fullscreen - && app.ui.section_open("light") && !app.ui.section_folded("light") - && app.ui.dialog.is_none() && app.ui.name_edit.is_none() && app.recording_shortcut.is_none() + app.ui.right == crate::state::RightPanel::Edit + && !app.ui.fullscreen + && app.ui.section_open("light") + && !app.ui.section_folded("light") + && app.ui.dialog.is_none() + && app.ui.name_edit.is_none() + && app.recording_shortcut.is_none() && !crate::panels::notices::blocks_input(app) && !crate::panels::library_problem::blocks_dialog_input(app) && !crate::updates_ui::blocks_input(app) @@ -138,12 +142,16 @@ pub(super) fn apply_pending(app: &mut LightcraftApp, ui: &egui::Ui) { } ctx.data_mut(|data| data.remove::(key)); for (id, steps) in TONAL.iter().zip(pending.steps) { - if steps == 0 { continue; } + if steps == 0 { + continue; + } let Some(spec) = controls::find(id) else { continue }; let settings = app.session.develop_of(pending.photo).unwrap_or_default(); let before = controls::get(&settings, id).unwrap_or(spec.default); let after = crate::widgets::nudged(spec, before, f64::from(steps)); - if after == before { continue; } + if after == before { + continue; + } let event = EditEvent::set(craft::behavior::Mixed::Same(before), after, spec.label.into(), None); apply(app, ctx, spec, &event); } diff --git a/crates/ui-egui/src/panels/edit/mixer.rs b/crates/ui-egui/src/panels/edit/mixer.rs index d15801c21d..13f8c0573a 100644 --- a/crates/ui-egui/src/panels/edit/mixer.rs +++ b/crates/ui-egui/src/panels/edit/mixer.rs @@ -174,9 +174,8 @@ fn point_color_swatches(ui: &mut egui::Ui, colors: &[Color32], selected: usize) // Measured in an invisible sizing child, then shown at the room it takes in a real run only: the swatches join // their group's arena in a real run alone, never in egui's sizing pass or an SDK measure. let width = ui.available_width().max(1.0); - let child = ui.new_child( - egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, vec2(width, f32::INFINITY))).sizing_pass().invisible(), - ); + let child = ui + .new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, vec2(width, f32::INFINITY))).sizing_pass().invisible()); let size = group().measure_in(&child, craft::behavior::Proposal::Ideal, body); let (rect, _) = ui.allocate_exact_size(vec2(size.x.min(width), size.y.max(24.0)), Sense::hover()); if measuring { @@ -193,10 +192,7 @@ fn point_color_swatches(ui: &mut egui::Ui, colors: &[Color32], selected: usize) fn point_color_visualize(ui: &mut egui::Ui, value: &mut bool) { let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()); let mut local = *value; - let shown = Checkbox::new(Bind::bound(&mut local)) - .id_salt("pointColorVisualize") - .label(crate::i18n::tr("Visualize range").to_owned()) - .show(ui); + let shown = Checkbox::new(Bind::bound(&mut local)).id_salt("pointColorVisualize").label(crate::i18n::tr("Visualize range").to_owned()).show(ui); if measuring { return; } diff --git a/crates/ui-egui/src/panels/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index 6afd3c3a6a..b6833d44d6 100644 --- a/crates/ui-egui/src/panels/edit/sliders.rs +++ b/crates/ui-egui/src/panels/edit/sliders.rs @@ -486,9 +486,7 @@ pub(super) fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize ("▶▶", Icon::ChevronDoubleRight, big), ] { let tooltip = crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label)); - let clicked = { - quick_arrow::show(ui, owner, ctl, txt, icon, tooltip) - }; + let clicked = { quick_arrow::show(ui, owner, ctl, txt, icon, tooltip) }; if clicked && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { let _ = app.run("develop.quickAdjust", json!({"control": ctl, "delta": d})); } diff --git a/crates/ui-egui/src/panels/edit/soft_proof_wave155_tests.rs b/crates/ui-egui/src/panels/edit/soft_proof_wave155_tests.rs index 2213906a33..5399bec543 100644 --- a/crates/ui-egui/src/panels/edit/soft_proof_wave155_tests.rs +++ b/crates/ui-egui/src/panels/edit/soft_proof_wave155_tests.rs @@ -30,7 +30,12 @@ fn fixture() -> (egui::Context, LightcraftApp, PhotoId) { fn frame(ctx: &egui::Context, events: Vec, mut body: impl FnMut(&mut egui::Ui)) -> Registries { let time = ctx.input(|i| i.time) + 1.0 / 60.0; - let input = egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 640.0))), events, ..Default::default() }; + let input = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 640.0))), + events, + ..Default::default() + }; let mut output = ctx.run_ui(input, |root_ui| { crate::widgets::take_registries(root_ui.ctx()); egui::CentralPanel::default().show(root_ui, |ui| body(ui)); @@ -47,7 +52,11 @@ fn at(reg: &Registries, name: &str) -> egui::Pos2 { fn click(ctx: &egui::Context, pos: egui::Pos2, mut body: impl FnMut(&mut egui::Ui)) { frame(ctx, vec![egui::Event::PointerMoved(pos)], &mut body); for pressed in [true, false] { - frame(ctx, vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], &mut body); + frame( + ctx, + vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], + &mut body, + ); } frame(ctx, Vec::new(), body); } @@ -67,11 +76,22 @@ fn wave155_production_device_gate_and_real_sdk_hit_owners() { }); } let record = observed.expect("SDK region recorded"); - for (name, label, role) in [(COPY, "Create Proof Copy", "Button"), (PERCEPTUAL, "Perceptual", "Button"), (RELATIVE, "Relative", "Button"), (PAPER, "Simulate Paper & Ink", "CheckBox")] { + for (name, label, role) in [ + (COPY, "Create Proof Copy", "Button"), + (PERCEPTUAL, "Perceptual", "Button"), + (RELATIVE, "Relative", "Button"), + (PAPER, "Simulate Paper & Ink", "CheckBox"), + ] { let expected = device || name == COPY; assert_eq!(reg.0.iter().filter(|(id, _)| id == name).count(), usize::from(expected), "{name} device={device}"); - if !expected { continue; } - let element = record.elements.iter().find(|e| e.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(label) && f.role == role)).unwrap_or_else(|| panic!("missing SDK {role} {label}")); + if !expected { + continue; + } + let element = record + .elements + .iter() + .find(|e| e.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(label) && f.role == role)) + .unwrap_or_else(|| panic!("missing SDK {role} {label}")); let hit = reg.1.iter().find(|(id, _)| id == name).unwrap().1; assert_eq!(hit.id, element.id, "{name}: automation must own the real component, not a hover probe"); assert!(hit.interact_rect.contains(at(®, name)), "{name}: click center outside hit"); @@ -84,8 +104,16 @@ fn wave155_local_options_select_both_intents_and_toggle_paper_twice() { let (ctx, _app, _) = fixture(); let (mut intent, mut paper) = (ProofIntent::Perceptual, false); let mut reg = (Vec::new(), Vec::new()); - for _ in 0..4 { reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper)); } - for (name, expected_intent, expected_paper) in [(RELATIVE, ProofIntent::Relative, false), (PERCEPTUAL, ProofIntent::Perceptual, false), (PERCEPTUAL, ProofIntent::Perceptual, false), (PAPER, ProofIntent::Perceptual, true), (PAPER, ProofIntent::Perceptual, false)] { + for _ in 0..4 { + reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper)); + } + for (name, expected_intent, expected_paper) in [ + (RELATIVE, ProofIntent::Relative, false), + (PERCEPTUAL, ProofIntent::Perceptual, false), + (PERCEPTUAL, ProofIntent::Perceptual, false), + (PAPER, ProofIntent::Perceptual, true), + (PAPER, ProofIntent::Perceptual, false), + ] { click(&ctx, at(®, name), |ui| proof_options(ui, &mut intent, &mut paper)); assert_eq!((intent, paper), (expected_intent, expected_paper), "{name}"); reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper)); @@ -145,7 +173,9 @@ fn wave155_real_copy_uses_displayed_photo_profile_name_and_success_toast() { let source = app.session.catalog.photo(id).unwrap().clone(); let count = app.session.catalog.photos().count(); let mut reg = (Vec::new(), Vec::new()); - for _ in 0..4 { reg = frame(&ctx, Vec::new(), |ui| soft_proofing(&mut app, ui, id)); } + for _ in 0..4 { + reg = frame(&ctx, Vec::new(), |ui| soft_proofing(&mut app, ui, id)); + } click(&ctx, at(®, COPY), |ui| soft_proofing(&mut app, ui, id)); assert_eq!(app.session.catalog.photos().count(), count + 1, "one activation, one copy"); let copy = app.session.catalog.photos().find(|p| p.copy_of == Some(id)).expect("copy of displayed photo"); @@ -168,7 +198,9 @@ fn wave155_disabled_sdk_controls_ignore_pointer_activation() { }); }; let mut reg = (Vec::new(), Vec::new()); - for _ in 0..4 { reg = frame(&ctx, Vec::new(), &mut draw); } + for _ in 0..4 { + reg = frame(&ctx, Vec::new(), &mut draw); + } for name in [RELATIVE, PAPER, COPY] { click(&ctx, at(®, name), &mut draw); reg = frame(&ctx, Vec::new(), &mut draw); @@ -180,7 +212,9 @@ fn wave155_disabled_sdk_controls_ignore_pointer_activation() { fn proof_copy_after_selection_change_undo_restores_both_original_photos() { let (ctx, mut app, previous) = fixture(); let next = *app.session.selection.ids.iter().find(|id| **id != previous).unwrap(); - for _ in 0..4 { frame(&ctx, vec![], |ui| soft_proofing(&mut app, ui, previous)); } + for _ in 0..4 { + frame(&ctx, vec![], |ui| soft_proofing(&mut app, ui, previous)); + } app.session.execute("library.select", &json!({"ids": [next.0], "active": next.0})).unwrap(); let originals = [previous, next].map(|id| json!(app.session.catalog.photo(id).unwrap())); let before_count = app.session.catalog.photos().count(); diff --git a/crates/ui-egui/src/panels/empty_library_action_port_tests.rs b/crates/ui-egui/src/panels/empty_library_action_port_tests.rs index a7297e3be4..725474e959 100644 --- a/crates/ui-egui/src/panels/empty_library_action_port_tests.rs +++ b/crates/ui-egui/src/panels/empty_library_action_port_tests.rs @@ -6,7 +6,14 @@ use egui_kittest::{Harness, kittest::Queryable}; use std::sync::{Arc, Mutex}; #[derive(Clone, Copy)] -enum Mode { Returns, Owner, Disabled, Measure, Sizing, NoActionGrid } +enum Mode { + Returns, + Owner, + Disabled, + Measure, + Sizing, + NoActionGrid, +} struct Fixture { app: LightcraftApp, @@ -40,7 +47,10 @@ fn fixture(width: f32, mode: Mode, busy: bool) -> Harness<'static, Fixture> { #[cfg(not(target_arch = "wasm32"))] let blocked = busy.then(|| crate::lightroom_import::stall_import(&mut app)); #[cfg(target_arch = "wasm32")] - let blocked = { assert!(!busy); None }; + let blocked = { + assert!(!busy); + None + }; let state = Fixture { app, mode, returned: Vec::new(), asked, _busy: blocked }; let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); @@ -59,11 +69,14 @@ fn fixture(width: f32, mode: Mode, busy: bool) -> Harness<'static, Fixture> { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible()); draw_return(&mut child, state); } - Mode::Disabled => { ui.add_enabled_ui(false, |ui| draw_return(ui, state)); } + Mode::Disabled => { + ui.add_enabled_ui(false, |ui| draw_return(ui, state)); + } Mode::Returns => draw_return(ui, state), } (state.app.widgets, state.app.widget_hits) = crate::widgets::take_registries(ui.ctx()); - }, state, + }, + state, ); h.run_steps(5); h @@ -114,7 +127,9 @@ fn tab_to(h: &mut Harness<'_, Fixture>, id: &str) { let focus = h.ctx.memory(|memory| memory.focused()); let current = focus.and_then(|id| h.ctx.read_response(id)).map(|response| response.rect); path.push((focus, current)); - if current == Some(wanted) { return; } + if current == Some(wanted) { + return; + } key(h, egui::Key::Tab, false); } panic!("natural Tab did not reach {id}: {path:?}"); @@ -135,10 +150,9 @@ fn empty_action_pointer_returns_each_exact_command_once() { #[test] fn empty_action_natural_tab_enter_and_space_return_once() { - for (id, command, activation) in [ - ("button:emptyImportPhotos", "file.addPhotos", egui::Key::Enter), - ("button:emptyImportLightroom", "file.importLightroom", egui::Key::Space), - ] { + for (id, command, activation) in + [("button:emptyImportPhotos", "file.addPhotos", egui::Key::Enter), ("button:emptyImportLightroom", "file.importLightroom", egui::Key::Space)] + { let mut h = fixture(1000.0, Mode::Returns, false); h.event(egui::Event::PointerGone); h.run_steps(2); @@ -204,7 +218,10 @@ fn empty_action_disabled_measure_and_sizing_probes_are_inert() { fn empty_action_actual_owner_availability_labels_and_cancel_picker_once() { let mut h = fixture(1000.0, Mode::Owner, false); assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr("Import Photos…").as_ref()).is_some()); - assert_eq!(h.state().app.widgets.iter().filter(|(id, _)| id == "button:emptyImportLightroom").count(), usize::from(!cfg!(target_arch = "wasm32"))); + assert_eq!( + h.state().app.widgets.iter().filter(|(id, _)| id == "button:emptyImportLightroom").count(), + usize::from(!cfg!(target_arch = "wasm32")) + ); click(&mut h, "button:emptyImportPhotos"); h.run_steps(10); { diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 375f7ffd58..09cdb8dc68 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -229,11 +229,8 @@ fn kind_picker(app: &mut LightcraftApp, ui: &mut egui::Ui) { /// Framework buttons own both pointer and keyboard activation; sizing must not publish targets or run actions. fn filter_action(ui: &mut egui::Ui, widget: &str, label: &str, enabled: bool) -> bool { let enabled = enabled && ui.is_enabled(); - let shown = Button::new(crate::i18n::tr(label).to_owned()) - .id(egui::Id::unique(widget)) - .size(craft::theme::ControlSize::Sm) - .enabled(enabled) - .show(ui); + let shown = + Button::new(crate::i18n::tr(label).to_owned()).id(egui::Id::unique(widget)).size(craft::theme::ControlSize::Sm).enabled(enabled).show(ui); if measuring(ui) { return false; } diff --git a/crates/ui-egui/src/panels/filterbar/tests.rs b/crates/ui-egui/src/panels/filterbar/tests.rs index 9a24974d89..275b5026aa 100644 --- a/crates/ui-egui/src/panels/filterbar/tests.rs +++ b/crates/ui-egui/src/panels/filterbar/tests.rs @@ -189,7 +189,6 @@ fn filter_kind_tab_enter_navigation_preserves_opener_focus() { assert_ne!(h.view.ctx.memory(|memory| memory.focused()), Some(focused), "Tab can leave the opener"); } - #[test] fn filter_kind_pointer_cancel_keeps_the_grid_keyboard_owner() { let mut h = fixture(1900.0); diff --git a/crates/ui-egui/src/panels/filterbar_actions_external155_tests.rs b/crates/ui-egui/src/panels/filterbar_actions_external155_tests.rs index 0f86bb5936..560c4dccf8 100644 --- a/crates/ui-egui/src/panels/filterbar_actions_external155_tests.rs +++ b/crates/ui-egui/src/panels/filterbar_actions_external155_tests.rs @@ -39,12 +39,18 @@ fn pointer(h: &mut Headless, widget: &str, before_release: impl Fn(&Headless)) { h.app.synthetic.push(egui::Event::PointerMoved(at)); h.step(); h.app.synthetic.push(egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE, + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, }); h.step(); before_release(h); h.app.synthetic.push(egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE, + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, }); h.step(); h.step(); @@ -231,10 +237,13 @@ fn filterbar_actions_external155_inherited_disabled_button_keeps_target_but_cann let mut at = egui::Pos2::ZERO; for frame in 0..5 { let events = if frame == 2 || frame == 3 { - vec![egui::Event::PointerMoved(at), egui::Event::PointerButton { - pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE, - }] - } else { vec![] }; + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE }, + ] + } else { + vec![] + }; let raw = HeadlessView::raw_input(egui::vec2(500.0, 200.0), 1.0, frame as f64 / 60.0, events); view.run(raw, |ui| { crate::widgets::take_registries(ui.ctx()); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 8390566eb3..251f8bee00 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1,12 +1,12 @@ //! Photo Grid (justified rows) and Square Grid. Virtualized: only visible cells request thumbnails. +#[cfg(test)] +mod folder_header_boundary_flow_tests; #[cfg(test)] mod folder_header_flow_tests; #[cfg(test)] mod folder_header_sdk_flow_tests; #[cfg(test)] -mod folder_header_boundary_flow_tests; -#[cfg(test)] mod header_tests; use std::collections::{HashMap, HashSet}; diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index a01bebc036..781a9336e2 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -3,9 +3,9 @@ //! keyword gives it to the selected photos or takes it away; the arrow shows the photos with it. use craft::ui::buttons::IconButton; -use craft::ui::primitives::IconSpec; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::primitives::IconSpec; use craft::ui::text::TextField; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use lightcraft_catalog::keywords::{KeywordInfo, KeywordNode, same}; @@ -384,7 +384,9 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId ui, ("keyword-list-shortcut", r.path.to_lowercase()), plus, - crate::panels::detail::host::Target::new(crate::i18n::tr("Part of the keyword shortcut")).tooltip(crate::i18n::tr("Part of the keyword shortcut")).hover_only(), + crate::panels::detail::host::Target::new(crate::i18n::tr("Part of the keyword shortcut")) + .tooltip(crate::i18n::tr("Part of the keyword shortcut")) + .hover_only(), ); register(ui, format!("keywordShortcut:{}", r.path), plus); } diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index e6461b8e48..fd93c5a8ce 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -27,21 +27,24 @@ pub fn view_switch(app: &mut LightcraftApp, ui: &mut egui::Ui) { use crate::state::KeywordingView as V; ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0); - for (view, id, label) in - [ + for (view, id, label) in [ (V::Enter, "enter", "Enter Keywords"), (V::Keywords, "keywords", "Keywords"), (V::Containing, "containing", "& Containing"), (V::WillExport, "willExport", "Will Export"), - ] - { + ] { let key = format!("keywordView:{id}"); // (a toggle button: the chosen view stays pressed, in the framework's own on look) - let shown = craft::ui::buttons::ToggleButton::new(crate::i18n::tr(label).to_owned(), craft::ui::contract::Bind::given(app.ui.keywording_view == view)) - .id_salt(&key) - .size(craft::theme::ControlSize::Sm) - .show(ui); - if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { continue; } + let shown = craft::ui::buttons::ToggleButton::new( + crate::i18n::tr(label).to_owned(), + craft::ui::contract::Bind::given(app.ui.keywording_view == view), + ) + .id_salt(&key) + .size(craft::theme::ControlSize::Sm) + .show(ui); + if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { + continue; + } crate::widgets::register_response(key, shown.response.rect, &shown.response); if ui.is_enabled() && shown.events.committed().is_some() { app.ui.keywording_view = view; @@ -149,7 +152,8 @@ fn chip(ui: &mut egui::Ui, path: &str, name: &str, partial: bool, cross: bool, r // spans the whole chip so that its outline holds the ×, which sits over its end (the later widget takes the press). let body = Rect::from_min_max(rect.min, pos2(rect.right() - CROSS_W, rect.bottom())); let end = Rect::from_min_max(pos2(rect.right() - CROSS_W, rect.top()), rect.max); - let mut name = Button::new(full.clone()).painted(shown).id(id).size(craft::theme::ControlSize::Sm).align(HAlign::Start).tooltip(tip).show_at(ui, rect); + let mut name = + Button::new(full.clone()).painted(shown).id(id).size(craft::theme::ControlSize::Sm).align(HAlign::Start).tooltip(tip).show_at(ui, rect); // (the name answers as the part of the chip that is not the ×) name.response.rect = body; name.response.interact_rect = name.response.interact_rect.intersect(body); @@ -278,9 +282,7 @@ fn chip_acts(app: &mut LightcraftApp, ui: &mut egui::Ui, c: &Chip, drawn: Drawn) return; } let c = c.clone(); - Menu::context(crate::i18n::tr("Keyword"), &drawn.body) - .id_salt(("keyword-chip-menu", c.path.to_lowercase())) - .show(ui, |ui, _| menu(app, ui, &c)); + Menu::context(crate::i18n::tr("Keyword"), &drawn.body).id_salt(("keyword-chip-menu", c.path.to_lowercase())).show(ui, |ui, _| menu(app, ui, &c)); } /// When a list is shortened, only this many chips are measured for it: more than the lines it @@ -358,7 +360,10 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sel } Line::Fewer => { ui.add_space(6.0); - let shown = Button::new(crate::i18n::tr("Show fewer")).id(egui::Id::unique(("keyword-chips-fewer", selection))).size(craft::theme::ControlSize::Sm).show(ui); + let shown = Button::new(crate::i18n::tr("Show fewer")) + .id(egui::Id::unique(("keyword-chips-fewer", selection))) + .size(craft::theme::ControlSize::Sm) + .show(ui); if !measuring(ui) { crate::widgets::register_response("keywordChipsFewer", shown.response.rect, &shown.response); if ui.is_enabled() && shown.clicked() { @@ -546,12 +551,8 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at let (r, _) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover()); let shown_name = chip_label(name, false, width - 16.0, |s| ui.painter().layout_no_wrap(s.to_string(), t.font(13.0), t.text).size().x); let text = if place.is_empty() { shown_name } else { format!("{shown_name} · {}", place.replace(SEP, " › ")) }; - let mut button = Button::new(said.to_owned()) - .painted(text) - .id(id) - .variant(craft::theme::Variant::GHOST) - .align(HAlign::Start) - .selected(lit); + let mut button = + Button::new(said.to_owned()).painted(text).id(id).variant(craft::theme::Variant::GHOST).align(HAlign::Start).selected(lit); if let Some(tip) = tip { button = button.tooltip(tip); } diff --git a/crates/ui-egui/src/panels/keywording/add.rs b/crates/ui-egui/src/panels/keywording/add.rs index 5699451e44..897416e900 100644 --- a/crates/ui-egui/src/panels/keywording/add.rs +++ b/crates/ui-egui/src/panels/keywording/add.rs @@ -49,7 +49,6 @@ fn focused(ctx: &egui::Context, field: egui::Id) -> bool { craft::ui::runtime::focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == field) } - /// The painter is a real sibling SDK stop, so Tab can leave the add field's typing run. /// Its text remains an app preference; only Enter asks the existing Paint command to run. pub(crate) fn painter_field(ui: &mut egui::Ui, text: &mut String) -> bool { diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index f356ffa5e2..62336d1569 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -1,8 +1,6 @@ use std::collections::HashMap; -use super::rows::{ - AlbumDrag, MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, submenu, tree_open, -}; +use super::rows::{AlbumDrag, MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, submenu, tree_open}; use super::{Album, AlbumId, Align2, LibrarySource, LightcraftApp, Rect, Tokens, json, pos2, register, vec2}; /// How far each level of the albums' tree steps in, for the line that shows where a dragged album @@ -267,10 +265,9 @@ fn import_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, a: &Album) { app.toast(ui.ctx(), e); } }; - for (label, command, widget) in [ - ("Import Photos…", "file.addPhotos", "button:albumImportPhotos"), - ("Import from Folder…", "file.addFolder", "button:albumImportFolder"), - ] { + for (label, command, widget) in + [("Import Photos…", "file.addPhotos", "button:albumImportPhotos"), ("Import from Folder…", "file.addFolder", "button:albumImportFolder")] + { if entry("import", crate::i18n::tr(label)).widget(widget).show(ui) { run(app, ui, command, json!({"album": a.id.0})); } diff --git a/crates/ui-egui/src/panels/left/date_filter_flow_tests.rs b/crates/ui-egui/src/panels/left/date_filter_flow_tests.rs index 819de3e60d..1d5842447b 100644 --- a/crates/ui-egui/src/panels/left/date_filter_flow_tests.rs +++ b/crates/ui-egui/src/panels/left/date_filter_flow_tests.rs @@ -659,7 +659,12 @@ fn date_actual_section_has_supported_list_and_identity_keyed_tree_row_owners() { .filter(|element| !element.facts.as_ref().is_some_and(|facts| facts.name.as_deref() == Some("By Date"))) .collect::>(); assert_eq!(rows.len(), 5, "two roots and their three actual months; trace={:#?}", f.trace); - assert_eq!(rows.iter().filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref().is_some_and(|n| n.starts_with("March")))).count(), 2); + assert_eq!( + rows.iter() + .filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref().is_some_and(|n| n.starts_with("March")))) + .count(), + 2 + ); let root = lists[0]; let root_facts = root.facts.as_ref().expect("real collection root facts"); assert!(!root_facts.disabled && root_facts.interactive, "enabled actionable collection root: {root:#?}"); diff --git a/crates/ui-egui/src/panels/left/dates.rs b/crates/ui-egui/src/panels/left/dates.rs index 26fef61240..1548d6c3c6 100644 --- a/crates/ui-egui/src/panels/left/dates.rs +++ b/crates/ui-egui/src/panels/left/dates.rs @@ -1,8 +1,6 @@ use super::rows::tree_open; use super::{Icon, LibrarySource, LightcraftApp, json}; - - /// By Date and Keywords count every photo in the library, so choosing a row shows those photos /// from All Photos, not from whatever album or folder happened to be open, where they could be /// missing (issue #341). Only when choosing (`on`), not when clearing the row again. diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 38a0246ac3..168b162b44 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -15,7 +15,14 @@ struct Meta<'a> { } /// The rows of `nodes` and, for the open ones, of the folders inside them. -fn flatten<'a>(app: &LightcraftApp, ui: &egui::Ui, nodes: &'a [FolderNode], depth: usize, rows: &mut Vec, meta: &mut HashMap>) { +fn flatten<'a>( + app: &LightcraftApp, + ui: &egui::Ui, + nodes: &'a [FolderNode], + depth: usize, + rows: &mut Vec, + meta: &mut HashMap>, +) { for n in nodes { let key = lightcraft_catalog::query::folder_key(&n.path); let open_id = egui::Id::unique(("libfolder-open", key)); @@ -145,7 +152,6 @@ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'a /// can be reached. const SPRING_OPEN_SECONDS: f64 = 0.7; - /// A Folders row while photos are dragged from the grid: a release moves their files there on /// disk (`photo.moveToFolder`, one undo step). The row lights up and the dragged label says where /// they will go, as the same gesture onto an album only adds them to it. Held over a closed row, @@ -306,7 +312,6 @@ fn locate_missing_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNod } } - /// The node Synchronize Folder… of a Local folder `path` works on, with the name its dialog shows: /// the Folders row for that very folder, else (a folder above rows) the folder itself, as a folder /// holding other folders. `None` when no library photo lies in `path` or inside it. Reads the @@ -352,7 +357,6 @@ fn can_move_folder(app: &LightcraftApp) -> Result<(), String> { Ok(()) } - /// Move Folder To… of a folder row (widget `folderMoveTo`): asks for the destination through the /// shared folder dialog, off the UI thread where the host has one (issue #3140: a dialog on the UI /// thread froze the window); `folder.move` then runs when it closes ([`crate::pick::poll`]). diff --git a/crates/ui-egui/src/panels/left/local.rs b/crates/ui-egui/src/panels/left/local.rs index 1da6dd40d7..9f27470fcc 100644 --- a/crates/ui-egui/src/panels/left/local.rs +++ b/crates/ui-egui/src/panels/left/local.rs @@ -1,9 +1,7 @@ use std::collections::HashMap; use super::folders::{library_node_for, move_folder_item, reveal_item, synchronize_item}; -use super::rows::{ - MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, tree_open, -}; +use super::rows::{MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, tree_open}; use super::{LibrarySource, LightcraftApp, SidebarSection, json}; /// Local's folders as they stand this frame, and the folder being browsed among them. diff --git a/crates/ui-egui/src/panels/left/rows.rs b/crates/ui-egui/src/panels/left/rows.rs index e8ad58a7bb..73bfe94734 100644 --- a/crates/ui-egui/src/panels/left/rows.rs +++ b/crates/ui-egui/src/panels/left/rows.rs @@ -529,7 +529,17 @@ pub(super) struct SideSpec<'a> { impl<'a> SideSpec<'a> { pub(super) fn new(salt: &'a str, name: &'a str, show_counts: bool) -> Self { - SideSpec { salt, name, selected: None, show_counts, tree: true, build_all: false, focus_on_press: true, section_drag: None, album_drag: false } + SideSpec { + salt, + name, + selected: None, + show_counts, + tree: true, + build_all: false, + focus_on_press: true, + section_drag: None, + album_drag: false, + } } pub(super) fn selected(mut self, key: Option<&'a str>) -> Self { diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index 2b41f16b5e..637f6dc44a 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -2,9 +2,7 @@ use craft::ui::contract::{Props as _, ShowContainer as _, Trigger}; use craft::ui::menu::Menu; use super::albums::top_level_drop_target; -use super::rows::{ - AlbumDrag, MenuAt, ROW_HEIGHT, SectionDrag, SideEvent, SideRow, SideSpec, entry, host_menu, measuring, rule, side_list, -}; +use super::rows::{AlbumDrag, MenuAt, ROW_HEIGHT, SectionDrag, SideEvent, SideRow, SideSpec, entry, host_menu, measuring, rule, side_list}; use super::{Icon, LightcraftApp, Rect, SidebarSection, Tokens, icon_button, json, pos2, register, vec2}; /// Space above a section's header. @@ -253,7 +251,8 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe .unregistered(); let salt = format!("section-{widget}-{id}"); let mut header = ui.new_child(egui::UiBuilder::new().max_rect(list)); - let out = side_list(&mut header, SideSpec::new(&salt, crate::i18n::tr("Sidebar section"), false).keep_focus().section_drag(section, pinned), vec![row]); + let out = + side_list(&mut header, SideSpec::new(&salt, crate::i18n::tr("Sidebar section"), false).keep_focus().section_drag(section, pinned), vec![row]); let live = !measuring(ui) && ui.is_enabled(); if live { register(ui, format!("{widget}:{id}"), r); @@ -375,7 +374,8 @@ pub(super) fn sections_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, on: Opti rule(ui); } for s in app.ui.sidebar.sections().iter().filter(|s| s.id.available()) { - let shown = entry("sidebar-section", crate::i18n::tr(s.id.title())).checked(!s.hidden).widget(format!("sidebarMenu:section:{}", s.id.id())).show(ui); + let shown = + entry("sidebar-section", crate::i18n::tr(s.id.title())).checked(!s.hidden).widget(format!("sidebarMenu:section:{}", s.id.id())).show(ui); if shown { run = Some(("view.sidebarSection", json!({"section": s.id.id(), "show": s.hidden}))); } @@ -425,7 +425,12 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { pub(super) fn sidebar_title(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (_, hr) = ui.allocate_space(vec2(ui.available_width(), TITLE_HEIGHT)); let library = crate::panels::settings::open_library_name(app); - let mut row = SideRow::new("sidebarTitle", "folder", crate::i18n::tr("My Photos")).no_icon().strong().role(craft::ui::style::TypeRole::Title).unregistered().detail(library.clone()); + let mut row = SideRow::new("sidebarTitle", "folder", crate::i18n::tr("My Photos")) + .no_icon() + .strong() + .role(craft::ui::style::TypeRole::Title) + .unregistered() + .detail(library.clone()); if library.is_some() && let Some(l) = app.session.library.as_ref() { diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rs index fd30eb5219..b18ed1459a 100644 --- a/crates/ui-egui/src/panels/library_problem.rs +++ b/crates/ui-egui/src/panels/library_problem.rs @@ -256,7 +256,9 @@ pub(crate) fn capture_completion(app: &LightcraftApp) -> LibraryCompletion { } pub(crate) fn apply_completion(app: &mut LightcraftApp, completion: LibraryCompletion) { let LibraryCompletion(barrier, visible, absent) = completion; - if visible_mode(app) != visible || app.library_problem.as_ref().is_none_or(|p| p.dismissed) != absent { return; } + if visible_mode(app) != visible || app.library_problem.as_ref().is_none_or(|p| p.dismissed) != absent { + return; + } app.library_window_input = barrier; if let Some(mode) = visible { if app.library_window_input.drawn == Some(mode) && (!app.library_window_input.transition || app.library_window_input.shielded) { @@ -1083,41 +1085,43 @@ fn blocking_window( let mut shown = None; // The dialog mounts its own modal layer; this area only gives it a parent `Ui`. // Above the dialog it covers on the dialog stack, below a prompt. - craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_LIBRARY, window_id(id), || crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| { - let output = Dialog::new(crate::i18n::tr(title).to_owned()) - .id(window_id(id)) - .opened(Bind::given(true)) - .closable(false) - .backdrop(Backdrop::Scrim) - .footer(|ui, _| footer(ui)) - .show(ui, |ui, _| { - // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame - ui.set_width(width); - ui.spacing_mut().item_spacing.y = 8.0; - // The framework sizes the window from a measuring run of the body, where the list's scroll area and - // its rows (host targets only in a real pass) come out shorter: reserve the height the real body - // took, so the footer's buttons sit below the last row instead of over it. - let height_id = window_id(id).with("body-height"); - let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); - let top = ui.cursor().top(); - if let Some(height) = ui.ctx().data(|d| d.get_temp::(height_id)) { - ui.set_min_height(height); - } - body(ui); - if real { - // where the content ends (the cursor, which the reserved height does not move), so it can shrink - let height = (ui.cursor().top() - ui.spacing().item_spacing.y - top).max(0.0); - if ui.ctx().data(|d| d.get_temp::(height_id)).is_none_or(|kept| (kept - height).abs() > 0.5) { - ui.ctx().data_mut(|d| d.insert_temp(height_id, height)); - ui.ctx().request_repaint(); + craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_LIBRARY, window_id(id), || { + crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| { + let output = Dialog::new(crate::i18n::tr(title).to_owned()) + .id(window_id(id)) + .opened(Bind::given(true)) + .closable(false) + .backdrop(Backdrop::Scrim) + .footer(|ui, _| footer(ui)) + .show(ui, |ui, _| { + // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame + ui.set_width(width); + ui.spacing_mut().item_spacing.y = 8.0; + // The framework sizes the window from a measuring run of the body, where the list's scroll area and + // its rows (host targets only in a real pass) come out shorter: reserve the height the real body + // took, so the footer's buttons sit below the last row instead of over it. + let height_id = window_id(id).with("body-height"); + let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); + let top = ui.cursor().top(); + if let Some(height) = ui.ctx().data(|d| d.get_temp::(height_id)) { + ui.set_min_height(height); } - } - }) - .output; - if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ctx) { - shown = Some((output.closed, output.response)); - } - })); + body(ui); + if real { + // where the content ends (the cursor, which the reserved height does not move), so it can shrink + let height = (ui.cursor().top() - ui.spacing().item_spacing.y - top).max(0.0); + if ui.ctx().data(|d| d.get_temp::(height_id)).is_none_or(|kept| (kept - height).abs() > 0.5) { + ui.ctx().data_mut(|d| d.insert_temp(height_id, height)); + ui.ctx().request_repaint(); + } + } + }) + .output; + if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ctx) { + shown = Some((output.closed, output.response)); + } + }) + }); shown } @@ -1401,7 +1405,8 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { .color(t.canvas), ); register(ui, "indicator:temporarySession", r.rect); - let b = Button::new(crate::i18n::tr("Open Library…").to_owned()).id_salt("libraryReopen").size(craft::theme::ControlSize::Sm).show(ui); + let b = + Button::new(crate::i18n::tr("Open Library…").to_owned()).id_salt("libraryReopen").size(craft::theme::ControlSize::Sm).show(ui); if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { crate::widgets::register_response("button:libraryReopen", b.response.rect, &b.response); reopen = b.clicked() || crate::widgets::same_pass_click(&b.response); @@ -1432,7 +1437,8 @@ mod completion_tests { app.library_window_input.drawn = Some(super::WindowMode::Error); app.library_window_input.shielded = true; app.capture_ui_completion(ui.ctx()); - }).drop_without_applying_deltas(); + }) + .drop_without_applying_deltas(); assert!(app.library_window_input.transition); app.library_window_input.drawn = None; app.drain_ui_completions(&ctx); diff --git a/crates/ui-egui/src/panels/mask_component_actions_flow_tests.rs b/crates/ui-egui/src/panels/mask_component_actions_flow_tests.rs index af033bc9e4..5445aacd09 100644 --- a/crates/ui-egui/src/panels/mask_component_actions_flow_tests.rs +++ b/crates/ui-egui/src/panels/mask_component_actions_flow_tests.rs @@ -432,7 +432,6 @@ fn component_parent_disabled_measurement_and_sizing_refuse_actions_without_repla } } - /// Narrow first step: run only this selector before repeating the full eight journeys. #[test] fn component_parent_both_openers_binding_discriminator_and_shifted_owner_safety() { diff --git a/crates/ui-egui/src/panels/mask_controls.rs b/crates/ui-egui/src/panels/mask_controls.rs index 1fda33a938..44915f236c 100644 --- a/crates/ui-egui/src/panels/mask_controls.rs +++ b/crates/ui-egui/src/panels/mask_controls.rs @@ -81,10 +81,8 @@ impl Component for MaskHit { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let plate = if cx.response.hovered() { self.fill.hover.or(self.fill.rest) } else { self.fill.rest }; - let shapes: Vec = plate - .map(|color| Shape::rect_filled(cx.rect, self.fill.radius, color.gamma_multiply(self.opacity))) - .into_iter() - .collect(); + let shapes: Vec = + plate.map(|color| Shape::rect_filled(cx.rect, self.fill.radius, color.gamma_multiply(self.opacity))).into_iter().collect(); ui.reserve_slot(cx.visible).extend(&cx.response.ctx, shapes); } @@ -180,7 +178,17 @@ pub(in crate::panels) struct Hit<'a> { impl<'a> Hit<'a> { /// A control registered for automation as `widget`, named `label` for a screen reader. pub fn new(widget: &'a str, label: impl Into) -> Self { - Self { widget, label: label.into(), fill: Fill::NONE, selected: false, drag: false, pointer_only: false, enabled: true, visual: None, id: None } + Self { + widget, + label: label.into(), + fill: Fill::NONE, + selected: false, + drag: false, + pointer_only: false, + enabled: true, + visual: None, + id: None, + } } pub fn fill(mut self, fill: Fill) -> Self { @@ -226,7 +234,15 @@ impl<'a> Hit<'a> { pub fn show_at(self, ui: &mut Ui, rect: Rect) -> HitOutput { let t = Tokens::get(ui.ctx()); - let hit = MaskHit { common: Common::new(), accent: t.accent, fill: self.fill, selected: self.selected, drag: self.drag, pointer_only: self.pointer_only, opacity: ui.opacity() }; + let hit = MaskHit { + common: Common::new(), + accent: t.accent, + fill: self.fill, + selected: self.selected, + drag: self.drag, + pointer_only: self.pointer_only, + opacity: ui.opacity(), + }; let enabled = self.enabled && ui.is_enabled(); let shown = hit.label(self.label).id(self.id.unwrap_or_else(|| egui::Id::unique(self.widget))).enabled(enabled).show_at(ui, rect); if !measuring(ui) { diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index ca02455817..ff068fabbc 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -260,10 +260,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option ui.set_max_width(320.0); let mut st: MenuState = ui.data(|d| d.get_temp(state_id())).unwrap_or_default(); let before = st.search.clone(); - let r = crate::text_field::TextField::singleline(SEARCH, &mut st.search) - .hint(crate::i18n::tr("Search effects")) - .width(f32::INFINITY) - .show(ui); + let r = crate::text_field::TextField::singleline(SEARCH, &mut st.search).hint(crate::i18n::tr("Search effects")).width(f32::INFINITY).show(ui); // the search field takes the keyboard when the menu opens, in a live pass: a measuring run moves nothing if !measuring(ui) && !st.focused { crate::text_field::focus_id(ui.ctx(), r.response.id); @@ -312,9 +309,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option ui.painter().rect_filled(rect, 3.0, t.hover); } // (rows scrolled out of view can't be clicked) - let hit = ui - .is_rect_visible(rect) - .then(|| Hit::new(widget, display_name(name)).fill(Fill::on_hover(t.hover, 3.0)).show_at(ui, rect)); + let hit = ui.is_rect_visible(rect).then(|| Hit::new(widget, display_name(name)).fill(Fill::on_hover(t.hover, 3.0)).show_at(ui, rect)); if current == Some(name.as_str()) { ui.painter().text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, "✓", t.font(12.0), t.accent); } @@ -841,7 +836,6 @@ pub fn manage_body( } ui.add(egui::Label::new(egui::RichText::new(info).color(t.text_dim).size(11.0)).truncate()); }); - } } }); diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index bca086b202..06293d5978 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -290,7 +290,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let plus = text_button(ui, &format!("maskPlus:{}", m.id), "+", false).on_hover_text(crate::i18n::tr("Add to this mask")); opener_menu(ui, &plus, ("maskPlus", m.id), "Add to this mask", |ui| component_menu(app, ui, "add", ("maskPlus", m.id))); let minus = text_button(ui, &format!("maskMinus:{}", m.id), "−", false).on_hover_text(crate::i18n::tr("Subtract from this mask")); - opener_menu(ui, &minus, ("maskMinus", m.id), "Subtract from this mask", |ui| component_menu(app, ui, "subtract", ("maskMinus", m.id))); + opener_menu(ui, &minus, ("maskMinus", m.id), "Subtract from this mask", |ui| { + component_menu(app, ui, "subtract", ("maskMinus", m.id)) + }); }); describe_field(app, ui, false); } @@ -804,7 +806,6 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { let _ = app.run("view.maskOverlayMode", json!({"mode": mode})); } } - }); let colored = matches!(view, MaskView::Color | MaskView::ColorOnBw); if colored { @@ -849,8 +850,8 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { let label_rect = Rect::from_min_size(pos2(row.left() + 24.0, row.top() + 4.0), vec2(w - 46.0, 18.0)); let track_rect = Rect::from_min_max(pos2(row.left() + 24.0, row.top() + 22.0), pos2(row.right() - 22.0, row.top() + 40.0)); let value_rect = Rect::from_min_max(pos2(label_rect.right() - 64.0, label_rect.top()), label_rect.max); - // the reset hit area is the caption: the value field over the end of the row keeps its own presses - let label_hit = Rect::from_min_max(label_rect.min, pos2(value_rect.left(), label_rect.bottom())); + // the reset hit area is the caption: the value field over the end of the row keeps its own presses + let label_hit = Rect::from_min_max(label_rect.min, pos2(value_rect.left(), label_rect.bottom())); let id = ui.scope_id().with(spec.id); let mut value = app.ui.mask_overlay_opacity as f64; let label = Hit::new("maskOverlayOpacityLabel", crate::i18n::tr_format!("Reset {name}", name = crate::i18n::tr("Opacity"))) @@ -1294,7 +1295,6 @@ impl ComponentMenuTarget { } } - enum ComponentRowAction { Command(serde_json::Value), Rename, @@ -1438,7 +1438,9 @@ fn component_row_menu( } // Keep the existing component-creation menus and their model/download policy unchanged. for (label, op) in [("Intersect with", "intersect"), ("Subtract", "subtract")] { - Menu::submenu_row_enabled(ui, crate::i18n::tr(label), ui.is_enabled(), |ui, _| component_menu(app, ui, op, ("mask-component-row", op, target.key()))); + Menu::submenu_row_enabled(ui, crate::i18n::tr(label), ui.is_enabled(), |ui, _| { + component_menu(app, ui, op, ("mask-component-row", op, target.key())) + }); } Divider::horizontal().show(ui); if component_action(ui, target, "rename", crate::i18n::tr("Rename…"), targets) { @@ -1455,7 +1457,6 @@ fn component_row_menu( action } - /// Whether the SAM 3 model is missing in a build that could use it: then the download is /// offered (with `then` to start afterwards) instead of starting an AI mask. fn needs_model(app: &mut LightcraftApp, kind: &str, op: &str) -> bool { @@ -1604,7 +1605,13 @@ fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) { /// The menu a button opens: the framework's, opened by the button's own activation (the pointer, a long /// press and the keyboard alike) and closed by Escape, a click away or a pick. `key` tells this opener's /// menu from the others'. Nothing is drawn while only measuring. -fn opener_menu(ui: &mut egui::Ui, opener: &crate::widgets::TextButtonOutput, key: impl std::hash::Hash + std::fmt::Debug, label: &str, mut body: impl FnMut(&mut egui::Ui)) { +fn opener_menu( + ui: &mut egui::Ui, + opener: &crate::widgets::TextButtonOutput, + key: impl std::hash::Hash + std::fmt::Debug, + label: &str, + mut body: impl FnMut(&mut egui::Ui), +) { use craft::ui::contract::{Bind, Trigger}; if measuring(ui) { return; @@ -1612,7 +1619,10 @@ fn opener_menu(ui: &mut egui::Ui, opener: &crate::widgets::TextButtonOutput, key // The open state lives here, a pass at a time: a menu whose opener stops drawing closes. let pass = ui.ctx().cumulative_pass_nr(); let open_id = opener.response.id.with("mask-opener-menu-open"); - let mut open = ui.data(|d| d.get_temp::<(u64, bool)>(open_id)).filter(|(last, _)| *last == pass || last.saturating_add(1) == pass).is_some_and(|(_, open)| open); + let mut open = ui + .data(|d| d.get_temp::<(u64, bool)>(open_id)) + .filter(|(last, _)| *last == pass || last.saturating_add(1) == pass) + .is_some_and(|(_, open)| open); // Escape closes it while the keyboard is still on the button, outside the menu: a long press opens it there, and // the button has no use for the Escape the runtime hands it. let opener_id = opener.response.id; diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index e6387f040a..4f5abcab2d 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -374,7 +374,11 @@ pub(crate) fn prompt_allows_event(app: &LightcraftApp, event: &egui::Event) -> b fn prompt_event(event: &egui::Event) -> bool { matches!( event, - egui::Event::Key { .. } | egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone | egui::Event::AccessKitActionRequest(_) + egui::Event::Key { .. } + | egui::Event::PointerMoved(_) + | egui::Event::PointerButton { .. } + | egui::Event::PointerGone + | egui::Event::AccessKitActionRequest(_) ) } @@ -490,13 +494,17 @@ pub(crate) fn shield_pass(app: &LightcraftApp, ctx: &egui::Context) -> bool { /// next host frame. A changed/dismissed prompt is reset here as well, so a queued next notice is /// treated as a new transition. pub(crate) struct PromptCompletion(Option, bool); -pub(crate) fn begin_draw(app: &mut LightcraftApp) { app.notice_input.drawn = false; } +pub(crate) fn begin_draw(app: &mut LightcraftApp) { + app.notice_input.drawn = false; +} pub(crate) fn capture_completion(app: &LightcraftApp) -> PromptCompletion { PromptCompletion(prompt_key(app), app.notice_input.drawn) } pub(crate) fn apply_completion(app: &mut LightcraftApp, completion: PromptCompletion) { let PromptCompletion(current, drawn) = completion; - if prompt_key(app) != current { return; } + if prompt_key(app) != current { + return; + } if app.notice_input.key != current { // A prompt can change during the draw itself (Tasks -> Unsaved, or OK -> next notice). // Leave it in its transition state so the next host frame shields the new prompt too. @@ -525,7 +533,12 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s let mut chosen = input.activate.take().filter(|index| *index <= last); let specs: Vec = buttons .iter() - .map(|(bid, label, _)| crate::dialogs::FooterSpec { label: crate::i18n::tr(label).to_string(), name: format!("button:{bid}"), enabled: true, primary: false }) + .map(|(bid, label, _)| crate::dialogs::FooterSpec { + label: crate::i18n::tr(label).to_string(), + name: format!("button:{bid}"), + enabled: true, + primary: false, + }) .collect(); let picked = Cell::new(None); let shown_layer: Cell> = Cell::new(None); @@ -538,55 +551,57 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s } // The prompt is the top of the dialog stack (`STACK_PROMPT`), above a dialog or library window under it, however // the layers appeared. - craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_PROMPT, egui::Id::unique(id), || crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| { - let output = Dialog::new(crate::i18n::tr(title).to_owned()) - .id(egui::Id::unique(id)) - .opened(Bind::given(true)) - .closable(false) - .backdrop(Backdrop::Scrim) - .footer(|ui, _| { - let (clicked, shown) = crate::dialogs::footer_button_responses(ui, id, &specs); - if clicked.is_some() { - picked.set(clicked); - } - if !shown.is_empty() { - *responses.borrow_mut() = shown; - } - }) - .show(ui, |ui, _| { - // The first layout of a new layer is a sizing pass: finish its real hit areas in this same frame. - if ui.is_sizing_pass() { - ctx.request_discard("notice prompt: settle its buttons before input"); - } else if !craft::ui::runtime::measure::active(ui.ctx()) { - shown_layer.set(Some(ui.layer_id())); - } - // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame - ui.set_width(420.0); - ui.spacing_mut().item_spacing.y = 8.0; - ui.add(egui::Label::new(RichText::new(text).color(t.text_label)).wrap()); - }) - .output; - if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ctx) { - return; - } - if let Some(layer) = shown_layer.get() { - input.layer = Some(layer); - } - let responses = responses.borrow(); - // The real response ids are the AccessKit nodes a screen reader targets. - input.button_ids = specs.iter().zip(responses.iter()).map(|(spec, response)| (spec.name.clone(), response.id)).collect(); - // The safe Cancel/OK starts focused, and takes the focus back while nothing in the prompt has it. - if let Some(safe) = responses.get(cancel_index) - && !responses.iter().any(egui::Response::has_focus) - { - focus::request(ctx, FocusTarget::Id(safe.id)); - } - crate::widgets::announce_dialog(ctx, &output.response, crate::widgets::Modal::Alert); - crate::widgets::describe_dialog(ctx, &output.response, text); - if chosen.is_none() { - chosen = picked.get().filter(|index| *index <= last).or(output.closed.map(|_| cancel_index)); - } - })); + craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_PROMPT, egui::Id::unique(id), || { + crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| { + let output = Dialog::new(crate::i18n::tr(title).to_owned()) + .id(egui::Id::unique(id)) + .opened(Bind::given(true)) + .closable(false) + .backdrop(Backdrop::Scrim) + .footer(|ui, _| { + let (clicked, shown) = crate::dialogs::footer_button_responses(ui, id, &specs); + if clicked.is_some() { + picked.set(clicked); + } + if !shown.is_empty() { + *responses.borrow_mut() = shown; + } + }) + .show(ui, |ui, _| { + // The first layout of a new layer is a sizing pass: finish its real hit areas in this same frame. + if ui.is_sizing_pass() { + ctx.request_discard("notice prompt: settle its buttons before input"); + } else if !craft::ui::runtime::measure::active(ui.ctx()) { + shown_layer.set(Some(ui.layer_id())); + } + // a fixed width: a wrapped label in an auto-sized, centred window would move it every frame + ui.set_width(420.0); + ui.spacing_mut().item_spacing.y = 8.0; + ui.add(egui::Label::new(RichText::new(text).color(t.text_label)).wrap()); + }) + .output; + if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ctx) { + return; + } + if let Some(layer) = shown_layer.get() { + input.layer = Some(layer); + } + let responses = responses.borrow(); + // The real response ids are the AccessKit nodes a screen reader targets. + input.button_ids = specs.iter().zip(responses.iter()).map(|(spec, response)| (spec.name.clone(), response.id)).collect(); + // The safe Cancel/OK starts focused, and takes the focus back while nothing in the prompt has it. + if let Some(safe) = responses.get(cancel_index) + && !responses.iter().any(egui::Response::has_focus) + { + focus::request(ctx, FocusTarget::Id(safe.id)); + } + crate::widgets::announce_dialog(ctx, &output.response, crate::widgets::Modal::Alert); + crate::widgets::describe_dialog(ctx, &output.response, text); + if chosen.is_none() { + chosen = picked.get().filter(|index| *index <= last).or(output.closed.map(|_| cancel_index)); + } + }) + }); if gave_back { // and nothing drawn after the prompt sees it ctx.input_mut(|live| live.events.retain(|event| !prompt_event(event))); @@ -839,7 +854,8 @@ mod tests { super::prepare_ui_pass(&mut app, ui.ctx()); super::show(&mut app, ui.ctx()); app.capture_ui_completion(ui.ctx()); - }).drop_without_applying_deltas(); + }) + .drop_without_applying_deltas(); assert!(!app.notice_input.laid_out); app.drain_ui_completions(&ctx); assert!(app.notice_input.laid_out); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 5e62d1cff9..987ff45c11 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -177,10 +177,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { ui.label(RichText::new(count).color(t.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(PAD - 4.0); - let photos = Button::new(crate::i18n::tr("Show photos")) - .id_salt("person:photos") - .tooltip(crate::i18n::tr("Their photos in the grid")) - .show(ui); + let photos = + Button::new(crate::i18n::tr("Show photos")).id_salt("person:photos").tooltip(crate::i18n::tr("Their photos in the grid")).show(ui); let clicked = photos.clicked(); let response = photos.response; let real_pass = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); @@ -347,17 +345,23 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { } // the × is added after the tile, so it wins where they overlap let x_rect = Rect::from_min_size(pos2(r.right() - 24.0, r.top() + 4.0), vec2(20.0, 20.0)); - let x_resp = more.then(|| { - super::detail::host::target(ui, ("more-face-x", f.photo, f.index), x_rect, host(crate::i18n::tr("Hide this face").to_string())) - }); + let x_resp = + more.then(|| super::detail::host::target(ui, ("more-face-x", f.photo, f.index), x_rect, host(crate::i18n::tr("Hide this face").to_string()))); let above_rect = Rect::from_min_size(pos2(r.left() + 4.0, r.top() + 4.0), vec2(24.0, 20.0)); let above_resp = more.then(|| { - let tip = format!( - "All above: confirm {above_count} faces as {name} (this face and every shown face with equal or higher similarity). Press A." - ); - super::detail::host::target(ui, ("more-face-above", f.photo, f.index), above_rect, host(crate::i18n::tr("Confirm all above").to_string()).tooltip(tip)) + let tip = + format!("All above: confirm {above_count} faces as {name} (this face and every shown face with equal or higher similarity). Press A."); + super::detail::host::target( + ui, + ("more-face-above", f.photo, f.index), + above_rect, + host(crate::i18n::tr("Confirm all above").to_string()).tooltip(tip), + ) }); - if more && real && let Some(above) = above_resp.as_ref() { + if more + && real + && let Some(above) = above_resp.as_ref() + { register_response(format!("more-face-above:{}:{}", f.photo, f.index), above_rect, above); } let hovered = resp.hovered() || x_resp.as_ref().is_some_and(|x| x.hovered()) || above_resp.as_ref().is_some_and(|x| x.hovered()); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index c2cc667d0a..90aed4b6d3 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -124,7 +124,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if !measuring && !ui.is_sizing_pass() { let pass = ui.ctx().cumulative_pass_nr(); let open_id = more.response.id.with("preset-options-open"); - let mut open = ui.data(|data| data.get_temp::<(u64, bool)>(open_id)) + let mut open = ui + .data(|data| data.get_temp::<(u64, bool)>(open_id)) .filter(|(last, _)| *last == pass || last.saturating_add(1) == pass) .is_some_and(|(_, open)| open); // Use the compact SDK button's activation, including keyboard and long release. @@ -171,10 +172,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } let any_user = app.session.presets.iter().any(|p| !p.builtin); - let export = MenuItem::new(crate::i18n::tr("Export User Presets…")) - .id_salt("preset-options-export") - .enabled(any_user) - .show(ui); + let export = MenuItem::new(crate::i18n::tr("Export User Presets…")).id_salt("preset-options-export").enabled(any_user).show(ui); if !measuring { if crate::widgets::on_live_layer(&export.response) { crate::widgets::register_response("presetMenu:export", export.response.rect, &export.response); diff --git a/crates/ui-egui/src/panels/profile_group_headers_external155_tests.rs b/crates/ui-egui/src/panels/profile_group_headers_external155_tests.rs index 3aea6950f9..ee227791b4 100644 --- a/crates/ui-egui/src/panels/profile_group_headers_external155_tests.rs +++ b/crates/ui-egui/src/panels/profile_group_headers_external155_tests.rs @@ -5,12 +5,14 @@ use crate::widgets::{WidgetHit, take_registries}; use egui::{Event, Key, Modifiers, PointerButton}; #[derive(Clone, Copy)] -enum Pass { Real, EguiSizing, SdkSizing } +enum Pass { + Real, + EguiSizing, + SdkSizing, +} // Two groups deliberately share a title; count and source are independent of their display name. -const GROUPS: [(&str, bool, usize); 4] = [ - ("Artistic", false, 3), ("Artistic", true, 1), ("Favorites", false, 2), ("Empty folder", true, 0), -]; +const GROUPS: [(&str, bool, usize); 4] = [("Artistic", false, 3), ("Artistic", true, 1), ("Favorites", false, 2), ("Empty folder", true, 0)]; struct Frames { view: HeadlessView, @@ -54,14 +56,21 @@ impl Frames { }); if let Some(recorded) = recorded { elements = recorded.elements.clone(); - expanded = elements.iter().filter(|e| e.component == "ProfileGroupHeader" && e.part.is_none()) - .map(|e| (e.id, ui.ctx().accesskit_node_builder(e.id, |n| n.is_expanded()).flatten())).collect(); + expanded = elements + .iter() + .filter(|e| e.component == "ProfileGroupHeader" && e.part.is_none()) + .map(|e| (e.id, ui.ctx().accesskit_node_builder(e.id, |n| n.is_expanded()).flatten())) + .collect(); } }; match pass { Pass::Real => draw(ui), - Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().sizing_pass().invisible(), |ui| draw(ui)); } - Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); } + Pass::EguiSizing => { + ui.scope_builder(egui::UiBuilder::new().sizing_pass().invisible(), |ui| draw(ui)); + } + Pass::SdkSizing => { + craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); + } } }); (self.rects, self.hits) = take_registries(&self.view.ctx); @@ -70,11 +79,18 @@ impl Frames { self.bodies = bodies; } - fn settle(&mut self) { for _ in 0..3 { self.frame(vec![], Pass::Real); } } + fn settle(&mut self) { + for _ in 0..3 { + self.frame(vec![], Pass::Real); + } + } fn key(&mut self, key: Key, shift: bool) { let modifiers = Modifiers { shift, ..Modifiers::NONE }; for pressed in [true, false] { - self.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], Pass::Real); + self.frame( + vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], + Pass::Real, + ); } } fn target(&self, key: &str) -> (Rect, WidgetHit) { @@ -92,12 +108,19 @@ impl Frames { } fn click(&mut self, at: egui::Pos2, button: PointerButton) { self.frame(vec![Event::PointerMoved(at)], Pass::Real); - for pressed in [true, false] { self.frame(vec![pointer(at, button, pressed)], Pass::Real); } + for pressed in [true, false] { + self.frame(vec![pointer(at, button, pressed)], Pass::Real); + } } fn snapshot(&self) -> (serde_json::Value, usize, usize, u64, Vec) { let id = self.app.session.catalog.photos().next().unwrap().id; - (serde_json::to_value(self.app.session.develop_of(id).unwrap_or_default().as_ref()).unwrap(), - self.app.session.undo.len(), self.app.session.redo.len(), self.app.session.catalog.revision, self.app.session.profile_favorites.clone()) + ( + serde_json::to_value(self.app.session.develop_of(id).unwrap_or_default().as_ref()).unwrap(), + self.app.session.undo.len(), + self.app.session.redo.len(), + self.app.session.catalog.revision, + self.app.session.profile_favorites.clone(), + ) } } @@ -108,7 +131,9 @@ fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event { #[test] fn profile_groups_default_open_empty_and_same_named_sources_have_single_real_owner() { for width in [280.0, 420.0, 760.0] { - let mut f = Frames::new(); f.width = width; f.settle(); + let mut f = Frames::new(); + f.width = width; + f.settle(); assert_eq!(f.bodies, [true; 4]); assert_eq!(f.rects.len(), 4); assert_eq!(f.hits.len(), 4); @@ -131,7 +156,8 @@ fn profile_groups_default_open_empty_and_same_named_sources_have_single_real_own #[test] fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_independently() { for offset in [22.0, 48.0, 200.0, 370.0] { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let before = f.snapshot(); let (rect, hit) = f.target("profileGroup:Artistic"); let at = if offset == 370.0 { pos2(rect.right() - 22.0, rect.center().y) } else { pos2(rect.left() + offset, rect.center().y) }; @@ -143,12 +169,15 @@ fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_indepen assert_eq!(f.target("profileGroup:Artistic").1.id, hit.id); assert_eq!(f.expanded.iter().find(|(id, _)| *id == hit.id).unwrap().1, Some(false)); let imported = f.target("profileGroup:lut:Artistic").0.center(); - f.click(imported, PointerButton::Primary); f.frame(vec![], Pass::Real); + f.click(imported, PointerButton::Primary); + f.frame(vec![], Pass::Real); assert_eq!(f.bodies, [false, false, true, true]); - f.click(at, PointerButton::Primary); f.frame(vec![], Pass::Real); + f.click(at, PointerButton::Primary); + f.frame(vec![], Pass::Real); assert_eq!(f.bodies, [true, false, true, true]); let empty = f.target("profileGroup:lut:Empty folder").0.center(); - f.click(empty, PointerButton::Primary); f.frame(vec![], Pass::Real); + f.click(empty, PointerButton::Primary); + f.frame(vec![], Pass::Real); assert_eq!(f.state(true, "Empty folder"), Some(false)); assert_eq!(f.bodies, [true, false, true, false]); assert!(f.view.painted_text().iter().any(|s| s == "0")); @@ -158,7 +187,8 @@ fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_indepen #[test] fn profile_groups_unforced_tab_enter_space_and_shift_tab_visit_each_owner_once() { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let before = f.snapshot(); let first = f.target("profileGroup:Artistic").1.id; let second = f.target("profileGroup:lut:Artistic").1.id; @@ -181,7 +211,8 @@ fn profile_groups_unforced_tab_enter_space_and_shift_tab_visit_each_owner_once() #[test] fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let at = f.target("profileGroup:Artistic").0.center(); f.click(at, PointerButton::Secondary); assert_eq!(f.state(false, "Artistic"), None); @@ -190,7 +221,8 @@ fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() { f.frame(vec![Event::PointerMoved(outside)], Pass::Real); f.frame(vec![pointer(outside, PointerButton::Primary, false)], Pass::Real); assert_eq!(f.state(false, "Artistic"), None); - f.enabled = false; f.settle(); + f.enabled = false; + f.settle(); f.click(at, PointerButton::Primary); assert_eq!(f.state(false, "Artistic"), None); } @@ -198,14 +230,17 @@ fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() { #[test] fn profile_groups_both_sizing_modes_publish_nothing_and_cannot_persist_release() { for pass in [Pass::EguiSizing, Pass::SdkSizing] { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let before = f.snapshot(); let at = f.target("profileGroup:Artistic").0.center(); f.frame(vec![Event::PointerMoved(at)], Pass::Real); f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real); f.frame(vec![pointer(at, PointerButton::Primary, false)], pass); assert!(f.rects.is_empty() && f.hits.is_empty()); - for (title, imported, _) in GROUPS { assert_eq!(f.state(imported, title), None); } + for (title, imported, _) in GROUPS { + assert_eq!(f.state(imported, title), None); + } assert_eq!(f.snapshot(), before); // Existing closed state also survives measurement without being reinitialized. f.view.ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("profile-group", true, "Artistic")), false)); @@ -218,24 +253,41 @@ fn profile_groups_both_sizing_modes_publish_nothing_and_cannot_persist_release() #[test] fn profile_groups_translation_count_and_original_face_positions_are_preserved() { struct Restore(crate::i18n::Locale); - impl Drop for Restore { fn drop(&mut self) { crate::i18n::set_language(self.0); } } + impl Drop for Restore { + fn drop(&mut self) { + crate::i18n::set_language(self.0); + } + } let _restore = Restore(crate::i18n::language()); crate::i18n::set_language(crate::i18n::Locale::De); - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let painted = f.view.painted_text(); assert!(painted.iter().any(|s| s == crate::i18n::builtin_label("Favorites", true))); assert!(painted.iter().any(|s| s == "Artistic"), "imported label stays literal"); - for count in ["3", "1", "2", "0"] { assert!(painted.iter().any(|s| s == count)); } + for count in ["3", "1", "2", "0"] { + assert!(painted.iter().any(|s| s == count)); + } fn shapes<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>, paths: &mut Vec<&'a egui::epaint::PathShape>) { match shape { - egui::Shape::Vec(v) => for s in v { shapes(s, texts, paths); }, - egui::Shape::Text(s) => texts.push(s), egui::Shape::Path(s) => paths.push(s), _ => {}, + egui::Shape::Vec(v) => { + for s in v { + shapes(s, texts, paths); + } + } + egui::Shape::Text(s) => texts.push(s), + egui::Shape::Path(s) => paths.push(s), + _ => {} } } - let mut texts = vec![]; let mut paths = vec![]; - for s in &f.view.shapes { shapes(&s.shape, &mut texts, &mut paths); } + let mut texts = vec![]; + let mut paths = vec![]; + for s in &f.view.shapes { + shapes(&s.shape, &mut texts, &mut paths); + } let r = f.target("profileGroup:Artistic").0; assert!(texts.iter().any(|s| s.galley.job.text == "3" && (s.pos.x + s.galley.size().x - (r.right() - 22.0)).abs() < 0.01)); assert!(texts.iter().any(|s| (s.pos.x - (r.left() + 36.0)).abs() < 0.01 && (s.pos.y + s.galley.size().y / 2.0 - r.center().y).abs() < 0.01)); - assert!(paths.iter().any(|s| s.points == vec![pos2(r.left() + 18.0, r.center().y - 2.0), pos2(r.left() + 22.0, r.center().y + 2.0), pos2(r.left() + 26.0, r.center().y - 2.0)])); + assert!(paths.iter().any(|s| s.points + == vec![pos2(r.left() + 18.0, r.center().y - 2.0), pos2(r.left() + 22.0, r.center().y + 2.0), pos2(r.left() + 26.0, r.center().y - 2.0)])); } diff --git a/crates/ui-egui/src/panels/profile_tile_favorite_tests.rs b/crates/ui-egui/src/panels/profile_tile_favorite_tests.rs index 09a37eae4f..81df059ec3 100644 --- a/crates/ui-egui/src/panels/profile_tile_favorite_tests.rs +++ b/crates/ui-egui/src/panels/profile_tile_favorite_tests.rs @@ -7,7 +7,11 @@ use egui::{Event, Key, Modifiers, PointerButton}; const PROFILE: &str = "lc.cine.teal-amber"; const NAME: &str = "Teal & Amber"; #[derive(Clone, Copy)] -enum Pass { Real, EguiSizing, SdkSizing } +enum Pass { + Real, + EguiSizing, + SdkSizing, +} struct Frames { app: LightcraftApp, @@ -28,14 +32,30 @@ struct Frames { impl Frames { fn new() -> Self { let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx); ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx); + ctx.enable_accesskit(); let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); app.install_framework(&ctx); let photo = app.session.visible_cloned()[0]; app.run("library.select", json!({"ids": [photo.0], "active": photo.0})).unwrap(); // Deliberately use a non-default amount to catch accidental star application/reset. app.run("develop.profile", json!({"id": "lc.color", "amount": 37})).unwrap(); - Self { app, ctx, photo, now: 0.0, enabled: true, rects: vec![], hits: vec![], elements: vec![], selections: vec![], visible_focus: vec![], intents: vec![], shapes: vec![], probe_guard: false } + Self { + app, + ctx, + photo, + now: 0.0, + enabled: true, + rects: vec![], + hits: vec![], + elements: vec![], + selections: vec![], + visible_focus: vec![], + intents: vec![], + shapes: vec![], + probe_guard: false, + } } fn frame(&mut self, events: Vec, pass: Pass) { let _ = take_registries(&self.ctx); @@ -63,9 +83,19 @@ impl Frames { visible_focus.push((controls.star.id, controls.star_focus_visible)); for response in [&controls.tile, &controls.star] { // button-role toggles report their state as pressed (toggled), not selected - selections.push((response.id, ui.ctx().accesskit_node_builder(response.id, |n| (n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), n.description().map(str::to_owned))))); + selections.push(( + response.id, + ui.ctx().accesskit_node_builder(response.id, |n| { + ( + n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), + n.description().map(str::to_owned), + ) + }), + )); + } + if controls.intent != ProfileCellIntent::None { + intents.push(controls.intent); } - if controls.intent != ProfileCellIntent::None { intents.push(controls.intent); } profile_cell_apply(app, ui, PROFILE, controls.intent); } if probe_guard { @@ -75,27 +105,42 @@ impl Frames { } }); }); - if let Some(record) = record { elements = record.elements.clone(); } + if let Some(record) = record { + elements = record.elements.clone(); + } }; match pass { Pass::Real => draw(ui), - Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible(), |ui| draw(ui)); } - Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); } + Pass::EguiSizing => { + ui.scope_builder(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible(), |ui| draw(ui)); + } + Pass::SdkSizing => { + craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); + } } }); out.textures_delta.clear(); self.shapes = out.shapes; (self.rects, self.hits) = take_registries(&self.ctx); - self.elements = elements; self.selections = selections; self.visible_focus = visible_focus; self.intents = intents; + self.elements = elements; + self.selections = selections; + self.visible_focus = visible_focus; + self.intents = intents; + } + fn settle(&mut self) { + for _ in 0..3 { + self.frame(vec![], Pass::Real); + } } - fn settle(&mut self) { for _ in 0..3 { self.frame(vec![], Pass::Real); } } fn target(&self, key: &str) -> (Rect, WidgetHit) { assert_eq!(self.rects.iter().filter(|(id, _)| id == key).count(), 1); assert_eq!(self.hits.iter().filter(|(id, _)| id == key).count(), 1); let r = self.rects.iter().find(|(id, _)| id == key).unwrap().1; let hit = self.hits.iter().find(|(id, _)| id == key).unwrap().1; - let element = self.elements.iter().find(|e| e.id == hit.id && e.part.is_none()).expect("locator points at actual SDK component, not a hover probe"); - assert_eq!(element.component, "ProfileCellAction"); assert_eq!(element.rect, r); + let element = + self.elements.iter().find(|e| e.id == hit.id && e.part.is_none()).expect("locator points at actual SDK component, not a hover probe"); + assert_eq!(element.component, "ProfileCellAction"); + assert_eq!(element.rect, r); assert_eq!(hit.interact_rect, r); if self.enabled { assert!(element.stop.is_some()); @@ -114,104 +159,168 @@ impl Frames { fn key(&mut self, key: Key, shift: bool) { let modifiers = Modifiers { shift, ..Modifiers::NONE }; for pressed in [true, false] { - self.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], Pass::Real); + self.frame( + vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], + Pass::Real, + ); } } fn assert_state(&self, owner: egui::Id, on: bool) { - let node = self.selections.iter().find(|(id,_)| *id==owner).expect("current SDK response").1.as_ref().expect("actual AX button node"); + let node = self.selections.iter().find(|(id, _)| *id == owner).expect("current SDK response").1.as_ref().expect("actual AX button node"); // For Button the SDK reports the state as pressed (toggled); only On counts here. The explicit // localized description must remain available in *both* states. - assert_eq!(node.0,on.then_some(true)); - assert_eq!(node.1.as_deref(),Some(crate::i18n::tr(if on {"On"} else {"Off"}))); + assert_eq!(node.0, on.then_some(true)); + assert_eq!(node.1.as_deref(), Some(crate::i18n::tr(if on { "On" } else { "Off" }))); + } + fn settings(&self) -> serde_json::Value { + serde_json::to_value(self.app.session.develop_of(self.photo).unwrap().as_ref()).unwrap() } - fn settings(&self) -> serde_json::Value { serde_json::to_value(self.app.session.develop_of(self.photo).unwrap().as_ref()).unwrap() } fn snapshot(&self) -> serde_json::Value { json!({"settings":self.settings(), "undo":self.app.session.undo.len(), "redo":self.app.session.redo.len(), "revision":self.app.session.catalog.revision, "favorites":self.app.session.profile_favorites, "recent":self.app.session.profile_recent}) } } -fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event { Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE } } -fn tile(tag: &str) -> String { if tag.is_empty() { format!("profileCell:{PROFILE}") } else { format!("profileCell:fav:{PROFILE}") } } -fn star(tag: &str) -> String { if tag.is_empty() { format!("profileStar:{PROFILE}") } else { format!("profileStar:fav:{PROFILE}") } } +fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event { + Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE } +} +fn tile(tag: &str) -> String { + if tag.is_empty() { format!("profileCell:{PROFILE}") } else { format!("profileCell:fav:{PROFILE}") } +} +fn star(tag: &str) -> String { + if tag.is_empty() { format!("profileStar:{PROFILE}") } else { format!("profileStar:fav:{PROFILE}") } +} #[test] fn profile_tile_favorite_four_real_owners_preserve_duplicate_locators_and_geometry() { - let mut f = Frames::new(); let before = f.snapshot(); f.settle(); + let mut f = Frames::new(); + let before = f.snapshot(); + f.settle(); assert_eq!(f.snapshot(), before, "idle controls never apply or favorite"); - assert_eq!(f.rects.len(), 4); assert_eq!(f.hits.len(), 4); + assert_eq!(f.rects.len(), 4); + assert_eq!(f.hits.len(), 4); let mut ids = std::collections::HashSet::new(); for tag in ["", "fav"] { - let (cell, t) = f.target(&tile(tag)); let (s, sh) = f.target(&star(tag)); + let (cell, t) = f.target(&tile(tag)); + let (s, sh) = f.target(&star(tag)); assert!(ids.insert(t.id) && ids.insert(sh.id)); - assert_eq!(cell.size(), vec2(160.0, 144.0)); assert_eq!(s.size(), vec2(20.0, 20.0)); + assert_eq!(cell.size(), vec2(160.0, 144.0)); + assert_eq!(s.size(), vec2(20.0, 20.0)); assert_eq!(s.center(), pos2(cell.right() - 13.0, cell.top() + 13.0)); - f.assert_state(t.id,false); - f.assert_state(sh.id,false); + f.assert_state(t.id, false); + f.assert_state(sh.id, false); } assert_eq!(f.elements.iter().filter(|e| e.component == "ProfileCellAction").count(), 4, "no proxy nodes or extra focus stops"); } #[test] fn profile_tile_favorite_star_pointer_changes_only_favorites_never_applies_or_adds_history() { - let mut f = Frames::new(); f.settle(); - let settings = f.settings(); let undo = f.app.session.undo.len(); let redo = f.app.session.redo.len(); - let revision = f.app.session.catalog.revision; let recent = f.app.session.profile_recent.clone(); - let main_id = f.target(&star("")).1.id; let duplicate_id = f.target(&star("fav")).1.id; + let mut f = Frames::new(); + f.settle(); + let settings = f.settings(); + let undo = f.app.session.undo.len(); + let redo = f.app.session.redo.len(); + let revision = f.app.session.catalog.revision; + let recent = f.app.session.profile_recent.clone(); + let main_id = f.target(&star("")).1.id; + let duplicate_id = f.target(&star("fav")).1.id; f.click(&star("")); assert_eq!(f.intents, [ProfileCellIntent::Favorite], "star overlap must not activate tile too"); - assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); f.settle(); - for owner in [main_id, duplicate_id] { f.assert_state(owner,true); } - f.click(&star("fav")); assert_eq!(f.intents, [ProfileCellIntent::Favorite]); + assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); + f.settle(); + for owner in [main_id, duplicate_id] { + f.assert_state(owner, true); + } + f.click(&star("fav")); + assert_eq!(f.intents, [ProfileCellIntent::Favorite]); assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); - f.settle();for owner in [main_id,duplicate_id] { f.assert_state(owner,false); } - assert_eq!(f.settings(), settings); assert_eq!(f.app.session.undo.len(), undo); assert_eq!(f.app.session.redo.len(), redo); - assert_eq!(f.app.session.catalog.revision, revision); assert_eq!(f.app.session.profile_recent, recent); + f.settle(); + for owner in [main_id, duplicate_id] { + f.assert_state(owner, false); + } + assert_eq!(f.settings(), settings); + assert_eq!(f.app.session.undo.len(), undo); + assert_eq!(f.app.session.redo.len(), redo); + assert_eq!(f.app.session.catalog.revision, revision); + assert_eq!(f.app.session.profile_recent, recent); } #[test] fn profile_tile_favorite_tile_pointer_applies_once_at_100_and_applied_tile_is_noop() { - let mut f = Frames::new(); f.settle(); let undo = f.app.session.undo.len(); + let mut f = Frames::new(); + f.settle(); + let undo = f.app.session.undo.len(); let favorites = f.app.session.profile_favorites.clone(); - f.click(&tile("")); assert_eq!(f.intents, [ProfileCellIntent::Apply]); f.settle(); + f.click(&tile("")); + assert_eq!(f.intents, [ProfileCellIntent::Apply]); + f.settle(); let d = f.app.session.develop_of(f.photo).unwrap(); - assert_eq!(d.profile.id, PROFILE); assert_eq!(d.profile.amount, 100.0); - assert_eq!(f.app.session.undo.len(), undo + 1); assert_eq!(f.app.session.profile_favorites, favorites); - for tag in ["","fav"] { f.assert_state(f.target(&tile(tag)).1.id,true); f.assert_state(f.target(&star(tag)).1.id,false); } + assert_eq!(d.profile.id, PROFILE); + assert_eq!(d.profile.amount, 100.0); + assert_eq!(f.app.session.undo.len(), undo + 1); + assert_eq!(f.app.session.profile_favorites, favorites); + for tag in ["", "fav"] { + f.assert_state(f.target(&tile(tag)).1.id, true); + f.assert_state(f.target(&star(tag)).1.id, false); + } // Already-applied is a no-op even when its amount is not the tile's 100% default. - f.app.run("develop.profile", json!({"id":PROFILE,"amount":61})).unwrap(); f.settle(); - let before = f.snapshot(); f.click(&tile("fav")); - assert!(f.intents.is_empty()); assert_eq!(f.snapshot(), before); - f.click(&star("fav")); assert_eq!(f.intents, [ProfileCellIntent::Favorite]); - assert_eq!(f.settings(), before["settings"]); assert_eq!(f.app.session.undo.len(), before["undo"].as_u64().unwrap() as usize); + f.app.run("develop.profile", json!({"id":PROFILE,"amount":61})).unwrap(); + f.settle(); + let before = f.snapshot(); + f.click(&tile("fav")); + assert!(f.intents.is_empty()); + assert_eq!(f.snapshot(), before); + f.click(&star("fav")); + assert_eq!(f.intents, [ProfileCellIntent::Favorite]); + assert_eq!(f.settings(), before["settings"]); + assert_eq!(f.app.session.undo.len(), before["undo"].as_u64().unwrap() as usize); } #[test] fn profile_tile_favorite_natural_tab_enter_space_visit_separate_tile_and_star_owners() { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let ids = [f.target(&tile("")).1.id, f.target(&star("")).1.id, f.target(&tile("fav")).1.id, f.target(&star("fav")).1.id]; assert_eq!(f.ctx.memory(|m| m.focused()), None); - f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[0])); - f.key(Key::Enter, false); assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.id, PROFILE); - let settings = f.settings(); let undo = f.app.session.undo.len(); - f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[1])); - f.key(Key::Space, false); assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); - assert_eq!(f.settings(), settings); assert_eq!(f.app.session.undo.len(), undo); - f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2])); - f.key(Key::Space, false); assert_eq!(f.app.session.undo.len(), undo, "applied tile keyboard activation is no-op"); - f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[3])); - f.key(Key::Enter, false); assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); - f.key(Key::Tab, true); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2])); + f.key(Key::Tab, false); + assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[0])); + f.key(Key::Enter, false); + assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.id, PROFILE); + let settings = f.settings(); + let undo = f.app.session.undo.len(); + f.key(Key::Tab, false); + assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[1])); + f.key(Key::Space, false); + assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); + assert_eq!(f.settings(), settings); + assert_eq!(f.app.session.undo.len(), undo); + f.key(Key::Tab, false); + assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2])); + f.key(Key::Space, false); + assert_eq!(f.app.session.undo.len(), undo, "applied tile keyboard activation is no-op"); + f.key(Key::Tab, false); + assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[3])); + f.key(Key::Enter, false); + assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); + f.key(Key::Tab, true); + assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2])); } #[test] fn profile_tile_favorite_each_keyboard_activation_key_works_on_each_owner_without_forced_focus() { for key in [Key::Enter, Key::Space] { for favorite in [false, true] { - let mut f = Frames::new(); f.settle(); let undo = f.app.session.undo.len(); - f.key(Key::Tab, false); if favorite { f.key(Key::Tab, false); } - let before = f.settings(); f.key(key, false); + let mut f = Frames::new(); + f.settle(); + let undo = f.app.session.undo.len(); + f.key(Key::Tab, false); if favorite { - assert_eq!(f.settings(), before); assert_eq!(f.app.session.undo.len(), undo); + f.key(Key::Tab, false); + } + let before = f.settings(); + f.key(key, false); + if favorite { + assert_eq!(f.settings(), before); + assert_eq!(f.app.session.undo.len(), undo); assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); } else { assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.amount, 100.0); @@ -225,16 +334,23 @@ fn profile_tile_favorite_each_keyboard_activation_key_works_on_each_owner_withou #[test] fn profile_tile_favorite_secondary_cancelled_and_disabled_owners_do_not_mutate() { for target in [tile(""), star("")] { - let mut f = Frames::new(); f.settle(); let before = f.snapshot(); let at = f.target(&target).0.center(); + let mut f = Frames::new(); + f.settle(); + let before = f.snapshot(); + let at = f.target(&target).0.center(); f.frame(vec![Event::PointerMoved(at)], Pass::Real); - for pressed in [true, false] { f.frame(vec![pointer(at, PointerButton::Secondary, pressed)], Pass::Real); } + for pressed in [true, false] { + f.frame(vec![pointer(at, PointerButton::Secondary, pressed)], Pass::Real); + } assert_eq!(f.snapshot(), before); f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real); let outside = pos2(430.0, 300.0); f.frame(vec![Event::PointerMoved(outside)], Pass::Real); f.frame(vec![pointer(outside, PointerButton::Primary, false)], Pass::Real); assert_eq!(f.snapshot(), before); - f.enabled = false; f.settle(); f.click(&target); + f.enabled = false; + f.settle(); + f.click(&target); assert_eq!(f.snapshot(), before); } } @@ -243,7 +359,10 @@ fn profile_tile_favorite_secondary_cancelled_and_disabled_owners_do_not_mutate() fn profile_tile_favorite_independent_sizing_guards_reject_release_and_explicit_intents() { for pass in [Pass::EguiSizing, Pass::SdkSizing] { for target in [tile(""), star("")] { - let mut f = Frames::new(); f.settle(); let before = f.snapshot(); let at = f.target(&target).0.center(); + let mut f = Frames::new(); + f.settle(); + let before = f.snapshot(); + let at = f.target(&target).0.center(); f.frame(vec![Event::PointerMoved(at)], Pass::Real); f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real); f.probe_guard = true; @@ -256,25 +375,31 @@ fn profile_tile_favorite_independent_sizing_guards_reject_release_and_explicit_i #[test] fn profile_tile_favorite_idle_and_pointer_move_never_dispatch_or_clear_last_profile_hover() { - let mut f = Frames::new(); f.settle(); let before = f.snapshot(); + let mut f = Frames::new(); + f.settle(); + let before = f.snapshot(); let saved = (f.photo, PROFILE.to_string()); f.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("last-profile-hover"), saved.clone())); for key in [tile(""), star(""), tile("fav"), star("fav")] { - let at = f.target(&key).0.center(); f.frame(vec![Event::PointerMoved(at)], Pass::Real); - assert!(f.intents.is_empty()); assert_eq!(f.snapshot(), before); - assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), Some(saved.clone())); + let at = f.target(&key).0.center(); + f.frame(vec![Event::PointerMoved(at)], Pass::Real); + assert!(f.intents.is_empty()); + assert_eq!(f.snapshot(), before); + assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), Some(saved.clone())); } f.click(&star("")); - assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), Some(saved)); + assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), Some(saved)); f.click(&tile("")); - assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), None); + assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), None); } #[test] fn profile_tile_favorite_pointer_idle_stays_hidden_but_keyboard_star_focus_is_visible() { - let mut f = Frames::new(); f.settle(); + let mut f = Frames::new(); + f.settle(); let star_id = f.target(&star("")).1.id; - f.click(&star("")); f.click(&star("")); + f.click(&star("")); + f.click(&star("")); assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); f.frame(vec![Event::PointerMoved(pos2(430.0, 300.0))], Pass::Real); assert_eq!(f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1, false); @@ -288,14 +413,16 @@ fn profile_tile_favorite_pointer_idle_stays_hidden_but_keyboard_star_focus_is_vi let id = f.ctx.memory(|m| m.focused()).expect("Tab focuses a real owner"); assert!(ids.contains(&id) && !path.contains(&id), "unexpected Tab route: {path:?} then {id:?}"); path.push(id); - if id == star_id {break;} + if id == star_id { + break; + } } assert_eq!(path.last(), Some(&star_id), "ordinary, unfavorited star must be reachable: {path:?}"); assert!(f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1); f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2])); assert!(!f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1); - assert_eq!(f.snapshot(),before); + assert_eq!(f.snapshot(), before); } // The real panel is drawn in every frame. Only delivery of thumbnail pixels is omitted: diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index 5551d56efa..5765eaef6e 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -24,7 +24,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { show_with_thumbnail(app, ui, id, paint_thumbnail); } -fn show_with_thumbnail(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, thumbnail: impl Fn(&mut LightcraftApp, &egui::Painter, PhotoId, &DevelopSettings, Rect)) { +fn show_with_thumbnail( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + id: PhotoId, + thumbnail: impl Fn(&mut LightcraftApp, &egui::Painter, PhotoId, &DevelopSettings, Rect), +) { let t = Tokens::get(ui.ctx()); let d = (*app.session.develop_of(id).unwrap_or_default()).clone(); // header: back + title @@ -141,12 +146,12 @@ fn profile_group_header(ui: &mut egui::Ui, title: &str, imported: bool, count: u /// leaf keeps the original face while the public SDK pipeline owns the single hit/focus stop, /// binding, keyboard/AT activation, cancellation and expanded accessibility state. mod group_header { - use std::sync::Arc; + use crate::theme::Tokens; use craft::behavior::{Metrics, Sense}; use craft::ui::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Pointer as _, Props as _, Role}; use craft::ui::style::{ComponentStyle, FocusLook, StyleCx}; use egui::{Color32, Galley, Stroke, Vec2, pos2, vec2}; - use crate::theme::Tokens; + use std::sync::Arc; #[derive(Clone, Debug, PartialEq, ComponentStyle)] pub(super) struct HeaderStyle { @@ -175,11 +180,16 @@ mod group_header { let t = Tokens::get(ui.ctx()); let label = crate::i18n::builtin_label(title, !imported); Self { - common: Common::new(), open, focus: t.accent, + common: Common::new(), + open, + focus: t.accent, label: ui.painter().layout_no_wrap(label.to_string(), t.semibold(13.0), t.text_label), count: ui.painter().layout_no_wrap(count.to_string(), t.font(12.0), t.text_dim), - ink: t.text_label, dim: t.text_dim, opacity: ui.opacity(), - }.label(label.to_string()) + ink: t.text_label, + dim: t.text_dim, + opacity: ui.opacity(), + } + .label(label.to_string()) } } @@ -193,11 +203,19 @@ mod group_header { fn style(_: &StyleCx<'_>, key: ProfileGroupHeaderStyleKey) -> HeaderStyle { HeaderStyle { metrics: Metrics::new(), focus: FocusLook::new(Stroke::new(2.0, key.focus), -2.0) } } - fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { vec2(0.0, 32.0) } - fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS } - fn bind(&mut self) -> Option> { Some(self.open.reborrow()) } + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + vec2(0.0, 32.0) + } + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS + } + fn bind(&mut self) -> Option> { + Some(self.open.reborrow()) + } fn update(&mut self, cx: &mut Cx<'_, Self>) { - if cx.activation().is_some() { cx.set(!cx.value().copied().unwrap_or(true)); } + if cx.activation().is_some() { + cx.set(!cx.value().copied().unwrap_or(true)); + } } fn access(&self, access: &mut craft::ui::contract::Access, cx: &Cx<'_, Self>) { access.expanded(cx.value().copied().unwrap_or(true)); @@ -214,12 +232,18 @@ mod group_header { let label_at = pos2(r.left() + 36.0, r.center().y - self.label.size().y / 2.0); let count_at = pos2(r.right() - 22.0 - self.count.size().x, r.center().y - self.count.size().y / 2.0); let text = |at, galley, color| egui::epaint::TextShape::new(at, galley, color).with_opacity_factor(self.opacity).into(); - ui.reserve_slot(cx.visible).extend(&cx.response.ctx, vec![ - egui::Shape::line(offsets.map(|offset| center + offset).to_vec(), Stroke::new(1.2, self.ink.gamma_multiply(self.opacity))), - text(label_at, Arc::clone(&self.label), self.ink), text(count_at, Arc::clone(&self.count), self.dim), - ]); + ui.reserve_slot(cx.visible).extend( + &cx.response.ctx, + vec![ + egui::Shape::line(offsets.map(|offset| center + offset).to_vec(), Stroke::new(1.2, self.ink.gamma_multiply(self.opacity))), + text(label_at, Arc::clone(&self.label), self.ink), + text(count_at, Arc::clone(&self.count), self.dim), + ], + ); + } + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() } - fn finish(self, cx: Cx<'_, Self>) -> EditResponse { cx.edit_response() } } } @@ -318,37 +342,66 @@ struct ProfileCellControls { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ProfileCellIntent { None, Favorite, Apply } +enum ProfileCellIntent { + None, + Favorite, + Apply, +} #[allow(clippy::too_many_arguments)] -fn profile_cell_controls(ui: &mut egui::Ui, tag: &str, p_id: &str, p_name: &str, cell: Rect, star: Rect, applied: bool, fav: bool) -> ProfileCellControls { +fn profile_cell_controls( + ui: &mut egui::Ui, + tag: &str, + p_id: &str, + p_name: &str, + cell: Rect, + star: Rect, + applied: bool, + fav: bool, +) -> ProfileCellControls { use craft::ui::contract::{Props as _, Show as _}; let tile_key = if tag.is_empty() { format!("profileCell:{p_id}") } else { format!("profileCell:{tag}:{p_id}") }; let star_key = format!("profileStar:{}{}", if tag.is_empty() { "" } else { "fav:" }, p_id); let label = crate::i18n::profile_label(p_id, p_name).to_string(); let tile = cell_action::ProfileCellAction::new(ui) - .id_salt(("profile-tile", tile_key.as_str())).label(label.clone()).description(crate::i18n::tr(if applied { "On" } else { "Off" }).to_string()).selected(applied).show_at(ui, cell); + .id_salt(("profile-tile", tile_key.as_str())) + .label(label.clone()) + .description(crate::i18n::tr(if applied { "On" } else { "Off" }).to_string()) + .selected(applied) + .show_at(ui, cell); let star_out = cell_action::ProfileCellAction::new(ui) .id_salt(("profile-star", star_key.as_str())) - .label(format!("{}: {}", crate::i18n::tr("Favorite"), label)).description(crate::i18n::tr(if fav { "On" } else { "Off" }).to_string()).selected(fav).show_at(ui, star); + .label(format!("{}: {}", crate::i18n::tr("Favorite"), label)) + .description(crate::i18n::tr(if fav { "On" } else { "Off" }).to_string()) + .selected(fav) + .show_at(ui, star); let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); if real { crate::widgets::register_response(tile_key, cell, &tile.response); crate::widgets::register_response(star_key, star, &star_out.response); } // A single command at most, even if an activation source is ever shared by mistake. - let intent = if !real { ProfileCellIntent::None } - else if craft::ui::contract::clicked(&star_out.response) { ProfileCellIntent::Favorite } - else if !applied && craft::ui::contract::clicked(&tile.response) { ProfileCellIntent::Apply } - else { ProfileCellIntent::None }; + let intent = if !real { + ProfileCellIntent::None + } else if craft::ui::contract::clicked(&star_out.response) { + ProfileCellIntent::Favorite + } else if !applied && craft::ui::contract::clicked(&tile.response) { + ProfileCellIntent::Apply + } else { + ProfileCellIntent::None + }; ProfileCellControls { tile: tile.response, star: star_out.response, star_focus_visible: star_out.focus_visible, intent } } /// Shared with in-memory tests: the real command boundary, not a model-mutating focus proxy. fn profile_cell_apply(app: &mut LightcraftApp, ui: &egui::Ui, p_id: &str, intent: ProfileCellIntent) { - if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { return; } + if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { + return; + } match intent { - ProfileCellIntent::Favorite => { let _ = app.run("profile.favorite", json!({"id": p_id})); } + ProfileCellIntent::Favorite => { + let _ = app.run("profile.favorite", json!({"id": p_id})); + } ProfileCellIntent::Apply => { let _ = app.run("develop.profile", json!({"id": p_id, "amount": 100})); ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))); @@ -389,7 +442,9 @@ mod cell_action { } impl Outcome for ActionOutput { type Value = NoValue; - fn response(&self) -> &egui::Response { &self.response } + fn response(&self) -> &egui::Response { + &self.response + } } impl Component for ProfileCellAction { const ROLE: Role = Role::BUTTON; @@ -400,7 +455,9 @@ mod cell_action { fn style(_: &StyleCx<'_>, key: ProfileCellActionStyleKey) -> ActionStyle { ActionStyle { metrics: Metrics::new(), focus: FocusLook::new(Stroke::new(2.0, key.accent), -2.0) } } - fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS } + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS + } fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {} fn finish(self, cx: Cx<'_, Self>) -> ActionOutput { ActionOutput { response: cx.response.clone(), focus_visible: cx.focus_visible() } diff --git a/crates/ui-egui/src/panels/right/crop.rs b/crates/ui-egui/src/panels/right/crop.rs index d823a3769f..888094182e 100644 --- a/crates/ui-egui/src/panels/right/crop.rs +++ b/crates/ui-egui/src/panels/right/crop.rs @@ -95,7 +95,6 @@ fn custom_aspect(ui: &mut egui::Ui, owner: PhotoId) -> Option crate::widgets::register_response("button:cropCustomApply", go.response.rect, &go.response); apply |= go.clicked(); } - }); if !aspect_real(ui) || !ui.is_enabled() { return None; @@ -357,7 +356,9 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { (O::None, "None", "none"), ]; // scoped to the photo: a menu opened (or a row held) for one photo never picks for another - let picked = ui.push_id(("crop-overlay", id), |ui| crate::widgets::labeled_dropdown(ui, "cropOverlay", "Overlay", "", &overlays, app.ui.crop_overlay)).inner; + let picked = ui + .push_id(("crop-overlay", id), |ui| crate::widgets::labeled_dropdown(ui, "cropOverlay", "Overlay", "", &overlays, app.ui.crop_overlay)) + .inner; if let Some(o) = picked && interactive { diff --git a/crates/ui-egui/src/panels/right/crop_checkboxes_external155_tests.rs b/crates/ui-egui/src/panels/right/crop_checkboxes_external155_tests.rs index 9f6f1d95d7..cf4ce78b16 100644 --- a/crates/ui-egui/src/panels/right/crop_checkboxes_external155_tests.rs +++ b/crates/ui-egui/src/panels/right/crop_checkboxes_external155_tests.rs @@ -8,10 +8,18 @@ const VISUALIZE: &str = "check:remove.visualizeSpots"; const CATCHLIGHT: &str = "check:redeye.catchlight"; #[derive(Clone, Copy)] -enum Panel { Crop, Remove, Eye } +enum Panel { + Crop, + Remove, + Eye, +} #[derive(Clone, Copy)] -enum Pass { Normal, NativeSizing, SdkMeasure } +enum Pass { + Normal, + NativeSizing, + SdkMeasure, +} struct Controls { app: LightcraftApp, @@ -68,7 +76,9 @@ impl Controls { } fn settle(&mut self) { - for _ in 0..3 { self.frame(vec![], Pass::Normal); } + for _ in 0..3 { + self.frame(vec![], Pass::Normal); + } } fn has(&self, id: &str) -> bool { @@ -212,7 +222,9 @@ fn crop_checkboxes_external155_catchlight_is_pet_only_and_uses_selected_index() fn crop_checkboxes_external155_both_measurement_modes_publish_no_checkbox_targets_or_edits() { for (panel, id) in [(Panel::Crop, CONSTRAIN), (Panel::Remove, VISUALIZE), (Panel::Eye, CATCHLIGHT)] { let mut h = Controls::new(panel); - if matches!(panel, Panel::Eye) { h.eyes(); } + if matches!(panel, Panel::Eye) { + h.eyes(); + } for pass in [Pass::NativeSizing, Pass::SdkMeasure] { h.settle(); h.focus(id); diff --git a/crates/ui-egui/src/panels/right/crop_overlay_flow_tests.rs b/crates/ui-egui/src/panels/right/crop_overlay_flow_tests.rs index 28efe0f908..56baf1deda 100644 --- a/crates/ui-egui/src/panels/right/crop_overlay_flow_tests.rs +++ b/crates/ui-egui/src/panels/right/crop_overlay_flow_tests.rs @@ -326,14 +326,19 @@ impl Fixture { assert_eq!(Some(self.hit(FACE).layer_id), self.record_layer, "the face belongs to the actual parent's layer"); assert!(self.panel.expand(1.0).contains_rect(face), "no panel widening: {face:?} panel={:?}", self.panel); let shown = OPTIONS.iter().find(|(choice, _, _)| *choice == self.app.ui.crop_overlay).map_or("", |(_, label, _)| crate::i18n::tr(label)); - assert!(self.texts.iter().any(|text| text.text == shown && face.expand(1.0).intersects(text.rect)), "the face says {shown}; texts={:?}", self.texts); + assert!( + self.texts.iter().any(|text| text.text == shown && face.expand(1.0).intersects(text.rect)), + "the face says {shown}; texts={:?}", + self.texts + ); let mut owners = std::collections::HashSet::new(); for (index, (_, label, _)) in OPTIONS.iter().enumerate() { let name = locator(index); let rect = self.rect(&name); let hit = self.hit(&name); assert!(owners.insert(hit.id), "one owner per row"); - let painted: Vec<_> = self.texts.iter().filter(|text| text.text == crate::i18n::tr(label) && rect.expand(1.0).intersects(text.rect)).collect(); + let painted: Vec<_> = + self.texts.iter().filter(|text| text.text == crate::i18n::tr(label) && rect.expand(1.0).intersects(text.rect)).collect(); assert_eq!(painted.len(), 1, "full localized label is painted once: {name}; texts={:?}", self.texts); assert!(painted[0].clip.expand(1.0).contains_rect(painted[0].rect), "localized label must not be clipped: {name} {:?}", painted[0]); if index > 0 { diff --git a/crates/ui-egui/src/panels/right/history.rs b/crates/ui-egui/src/panels/right/history.rs index 84aee23d2b..e5b7ccadf2 100644 --- a/crates/ui-egui/src/panels/right/history.rs +++ b/crates/ui-egui/src/panels/right/history.rs @@ -1,7 +1,7 @@ +use super::{Align2, Icon, LightcraftApp, PhotoId, Rect, Tokens, header, json, padded, paint, pos2, text_button, vec2}; +use crate::panels::detail::host; use craft::ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Divider; -use crate::panels::detail::host; -use super::{Align2, Icon, LightcraftApp, PhotoId, Rect, Tokens, header, json, padded, paint, pos2, text_button, vec2}; pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let Some(p) = app.session.catalog.photo(id).cloned() else { return }; @@ -94,9 +94,9 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) let mut targets = Vec::new(); let mut layer = None; let mut action = None; - craft::ui::menu::Menu::context(crate::i18n::tr("Version"), &resp) - .id_salt(("history-menu", "version", id.0, i)) - .show(ui, |ui, menu| { + craft::ui::menu::Menu::context(crate::i18n::tr("Version"), &resp).id_salt(("history-menu", "version", id.0, i)).show( + ui, + |ui, menu| { layer = Some(ui.layer_id()); if !interactive { ui.disable(); @@ -122,15 +122,34 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) action = Some(VersionMenuAction::Delete); menu.request_close(); } - }); + }, + ); let eligible = publish_history_menu(ui.ctx(), layer, targets); if interactive && eligible { match action { - Some(VersionMenuAction::Restore) => { let _ = app.run("version.restore", json!({"index": i})); } - Some(VersionMenuAction::Update) => { let _ = app.run("version.update", json!({"index": i})); } - Some(VersionMenuAction::Rename) => { crate::panels::dialogs::prompt(app, "Rename Version", "Version name", &v.name, "version.rename", json!({"index": i}), "name"); } - Some(VersionMenuAction::Before) => { let _ = app.run("beforeAfter.setBefore", json!({"source": "version", "name": v.name})); } - Some(VersionMenuAction::Delete) => { let _ = app.run("version.delete", json!({"index": i})); } + Some(VersionMenuAction::Restore) => { + let _ = app.run("version.restore", json!({"index": i})); + } + Some(VersionMenuAction::Update) => { + let _ = app.run("version.update", json!({"index": i})); + } + Some(VersionMenuAction::Rename) => { + crate::panels::dialogs::prompt( + app, + "Rename Version", + "Version name", + &v.name, + "version.rename", + json!({"index": i}), + "name", + ); + } + Some(VersionMenuAction::Before) => { + let _ = app.run("beforeAfter.setBefore", json!({"source": "version", "name": v.name})); + } + Some(VersionMenuAction::Delete) => { + let _ = app.run("version.delete", json!({"index": i})); + } None => {} } } @@ -221,9 +240,9 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) let mut targets = Vec::new(); let mut layer = None; let mut action = None; - craft::ui::menu::Menu::context(crate::i18n::tr("History"), &resp) - .id_salt(("history-menu", "history", id.0, i)) - .show(ui, |ui, menu| { + craft::ui::menu::Menu::context(crate::i18n::tr("History"), &resp).id_salt(("history-menu", "history", id.0, i)).show( + ui, + |ui, menu| { layer = Some(ui.layer_id()); if !interactive { ui.disable(); @@ -241,14 +260,21 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) action = Some(HistoryMenuAction::Clear); menu.request_close(); } - }); + }, + ); let eligible = publish_history_menu(ui.ctx(), layer, targets); if interactive && eligible { match action { - Some(HistoryMenuAction::Before) => { let _ = app.run("beforeAfter.setBefore", json!({"source": "history", "index": i})); } - Some(HistoryMenuAction::CreateVersion) => { let _ = app.run("history.restore", json!({"index": i})); - let _ = app.run("version.create", json!({"name": h.label})); } - Some(HistoryMenuAction::Clear) => { let _ = app.run("history.clear", json!({})); } + Some(HistoryMenuAction::Before) => { + let _ = app.run("beforeAfter.setBefore", json!({"source": "history", "index": i})); + } + Some(HistoryMenuAction::CreateVersion) => { + let _ = app.run("history.restore", json!({"index": i})); + let _ = app.run("version.create", json!({"name": h.label})); + } + Some(HistoryMenuAction::Clear) => { + let _ = app.run("history.clear", json!({})); + } None => {} } } @@ -258,20 +284,22 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) }); } -enum VersionMenuAction { Restore, Update, Rename, Before, Delete } -enum HistoryMenuAction { Before, CreateVersion, Clear } +enum VersionMenuAction { + Restore, + Update, + Rename, + Before, + Delete, +} +enum HistoryMenuAction { + Before, + CreateVersion, + Clear, +} /// Draw real SDK actions, but do not publish or run app effects from a fading exit body. -fn history_menu_action( - ui: &mut egui::Ui, - key: (&str, u64, usize, &str), - label: &'static str, - targets: &mut Vec<(String, egui::Response)>, -) -> bool { - let shown = craft::ui::menu::MenuItem::new(crate::i18n::tr(label)) - .id_salt(("history-action", key)) - .enabled(ui.is_enabled()) - .show(ui); +fn history_menu_action(ui: &mut egui::Ui, key: (&str, u64, usize, &str), label: &'static str, targets: &mut Vec<(String, egui::Response)>) -> bool { + let shown = craft::ui::menu::MenuItem::new(crate::i18n::tr(label)).id_salt(("history-action", key)).enabled(ui.is_enabled()).show(ui); let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()); if measuring { return false; @@ -283,11 +311,7 @@ fn history_menu_action( /// The Area stores its CURRENT interactability after its body returns. Querying it inside /// the closure would use the previous pass and break same-target reopen during the exit. -fn publish_history_menu( - ctx: &egui::Context, - layer: Option, - targets: Vec<(String, egui::Response)>, -) -> bool { +fn publish_history_menu(ctx: &egui::Context, layer: Option, targets: Vec<(String, egui::Response)>) -> bool { let eligible = layer.and_then(|layer| egui::AreaState::load(ctx, layer.id)).is_some_and(|state| state.interactable); if eligible { for (name, response) in targets { diff --git a/crates/ui-egui/src/panels/right/history_sdk_action_tests.rs b/crates/ui-egui/src/panels/right/history_sdk_action_tests.rs index 8252e64084..cee58a1262 100644 --- a/crates/ui-egui/src/panels/right/history_sdk_action_tests.rs +++ b/crates/ui-egui/src/panels/right/history_sdk_action_tests.rs @@ -2,13 +2,17 @@ //! Authored for the existing integrator’s normal test consumer; execution results are reported separately. use super::*; -use std::sync::Arc; -use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui}; use crate::headless::HeadlessView; use crate::widgets::{WidgetHit, take_registries}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui}; +use std::sync::Arc; #[derive(Clone, Copy)] -enum Pass { Real, Measure, Sizing } +enum Pass { + Real, + Measure, + Sizing, +} struct Frames { ctx: egui::Context, @@ -32,10 +36,13 @@ impl Frames { } fn frame(&mut self, events: Vec, mut draw: impl FnMut(&mut Ui)) { - let requested: Vec<_> = events.iter().filter_map(|event| match event { - Event::Key { key, pressed, .. } => Some((*key, *pressed)), - _ => None, - }).collect(); + let requested: Vec<_> = events + .iter() + .filter_map(|event| match event { + Event::Key { key, pressed, .. } => Some((*key, *pressed)), + _ => None, + }) + .collect(); let mut live = Vec::new(); let mut published = (vec![], vec![]); let mut publication = Vec::new(); @@ -47,10 +54,16 @@ impl Frames { let enabled = self.enabled; let mut output = self.ctx.run_ui(raw, |ui| { if !requested.is_empty() { - let events: Vec<_> = ui.input(|input| input.events.iter().filter_map(|event| match event { - Event::Key { key, pressed, .. } => Some((*key, *pressed)), - _ => None, - }).collect()); + let events: Vec<_> = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + Event::Key { key, pressed, .. } => Some((*key, *pressed)), + _ => None, + }) + .collect() + }); live.push((ui.ctx().cumulative_pass_nr(), events)); } ui.set_max_width(350.0); @@ -71,7 +84,12 @@ impl Frames { let discarded = ui.ctx().will_discard(); if publication.len() < 8 { let menus: Vec<_> = hits.iter().filter(|(name, _)| name.contains("Menu:")).map(|(name, hit)| (name.clone(), hit.id)).collect(); - publication.push(format!("pass={} discarded={discarded} sdk_keys_open_last_pass={} native_popup={} menu_owners={menus:?}", ui.ctx().cumulative_pass_nr(), craft::ui::runtime::overlay::any_open(ui.ctx(), craft::ui::runtime::overlay::OpenFilter::Keys), egui::Popup::is_any_open(ui.ctx()))); + publication.push(format!( + "pass={} discarded={discarded} sdk_keys_open_last_pass={} native_popup={} menu_owners={menus:?}", + ui.ctx().cumulative_pass_nr(), + craft::ui::runtime::overlay::any_open(ui.ctx(), craft::ui::runtime::overlay::OpenFilter::Keys), + egui::Popup::is_any_open(ui.ctx()) + )); } published = if discarded { (vec![], vec![]) } else { (rects, hits) }; }); @@ -85,7 +103,10 @@ impl Frames { if self.key_trace.len() == 64 { self.key_trace.remove(0); } - self.key_trace.push(format!("requested={requested:?} live_after_hook={live:?} native={native:?} sdk={sdk:?} native_popup={} owners={owners:?}", egui::Popup::is_any_open(&self.ctx))); + self.key_trace.push(format!( + "requested={requested:?} live_after_hook={live:?} native={native:?} sdk={sdk:?} native_popup={} owners={owners:?}", + egui::Popup::is_any_open(&self.ctx) + )); } } @@ -108,9 +129,9 @@ impl Frames { } fn escape(&mut self, mut draw: impl FnMut(&mut Ui)) { - let events = [true, false].map(|pressed| Event::Key { - key: Key::Escape, physical_key: Some(Key::Escape), pressed, repeat: false, modifiers: Modifiers::NONE, - }).to_vec(); + let events = [true, false] + .map(|pressed| Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed, repeat: false, modifiers: Modifiers::NONE }) + .to_vec(); self.frame(events, &mut draw); self.settle(draw); } @@ -151,7 +172,14 @@ impl Frames { } fn assert_dismissed(&self) { - assert!(!self.rects.iter().any(|(id, _)| id.starts_with("versionMenu:") || id.starts_with("historyMenu:")), "action popup must be dismissed; sdk_keys_open={} sdk_top={:?} native_popup={} publication={:?}", craft::ui::runtime::overlay::any_open(&self.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), craft::ui::runtime::overlay::top(&self.ctx), egui::Popup::is_any_open(&self.ctx), self.publication); + assert!( + !self.rects.iter().any(|(id, _)| id.starts_with("versionMenu:") || id.starts_with("historyMenu:")), + "action popup must be dismissed; sdk_keys_open={} sdk_top={:?} native_popup={} publication={:?}", + craft::ui::runtime::overlay::any_open(&self.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), + craft::ui::runtime::overlay::top(&self.ctx), + egui::Popup::is_any_open(&self.ctx), + self.publication + ); } } @@ -346,16 +374,24 @@ fn sdk_history_missing_photo_is_a_control_and_command_no_op() { assert_eq!(state(&app, active), before); } - #[derive(Clone, Copy)] -enum Panel { Snapshots, History } +enum Panel { + Snapshots, + History, +} fn draw_panel(panel: Panel, app: &mut LightcraftApp, ui: &mut Ui, id: PhotoId) { - match panel { Panel::Snapshots => versions(app, ui, id), Panel::History => activity(app, ui, id) } + match panel { + Panel::Snapshots => versions(app, ui, id), + Panel::History => activity(app, ui, id), + } } fn open_panel_menu(panel: Panel, f: &mut Frames, app: &mut LightcraftApp, id: PhotoId, index: usize) { - match panel { Panel::Snapshots => version_menu(f, app, id, index), Panel::History => history_menu(f, app, id, index) } + match panel { + Panel::Snapshots => version_menu(f, app, id, index), + Panel::History => history_menu(f, app, id, index), + } } fn document(app: &LightcraftApp) -> serde_json::Value { @@ -529,7 +565,11 @@ fn history_actions_unforced_tab_enter_space_cancel_exit_and_real_reopen() { assert_eq!(app.session.before.get(&id), Some(settings)); assert_eq!(photo(&app, id), initial); assert_eq!(app.session.undo.len(), undo); - let params = if action == "history-before" { json!({"source":"history", "index":index}) } else { json!({"source":"version", "name":initial.versions[0].name}) }; + let params = if action == "history-before" { + json!({"source":"history", "index":index}) + } else { + json!({"source":"version", "name":initial.versions[0].name}) + }; assert_one_command(&app, journal, "beforeAfter.setBefore", params); } } @@ -544,8 +584,14 @@ fn history_already_open_disabled_popup_refuses_pointer_and_keys_then_recovers() for panel in [Panel::Snapshots, Panel::History] { let (mut app, id) = fixture(); let initial = photo(&app, id); - let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 }; - let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") }; + let index = match panel { + Panel::Snapshots => 0, + Panel::History => initial.history.len() - 3, + }; + let target = match panel { + Panel::Snapshots => "versionMenu:0:restore".to_owned(), + Panel::History => format!("historyMenu:{index}:before"), + }; let mut f = Frames::new(); open_panel_menu(panel, &mut f, &mut app, id, index); f.tab_to(&target, |ui| draw_panel(panel, &mut app, ui, id)); @@ -577,19 +623,32 @@ fn history_measured_release_is_inert_then_the_same_row_and_action_recover() { for pass in [Pass::Sizing, Pass::Measure] { let (mut app, id) = fixture(); let initial = photo(&app, id); - let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 }; - let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") }; - let row = match panel { Panel::Snapshots => "version:0".to_owned(), Panel::History => format!("history:{index}") }; + let index = match panel { + Panel::Snapshots => 0, + Panel::History => initial.history.len() - 3, + }; + let target = match panel { + Panel::Snapshots => "versionMenu:0:restore".to_owned(), + Panel::History => format!("historyMenu:{index}:before"), + }; + let row = match panel { + Panel::Snapshots => "version:0".to_owned(), + Panel::History => format!("history:{index}"), + }; let mut f = Frames::new(); open_panel_menu(panel, &mut f, &mut app, id, index); let owner = f.hit(&row).id; let at = f.rect(&target).center(); let baseline = document(&app); f.frame(vec![Event::PointerMoved(at)], |ui| draw_panel(panel, &mut app, ui, id)); - f.frame(vec![Event::PointerButton { pos:at, button:PointerButton::Primary, pressed:true, modifiers:Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id)); + f.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], |ui| { + draw_panel(panel, &mut app, ui, id) + }); assert_eq!(document(&app), baseline, "ordinary action press is not its release"); f.pass = pass; - f.frame(vec![Event::PointerButton { pos:at, button:PointerButton::Primary, pressed:false, modifiers:Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id)); + f.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], |ui| { + draw_panel(panel, &mut app, ui, id) + }); assert_eq!(document(&app), baseline); assert!(!f.rects.iter().any(|(id, _)| id.starts_with("version:") || id.starts_with("history:") || id.contains("Menu:"))); assert!(!f.hits.iter().any(|(id, _)| id.starts_with("version:") || id.starts_with("history:") || id.contains("Menu:"))); @@ -629,8 +688,8 @@ fn history_stale_photo_and_other_panel_cannot_retarget_an_existing_popup() { let (mut app, id) = fixture(); let other = app.session.catalog.photos().find(|p| p.id != id).unwrap().id; let template = photo(&app, id); - app.session.catalog.apply(lightcraft_catalog::Op::SetVersions { id:other, versions:template.versions.clone() }).unwrap(); - app.session.catalog.apply(lightcraft_catalog::Op::SetHistory { id:other, history:template.history.clone() }).unwrap(); + app.session.catalog.apply(lightcraft_catalog::Op::SetVersions { id: other, versions: template.versions.clone() }).unwrap(); + app.session.catalog.apply(lightcraft_catalog::Op::SetHistory { id: other, history: template.history.clone() }).unwrap(); let mut f = Frames::new(); version_menu(&mut f, &mut app, id, 0); let owner = f.hit("version:0").id; @@ -664,7 +723,6 @@ fn history_stale_photo_and_other_panel_cannot_retarget_an_existing_popup() { assert_eq!(document(&app), baseline); } - #[test] fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the_same_target() { for panel in [Panel::Snapshots, Panel::History] { @@ -675,9 +733,18 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the let baseline = document(&app); let undo = app.session.undo.len(); let journal = app.session.journal.len(); - let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 }; - let row = match panel { Panel::Snapshots => "version:0".to_owned(), Panel::History => format!("history:{index}") }; - let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") }; + let index = match panel { + Panel::Snapshots => 0, + Panel::History => initial.history.len() - 3, + }; + let row = match panel { + Panel::Snapshots => "version:0".to_owned(), + Panel::History => format!("history:{index}"), + }; + let target = match panel { + Panel::Snapshots => "versionMenu:0:restore".to_owned(), + Panel::History => format!("historyMenu:{index}:before"), + }; let mut f = Frames::new(); f.settle(|ui| draw_panel(panel, &mut app, ui, id)); let bounds = f.rect(&row); @@ -700,14 +767,22 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the eprintln!("History first-Tab boundary {target}: {:?}", f.key_trace); // No idle/settle frame between cancel and the next genuine secondary press/release. - f.frame(vec![Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: true, repeat: false, modifiers: Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id)); + f.frame( + vec![Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: true, repeat: false, modifiers: Modifiers::NONE }], + |ui| draw_panel(panel, &mut app, ui, id), + ); assert_eq!(document(&app), baseline, "Escape cannot replay the focused action"); - f.frame(vec![ - Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: false, repeat: false, modifiers: Modifiers::NONE }, - Event::PointerMoved(right), - Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, - ], |ui| draw_panel(panel, &mut app, ui, id)); - f.frame(vec![Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id)); + f.frame( + vec![ + Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: false, repeat: false, modifiers: Modifiers::NONE }, + Event::PointerMoved(right), + Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + ], + |ui| draw_panel(panel, &mut app, ui, id), + ); + f.frame(vec![Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }], |ui| { + draw_panel(panel, &mut app, ui, id) + }); assert!(!egui::Popup::is_any_open(&f.ctx)); assert_eq!(document(&app), baseline, "immediate reopening is not activation or restoration"); f.tab_to(&target, |ui| draw_panel(panel, &mut app, ui, id)); @@ -734,7 +809,6 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the } } - #[test] fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activate() { for panel in [Panel::Snapshots, Panel::History] { @@ -745,8 +819,14 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat let selection = app.session.selection.clone(); let undo = app.session.undo.len(); let journal = app.session.journal.len(); - let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 }; - let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") }; + let index = match panel { + Panel::Snapshots => 0, + Panel::History => initial.history.len() - 3, + }; + let target = match panel { + Panel::Snapshots => "versionMenu:0:restore".to_owned(), + Panel::History => format!("historyMenu:{index}:before"), + }; let mut f = Frames::new(); open_panel_menu(panel, &mut f, &mut app, id, index); assert!(craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys)); @@ -765,7 +845,11 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat eprintln!("History publication open {target}: {:?}", f.publication); f.escape(|ui| draw_panel(panel, &mut app, ui, id)); - eprintln!("History publication cancelled {target}: sdk_keys_open={} passes={:?}", craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), f.publication); + eprintln!( + "History publication cancelled {target}: sdk_keys_open={} passes={:?}", + craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), + f.publication + ); f.assert_dismissed(); assert!(!craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys)); assert_eq!(document(&app), baseline, "cancel may neither edit nor replay an action"); @@ -788,7 +872,11 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat assert_one_command(&app, journal, "beforeAfter.setBefore", json!({"source": "history", "index": index})); } } - eprintln!("History publication activated {target}: sdk_keys_open={} passes={:?}", craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), f.publication); + eprintln!( + "History publication activated {target}: sdk_keys_open={} passes={:?}", + craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), + f.publication + ); f.assert_dismissed(); assert!(!craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys)); assert_eq!(other_photos(&app, id), others); diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index 8216716338..aaab80e83f 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -433,10 +433,8 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr ui.label(egui::RichText::new(label).size(11.5).color(t.text_dim)); let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()); let editable = ui.is_enabled() && !targets.is_empty() && !measuring; - let entries: Vec<_> = lightcraft_catalog::CopyrightStatus::ALL - .into_iter() - .map(|status| Entry::new(status, crate::i18n::tr(status.label()))) - .collect(); + let entries: Vec<_> = + lightcraft_catalog::CopyrightStatus::ALL.into_iter().map(|status| Entry::new(status, crate::i18n::tr(status.label()))).collect(); let value = if mixed { Mixed::Mixed } else { Mixed::Same(current) }; let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), 24.0), Sense::hover()); // The fixed field has already reserved its measured size. A speculative pass must not @@ -447,12 +445,11 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr } // Keep LightCraft's translated Mixed label without replacing the SDK's mixed binding. let words = WordRows::new().row(Word::keyed("select.mixed", MIXED), crate::i18n::tr(MIXED)); - let shown = with_env(ui, |scope| scope.words = Some(WordsOverride::Overlay(words)), |ui| { - Select::new(label, Bind::given(value), &entries) - .id_salt("info-copyright-status") - .enabled(editable) - .show_at(ui, rect) - }); + let shown = with_env( + ui, + |scope| scope.words = Some(WordsOverride::Overlay(words)), + |ui| Select::new(label, Bind::given(value), &entries).id_salt("info-copyright-status").enabled(editable).show_at(ui, rect), + ); if !measuring { crate::widgets::register_response("field:copyrightStatus", shown.response.rect, &shown.response); // The SDK owns drafts, keyboard navigation and dismissal. Only its commit edits the diff --git a/crates/ui-egui/src/panels/right/info_copyright_tests.rs b/crates/ui-egui/src/panels/right/info_copyright_tests.rs index ace72fc91f..6c2fcf7436 100644 --- a/crates/ui-egui/src/panels/right/info_copyright_tests.rs +++ b/crates/ui-egui/src/panels/right/info_copyright_tests.rs @@ -259,7 +259,10 @@ fn keyboard_escape_drops_draft_and_reopen_has_original_value() { assert_eq!(f.values(), [Status::PublicDomain, Status::PublicDomain, Status::Copyrighted]); assert_eq!(f.app.session.undo.len(), 1); assert_eq!(f.app.session.journal.len(), 1); - assert_eq!(f.app.session.journal[0], ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::>(),"copyrightStatus":Status::PublicDomain.id()}))); + assert_eq!( + f.app.session.journal[0], + ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::>(),"copyrightStatus":Status::PublicDomain.id()})) + ); f.app.session.undo_step().unwrap(); assert_eq!(metadata_state(&f.app, &f.ids)["photos"], original["photos"]); assert_eq!(f.app.session.selection, selection); @@ -419,7 +422,10 @@ fn measured_opener(pass: u8) { assert_eq!(f.values(), [Status::Unknown, Status::Unknown, Status::PublicDomain]); assert_eq!(f.app.session.undo.len(), 1); assert_eq!(f.app.session.journal.len(), 1, "one accepted command, not a speculative release and a real pick"); - assert_eq!(f.app.session.journal[0], ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::>(),"copyrightStatus":Status::Unknown.id()}))); + assert_eq!( + f.app.session.journal[0], + ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::>(),"copyrightStatus":Status::Unknown.id()})) + ); f.app.session.undo_step().unwrap(); assert_eq!(metadata_state(&f.app, &ids)["photos"], before["photos"], "Undo restores every photo, including the untouched third target"); assert_eq!(f.app.session.selection, selection); diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index 322e75e0c8..7746b4ddab 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -1,6 +1,6 @@ +use super::{HOLD, LightcraftApp, PhotoId, Rect, Tokens, fold_header, json, padded, register, text_button, vec2}; use craft::ui::buttons::Button; use craft::ui::contract::{Props as _, Show as _}; -use super::{HOLD, LightcraftApp, PhotoId, Rect, Tokens, fold_header, json, padded, register, text_button, vec2}; pub(super) fn keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // (the box is the selection's: the active photo only says that there is one) @@ -367,51 +367,68 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { let face = crate::i18n::builtin_label(¤t, current == recent).to_owned(); // (the dropdown takes the rest of the line, so a long set name is not cut and the chevron stays) let room = ui.available_width(); - crate::widgets::dropdown_menu_sized(ui, "keywordSetCombo", crate::i18n::tr("Keyword Set"), &face, Some(room), craft::theme::ControlSize::Sm, |ui| { - for set in sets["sets"].as_array().into_iter().flatten() { - let name = set["name"].as_str().unwrap_or_default(); - if crate::widgets::menu_row(ui, ("keywordSet", name), None, crate::i18n::builtin_label(name, name == recent), None, name == current, true) { - let _ = app.run("keyword.useSet", json!({"name": name})); + crate::widgets::dropdown_menu_sized( + ui, + "keywordSetCombo", + crate::i18n::tr("Keyword Set"), + &face, + Some(room), + craft::theme::ControlSize::Sm, + |ui| { + for set in sets["sets"].as_array().into_iter().flatten() { + let name = set["name"].as_str().unwrap_or_default(); + if crate::widgets::menu_row( + ui, + ("keywordSet", name), + None, + crate::i18n::builtin_label(name, name == recent), + None, + name == current, + true, + ) { + let _ = app.run("keyword.useSet", json!({"name": name})); + } } - } - crate::widgets::menu_divider(ui); - // Edit Set…: the current nine, slot by slot (named, Recent Keywords becomes a set) - if crate::widgets::menu_row(ui, "keywordSetMenu:edit", Some("keywordSetMenu:edit"), crate::i18n::tr("Edit Set…"), None, false, true) { - let mut slots: Vec = - sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); - slots.resize(9, String::new()); - let named = current != recent; - app.ui.dialog = Some(crate::state::Dialog::KeywordSet { - replaces: named.then(|| current.clone()), - name: if named { current.clone() } else { String::new() }, - slots, - as_new: false, - }); - } - if crate::widgets::menu_row(ui, "keywordSetMenu:save", None, crate::i18n::tr("Save Current Keywords as Set…"), None, false, true) { - app.ui.dialog = Some(crate::state::Dialog::TextPrompt { - title: "Save Keyword Set".into(), - hint: "Set name".into(), - value: String::new(), - command: "keyword.saveSet".into(), - params: json!({}), - key: "name".into(), - }); - } - if current != recent - && crate::widgets::menu_row( - ui, - "keywordSetMenu:delete", - None, - &crate::i18n::tr_format!("Delete “{current}”", current = current), - None, - false, - true, - ) - { - let _ = app.run("keyword.deleteSet", json!({"name": current})); - } - }); + crate::widgets::menu_divider(ui); + // Edit Set…: the current nine, slot by slot (named, Recent Keywords becomes a set) + if crate::widgets::menu_row(ui, "keywordSetMenu:edit", Some("keywordSetMenu:edit"), crate::i18n::tr("Edit Set…"), None, false, true) + { + let mut slots: Vec = + sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); + slots.resize(9, String::new()); + let named = current != recent; + app.ui.dialog = Some(crate::state::Dialog::KeywordSet { + replaces: named.then(|| current.clone()), + name: if named { current.clone() } else { String::new() }, + slots, + as_new: false, + }); + } + if crate::widgets::menu_row(ui, "keywordSetMenu:save", None, crate::i18n::tr("Save Current Keywords as Set…"), None, false, true) { + app.ui.dialog = Some(crate::state::Dialog::TextPrompt { + title: "Save Keyword Set".into(), + hint: "Set name".into(), + value: String::new(), + command: "keyword.saveSet".into(), + params: json!({}), + key: "name".into(), + }); + } + if current != recent + && crate::widgets::menu_row( + ui, + "keywordSetMenu:delete", + None, + &crate::i18n::tr_format!("Delete “{current}”", current = current), + None, + false, + true, + ) + { + let _ = app.run("keyword.deleteSet", json!({"name": current})); + } + }, + ); }); let kws: Vec = sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect(); if kws.is_empty() { diff --git a/crates/ui-egui/src/panels/right/remove_controls_flow_tests.rs b/crates/ui-egui/src/panels/right/remove_controls_flow_tests.rs index 79e32382c2..8f2d80e7d8 100644 --- a/crates/ui-egui/src/panels/right/remove_controls_flow_tests.rs +++ b/crates/ui-egui/src/panels/right/remove_controls_flow_tests.rs @@ -393,7 +393,11 @@ fn remove_natural_keyboard_modes_numeric_commit_and_slider_steps_use_the_real_fo } f.key(Key::ArrowDown); } - assert!(craft::ui::runtime::focus::focused_rec(&f.ctx).is_some_and(|r| r.stop.id == f.hit("removeMode:heal").id), "arrows reach Heal; trace={:#?}", f.trace); + assert!( + craft::ui::runtime::focus::focused_rec(&f.ctx).is_some_and(|r| r.stop.id == f.hit("removeMode:heal").id), + "arrows reach Heal; trace={:#?}", + f.trace + ); f.key(Key::Space); assert_eq!(f.app.ui.tool, "heal"); assert_eq!(f.app.session.undo.len(), undo); diff --git a/crates/ui-egui/src/panels/strip.rs b/crates/ui-egui/src/panels/strip.rs index cd6da96acb..5133eb109d 100644 --- a/crates/ui-egui/src/panels/strip.rs +++ b/crates/ui-egui/src/panels/strip.rs @@ -14,13 +14,9 @@ const BUTTON_H: f32 = 40.0; /// Space between tool buttons. const GAP: f32 = 6.0; - /// Keep one definition of the actual Panel frame for drawing and its intrinsic reservation. fn panel_frame(t: &Tokens) -> egui::Frame { - egui::Frame::NONE - .fill(t.chrome) - .inner_margin(egui::Margin { left: 0, right: 0, top: 8, bottom: 8 }) - .stroke(egui::Stroke::new(1.0, t.divider)) + egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left: 0, right: 0, top: 8, bottom: 8 }).stroke(egui::Stroke::new(1.0, t.divider)) } /// Panel's documented separator is outside the frame, in its inner-facing outer margin. @@ -76,64 +72,59 @@ pub(crate) fn show_in_shell(app: &mut LightcraftApp, ui: &mut egui::Ui, rtl: boo pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - egui::Panel::right("tool_strip") - .exact_size(t.strip_w) - .resizable(false) - .frame(panel_frame(&t)) - .show(ui, |ui| { - crate::widgets::announce_region(ui, egui::accesskit::Role::Toolbar, crate::i18n::tr("Tool strip")); - let has_photo = app.session.active().is_some(); - ui.vertical_centered(|ui| { - ui.spacing_mut().item_spacing.y = GAP; - let sz = vec2(t.strip_w, BUTTON_H); - if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() { - let _ = app.run("panel.presets", json!({})); + egui::Panel::right("tool_strip").exact_size(t.strip_w).resizable(false).frame(panel_frame(&t)).show(ui, |ui| { + crate::widgets::announce_region(ui, egui::accesskit::Role::Toolbar, crate::i18n::tr("Tool strip")); + let has_photo = app.session.active().is_some(); + ui.vertical_centered(|ui| { + ui.spacing_mut().item_spacing.y = GAP; + let sz = vec2(t.strip_w, BUTTON_H); + if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() { + let _ = app.run("panel.presets", json!({})); + } + for (id, icon, panel, tip) in [ + ("edit", Icon::Sliders, RightPanel::Edit, "Edit (E)"), + ("crop", Icon::Crop, RightPanel::Crop, "Crop & Rotate (C)"), + ("remove", Icon::Eraser, RightPanel::Remove, "Remove (H)"), + ("masking", Icon::Mask, RightPanel::Masking, "Masking (M)"), + ("redeye", Icon::Eye, RightPanel::RedEye, "Red Eye"), + ] { + let on = app.ui.right == panel || (panel == RightPanel::Edit && app.ui.right == RightPanel::Profiles); + if icon_button(ui, id, icon, sz, on, has_photo, tip).clicked() { + let _ = app.run(&format!("panel.{id}"), json!({})); } - for (id, icon, panel, tip) in [ - ("edit", Icon::Sliders, RightPanel::Edit, "Edit (E)"), - ("crop", Icon::Crop, RightPanel::Crop, "Crop & Rotate (C)"), - ("remove", Icon::Eraser, RightPanel::Remove, "Remove (H)"), - ("masking", Icon::Mask, RightPanel::Masking, "Masking (M)"), - ("redeye", Icon::Eye, RightPanel::RedEye, "Red Eye"), - ] { - let on = app.ui.right == panel || (panel == RightPanel::Edit && app.ui.right == RightPanel::Profiles); - if icon_button(ui, id, icon, sz, on, has_photo, tip).clicked() { - let _ = app.run(&format!("panel.{id}"), json!({})); - } - if id == "edit" { - separator(ui, &t); - } + if id == "edit" { + separator(ui, &t); } - separator(ui, &t); - if icon_button(ui, "versions", Icon::Versions, sz, app.ui.right == RightPanel::Versions, has_photo, "Versions (Shift+V)").clicked() { - let _ = app.run("panel.versions", json!({})); - } - if icon_button(ui, "activity", Icon::Activity, sz, app.ui.right == RightPanel::Activity, true, "History & Activity (Y)").clicked() { - let _ = app.run("panel.activity", json!({})); - } - if icon_button(ui, "more", Icon::More, sz, false, true, "More").clicked() { - app.ui.dialog = Some(crate::state::Dialog::About); - } - }); - // bottom icons: two buttons and one gap tall, so Info ends at the bottom margin as - // Presets starts at the top one - let bottom = ui.max_rect().bottom(); - let mut child = - ui.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_max( - egui::pos2(ui.max_rect().left(), bottom - (2.0 * BUTTON_H + GAP)), - ui.max_rect().right_bottom(), - ))); - child.vertical_centered(|ui| { - ui.spacing_mut().item_spacing.y = GAP; - let sz = vec2(t.strip_w, BUTTON_H); - if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() { - let _ = app.run("panel.keywords", json!({})); - } - if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() { - let _ = app.run("panel.info", json!({})); - } - }); + } + separator(ui, &t); + if icon_button(ui, "versions", Icon::Versions, sz, app.ui.right == RightPanel::Versions, has_photo, "Versions (Shift+V)").clicked() { + let _ = app.run("panel.versions", json!({})); + } + if icon_button(ui, "activity", Icon::Activity, sz, app.ui.right == RightPanel::Activity, true, "History & Activity (Y)").clicked() { + let _ = app.run("panel.activity", json!({})); + } + if icon_button(ui, "more", Icon::More, sz, false, true, "More").clicked() { + app.ui.dialog = Some(crate::state::Dialog::About); + } }); + // bottom icons: two buttons and one gap tall, so Info ends at the bottom margin as + // Presets starts at the top one + let bottom = ui.max_rect().bottom(); + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(egui::Rect::from_min_max(egui::pos2(ui.max_rect().left(), bottom - (2.0 * BUTTON_H + GAP)), ui.max_rect().right_bottom())), + ); + child.vertical_centered(|ui| { + ui.spacing_mut().item_spacing.y = GAP; + let sz = vec2(t.strip_w, BUTTON_H); + if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() { + let _ = app.run("panel.keywords", json!({})); + } + if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() { + let _ = app.run("panel.info", json!({})); + } + }); + }); } fn separator(ui: &mut egui::Ui, t: &Tokens) { @@ -183,13 +174,11 @@ mod intrinsic_reservation_tests { let frame = egui::Frame::NONE.stroke(egui::Stroke::new(stroke, egui::Color32::GRAY)); let expected = centered_reservation(48.0, child_width, frame_with_separator(frame, ui.style())); let root = ui.available_rect_before_wrap(); - egui::Panel::right("intrinsic-regression") - .exact_size(48.0).resizable(false).frame(frame) - .show(ui, |ui| { - ui.vertical_centered(|ui| { - ui.allocate_exact_size(vec2(child_width, 40.0), egui::Sense::hover()); - }); + egui::Panel::right("intrinsic-regression").exact_size(48.0).resizable(false).frame(frame).show(ui, |ui| { + ui.vertical_centered(|ui| { + ui.allocate_exact_size(vec2(child_width, 40.0), egui::Sense::hover()); }); + }); let actual = root.right() - ui.available_rect_before_wrap().right(); assert_eq!(actual, expected, "width={width} scale={scale} child={child_width} stroke={stroke}"); if child_width == 32.0 { diff --git a/crates/ui-egui/src/panels/tests_named_person_actions.rs b/crates/ui-egui/src/panels/tests_named_person_actions.rs index f2a3c226c7..7e0b9e54e1 100644 --- a/crates/ui-egui/src/panels/tests_named_person_actions.rs +++ b/crates/ui-egui/src/panels/tests_named_person_actions.rs @@ -31,10 +31,8 @@ impl Frames { crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx); ctx.enable_accesskit(); - craft::ui::install( - &ctx, - craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::window::system::NoWindows)), - ).unwrap(); + craft::ui::install(&ctx, craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::window::system::NoWindows))) + .unwrap(); let mut session = lightcraft_engine::Session::new(); for (n, name) in [(1, CANONICAL), (2, REQUESTED), (3, "John Roe")] { let mut photo = Photo::new(PhotoId(n), Source::Demo { scene: 0 }, "synthetic.jpg", "JPEG", 32, 32, "2026-01-01T00:00:00"); @@ -50,7 +48,10 @@ impl Frames { app.ui.view = ViewMode::People; app.ui.person_page = Some(REQUESTED.into()); app.caches.person_page = Some(( - REQUESTED.into(), app.session.catalog.revision, app.caches.faces_indexed, 0.0, + REQUESTED.into(), + app.session.catalog.revision, + app.caches.faces_indexed, + 0.0, Arc::new(PersonPage { name: CANONICAL.into(), ..Default::default() }), )); Self { ctx, app, time: 0.0, rects: vec![], hits: vec![], sizing: false, measuring: false, disabled: false, nodes: vec![] } @@ -86,7 +87,9 @@ impl Frames { } fn settle(&mut self) { - for _ in 0..3 { self.frame(vec![]); } + for _ in 0..3 { + self.frame(vec![]); + } } fn at(&self, id: &str) -> Pos2 { diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index 11f112e66c..d6f3f881d0 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -148,7 +148,8 @@ fn filter_button(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rec crate::i18n::tr("Filter bar").into() }; let accent = if filtering { Some(t.accent) } else { None }; - let (fresp, live) = bar_icon(ui, fr, ("top", "filter"), "icon:filter", Icon::Filter, 16, accent.unwrap_or(t.icon), accent.unwrap_or(t.text), &tip); + let (fresp, live) = + bar_icon(ui, fr, ("top", "filter"), "icon:filter", Icon::Filter, 16, accent.unwrap_or(t.icon), accent.unwrap_or(t.text), &tip); if live && active > 0 { let c = fr.right_top() + vec2(-3.0, 8.0); ui.painter().circle_filled(c, 7.0, t.accent); diff --git a/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs b/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs index 159a3d1c50..c6787f5882 100644 --- a/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs +++ b/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs @@ -4,7 +4,11 @@ use crate::headless::HeadlessView; use crate::widgets::{WidgetHit, take_registries}; #[derive(Clone, Copy)] -enum Pass { Real, EguiSizing, SdkSizing } +enum Pass { + Real, + EguiSizing, + SdkSizing, +} struct Panel { app: LightcraftApp, @@ -21,20 +25,27 @@ impl Panel { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); let photo = app.session.catalog.photos().next().unwrap().id; let mut meta = app.session.catalog.photo(photo).unwrap().meta.clone(); - meta.regions = (0..3).map(|i| lightcraft_meta::Region { - rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 }, - kind: lightcraft_meta::RegionKind::Face, - name: None, - description: None, - }).collect(); + meta.regions = (0..3) + .map(|i| lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 }, + kind: lightcraft_meta::RegionKind::Face, + name: None, + description: None, + }) + .collect(); app.session.commit("unnamed port fixture", lightcraft_catalog::Op::SetMeta { id: photo, meta: Box::new(meta) }).unwrap(); let list = Unnamed { - total: 3, ready: true, ordered: true, - faces: (0..3).map(|index| UnnamedFace { - photo: photo.0, index, - view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.25, y1: 0.5 }, - suggestion: None, - }).collect(), + total: 3, + ready: true, + ordered: true, + faces: (0..3) + .map(|index| UnnamedFace { + photo: photo.0, + index, + view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.25, y1: 0.5 }, + suggestion: None, + }) + .collect(), }; app.caches.unnamed = Some((app.session.catalog.revision, app.caches.faces_indexed, 0.0, Arc::new(list.clone()))); let view = HeadlessView::new(); @@ -56,12 +67,18 @@ impl Panel { naming_bar(app, ui); }); }); - if let Some(record) = record { elements = record.elements.clone(); } + if let Some(record) = record { + elements = record.elements.clone(); + } }; match pass { Pass::Real => draw(ui), - Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().sizing_pass(), |ui| draw(ui)); } - Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); } + Pass::EguiSizing => { + ui.scope_builder(egui::UiBuilder::new().sizing_pass(), |ui| draw(ui)); + } + Pass::SdkSizing => { + craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); + } } }); (self.rects, self.hits) = take_registries(&self.view.ctx); @@ -71,7 +88,11 @@ impl Panel { fn target(&self, id: &str) -> Rect { let rect = self.rects.iter().find(|(key, _)| key == id).unwrap().1; let hit = self.hits.iter().find(|(key, _)| key == id).unwrap().1; - let element = self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("automation points at the real SDK component, not a probe"); + let element = self + .elements + .iter() + .find(|element| element.id == hit.id && element.part.is_none()) + .expect("automation points at the real SDK component, not a probe"); assert_eq!(element.component, "Button"); assert_eq!(element.rect, rect); assert_eq!(hit.interact_rect, rect.intersect(hit.interact_rect)); @@ -82,7 +103,10 @@ impl Panel { let pos = self.target(id).center(); self.frame(vec![egui::Event::PointerMoved(pos)], Pass::Real); for pressed in [true, false] { - self.frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], Pass::Real); + self.frame( + vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], + Pass::Real, + ); } self.frame(vec![], Pass::Real); } @@ -127,7 +151,10 @@ fn unnamed_port_select_all_then_type_and_return_names_exact_keys_in_one_undo() { let undo = p.app.session.undo.len(); p.frame(vec![egui::Event::Text("Port Example".into())], Pass::Real); for pressed in [true, false] { - p.frame(vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }], Pass::Real); + p.frame( + vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }], + Pass::Real, + ); } let photo = lightcraft_catalog::PhotoId(p.list.faces[0].photo); assert!(p.app.session.catalog.photo(photo).unwrap().meta.regions.iter().all(|region| region.name.as_deref() == Some("Port Example"))); @@ -178,14 +205,29 @@ fn unnamed_port_sizing_never_registers_or_changes_selection_or_settings() { p.frame(vec![], Pass::Real); p.frame(vec![], Pass::Real); let pos = p.target(target).center(); - let before = (p.app.ui.unnamed_selected.clone(), p.app.ui.unnamed_name.clone(), p.app.ui.unnamed_anchor, p.app.ui.dialog.clone(), p.app.session.undo.len()); + let before = ( + p.app.ui.unnamed_selected.clone(), + p.app.ui.unnamed_name.clone(), + p.app.ui.unnamed_anchor, + p.app.ui.dialog.clone(), + p.app.session.undo.len(), + ); p.frame(vec![egui::Event::PointerMoved(pos)], pass); for pressed in [true, false] { - p.frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], pass); + p.frame( + vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], + pass, + ); assert!(!p.rects.iter().any(|(id, _)| id == target)); assert!(!p.hits.iter().any(|(id, _)| id == target)); } - let after = (p.app.ui.unnamed_selected.clone(), p.app.ui.unnamed_name.clone(), p.app.ui.unnamed_anchor, p.app.ui.dialog.clone(), p.app.session.undo.len()); + let after = ( + p.app.ui.unnamed_selected.clone(), + p.app.ui.unnamed_name.clone(), + p.app.ui.unnamed_anchor, + p.app.ui.dialog.clone(), + p.app.session.undo.len(), + ); assert_eq!(before, after); } } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d7e5763507..bcd88adf60 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -297,12 +297,11 @@ pub(crate) fn framework_commands(keymap: &Keymap) -> craft::ui::runtime::command && (bindable().iter().any(|b| binding(keymap, b.id, b.default).and_then(parse) == chord) || ALIASES.iter().any(|(alias, _, _)| parse(alias) == chord)) }; - let unbound: Vec<&'static str> = - [(NavCommand::NextPane, "F6"), (NavCommand::PreviousPane, "Shift+F6"), (NavCommand::FocusMenuBar, "F10")] - .into_iter() - .filter(|(_, sc)| uses(sc)) - .map(|(command, _)| command.id()) - .collect(); + let unbound: Vec<&'static str> = [(NavCommand::NextPane, "F6"), (NavCommand::PreviousPane, "Shift+F6"), (NavCommand::FocusMenuBar, "F10")] + .into_iter() + .filter(|(_, sc)| uses(sc)) + .map(|(command, _)| command.id()) + .collect(); // One `Arc` per unbound set: the runtime rebuilds its keymap only when the `Arc` changes. static LAST: std::sync::Mutex, std::sync::Arc)>> = std::sync::Mutex::new(None); let mut last = LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -575,14 +574,19 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { /// The keys pressed this frame: the commands to fire, the aliases (command and params) to run, and /// whether an unmodified H that no keymap assignment has claimed was pressed (the Masking panel's /// pin toggle, see `handle`). -fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context, clips: Vec) -> (Vec, Vec<(&'static str, serde_json::Value)>, bool) { +fn pressed_commands( + app: &LightcraftApp, + ctx: &egui::Context, + clips: Vec, +) -> (Vec, Vec<(&'static str, serde_json::Value)>, bool) { let mut fire: Vec = Vec::new(); // An Escape no framework component took reaches the app as the window's Cancel (the runtime keeps the raw key): // the app's own Escape bindings (View ▸ Back and the like) read it there, last in the pass. // While a framework popup (a menu, a dropdown) is open the Escape is the popup's: the runtime lends the focused // row's unused Escape to the window, so taking it here, before the popup is drawn, would leave the menu open. let popup_owns_escape = craft::ui::runtime::overlay::any_open(ctx, craft::ui::runtime::overlay::OpenFilter::Keys); - let window_escape = !popup_owns_escape && craft::ui::runtime::keys::with_window_intents(ctx, false, |w| w.take(craft::ui::runtime::keys::Intent::Cancel)); + let window_escape = + !popup_owns_escape && craft::ui::runtime::keys::with_window_intents(ctx, false, |w| w.take(craft::ui::runtime::keys::Intent::Cancel)); // The same for the clipboard events the runtime routed to the window as edit commands. let mut window_edits: Vec = clips; craft::ui::runtime::keys::with_window_intents(ctx, false, |w| { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 7f5e1597ca..22fb5b81d8 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -13,7 +13,6 @@ fn settle_budget_only_expands_for_llvm_coverage_runs() { } mod activity; -mod dialog_settings_popup_contract; mod album_picker; mod album_remove; mod alt_preview; @@ -35,12 +34,13 @@ mod curve; mod date_picker; mod dialog_copy; mod dialog_fit; -mod dialog_settings_blur_count; mod dialog_primary; mod dialog_settings; -mod dialog_settings_text; +mod dialog_settings_blur_count; mod dialog_settings_keyboard_contract; mod dialog_settings_keyboard_guards; +mod dialog_settings_popup_contract; +mod dialog_settings_text; mod dialog_tab; mod dialogs; mod disk_space; @@ -126,5 +126,5 @@ mod zoom_keys; pub(super) mod fixtures; pub(super) mod render_fixtures; -mod real_journey; mod port_screenshots; +mod real_journey; diff --git a/crates/ui-egui/src/tests/guided_guides.rs b/crates/ui-egui/src/tests/guided_guides.rs index c6c0484640..ab11a976cb 100644 --- a/crates/ui-egui/src/tests/guided_guides.rs +++ b/crates/ui-egui/src/tests/guided_guides.rs @@ -281,7 +281,10 @@ fn a_press_on_a_menu_over_a_guide_selects_nothing() { let r = h.request("ui.click", json!({"x": line.x - 30.0, "y": line.y - 30.0, "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.settle(SETTLE); - assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo"); + assert!( + craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), + "the context menu is open over the photo" + ); let img = h.app.image_rect.expect("the photo on screen"); let (lx, ly) = ((line.x - img.left()) / img.width(), (line.y - img.top()) / img.height()); let r = h.request("ui.pointer", json!({"events": [{"kind": "down", "x": lx, "y": ly}, {"kind": "up", "x": lx, "y": ly}]}), T); @@ -310,7 +313,10 @@ fn a_press_on_a_menu_over_an_endpoint_moves_nothing() { let r = h.request("ui.click", json!({"x": end.x - 30.0, "y": end.y - 30.0, "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.settle(SETTLE); - assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo"); + assert!( + craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), + "the context menu is open over the photo" + ); let img = h.app.image_rect.expect("the photo on screen"); let (ex, ey) = ((end.x - img.left()) / img.width(), (end.y - img.top()) / img.height()); let r = h.request( @@ -344,7 +350,10 @@ fn a_press_that_leaves_the_menu_in_one_frame_draws_nothing() { let r = h.request("ui.click", json!({"x": end.x - 30.0, "y": end.y - 30.0, "button": "right"}), T); assert_eq!(r["ok"], true, "{r}"); h.settle(SETTLE); - assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo"); + assert!( + craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), + "the context menu is open over the photo" + ); // one batch: go down 1px inside the menu, then straight off it to bare photo, far below // both guides, and release there — the current pointer never sees the menu again let img = h.app.image_rect.expect("the photo on screen"); diff --git a/crates/ui-egui/src/tests/library_problem.rs b/crates/ui-egui/src/tests/library_problem.rs index eee82ac5c0..ad9c28ea97 100644 --- a/crates/ui-egui/src/tests/library_problem.rs +++ b/crates/ui-egui/src/tests/library_problem.rs @@ -932,14 +932,7 @@ fn library_recovery_actions_155_retry_reaches_existing_switch_guard_without_disk let (keep_pending, rx) = std::sync::mpsc::channel(); let mut rx = Some(rx); h.app.services.picker = Some(Box::new(move |_| Ok(rx.take().expect("one fake pending picker")))); - let picked = crate::pick::ask( - &mut h.app, - "folder.move", - &json!({}), - "path", - crate::pick::PickRequest::folder("Fake pending move"), - |_| None, - ); + let picked = crate::pick::ask(&mut h.app, "folder.move", &json!({}), "path", crate::pick::PickRequest::folder("Fake pending move"), |_| None); assert!(matches!(picked, crate::pick::Picked::Later)); recovery_actions_155_click(&mut h, "button:libraryRetry"); let problem = h.app.library_problem.as_ref().expect("Retry keeps the error window"); diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 02aeea2914..a48e5c7107 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -1847,9 +1847,7 @@ fn the_masking_panel_has_no_widget_id_clashes() { h.settle(SETTLE); h.step(); let clashes = id_clash_warnings(&h); - let near = |p: egui::Pos2| { - h.app.widgets.iter().filter(|(_, r)| r.expand(6.0).contains(p)).map(|(w, _)| w.clone()).collect::>() - }; + let near = |p: egui::Pos2| h.app.widgets.iter().filter(|(_, r)| r.expand(6.0).contains(p)).map(|(w, _)| w.clone()).collect::>(); let said: Vec<_> = clashes.iter().map(|(t, p)| format!("{t} at {p:?} near {:?}", near(*p))).collect(); assert!(clashes.is_empty(), "{said:#?}"); } diff --git a/crates/ui-egui/src/tests/port_screenshots.rs b/crates/ui-egui/src/tests/port_screenshots.rs index d99cfba320..d6b71dbc3d 100644 --- a/crates/ui-egui/src/tests/port_screenshots.rs +++ b/crates/ui-egui/src/tests/port_screenshots.rs @@ -145,7 +145,10 @@ fn scenes() -> Vec<(&'static str, Scene)> { // the menu bar with a menu open, and the photo menu for title in ["File", "Edit", "Photo", "View", "Help"] { all.push(( - { let name: &'static str = Box::leak(format!("menubar-{}", title.to_lowercase()).into_boxed_str()); name }, + { + let name: &'static str = Box::leak(format!("menubar-{}", title.to_lowercase()).into_boxed_str()); + name + }, Box::new(move |h| { select(h, 2)?; ui(h, json!({"view": "photoGrid", "leftPanel": true}))?; @@ -252,9 +255,15 @@ fn scenes() -> Vec<(&'static str, Scene)> { all.push(open_dialog("dlg-whats-new", json!({"kind": "whatsNew"}))); all.push(open_dialog("dlg-welcome-1", json!({"kind": "welcome", "page": 0}))); all.push(open_dialog("dlg-welcome-3", json!({"kind": "welcome", "page": 2}))); - all.push(open_dialog("dlg-system-info", json!({"kind": "systemInfo", "rows": [["Version", "1.0"], ["Platform", "Linux"], ["Memory", "16 GiB"]]}))); + all.push(open_dialog( + "dlg-system-info", + json!({"kind": "systemInfo", "rows": [["Version", "1.0"], ["Platform", "Linux"], ["Memory", "16 GiB"]]}), + )); all.push(open_dialog("dlg-confirm-delete", json!({"kind": "confirmDelete", "count": 3}))); - all.push(open_dialog("dlg-remove-folder", json!({"kind": "removeFolder", "path": "/pics/trip", "name": "pics/trip", "count": 12, "disk": false}))); + all.push(open_dialog( + "dlg-remove-folder", + json!({"kind": "removeFolder", "path": "/pics/trip", "name": "pics/trip", "count": 12, "disk": false}), + )); all.push(open_dialog( "dlg-move-photos", json!({"kind": "movePhotos", "ids": [1, 2], "folder": "/pics/trip", "name": "trip", "dont_ask": false, "library": 0}), @@ -293,7 +302,10 @@ fn scenes() -> Vec<(&'static str, Scene)> { all.push(open_dialog("dlg-denoise-model", json!({"kind": "denoiseModel", "info": {}, "accepted": false}))); all.push(open_dialog("dlg-sam-model", json!({"kind": "samModel", "then": null}))); all.push(open_dialog("dlg-lens-database", json!({"kind": "lensDatabase", "dir": "/tmp/lens", "mirrors": []}))); - all.push(open_dialog("dlg-lightroom-catalog", json!({"kind": "lightroomCatalog", "folder": "/Lightroom", "catalog": "/Lightroom/Catalog.lrcat"}))); + all.push(open_dialog( + "dlg-lightroom-catalog", + json!({"kind": "lightroomCatalog", "folder": "/Lightroom", "catalog": "/Lightroom/Catalog.lrcat"}), + )); all.push(open_dialog( "dlg-lightroom-destination", json!({"kind": "lightroomDestination", "catalog": "/Lightroom/Catalog.lrcat", "library": "Photos", "photos": 120, "new_library": false, @@ -321,7 +333,8 @@ fn scenes() -> Vec<(&'static str, Scene)> { let _ = std::fs::remove_dir_all(&folder); std::fs::create_dir_all(folder.join("day 2")).map_err(|e| e.to_string())?; for i in 0..8usize { - let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [((x * 2 + i * 30) % 256) as u8, (y * 4 % 256) as u8, (60 + i * 25) as u8, 255]); + let img = + lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [((x * 2 + i * 30) % 256) as u8, (y * 4 % 256) as u8, (60 + i * 25) as u8, 255]); let png = lightcraft_engine::export::encode_image( &img, &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, @@ -378,7 +391,10 @@ fn port_screenshots() { let why = match done { Ok(Ok(())) => continue, Ok(Err(e)) => e, - Err(panic) => format!("panicked: {}", panic.downcast_ref::().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default()), + Err(panic) => format!( + "panicked: {}", + panic.downcast_ref::().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default() + ), }; eprintln!("SHOT-MISSING {file}: {why}"); missing.push(format!("{file}: {}", why.lines().next().unwrap_or(""))); diff --git a/crates/ui-egui/src/tests/rating.rs b/crates/ui-egui/src/tests/rating.rs index 6fe7de1472..fe7fd0d4a1 100644 --- a/crates/ui-egui/src/tests/rating.rs +++ b/crates/ui-egui/src/tests/rating.rs @@ -31,7 +31,12 @@ fn drive(click: Option, keys: &[egui::Key], build: impl Fn(&mut egui::Ui) -> let mut reported = Vec::new(); let mut nodes = Vec::new(); let mut rects: Vec<(String, Rect)> = Vec::new(); - let button = |at: Pos2, pressed: bool| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let button = |at: Pos2, pressed: bool| egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }; for frame in 0..10 { let mut events = Vec::new(); if let Some(n) = click { diff --git a/crates/ui-egui/src/tests/real_journey.rs b/crates/ui-egui/src/tests/real_journey.rs index 365459cd5a..4716a8593c 100644 --- a/crates/ui-egui/src/tests/real_journey.rs +++ b/crates/ui-egui/src/tests/real_journey.rs @@ -33,19 +33,12 @@ const EXPOSURE: f64 = 1.25; fn ask(h: &mut Headless, method: &str, params: Value) -> Value { let r = h.request(method, params.clone(), REQUEST); assert_eq!(r["ok"], true, "{method} {params}: {r}"); - assert!( - h.settle(SETTLE), - "{method}: UI did not settle within the bounded wait" - ); + assert!(h.settle(SETTLE), "{method}: UI did not settle within the bounded wait"); r["result"].clone() } fn execute(h: &mut Headless, command: &str, params: Value) -> Value { - ask( - h, - "engine.execute", - json!({"command": command, "params": params}), - ) + ask(h, "engine.execute", json!({"command": command, "params": params})) } /// What to do when the executor bound neither variable. @@ -60,20 +53,11 @@ fn fresh_root() -> PathBuf { let tmp = std::env::var_os("TMPDIR").expect(HOW_TO_RUN); let tmp = PathBuf::from(tmp); assert!(tmp.is_absolute()); - let tmp = tmp - .canonicalize() - .expect("private TMPDIR must already exist"); + let tmp = tmp.canonicalize().expect("private TMPDIR must already exist"); assert_ne!(tmp, Path::new("/tmp"), "never use the shared system tmp"); - let root = PathBuf::from( - std::env::var_os("LIGHTCRAFT_REAL_JOURNEY_ROOT") - .expect(HOW_TO_RUN), - ); + let root = PathBuf::from(std::env::var_os("LIGHTCRAFT_REAL_JOURNEY_ROOT").expect(HOW_TO_RUN)); assert!(root.is_absolute()); - assert_eq!( - root.parent(), - Some(tmp.as_path()), - "case must be a direct child of private TMPDIR" - ); + assert_eq!(root.parent(), Some(tmp.as_path()), "case must be a direct child of private TMPDIR"); let name = root.file_name().unwrap().to_str().unwrap(); assert!(name.starts_with("lc-real-journey-") && name.len() <= 100); // create_dir is intentionally create-new: an existing path/symlink is an error, not cleanup. @@ -85,18 +69,9 @@ fn fresh_root() -> PathBuf { fn fixture(path: &Path, variant: usize) -> Vec { let image = lightcraft_raster::Rgba8::from_fn(64, 48, |x, y| { // Dark, non-neutral, non-clipping gradients; each fixture has distinct bytes and pixels. - [ - (24 + x + variant * 19) as u8, - (16 + y + variant * 11) as u8, - (20 + (x + y) / 3 + variant * 7) as u8, - 255, - ] + [(24 + x + variant * 19) as u8, (16 + y + variant * 11) as u8, (20 + (x + y) / 3 + variant * 7) as u8, 255] }); - let bytes = lightcraft_codecs::encode_png( - &lightcraft_codecs::EncodeImage::rgba8(&image), - &lightcraft_codecs::EncodeMeta::default(), - ) - .unwrap(); + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&image), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::write(path, &bytes).unwrap(); bytes } @@ -107,19 +82,13 @@ fn headless(session: Session, out: &Path) -> Headless { local_places: Some(Vec::new()), // don't enumerate the host's home folder write: Some(Box::new(move |path, bytes| { let path = Path::new(path); - if path.parent() != Some(destination.as_path()) - || path.extension().and_then(|s| s.to_str()) != Some("png") - { + if path.parent() != Some(destination.as_path()) || path.extension().and_then(|s| s.to_str()) != Some("png") { return Err("journey export escaped its private PNG output folder".into()); } if bytes.len() > 1_048_576 { return Err("tiny-fixture output exceeded 1 MiB".into()); } - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(path) - .map_err(|e| e.to_string())?; + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| e.to_string())?; file.write_all(bytes).map_err(|e| e.to_string())?; file.sync_all().map_err(|e| e.to_string()) })), @@ -129,41 +98,22 @@ fn headless(session: Session, out: &Path) -> Headless { } fn photo(h: &Headless, id: PhotoId) -> Photo { - h.app - .session - .catalog - .photo(id) - .expect("exact imported photo id") - .as_ref() - .clone() + h.app.session.catalog.photo(id).expect("exact imported photo id").as_ref().clone() } fn selected(h: &Headless, chosen: PhotoId, other: PhotoId) { assert_eq!(h.app.session.selection.ids, vec![chosen]); assert_eq!(h.app.session.selection.active, Some(chosen)); assert!(!h.app.session.selection.ids.contains(&other)); - assert_eq!( - h.app.session.selection.state_of(chosen), - lightcraft_engine::SelectionState::Active - ); - assert_eq!( - h.app.session.selection.state_of(other), - lightcraft_engine::SelectionState::NotSelected - ); + assert_eq!(h.app.session.selection.state_of(chosen), lightcraft_engine::SelectionState::Active); + assert_eq!(h.app.session.selection.state_of(other), lightcraft_engine::SelectionState::NotSelected); } fn copied_path(p: &Photo, library: &Path, expected: &[u8]) -> PathBuf { - let Source::File { path } = &p.source else { - panic!("import must use a real file") - }; + let Source::File { path } = &p.source else { panic!("import must use a real file") }; let path = PathBuf::from(path).canonicalize().unwrap(); assert!(path.starts_with(library.join("Originals"))); - assert_eq!( - std::fs::read(&path).unwrap(), - expected, - "copied original bytes for {}", - p.file_name - ); + assert_eq!(std::fs::read(&path).unwrap(), expected, "copied original bytes for {}", p.file_name); assert_eq!((p.width, p.height), (64, 48)); assert!(p.content_hash.as_ref().is_some_and(|hash| hash.len() == 32)); path @@ -200,11 +150,7 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { let mut session = Session::new().with_fs(); assert!(session.open_library(&library, false).unwrap().created); - assert_eq!( - session.catalog.len(), - 0, - "no demo seed or memory-only catalog" - ); + assert_eq!(session.catalog.len(), 0, "no demo seed or memory-only catalog"); let mut h = headless(session, &out); // Explicit engine action: selected paths, not a directory scan or a host file picker. let imported = execute( @@ -215,62 +161,26 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { }), ); assert_eq!(imported["scanned"], 2, "{imported}"); - assert_eq!( - imported["imported"].as_array().unwrap().len(), - 2, - "{imported}" - ); + assert_eq!(imported["imported"].as_array().unwrap().len(), 2, "{imported}"); assert_eq!(imported["failed"], json!([]), "{imported}"); assert_eq!(imported["duplicates"], json!([]), "{imported}"); assert_eq!(h.app.session.catalog.len(), 2); - assert!( - !h.app - .session - .catalog - .photos() - .any(|p| p.file_name == "not-imported.png") - ); - let chosen = h - .app - .session - .catalog - .photos() - .find(|p| p.file_name == "chosen.png") - .unwrap() - .id; - let other = h - .app - .session - .catalog - .photos() - .find(|p| p.file_name == "unchosen.png") - .unwrap() - .id; + assert!(!h.app.session.catalog.photos().any(|p| p.file_name == "not-imported.png")); + let chosen = h.app.session.catalog.photos().find(|p| p.file_name == "chosen.png").unwrap().id; + let other = h.app.session.catalog.photos().find(|p| p.file_name == "unchosen.png").unwrap().id; assert_ne!(chosen, other); let chosen_copy = copied_path(&photo(&h, chosen), &library, &chosen_bytes); let other_copy = copied_path(&photo(&h, other), &library, &other_bytes); assert_ne!(chosen_copy, other_copy); let untouched = photo(&h, other); - ask( - &mut h, - "ui.set", - json!({"view": "photoGrid", "right": "edit"}), - ); + ask(&mut h, "ui.set", json!({"view": "photoGrid", "right": "edit"})); // Actual pointer activation of the exact photo's registered grid widget. - ask( - &mut h, - "ui.clickWidget", - json!({"id": format!("thumb:{}", chosen.0)}), - ); + ask(&mut h, "ui.clickWidget", json!({"id": format!("thumb:{}", chosen.0)})); selected(&h, chosen, other); execute(&mut h, "photo.rate", json!({"rating": 4})); // implicit selection, NOT explicit ids assert_eq!(photo(&h, chosen).rating, 4); - assert_eq!( - photo(&h, other), - untouched, - "rating must not affect the unchosen photo" - ); + assert_eq!(photo(&h, other), untouched, "rating must not affect the unchosen photo"); execute(&mut h, "library.filter", json!({"rating": 4})); assert_eq!(h.app.session.visible_cloned(), vec![chosen]); selected(&h, chosen, other); @@ -287,60 +197,31 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { assert_eq!(before_edit.develop.light.exposure, 0.0); let undo_count = h.app.session.undo.len(); // Actual widget click + text input + Enter, with no develop.set bypass. - ask( - &mut h, - "ui.clickWidget", - json!({"id": "sliderValue:light.exposure"}), - ); + ask(&mut h, "ui.clickWidget", json!({"id": "sliderValue:light.exposure"})); ask(&mut h, "ui.text", json!({"text": "1.25"})); ask(&mut h, "ui.key", json!({"key": "Enter"})); assert_eq!(photo(&h, chosen).develop.light.exposure, EXPOSURE); - assert_eq!( - h.app.session.undo.len(), - undo_count + 1, - "one committed typed-value edit" - ); + assert_eq!(h.app.session.undo.len(), undo_count + 1, "one committed typed-value edit"); let edited = photo(&h, chosen); assert_ne!(edited.develop, before_edit.develop); assert_eq!(photo(&h, other), untouched); let reference = export_photo(&mut h.app.session, chosen, &options, 1).unwrap(); let reference_pixels = png_pixels(&reference.bytes); - assert_ne!( - reference.bytes, baseline.bytes, - "Develop must change encoded output" - ); - assert_ne!( - reference_pixels, baseline_pixels, - "Develop must change actual decoded pixels, not just metadata" - ); - let energy = |img: &lightcraft_raster::Rgb32f| { - img.data - .iter() - .flatten() - .map(|v| f64::from(*v)) - .sum::() - }; - assert!( - energy(&reference_pixels) > energy(&baseline_pixels) * 1.1, - "positive Exposure must brighten the pixels" - ); + assert_ne!(reference.bytes, baseline.bytes, "Develop must change encoded output"); + assert_ne!(reference_pixels, baseline_pixels, "Develop must change actual decoded pixels, not just metadata"); + let energy = |img: &lightcraft_raster::Rgb32f| img.data.iter().flatten().map(|v| f64::from(*v)).sum::(); + assert!(energy(&reference_pixels) > energy(&baseline_pixels) * 1.1, "positive Exposure must brighten the pixels"); // Explicit engine Undo/Redo actions; no claim about OS keyboard accelerator handling. execute(&mut h, "edit.undo", json!({})); assert_eq!(photo(&h, chosen).develop, before_edit.develop); let undone = export_photo(&mut h.app.session, chosen, &options, 1).unwrap(); - assert_eq!( - undone.bytes, baseline.bytes, - "Undo restores exact rendered PNG bytes" - ); + assert_eq!(undone.bytes, baseline.bytes, "Undo restores exact rendered PNG bytes"); assert_eq!(h.app.session.undo.len(), undo_count); execute(&mut h, "edit.redo", json!({})); assert_eq!(photo(&h, chosen).develop, edited.develop); let redone = export_photo(&mut h.app.session, chosen, &options, 1).unwrap(); - assert_eq!( - redone.bytes, reference.bytes, - "Redo restores exact rendered PNG bytes" - ); + assert_eq!(redone.bytes, reference.bytes, "Redo restores exact rendered PNG bytes"); assert_eq!(h.app.session.undo.len(), undo_count + 1); assert_eq!(photo(&h, other), untouched); selected(&h, chosen, other); @@ -357,30 +238,12 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { let mut reopened = Session::new().with_fs(); assert!(!reopened.open_library(&library, false).unwrap().created); - assert_eq!( - reopened.library.as_ref().unwrap().dir, - library.canonicalize().unwrap() - ); - assert_eq!( - reopened.catalog.to_snapshot(), - document_before_close, - "whole persisted document, not a hand-built catalog" - ); - assert!( - reopened.undo.is_empty() && reopened.redo.is_empty(), - "Undo stacks are session-local, not persisted" - ); + assert_eq!(reopened.library.as_ref().unwrap().dir, library.canonicalize().unwrap()); + assert_eq!(reopened.catalog.to_snapshot(), document_before_close, "whole persisted document, not a hand-built catalog"); + assert!(reopened.undo.is_empty() && reopened.redo.is_empty(), "Undo stacks are session-local, not persisted"); let mut h = headless(reopened, &out); - assert_eq!( - photo(&h, chosen), - chosen_before_close, - "exact chosen identity/settings/rating/history from disk" - ); - assert_eq!( - photo(&h, other), - untouched, - "exact unchosen document remains unchanged" - ); + assert_eq!(photo(&h, chosen), chosen_before_close, "exact chosen identity/settings/rating/history from disk"); + assert_eq!(photo(&h, other), untouched, "exact unchosen document remains unchanged"); selected(&h, chosen, other); // view.json selection persisted; no selection injection after reopen copied_path(&photo(&h, chosen), &library, &chosen_bytes); copied_path(&photo(&h, other), &library, &other_bytes); @@ -388,11 +251,7 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { execute(&mut h, "library.filter", json!({"rating": 4})); assert_eq!(h.app.session.visible_cloned(), vec![chosen]); selected(&h, chosen, other); - assert_eq!( - std::fs::read_dir(&out).unwrap().count(), - 0, - "references never wrote delivery files" - ); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "references never wrote delivery files"); let mut params = options_json; params["dir"] = json!(out.to_string_lossy()); // No ids/path override: app.export must use the actual persisted selection. @@ -400,41 +259,17 @@ fn persistent_selected_import_develop_undo_redo_reopen_export() { let delivered = exported["files"].as_array().unwrap(); assert_eq!(delivered.len(), 1, "{exported}"); let target = out.join("chosen.png"); - assert_eq!( - delivered[0]["path"], - json!(target.to_string_lossy()), - "{exported}" - ); - assert_eq!( - ( - delivered[0]["width"].as_u64(), - delivered[0]["height"].as_u64() - ), - (Some(32), Some(24)) - ); + assert_eq!(delivered[0]["path"], json!(target.to_string_lossy()), "{exported}"); + assert_eq!((delivered[0]["width"].as_u64(), delivered[0]["height"].as_u64()), (Some(32), Some(24))); assert_eq!(delivered[0]["bytes"], json!(reference.bytes.len())); let bytes = std::fs::read(&target).unwrap(); - assert_eq!( - bytes, reference.bytes, - "fresh-Session selected-only disk delivery is byte-for-byte the edited reference" - ); + assert_eq!(bytes, reference.bytes, "fresh-Session selected-only disk delivery is byte-for-byte the edited reference"); assert_eq!(png_pixels(&bytes), reference_pixels); - let files: Vec<_> = std::fs::read_dir(&out) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!( - files, - vec![std::ffi::OsString::from("chosen.png")], - "no unselected output or hidden sidecars" - ); + let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(files, vec![std::ffi::OsString::from("chosen.png")], "no unselected output or hidden sidecars"); assert!(!out.join("unchosen.png").exists()); assert!(!out.join("not-imported.png").exists()); - assert_eq!( - photo(&h, chosen), - chosen_before_close, - "export does not edit the document" - ); + assert_eq!(photo(&h, chosen), chosen_before_close, "export does not edit the document"); assert_eq!(photo(&h, other), untouched); assert_eq!(std::fs::read(&chosen_input).unwrap(), chosen_bytes); assert_eq!(std::fs::read(&other_input).unwrap(), other_bytes); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 04dc7f8519..04ff97df1d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -686,7 +686,8 @@ pub fn labeled_dropdown(ui: &mut Ui, id: &str, label: &str, // keyboard focus and dismissal. Menu::new(name.to_owned()).id_salt(("labeled-dropdown", id)).values().opened_by(&r, Trigger::Click).show(ui, |ui, _| { for (i, (v, l, key)) in items.iter().enumerate() { - let mut row = MenuItem::new(crate::i18n::tr(l).replace('&', "&&")).id_salt(("labeled-dropdown-item", id, *key)).entry_checked(i == active); + let mut row = + MenuItem::new(crate::i18n::tr(l).replace('&', "&&")).id_salt(("labeled-dropdown-item", id, *key)).entry_checked(i == active); if i == active { row = row.default_stop(); } @@ -971,17 +972,17 @@ pub mod date_picker; mod menu_field; pub(crate) use menu_field::{menu_field, menu_field_with_id}; mod hit_area; +mod icon_button; #[cfg(test)] #[path = "widgets/tests_numeric_entry.rs"] mod numeric_entry_tests; pub mod progress; pub mod rating; -mod icon_button; mod slider; -pub(crate) use slider::{Row as SliderRow, field as slider_field, slider_row, slider_salted}; -pub use slider::{SliderOut, slider}; pub use hit_area::{HitArea, HitAreaOutput}; pub use icon_button::IconButtonOutput; +pub(crate) use slider::{Row as SliderRow, field as slider_field, slider_row, slider_salted}; +pub use slider::{SliderOut, slider}; mod text_button; pub mod text_field; pub use text_button::TextButtonOutput; diff --git a/crates/ui-egui/src/widgets/album_picker.rs b/crates/ui-egui/src/widgets/album_picker.rs index 016b00ac2c..bb38f42f7d 100644 --- a/crates/ui-egui/src/widgets/album_picker.rs +++ b/crates/ui-egui/src/widgets/album_picker.rs @@ -17,8 +17,8 @@ use craft::ui::contract::overlay::{Dismiss, Outside}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::controls::disclosure::DisclosureGlyph; use craft::ui::popover::Popover; -use craft::ui::runtime::focus::Initial; use craft::ui::primitives::{Glyph, HAlign, IconSpec}; +use craft::ui::runtime::focus::Initial; use egui::{Rect, Response, RichText, Ui, vec2}; use crate::icons::Icon; @@ -435,7 +435,15 @@ impl<'a> AlbumPicker<'a> { let by_id = index(entries); for i in &hits { let e = &entries[*i]; - row(ui, e, &path_in(entries, &by_id, e.id), 0.0, highlighted == Some(*i), (up || down) && highlighted == Some(*i), &mut picked); + row( + ui, + e, + &path_in(entries, &by_id, e.id), + 0.0, + highlighted == Some(*i), + (up || down) && highlighted == Some(*i), + &mut picked, + ); } } }); diff --git a/crates/ui-egui/src/widgets/date_picker.rs b/crates/ui-egui/src/widgets/date_picker.rs index d168d2777a..9fe4889554 100644 --- a/crates/ui-egui/src/widgets/date_picker.rs +++ b/crates/ui-egui/src/widgets/date_picker.rs @@ -370,7 +370,8 @@ impl<'a> DatePicker<'a> { if open { // open on the value (or today), at its precision when it is one of those offered let at = value.or(today).unwrap_or(PickedDate::year(2026)); - let fallback = if precisions.contains(&Precision::Day) { Precision::Day } else { precisions.first().copied().unwrap_or(Precision::Day) }; + let fallback = + if precisions.contains(&Precision::Day) { Precision::Day } else { precisions.first().copied().unwrap_or(Precision::Day) }; let precision = value.map(|v| v.precision()).filter(|p| precisions.contains(p)).unwrap_or(fallback); ui.data_mut(|d| { d.insert_temp(state, View::open(at, precision)); diff --git a/crates/ui-egui/src/widgets/rating.rs b/crates/ui-egui/src/widgets/rating.rs index 6ab4bf9a2c..83c668d676 100644 --- a/crates/ui-egui/src/widgets/rating.rs +++ b/crates/ui-egui/src/widgets/rating.rs @@ -157,12 +157,7 @@ pub fn favorite_button(ui: &mut Ui, widget: String, favorite: bool, name: &str) // the layout's room, sensing nothing: the framework button owns the pointer let (id, rect) = ui.allocate_space(vec2(side, side)); let star = FavoriteStar { favorite, lit: t.star, quiet: t.icon }; - let out = IconButton::new(IconSpec::glyph(&star)) - .id(id) - .label(name.to_owned()) - .tooltip(name.to_owned()) - .selected(favorite) - .show_at(ui, rect); + let out = IconButton::new(IconSpec::glyph(&star)).id(id).label(name.to_owned()).tooltip(name.to_owned()).selected(favorite).show_at(ui, rect); // (rows scrolled out of view can't be clicked) if ui.is_rect_visible(rect) && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) { crate::widgets::register_response(widget, rect, &out.response); diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index e70bd9edfd..d39b3075df 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -157,7 +157,11 @@ pub(crate) fn field(ui: &mut Ui, row: &Row<'_>) -> Shown { NumberCodec::new(Reader::new(), usize::from(spec.decimals)) .parse_with(move |text| super::typed_value(&number_spec, text)), ) - .scale(if spec.id == "wb.temp" { SliderScale::Custom { position: kelvin_position, value_at: kelvin_value_at } } else { SliderScale::Linear }) + .scale(if spec.id == "wb.temp" { + SliderScale::Custom { position: kelvin_position, value_at: kelvin_value_at } + } else { + SliderScale::Linear + }) .fill(false) .tooltip(crate::i18n::tr(VALUE_HINT).to_owned()) .enabled(enabled) @@ -186,7 +190,14 @@ pub(crate) fn field(ui: &mut Ui, row: &Row<'_>) -> Shown { /// Names the row's real parts for automation, says how to reset it, keeps the shortcut gate's slider focus and /// gives the value field back after a typed edit ends. Returns the track's id. -fn publish(ui: &Ui, row: &Row<'_>, id: egui::Id, name: &str, out: &SliderFieldOutput, record: &craft::ui::runtime::inspect::Recorded) -> Option { +fn publish( + ui: &Ui, + row: &Row<'_>, + id: egui::Id, + name: &str, + out: &SliderFieldOutput, + record: &craft::ui::runtime::inspect::Recorded, +) -> Option { let spec = row.spec; let ctx = ui.ctx(); let focused = craft::ui::runtime::focus::focused_rec(ctx); @@ -412,7 +423,8 @@ mod face { let index = (along.floor() as usize).min(segments - 1); if let (Some(from), Some(to)) = (self.stops.get(index), self.stops.get(index + 1)) { let color = crate::widgets::lerp(*from, *to, along - index as f32); - let strip = Rect::from_min_max(pos2(rect.left() + rect.width() * a, rect.top()), pos2(rect.left() + rect.width() * b, rect.bottom())); + let strip = + Rect::from_min_max(pos2(rect.left() + rect.width() * a, rect.top()), pos2(rect.left() + rect.width() * b, rect.bottom())); draw.data_fill(&PaintShape::Rect(strip, CornerRadius::ZERO), DataColor::new(color)); } } diff --git a/crates/ui-egui/src/widgets/tests_hit_area.rs b/crates/ui-egui/src/widgets/tests_hit_area.rs index f24f952736..7245c93716 100644 --- a/crates/ui-egui/src/widgets/tests_hit_area.rs +++ b/crates/ui-egui/src/widgets/tests_hit_area.rs @@ -59,9 +59,7 @@ impl Frames { /// A key pressed and released in one frame: the framework shows a focus ring only for focus a key reached, so a test /// that only asks for the focus paints none. fn key(key: egui::Key) -> Vec { - [true, false] - .map(|pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::NONE }) - .to_vec() + [true, false].map(|pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: egui::Modifiers::NONE }).to_vec() } /// An area's face fills the very rectangle its leaf paints the inset keyboard focus ring in: painted after the leaf, diff --git a/crates/ui-egui/src/widgets/text_button.rs b/crates/ui-egui/src/widgets/text_button.rs index 30cf71f67f..b6c598b965 100644 --- a/crates/ui-egui/src/widgets/text_button.rs +++ b/crates/ui-egui/src/widgets/text_button.rs @@ -164,4 +164,3 @@ pub(super) fn show(ui: &mut Ui, id: &str, label: &str, active: bool) -> TextButt #[cfg(test)] #[path = "tests_text_button.rs"] mod tests; - diff --git a/crates/ui-egui/src/widgets/text_field.rs b/crates/ui-egui/src/widgets/text_field.rs index 437d8d42a7..dc6d700c59 100644 --- a/crates/ui-egui/src/widgets/text_field.rs +++ b/crates/ui-egui/src/widgets/text_field.rs @@ -119,7 +119,8 @@ pub(crate) fn text_id(id: egui::Id) -> egui::Id { } fn has_focus(ctx: &egui::Context, id: egui::Id) -> bool { - craft::ui::runtime::focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == id || rec.stop.root == id) || ctx.memory(|m| m.has_focus(id) || m.has_focus(text_id(id))) + craft::ui::runtime::focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == id || rec.stop.root == id) + || ctx.memory(|m| m.has_focus(id) || m.has_focus(text_id(id))) } /// What a field remembers between passes: the pass it was last drawn in and whether an edit was under way. @@ -288,8 +289,8 @@ impl<'a> TextField<'a> { } // The field's own Cut / Copy / Paste menu takes the focus while it is open, but the edit goes on under it: the // typing stays, and Esc closes only the menu. - let editing = ending.is_none() - && (has_focus(ui.ctx(), id) || (real && was_editing(ui.ctx(), widget) && edit_menu_open(ui.ctx(), record.as_deref()))); + let editing = + ending.is_none() && (has_focus(ui.ctx(), id) || (real && was_editing(ui.ctx(), widget) && edit_menu_open(ui.ctx(), record.as_deref()))); if real { ui.data_mut(|d| d.insert_temp(id.with("memo"), Memo { editing, pass })); } diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index ae5492e0e6..04cff72eb3 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -16,15 +16,18 @@ fn harness(state: Option, width: f32, scale: f32) -> Harness<'static, L app.ui.left_panel = true; app.ui.right = RightPanel::Edit; } - let mut h = Harness::builder().with_size(vec2(width, 900.0)).with_pixels_per_point(scale) + let mut h = Harness::builder() + .with_size(vec2(width, 900.0)) + .with_pixels_per_point(scale) // the framework runtime (docking, keys, AccessKit) installs before the first pass, as the app's host does - .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)).build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) + .build_ui_state( + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(8); h } diff --git a/crates/ui-egui/tests/it/landmarks.rs b/crates/ui-egui/tests/it/landmarks.rs index caf5056c96..378a9ded1b 100644 --- a/crates/ui-egui/tests/it/landmarks.rs +++ b/crates/ui-egui/tests/it/landmarks.rs @@ -14,15 +14,17 @@ fn harness(view: ViewMode) -> Harness<'static, LightcraftApp> { app.ui.left_panel = true; app.ui.view = view; app.ui.right = RightPanel::Edit; - let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)) + let mut h = Harness::builder() + .with_size(vec2(1500.0, 950.0)) // the framework runtime (docking, keys, AccessKit) installs before the first pass, as the app's host does - .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)).build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) + .build_ui_state( + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); h } @@ -74,15 +76,17 @@ fn an_empty_filmstrip_is_still_a_landmark_and_says_why() { app.ui.left_panel = true; app.ui.view = ViewMode::Detail; app.ui.right = RightPanel::Edit; - let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)) + let mut h = Harness::builder() + .with_size(vec2(1500.0, 950.0)) // the framework runtime (docking, keys, AccessKit) installs before the first pass, as the app's host does - .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)).build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) + .build_ui_state( + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); assert_eq!(count(&h, Role::Region, "Filmstrip"), 1, "the empty strip is still a landmark"); let said = h diff --git a/crates/ui-egui/tests/it/local_places.rs b/crates/ui-egui/tests/it/local_places.rs index cb121ef650..a56f8c663f 100644 --- a/crates/ui-egui/tests/it/local_places.rs +++ b/crates/ui-egui/tests/it/local_places.rs @@ -42,12 +42,12 @@ fn harness(places: Vec<(String, String)>, kept: Vec) -> Harness<'static, .with_size(vec2(1000.0, 800.0)) .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) .build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(8); h } diff --git a/crates/ui-egui/tests/it/sidebar_names.rs b/crates/ui-egui/tests/it/sidebar_names.rs index 2b42085966..ea305b4578 100644 --- a/crates/ui-egui/tests/it/sidebar_names.rs +++ b/crates/ui-egui/tests/it/sidebar_names.rs @@ -21,12 +21,12 @@ fn sidebar() -> Harness<'static, LightcraftApp> { .with_size(vec2(1500.0, 950.0)) .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) .build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); h } @@ -64,12 +64,12 @@ fn a_month_triangle_names_its_year() { .with_size(vec2(1500.0, 950.0)) .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) .build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); for year in ["Expand 2025", "Expand 2026"] { h.get_by_label(year).click(); @@ -104,12 +104,12 @@ fn a_keyword_list_triangle_names_its_keyword() { .with_size(vec2(1500.0, 950.0)) .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) .build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); let names = button_names(&h); assert!(names.iter().any(|n| n == "Collapse Trips"), "the open keyword's triangle: {names:?}"); diff --git a/crates/ui-egui/tests/it/thumb_size_slider.rs b/crates/ui-egui/tests/it/thumb_size_slider.rs index d34f67ee7a..042be46b7d 100644 --- a/crates/ui-egui/tests/it/thumb_size_slider.rs +++ b/crates/ui-egui/tests/it/thumb_size_slider.rs @@ -20,12 +20,12 @@ fn grid() -> Harness<'static, LightcraftApp> { .with_size(vec2(1500.0, 950.0)) .with_context_setup(|ctx| LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()).install_framework(ctx)) .build_ui_state( - |ui, app: &mut LightcraftApp| { - app.logic(&ui.ctx().clone()); - app.ui(ui); - }, - app, - ); + |ui, app: &mut LightcraftApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); h.run_steps(10); h }