Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Merge branch 'main' of https://github.com/storytold/lightcraft into space-hold-pan

helgehelge123840e33a31184
diff --cc crates/ui-egui/src/app.rs
index 000000000,30a672c52..8968bd908
mode 000000,100644..100644
--- a/crates/ui-egui/src/app.rs
+++ b/crates/ui-egui/src/app.rs
@@@ -1,0 -1,626 +1,627 @@@
+ use super::clock::{AppClock, monotonic_ms};
+ use super::services::Services;
+ use super::state::{GestureFrame, InjectedDrop, InjectedPress};
+ use super::*;
+
+ mod control;
+ mod frame;
+ mod input;
+ mod prefs;
+ mod screenshot;
+
+ #[cfg(test)]
+ pub(crate) use frame::import_tick_allowed;
+ #[cfg(test)]
+ pub(crate) use screenshot::shot_ready;
+
+ impl LightcraftApp {
+ /// Build the app with default UI, renderer, cache and control state, and move AI segmentation
+ /// to a worker so frames apply results instead of waiting.
+ pub fn new(mut session: Session, services: Services) -> Self {
+ // AI mask requests run on the model's worker; frames apply their results (never wait)
+ session.segmenter.background = true;
+ Self {
+ session,
+ ui: UiState::default(),
+ services,
+ renderer: render::Renderer::default(),
+ perf: Perf::default(),
+ caches: Caches::default(),
+ integrated_titlebar: false,
+ window_movable: None,
+ native_menu: false,
+ native_shortcuts: Default::default(),
+ recording_shortcut: None,
+ text_focus: false,
+ headless_host: false,
+ notices: vec![],
+ updates_rt: Default::default(),
+ quit_prompt: None,
+ notice_input: Default::default(),
+ quit_confirmed: false,
+ control_rx: None,
+ pending_screenshots: vec![],
+ pending_gestures: vec![],
+ layout_epoch: 0,
+ screenshot_token: 0,
+ shot_bytes: 0,
+ shot_geometry_epoch: 0,
+ last_shot_geometry: None,
+ max_texture_side: MAX_TEXTURE_SIDE,
+ clock: AppClock::new(),
+ accesskit_language: None,
+ slideshow_hidden_at: None,
+ slideshow_auto_paused: false,
+ dropped_files: vec![],
+ synthetic_in_flight: false,
+ ui_passes: 0,
+ #[cfg(test)]
+ library_passes: vec![],
+ shadow: None,
+ synthetic: vec![],
+ pointer_cleanup: false,
+ drop_hover: vec![],
+ drop_pending: vec![],
+ copied: None,
+ pending_picks: vec![],
+ synthetic_mods: egui::Modifiers::NONE,
+ synthetic_mods_release: false,
+ host_mods: egui::Modifiers::NONE,
+ styled: false,
+ font_language: i18n::Locale::En,
+ chinese_font: None,
+ fonts_ready: false,
+ last_time: 0.0,
+ canvas_rect: None,
+ image_rect: None,
+ grid_scroll: None,
+ film_scroll: None,
+ widgets: vec![],
+ widget_hits: vec![],
+ next_widgets: vec![],
+ next_widget_hits: vec![],
+ gesture: None,
++ space_hand: None,
+ brush_live: None,
+ loupe_shown: None,
+ region_view: None,
+ region_before_view: None,
+ size_hold: Default::default(),
+ drag_scale: Default::default(),
+ window_refused: None,
+ region_tiles: Default::default(),
+ compare_windows: [None; 2],
+ compare_tiles: Default::default(),
+ compare_hold_until: f64::NEG_INFINITY,
+ merge: merge::MergeState::default(),
+ import: None,
+ scan: None,
+ sync: None,
+ sync_owns_changes: false,
+ sync_run: None,
+ lightroom: None,
+ lightroom_last: None,
+ lightroom_result: None,
+ review_pending: None,
+ shown_library: None,
+ export: None,
+ tasks: Default::default(),
+ last_export_result: None,
+ slideshow_export_reported: true,
+ hover_preview: None,
+ window_is_fullscreen: false,
+ gpu_applied: None,
+ gpu_notice: false,
+ memory_applied: None,
+ display_applied: None,
+ display_error: None,
+ screen_profile: None,
+ screen_profile_read: None,
+ library_problem: None,
+ library_window_input: Default::default(),
+ alt_asks_for_library: false,
+ recent_checks: Default::default(),
+ activity_expanded: false,
+ model_setup: Default::default(),
+ }
+ }
+
+ /// Supply the browser's separately downloaded Simplified Chinese font before the first frame.
+ pub fn with_chinese_font(mut self, bytes: Vec<u8>) -> Self {
+ if !bytes.is_empty() {
+ self.chinese_font = Some(std::sync::Arc::new(egui::FontData::from_owned(bytes)));
+ }
+ self
+ }
+
+ /// Attach the control-channel receiver and keep CPU copies of photo textures, which headless
+ /// screenshots need; returns the app for chaining.
+ pub fn with_control(mut self, rx: Receiver<ControlRequest>) -> Self {
+ self.control_rx = Some(rx);
+ // keep CPU copies of photo textures so `ui.screenshot {"headless": true}` can draw them
+ self.renderer.keep_pixels = true;
+ self
+ }
+
+ /// Seconds on the app's monotonic clock. Every timer that must advance while the window is
+ /// hidden (imports, autosave, playback, toasts, captures) uses this, never `i.time`.
+ pub fn tick_now(&self) -> f64 {
+ self.clock.now()
+ }
+
+ /// The app clock in milliseconds, for control deadlines and timers.
+ fn tick_now_ms(&self) -> f64 {
+ self.clock.now() * 1000.0
+ }
+
+ /// Give a headless driver its simulated time (`None` returns to the monotonic host clock).
+ pub fn set_simulated_clock(&mut self, seconds: Option<f64>) {
+ self.clock.simulated = seconds.filter(|s| s.is_finite() && *s >= 0.0);
+ }
+
+ /// The open person page, the way back to it, and the photo it was opened from follow a rename.
+ fn follow_renamed_person(&mut self, from: &str, to: &str) {
+ let same = |n: &str| n.trim().to_lowercase() == from.trim().to_lowercase();
+ if self.ui.person_page.as_deref().is_some_and(same) {
+ self.ui.person_page = Some(to.to_string());
+ }
+ if self.ui.last_person.as_deref().is_some_and(same) {
+ self.ui.last_person = Some(to.to_string());
+ }
+ if let Some((Some(name), photo)) = self.ui.person_from.clone()
+ && same(&name)
+ {
+ self.ui.person_from = Some((Some(to.to_string()), photo));
+ }
+ }
+
+ /// Run a UI or engine command by id. The single entry point for every frontend path.
+ pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
+ self.run_typed(id, params).map_err(|e| e.message)
+ }
+
+ /// [`LightcraftApp::run`], keeping what kind of error a refusal is: for code that decides on it
+ /// (offer a model's download, treat a cancel as one) instead of reading the message.
+ pub fn run_typed(&mut self, id: &str, params: Value) -> Result<Value, CommandError> {
+ if let Some(result) = model_setup::intercept(self, id, &params) {
+ return result.map_err(CommandError::from);
+ }
+ if let Some(r) = menus::run_ui_command(self, id, &params) {
+ if r.is_ok() {
+ docking::reveal_command(self, id)?;
+ }
+ return r.map_err(CommandError::from);
+ }
+ let params = if id == "crop.aspect"
+ && params.get("aspect").and_then(Value::as_str) == Some("toggle")
+ && self.crop_tool_aspect().is_some()
+ && self.session.active().and_then(|id| self.session.develop_of(id)).is_some_and(|d| d.crop == lightcraft_develop::Crop::default())
+ {
+ serde_json::json!({"aspect": "free"})
+ } else {
+ params
+ };
+ let r = self.session.execute(id, &params).map_err(CommandError::from);
+ if r.is_ok() && matches!(id, "crop.aspect" | "crop.rotateAspect") {
+ self.ui.crop_default_aspect = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("original") {
+ Some(serde_json::json!("original"))
+ } else {
+ self.session
+ .active()
+ .and_then(|photo| self.session.develop_of(photo))
+ .map(|d| d.crop.aspect.map_or(serde_json::json!("free"), |(w, h)| serde_json::json!([w as f64 / 100.0, h as f64 / 100.0])))
+ };
+ }
+ if r.is_ok() && id == "library.toggleFilters" {
+ // the search field shows the text filter: empty while the filters are off, back with them
+ self.ui.search = self.session.filter.text.clone();
+ }
+ if r.is_ok() && id == "library.clearFilter" {
+ // the search field shows the text filter: cleared from anywhere (the loupe's pill, the
+ // menu), it must not keep a search that no longer applies (issue #1648)
+ self.ui.search.clear();
+ }
+ if r.is_ok() && id == "mask.adjust" {
+ // Judge local adjustments on the photo, without the selection overlay obscuring them.
+ // Keep it hidden after release; O / the overlay eye can show it again.
+ self.ui.mask_overlay = false;
+ }
+ if r.is_ok() && matches!(id, "mask.add" | "mask.addComponent" | "mask.duplicate" | "mask.select") {
+ // A new or newly picked mask shows its overlay again, as in Lightroom: hidden by a slider
+ // drag above, it stayed hidden while the Overlay menu still named a mode (issue #1800).
+ self.ui.mask_overlay = true;
+ }
+ if r.is_ok() {
+ // These commands finish synchronously, so their completion would otherwise
+ // be invisible once the activity stack is gone. Never show success on error.
+ let completed = match id {
+ "library.compact" => Some(format!("✓ {}", i18n::tr("Optimize Library"))),
+ "library.clearPreviews" => Some(format!("✓ {}", i18n::tr("Discard Preview Cache"))),
+ "develop.autoSync" => Some(format!("{}: {}", i18n::tr("Auto Sync"), i18n::tr(if self.session.auto_sync { "On" } else { "Off" }))),
+ _ => None,
+ };
+ if let Some(message) = completed {
+ let now = self.tick_now();
+ self.ui.toast = Some((message, now + TOAST_SECONDS, None));
+ }
+ }
+ if r.is_ok() && id == "photo.label" {
+ let label = params.get("label").and_then(Value::as_str).and_then(lightcraft_catalog::ColorLabel::parse);
+ let text = match label {
+ Some(label) => {
+ let name =
+ self.session.catalog.custom_label_name(label).map(str::to_owned).unwrap_or_else(|| i18n::tr(&format!("{label:?}")).into());
+ i18n::tr_format!("{name} Label", name = name)
+ }
+ None => i18n::tr("Color label cleared").into(),
+ };
+ let now = self.tick_now();
+ self.ui.toast = Some((text, now + TOAST_SECONDS, label));
+ }
+ match &r {
+ Err(e) => {
+ log::warn!("{id}: {e}");
+ self.ui.status = e.message.clone();
+ // no detector yet: offer it (its terms first) instead of only saying so
+ if id == "faces.detect" && e.kind == ErrorKind::ModelMissing(AiModel::FaceDetector) {
+ panels::faces::offer_detector(self);
+ }
+ }
+ Ok(v) if id == "faces.detect" => self.ui.status = detect_summary(v),
+ Ok(v) if id == "faces.renamePerson" => {
+ let to = v["to"].as_str().unwrap_or("").to_string();
+ let from = params.get("from").and_then(Value::as_str).unwrap_or("");
+ if !to.is_empty() {
+ self.follow_renamed_person(from, &to);
+ }
+ }
+ Ok(_) => {}
+ }
+ r
+ }
+
+ /// The remembered ratio belongs to the tool until the user starts editing the crop.
+ pub(crate) fn crop_tool_aspect(&self) -> Option<(u32, u32)> {
+ let photo = self.session.active()?;
+ let d = self.session.develop_of(photo)?;
+ if d.crop != lightcraft_develop::Crop::default() {
+ return d.crop.aspect;
+ }
+ // nothing chosen yet: locked to the photo's own shape, as Lightroom starts (#991); one
+ // Lock toggle (remembered as "free") unlocks it for good
+ let remembered = self.ui.crop_default_aspect.clone().unwrap_or_else(|| Value::String("original".into()));
+ match &remembered {
+ Value::String(s) if s == "original" => {
+ let p = self.session.catalog.photo(photo)?;
+ let (w, h) = (p.width.max(1).saturating_mul(100), p.height.max(1).saturating_mul(100));
+ Some(if d.orientation.swaps_axes() { (h, w) } else { (w, h) })
+ }
+ Value::Array(a) => {
+ let number = |i: usize| {
+ let v = a.get(i)?.as_f64()? * 100.0;
+ (v.is_finite() && v >= 1.0 && v <= f64::from(u32::MAX)).then_some(v.round() as u32)
+ };
+ Some((number(0)?, number(1)?))
+ }
+ _ => None,
+ }
+ }
+
+ /// Called only after a crop gesture begins, inside its undo transaction.
+ pub(crate) fn begin_crop(&mut self) -> Result<(), String> {
+ // nothing chosen yet: the photo's own shape, as `crop_tool_aspect` shows it
+ let aspect = self.ui.crop_default_aspect.clone().unwrap_or_else(|| serde_json::json!("original"));
+ if self.session.interaction.is_some()
+ && self.session.active().and_then(|id| self.session.develop_of(id)).is_some_and(|d| d.crop == lightcraft_develop::Crop::default())
+ && aspect != serde_json::json!("free")
+ // the remembered ratio, turned like the new photo's crop (as a named ratio is)
+ && let Err(e) = self.session.execute("crop.aspect", &serde_json::json!({"aspect": aspect, "orientation": "crop"}))
+ {
+ // A remembered value the command refuses (a hand-edited settings file) would refuse
+ // every crop drag on an untouched photo: forget it and let this drag go ahead.
+ self.ui.crop_default_aspect = None;
+ self.ui.status = e.to_string();
+ }
+ Ok(())
+ }
+
+ /// Advance a running slideshow, but not while the window is hidden: in 0.36 `i.time` froze
+ /// there, and a minimized show must not keep waking the event loop or requesting full-size
+ /// slide renders overnight. Playback is auto-paused on hide and resumed on unhide with the
+ /// slide's remaining time preserved.
+ fn slideshow_tick(&mut self, ctx: &egui::Context, now: f64) {
+ let hidden = ctx.input(|i| i.viewport().visible() == Some(false));
+ let Some(run) = self.ui.slideshow.as_mut() else {
+ self.slideshow_hidden_at = None;
+ self.slideshow_auto_paused = false;
+ return;
+ };
+ if hidden {
+ if self.slideshow_hidden_at.is_none() {
+ self.slideshow_hidden_at = Some(now);
+ if !run.play.is_paused() {
+ run.play.toggle_pause(now);
+ self.slideshow_auto_paused = true;
+ }
+ }
+ return;
+ }
+ if self.slideshow_hidden_at.take().is_some() && self.slideshow_auto_paused {
+ self.slideshow_auto_paused = false;
+ if run.play.is_paused() {
+ run.play.toggle_pause(now);
+ }
+ }
+ panels::slideshow::tick(self, ctx, now);
+ }
+
+ /// Announce the end of a Build Previews run.
+ fn preview_build_status(&mut self, ctx: &egui::Context) {
+ use std::sync::atomic::Ordering;
+ let Some(b) = self.session.preview_build.clone() else { return };
+ let key = std::sync::Arc::as_ptr(&b) as usize;
+ if b.finished.load(Ordering::Relaxed) {
+ if self.ui.preview_build_seen != Some((key, true)) {
+ self.ui.preview_build_seen = Some((key, true));
+ let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed));
+ let plural = if done == 1 { "" } else { "s" };
+ let mut msg = match (b.error(), b.what) {
+ (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }),
+ (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural),
+ (None, what) => {
+ crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what))
+ }
+ };
+ if failed > 0 {
+ msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed));
+ }
+ self.toast(ctx, msg);
+ }
+ } else {
+ // The activity stack shows the run while it works; poll for the end.
+ ctx.request_repaint_after(std::time::Duration::from_millis(250));
+ }
+ }
+
+ /// Announce when saving the library starts failing (changes then live only in memory and are
+ /// retried) and when it works again; the top bar's cloud icon shows the state meanwhile.
+ fn save_status(&mut self, ctx: &egui::Context) {
+ let unsaved = self.session.unsaved().map(|(n, e)| (n, e.to_string()));
+ match (unsaved, self.ui.unsaved_seen) {
+ (Some((n, e)), false) => {
+ self.ui.unsaved_seen = true;
+ let t = self.tick_now();
+ self.ui.toast = Some((
+ crate::i18n::tr_format!(
+ "{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry",
+ if n == 1 { "" } else { "s" },
+ n = n,
+ e = e
+ ),
+ t + 6.0,
+ None,
+ ));
+ }
+ (None, true) => {
+ self.ui.unsaved_seen = false;
+ self.toast(ctx, crate::i18n::tr("Library saved"));
+ }
+ (Some(_), true) => ctx.request_repaint_after(std::time::Duration::from_secs(2)), // retry
+ (None, false) => {}
+ }
+ }
+
+ pub fn toast(&mut self, ctx: &egui::Context, text: impl Into<String>) {
+ self.toast_for(ctx, text, TOAST_SECONDS);
+ }
+
+ /// Auto straighten (the crop panel's Auto, a double-click with the Straighten tool), saying so
+ /// when it finds nothing to level by instead of leaving the photo as it is without a word.
+ pub fn auto_straighten(&mut self, ctx: &egui::Context) {
+ match self.run("crop.autoStraighten", serde_json::json!({})) {
+ Ok(r) if r.get("changed").and_then(Value::as_bool) == Some(false) => {
+ self.toast(ctx, crate::i18n::tr("No horizon or vertical lines to level by"));
+ }
+ Ok(_) => {}
+ Err(e) => self.toast(ctx, e),
+ }
+ }
+
+ /// A toast that stays `secs` seconds (messages that say where to look or what to do next).
+ pub fn toast_for(&mut self, _ctx: &egui::Context, text: impl Into<String>, secs: f64) {
+ let t = self.tick_now();
+ self.ui.toast = Some((text.into(), t + secs, None));
+ }
+
+ /// Reverse geocoding: say how a place-names download ended (a failure stays readable, with what to do).
+ fn place_names_outcome(&mut self, ctx: &egui::Context) {
+ use lightcraft_engine::cmd::geocode::DownloadOutcome;
+ match self.session.place_names.take_outcome() {
+ Some(DownloadOutcome::Done(_)) => self.toast(ctx, crate::i18n::tr("Place names downloaded")),
+ Some(DownloadOutcome::Cancelled) => self.toast(ctx, crate::i18n::tr("Place names download cancelled")),
+ Some(DownloadOutcome::Failed(e)) => self.toast_error(ctx, e),
+ None if self.session.place_names.downloading() => ctx.request_repaint_after(std::time::Duration::from_millis(500)),
+ None => {}
+ }
+ }
+
+ /// AI masks: apply finished background requests (clicks, descriptions, detail passes) and
+ /// show their errors; start a zoomed-in detail pass once the clicking stops
+ /// (`ui.detail_due`); watch the model download. Never waits for the model.
+ fn ai_mask_detail(&mut self, ctx: &egui::Context, now: f64) {
+ let polled = self.session.segment_poll();
+ if polled.changed {
+ ctx.request_repaint();
+ }
+ if let Some(mask) = polled.refine {
+ // a new selection from a click or a description: show it, as `run` does for new masks
+ self.ui.mask_overlay = true;
+ self.ui.detail_due = Some((now + 0.3, mask));
+ }
+ if let Some(e) = polled.messages.into_iter().last() {
+ self.ai_error(ctx, e, None);
+ }
+ let seg = &self.session.segmenter;
+ if seg.busy() || seg.pending_clicks().is_some() {
+ ctx.request_repaint_after(std::time::Duration::from_millis(50));
+ }
+ let download = seg.download_status();
+ if download.running {
+ ctx.request_repaint_after(std::time::Duration::from_millis(250));
+ }
+ // a download finishing while its dialog is closed: say so once
+ if self.ui.sam_downloading && !download.running {
+ self.ui.sam_downloading = false;
+ let open = matches!(self.ui.dialog, Some(state::Dialog::SamModel { .. }));
+ match sam_download_ended(&download) {
+ _ if open => {}
+ Some((text, true)) => self.toast_error(ctx, text),
+ Some((text, false)) => self.toast(ctx, text),
+ None => {}
+ }
+ }
+ if let Some((due, mask)) = self.ui.detail_due {
+ if now >= due && !self.session.segmenter.busy() && !self.session.segmenter.detail_busy() {
+ self.ui.detail_due = None;
+ if let Err(e) = self.run("mask.refineDetail", serde_json::json!({"id": mask})) {
+ log::warn!("detail pass: {e}");
+ }
+ } else {
+ ctx.request_repaint_after(std::time::Duration::from_millis(150));
+ }
+ }
+ if self.session.segmenter.detail_busy() {
+ ctx.request_repaint_after(std::time::Duration::from_millis(200));
+ }
+ }
+
+ /// An AI mask error: when the model isn't installed, the dialog that offers to download it
+ /// (`then`: the AI mask to start afterwards); otherwise a toast. Decided on the error's kind
+ /// ([`ErrorKind::ModelMissing`]), not its words.
+ pub fn ai_error(&mut self, ctx: &egui::Context, e: impl Into<CommandError>, then: Option<(&str, &str)>) {
+ let e = e.into();
+ if lightcraft_engine::segment::Segmenter::AVAILABLE && e.kind == ErrorKind::ModelMissing(AiModel::Sam3) {
+ self.offer_sam_download(then);
+ } else {
+ self.toast_error(ctx, e.message);
+ }
+ }
+
+ /// Open the dialog offering the SAM 3 download (never downloads by itself).
+ pub fn offer_sam_download(&mut self, then: Option<(&str, &str)>) {
+ if self.ui.dialog.is_none() || matches!(self.ui.dialog, Some(state::Dialog::SamModel { .. })) {
+ self.ui.dialog = Some(state::Dialog::SamModel { then: then.map(|(k, o)| (k.to_string(), o.to_string())), error: None });
+ }
+ }
+
+ /// A toast for an error the user has to read and act on (stays 6 s).
+ pub fn toast_error(&mut self, _ctx: &egui::Context, text: impl Into<String>) {
+ let t = self.tick_now();
+ self.ui.toast = Some((text.into(), t + 6.0, None));
+ }
+
+ /// The process is about to end (settings and library are saved by then): make sure nothing is
+ /// inside the GPU driver when it does (issue #620: a render running on a worker thread while
+ /// the process exits crashes in the driver). No GPU work starts from here on; the render
+ /// workers get up to `timeout` to finish their jobs, and what is left of it goes to GPU work
+ /// on other threads (export, denoise, the device warm-up). `false`: the deadline passed first
+ /// (the host exits anyway). The app renders nothing afterwards.
+ pub fn shutdown(&mut self, timeout: std::time::Duration) -> bool {
+ lightcraft_engine::gpu::begin_shutdown();
+ #[cfg(not(target_arch = "wasm32"))]
+ let t0 = std::time::Instant::now();
+ let stopped = self.renderer.shutdown(timeout);
+ #[cfg(not(target_arch = "wasm32"))]
+ let timeout = timeout.saturating_sub(t0.elapsed());
+ let idle = lightcraft_engine::gpu::wait_idle(timeout);
+ stopped && idle
+ }
+
+ /// Background and queue work. Called before layout on every host pass and, while the window is
+ /// hidden, from `Context::run_logic`. It may read the refreshed viewport fields only: never
+ /// `i.time`, events, keys or dropped files.
+ pub fn logic(&mut self, ctx: &egui::Context) {
+ i18n::set_language(self.ui.language);
+ // The fork's AccessKit root language and bidi runs follow the locale; presentation only.
+ // Compare against the cached string: `Context::language()` allocates on every call, and
+ // this runs on every UI pass and every hidden logic tick.
+ let language = self.ui.language.code();
+ if self.accesskit_language.as_deref() != Some(language) {
+ ctx.set_language(Some(language.to_owned()));
+ self.accesskit_language = Some(language.to_owned());
+ }
+ let t0 = monotonic_ms();
+ self.note_max_texture_side(ctx);
+ self.note_shot_geometry(ctx);
+ self.ensure_fonts(ctx);
+ // Applying the theme belongs to logic: a host that only calls `logic` (and every hidden
+ // tick) must see an Appearance Mode / system-theme change, and the UI pass that follows
+ // then draws with the new visuals. `ui` keeps its own call for a settings change made by
+ // a command during the same pass; it is a no-op when the theme already matches.
+ self.sync_theme(ctx);
+ self.logic_background(ctx);
+ self.perf.logic_ms = monotonic_ms() - t0;
+ }
+
+ /// Frame timings once layout is done (`t0`: when layout started).
+ fn end_frame(&mut self, ctx: &egui::Context, t0: f64) {
+ if self.ui.frame_rate {
+ frame_rate::show(ctx, self);
+ } else {
+ frame_rate::forget(ctx);
+ }
+ panels::edit::wheel_pointer_frame_end(ctx);
+ ctx.output(|o| {
+ for c in &o.commands {
+ if let egui::OutputCommand::CopyText(text) = c {
+ self.copied = Some(text.clone());
+ }
+ }
+ });
+ self.perf.frame_ms = monotonic_ms() - t0;
+ self.perf.update_ms = self.perf.logic_ms + self.perf.frame_ms;
+ self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms);
+ }
+
+ /// Lay out the whole window: input/setup for the known UI phase, then presentation, then the
+ /// frame bookkeeping. A hidden `run_logic` never reaches this.
+ pub fn ui(&mut self, ui: &mut egui::Ui) {
+ i18n::set_language(self.ui.language);
+ let ctx = ui.ctx().clone();
+ if !self.fonts_ready {
+ ctx.request_repaint();
+ return;
+ }
+ self.sync_theme(&ctx);
+ self.ui_pass(&ctx);
+ self.draw_window(ui);
+ self.finish_ui_pass(&ctx);
+ }
+ }
+
+ /// "Found 3 faces in 2 photos" for a `faces.detect` result.
+ pub(crate) fn detect_summary(v: &Value) -> String {
+ let photos = v["photos"].as_array().map(Vec::as_slice).unwrap_or_default();
+ let counts: Vec<usize> = photos.iter().map(|p| p["faces"].as_array().map_or(0, Vec::len)).collect();
+ let (faces, with) = (counts.iter().sum::<usize>(), counts.iter().filter(|n| **n > 0).count());
+ let plural = |n: usize, w: &str| format!("{n} {w}{}", if n == 1 { "" } else { "s" });
+ match (faces, photos.len()) {
+ (0, 1) => "No faces found".into(),
+ (0, n) => format!("No faces found in {}", plural(n, "photo")),
+ (f, 1) => format!("Found {}", plural(f, "face")),
+ (f, _) => format!("Found {} in {}", plural(f, "face"), plural(with, "photo")),
+ }
+ }
+
+ /// What to say when a SAM 3 download ended while its dialog was closed: the text, and whether it is
+ /// shown as an error toast. A cancel is told by `cancelled`, not by the error's words.
+ pub(crate) fn sam_download_ended(download: &lightcraft_engine::segment::DownloadStatus) -> Option<(String, bool)> {
+ match &download.error {
+ Some(_) if download.cancelled => {
+ Some((crate::i18n::tr("SAM 3 download stopped: it resumes where it left off next time.").to_string(), false))
+ }
+ Some(e) => Some((crate::i18n::tr_format!("The SAM 3 download failed: {e}", e = e), true)),
+ None if download.finished => Some((crate::i18n::tr("The SAM 3 model is installed: Object and Describe masks are ready.").to_string(), true)),
+ None => None,
+ }
+ }
diff --cc crates/ui-egui/src/app/input.rs
index 000000000,0757ecbe0..6c03c9c38
mode 000000,100644..100644
--- a/crates/ui-egui/src/app/input.rs
+++ b/crates/ui-egui/src/app/input.rs
@@@ -1,0 -1,261 +1,271 @@@
+ use super::*;
+
+ impl LightcraftApp {
+ /// Take the host's dropped files, exactly once. The queue is filled by `raw_input_hook`, so a
+ /// hidden logic tick can never replay the last pass's drop. Web hosts call this in their UI
+ /// phase (they need `bytes_async`, which is not available on a native file path).
+ pub fn take_dropped_files(&mut self) -> Vec<egui::DroppedFileHandle> {
+ std::mem::take(&mut self.dropped_files)
+ }
+
+ /// Import native drops as presets, face models or photos.
+ pub(super) fn import_dropped_files(&mut self, ctx: &egui::Context) {
+ let dropped = self.take_dropped_files();
+ if dropped.is_empty() {
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ self.handle_dropped_files(ctx, dropped);
+ #[cfg(target_arch = "wasm32")]
+ let _ = (dropped, ctx);
+ }
+
+ /// Files dropped on the window: face models open their licence dialog, presets import as
+ /// presets, photos and folders go to the import review (or straight in, Settings ▸ Import).
+ #[cfg(not(target_arch = "wasm32"))]
+ fn handle_dropped_files(&mut self, ctx: &egui::Context, dropped: Vec<egui::DroppedFileHandle>) {
+ let dropped: Vec<String> =
+ dropped.iter().map(|f| egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect();
+ if dropped.is_empty() {
+ return;
+ }
+ // a dialog is on screen: the review would replace it, losing what it holds
+ if self.ui.dialog.is_some() {
+ self.toast(ctx, crate::i18n::tr("Close the open dialog, then drop the files again"));
+ return;
+ }
+ let drop = drop_overlay::classify(dropped);
+ if let Some(model) = drop.models.first()
+ && let Err(e) = panels::faces::open_dialog(self, model)
+ {
+ self.toast(ctx, e);
+ }
+ if !drop.presets.is_empty() {
+ // presets live in a library: with none open they would go with the session it replaces
+ if panels::library_problem::holds_drops(self) {
+ self.toast(ctx, crate::i18n::tr("Open a library first, then drop the presets again"));
+ } else {
+ let _ = self.run("file.importPresets", serde_json::json!({"paths": drop.presets}));
+ }
+ }
+ if drop.photos.is_empty() {
+ return;
+ }
+ // no library open yet (the launch list, a library that failed to open): they wait for one
+ let Some(photos) = panels::library_problem::hold_dropped(self, ctx, drop.photos) else { return };
+ if self.lightroom.is_some() {
+ self.toast(ctx, crate::i18n::tr("Finish Lightroom catalog import before adding photos"));
+ return;
+ }
+ if import::running(self) {
+ self.toast(ctx, crate::i18n::tr("An import is running"));
+ return;
+ }
+ let started = if self.ui.settings.import_dropped_directly {
+ // read and added on a worker thread (dropped folders can be large, or on a slow drive)
+ import::start_paths(self, photos).map(|_| ())
+ } else {
+ import::open(self, photos).map(|_| ())
+ };
+ if let Err(e) = started {
+ self.toast(ctx, e);
+ }
+ }
+
+ /// A file dropped by the host, kept for the next UI pass (web hosts consume their own queue).
+ fn queue_dropped_files(&mut self, raw: &mut egui::RawInput) {
+ if !raw.dropped_files.is_empty() {
+ self.dropped_files.append(&mut raw.dropped_files);
+ }
+ }
+
+ /// Take the host's dropped files once and inject synthetic events (pointer events one per
+ /// frame; key sequences up to the release).
+ ///
+ /// The hook also runs before a hidden logic-only tick, so it injects at most one batch and
+ /// keeps that batch in flight until a completed UI pass consumed it. It never injects while
+ /// the fonts are not installed (the pass would draw nothing and the events would be lost).
+ pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
+ let file = |p: &String| (!p.is_empty()).then(|| std::path::PathBuf::from(p));
+ if !self.drop_pending.is_empty() {
+ raw.dropped_files = std::mem::take(&mut self.drop_pending)
+ .into_iter()
+ .map(|p| std::sync::Arc::new(InjectedDrop(p.into())) as egui::DroppedFileHandle)
+ .collect();
+ }
+ if !self.drop_hover.is_empty() {
+ raw.hovered_files = self.drop_hover.iter().map(|p| egui::HoveredFile { path: file(p), ..Default::default() }).collect();
+ }
+ // Queue after injecting, so a `ui.dropFiles` request is consumed exactly once by the UI phase.
+ self.queue_dropped_files(raw);
+ // Track the real host modifier state separately from the app's synthetic ownership. A host
+ // change means the host now owns the modifier state: relinquish any synthetic claim and do
+ // not later synthesise a release for a key that is physically held.
+ if let Some(host_mods) = raw.events.iter().rev().find_map(|event| match event {
+ egui::Event::ModifiersChanged(modifiers) => Some(*modifiers),
+ _ => None,
+ }) {
+ self.host_mods = host_mods;
+ self.synthetic_mods = egui::Modifiers::NONE;
+ self.synthetic_mods_release = false;
+ }
+ // A prompt owns all input. On its first host frame this also removes pointer/touch input
+ // before egui computes its hit test; later frames keep only key releases, the prompt's own
+ // keys, and AccessKit actions targeted at a prompt button. See `notices::filter_raw_input`.
+ let batch_in_flight = self.synthetic_in_flight;
+ if crate::panels::notices::prepare_raw_input(self, ctx, raw) {
+ // A prompt appearing during a synthetic drag must abort the drag, not let its remaining
+ // move/release events act under the prompt or after it is dismissed. If a whole batch
+ // was already injected, it is unsafe as well: this frame's prompt filter drops it
+ // before a panel sees it, so it must not report a successful delivery.
+ self.cancel_gestures_for_barrier(batch_in_flight, "a modal prompt appeared");
+ self.queue_pointer_cleanup();
+ }
+ // Enforce the stall deadline before injecting another event: a request that expired during
+ // a long frame gap must not get one more event on the frame that resumes.
+ self.expire_gestures();
+ // A canceled press is released by resetting egui's pointer state before its next input
+ // pass, even while another batch is in flight or the fonts are not ready, so the pointer
+ // cannot stay down. No move/release event is injected: either could start a drag or
+ // become a click on the widget being canceled.
+ self.apply_pointer_cleanup(ctx, raw);
+ if !self.fonts_ready || self.synthetic_in_flight {
+ return;
+ }
+ if self.drop_gestures_stale_before_injection(ctx) {
+ // The stale check can cancel the head gesture while its press is already down.
+ self.apply_pointer_cleanup(ctx, raw);
+ return;
+ }
+ // the frame after a synthetic release / key: restore the host's physical modifiers, not
+ // necessarily NONE (Shift may still be held while a synthetic Alt gesture is released)
+ if std::mem::take(&mut self.synthetic_mods_release) && self.synthetic_mods != egui::Modifiers::NONE {
+ self.synthetic_mods = egui::Modifiers::NONE;
+ raw.events.push(egui::Event::ModifiersChanged(self.host_mods));
+ }
+ if self.synthetic.is_empty() {
+ return;
+ }
- let n = match self.synthetic[0] {
- egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. } => 1,
- _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1),
++ let pointer =
++ |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });
++ let n = if pointer(&self.synthetic[0]) {
++ 1
++ } else {
++ // a key sequence up to its release; a key held down (no release yet) stops before the
++ // pointer events that follow, which then still come one per frame
++ let release = self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map(|i| i + 1);
++ let next_pointer = self.synthetic.iter().position(pointer);
++ match (release, next_pointer) {
++ (Some(r), Some(q)) => r.min(q),
++ (r, q) => r.or(q).unwrap_or(self.synthetic.len()),
++ }
+ };
+ // A press needs the pointer at its position before the button event; the move that is
+ // itself the first event is delivered by the drain below, so it must not be sent twice.
+ if let Some(egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() {
+ raw.events.push(egui::Event::PointerMoved(*p));
+ }
+ // egui's `input.modifiers` follow `ModifiersChanged` events, not the modifiers carried by
+ // pointer/key events: announce the injected events' modifiers (held from button down to
+ // the frame after up), so ⌥-drag, ⇧-click … work through the control channel
+ let carried = self.synthetic[..n].iter().find_map(|e| match e {
+ egui::Event::PointerButton { pressed, modifiers, .. } => Some((*modifiers, !pressed)),
+ egui::Event::Key { modifiers, .. } => Some((*modifiers, true)),
+ _ => None,
+ });
+ if let Some((m, ends)) = carried {
+ if m != self.synthetic_mods {
+ self.synthetic_mods = m;
+ raw.events.push(egui::Event::ModifiersChanged(m));
+ }
+ self.synthetic_mods_release = ends;
+ }
+ let blocked_by_prompt = self.synthetic[..n].iter().any(|event| !crate::panels::notices::prompt_allows_event(self, event));
+ let head = self.head_gesture();
+ if let Some(head) = head {
+ let gesture = &mut self.pending_gestures[head];
+ for event in &self.synthetic[..n] {
+ match event {
+ egui::Event::PointerButton { button, pressed: true, .. } => {
+ gesture.pressed = Some(InjectedPress { button: *button });
+ }
+ egui::Event::PointerButton { button, pressed: false, .. }
+ if gesture.pressed.as_ref().is_some_and(|press| press.button == *button) =>
+ {
+ gesture.pressed = None;
+ }
+ _ => {}
+ }
+ }
+ gesture.started = true;
+ gesture.remaining_events = gesture.remaining_events.saturating_sub(n);
+ }
+ raw.events.extend(self.synthetic.drain(..n));
+ // The same barrier applies after injection: only the prompt's own keys and targeted
+ // AccessKit actions survive; host input and `ui.text`/clipboard never reach the background.
+ crate::panels::notices::filter_raw_input(self, raw);
+ if blocked_by_prompt && let Some(index) = head {
+ // A settled prompt is already laid out, so this is not the prompt-creation-cancels-all
+ // path: only the gesture whose batch the barrier removed fails. Allowed prompt keys,
+ // pointer input and targeted AccessKit actions still report a successful delivery.
+ let gesture = self.pending_gestures.remove(index);
+ self.cancel_gesture_events(&gesture, true);
+ let _ = gesture.reply.send(serde_json::json!({
+ "ok": false,
+ "error": format!("{} canceled: the open modal prompt blocked this input", gesture.method),
+ }));
+ }
+ // The 5 s deadline is a delivery-stall limit, not a limit on a gesture's frame count: a
+ // drag feeds one event per host frame, so every batch that the app consumes proves the UI
+ // is alive and restarts the clock for the whole queue.
+ let now = self.tick_now_ms();
+ for gesture in &mut self.pending_gestures {
+ gesture.deadline_ms = now + GESTURE_TIMEOUT_MS;
+ }
+ self.synthetic_in_flight = true;
+ }
+ }
+
+ #[cfg(test)]
+ mod drop_tests {
+ #[test]
+ fn photo_sidecars_are_not_presets() {
+ let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+ let dropped = v(&["/a/IMG_1.CR2", "/a/IMG_1.xmp", "/a/IMG_2.jpg", "/a/IMG_2.jpg.XMP", "/a/Look.xmp", "/b/IMG_1.xmp"]);
+ let (presets, photos) = super::split_presets(dropped);
+ assert_eq!(photos, v(&["/a/IMG_1.CR2", "/a/IMG_2.jpg"]));
+ assert_eq!(presets, v(&["/a/Look.xmp", "/b/IMG_1.xmp"]));
+ }
+
+ #[test]
+ fn detection_results_are_summarised_in_words() {
+ let r =
+ |counts: &[usize]| serde_json::json!({"photos": counts.iter().map(|n| serde_json::json!({"faces": vec![0; *n]})).collect::<Vec<_>>()});
+ assert_eq!(super::detect_summary(&r(&[0])), "No faces found");
+ assert_eq!(super::detect_summary(&r(&[1])), "Found 1 face");
+ assert_eq!(super::detect_summary(&r(&[3])), "Found 3 faces");
+ assert_eq!(super::detect_summary(&r(&[0, 0])), "No faces found in 2 photos");
+ assert_eq!(super::detect_summary(&r(&[2, 0, 1])), "Found 3 faces in 2 photos");
+ assert_eq!(super::detect_summary(&serde_json::json!({})), "No faces found in 0 photos");
+ }
+
+ #[test]
+ fn dropped_face_models_are_told_apart() {
+ for p in ["/a/model.onnx", "/a/dir/M.ONNX"] {
+ assert!(super::is_model_file(p), "{p}");
+ }
+ for p in ["/a/model.onnx.jpg", "/a/onnx", "/a/b.png"] {
+ assert!(!super::is_model_file(p), "{p}");
+ }
+ }
+
+ #[test]
+ fn dropped_presets_are_told_apart_from_photos() {
+ for p in ["/a/Look.lrtemplate", "/a/b.XMP", "/a/pack.zip", "/a/x.lcpreset", "/a/Magic Hour.mplumpack", "/a/Pop.lmp", "/a/Bundle.LMP"] {
+ assert!(super::is_preset_file(p), "{p}");
+ }
+ for p in ["/a/IMG_1.CR2", "/a/b.dng", "/a/c.jpg", "/a/folder"] {
+ assert!(!super::is_preset_file(p), "{p}");
+ }
+ }
+ }
diff --cc crates/ui-egui/src/lib.rs
index 28622bbbe,8da88f9ae..b4fcaec54
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -42,9 -31,7 +31,8 @@@ pub mod reload
pub mod render;
pub mod shortcuts;
pub mod sidebar;
- pub mod slideshow_export;
pub mod softpaint;
+pub mod space_hand;
pub mod state;
pub mod sync;
pub mod tasks;
diff --cc crates/ui-egui/src/panels/detail.rs
index 18adf99a3,25f3baa24..9c9b2d68e
--- a/crates/ui-egui/src/panels/detail.rs
+++ b/crates/ui-egui/src/panels/detail.rs
@@@ -1711,1584 -815,65 +828,64 @@@ pub(crate) fn click_zoom_and_pan(app: &
if zoomed && resp.dragged() {
pan_image(app, canvas, img, resp.drag_delta());
}
- let _ = (native, aspect);
}
- // ------------------------------------------------------------------------ crop
+ #[cfg(test)]
+ mod tests {
+ /// The rotation pointer's arc bulges away from the side of the crop box it is on, and follows
+ /// a box that is itself rotated.
+ #[test]
+ fn rotate_cursor_faces_away_from_the_crop_box() {
+ use egui::{Pos2, pos2};
+ use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, PI};
+ let near = |a: f32, b: f32| ((a - b + PI).rem_euclid(2.0 * PI) - PI).abs() < 1e-3;
+ let pts = [pos2(100.0, 100.0), pos2(300.0, 100.0), pos2(300.0, 200.0), pos2(100.0, 200.0)];
+ let turn = |x: f32, y: f32| super::rotate_cursor_turn(&pts, pos2(x, y), false);
+ assert!(near(turn(200.0, 80.0), 0.0), "above: as drawn");
+ assert!(near(turn(320.0, 150.0), FRAC_PI_2), "right");
+ assert!(near(turn(200.0, 230.0), PI), "below");
+ assert!(near(turn(70.0, 150.0), -FRAC_PI_2), "left");
+ assert!(near(turn(290.0, 60.0), 0.0), "above the top edge near its end: still up");
+ // off each corner: diagonally out from it
+ assert!(near(turn(80.0, 80.0), -FRAC_PI_4), "top-left corner");
+ assert!(near(turn(320.0, 80.0), FRAC_PI_4), "top-right corner");
+ assert!(near(turn(320.0, 220.0), 3.0 * FRAC_PI_4), "bottom-right corner");
+ assert!(near(turn(80.0, 220.0), -3.0 * FRAC_PI_4), "bottom-left corner");
+ assert!(near(super::rotate_cursor_turn(&pts, pos2(200.0, 110.0), true), 0.0), "dragged back over the top edge: still up");
+ // a box turned 90°: its top edge is now on the right
+ let turned = [pts[3], pts[0], pts[1], pts[2]].map(|p| pos2(400.0 - p.y, p.x));
+ assert!(near(super::rotate_cursor_turn(&turned, pos2(420.0, 200.0), false), FRAC_PI_2));
+ // a box turned 30°: straight out from its top edge is 30° clockwise of up
+ let c = pos2(200.0, 150.0);
+ let rot = |p: Pos2| {
+ let (s, co) = (30f32.to_radians().sin(), 30f32.to_radians().cos());
+ let d = p - c;
+ pos2(c.x + d.x * co - d.y * s, c.y + d.x * s + d.y * co)
+ };
+ let tilted = pts.map(rot);
+ assert!(near(super::rotate_cursor_turn(&tilted, rot(pos2(200.0, 60.0)), false), 30f32.to_radians()));
+ }
+
+ use super::{film_label, flipped_corners, outside_crop_mesh, texture_side};
+ use egui::{Color32, Pos2, Rect, pos2};
- fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, frame: &Frame, d: &DevelopSettings, id: PhotoId) {
- // the selected guide belongs to this photo and to the Guided Upright tool, and to a guide
- // that still exists (a Delete after the last one leaves the selection behind)
- if app.ui.tool != "guidedUpright" || app.ui.selected_guide.is_some_and(|(photo, i)| photo != id.0 || i >= d.geometry.guides.len()) {
- app.ui.selected_guide = None;
+ /// A rotated `w` × `h` box centred on `centre`.
+ fn box_at(centre: Pos2, w: f32, h: f32, angle: f32) -> [Pos2; 4] {
+ let (s, c) = angle.to_radians().sin_cos();
+ [(-w, -h), (w, -h), (w, h), (-w, h)].map(|(x, y)| pos2(centre.x + (x * c - y * s) / 2.0, centre.y + (x * s + y * c) / 2.0))
}
- if app.ui.tool == "guidedUpright" {
- guided_overlay(app, ui, resp, map, frame, d, id);
- return;
- }
- if app.ui.tool == "straighten" {
- straighten_overlay(app, ui, resp, false);
- return;
- }
- // hold ⌘ and drag: draw a straighten line without leaving the crop tool
- let cmd_drag = resp.drag_started() && ui.input(|i| i.modifiers.command);
- if cmd_drag || matches!(app.gesture, Some(Gesture::StraightenLine { .. })) {
- straighten_overlay(app, ui, resp, true);
- return;
- }
- if resp.hovered() && ui.input(|i| i.modifiers.command) {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- }
- let quad = frame_crop_quad(d, frame);
- let pts: Vec<Pos2> = quad.iter().map(|q| map.screen(*q)).collect();
- let p = ui.painter();
- // darken outside the crop (the box's corners in screen order: a flipped photo shows its
- // top-left corner elsewhere)
- let quad = flipped_corners(&pts, frame.flip_h, frame.flip_v);
- if pts.len() == 4 {
- p.add(outside_crop_mesh(map.rect, &quad, Color32::from_black_alpha(150)));
- }
- p.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.0, Color32::WHITE)));
- // overlay guides
- let lerp = |a: Pos2, b: Pos2, t: f32| a + (b - a) * t;
- let guide = Stroke::new(0.8, Color32::from_white_alpha(150));
- // (u, v) across / down the (rotated) crop frame
- let at = |(u, v): (f32, f32)| pts[0] + (pts[1] - pts[0]) * u + (pts[3] - pts[0]) * v;
- let (cw, ch) = (pts[0].distance(pts[1]), pts[0].distance(pts[3]));
- for line in super::crop_overlay::paths(app.ui.crop_overlay, app.ui.crop_overlay_orient, cw, ch) {
- p.add(egui::Shape::line(line.into_iter().map(at).collect(), guide));
- }
- // handles: 0..3 corners, 4..7 edges (top, right, bottom, left)
- let handles: Vec<Pos2> = (0..8).map(|i| if i < 4 { pts[i] } else { lerp(pts[i - 4], pts[(i - 3) % 4], 0.5) }).collect();
- for (i, h) in handles.iter().enumerate() {
- register(ui, format!("cropHandle:{i}"), Rect::from_center_size(*h, vec2(14.0, 14.0)));
- let s = if i < 4 { 12.0 } else { 9.0 };
- p.rect_filled(Rect::from_center_size(*h, vec2(s, 3.0)), 0.0, Color32::WHITE);
- p.rect_filled(Rect::from_center_size(*h, vec2(3.0, s)), 0.0, Color32::WHITE);
- }
- // the keyboard: each handle (and the box itself) a stand-in Tab reaches and the arrows move
- if crop_keys(app, ui, map, &handles, &pts, d, frame) {
- return;
- }
- let inside = |q: Pos2| {
- let n = map.norm(q);
- let s = to_straight(n, d.crop.geometry.angle, frame);
- d.crop.geometry.rect.contains(Point::new(s.x.clamp(-1.0, 2.0), s.y))
- };
- // a crop drag cut short (the tool closed before the release) leaves its gesture behind: with no
- // button held it is over
- if matches!(app.gesture, Some(Gesture::CropRotate { .. } | Gesture::CropHandle { .. }))
- && !resp.drag_stopped()
- && !ui.input(|i| i.pointer.any_down())
- {
- app.gesture = None;
- }
- // while rotating, the pointer may leave the canvas: it still shows rotation and the angle
- let rotating = matches!(app.gesture, Some(Gesture::CropRotate { .. }));
- let pointer = resp.hover_pos().or_else(|| if rotating { ui.input(|i| i.pointer.latest_pos()) } else { None });
- // with ⌘ held a drag draws a level line (the straighten crosshair, set above), not a rotation
- let straightening = !rotating && ui.input(|i| i.modifiers.command);
- if let Some(hq) = pointer.filter(|_| !straightening) {
- // a move or resize drag keeps its pointer wherever it goes, even past the box
- let held = match app.gesture {
- Some(Gesture::CropHandle { handle, .. }) => Some(usize::from(handle)),
- _ => None,
- };
- let near = held.or_else(|| handles.iter().position(|h| h.distance(hq) < 12.0)).filter(|_| !rotating);
- let cursor = match near {
- Some(0 | 2) => egui::CursorIcon::ResizeNwSe,
- Some(1 | 3) => egui::CursorIcon::ResizeNeSw,
- Some(4 | 6) => egui::CursorIcon::ResizeVertical,
- Some(5 | 7) => egui::CursorIcon::ResizeHorizontal,
- // 8: the whole box
- Some(_) => egui::CursorIcon::Move,
- None if inside(hq) && !rotating => egui::CursorIcon::Move,
- // a drag here rotates: no system cursor shows that, so draw a curved double arrow
- None => {
- rotate_cursor(ui, hq, rotate_cursor_turn(&pts, hq, inside(hq)));
- egui::CursorIcon::None
- }
- };
- ui.ctx().set_cursor_icon(cursor);
- }
- // the angle next to the pointer, drawn once this frame's rotation is applied (below)
- let readout_at = pointer.filter(|_| rotating);
- let mut shown_angle = d.crop.geometry.angle;
- // double-click inside the crop box applies the crop (same as Return / Done)
- if resp.double_clicked()
- && let Some(q) = resp.interact_pointer_pos()
- && inside(q)
- && !handles.iter().any(|h| h.distance(q) < 12.0)
- {
- let _ = app.run("tool.done", json!({}));
- return;
- }
- // egui reports a drag only once the pointer has moved a few px: the zone is where the button
- // went down, where the cursor showed it, not where the pointer is by then
- if resp.drag_started()
- && let Some(q) = ui.input(|i| i.pointer.press_origin()).or_else(|| resp.interact_pointer_pos())
- {
- if let Err(e) = app.run("develop.beginInteraction", json!({"label": "Crop"})).and_then(|_| app.begin_crop().map(|_| serde_json::Value::Null))
- {
- app.ui.status = e;
- let _ = app.session.cancel_interaction();
- return;
- }
- let d = app.session.develop_of(id).unwrap_or_default();
- app.gesture = Some(match handles.iter().position(|h| h.distance(q) < 12.0) {
- Some(h) => Gesture::CropHandle { handle: h as u8, start: d.crop.geometry.rect, angle: d.crop.geometry.angle },
- None if inside(q) => Gesture::CropHandle { handle: 8, start: d.crop.geometry.rect, angle: d.crop.geometry.angle },
- None => {
- let c = map.screen(Point::new(0.5, 0.5));
- Gesture::CropRotate { start_angle: d.crop.geometry.angle, a0: (q - c).angle() }
- }
- });
- }
- if resp.dragged()
- && let Some(q) = resp.interact_pointer_pos()
- {
- match app.gesture.clone() {
- Some(Gesture::CropHandle { handle, start, angle }) => {
- // The crop model decides what the drag does (anchor, aspect lock, image bounds): see
- // `lightcraft_geom::drag_crop`; the UI only reports where the pointer started and is.
- let n = to_straight(map.norm(q), angle, frame);
- let orig = ui.input(|i| i.pointer.press_origin()).map(|q0| to_straight(map.norm(q0), angle, frame)).unwrap_or(n);
- // Shift keeps the current proportions for this drag only; the Lock toggle is untouched.
- let keep_ratio = ui.input(|i| i.modifiers.shift);
- let _ = app.run(
- "crop.drag",
- json!({"handle": handle, "from": [orig.x, orig.y], "to": [n.x, n.y], "start": [start.x0, start.y0, start.x1, start.y1], "keepRatio": keep_ratio}),
- );
- }
- Some(Gesture::CropRotate { start_angle, a0 }) => {
- let c = map.screen(Point::new(0.5, 0.5));
- let a = (q - c).angle();
- let ang = (start_angle + (a - a0).to_degrees() as f64).clamp(-45.0, 45.0);
- shown_angle = (ang * 100.0).round() / 100.0;
- let _ = app.run("crop.straighten", json!({"angle": shown_angle}));
- }
- _ => {}
- }
- }
- if resp.drag_stopped() {
- app.gesture = None;
- let _ = app.run("develop.endInteraction", json!({}));
- }
- if let Some(at) = readout_at {
- // the canvas (the loupe's own rect), not the photo: rotating happens in the margin around it
- angle_readout(ui, at, shown_angle, resp.rect);
- }
- }
-
- /// The crop handles' names for screen readers, in `crop.drag`'s numbering: 0..3 corners, 4..7
- /// edges (top, right, bottom, left), 8 the whole box.
- const CROP_HANDLE_NAMES: [&str; 9] = [
- "Crop top-left corner",
- "Crop top-right corner",
- "Crop bottom-right corner",
- "Crop bottom-left corner",
- "Crop top edge",
- "Crop right edge",
- "Crop bottom edge",
- "Crop left edge",
- "Crop box",
- ];
-
- /// Keyboard stand-ins for the crop handles: an arrow press drags the focused one by a step (one
- /// undo step each), as a pointer drag from its place would. Return applies the crop. True when the
- /// frame is over (the crop was applied).
- fn crop_keys(
- app: &mut LightcraftApp,
- ui: &mut egui::Ui,
- map: &CanvasMap,
- handles: &[Pos2],
- pts: &[Pos2],
- d: &DevelopSettings,
- frame: &Frame,
- ) -> bool {
- let r = d.crop.geometry.rect;
- let centre = if pts.len() == 4 { pts.iter().fold(Pos2::ZERO, |acc, q| acc + q.to_vec2() / 4.0) } else { return false };
- let pct = |v: f64| if v.is_finite() { (v * 100.0).round() as i64 } else { 0 };
- let value = format!("left {}%, top {}%, right {}%, bottom {}%", pct(r.x0), pct(r.y0), pct(r.x1), pct(r.y1));
- for (i, name) in CROP_HANDLE_NAMES.iter().enumerate() {
- let Some(at) = handles.get(i).copied().or_else(|| (i == 8).then_some(centre)) else { continue };
- let keys = crate::canvas_keys::handle(ui, &format!("crop:{i}"), crate::i18n::tr(name), value.clone(), at);
- if keys.activated {
- let _ = app.run("tool.done", json!({}));
- return true;
- }
- let Some((dx, dy)) = keys.delta else { continue };
- // the drag runs in the straightened crop frame, as a pointer drag from the handle would;
- // the arrows follow the screen
- let angle = d.crop.geometry.angle;
- let to_q = at + vec2(dx as f32 * map.rect.width(), dy as f32 * map.rect.height());
- let (from, to) = (to_straight(map.norm(at), angle, frame), to_straight(map.norm(to_q), angle, frame));
- let started = app.run("develop.beginInteraction", json!({"label": "Crop"})).and_then(|_| app.begin_crop().map(|_| serde_json::Value::Null));
- if let Err(e) = started {
- app.ui.status = e;
- let _ = app.session.cancel_interaction();
- return false;
- }
- let _ = app.run(
- "crop.drag",
- json!({"handle": i, "from": [from.x, from.y], "to": [to.x, to.y], "start": [r.x0, r.y0, r.x1, r.y1], "keepRatio": false}),
- );
- let _ = app.run("develop.endInteraction", json!({}));
- }
- false
- }
-
- /// The crop angle as the rotation readout shows it: like the Straighten value, in degrees.
- pub(crate) fn crop_angle_label(angle: f64) -> String {
- let shown =
- lightcraft_develop::controls::find("crop.angle").map_or_else(|| format!("{angle:.2}"), |spec| crate::widgets::shown_value(spec, angle));
- // the slider's format turns a rounded −0.00 into "0": every zero reads "0.00", the angle's
- // usual two decimals
- let shown = if shown == "0" { "0.00".to_string() } else { shown };
- format!("{shown}°")
- }
-
- /// Where the angle readout of `size` goes for a pointer `at`: below right of it, flipped to the
- /// left / above where that would leave `bounds`, then kept inside them.
- pub(crate) fn readout_rect(at: Pos2, size: egui::Vec2, bounds: Rect) -> Rect {
- // without a real pointer or bounds (NaN, an empty rect) there is nothing to keep it in; and
- // f32::clamp panics on NaN, so only finite numbers get there
- if !at.is_finite() || !bounds.is_finite() || !bounds.is_positive() {
- let at = if at.is_finite() { at } else { bounds.min.max(Pos2::ZERO) };
- let at = if at.is_finite() { at } else { Pos2::ZERO };
- return Rect::from_min_size(at + vec2(18.0, 14.0), size);
- }
- let x = if at.x + 18.0 + size.x > bounds.right() { at.x - 18.0 - size.x } else { at.x + 18.0 };
- let y = if at.y + 14.0 + size.y > bounds.bottom() { at.y - 14.0 - size.y } else { at.y + 14.0 };
- let x = x.clamp(bounds.left(), (bounds.right() - size.x).max(bounds.left()));
- let y = y.clamp(bounds.top(), (bounds.bottom() - size.y).max(bounds.top()));
- Rect::from_min_size(pos2(x, y), size)
- }
-
- /// On top of everything (the tooltip layer), so neither the photo nor a panel covers it.
- fn top_painter(ui: &egui::Ui, name: &'static str) -> egui::Painter {
- ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique(name)))
- }
-
- /// The rotation pointer: a curved double arrow on a dark disc, so it reads over any photo,
- /// turned `turn` radians clockwise ([`rotate_cursor_turn`]).
- fn rotate_cursor(ui: &egui::Ui, at: Pos2, turn: f32) {
- let p = top_painter(ui, "crop-rotate-cursor");
- let r = Rect::from_center_size(at, vec2(22.0, 22.0));
- p.circle_filled(at, 12.0, Color32::from_black_alpha(150));
- crate::icons::paint_turned(&p, r.shrink(2.0), crate::icons::Icon::RotateDrag, Color32::WHITE, turn);
- register(ui, "cropRotateCursor", r);
- }
-
- /// How far to turn the rotation pointer (radians, clockwise) so its arc, drawn bulging up, bulges
- /// away from the crop box `pts` (its four corners on screen, maybe rotated): up above the top edge,
- /// right beside the right edge, down below it, diagonally off a corner. Measured from the nearest
- /// point of the box's outline; `inside` (a rotate drag that has come back over the box) faces it
- /// the other way, still away from that edge.
- fn rotate_cursor_turn(pts: &[Pos2], q: Pos2, inside: bool) -> f32 {
- let nearest = (0..pts.len())
- .map(|i| {
- let (a, b) = (pts[i], pts[(i + 1) % pts.len()]);
- let ab = b - a;
- let t = if ab.length_sq() > 0.0 { ((q - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
- a + ab * t
- })
- .min_by(|a, b| a.distance_sq(q).total_cmp(&b.distance_sq(q)));
- let Some(nearest) = nearest else { return 0.0 };
- let away = if inside { nearest - q } else { q - nearest };
- if away.length() < 0.5 {
- return 0.0;
- }
- away.y.atan2(away.x) + std::f32::consts::FRAC_PI_2
- }
-
- /// While rotating: the angle, next to the pointer, kept inside `bounds` (the canvas): on the
- /// pointer's other side when it would run past an edge.
- fn angle_readout(ui: &egui::Ui, at: Pos2, angle: f64, bounds: Rect) {
- let t = Tokens::get(ui.ctx());
- let p = top_painter(ui, "crop-angle-readout");
- let galley = p.layout_no_wrap(crop_angle_label(angle), t.font(12.5), Color32::WHITE);
- let rect = readout_rect(at, galley.size() + vec2(12.0, 6.0), bounds);
- p.rect_filled(rect, 4.0, Color32::from_black_alpha(170));
- p.galley(rect.min + vec2(6.0, 3.0), galley, Color32::WHITE);
- register(ui, "cropAngleReadout", rect);
- }
-
- /// Guided Upright: draw up to four guides along lines that should be vertical or horizontal. Guides are
- /// stored in lens-corrected (pre-perspective) coordinates, so they stay attached to the image as it warps.
- fn guided_overlay(
- app: &mut LightcraftApp,
- ui: &mut egui::Ui,
- resp: &egui::Response,
- map: &CanvasMap,
- frame: &Frame,
- d: &DevelopSettings,
- id: PhotoId,
- ) {
- let p = ui.painter_at(map.rect.expand(8.0));
- let col = Color32::from_rgb(255, 196, 40);
- // the selected guide: brighter, so the Delete key has a visible target
- let selected = app.ui.selected_guide.filter(|(photo, _)| *photo == id.0).map(|(_, i)| i);
- let draw = |a: Pos2, b: Pos2, sel: bool| {
- let (edge, core, at) = if sel { (3.5, 2.5, 5.0) } else { (3.0, 1.5, 4.0) };
- p.line_segment([a, b], Stroke::new(edge, Color32::from_black_alpha(120)));
- p.line_segment([a, b], Stroke::new(core, if sel { Color32::WHITE } else { col }));
- for q in [a, b] {
- p.circle_filled(q, at, if sel { Color32::WHITE } else { col });
- p.circle_stroke(q, at, Stroke::new(1.0, Color32::BLACK));
- }
- };
- let on_screen = |guide: &(Point, Point)| {
- let (sa, sb) = (map.screen(frame.corrected_to_transformed(guide.0)), map.screen(frame.corrected_to_transformed(guide.1)));
- (sa, sb)
- };
- for (i, guide) in d.geometry.guides.iter().enumerate() {
- let (sa, sb) = on_screen(guide);
- register(ui, format!("uprightGuide:{i}"), Rect::from_two_pos(sa, sb));
- draw(sa, sb, selected == Some(i));
- }
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- // A press starts what it means, right away (the pointer's press point, not where a drag
- // threshold would have been crossed): on an endpoint it drags that endpoint (the guide is
- // selected when it lands), on a line it selects the guide (a press on the selected one
- // deselects), anywhere else it starts a new guide from the press point. The primary button
- // only, never on the navigator — it pans the photo, it draws no guide — and only where the
- // loupe itself takes the press: `contains_pointer` is layer-aware over the current pointer
- // (the raw pointer is not), and `layer_id_at` asks the same question at the press point —
- // a menu can receive the press and the pointer can leave it within the same frame, so the
- // press itself must belong to the loupe's layer. Anything floating above the photo — a
- // context menu, a dropdown, a dialog — owns its own press; the guide under it stays put.
- // A slow frame can also swallow the whole press-move-release into one batch, and egui
- // clears `press_origin` on the release: then the press position is read back from the
- // frame's own events, so the gesture still starts where the pointer went down.
- let nav = app.widgets.iter().rev().find(|(w, _)| w == "canvas:navigator").map(|(_, r)| *r);
- if ui.input(|i| i.pointer.primary_pressed())
- && let Some(q) = ui
- .input(|i| {
- i.pointer.press_origin().or_else(|| {
- i.events.iter().rev().find_map(|e| match e {
- egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
- _ => None,
- })
- })
- })
- .or(resp.interact_pointer_pos())
- && resp.contains_pointer()
- && ui.ctx().layer_id_at(q) == Some(resp.layer_id)
- && resp.rect.contains(q)
- && !nav.is_some_and(|n| n.expand(5.0).contains(q))
- {
- let endpoint = d.geometry.guides.iter().enumerate().find_map(|(i, guide)| {
- let (a, b) = on_screen(guide);
- if a.distance(q) <= 7.0 {
- Some((i, 0))
- } else if b.distance(q) <= 7.0 {
- Some((i, 1))
- } else {
- None
- }
- });
- let line = d.geometry.guides.iter().position(|guide| {
- let (a, b) = on_screen(guide);
- point_segment_dist(q, a, b) <= 6.0
- });
- match (endpoint, line) {
- (Some((i, end)), _) => app.gesture = Some(Gesture::GuideEndpoint { i, end, from: q }),
- (None, Some(i)) => app.ui.selected_guide = if selected == Some(i) { None } else { Some((id.0, i)) },
- // drawing a new guide leaves nothing selected
- (None, None) => {
- app.ui.selected_guide = None;
- app.gesture = Some(Gesture::Guide { a: map.norm(q) });
- }
- }
- }
- let q = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
- if let (Some(Gesture::Guide { a }), Some(q)) = (&app.gesture, q) {
- draw(map.screen(*a), q, false);
- }
- // the endpoint being dragged: the guide follows the pointer, bright
- if let (Some(Gesture::GuideEndpoint { i, end, .. }), Some(q)) = (&app.gesture, q)
- && let Some(guide) = d.geometry.guides.get(*i)
- {
- let fixed = if *end == 0 { guide.1 } else { guide.0 };
- draw(map.screen(frame.corrected_to_transformed(fixed)), q, true);
- }
- if ui.input(|i| i.pointer.any_released()) {
- match app.gesture.take() {
- // the endpoint lands: the guide stays (one undo step) and is selected. A press
- // without a real drag only selects — no no-op undo entry for a click.
- Some(Gesture::GuideEndpoint { i, end, from }) => {
- app.ui.selected_guide = Some((id.0, i));
- if let (Some(q), Some(guide)) = (q, d.geometry.guides.get(i)) {
- let fixed_t = if end == 0 { guide.1 } else { guide.0 };
- let new_t = frame.transformed_to_corrected(map.norm(q));
- let (a, b) = if end == 0 { (new_t, fixed_t) } else { (fixed_t, new_t) };
- let (na, nb) = (frame.corrected_to_transformed(a), frame.corrected_to_transformed(b));
- // a press that only selected (it landed within the endpoint's grab radius
- // and never moved) writes no guide: compare against where it went down
- let moved = from.distance(q) > 2.0;
- if moved && na.dist(nb) > 0.02 {
- let all: Vec<[f64; 4]> = d
- .geometry
- .guides
- .iter()
- .enumerate()
- .map(|(j, g)| {
- let (x, y) = if j == i { (a, b) } else { *g };
- [x.x, x.y, y.x, y.y]
- })
- .collect();
- let _ = app.run("geometry.guides", json!({"guides": all}));
- }
- }
- }
- Some(Gesture::Guide { a }) => {
- if let Some(q) = q
- && map.norm(q).dist(a) > 0.02
- {
- let b = map.norm(q);
- let (ca, cb) = (frame.transformed_to_corrected(a), frame.transformed_to_corrected(b));
- let _ = app.run("geometry.guides", json!({"guides": [[ca.x, ca.y, cb.x, cb.y]], "add": true}));
- }
- }
- other => app.gesture = other,
- }
- }
- }
-
- /// Normalized oriented coords → the straightened (rotated) frame the crop rect lives in.
- fn to_straight(n: Point, angle: f64, frame: &Frame) -> Point {
- let (w, h) = (frame.ow, frame.oh);
- let px = Point::new(n.x * w, n.y * h);
- let r = Affine::rotate_about(angle.to_radians(), Point::new(w / 2.0, h / 2.0)).apply(px);
- Point::new(r.x / w, r.y / h)
- }
-
- /// How far `q` is from the segment `a`–`b` (screen pixels): the click that selects a guide.
- fn point_segment_dist(q: Pos2, a: Pos2, b: Pos2) -> f32 {
- let ab = b - a;
- let t = if ab.length_sq() > 0.0 { ((q - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
- (a + ab * t).distance(q)
- }
-
- /// A crop box's corners (top-left, top-right, bottom-right, bottom-left of the unflipped photo)
- /// in the order they appear on screen when the photo is shown flipped.
- fn flipped_corners(pts: &[Pos2], flip_h: bool, flip_v: bool) -> [Pos2; 4] {
- let at = |i: usize| pts.get(i).copied().unwrap_or(Pos2::ZERO);
- let order = match (flip_h, flip_v) {
- (false, false) => [0, 1, 2, 3],
- (true, false) => [1, 0, 3, 2],
- (false, true) => [3, 2, 1, 0],
- (true, true) => [2, 3, 0, 1],
- };
- order.map(at)
- }
-
- /// The dimming outside the crop box: the photo's rectangle minus the crop quad, as one mesh of
- /// non-overlapping convex pieces. The quad is a rotated rectangle, so its opposite sides are
- /// parallel and the plane outside it splits into four disjoint half-strips: outside edge `i`
- /// and inside edge `i + 1`. Each is clipped to the photo and fanned into triangles.
- ///
- /// Issue #731: joining photo corner `i` to crop corner `i` with a quad per side only works while
- /// the two rectangles are aligned. Rotated, those quads cross themselves and each other, which
- /// showed as dimmed wedges inside the crop and doubly dark ones outside, growing with the angle.
- /// A degenerate quad (a point, a line, a non-finite corner) dims nothing.
- fn outside_crop_mesh(img: Rect, quad: &[Pos2; 4], color: Color32) -> egui::epaint::Mesh {
- let mut mesh = egui::epaint::Mesh::default();
- if !quad.iter().all(|q| q.x.is_finite() && q.y.is_finite()) || !img.is_finite() {
- return mesh;
- }
- let centre = pos2((quad[0].x + quad[1].x + quad[2].x + quad[3].x) / 4.0, (quad[0].y + quad[1].y + quad[2].y + quad[3].y) / 4.0);
- // signed distance from edge i's line, positive towards the crop's centre
- let side = |i: usize, q: Pos2| -> Option<f32> {
- let (a, b) = (quad[i % 4], quad[(i + 1) % 4]);
- let n = vec2(a.y - b.y, b.x - a.x);
- let orient = n.dot(centre - a);
- // an edge the centre lies on: the box is flat
- (orient.abs() > 1e-6 * n.length().max(1.0)).then(|| n.dot(q - a) * orient.signum())
- };
- // Sutherland–Hodgman: the part of a convex polygon where `keep` is at or above zero
- let clip = |poly: &[Pos2], keep: &dyn Fn(Pos2) -> Option<f32>| -> Option<Vec<Pos2>> {
- let mut out = Vec::with_capacity(poly.len() + 2);
- for (k, &a) in poly.iter().enumerate() {
- let b = *poly.get((k + 1) % poly.len())?;
- let (da, db) = (keep(a)?, keep(b)?);
- if da >= 0.0 {
- out.push(a);
- }
- if (da < 0.0) != (db < 0.0) && (da - db).abs() > f32::EPSILON {
- let t = da / (da - db);
- out.push(a + (b - a) * t);
- }
- }
- Some(out)
- };
- let photo = [img.left_top(), img.right_top(), img.right_bottom(), img.left_bottom()];
- for i in 0..4 {
- let outside = |q: Pos2| side(i, q).map(|d| -d);
- let inside_next = |q: Pos2| side(i + 1, q);
- let Some(strip) = clip(&photo, &outside).and_then(|poly| clip(&poly, &inside_next)) else { return egui::epaint::Mesh::default() };
- if strip.len() < 3 {
- continue;
- }
- let base = mesh.vertices.len() as u32;
- mesh.vertices.extend(strip.iter().map(|&pos| egui::epaint::Vertex { pos, uv: Pos2::ZERO, color }));
- for k in 1..(strip.len() as u32).saturating_sub(1) {
- mesh.indices.extend([base, base + k, base + k + 1]);
- }
- }
- mesh
- }
-
- fn frame_crop_quad(d: &DevelopSettings, frame: &Frame) -> [Point; 4] {
- let f = Frame { crop: d.crop.geometry, ..frame.clone() };
- f.crop_quad_norm()
- }
-
- // ------------------------------------------------------------------------ masks
-
- /// Where a mask component's pin sits (normalized), for shapes that have a place on the photo.
- pub(crate) fn component_pin(shape: &MaskShape) -> Option<Point> {
- match shape {
- MaskShape::Radial { center, .. } => Some(*center),
- MaskShape::Linear { start, end } => Some(Point::new((start.x + end.x) / 2.0, (start.y + end.y) / 2.0)),
- MaskShape::Brush { strokes } => strokes.iter().find(|s| !s.erase).and_then(|s| s.points.first()).copied(),
- _ => None,
- }
- }
-
- /// `shape` moved by `dn` (normalized); `handle` 1/2 = a linear gradient's start/end set to `at`.
- fn moved_shape(shape: &MaskShape, handle: u8, dn: Point, at: Point, map: &CanvasMap, alt: bool) -> MaskShape {
- let mv = |p: Point| Point::new(p.x + dn.x, p.y + dn.y);
- match shape.clone() {
- MaskShape::Radial { center, rx, ry, angle, feather, invert } => match handle {
- 1 | 3 => {
- let l = frame_long_norm(map);
- let dx = (at.x - center.x) / l.0;
- let dy = (at.y - center.y) / l.1;
- let (s, co) = angle.to_radians().sin_cos();
- let new_rx = (dx * co + dy * s).abs().max(0.01);
- let mut new_ry = ry;
- if alt {
- new_ry = ry * (new_rx / rx.max(0.01));
- }
- if (new_rx - new_ry).abs() / new_rx.max(new_ry) < 0.05 {
- new_ry = new_rx;
- }
- MaskShape::Radial { center, rx: new_rx, ry: new_ry, angle, feather, invert }
- }
- 2 | 4 => {
- let l = frame_long_norm(map);
- let dx = (at.x - center.x) / l.0;
- let dy = (at.y - center.y) / l.1;
- let (s, co) = angle.to_radians().sin_cos();
- let new_ry = (dx * (-s) + dy * co).abs().max(0.01);
- let mut new_rx = rx;
- if alt {
- new_rx = rx * (new_ry / ry.max(0.01));
- }
- if (new_rx - new_ry).abs() / new_rx.max(new_ry) < 0.05 {
- new_rx = new_ry;
- }
- MaskShape::Radial { center, rx: new_rx, ry: new_ry, angle, feather, invert }
- }
- 5 => {
- let l = frame_long_norm(map);
- let dx = (at.x - center.x) / l.0;
- let dy = (at.y - center.y) / l.1;
- let new_angle = dy.atan2(dx).to_degrees();
- MaskShape::Radial { center, rx, ry, angle: new_angle, feather, invert }
- }
- _ => MaskShape::Radial { center: mv(center), rx, ry, angle, feather, invert },
- },
- MaskShape::Linear { start, end } => match handle {
- 1 => MaskShape::Linear { start: at, end },
- 2 => MaskShape::Linear { start, end: at },
- _ => MaskShape::Linear { start: mv(start), end: mv(end) },
- },
- MaskShape::Brush { mut strokes } => {
- for st in &mut strokes {
- st.points.iter_mut().for_each(|p| *p = mv(*p));
- }
- MaskShape::Brush { strokes }
- }
- s => s,
- }
- }
-
- /// Hit the geometric ellipse, independently of feather/inversion. Radii use long-edge units,
- /// so undo the same scaling and rotation used to draw its outline before testing containment.
- fn radial_body_contains(shape: &MaskShape, at: Point, map: &CanvasMap) -> bool {
- let MaskShape::Radial { center, rx, ry, angle, .. } = shape else { return false };
- if !rx.is_finite() || !ry.is_finite() || *rx <= 0.0 || *ry <= 0.0 {
- return false;
- }
- let l = frame_long_norm(map);
- let dx = (at.x - center.x) / l.0;
- let dy = (at.y - center.y) / l.1;
- let (s, co) = angle.to_radians().sin_cos();
- let x = (dx * co + dy * s) / rx;
- let y = (-dx * s + dy * co) / ry;
- x * x + y * y <= 1.0
- }
-
- /// Colour Range eyedropper: a click samples the colour under it for the selected mask's
- /// colour range, at normalized frame coordinates (crop, rotation and zoom aware);
- /// ⇧-click adds a sample (up to 5).
- fn color_range_pick(app: &mut LightcraftApp, ui: &egui::Ui, resp: &egui::Response, map: &CanvasMap) {
- if resp.clicked()
- && let Some(q) = resp.interact_pointer_pos()
- {
- let n = map.norm(q);
- let add = ui.input(|i| i.modifiers.shift);
- if let Err(e) = app.run("mask.sampleColor", json!({"x": n.x, "y": n.y, "add": add})) {
- app.toast(ui.ctx(), e);
- }
- }
- }
-
- /// The Masking tool on the photo: outlines and handles of the selected mask, a pin per mask
- /// component (click selects its mask, drag moves the component), and brush painting. The mask
- /// itself shows as a rendered overlay ([`view_overlay`]).
- fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
- let long = (map.rect.width().max(map.rect.height())) as f64;
- let active = app.session.active_mask;
- let clip = app.canvas_rect.unwrap_or(map.rect);
- let p = &ui.painter_at(clip);
- // (mask, component, handle, screen position) of everything that can be grabbed
- let mut grips: Vec<(u32, usize, u8, Pos2)> = Vec::new();
- // pins follow Show Pins and the Tool Overlay mode (Shift+H); Auto hides them while brushing
- let (mode, live) = (app.ui.tool_overlay, pins_live(app, resp, map));
- let mut pins = p.clone();
- if mode == ToolOverlay::Auto && matches!(app.gesture, Some(Gesture::Brush { .. })) {
- pins.set_invisible();
- }
- for m in &d.masks {
- let sel = Some(m.id) == active;
- // Ctrl+Shift+O (`mask_overlay_all`) shows every visible mask's region; outline each one
- // too, not just the selected mask. Handles and the rotation grip stay on the selected
- // mask so nothing else becomes draggable. The component check keeps this in step with the
- // painted region (`view_overlay` at detail.rs:1354 only covers masks with components).
- let show_outline = sel || (app.ui.mask_overlay_all && m.visible && !m.components.is_empty());
- let stroke_a: u8 = if sel { 230 } else { 170 };
- for (ci, c) in m.components.iter().enumerate() {
- match &c.shape {
- MaskShape::Radial { center, rx, ry, angle, .. } if show_outline => {
- let pts: Vec<Pos2> = (0..64)
- .map(|i| {
- let a = i as f64 / 64.0 * std::f64::consts::TAU;
- let (s, co) = angle.to_radians().sin_cos();
- let (x, y) = (rx * a.cos(), ry * a.sin());
- let l = frame_long_norm(map);
- map.screen(Point::new(center.x + (x * co - y * s) * l.0, center.y + (x * s + y * co) * l.1))
- })
- .collect();
- p.add(egui::Shape::closed_line(pts, Stroke::new(1.5, Color32::from_white_alpha(stroke_a))));
-
- if sel {
- let l = frame_long_norm(map);
- for (i, a_deg) in [0.0_f64, 90.0_f64, 180.0_f64, 270.0_f64].into_iter().enumerate() {
- let a_local = a_deg.to_radians();
- let (s, co) = angle.to_radians().sin_cos();
- let (x, y) = (rx * a_local.cos(), ry * a_local.sin());
- let q = map.screen(Point::new(center.x + (x * co - y * s) * l.0, center.y + (x * s + y * co) * l.1));
- p.circle_stroke(q, 5.0, Stroke::new(1.5, Color32::WHITE));
- register(ui, format!("maskHandle:{}:{ci}:{}", m.id, i + 1), Rect::from_center_size(q, vec2(14.0, 14.0)));
- grips.push((m.id, ci, i as u8 + 1, q));
- }
-
- let (s, co) = angle.to_radians().sin_cos();
- let rot_r = rx + 0.08;
- let rot_q = map.screen(Point::new(center.x + (rot_r * co) * l.0, center.y + (rot_r * s) * l.1));
- let h1_q = map.screen(Point::new(center.x + (rx * co) * l.0, center.y + (rx * s) * l.1));
- p.line_segment([h1_q, rot_q], Stroke::new(1.0, Color32::from_white_alpha(200)));
- p.circle_stroke(rot_q, 4.0, Stroke::new(1.5, Color32::WHITE));
- register(ui, format!("maskHandle:{}:{ci}:5", m.id), Rect::from_center_size(rot_q, vec2(14.0, 14.0)));
- grips.push((m.id, ci, 5, rot_q));
- }
- }
- MaskShape::Linear { start, end } if show_outline => {
- let (a, b) = (map.screen(*start), map.screen(*end));
- let dir = (b - a).normalized();
- let perp = vec2(-dir.y, dir.x) * 3000.0;
- let (a1, a2): (u8, u8) = if sel { (230, 110) } else { (170, 80) };
- for (q, alpha) in [(a, a1), (b, a2)] {
- p.line_segment([q - perp, q + perp], Stroke::new(1.0, Color32::from_white_alpha(alpha)));
- }
- if sel {
- for (i, q) in [a, b].iter().enumerate() {
- p.circle_stroke(*q, 5.0, Stroke::new(1.5, Color32::WHITE));
- register(ui, format!("maskHandle:{}:{ci}:{i}", m.id), Rect::from_center_size(*q, vec2(14.0, 14.0)));
- grips.push((m.id, ci, i as u8 + 1, *q));
- }
- }
- }
- _ => {}
- }
- if app.ui.mask_pins
- && mode.shows(sel, live)
- && let Some(at) = component_pin(&c.shape)
- {
- let q = map.screen(at);
- pin(&pins, q, sel);
- register(ui, format!("maskPin:{}:{ci}", m.id), Rect::from_center_size(q, vec2(14.0, 14.0)));
- grips.push((m.id, ci, 0, q));
- }
- }
- }
- mask_keys(app, ui, map, d, &grips);
- // Object selections (SAM 3) of the selected mask: each click, green to include, red to exclude
- // (clicks still on their way to the model included)
- let pending = app.session.segmenter.pending_clicks().cloned();
- for m in d.masks.iter().filter(|m| Some(m.id) == active) {
- for (k, c) in m.components.iter().enumerate() {
- if let MaskShape::Object { hint, exclude, .. } = &c.shape {
- let (hint, exclude) = match pending.as_ref().filter(|q| (q.mask, q.comp) == (m.id, k)) {
- Some(q) => (&q.hint, &q.exclude),
- None => (hint, exclude),
- };
- for (pts, col) in [(hint, Color32::from_rgb(40, 200, 90)), (exclude, Color32::from_rgb(230, 60, 60))] {
- for q in pts {
- let q = map.screen(*q);
- p.circle_filled(q, 5.0, col);
- p.circle_stroke(q, 5.0, Stroke::new(1.5, Color32::WHITE));
- }
- }
- }
- }
- }
- // Colour Range "Pick": the Masking panel owns the loupe's clicks (general_interaction
- // never runs while it is open), so the eyedropper is handled here too.
- if app.ui.tool == "colorRange" {
- if resp.hovered() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- }
- color_range_pick(app, ui, resp, map);
- return;
- }
- // Object tool: a click includes what's under it, ⌥-click leaves it out
- if app.ui.tool == "object" {
- if resp.hovered() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- }
- if resp.clicked()
- && let Some(q) = resp.interact_pointer_pos()
- {
- let n = map.norm(q);
- let exclude = ui.input(|i| i.modifiers.alt);
- match app.run_typed("mask.objectPoint", json!({"x": n.x, "y": n.y, "exclude": exclude})) {
- Ok(_) => {
- if let Some(mid) = app.session.active_mask {
- app.ui.detail_due = Some((app.tick_now() + 1.0, mid));
- }
- }
- Err(e) => app.ai_error(ui.ctx(), e, Some(("object", "new"))),
- }
- }
- return;
- }
- // brush tool
- if app.ui.tool == "brush" {
- let r = (app.ui.brush_size as f64 * long) as f32;
- if let Some(h) = resp.hover_pos() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::None);
- p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE));
- p.circle_stroke(h, r * (1.0 - app.ui.brush_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(120)));
- }
- if let Some(q) = resp.interact_pointer_pos()
- && (resp.drag_started() || resp.dragged() || resp.clicked())
- {
- let n = map.norm(q);
- let force = if app.ui.brush_pressure { ui.input(pen_force) } else { None };
- match &mut app.gesture {
- // a held, unmoving pointer records nothing: coverage builds by passes, not time (#518)
- Some(Gesture::Brush { points, .. }) if points.last() == Some(&n) => {}
- Some(Gesture::Brush { points, pressure }) => {
- record_pressure(pressure, points.len(), force);
- points.push(n);
- }
- _ => {
- let mut pressure = Vec::new();
- record_pressure(&mut pressure, 0, force);
- app.gesture = Some(Gesture::Brush { points: vec![n], pressure });
- }
- }
- }
- // the stroke being painted (the render shows it once it's committed), with the committed
- // stroke's dab spacing, feather and flow (issue #517)
- if let Some(Gesture::Brush { points, pressure }) = &app.gesture {
- let screen: Vec<Pos2> = points.iter().map(|q| map.screen(*q)).collect();
- let opacity = if app.ui.mask_overlay && app.ui.mask_overlay_opacity > 0.0 { app.ui.mask_overlay_opacity / 100.0 } else { 110.0 / 255.0 };
- let params = crate::brush_live::LiveParams {
- clip,
- scale: ui.ctx().pixels_per_point(),
- r,
- hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)),
- flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0),
- density: 1.0,
- color: app.ui.mask_overlay_color,
- opacity: opacity.clamp(0.0, 1.0),
- };
- crate::brush_live::paint(&mut app.brush_live, ui.ctx(), p, params, &screen, pressure);
- } else {
- app.brush_live = None;
- }
- if (resp.drag_stopped() || resp.clicked())
- && let Some(Gesture::Brush { points, pressure }) = app.gesture.take()
- {
- app.brush_live = None;
- let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect();
- // holding ⌥ (Alt) paints with the other mode: Erase while adding, Add while erasing
- let (alt, shift) = resp.ctx.input(|i| (i.modifiers.alt, i.modifiers.shift));
- let erase = app.ui.brush_erase != alt;
- // a ⇧-click draws a straight line from where the last stroke ended, as in Lightroom
- let connect = shift && resp.clicked() && pts.len() == 1;
- let _ = app.run(
- "mask.brushStroke",
- json!({"points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather, "flow": app.ui.brush_flow,
- "erase": erase, "autoMask": app.ui.brush_auto_mask, "pressure": pressure, "connect": connect}),
- );
- }
- return;
- }
- // the grip under the pointer: the selected mask's first, then the nearest
- let hit = |q: Pos2| {
- grips
- .iter()
- .filter(|g| g.3.distance(q) < 10.0)
- .min_by(|a, b| {
- (Some(a.0) != active, a.3.distance(q)).partial_cmp(&(Some(b.0) != active, b.3.distance(q))).unwrap_or(std::cmp::Ordering::Equal)
- })
- .copied()
- };
- if resp.clicked()
- && let Some(q) = resp.interact_pointer_pos()
- && let Some((mid, ..)) = hit(q)
- && Some(mid) != active
- {
- let _ = app.run("mask.select", json!({"id": mid}));
- }
- if resp.drag_started()
- && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
- {
- let grip = hit(q).map(|(m, c, h, _)| (m, c, h)).or_else(|| {
- let m = d.masks.iter().find(|m| Some(m.id) == active)?;
- // Handles take precedence; otherwise grab the selected radial component under
- // the press, including components after the first in compound masks.
- let at = map.norm(q);
- if let Some(ci) = m.components.iter().position(|c| radial_body_contains(&c.shape, at, map)) {
- return Some((m.id, ci, 0));
- }
- // anywhere on the photo drags the selected linear gradient
- matches!(m.components.first()?.shape, MaskShape::Linear { .. }).then_some((m.id, 0, 0))
- });
- if let Some((mask, comp, handle)) = grip
- && let Some(original_shape) = d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone())
- {
- if Some(mask) != active {
- let _ = app.run("mask.select", json!({"id": mask}));
- }
- let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"}));
- app.gesture = Some(Gesture::MaskHandle { mask, comp, handle, original_shape });
- }
- }
- if resp.dragged()
- && let (Some(Gesture::MaskHandle { mask, comp, handle, original_shape }), Some(q)) = (app.gesture.clone(), resp.interact_pointer_pos())
- {
- let n = map.norm(q);
- let press_origin = ui.input(|i| i.pointer.press_origin()).unwrap_or(q);
- let n0 = map.norm(press_origin);
- let dn = Point::new(n.x - n0.x, n.y - n0.y);
- let alt = ui.input(|i| i.modifiers.alt);
- let new_shape = moved_shape(&original_shape, handle, dn, n, map, alt);
- let _ = app.run("mask.update", json!({"id": mask, "component": comp, "shape": new_shape}));
- }
- if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::MaskHandle { .. })) {
- app.gesture = None;
- let _ = app.run("develop.endInteraction", json!({}));
- }
- }
-
- /// A mask handle's name for screen readers: `handle` 0 is the component's pin, 1..5 a radial
- /// gradient's right / bottom / left / top edge and rotation, 1..2 a linear gradient's start and end.
- fn mask_handle_name(mask: &str, shape: &MaskShape, handle: u8) -> String {
- let part = match (shape, handle) {
- (_, 0) => "pin",
- (MaskShape::Radial { .. }, 1) => "right edge",
- (MaskShape::Radial { .. }, 2) => "bottom edge",
- (MaskShape::Radial { .. }, 3) => "left edge",
- (MaskShape::Radial { .. }, 4) => "top edge",
- (MaskShape::Radial { .. }, _) => "rotation",
- (MaskShape::Linear { .. }, 1) => "start",
- (MaskShape::Linear { .. }, _) => "end",
- _ => "handle",
- };
- format!("{mask} {}", crate::i18n::tr(part))
- }
-
- /// Keyboard stand-ins for the mask handles and pins: an arrow press moves the focused one by a
- /// step (one undo step), as dragging it would; Return on a pin selects its mask.
- fn mask_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &DevelopSettings, grips: &[(u32, usize, u8, Pos2)]) {
- for &(mid, ci, handle, q) in grips {
- let Some(m) = d.masks.iter().find(|m| m.id == mid) else { continue };
- let Some(shape) = m.components.get(ci).map(|c| &c.shape) else { continue };
- let at = map.norm(q);
- let mask_name = if m.name.trim().is_empty() { format!("{} {mid}", crate::i18n::tr("Mask")) } else { m.name.clone() };
- let name = mask_handle_name(&mask_name, shape, handle);
- let keys = crate::canvas_keys::handle(ui, &format!("mask:{mid}:{ci}:{handle}"), &name, crate::canvas_keys::position_text(at.x, at.y), q);
- if keys.activated && app.session.active_mask != Some(mid) {
- let _ = app.run("mask.select", json!({"id": mid}));
- }
- let Some((dx, dy)) = keys.delta else { continue };
- if app.session.active_mask != Some(mid) {
- let _ = app.run("mask.select", json!({"id": mid}));
- }
- let to = Point::new(at.x + dx, at.y + dy);
- let new_shape = moved_shape(shape, handle, Point::new(dx, dy), to, map, false);
- let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"}));
- let _ = app.run("mask.update", json!({"id": mid, "component": ci, "shape": new_shape}));
- let _ = app.run("develop.endInteraction", json!({}));
- }
- }
-
- /// Long-edge units → normalized units for x and y.
- fn frame_long_norm(map: &CanvasMap) -> (f64, f64) {
- // derive from the mapping: 1 normalized unit in x and y in screen points
- let o = map.screen(Point::new(0.0, 0.0));
- let x = map.screen(Point::new(1.0, 0.0)).distance(o) as f64;
- let y = map.screen(Point::new(0.0, 1.0)).distance(o) as f64;
- let l = x.max(y);
- (l / x.max(1e-9), l / y.max(1e-9))
- }
-
- /// Auto's condition for the Tool Overlay (Shift+H): the pointer is over the photo, or a pin is
- /// being dragged.
- fn pins_live(app: &LightcraftApp, resp: &egui::Response, map: &CanvasMap) -> bool {
- resp.hover_pos().is_some_and(|q| map.rect.contains(q))
- || matches!(app.gesture, Some(Gesture::SpotMove { .. } | Gesture::MaskHandle { .. }))
- // a handle moved with the keyboard stays shown while it has the focus
- || crate::canvas_keys::has_focus(&resp.ctx)
- }
-
- fn pin(p: &egui::Painter, c: Pos2, sel: bool) {
- p.circle_filled(c, 6.0, if sel { Color32::from_rgb(1, 101, 221) } else { Color32::from_gray(200) });
- p.circle_stroke(c, 6.0, Stroke::new(1.5, Color32::WHITE));
- }
-
- // ------------------------------------------------------------------------ remove
-
- /// The Remove tool on the photo: every spot's outline and pin (the selected one with its source),
- /// click a pin to select its spot, drag a target or source to move it, paint elsewhere to add one.
- /// The Tool Overlay mode (Shift+H) says which spots show; a hidden spot can't be grabbed, so a
- /// click there adds a new one.
- fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
- let long = (map.rect.width().max(map.rect.height())) as f64;
- let active = app.session.active_spot.filter(|i| *i < d.spots.len());
- let (mode, live) = (app.ui.tool_overlay, pins_live(app, resp, map));
- // Auto also hides them while a new spot is painted
- let painting = mode == ToolOverlay::Auto && matches!(app.gesture, Some(Gesture::Spot { .. }));
- let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect));
- let mut pins = p.clone();
- if painting {
- pins.set_invisible();
- }
- // (spot, is source, screen centre, radius) of everything that can be grabbed
- let mut grips: Vec<(usize, bool, Pos2, f32)> = Vec::new();
- for (i, s) in d.spots.iter().enumerate() {
- let r = (s.size * long) as f32;
- let sel = Some(i) == active;
- if !mode.shows(sel, live) {
- continue;
- }
- let p = &pins;
- let col = Color32::from_white_alpha(if sel { 230 } else { 150 });
- for q in &s.points {
- p.circle_stroke(map.screen(*q), r, Stroke::new(if sel { 1.5 } else { 1.0 }, col));
- }
- let Some(&t) = s.points.first() else { continue };
- let tq = map.screen(t);
- if let Some(o) = s.source_offset.filter(|_| sel) {
- let sq = map.screen(Point::new(t.x + o.x, t.y + o.y));
- for q in &s.points {
- p.circle_stroke(map.screen(Point::new(q.x + o.x, q.y + o.y)), r, Stroke::new(1.0, Color32::from_white_alpha(170)));
- }
- let dir = (tq - sq).normalized();
- p.arrow(sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length()), Stroke::new(1.0, Color32::from_white_alpha(200)));
- register(ui, format!("spotSource:{i}"), Rect::from_center_size(sq, vec2(14.0, 14.0)));
- grips.push((i, true, sq, r));
- }
- pin(p, tq, sel);
- register(ui, format!("spotPin:{i}"), Rect::from_center_size(tq, vec2(14.0, 14.0)));
- grips.push((i, false, tq, r));
- }
- if spot_keys(app, ui, map, d, &grips) {
- return;
- }
- let r = (app.ui.remove_size as f64 * long) as f32;
- // a target or source under `q`: the selected spot's first, then the nearest pin
- let hit = |q: Pos2| {
- grips
- .iter()
- .filter(|g| g.2.distance(q) < g.3.max(8.0))
- .min_by(|a, b| {
- (Some(a.0) != active, a.2.distance(q)).partial_cmp(&(Some(b.0) != active, b.2.distance(q))).unwrap_or(std::cmp::Ordering::Equal)
- })
- .copied()
- };
- let hover = resp.hover_pos().and_then(hit);
- if let Some(h) = resp.hover_pos() {
- if hover.is_some() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
- } else {
- ui.ctx().set_cursor_icon(egui::CursorIcon::None);
- p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE));
- p.circle_stroke(h, r * (1.0 - app.ui.remove_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(110)));
- }
- }
- let press = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos());
- if resp.drag_started()
- && let Some((spot, source, ..)) = press.and_then(hit)
- {
- if Some(spot) != active {
- let _ = app.run("spot.select", json!({"index": spot}));
- }
- let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"}));
- app.gesture = Some(Gesture::SpotMove { spot, source });
- }
- if let Some(Gesture::SpotMove { spot, source }) = app.gesture.clone() {
- if resp.dragged()
- && let Some(q) = resp.interact_pointer_pos()
- {
- let (n, n0) = (map.norm(q), map.norm(q - resp.drag_delta()));
- let dn = [n.x - n0.x, n.y - n0.y];
- if dn != [0.0, 0.0] {
- let _ = app.run("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: dn}));
- }
- }
- if resp.drag_stopped() {
- app.gesture = None;
- let _ = app.run("develop.endInteraction", json!({}));
- }
- return;
- }
- if resp.clicked()
- && let Some((spot, ..)) = press.and_then(hit)
- {
- let _ = app.run("spot.select", json!({"index": spot}));
- return;
- }
- if let Some(q) = resp.interact_pointer_pos()
- && (resp.drag_started() || resp.dragged() || resp.clicked())
- {
- let n = map.norm(q);
- match &mut app.gesture {
- Some(Gesture::Spot { points }) => points.push(n),
- _ => app.gesture = Some(Gesture::Spot { points: vec![n] }),
- }
- }
- if let Some(Gesture::Spot { points }) = &app.gesture {
- for q in points {
- p.circle_filled(map.screen(*q), r, Color32::from_white_alpha(60));
- }
- }
- if (resp.drag_stopped() || resp.clicked())
- && let Some(Gesture::Spot { points }) = app.gesture.take()
- {
- let mode = match app.ui.tool.as_str() {
- "heal" => "heal",
- "clone" => "clone",
- "fill" => "fill",
- _ => "remove",
- };
- let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect();
- let _ = app.run(
- "spot.add",
- json!({"mode": mode, "points": pts, "size": app.ui.remove_size, "feather": app.ui.remove_feather, "opacity": app.ui.remove_opacity}),
- );
- }
- }
-
- /// Keyboard stand-ins for the Remove tool: each spot's target and source (an arrow press moves
- /// it a step, one undo step; Return selects the spot), and a placement point that the arrows move
- /// and Return turns into a new spot of the brush's size there. True when a spot was added.
- fn spot_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &DevelopSettings, grips: &[(usize, bool, Pos2, f32)]) -> bool {
- for &(spot, source, q, _) in grips {
- let at = map.norm(q);
- let name =
- format!("{} {}{}", crate::i18n::tr("Spot"), spot + 1, if source { format!(" {}", crate::i18n::tr("source")) } else { String::new() });
- let size = d.spots.get(spot).map(|s| s.size).unwrap_or_default();
- let value = format!("{}, {} {:.0}%", crate::canvas_keys::position_text(at.x, at.y), crate::i18n::tr("size"), size * 100.0);
- let keys = crate::canvas_keys::handle(ui, &format!("spot:{spot}:{}", if source { "source" } else { "target" }), &name, value, q);
- if (keys.activated || keys.delta.is_some()) && app.session.active_spot != Some(spot) {
- let _ = app.run("spot.select", json!({"index": spot}));
- }
- if let Some((dx, dy)) = keys.delta {
- let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"}));
- let _ = app.run("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: [dx, dy]}));
- let _ = app.run("develop.endInteraction", json!({}));
- }
- }
- // where a new spot goes: the photo's centre at first, then wherever the arrows took it
- let key = egui::Id::unique("lc-spot-placement");
- let place: (f64, f64) = ui.data(|m| m.get_temp(key)).unwrap_or((0.5, 0.5));
- let q = map.screen(Point::new(place.0, place.1));
- let keys = crate::canvas_keys::handle(
- ui,
- "spot:new",
- crate::i18n::tr("New spot (Return adds it here)"),
- crate::canvas_keys::position_text(place.0, place.1),
- q,
- );
- if let Some((dx, dy)) = keys.delta {
- let moved = ((place.0 + dx).clamp(0.0, 1.0), (place.1 + dy).clamp(0.0, 1.0));
- ui.data_mut(|m| m.insert_temp(key, moved));
- }
- if crate::canvas_keys::has_focus(ui.ctx()) && ui.memory(|m| m.has_focus(crate::canvas_keys::id("spot:new"))) {
- let r = (app.ui.remove_size as f64 * (map.rect.width().max(map.rect.height())) as f64) as f32;
- ui.painter().circle_stroke(q, r, Stroke::new(1.0, Color32::WHITE));
- }
- if keys.activated {
- let mode = match app.ui.tool.as_str() {
- "heal" => "heal",
- "clone" => "clone",
- "fill" => "fill",
- _ => "remove",
- };
- let _ = app.run(
- "spot.add",
- json!({"mode": mode, "points": [[place.0, place.1]], "size": app.ui.remove_size, "feather": app.ui.remove_feather, "opacity": app.ui.remove_opacity}),
- );
- return true;
- }
- false
- }
-
- // ------------------------------------------------------------------------ red eye
-
- /// Red Eye tool: drag an ellipse over an eye (a new correction), click one to select it.
- fn eye_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
- // screen points per long-edge unit
- let o = map.screen(Point::new(0.0, 0.0));
- let (sx, sy) = (map.screen(Point::new(1.0, 0.0)).distance(o), map.screen(Point::new(0.0, 1.0)).distance(o));
- let per_long = sx.max(sy);
- let p = ui.painter();
- for (i, e) in d.red_eye.iter().enumerate() {
- let c = map.screen(e.center);
- let r = vec2(e.rx as f32 * per_long, e.ry as f32 * per_long);
- let sel = i == app.ui.eye;
- let col = if sel { Color32::WHITE } else { Color32::from_white_alpha(150) };
- p.add(egui::Shape::ellipse_stroke(c, r, Stroke::new(if sel { 1.5 } else { 1.0 }, col)));
- p.line_segment([c - vec2(4.0, 0.0), c + vec2(4.0, 0.0)], Stroke::new(1.0, col));
- p.line_segment([c - vec2(0.0, 4.0), c + vec2(0.0, 4.0)], Stroke::new(1.0, col));
- }
- if resp.hover_pos().is_some() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- }
- if resp.drag_started()
- && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
- {
- // from where the button went down (a drag is recognized only after some movement)
- app.gesture = Some(Gesture::Eye { a: map.norm(q) });
- }
- if let Some(Gesture::Eye { a }) = app.gesture
- && let Some(q) = resp.interact_pointer_pos()
- {
- let (a, b) = (map.screen(a), q);
- p.add(egui::Shape::ellipse_stroke(a.lerp(b, 0.5), ((b - a) / 2.0).abs(), Stroke::new(1.0, Color32::WHITE)));
- }
- if resp.drag_stopped()
- && let Some(Gesture::Eye { a }) = app.gesture.take()
- && let Some(q) = resp.interact_pointer_pos()
- {
- let (sa, sb) = (map.screen(a), q);
- let half = ((sb - sa) / 2.0).abs() / per_long;
- if half.x > 0.002 && half.y > 0.002 {
- let c = map.norm(sa.lerp(sb, 0.5));
- let r = app.run("redeye.add", json!({"center": [c.x, c.y], "rx": half.x, "ry": half.y, "pet": app.ui.eye_pet}));
- if let Ok(v) = r {
- app.ui.eye = v["index"].as_u64().unwrap_or(0) as usize;
- }
- }
- } else if resp.clicked()
- && let Some(q) = resp.interact_pointer_pos()
- && let Some(i) = d.red_eye.iter().position(|e| {
- let c = map.screen(e.center);
- let (dx, dy) = ((q.x - c.x) / (e.rx as f32 * per_long).max(4.0), (q.y - c.y) / (e.ry as f32 * per_long).max(4.0));
- dx * dx + dy * dy <= 1.0
- })
- {
- app.ui.eye = i;
- }
- }
-
- // ------------------------------------------------------------------------ filmstrip
-
- /// A filmstrip cell's file-name label: names longer than 14 characters are cut to 13 and an
- /// ellipsis. Counts characters, not bytes, so a CJK name is never cut inside a character (#266).
- fn film_label(name: &str) -> String {
- if name.chars().nth(14).is_some() { format!("{}…", name.chars().take(13).collect::<String>()) } else { name.to_string() }
- }
-
- /// Draw the horizontal filmstrip in `r`: selectable thumbnail cells with names and format when
- /// film names are on, badges when film badges are on, and stack counts, following the active
- /// photo and scrolling sideways with the wheel. Clicks select: Command toggles and Shift extends
- /// the range; in Compare they adjust the pair's selection, and a plain click replaces the active
- /// side.
- pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) {
- let t = Tokens::get(ui.ctx());
- ui.painter().rect_filled(r, 0.0, t.canvas);
- ui.painter().rect_filled(Rect::from_min_size(r.min, vec2(r.width(), 4.0)), 0.0, Color32::from_gray(0x20));
- let ids = app.session.visible_cloned();
- let active = app.session.selection.active;
- let cell_w = 120.0;
- let ppp = ui.ctx().pixels_per_point();
- if ids.is_empty() {
- let why = if app.session.filter != Default::default() { "No photos match the filters (View → Clear Filters)" } else { "No photos" };
- ui.painter().text(r.center(), Align2::CENTER_CENTER, why, t.font(12.5), t.text_dim);
- return;
- }
- let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r.shrink2(vec2(0.0, 4.0))));
- // a vertical mouse wheel scrolls the strip sideways (horizontal trackpad scrolls still work)
- child.style_mut().always_scroll_the_only_direction = true;
- // only a new active photo (or the strip appearing) scrolls it; see `grid::follow_active`
- let follow = super::grid::follow_active(child.ctx(), egui::Id::unique("film-follow-active"), active, app.session.source);
- // a wheel notch scrolls a third of its width; see `grid::wheel_step`
- register(ui, "filmstrip", child.max_rect());
- let wheel = super::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]).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));
- }
- if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) {
- continue;
- }
- let resp = ui.interact(cr, egui::Id::unique(("film", id.0)), Sense::click());
- let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some();
- crate::widgets::announce(&resp, film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed));
- register(ui, format!("film:{}", id.0), cr);
- let state = app.session.selection.state_of(*id);
- let sel = state == lightcraft_engine::SelectionState::Active;
- 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));
- super::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.tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
- if sel {
- p.rect_stroke(fr, 0.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside);
- } else if state == lightcraft_engine::SelectionState::Selected {
- p.rect_stroke(fr, 0.0, Stroke::new(1.5, Color32::from_gray(170)), StrokeKind::Outside);
- }
- 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 = ui.interact(br, egui::Id::unique(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed {
- "Stack — click to expand"
- } else {
- "Stack — click to collapse"
- });
- crate::widgets::announce(&badge, crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" }));
- register(ui, format!("filmstack:{}", id.0), br);
- 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() {
- super::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)
- super::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);
- }
- }
- // the same photo actions as the grid and loupe (Restore / Delete Permanently in Recently Deleted)
- crate::widgets::context_menu(&resp, |ui| super::grid::context_menu(app, ui, *id));
- }
- });
- }
-
- /// What a screen reader says for a filmstrip thumbnail: the file, and why there is no picture
- /// when the thumbnail failed (the painted `!` has no name of its own). The name is empty when the
- /// catalog no longer has the photo (or its file name is blank); the reason then stands alone.
- pub(crate) fn film_spoken(file_name: &str, failed: bool) -> String {
- match (file_name.is_empty(), failed) {
- (_, false) => file_name.to_string(),
- (true, true) => crate::i18n::tr("This photo can't be opened").to_string(),
- (false, true) => format!("{file_name}, {}", crate::i18n::tr("This photo can't be opened")),
- }
- }
-
- /// Rating, flag and edited badges along a filmstrip thumbnail's bottom edge (Settings → Interface).
- fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog::Photo) {
- use crate::icons::{Icon, paint};
- use lightcraft_catalog::Flag;
- let edited = ph.is_edited();
- if ph.rating == 0 && ph.flag == Flag::None && !edited {
- return;
- }
- let bar = Rect::from_min_max(pos2(fr.left(), fr.bottom() - 15.0), fr.right_bottom());
- p.rect_filled(bar, 0.0, Color32::from_black_alpha(130));
- let y = bar.center().y;
- let mut x = bar.left() + 3.0;
- x += crate::rating::paint_rating(p, pos2(x, y), ph.rating, crate::rating::RatingSize::Small, t.star) + 2.0;
- match ph.flag {
- Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPickFilled, t.pick),
- Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, t.reject),
- Flag::None => {}
- }
- if edited {
- paint(p, Rect::from_min_size(pos2(bar.right() - 13.0, y - 5.0), vec2(10.0, 10.0)), Icon::Sliders, t.text_label);
- }
- }
-
- #[cfg(test)]
- mod preview_geometry_tests {
- use super::{fit_rect, fit_texture_rect, label_badge_rect};
- use crate::state::Zoom;
- use egui::{Rect, pos2, vec2};
-
- /// The "Before" label sits on a dark pill that wraps the text with padding on every side.
- #[test]
- fn before_label_badge_wraps_the_text() {
- let text = vec2(40.0, 14.0);
- let pane = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
- let photo = Rect::from_min_size(pos2(20.0, 30.0), vec2(400.0, 300.0));
- let bg = label_badge_rect(photo, pane, text, 0.0);
- assert_eq!(bg.min, pos2(28.0, 38.0));
- assert_eq!(bg.size(), vec2(56.0, 22.0));
- assert!(photo.contains_rect(bg));
- }
-
- /// Zoomed in, the photo's corner is off the canvas: the pill moves to the canvas' corner
- /// instead of leaving with it (issue #2267), on whichever axes the photo reaches past.
- #[test]
- fn before_label_badge_stays_in_the_pane_when_the_photo_reaches_past_it() {
- let text = vec2(40.0, 14.0);
- let pane = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0));
- let both = label_badge_rect(Rect::from_min_size(pos2(-900.0, -700.0), vec2(3000.0, 2000.0)), pane, text, 0.0);
- assert_eq!(both.min, pos2(108.0, 58.0));
- assert!(pane.contains_rect(both));
- let left_only = label_badge_rect(Rect::from_min_size(pos2(-900.0, 120.0), vec2(3000.0, 400.0)), pane, text, 0.0);
- assert_eq!(left_only.min, pos2(108.0, 128.0));
- assert!(pane.contains_rect(left_only));
- }
-
- /// With a filter active, the pill in the canvas' corner has that corner: the label sits below
- /// it, whether the photo is past the pane or just under the pill. A photo lower down is left
- /// alone. A wide label near the pane's right edge stays inside the pane.
- #[test]
- fn before_label_badge_keeps_clear_of_the_filter_pill_and_the_right_edge() {
- let text = vec2(40.0, 14.0);
- let pane = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0));
- let inset = super::FILTER_PILL_INSET + super::FILTER_PILL_HEIGHT;
- let past = label_badge_rect(Rect::from_min_size(pos2(-900.0, -700.0), vec2(3000.0, 2000.0)), pane, text, inset);
- assert_eq!(past.min, pos2(108.0, 50.0 + inset + 8.0));
- let under = label_badge_rect(Rect::from_min_size(pos2(200.0, 60.0), vec2(400.0, 300.0)), pane, text, inset);
- assert_eq!(under.min.y, 50.0 + inset + 8.0, "a photo whose corner is under the pill moves down too");
- let lower = label_badge_rect(Rect::from_min_size(pos2(200.0, 200.0), vec2(400.0, 300.0)), pane, text, inset);
- assert_eq!(lower.min, pos2(208.0, 208.0));
- let wide = label_badge_rect(Rect::from_min_size(pos2(860.0, 200.0), vec2(400.0, 300.0)), pane, text, 0.0);
- assert!(pane.contains_rect(wide), "{wide:?}");
- assert_eq!(wide.max.x, pane.right() - 8.0, "8 points from the pane's right edge, like the left inset");
- }
-
- #[test]
- fn portrait_preview_keeps_its_ratio_inside_a_landscape_frame() {
- let frame = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 200.0));
- let image = fit_texture_rect(frame, [100, 200]);
-
- assert!((image.width() / image.height() - 0.5).abs() < 1e-6);
- assert_eq!(image.center(), frame.center());
- assert!(frame.contains_rect(image));
- }
-
- /// A 100 % view must put the photo's corner on a whole physical pixel, or the GPU's bilinear
- /// filter softens it (a 1279.5 pt canvas on a 2x display centred the photo half a pixel off).
- #[test]
- fn percent_zoom_lands_on_whole_physical_pixels() {
- let area = Rect::from_min_size(pos2(0.0, 42.0), vec2(1279.5, 726.0));
- for ppp in [1.0, 1.25, 2.0, 3.0] {
- for pan in [(0.5, 0.5), (0.3, 0.7), (0.4999, 0.5001)] {
- let image = fit_rect(area, 5152.0 / 7728.0, Zoom::Percent(100.0), [5152, 7728], ppp, pan);
- for v in [image.min.x, image.min.y] {
- assert!((v * ppp - (v * ppp).round()).abs() < 1e-3, "{v} pt is not a whole pixel at {ppp}x, pan {pan:?}");
- }
- assert!((image.width() * ppp - 5152.0).abs() < 1e-3, "size stays the photo's own pixels");
- }
- }
- }
-
- #[test]
- fn portrait_preview_aspect_fits_detail_area_without_stretching() {
- let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 200.0));
- let image = fit_rect(area, 0.5, Zoom::Fit, [4000, 6000], 1.0, (0.5, 0.5));
-
- assert!((image.width() / image.height() - 0.5).abs() < 1e-6);
- assert_eq!(image.size(), vec2(100.0, 200.0));
- assert_eq!(image.center(), area.center());
- }
- }
-
- /// Straighten tool: drag along a horizon (or a vertical) to set the crop angle; double-click = Auto.
- /// The image is shown unrotated in the crop view, so the line's on-screen angle is its image angle.
- /// `held`: drawn with ⌘ held in the crop tool, which stays active afterwards.
- fn straighten_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, held: bool) {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
- if !held && resp.double_clicked() {
- app.auto_straighten(ui.ctx());
- app.ui.tool.clear();
- app.gesture = None;
- return;
- }
- if resp.drag_started()
- && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
- {
- app.gesture = Some(Gesture::StraightenLine { a: q });
- }
- let Some(Gesture::StraightenLine { a }) = app.gesture.clone() else { return };
- let Some(b) = resp.interact_pointer_pos().or(resp.hover_pos()) else { return };
- let p = ui.painter();
- p.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140)));
- p.line_segment([a, b], Stroke::new(1.5, Color32::WHITE));
- if resp.drag_stopped() {
- app.gesture = None;
- let v = b - a;
- if v.length() > 8.0 {
- let mut deg = v.y.atan2(v.x).to_degrees() as f64;
- // fold to the nearest axis: a line closer to vertical straightens plumb lines
- while deg > 45.0 {
- deg -= 90.0;
- }
- while deg < -45.0 {
- deg += 90.0;
- }
- let _ = app.run("crop.straighten", json!({"angle": (-deg * 100.0).round() / 100.0}));
- }
- if !held {
- app.ui.tool.clear();
- }
- }
- }
-
- #[cfg(test)]
- mod tests {
- /// The rotation pointer's arc bulges away from the side of the crop box it is on, and follows
- /// a box that is itself rotated.
- #[test]
- fn rotate_cursor_faces_away_from_the_crop_box() {
- use egui::{Pos2, pos2};
- use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, PI};
- let near = |a: f32, b: f32| ((a - b + PI).rem_euclid(2.0 * PI) - PI).abs() < 1e-3;
- let pts = [pos2(100.0, 100.0), pos2(300.0, 100.0), pos2(300.0, 200.0), pos2(100.0, 200.0)];
- let turn = |x: f32, y: f32| super::rotate_cursor_turn(&pts, pos2(x, y), false);
- assert!(near(turn(200.0, 80.0), 0.0), "above: as drawn");
- assert!(near(turn(320.0, 150.0), FRAC_PI_2), "right");
- assert!(near(turn(200.0, 230.0), PI), "below");
- assert!(near(turn(70.0, 150.0), -FRAC_PI_2), "left");
- assert!(near(turn(290.0, 60.0), 0.0), "above the top edge near its end: still up");
- // off each corner: diagonally out from it
- assert!(near(turn(80.0, 80.0), -FRAC_PI_4), "top-left corner");
- assert!(near(turn(320.0, 80.0), FRAC_PI_4), "top-right corner");
- assert!(near(turn(320.0, 220.0), 3.0 * FRAC_PI_4), "bottom-right corner");
- assert!(near(turn(80.0, 220.0), -3.0 * FRAC_PI_4), "bottom-left corner");
- assert!(near(super::rotate_cursor_turn(&pts, pos2(200.0, 110.0), true), 0.0), "dragged back over the top edge: still up");
- // a box turned 90°: its top edge is now on the right
- let turned = [pts[3], pts[0], pts[1], pts[2]].map(|p| pos2(400.0 - p.y, p.x));
- assert!(near(super::rotate_cursor_turn(&turned, pos2(420.0, 200.0), false), FRAC_PI_2));
- // a box turned 30°: straight out from its top edge is 30° clockwise of up
- let c = pos2(200.0, 150.0);
- let rot = |p: Pos2| {
- let (s, co) = (30f32.to_radians().sin(), 30f32.to_radians().cos());
- let d = p - c;
- pos2(c.x + d.x * co - d.y * s, c.y + d.x * s + d.y * co)
- };
- let tilted = pts.map(rot);
- assert!(near(super::rotate_cursor_turn(&tilted, rot(pos2(200.0, 60.0)), false), 30f32.to_radians()));
- }
-
- use super::{film_label, flipped_corners, outside_crop_mesh, texture_side};
- use egui::{Color32, Pos2, Rect, pos2};
-
- /// A rotated `w` × `h` box centred on `centre`.
- fn box_at(centre: Pos2, w: f32, h: f32, angle: f32) -> [Pos2; 4] {
- let (s, c) = angle.to_radians().sin_cos();
- [(-w, -h), (w, -h), (w, h), (-w, h)].map(|(x, y)| pos2(centre.x + (x * c - y * s) / 2.0, centre.y + (x * s + y * c) / 2.0))
- }
-
- /// Signed distances from a convex polygon's edges, positive inwards (its winding either way).
- fn sides(poly: &[Pos2], p: Pos2) -> Vec<f32> {
- let n = poly.len() as f32;
- let centre = pos2(poly.iter().map(|q| q.x).sum::<f32>() / n, poly.iter().map(|q| q.y).sum::<f32>() / n);
- (0..poly.len())
- .map(|i| {
- let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
- let nrm = egui::vec2(a.y - b.y, b.x - a.x).normalized();
- nrm.dot(p - a) * nrm.dot(centre - a).signum()
- })
- .collect()
+
+ /// Signed distances from a convex polygon's edges, positive inwards (its winding either way).
+ fn sides(poly: &[Pos2], p: Pos2) -> Vec<f32> {
+ let n = poly.len() as f32;
+ let centre = pos2(poly.iter().map(|q| q.x).sum::<f32>() / n, poly.iter().map(|q| q.y).sum::<f32>() / n);
+ (0..poly.len())
+ .map(|i| {
+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
+ let nrm = egui::vec2(a.y - b.y, b.x - a.x).normalized();
+ nrm.dot(p - a) * nrm.dot(centre - a).signum()
+ })
+ .collect()
}
/// Issue #731: the dimming is the photo minus the crop box at any angle. Every point of the
diff --cc crates/ui-egui/src/tests.rs
index 000000000,49174ff0d..48ddde8e5
mode 000000,100644..100644
--- a/crates/ui-egui/src/tests.rs
+++ b/crates/ui-egui/src/tests.rs
@@@ -1,0 -1,84 +1,85 @@@
+ mod activity;
+ mod album_picker;
+ mod album_remove;
+ mod appearance;
+ mod before_after;
+ mod browse_active;
+ mod button;
+ mod canvas_keys;
+ mod canvas_pan;
+ mod capture_time;
+ mod compare;
+ mod copy_paste_dialogs;
+ mod crop_rotate;
+ mod crop_tool;
+ mod curve;
+ mod date_picker;
+ mod dialog_fit;
+ mod dialog_primary;
+ mod dialog_settings;
+ mod dialog_tab;
+ mod dialogs;
+ mod docking_acceptance;
+ mod drop_import;
+ mod edit_layout;
+ mod empty_library;
+ mod error_kinds;
+ mod filmstrip;
+ mod focus_point;
+ mod folder_drop;
+ mod grading;
+ mod grid;
+ mod guided_guides;
+ mod histogram_drag;
+ mod info_dialogs;
+ mod keymap;
+ mod keyword_files;
+ mod keyword_list;
+ mod keyword_set;
+ mod keyword_sidebar;
+ mod keywording;
+ mod labels;
+ mod launch_library;
+ mod layout_image;
+ mod library_problem;
+ mod lifecycle_037;
+ mod lightroom_destination;
+ mod lights_out;
+ mod mask_effects;
+ mod masking;
+ mod masking_layout;
+ mod menubar;
+ mod merge_preview;
+ mod model_setup;
+ mod offline;
+ mod open_lightroom;
+ pub(super) mod panels;
+ mod preset_favorites;
+ mod preset_import;
+ mod preview_limit;
+ mod print;
+ mod profile_menu;
+ mod profiles_layout;
+ mod progress;
+ mod quit_unsaved;
+ mod rating;
+ mod recheck;
+ mod rename_person;
+ mod rules_editor;
+ mod sam_setup;
+ mod scroll;
+ mod slider_reset;
+ mod slideshow;
+ mod solo_sections;
++mod space_hand;
+ mod switch_library;
+ mod sync;
+ mod tallies;
+ mod temp_slider;
+ mod titlebar;
+ mod tool_overlay;
+ mod unsaved;
+ mod view_cost;
+ mod wb_selector;
+ mod zoom;
+ mod zoom_keys;
diff --cc crates/ui-egui/src/tests/space_hand.rs
index 02c90705b,000000000..02c90705b
mode 100644,000000..100644
--- a/crates/ui-egui/src/tests/space_hand.rs
+++ b/crates/ui-egui/src/tests/space_hand.rs