From 414ae0b2c21efca8c42c8616a1b4db30057945fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bihacsy=20L=C3=A1szl=C3=B3?= <115165402+Skaywalker@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:45:29 +0200 Subject: [PATCH 01/37] i18n(hu): align six rows with the catalog conventions (#5434) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three prompts used the formal verb form ("Adjon", "Válasszon", "kattintson"); the catalog addresses the user informally throughout. Two colour profile messages put an article before a placeholder ("A(z) „{name}”") and glued a suffix to one ("{mode}-profilja"). The correct form depends on the inserted value, so the placeholders now stand after a colon or in brackets. The Ask On Mismatch hint kept the English option name; it now names the Hungarian label of that option in Color Settings. --- crates/ui-egui/src/i18n/hu.tsv | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0404b429cec..54bde5d0c46 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1194,7 +1194,7 @@ Capture Brush Size in Preset Ecsetméret rögzítése az előbeállításban Include Tool Settings Eszközbeállítások belefoglalása Include Color Szín belefoglalása - Enter a name for the brush preset Adjon nevet az ecset-előbeállításnak + Enter a name for the brush preset Adj nevet az ecset-előbeállításnak A brush preset with this name already exists Már van ilyen nevű ecset-előbeállítás New Crop Preset… Új körbevágási előbeállítás… New Tool Preset Új eszköz-előbeállítás @@ -2490,8 +2490,8 @@ navigator Zoom Nagyítás mértéke Camera Raw Filter ({layer}) Camera Raw szűrő ({layer}) Camera Raw isn't open A Camera Raw nincs megnyitva Cancelled opening {name} Megnyitás megszakítva: {name} - The document “{name}” does not have an embedded {mode} profile. A(z) „{name}” dokumentumnak nincs beágyazott {mode}-profilja. - The document “{name}” has an embedded color profile that does not match the current {mode} working space. A(z) „{name}” dokumentum beágyazott színprofilja nem egyezik az aktuális {mode}-munkaszíntérrel. + The document “{name}” does not have an embedded {mode} profile. Nincs beágyazott profil ({mode}) ebben a dokumentumban: „{name}” + The document “{name}” has an embedded color profile that does not match the current {mode} working space. A dokumentum beágyazott színprofilja nem egyezik az aktuális munkaszíntérrel ({mode}): „{name}” Working: {working} Munkaszíntér: {working} Cancelled {label} Megszakítva: {label} Clarity Tisztaság @@ -4018,7 +4018,7 @@ cameraRaw Yellow Sárga The layer or its mask changed. Drag the mask onto the Trash again. A réteg vagy a maszkja megváltozott. Húzd újra a maszkot a Kukába. Transform On Drop Átalakítás elengedéskor Vanishing Point is not active Az Enyészpont nem aktív - Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattintson a négy sarokra + Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattints a négy sarokra Response curve Válaszgörbe Show home recent files Legutóbbi fájlok megjelenítése a kezdőképernyőn Clear Brush Controls Ecsetvezérlők törlése @@ -4051,7 +4051,7 @@ cameraRaw Yellow Sárga Drag to pan · Scroll to zoom · Double-click to fit Húzás: mozgatás · Görgetés: nagyítás · Dupla kattintás: igazítás Gradient Preset Options Színátmenet-előbeállítás beállításai Import .GRD .GRD importálása - Choose a gradient file (.grd). Válasszon színátmenetfájlt (.grd). + Choose a gradient file (.grd). Válassz színátmenetfájlt (.grd). Save Settings… Beállítások mentése… Load Settings… Beállítások betöltése… Save these settings as a Camera Raw .xmp file A beállítások mentése Camera Raw .xmp-fájlként @@ -4078,7 +4078,7 @@ cameraRaw Yellow Sárga Use the embedded profile ({profile}) A beágyazott profil használata ({profile}) Convert to the working space ({profile}) Átalakítás a munkaszíntérbe ({profile}) Remember this choice for future images A választás megjegyzése a későbbi képekhez - Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. A kérdés a Szerkesztés › Színbeállítások Ask On Mismatch beállításával kapcsolható vissza. + Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. A kérdést a Szerkesztés › Színbeállítások „Profileltérés: rákérdezés megnyitáskor” beállításával kapcsolhatod vissza. Button Mode Gomb mód Button Mode On Gomb mód be From 2b934aa53ae35935203c3475a826a32903e08ce8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stevan=20Marjanovi=C4=87?= Date: Thu, 15 Oct 2026 04:45:34 +0200 Subject: [PATCH 02/37] UI: centre text vertically in shared text fields (#5550) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * UI: centre text vertically in shared text fields TextEdit draws its line at the top of its rect, and the theme's 24 pt interact height made the edit taller than the field's inside, so text in widgets::text_field sat a few pixels high (Preferences search, hex fields, name fields) while dropdowns and value fields were centred. Fill the box and centre the line in it. * Fixed failing test --------- Co-authored-by: Stevan Marjanović <24486184+stevanmarjanovic@users.noreply.github.com> --- crates/ui-egui/src/widgets.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 93f96797025..9f2521a8658 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -759,14 +759,20 @@ pub fn text_field_ex(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, w ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); } let font = if mono { theme::mono(12.0) } else { egui::FontId::proportional(12.5) }; - let mut edit = egui::TextEdit::singleline(text).id(id).hint_text(hint).frame(egui::Frame::NONE).font(font); + let inner = rect.shrink2(TEXT_FIELD_PAD); + // TextEdit draws its text at the top of its rect; fill the box and centre the line in it, so + // the text sits on the field's middle like a dropdown's or value field's. + let mut edit = + egui::TextEdit::singleline(text).id(id).hint_text(hint).frame(egui::Frame::NONE).font(font).min_size(inner.size()).vertical_align(egui::Align::Center); if let Some(limit) = char_limit { edit = edit.char_limit(limit); } // A child Ui keeps the field's selection colour local: `Visuals::selection` also fills selected // list rows and slider trails, which must keep the theme's. let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(TEXT_FIELD_PAD)).layout(layout)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(layout)); + // The theme's 24 pt interact height would make the edit taller than the box's inside. + child.spacing_mut().interact_size.y = inner.height(); child.style_mut().visuals.selection.bg_fill = t.field_selection(); child.add(edit) } From 88c7286d99847e8292c75e2471c75c72a01a90ac Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:45:39 +0300 Subject: [PATCH 03/37] fix(ui): the Move tool keeps Photoshop's arrow pointer (#5814) The canvas cursor match mapped Tool::Move to CursorIcon::Move, the 4-way move cursor, while Photoshop shows its standard arrow pointer and marks the movable layer with the hover outline. Use CursorIcon::Default for the tool (#5646). --- crates/ui-egui/src/canvas.rs | 4 +++- crates/ui-egui/src/marquee_tests.rs | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 37415bc0c15..d9414d857f7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3991,7 +3991,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: { egui::CursorIcon::Crosshair } - Tool::Move => egui::CursorIcon::Move, + // Photoshop's Move tool keeps the standard arrow pointer (#5646): the movable + // layer under it is marked by the hover outline, not by a different cursor. + Tool::Move => egui::CursorIcon::Default, // Dragging is handled with the pan itself, above. Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false), Tool::RotateView => crate::rotate_view::cursor(response.dragged()), diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index 40e9bbd392c..169d4588b9f 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -546,6 +546,15 @@ fn mouse_drag_inside_the_selection_moves_it() { assert_eq!(selection(&h), Rect::new(120, 90, 220, 170), "moved by (20, 10)"); } +/// #5646: the Move tool keeps Photoshop's arrow pointer instead of the 4-way move cursor (the +/// hover outline still marks the layer under the pointer). +#[test] +fn the_move_tool_keeps_the_arrow_pointer() { + let mut h = harness(Tool::Move); + move_to(&mut h, 200.0, 150.0); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default); +} + /// #1428: hovering inside the ants with a marquee shows the move cursor (a press there drags the /// outline); outside it is the marquee's own cursor. #[test] From 9b59a8ca6e0b687450392b290f53b26b23fa878c Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Thu, 15 Oct 2026 09:45:45 +0700 Subject: [PATCH 04/37] fix(pen): keep unfinished paths in their original document (#5460) * fix(pen): finish draft before creating a document * test(pen): keep open work path in its source document --- crates/ui-egui/src/lib.rs | 4 ++++ crates/ui-egui/src/pen_draw_tests.rs | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5929e933851..32a39623438 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1086,6 +1086,10 @@ impl PhotocraftApp { id, "layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath" ) && on_active_layer; + // A draft Pen path belongs to the current document, not the one about to be created. + if id == "file.new" && self.ui.pen.is_some() { + vector_ui::pen_commit(self, false); + } let r = if id == "actions.play" { actions::play(self, ¶ms) } else if photocraft_engine::actions_cmds::shell_view_command(id) { diff --git a/crates/ui-egui/src/pen_draw_tests.rs b/crates/ui-egui/src/pen_draw_tests.rs index 74689a10707..d8bb39d82f4 100644 --- a/crates/ui-egui/src/pen_draw_tests.rs +++ b/crates/ui-egui/src/pen_draw_tests.rs @@ -122,6 +122,23 @@ fn alt_breaks_the_handle_being_dragged_and_grabs_the_last_outgoing_handle() { assert!(near([k.out_ctrl.x, k.out_ctrl.y], [140.0, 20.0])); } +#[test] +fn opening_a_new_document_finishes_the_previous_pen_path() { + let mut h = harness(); + click(&mut h, [20.0, 20.0]); + click(&mut h, [120.0, 20.0]); + assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2)); + let original = h.state().session.active().unwrap().doc.id; + + h.state_mut().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + assert!(h.state().ui.pen.is_none(), "the Pen draft must not overlay the new document"); + let docs = h.state().session.documents(); + assert_eq!(docs.len(), 2); + assert_eq!(docs[0].doc.id, original); + assert_eq!(docs[0].doc.work_path.as_ref().unwrap().subpaths[0].knots.len(), 2); + assert!(docs[1].doc.work_path.is_none(), "the new document starts with no path"); +} + #[test] fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() { let mut h = harness(); From f4351cb37cfdb1fc0350d6550009934b2310308d Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:45:59 -0400 Subject: [PATCH 05/37] Drag and drop: PhotoCraft comes to the front after a drop (#5687) (#5894) Files dropped from another app's window (a file manager) were imported, but the source window stayed in front of PhotoCraft. The frame that takes a drop now asks for focus, so PhotoCraft comes forward as Photoshop does. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/file_open/tests.rs | 23 +++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 +++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index bdefab6229a..b1eb1e7b723 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -572,6 +572,29 @@ fn a_drop_slot_counts_documents_not_the_tabs_shown() { assert_eq!(crate::canvas::TabStrip { rect: strip.rect, tabs: vec![] }.slot(10.0), 0); } +/// #5687: files dropped from another app's window bring PhotoCraft to the front (a focus request +/// in the frame that takes the drop), so the source window ends up behind it. +#[test] +fn a_drop_brings_the_window_to_the_front() { + let dir = std::env::temp_dir().join(format!("photocraft-drop-focus-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("photo.png"); + std::fs::write(&file, png_bytes(8, 8)).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).with_max_steps(8).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()) + }); + h.run_steps(2); + let focus = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + h.output().viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::Focus)) + }; + assert!(!focus(&h), "no focus request without a drop"); + h.input_mut().dropped_files.push(dropped(file, Err("read from the path".into()))); + h.step(); + assert!(focus(&h), "the drop brings the window forward"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The whole app (eframe harness, real layout): over the tab strip, the pointer read from the OS /// service picks a slot; files dropped there open (in the background) at it; dropped on the canvas they're placed in Free Transform, and Esc takes the place back. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 32a39623438..6f4346e06c3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1839,6 +1839,9 @@ impl eframe::App for PhotocraftApp { if !dropped.is_empty() { let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); self.open_dropped(ctx, dropped, at); + // Files dragged in from another app's window: PhotoCraft comes to the front and takes + // the keyboard, as Photoshop does, instead of staying behind the source (#5687). + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); } self.place_next_dropped(ctx); // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a From 2fbd171427b2fe3c1908552d239822e1d9f4172f Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Thu, 15 Oct 2026 04:46:04 +0200 Subject: [PATCH 06/37] Options bar: Show Transform Controls in every theme (#5740) (#5802) The Studio, Adwaita and Breeze themes' Move tool options bar had only Auto-Select and a hint, so Show Transform Controls could not be turned on there and a click on a layer never showed its box and handles. The toggle is now in every theme, as Auto-Select is (#1275). Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/move_auto_select_tests.rs | 26 ++++++++++++++++++++ crates/ui-egui/src/panels.rs | 3 +++ 2 files changed, 29 insertions(+) diff --git a/crates/ui-egui/src/move_auto_select_tests.rs b/crates/ui-egui/src/move_auto_select_tests.rs index 0f01222a57b..3d635922e34 100644 --- a/crates/ui-egui/src/move_auto_select_tests.rs +++ b/crates/ui-egui/src/move_auto_select_tests.rs @@ -152,6 +152,32 @@ fn every_theme_shows_the_auto_select_toggle() { } } +#[test] +fn every_theme_shows_the_transform_controls_toggle() { + // #5740: outside the Pro themes the Move tool's options bar had no Show Transform Controls, so + // a click on a layer never showed its box and handles there. + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + for theme in crate::theme::ThemeKind::ALL { + let (app, _, _) = app(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 60.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, theme); + h.run_steps(4); + let before = h.state().ui.tool_options.move_show_transform; + h.get_by_label("Show Transform Controls").click(); + h.run_steps(2); + assert_ne!(h.state().ui.tool_options.move_show_transform, before, "{theme:?}: the toggle flips Show Transform Controls"); + } +} + #[test] fn every_theme_shows_the_type_options() { // #1387: outside the Pro themes the Type tool's options bar was only the hint "Click to add diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 769f5a8b9a4..d8b8e93cfba 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1391,6 +1391,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Tool::Move => { // The Studio themes keep Photoshop's Auto-Select toggle too (#1275). widgets::checkbox(ui, &mut app.ui.tool_options.move_auto_select, tl!("Auto-Select:")); + // And Show Transform Controls (#5740): without it the box could not be + // turned on outside the Pro themes. + widgets::checkbox(ui, &mut app.ui.tool_options.move_show_transform, tl!("Show Transform Controls")); hint(ui, tl!("Drag to move the active layer")); } Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), From 37f57f2e9c4edba7414eb0095330241999ef926a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:46:09 +0200 Subject: [PATCH 07/37] Preserve Layers scroll per document (#5522) (#5540) * chore: reserve draft implementation for #5522 * fix(ui): retain each document's Layers scroll position (#5522) --- crates/ui-egui/src/layer_reveal_tests.rs | 29 ++++++++++++++++++++++++ crates/ui-egui/src/panels.rs | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/layer_reveal_tests.rs b/crates/ui-egui/src/layer_reveal_tests.rs index e2c65a32220..181e42dc17e 100644 --- a/crates/ui-egui/src/layer_reveal_tests.rs +++ b/crates/ui-egui/src/layer_reveal_tests.rs @@ -132,3 +132,32 @@ fn reveal_survives_odd_documents() { h.state_mut().sync_views(); h.run_steps(3); } +#[test] +fn layers_scroll_position_survives_document_switches() { + for theme in [ThemeKind::ProMedium, ThemeKind::Studio] { + let (app, inner, _, _, _) = tall_doc(); + let mut h = harness(app, theme); + h.state_mut().run("layer.select", json!({"layer": inner.0})).unwrap(); + h.run_steps(4); + let before = row(&h, "Deep inside").unwrap(); + assert!(in_view(&h, before)); + + // A short second document clamps its own scroll offset to zero. That must + // not erase the first document's position or trigger a selection change. + h.state_mut().run("file.new", json!({"width": 20, "height": 20})).unwrap(); + h.state_mut().sync_views(); + h.run_steps(4); + for _ in 0..3 { + h.state_mut().session.set_active(0); + h.state_mut().sync_views(); + h.run_steps(4); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(inner)); + let restored = row(&h, "Deep inside").unwrap(); + assert!(in_view(&h, restored), "{theme:?}: restored bottom row: {restored:?}"); + assert!((restored.top() - before.top()).abs() < 0.5, "{theme:?}: restored exact scroll position"); + h.state_mut().session.set_active(1); + h.state_mut().sync_views(); + h.run_steps(4); + } + } +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d8b8e93cfba..fcdbe4bb2e6 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2312,7 +2312,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let fill = ui.available_height() > footer + 60.0; let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY }; egui::ScrollArea::vertical() - .id_salt("layer-rows") + // Keep each document's position independent, even when tab indices change (#5522). + .id_salt(("layer-rows", doc.id.0)) .max_height(rows_h) .min_scrolled_height(if fill { rows_h } else { 0.0 }) .auto_shrink([false, !fill]) From be4cadd83ddb81a24a630c64ad4e8404c44c9186 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:46:15 -0400 Subject: [PATCH 08/37] Rulers: Alt-drag makes a guide of the other orientation (#5698) (#5885) As in Photoshop, dragging a guide out of the top ruler with Alt/Option held makes a vertical guide, and out of the left ruler a horizontal one; without Alt each ruler makes its own kind, as before. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/rulers.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs index 7f908600655..972d7c0346b 100644 --- a/crates/ui-egui/src/rulers.rs +++ b/crates/ui-egui/src/rulers.rs @@ -431,6 +431,9 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: & ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical }); } if let Some(pos) = resp.interact_pointer_pos().filter(|_| salt != "ruler-corner" && (resp.dragged() || resp.drag_started())) { + // ⌥/Alt turns the guide the other way, as in Photoshop: a vertical guide out of the top + // ruler, a horizontal one out of the left (#5698), switching as Alt goes up and down. + let vertical = vertical != ui.input(|i| i.modifiers.alt); let d = xf.to_doc(pos); let along = if vertical { d[0] } else { d[1] }; let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) }; @@ -951,6 +954,35 @@ mod tests { } } + /// #5698: as in Photoshop, an Alt-drag out of the top ruler makes a vertical guide and one out + /// of the left ruler a horizontal guide; without Alt each ruler makes its own kind. + #[test] + fn alt_drags_a_guide_of_the_other_orientation_out_of_a_ruler() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let drag = |from: Pos2, modifiers: egui::Modifiers| { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + let to = xf.to_screen(37.0, 90.0); + h.event_modifiers(egui::Event::PointerMoved(from), modifiers); + h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerMoved(to), modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); + assert_eq!(drag(top, egui::Modifiers::NONE), (vec![], vec![90.0]), "top ruler: horizontal"); + assert_eq!(drag(left, egui::Modifiers::NONE), (vec![37.0], vec![]), "left ruler: vertical"); + assert_eq!(drag(top, egui::Modifiers::ALT), (vec![37.0], vec![]), "Alt from the top ruler: vertical"); + assert_eq!(drag(left, egui::Modifiers::ALT), (vec![], vec![90.0]), "Alt from the left ruler: horizontal"); + } + /// #3770: a guide Shift-dragged out of a ruler lands on the nearest tick the ruler draws /// (tenths of the labelled step, in the ruler unit); without Shift it lands where it's dropped. #[test] @@ -978,6 +1010,8 @@ mod tests { h.state().session.active().unwrap().doc.guides.vertical.clone() }; assert_eq!(drag_guide(egui::Modifiers::NONE), vec![37.0]); + // #5698: Alt turns it into a horizontal guide (at the drop's y, the document's centre). + assert_eq!(drag_guide(egui::Modifiers::ALT), Vec::::new(), "no vertical guide with Alt"); // Pixels at 100%: labels every 100 px, ticks every 10 px. assert_eq!(drag_guide(egui::Modifiers::SHIFT), vec![40.0]); From 3aaffdde681b17ed7653845c467e1e84b2fe4421 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:46:20 -0400 Subject: [PATCH 09/37] Adjustment layers: a live preview is never coarser than the screen (#5764) (#5778) Dragging a Curves point (or any control) in the Properties panel of an adjustment layer previews through `canvas::ensure_proxy_preview`, which picked its downscale factor from the document size alone (`proxy::preview_factor`): any document over 5 MP was drawn from a 2-5x reduced copy at every zoom, so at 100 % the canvas turned blocky until the mouse was released. Cap the factor by the view's zoom with the rule the Image > Adjustments dialogs already use (`adjust_preview::proxy_factor`: the proxy stays at least at screen resolution) when the wgpu compositor can draw the full-size document. At 50 % and closer the drag now shows the full-size composite; zoomed out, the proxy still saves the work. Documents the GPU compositor doesn't cover keep the old proxy (the full size would be a CPU composite per change). Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 14 +++++++++++--- crates/ui-egui/src/proxy.rs | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d9414d857f7..cb7227d6e82 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1924,14 +1924,22 @@ fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option /// If a live adjustment preview is active on a large document, composite it on the proxy and upload /// it under its own GPU key. Returns (factor, gpu key, dimensions) when the proxy should be drawn. -fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64, [u32; 2])> { +/// `zoom` is the view's (physical screen pixels per document pixel). +fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { let (layer, params) = app.live_adjust.clone()?; let (doc_id, revision, doc) = { let st = app.session.documents().get(idx)?; (st.doc.id, st.revision, st.doc.clone()) }; // Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size). - let k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); + let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); + // Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when + // the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen + // (none at 50 % and closer). Otherwise the full size would be a CPU composite per change. + let fine = crate::proxy::view_factor(k, zoom); + if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) { + k = fine; + } if k <= 1 { return None; } @@ -2962,7 +2970,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if app.gpu.is_some() && gpu_ok && let Some((k, key, preview_size)) = - ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx)) + ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx, view.zoom)) { on_gpu = true; app.navigator_gpu.remove(&doc.id); diff --git a/crates/ui-egui/src/proxy.rs b/crates/ui-egui/src/proxy.rs index dc30cc31485..a3a73c75426 100644 --- a/crates/ui-egui/src/proxy.rs +++ b/crates/ui-egui/src/proxy.rs @@ -27,6 +27,13 @@ pub fn preview_factor(doc: &Document, reduced: bool) -> u32 { if reduced { factor(doc) } else { 1 } } +/// A live preview's factor `k` capped for a view at `zoom` (physical screen pixels per document +/// pixel): never coarser than the screen ([`crate::adjust_preview::proxy_factor`]), so a view at +/// 100 % shows full resolution instead of k-pixel blocks while a control moves (#5764). +pub fn view_factor(k: u32, zoom: f32) -> u32 { + k.min(crate::adjust_preview::proxy_factor(zoom)).max(1) +} + pub use photocraft_compose::proxy::{downsample, proxy_document}; #[cfg(test)] @@ -48,6 +55,23 @@ mod tests { assert_eq!(preview_factor(&small, true), 1); } + /// #5764: dragging a Curves point on a large document showed the canvas in k-pixel blocks at + /// any zoom. The proxy may only be as coarse as the screen. + #[test] + fn view_factor_never_coarser_than_the_screen() { + let big = Document::new("b", Size::new(6016, 6016), ColorMode::Rgb, SampleType::U8); + let k = preview_factor(&big, true); + assert!(k > 2, "{k}"); + assert_eq!(view_factor(k, 1.0), 1, "100 %: full resolution"); + assert_eq!(view_factor(k, 2.0), 1, "zoomed in: full resolution"); + assert_eq!(view_factor(k, 0.6), 1); + assert_eq!(view_factor(k, 0.5), 2); + assert_eq!(view_factor(k, 0.1), k, "far out: the document's proxy"); + assert_eq!(view_factor(1, 0.1), 1, "small documents stay full size"); + assert_eq!(view_factor(k, f32::NAN), 1); + assert_eq!(view_factor(0, 0.1), 1); + } + #[test] fn proxy_keeps_structure_and_ids() { let doc = Document::with_background("d", Size::new(4000, 3000), ColorMode::Rgb, SampleType::U8, Color::WHITE); From b6cdb16caffa8095b8e9b61c4da97ac3f05a4aac Mon Sep 17 00:00:00 2001 From: nrq6993-a11y Date: Thu, 15 Oct 2026 05:46:25 +0300 Subject: [PATCH 10/37] UI: unsaved-changes buttons show every key in one style (storytold/photocraft#5564) (#5603) German showed "Ja (Y)" next to "(N)ein". Keys now go inside the words only when every translated label starts with its key; otherwise all labels append it ("Ja (Y)", "Nein (N)", "Abbrechen (C)"). Co-authored-by: Cursor --- crates/ui-egui/src/discard_ui.rs | 50 ++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index 58519899d08..30e5f47deb0 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -265,7 +265,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { vec![(ButtonRole::Default, "Yes", Some(Key::Y), 84.0, Answer::Save), (ButtonRole::Alternate, "No", Some(Key::N), 84.0, Answer::Discard), cancel] }; let mut answer = ctx.input_mut(|i| buttons.iter().find(|b| b.2.is_some_and(|k| i.consume_key(egui::Modifiers::NONE, k))).map(|b| b.4)); - let labels: Vec = buttons.iter().map(|b| button_label(mac, b.1, b.2)).collect(); + let labels = button_labels(mac, &buttons.iter().map(|b| (b.1, b.2)).collect::>()); let row: Vec = buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3)).collect(); let modal = egui::Modal::new(egui::Id::new("discard-prompt")).show(ctx, |ui| { ui.set_max_width(420.0); @@ -361,17 +361,30 @@ enum Answer { } /// macOS keeps the plain button wording even though the keyboard shortcuts still work. +#[cfg(test)] fn button_label(mac: bool, label: &str, key: Option) -> String { - if mac { tl!(label).to_string() } else { key.map_or_else(|| tl!(label).to_string(), |k| mnemonic(label, k)) } + button_labels(mac, &[(label, key)]).into_iter().next().unwrap_or_default() } -/// "(S)ave": the key in parentheses, or appended ("Guardar (S)") when the translation doesn't start with it. -fn mnemonic(label: &str, key: Key) -> String { - let (label, k) = (tl!(label), key.name()); - match label.split_at_checked(1) { - Some((first, rest)) if first.eq_ignore_ascii_case(k) => format!("({first}){rest}"), - _ => format!("{label} ({k})"), - } +/// The labels of one dialog's buttons, each with its key in the same style: "(Y)es" when every +/// translation starts with its key, otherwise appended to all ("Ja (Y)", "Nein (N)") (#5564). +fn button_labels(mac: bool, buttons: &[(&str, Option)]) -> Vec { + let starts_with_key = |label: &str, k: Key| label.split_at_checked(1).is_some_and(|(first, _)| first.eq_ignore_ascii_case(k.name())); + let inline = buttons.iter().all(|&(label, key)| key.is_none_or(|k| starts_with_key(tl!(label), k))); + buttons + .iter() + .map(|&(label, key)| { + let text = tl!(label); + match key { + None => text.to_string(), + Some(_) if mac => text.to_string(), + Some(k) => match text.split_at_checked(1) { + Some((first, rest)) if inline => format!("({first}){rest}"), + _ => format!("{text} ({})", k.name()), + }, + } + }) + .collect() } #[cfg(test)] @@ -529,9 +542,9 @@ mod tests { #[test] fn mnemonic_labels_bracket_the_key() { - assert_eq!(mnemonic("Don't Save", Key::D), "(D)on't Save"); - assert_eq!(mnemonic("Guardar", Key::S), "Guardar (S)"); - assert_eq!(mnemonic("保存", Key::S), "保存 (S)"); + assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save"); + assert_eq!(button_label(false, "Guardar", Some(Key::S)), "Guardar (S)"); + assert_eq!(button_label(false, "保存", Some(Key::S)), "保存 (S)"); } type Prompted = egui_kittest::Harness<'static, PhotocraftApp>; @@ -668,6 +681,19 @@ mod tests { assert_eq!(button_label(false, "Cancel", Some(Key::C)), "(C)ancel"); } + /// German "Ja" doesn't start with Y, so every button appends its key rather than mixing + /// "Ja (Y)" with "(N)ein" (#5564). + #[test] + fn one_dialog_shows_every_key_in_the_same_style() { + let buttons = [("Yes", Some(Key::Y)), ("No", Some(Key::N)), ("Cancel", Some(Key::C))]; + assert_eq!(button_labels(false, &buttons), ["(Y)es", "(N)o", "(C)ancel"]); + let german = crate::i18n::Lang::from_code("de").unwrap(); + crate::i18n::with_language(german, || { + assert_eq!(button_labels(false, &buttons), ["Ja (Y)", "Nein (N)", "Abbrechen (C)"]); + assert_eq!(button_labels(true, &buttons), ["Ja", "Nein", "Abbrechen"]); + }); + } + #[test] fn macos_asks_dont_save_cancel_save_with_the_default_last() { let mut h = prompt_on(egui::os::OperatingSystem::Mac); From 8e2c5ddb40ffe9780f55afbe75996a24d52eb33c Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:46:30 -0400 Subject: [PATCH 11/37] macOS: a bundled app keeps its own Dock icon (#5849) (#5879) The main window set a runtime PNG icon everywhere. On macOS that replaces the app bundle's PhotoCraft.icns in the Dock, so the system couldn't render it in its own style (Liquid Glass and its tinted and dark variants). The runtime icon is now skipped when running from an .app bundle; unbundled runs and the Windows and Linux builds still set it. Co-authored-by: Claude Opus 5.5 --- apps/photocraft/src/app_icon.rs | 35 +++++++++++++++++++++++++++++++++ apps/photocraft/src/main.rs | 6 ++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/apps/photocraft/src/app_icon.rs b/apps/photocraft/src/app_icon.rs index 90ce94ea041..54eea2d6b58 100644 --- a/apps/photocraft/src/app_icon.rs +++ b/apps/photocraft/src/app_icon.rs @@ -26,6 +26,25 @@ pub fn window_icon() -> egui::IconData { } } +/// Whether the window gets [`window_icon`] at runtime: everywhere except inside a macOS app +/// bundle. There the Dock shows the bundle's `PhotoCraft.icns` (`CFBundleIconFile`), which macOS +/// renders in its own style (Liquid Glass and its tinted and dark variants); a runtime PNG +/// replaced it with a flat picture (#5849). `exe` is the running executable. +pub fn sets_runtime_icon(exe: Option<&std::path::Path>) -> bool { + !(cfg!(target_os = "macos") && exe.is_some_and(in_app_bundle)) +} + +/// Whether `exe` is an app bundle's executable: `…/Name.app/Contents/MacOS/binary`. +fn in_app_bundle(exe: &std::path::Path) -> bool { + let name = |p: Option<&std::path::Path>| p.and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()); + let macos = exe.parent(); + let contents = macos.and_then(std::path::Path::parent); + let bundle = contents.and_then(std::path::Path::parent); + name(macos).as_deref() == Some("MacOS") + && name(contents).as_deref() == Some("Contents") + && name(bundle).is_some_and(|n| n.len() > 4 && n.to_ascii_lowercase().ends_with(".app")) +} + #[cfg(target_os = "macos")] const PNG: &[u8] = include_bytes!("../../../assets/app-icon/photocraft-1024.png"); #[cfg(not(target_os = "macos"))] @@ -45,6 +64,22 @@ mod tests { u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize } + /// #5849: a macOS app bundle keeps its .icns in the Dock; unbundled runs (cargo run, the + /// Linux and Windows builds) still set the runtime icon. + #[test] + fn only_a_macos_app_bundle_skips_the_runtime_icon() { + use std::path::Path; + assert!(in_app_bundle(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft"))); + assert!(in_app_bundle(Path::new("/Users/a/Downloads/PhotoCraft Beta.APP/Contents/MacOS/photocraft"))); + assert!(!in_app_bundle(Path::new("/Users/a/src/photocraft/target/release/photocraft"))); + assert!(!in_app_bundle(Path::new("/opt/Contents/MacOS/photocraft")), "not inside a .app"); + assert!(!in_app_bundle(Path::new("/.app/Contents/MacOS/photocraft")), "a bare `.app` is no bundle name"); + assert!(!in_app_bundle(Path::new("photocraft"))); + assert!(sets_runtime_icon(None)); + assert!(sets_runtime_icon(Some(Path::new("/usr/bin/photocraft")))); + assert_eq!(sets_runtime_icon(Some(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft"))), !cfg!(target_os = "macos")); + } + #[test] fn window_icon_decodes() { let icon = window_icon(); diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 1739568159b..de1155edbd3 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -78,9 +78,11 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { /// different offset every launch (#419). A later launch restores the saved position instead /// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves. fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { + let viewport = egui::ViewportBuilder::default(); + // Not inside a macOS app bundle: its Dock icon is the bundle's .icns (`app_icon`, #5849). + let viewport = if app_icon::sets_runtime_icon(std::env::current_exe().ok().as_deref()) { viewport.with_icon(app_icon::window_icon()) } else { viewport }; eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_icon(app_icon::window_icon()) + viewport: viewport .with_app_id(APP_ID) .with_title("PhotoCraft") .with_inner_size([1440.0, 900.0]) From 3887d8f738d21b6b4e431d50bcba2c9a59f9004f Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:46:36 -0400 Subject: [PATCH 12/37] Title bar: dialogs no longer stop the window dragging on macOS (#5826) (#5860) The overlay that keeps the title strip's free gap draggable under a dialog's modal layer (#4913) only ran with the custom title bar. macOS keeps the OS traffic lights over the app's own title strip (custom_titlebar is false), so with the Embedded Profile Mismatch prompt or any dialog open the window could not be moved. The overlay now runs whenever the strip is drawn. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 10 +++++++++- crates/ui-egui/src/titlebar.rs | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6f4346e06c3..9c75ec3a368 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1970,7 +1970,7 @@ impl eframe::App for PhotocraftApp { notices::show(self, &ctx); gpu_status::show_fallback(self, &ctx); kys_import::show_offer(self, &ctx); - if chrome && self.ui.panels.menu_bar && self.custom_titlebar && !self.ui.dialogs.is_empty() { + if self.titlebar_modal_drag(chrome) { titlebar::modal_drag_overlay(&ctx); } if self.custom_titlebar { @@ -2041,6 +2041,14 @@ fn read_dropped(_f: &dyn egui::DroppedFile) -> Result, String> { } impl PhotocraftApp { + /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title + /// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not + /// only with the custom title bar: on macOS the strip under the traffic lights is the window's + /// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826). + pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool { + chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty() + } + /// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets /// it and command `id` edits the target (adjustments, filters, fills) without naming one: /// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index de10ca30f3d..25b23ee0f65 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -538,6 +538,23 @@ mod tests { use egui::{Event, Pos2, RawInput, ViewportId}; use photocraft_engine::Session; + /// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS + /// (OS traffic lights over the app's own title strip) a dialog left the window undraggable. + #[test] + fn a_dialog_keeps_the_title_strip_draggable_with_either_title_bar() { + for custom in [false, true] { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.custom_titlebar = custom; + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + assert!(!app.titlebar_modal_drag(true), "no dialog, no overlay"); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + assert!(app.titlebar_modal_drag(true), "custom title bar: {custom}"); + assert!(!app.titlebar_modal_drag(false), "chrome hidden (full screen): no title strip"); + app.ui.panels.menu_bar = false; + assert!(!app.titlebar_modal_drag(true), "no menu bar, no title strip"); + } + } + /// A headless window `width` pt wide showing the title bar and the resize zones. struct Win { ctx: egui::Context, From 7efebfa050ac87561755b44d0093c0fc540deab1 Mon Sep 17 00:00:00 2001 From: Juan Antonio Redondo <35599027+JuanAntonioRC@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:46:41 +0200 Subject: [PATCH 13/37] =?UTF-8?q?fix(path):=20Shift=20locks=20a=20Direct?= =?UTF-8?q?=20Selection=20anchor=20drag=20to=2045=C2=B0=20(#5475)=20(#5498?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dragging selected anchors with the Direct Selection tool ignored Shift, so lengthening a slanted bar also nudged it vertically. As in Photoshop, Shift now locks the anchor move to multiples of 45° from the press, in the live preview and in the committed path.moveAnchors. It works whether Shift is held from the press or added during the drag; Shift at the press still toggles the anchor's selection as before. Reuses stroke_constraint::snap45 (the Gradient tool's Shift lock). Fixes #5475 Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/direct_select.rs | 10 ++++++++-- crates/ui-egui/src/direct_select_tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index 26fba5dadc3..b27d9ea466a 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -94,6 +94,11 @@ pub enum Edit { } impl Edit { + /// The drag's end with ⇧ held: moving anchors locks to multiples of 45°, as in Photoshop (#5475). + fn constrain(&self, start: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] { + if shift && matches!(self, Edit::Anchors(_)) { crate::stroke_constraint::snap45(start, p) } else { p } + } + /// The edit for a drag from `start` to `end`, as a command and its params (without target). fn command(&self, start: [f64; 2], end: [f64; 2]) -> (&'static str, Value) { let d = [end[0] - start[0], end[1] - start[1]]; @@ -238,7 +243,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool let ds = &mut app.ui.direct_selection; match &mut ds.drag { Some(Drag::Edit { base, edit, start, end, preview, .. }) => { - *end = [x, y]; + *end = edit.constrain(*start, [x, y], mods.shift); *preview = edit.preview(base, *start, *end); } Some(Drag::Marquee { end, .. }) => *end = [x, y], @@ -248,7 +253,8 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool } ToolEvent::Up { x, y } => match app.ui.direct_selection.drag.take() { Some(Drag::Edit { target, base, edit, start, .. }) => { - release(app, target, &base, &edit, start, [x, y]); + let end = edit.constrain(start, [x, y], mods.shift); + release(app, target, &base, &edit, start, end); app.ui.direct_selection.coalesce = None; true } diff --git a/crates/ui-egui/src/direct_select_tests.rs b/crates/ui-egui/src/direct_select_tests.rs index 0f3a5ba990b..31a16bfcda2 100644 --- a/crates/ui-egui/src/direct_select_tests.rs +++ b/crates/ui-egui/src/direct_select_tests.rs @@ -326,6 +326,28 @@ fn arrow_keys_nudge_the_selected_anchors() { assert_eq!(work(&app), before); } +/// #5475: ⇧ during an anchor drag locks it to 45°, whether it's held from the press or added later. +#[test] +fn shift_locks_an_anchor_drag_to_45_degrees() { + let mut app = app(Tool::DirectSelection); + with_path(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 44.0, pressure: 1.0 }, Modifiers::SHIFT); + let Some(Drag::Edit { preview: Some(p), .. }) = &app.ui.direct_selection.drag else { panic!("dragging") }; + assert_eq!(p.subpaths[0].knots[0].anchor, Point::new(70.0, 40.0), "the preview is locked too"); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 47.0 }, Modifiers::SHIFT); + assert_eq!(anchor(&app, 0), Point::new(100.0, 40.0)); + + // Diagonal, and without ⇧ the drag stays free. + // (⇧ at the press would deselect the anchor, so it comes once the drag is under way.) + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 131.0, y: 69.0 }, Modifiers::SHIFT); + let a = anchor(&app, 0); + assert!((a.x - 130.0).abs() < 1e-9 && (a.y - 70.0).abs() < 1e-9, "{a:?}"); + drag(&mut app, [130.0, 70.0], [140.0, 73.0], Modifiers::NONE); + assert_eq!(anchor(&app, 0), Point::new(140.0, 73.0)); +} + #[test] fn the_curvature_pen_drags_an_anchor_of_the_active_path_without_a_modifier() { // As in Photoshop: with no path being drawn, pressing an anchor and dragging moves it. From fd28da56dae573df141edc25059e62788eef8304 Mon Sep 17 00:00:00 2001 From: safvanedge Date: Thu, 15 Oct 2026 08:16:46 +0530 Subject: [PATCH 14/37] Type: keep text selection highlight visible while Command/Ctrl is held (#5542) * Type: keep text selection highlight visible while Command/Ctrl is held * Type: match Photoshop 1px dark frame and handle styling for type transform * Merge main; keep the transform box and underline colours from the theme tokens The selection-highlight fix stands on its own; the hard-coded box and underline colours and the removed reference point were unrelated to it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: safvanedge <241307593+safvanedge@users.noreply.github.com> Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/type_tool.rs | 20 ++++++++++---------- crates/ui-egui/src/type_tool_tests.rs | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index bee49293b51..56411274896 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1014,20 +1014,20 @@ pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewX } // Frame: paragraph text shows its box with handles; point text an underline per line. let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); - if crate::type_transform::draw(app, painter, xf, mods) { - return; - } + let has_transform = crate::type_transform::draw(app, painter, xf, mods); let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); let frame = Stroke::new(1.0, t.accent); match shape { Some(photocraft_doc::text::TextShape::Box { x, y, width, height }) => { - let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)]; - painter.add(egui::Shape::closed_line(c.to_vec(), frame)); - let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)]; - for p in c.iter().chain(mids.iter()) { - let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0)); - painter.rect_filled(r, 0.0, Color32::WHITE); - painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside); + if !has_transform { + let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)]; + painter.add(egui::Shape::closed_line(c.to_vec(), frame)); + let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)]; + for p in c.iter().chain(mids.iter()) { + let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0)); + painter.rect_filled(r, 0.0, Color32::WHITE); + painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside); + } } } _ => { diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index 0f5be9e2fa5..725d2890fb7 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -779,6 +779,23 @@ fn temporary_type_transform_visibility_and_cursors() { assert!(crate::type_transform::visible(h.state(), sticky)); } +#[test] +fn type_selection_highlight_visible_with_command_held() { + let (app, _id) = transform_app(false, false, Affine::IDENTITY); + let mut h = harness(1.0, app); + if let Some(ed) = h.state_mut().ui.text_edit.as_mut() { + ed.anchor = 0; + ed.caret = 5; + } + hold(&mut h, type_command()); + h.run(); + let accent = crate::theme::Tokens::get(&h.ctx).accent; + let expected_fill = egui::Color32::from_rgba_unmultiplied(accent.r(), accent.g(), accent.b(), 110); + let has_selection_highlight = + h.output().shapes.iter().any(|clipped| if let egui::Shape::Path(path) = &clipped.shape { path.fill == expected_fill && path.closed } else { false }); + assert!(has_selection_highlight, "selection highlight must remain visible while Ctrl/Cmd is held"); +} + /// Real canvas input: layer-local scaling stays correct across orientation, zoom, HiDPI and flip. #[test] fn temporary_type_transform_scales_without_reflow_or_leaving_type() { From b8e48d6d4c23c7362d63318ca29a40b16f424e03 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:48:20 -0400 Subject: [PATCH 15/37] Filter dialogs: a Random button for seeds (#5710) (#5886) Clouds, Difference Clouds, Add Noise, Fibers and the other seeded filters exposed a seed number, but a new pattern meant typing a different one. A Random button beside every seed field now picks a fresh seed, which the live preview renders at once. "Random" gains its row in the zh-Hans, zh-Hant, ru, fr and id catalogs, which claim complete coverage. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/filter_dialog.rs | 36 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 6 files changed, 41 insertions(+) diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index 3da07352044..92b96f91415 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -822,6 +822,11 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { ui.horizontal(|ui| { ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim)); crate::widgets::value_field(ui, &mut v, -30000.0..=30000.0, "", 80.0); + // A seed gets a fresh random value in one click (#5710): Clouds, Add Noise, + // Fibers… then render a new pattern, as each run of Photoshop's does. + if p.key == "seed" && ui.button(tl!("Random")).clicked() { + v = random_seed(ui.input(|i| i.time).to_bits(), v as i64) as f32; + } }); f.insert(p.key, json!(v.round() as i64)); } @@ -839,6 +844,15 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } } +/// A new seed for a dialog's Random button: 0..=30000 (what the field takes), never `current`. +/// `entropy` varies per click (the input time); the process's random hasher keys mix it. +fn random_seed(entropy: u64, current: i64) -> i64 { + use std::hash::BuildHasher; + let h = std::collections::hash_map::RandomState::new().hash_one(entropy); + let seed = (h % 30_001) as i64; + if seed == current { (seed + 1) % 30_001 } else { seed } +} + /// User-facing params (strip the dialog's private `__` keys). pub fn params_of(f: &Map) -> Value { // A document picker left at "None" (-1) means "not given". @@ -1005,6 +1019,28 @@ impl FilterPreviewKey { mod tests { use super::*; + /// #5710: the seed field's Random button always gives a different seed the field can hold. + #[test] + fn random_seeds_stay_in_range_and_change() { + let mut seen = std::collections::HashSet::new(); + for i in 0..200u64 { + let s = random_seed(i, 7); + assert!((0..=30_000).contains(&s), "{s}"); + assert_ne!(s, 7, "a click always changes the seed"); + seen.insert(s); + } + assert!(seen.len() > 100, "seeds spread out: {}", seen.len()); + assert_ne!(random_seed(1, 30_000), 30_000); + // Every seed dialog shows the button: Clouds, Add Noise and the like carry a `seed` param. + let specs = photocraft_engine::command_specs(); + assert!( + specs + .iter() + .filter(|c| c.id.starts_with("filter.")) + .any(|c| parse_spec(c.params).iter().any(|p| p.key == "seed" && matches!(p.kind, Kind::Int { .. }))) + ); + } + /// Preset names such as "iPhone 14 Pro Max" (the artboard dialog's choices) are text, not /// camelCase keys: they used to read "I Phone 14 Pro Max". #[test] diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index db40d97abf5..84a68be7429 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3179,3 +3179,4 @@ curves Smooth Lisser # View › Guides › right-click a guide Edit Selected Guides Modifier les repères sélectionnés Clear Selected Guides Effacer les repères sélectionnés + Random Aléatoire diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 544ead05a49..eb5167c2e95 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3166,3 +3166,4 @@ curves Smooth Haluskan # View › Guides › right-click a guide Edit Selected Guides Edit Panduan Terpilih Clear Selected Guides Hapus Panduan Terpilih + Random Acak diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 862788630b2..75c91a8836c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3144,3 +3144,4 @@ curves Smooth Сгладить # View › Guides › right-click a guide Edit Selected Guides Изменить выбранные направляющие Clear Selected Guides Удалить выбранные направляющие + Random Случайно diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2307739ed31..1ddd5fd8482 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2790,3 +2790,4 @@ curves Smooth 平滑 # View › Guides › right-click a guide Edit Selected Guides 编辑所选参考线 Clear Selected Guides 清除所选参考线 + Random 随机 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 478489f8c73..b14d5ec8c6b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2775,3 +2775,4 @@ curves Smooth 平滑 # View › Guides › right-click a guide Edit Selected Guides 編輯所選參考線 Clear Selected Guides 清除所選參考線 + Random 隨機 From f44d3b6f0601f79456d692e074e9f8462ba01a55 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:48:26 -0400 Subject: [PATCH 16/37] Brushes: dragging a preset to the list's edge scrolls the list (#5741) (#5862) A preset, group or folder dragged in the Brushes panel or the Brush Preset picker couldn't reach rows out of view: the list didn't scroll while dragging, so the drag stopped at the last visible row. Holding the drag at the list's top or bottom edge (or past it) now scrolls it, with the same ramp as the Layers panel's row drags. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/brushes_tab.rs | 9 ++++++ crates/ui-egui/src/brushes_tab_tests.rs | 37 +++++++++++++++++++++++++ crates/ui-egui/src/panels.rs | 2 +- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs index 709c91c1515..3f45526e526 100644 --- a/crates/ui-egui/src/brushes_tab.rs +++ b/crates/ui-egui/src/brushes_tab.rs @@ -885,6 +885,15 @@ pub fn preset_list(ui: &mut egui::Ui, presets: &[BrushPreset], current: Option<& let show = (st.show_name, st.show_stroke, st.show_tip); let collapsed = &st.collapsed; egui::ScrollArea::vertical().id_salt(layout.id).max_height(layout.max_height).auto_shrink([false, true]).show(ui, |ui| { + // A preset, group or folder dragged to the list's top or bottom edge (or past it) scrolls + // the list, as the Layers panel's rows do, so it can be dropped on rows out of view (#5741). + let dragging = egui::DragAndDrop::has_payload_of_type::(ui.ctx()) && ui.input(|i| i.pointer.primary_down()); + let pointer = ui.ctx().pointer_interact_pos(); + let delta = crate::panels::layer_drag_edge_scroll(pointer, ui.clip_rect(), dragging, ui.input(|i| i.stable_dt)); + if delta != 0.0 { + ui.scroll_with_delta(vec2(0.0, delta)); + ui.ctx().request_repaint(); + } ui.spacing_mut().item_spacing.y = 1.0; for (label, items) in grouped_presets(presets) { let items: Vec<&BrushPreset> = diff --git a/crates/ui-egui/src/brushes_tab_tests.rs b/crates/ui-egui/src/brushes_tab_tests.rs index 4672c062b44..0d0a8b790fb 100644 --- a/crates/ui-egui/src/brushes_tab_tests.rs +++ b/crates/ui-egui/src/brushes_tab_tests.rs @@ -51,6 +51,43 @@ fn dragging_a_brush_shows_its_tip_preview() { } } +/// #5741: a brush dragged to the list's bottom edge (or below it) scrolls the list, so it can be +/// dropped on rows out of view; the list used to stay put, and the drag stopped at the last +/// visible row. +#[test] +fn dragging_a_brush_to_the_list_edge_scrolls_the_list() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.ui.panels.brush_settings = true; + app.ui.brush_tab = 1; + app.ui.brushes_panel.view = BrushesView::List; + app.ui.brushes_panel.collapsed.clear(); + let name = app.session.tools.presets[0].name.clone(); + let (w, h_px) = (1200.0, 520.0); + let mut h = Harness::builder().with_size(vec2(w, h_px)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); + app + }); + h.run_steps(4); + let start = h.get_by_role_and_label(Role::Button, &name).rect(); + h.hover_at(start.center()); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: start.center(), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(start.center() + vec2(0.0, 12.0))); + h.run_steps(2); + assert!(egui::DragAndDrop::has_payload_of_type::(&h.ctx), "the brush is being dragged"); + // Held at the bottom of the window, below the list's last visible row. + let bottom = egui::pos2(start.center().x, h_px - 2.0); + for _ in 0..12 { + h.event(egui::Event::PointerMoved(bottom)); + h.run_steps(1); + } + let moved = h.query_by_role_and_label(Role::Button, &name).map(|n| n.rect()); + assert!(moved.is_none_or(|r| r.top() < start.top() - 1.0), "the list scrolled down: {start:?} → {moved:?}"); + h.event(egui::Event::PointerButton { pos: bottom, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); +} + #[test] fn grid_columns_centre_whole_columns_past_the_indent() { // 6 × 44 + 5 × 3 = 279 of the 290 past a 4 pt indent: 5 spare on each side (rounded down). diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index fcdbe4bb2e6..9fbb765a913 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2166,7 +2166,7 @@ fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static s /// list downward (reveals rows above) and negative upward (reveals rows below). /// The speed ramps with proximity to the edge and clamps to the maximum speed when /// dragged outside, using elapsed time instead of assuming a particular refresh rate. -fn layer_drag_edge_scroll(pointer: Option, viewport: Rect, dragging: bool, dt: f32) -> f32 { +pub(crate) fn layer_drag_edge_scroll(pointer: Option, viewport: Rect, dragging: bool, dt: f32) -> f32 { if !dragging || viewport.width() <= 0.0 || viewport.height() <= 0.0 || dt.is_nan() || dt <= 0.0 { return 0.0; } From f79f21931ec7e830060a2b1f5bd3906dd83cac85 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:48:32 +0300 Subject: [PATCH 17/37] fix(ui): smart filter adjustments open their own editor on double-click (#5812) An Image > Adjustments recorded on a smart object (Brightness/Contrast, Levels, Curves...) stores image.adjustments.. The Layers panel row called smart_ui::open_editor, which only knew filter_dialog and silently did nothing for those commands, so the filter could never be reopened. Route adjustments to adjust_dialog, seed it with the recorded params and let OK run layer.smartFilter.setParams (#5689). --- crates/ui-egui/src/smart_ui.rs | 49 +++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index deee9a7d17f..7f49843c538 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -295,15 +295,29 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: } return; } + // An adjustment recorded on the smart object (Brightness/Contrast, Levels…) re-opens its own + // Image › Adjustments editor, like the filters above. + if crate::adjust_dialog::has_dialog(&f.command) { + if let Some(id) = crate::adjust_dialog::open(app, &f.command) { + edit_filter(app, id, layer, index, &f.params); + } + return; + } if !crate::filter_dialog::has_dialog(&f.command) { return; } let Some(id) = crate::filter_dialog::open(app, &f.command) else { return }; + edit_filter(app, id, layer, index, &f.params); +} + +/// Hands the open dialog `id` the smart filter's recorded `params` and makes OK update that +/// filter (`layer.smartFilter.setParams`, see [`confirm_command`]) instead of adding another. +fn edit_filter(app: &mut PhotocraftApp, id: u64, layer: u64, index: usize, params: &Value) { if let Some(d) = app.ui.dialog_mut(id) { // The live preview would stack a second copy of the filter on the smart object. d.fields.remove("__preview"); d.fields.insert("__smartFilter".into(), json!({"layer": layer, "index": index})); - if let Value::Object(p) = &f.params { + if let Value::Object(p) = params { for (k, v) in p { if d.fields.contains_key(k) { d.fields.insert(k.clone(), v.clone()); @@ -405,4 +419,37 @@ mod tests { assert!(drawn.contains(&(frame, t.field))); assert!(drawn.iter().all(|(_, c)| *c != t.icon)); } + + /// #5689: an Image › Adjustments recorded on a smart object (Brightness/Contrast…) opens its + /// own editor from the Smart Filters row, with the recorded settings, and OK updates that + /// filter instead of stacking another. + #[test] + fn an_adjustment_smart_filter_opens_its_editor_and_updates_it() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("image.adjustments.brightnessContrast", json!({"brightness": 40, "contrast": -10})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let sm = match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + LayerContent::Smart(sm) => sm.clone(), + other => panic!("expected a smart object, got {other:?}"), + }; + assert_eq!(sm.smart_filters.len(), 1); + open_editor(&mut app, &egui::Context::default(), id, &sm, 0); + let d = app.ui.dialogs.last().expect("the adjustment editor opened"); + assert_eq!(d.fields.get("__adjust").and_then(Value::as_str), Some("brightnessContrast")); + assert_eq!(d.fields.get("brightness").and_then(Value::as_f64), Some(40.0), "the recorded settings"); + assert_eq!(d.fields.get("contrast").and_then(Value::as_f64), Some(-10.0)); + let dialog = d.id; + // OK updates the recorded filter (one history step), it does not add a second filter. + crate::dialogs::confirm(&mut app, dialog).unwrap(); + let LayerContent::Smart(sm) = &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { + panic!("the layer stays a smart object"); + }; + assert_eq!(sm.smart_filters.len(), 1, "no filter was stacked"); + assert_eq!(sm.smart_filters[0].params.get("brightness").and_then(Value::as_f64), Some(40.0)); + assert_eq!(sm.smart_filters[0].params.get("contrast").and_then(Value::as_f64), Some(-10.0)); + } } From 3fd787a2b59417015fec3aa674406a3d21261774 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:48:37 -0400 Subject: [PATCH 18/37] Canvas: no scroll glide with Enable Animations off (#5721) (#5883) Interface > Enable Animations off already made scroll areas jump straight to their target, but the canvas still panned from egui's smoothed wheel delta, gliding for several frames after each notch. With the preference off a plain wheel scroll now moves the canvas by the whole notch in the frame it arrives and stops there. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 ++- crates/ui-egui/src/wheel_nav.rs | 45 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cb7227d6e82..8e38d1d57e1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3203,12 +3203,14 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let bars_id = egui::Id::new(("pc-canvas-bars-hover", idx)); let over_bars = ctx.data(|d| d.get_temp::(bars_id)).unwrap_or(false); let nav_hovered = response.hovered() || free_hover || over_bars; - let wheel = crate::wheel_nav::read( + // Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721). + let wheel = crate::wheel_nav::read_with( &ctx, app.session.prefs().general.zoom_with_scroll_wheel, app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch, response.id.with("wheel"), nav_hovered, + app.session.prefs().interface.enable_animations, ); if nav_hovered { let pointer = ui.input(|i| i.pointer.hover_pos()); diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 8917f9123c9..bde5e71ae3e 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -198,6 +198,13 @@ const SNAP_IDLE_TIMEOUT: f64 = 0.5; /// accumulator per viewport. `hovered` gates accumulation: only the viewport receiving /// navigation may add raw input to the snap residual. pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool) -> Option { + read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true) +} + +/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's +/// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch +/// in the frame the wheel turns and stops there (#5721), as scroll areas already do. +pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool) -> Option { let notch = ctx.options(|o| o.input_options.line_scroll_speed); // --- Modifier tracking (always runs for all callers) --- @@ -316,6 +323,8 @@ pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, d.remove::(snap_time_id(owner)); }); } + // Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail). + let scroll = if smooth || alt || shift { scroll } else { raw }; classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, notch }) } } @@ -370,6 +379,42 @@ mod tests { (a - b).length() < 0.01 } + /// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and + /// nothing after; smoothed (the default) it glides, reaching the same total over later frames. + #[test] + fn unsmoothed_wheel_pans_at_once_without_a_glide() { + let pans = |smooth: bool| -> Vec { + let owner = Id::new("test-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, owner, true, smooth) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect() + }; + let notch = { + let ctx = Context::default(); + configure(&ctx); + ctx.options(|o| o.input_options.line_scroll_speed) + }; + let direct = pans(false); + assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); + assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); + let smooth = pans(true); + assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); + assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); + } + #[test] fn plain_scroll_pans() { assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); From 49f878d91b51867fc506fd3e9c8ba5d53f416f34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stevan=20Marjanovi=C4=87?= Date: Thu, 15 Oct 2026 05:48:43 +0200 Subject: [PATCH 19/37] Scaling around reference point no longer snaps center of image to reference point (#5510) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Stevan Marjanović --- crates/ui-egui/src/transform_tool.rs | 109 +++++++++++++-------------- 1 file changed, 51 insertions(+), 58 deletions(-) diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index d35aac90406..13f92b1d5f4 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -1717,8 +1717,7 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods let Some(inv) = h.inverse() else { return }; let (u, v) = inv.apply(p[0], p[1]); let (pu, pv) = inv.apply(g.pivot0[0], g.pivot0[1]); - // Moving edges/corner in unit space: [u0, v0, u1, v1] starting as [0, 0, 1, 1]. - let mut r = [0.0f64, 0.0, 1.0, 1.0]; + // Which sides of the unit box move: (u = 0, u = 1) and (v = 0, v = 1). let (mu, mv) = match g.hit { Hit::Corner(0) => ((true, false), (true, false)), Hit::Corner(1) => ((false, true), (true, false)), @@ -1729,33 +1728,21 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods Hit::Edge(2) => ((false, false), (false, true)), _ => ((true, false), (false, false)), }; - if mu.0 { - r[0] = u; - } - if mu.1 { - r[2] = u; - } - if mv.0 { - r[1] = v; - } - if mv.1 { - r[3] = v; - } - // ⌥: symmetric about the reference point. - if mods.alt { - if mu.0 { - r[2] = 2.0 * pu - r[0]; + // Each axis scales by a factor `k` about an anchor: the opposite side, or with ⌥ the + // reference point, wherever it was set (#1329). The dragged handle follows the cursor. + let axis = |moving: (bool, bool), at: f64, pivot: f64| -> (f64, f64) { + if !moving.0 && !moving.1 { + return (0.5, 1.0); } - if mu.1 { - r[0] = 2.0 * pu - r[2]; - } - if mv.0 { - r[3] = 2.0 * pv - r[1]; - } - if mv.1 { - r[1] = 2.0 * pv - r[3]; - } - } + let handle = if moving.0 { 0.0 } else { 1.0 }; + let anchor = if mods.alt { pivot } else { 1.0 - handle }; + let d = handle - anchor; + // A reference point on the dragged side leaves nothing to scale against. + let k = if d.abs() > 1e-9 { (at - anchor) / d } else { 1.0 }; + (anchor, if k.is_finite() { k } else { 1.0 }) + }; + let (mut au, mut ku) = axis(mu, u, pu); + let (mut av, mut kv) = axis(mv, v, pv); // Corners and edges scale proportionally by default; ⇧ frees them (the legacy // preference swaps the two for corners and always stretches edges, `legacy_mods`). let corner = matches!(g.hit, Hit::Corner(_)); @@ -1765,41 +1752,16 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods // corners), so the opposite edge's handle stays put. Past the opposite edge only // the dragged axis flips. if mu.0 || mu.1 { - let k = (r[2] - r[0]).abs(); - let c = if mods.alt { pv } else { 0.5 }; - r[1] = c - k / 2.0; - r[3] = c + k / 2.0; + (av, kv) = (if mods.alt { pv } else { 0.5 }, ku.abs()); } else { - let k = (r[3] - r[1]).abs(); - let c = if mods.alt { pu } else { 0.5 }; - r[0] = c - k / 2.0; - r[2] = c + k / 2.0; + (au, ku) = (if mods.alt { pu } else { 0.5 }, kv.abs()); } } if corner && !mods.shift { - let (sx, sy) = (r[2] - r[0], r[3] - r[1]); - let k = if sx.abs() > sy.abs() { sx.abs() } else { sy.abs() }; - let (nx, ny) = (k * sx.signum(), k * sy.signum()); - let (ax, ay) = if mods.alt { (pu, pv) } else { (if mu.0 { r[2] } else { r[0] }, if mv.0 { r[3] } else { r[1] }) }; - let fx = if mods.alt { - 0.5 - } else if mu.0 { - 1.0 - } else { - 0.0 - }; - let fy = if mods.alt { - 0.5 - } else if mv.0 { - 1.0 - } else { - 0.0 - }; - r[0] = ax - nx * fx; - r[2] = r[0] + nx; - r[1] = ay - ny * fy; - r[3] = r[1] + ny; + let k = ku.abs().max(kv.abs()); + (ku, kv) = (k * ku.signum(), k * kv.signum()); } + let r = [au - au * ku, av - av * kv, au + (1.0 - au) * ku, av + (1.0 - av) * kv]; let map = |a: f64, b: f64| { let (x, y) = h.apply(a, b); [x, y] @@ -3755,6 +3717,37 @@ mod tests { assert!(close(s.quad, corners([-50.0, 0.0, 150.0, 50.0])), "{:?}", s.quad); } + /// A reference point moved off the centre (⌥-click) is the centre of ⌥-scaling too, not just + /// of rotation: it stays put and the box scales away from it. + #[test] + fn alt_scales_about_a_moved_reference_point() { + let alt = egui::Modifiers::ALT; + // Reference point on the top-left corner: the bottom-right corner to (200, 100) doubles + // the box, top-left fixed (not centred on the reference point). + let mut s = session(); + s.pivot = [0.0, 0.0]; + drag(&mut s, [100.0, 50.0], [200.0, 100.0], alt); + assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad); + assert!(near(s.pivot, [0.0, 0.0]), "{:?}", s.pivot); + // Reference point at (25, 25): the right edge to x = 175 is 2× about x = 25, and + // proportionally 2× about y = 25 too. + let mut s = session(); + s.pivot = [25.0, 25.0]; + drag(&mut s, [100.0, 25.0], [175.0, 25.0], alt); + assert!(close(s.quad, corners([-25.0, -25.0, 175.0, 75.0])), "{:?}", s.quad); + // ⌥⇧: that edge's axis only. + let mut s = session(); + s.pivot = [25.0, 25.0]; + drag(&mut s, [100.0, 25.0], [175.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); + assert!(close(s.quad, corners([-25.0, 0.0, 175.0, 50.0])), "{:?}", s.quad); + // Reference point in line with the dragged corner horizontally: that axis has nothing to + // scale against and stays, the other doubles about it. + let mut s = session(); + s.pivot = [100.0, 50.0]; + drag(&mut s, [100.0, 0.0], [150.0, -50.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); + assert!(close(s.quad, corners([0.0, -50.0, 100.0, 50.0])), "{:?}", s.quad); + } + fn near(a: [f64; 2], b: [f64; 2]) -> bool { (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6 } From 8d8db22c94f8f9058e62fb283c136049c91bfd4d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 05:48:48 +0200 Subject: [PATCH 20/37] Type: a scaled type layer keeps its size when the Character fields show it (#5717) (#5718) egui's DragValue clamps an existing value to its range and reports a change, so showing a type layer scaled past 1296 pt (or below 0.1 pt) sent type.setStyle with the clamped size. Value fields now clamp only edits, never a value they merely show. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/type_tool_tests.rs | 20 ++++++++++++++++ crates/ui-egui/src/widgets.rs | 33 ++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index 725d2890fb7..f56829c6d14 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -1545,6 +1545,26 @@ mod multi_layer_formatting { assert_eq!(text(h.state(), ids[1]).char_runs(), peer); } + /// #5717: a layer scaled so its shown size or leading is past a field's range (2400 pt, or + /// 0.08 pt) keeps it while the Character panel and the options bar only show it. + #[test] + fn showing_a_scaled_layer_past_the_size_range_does_not_change_it() { + for (layer, scale) in [(0, 200.0), (1, 0.005)] { + for properties in [true, false] { + let (mut app, ids) = fixture(); + let id = ids[layer]; + app.run("type.edit", json!({"layer": id.0, "transform": [scale, 0.0, 0.0, scale, 0.0, 0.0]})).unwrap(); + selected(&mut app, &[id]); + let before = text(&app, id).char_runs(); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = controls(app, properties); + h.run_steps(3); + assert_eq!(text(h.state(), id).char_runs(), before, "scale {scale}, properties {properties}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "no history step"); + } + } + } + #[test] fn formatting_menus_isolate_the_edit_layer_and_range_but_honor_explicit_targets() { let (mut app, ids) = fixture(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9f2521a8658..6e841292e79 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -824,6 +824,9 @@ fn number_edit( let mut resp = ui.add( egui::DragValue::new(value) .range(range.clone()) + // Only edits are clamped (below): showing a value past the range, such as a type layer + // scaled to 2400 pt in a 1296 pt field, must not change it (#5717). + .clamp_existing_to_range(false) // A warp is an absolute-position jump. The scoped scrub below removes that jump. .speed(if wrapped_drag { 0.0 } else { speed }) .custom_formatter(move |v, _| match decimals { @@ -844,7 +847,12 @@ fn number_edit( }), ); if wrap_drag { - crate::scrub_wrap::update(ui, &resp, value, before, range, speed, wrapping); + crate::scrub_wrap::update(ui, &resp, value, before, range.clone(), speed, wrapping); + } + let (lo, hi) = (*range.start(), *range.end()); + // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. + if *value != before && lo <= hi { + *value = value.clamp(lo, hi); } resp.flags.set(egui::response::Flags::CHANGED, *value != before); resp @@ -2280,6 +2288,29 @@ mod tests { assert_eq!(*h.state(), (25.0, 3)); } + /// #5717: a value past the range shows as it is without reporting a change; an edit is clamped. + #[test] + fn value_field_keeps_a_shown_value_past_its_range_and_clamps_edits() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + |ui, (v, changes): &mut (f32, u32)| { + if super::value_field(ui, v, 0.1..=1296.0, "pt", 90.0).changed() { + *changes += 1; + } + }, + (2400.0, 0), + ); + h.run_steps(3); + assert_eq!(*h.state(), (2400.0, 0), "showing it changes nothing"); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("5000".into())); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(h.state().0, 1296.0, "a typed value is clamped"); + } + #[test] fn value_field_applies_typed_arithmetic() { use egui::Key::{Enter, Tab}; From cc9967654c0603adeabab61e082b7b2a63543049 Mon Sep 17 00:00:00 2001 From: safvanedge Date: Thu, 15 Oct 2026 09:18:55 +0530 Subject: [PATCH 21/37] fix(ui): restore previous tool when committing or canceling text edit (#5527) (#5528) * fix(ui): restore previous tool when committing or canceling text edit initiated via double-click * fix(ui): restore return tool only while on type and stay on type for layer thumbs - commit_with/cancel: restore return tool only while app.ui.tool.is_type() - edit_active: keep tool on Type when editing from layer thumbnail (matches Photoshop) - clear text_edit_return_tool when text_edit is dropped on lost text or stale transform - test tool switch mid-edit and edit_active remaining on Type --------- Co-authored-by: safvanedge <241307593+safvanedge@users.noreply.github.com> --- crates/ui-egui/src/state.rs | 4 ++ crates/ui-egui/src/type_tool.rs | 55 ++++++++++++++++++++++++++++ crates/ui-egui/src/type_transform.rs | 1 + 3 files changed, 60 insertions(+) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index aeefb3ecbd5..5cbda434e7b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1073,6 +1073,9 @@ pub struct UiState { /// Inline type editing session, if any. #[serde(default)] pub text_edit: Option, + /// Tool to restore when an inline type edit session commits or cancels (e.g. Move tool, #1132). + #[serde(skip)] + pub text_edit_return_tool: Option, /// Ctrl/Cmd Type-tool gesture, exposed to automation but never restored as a held pointer. #[serde(default, skip_deserializing)] pub type_transform: Option, @@ -1304,6 +1307,7 @@ impl Default for UiState { spring: None, recent_files: Vec::new(), text_edit: None, + text_edit_return_tool: None, type_transform: None, type_transform_pivot: None, cam_transform: None, diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 56411274896..d73bb2e2c44 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -121,6 +121,7 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> { ed.caret = n; } let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); + app.ui.text_edit_return_tool = None; app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; app.ui.mask_target = false; app.ui.vector_mask_target = false; @@ -132,6 +133,7 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> { /// type is there. pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { let Some(id) = hit_layer(app, x, y) else { return false }; + let previous_tool = app.ui.tool; commit(app); if app.session.select_layer(id).is_err() { return false; @@ -144,6 +146,9 @@ pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { app.ui.text_edit = Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: false, resize: None, preedit: None }); let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); + if !previous_tool.is_type() { + app.ui.text_edit_return_tool = Some(previous_tool); + } app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; app.ui.mask_target = false; app.ui.vector_mask_target = false; @@ -271,6 +276,7 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie let off = hit_offset(app, id, x, y); app.ui.text_edit = Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: true, resize: None, preedit: None }); + app.ui.text_edit_return_tool = None; return true; } false @@ -335,6 +341,7 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { // Like Photoshop: the placeholder is selected, so typing replaces it. let n = text.chars().count(); app.ui.text_edit = Some(TextEdit { layer: id, caret: n, anchor: 0, session: key, created: true, mask, dragging: false, resize: None, preedit: None }); + app.ui.text_edit_return_tool = None; } } @@ -773,6 +780,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { let id = LayerId(ed.layer); let Some(text) = current_text(app, id) else { app.ui.text_edit = None; + app.ui.text_edit_return_tool = None; return false; }; // Undo/redo can shorten the text under us. @@ -960,6 +968,11 @@ pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) { } crate::type_transform::reset(app); let Some(ed) = app.ui.text_edit.take() else { return }; + if let Some(tool) = app.ui.text_edit_return_tool.take() + && app.ui.tool.is_type() + { + app.ui.tool = tool; + } let Some(text) = current_text(app, LayerId(ed.layer)) else { return }; if ed.mask { // Type Mask: the text's glyphs become (or combine with) the selection and the working @@ -2392,6 +2405,11 @@ fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { pub fn cancel(app: &mut PhotocraftApp) { crate::type_transform::reset(app); let Some(ed) = app.ui.text_edit.take() else { return }; + if let Some(tool) = app.ui.text_edit_return_tool.take() + && app.ui.tool.is_type() + { + app.ui.tool = tool; + } undo_session(app, &ed); } @@ -2682,4 +2700,41 @@ mod tests { assert_eq!(word_boundary("hello big world", 7, false), 6); assert_eq!(word_boundary("hello big world", 15, false), 10); } + #[test] + fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() { + let (mut app, _) = variants(); + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Move, "commit restores the Move tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Also test cancel + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + cancel(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Move, "cancel restores the Move tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Switching tools mid-edit commits without overriding the newly chosen tool + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); + app.ui.tool = crate::state::Tool::Brush; + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Brush, "switching tools keeps the chosen tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Layers-thumbnail edit stays on Type tool (matches Photoshop) + app.ui.tool = crate::state::Tool::Move; + edit_active(&mut app).unwrap(); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, None); + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool"); + } } diff --git a/crates/ui-egui/src/type_transform.rs b/crates/ui-egui/src/type_transform.rs index b724cfe3211..0c1b4837edf 100644 --- a/crates/ui-egui/src/type_transform.rs +++ b/crates/ui-egui/src/type_transform.rs @@ -52,6 +52,7 @@ pub(crate) fn cancel_stale(app: &mut PhotocraftApp) { cancel_drag(app); if lost_layer { app.ui.text_edit = None; + app.ui.text_edit_return_tool = None; } } } From f02c0cbef7048d859189f3a333b6bec95d8fca16 Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Thu, 15 Oct 2026 14:49:09 +1100 Subject: [PATCH 22/37] =?UTF-8?q?File=20=E2=80=BA=20Scripts=20=E2=80=BA=20?= =?UTF-8?q?Browse:=20reject=20Photoshop=20ExtendScript=20(#5406)=20(#5435)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * File › Scripts › Browse rejects Photoshop ExtendScript. The picker listed .js/.jsx files that parse_script cannot run. Filter to JSON/text/droplet scripts and return a clear error for .js/.jsx paths. * File › Scripts › Browse keeps Photoshop extensions in the picker. Review feedback on #5435: filtering .js/.jsx out of the picker hid the rejection error from UI users. List Photoshop's script types (as #2452 asked) alongside PhotoCraft's so selecting one shows the ExtendScript error instead of hiding the file. --- crates/engine/src/automate_cmds.rs | 22 ++++++++++++++++++++++ crates/engine/src/automate_cmds/tests.rs | 21 +++++++++++++++++++++ crates/ui-egui/src/file_dialog/tests.rs | 15 ++++++++++++++- crates/ui-egui/src/file_ui.rs | 8 +++++--- 4 files changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs index 6a98ee3c4f3..4c78f90b348 100644 --- a/crates/engine/src/automate_cmds.rs +++ b/crates/engine/src/automate_cmds.rs @@ -24,6 +24,22 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } +/// Photoshop ExtendScript / UXP script suffixes — not PhotoCraft JSON or command lists. +fn extendscript_ext(path: &str) -> Option<&str> { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let dot = name.rfind('.')?; + let ext = &name[dot + 1..]; + let lower = ext.to_ascii_lowercase(); + matches!(lower.as_str(), "js" | "jsx" | "jsxbin" | "psjs" | "ccjs").then_some(ext) +} + +fn reject_extendscript(cmd: &str, path: &str) -> Result<()> { + match extendscript_ext(path) { + Some(_) => Err(bad(cmd, "PhotoCraft scripts are JSON or command lists (one command.id {json} per line), not Photoshop ExtendScript (.js/.jsx)")), + None => Ok(()), + } +} + /// Session state of the File-menu commands (not saved, not history). #[derive(Clone, Debug, Default)] pub struct FileMenuState { @@ -127,6 +143,12 @@ fn run_steps(s: &mut Session, steps: &[(String, Value)]) -> Vec { /// File › Scripts › Browse…: run a script file on the session. fn browse(s: &mut Session, p: &Value) -> Result { let cmd = "file.scripts.browse"; + if let Some(path) = p.get("path").and_then(Value::as_str) { + reject_extendscript(cmd, path)?; + } + if let Some(name) = p.get("name").and_then(Value::as_str) { + reject_extendscript(cmd, name)?; + } let steps = match (p.get("path").and_then(Value::as_str), p.get("script").and_then(Value::as_str), p.get("steps")) { (Some(path), _, _) => parse_script(&String::from_utf8_lossy(&read_file(path)?))?, (_, Some(text), _) => parse_script(text)?, diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/automate_cmds/tests.rs index 67852534c31..06d0e88f36c 100644 --- a/crates/engine/src/automate_cmds/tests.rs +++ b/crates/engine/src/automate_cmds/tests.rs @@ -54,6 +54,27 @@ fn browse_runs_a_script_file() { assert_eq!(r["results"].as_array().unwrap().len(), 1); } +#[test] +fn browse_rejects_photoshop_extendscript() { + let dir = tmp("jsx"); + let jsx = format!("{dir}/hello.jsx"); + std::fs::write(&jsx, "alert('hi');\n").unwrap(); + let mut s = Session::new(); + let err = s.execute("file.scripts.browse", json!({"path": jsx})).unwrap_err().to_string(); + assert!(err.contains("not Photoshop ExtendScript"), "{err}"); + assert!(err.contains("JSON"), "{err}"); + let js = format!("{dir}/hello.js"); + std::fs::write(&js, "alert('hi');\n").unwrap(); + assert!(s.execute("file.scripts.browse", json!({"path": js})).is_err()); + let err = s.execute("file.scripts.browse", json!({"name": "Resize.jsx", "script": "alert(1);"})).unwrap_err().to_string(); + assert!(err.contains(".js/.jsx"), "{err}"); + // A JSON script still runs even if the file name is not a Photoshop suffix. + let json = format!("{dir}/rotate.json"); + std::fs::write(&json, r#"[["file.new", {"width": 8, "height": 8}]]"#).unwrap(); + let r = s.execute("file.scripts.browse", json!({"path": json})).unwrap(); + assert_eq!(r["ok"], true); +} + #[test] fn recording_browse_script_captures_each_effect_once() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index dc21c670a60..2a325ea2ce4 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -329,10 +329,23 @@ fn scripts_browse_lists_only_script_files() { assert!(matches!( open.borrow().first().map(|(r, _)| r), Some(FileDialogRequest::Open { multiple: false, extensions: Some(exts), .. }) - if exts.iter().map(String::as_str).collect::>() == ["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt"] + if exts.iter().map(String::as_str).collect::>() == ["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt", "pcdroplet"] )); } +#[test] +fn scripts_browse_extendscript_picks_report_the_error() { + // Photoshop scripts stay in the picker (matching its filter) and choosing one shows why it won't run. + let (mut app, open, _) = app(); + let ctx = egui::Context::default(); + menus::invoke(&mut app, &ctx, "file.scripts.browse", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::Contents("resize.jsx".into(), b"alert('hi');".to_vec()))); + app.poll_file_dialog(&ctx, None); + assert!(app.ui.status_error); + assert!(app.ui.status.contains("not Photoshop ExtendScript"), "{}", app.ui.status); +} + #[test] fn last_used_dir_takes_the_most_recent_parent() { assert_eq!(last_used_dir(&[]), None); diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index c3b8abc4d76..3f87f6339c7 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -55,8 +55,10 @@ fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choi json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)}) } -/// File › Scripts › Browse… lists these script files (plus the JSON/text the engine parses). -const SCRIPT_EXTENSIONS: &[&str] = &["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt"]; +/// File › Scripts › Browse… lists Photoshop's script types (matching its filter, #2452) plus the +/// JSON/text/droplet files the engine parses; selecting a Photoshop script gets the engine's +/// "not Photoshop ExtendScript" error instead of hiding those files from the picker. +const SCRIPT_EXTENSIONS: &[&str] = &["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt", "pcdroplet"]; /// Menu items fronted here (dialogs before the engine command). `None` when not ours. pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { @@ -104,7 +106,7 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V "file.scripts.statistics" => json!({"dialog": crate::stack_dialog::open_statistics(app)}), "file.scripts.browse" => { return Some(app.pick_file_bytes_filtered(SCRIPT_EXTENSIONS, |app, name, bytes| { - let r = app.run("file.scripts.browse", json!({"script": String::from_utf8_lossy(&bytes)})); + let r = app.run("file.scripts.browse", json!({"name": name, "script": String::from_utf8_lossy(&bytes)})); if r.is_ok() { let template = "Ran script {name}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); From e47086717a186b28ff5acd16dfb5761731d49044 Mon Sep 17 00:00:00 2001 From: envy-ai <177786885+envy-ai@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:49:15 -0400 Subject: [PATCH 23/37] Channels: load the targeted layer mask as selection (#5562) * Load the targeted layer mask from Channels footer * Fix Channels test setup after mask reveal --- crates/ui-egui/src/channels_panel.rs | 68 +++++++++++++++++++++++++++- docs/ui-design.md | 1 + 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs index f232384139e..7f175b6209b 100644 --- a/crates/ui-egui/src/channels_panel.rs +++ b/crates/ui-egui/src/channels_panel.rs @@ -330,7 +330,11 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let load = icons::button(ui, "circle-dashed", 26.0, false, tl!("Load channel as selection")); if load.clicked() { - actions.push(("select.loadSelection".into(), json!({ "channel": target_ref }))); + // The selected mask row can coexist with a Composite engine target while mask + // painting is active. The footer follows the row the user sees as targeted. + let params = + if mask_targeted { json!({ "channel": "mask", "layer": masked.as_ref().map(|layer| layer.id.0) }) } else { json!({ "channel": target_ref }) }; + actions.push(("select.loadSelection".into(), params)); } actions.extend(drop(ui, &load, Footer::Load)); }); @@ -615,6 +619,68 @@ mod tests { assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the white channel selects everything"); } + /// The footer follows the targeted row shown by the panel when mask painting is active, + /// even though the engine's channel-view target remains Composite. Other channel targets + /// continue to load their own values, and each load remains one undoable selection change. + #[test] + fn footer_loads_the_selected_layer_mask_and_preserves_color_alpha_targets() { + let (mut h, _) = channels_harness(); + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + h.state_mut().run("layer.layerMask.hideAll", json!({})).unwrap(); + h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap(); + h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); + h.state_mut().ui.mask_target = true; + h.run_steps(2); + + let click_load = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + use egui::{Modifiers, PointerButton}; + let p = at(h, "Load channel as selection"); + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + }; + let sample = + |h: &egui_kittest::Harness<'_, PhotocraftApp>, x, y| h.state().session.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(x, y, 0); + + assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Composite); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "mask row selection wins over the Composite engine target"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_none()); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); + + h.state_mut().ui.mask_target = false; + h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "composite luminosity remains available"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + h.state_mut().run("channel.new", json!({"fill": "selection"})).unwrap(); + h.state_mut().run("select.deselect", json!({})).unwrap(); + h.state_mut().run("channel.target", json!({"channel": "red"})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "color channel still loads its own plane"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + + h.state_mut().run("channel.target", json!({"channel": 1})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "alpha channel still loads its own plane"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); + } + /// A plain click on a row still targets it, and a drag released elsewhere does nothing. #[test] fn clicks_still_target_and_a_drop_elsewhere_does_nothing() { diff --git a/docs/ui-design.md b/docs/ui-design.md index c6135ff7442..d4ac18d2977 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -58,6 +58,7 @@ curl -sfL -o assets/icons/.svg https://raw.githubusercontent.com/lucide-ic | Quick layer pick | `quick_pick.rs` | macOS: ⌘⌥⌃-click with any tool selects the topmost visible layer with pixels under the pointer (`layer.pickAt`) without switching tools; the drag and release are swallowed. Windows/Linux have no third modifier distinct from the ⌃⌥ brush resize, so the gesture is a no-op there (use the Move tool's Auto-Select). A failed pick is a status-bar error. | | Layers rows | `panels.rs` | Double-click: on the name renames in place; on the Background makes it a normal layer; on an adjustment or fill thumbnail opens its Properties; on a Smart Object thumbnail opens its contents (Edit Contents); anywhere else on the row opens Layer Style. | | Layer masks | `panels.rs` | Clicking the mask thumbnail targets the mask (corner-bracket frame; the tab reads "Layer, Layer Mask/8"). Brush, eraser (paints background colour), gradient, bucket and moving the selected pixels (⌘-drag, `select.float`; the hole takes the background colour) then send `"target": "mask"`. Adjustment and fill layers target their mask automatically. | +| Channels selection | `channels_panel.rs` | Load channel as selection in the footer follows the highlighted channel row. When the active layer mask is targeted for painting while the underlying channel view remains Composite, it loads that layer mask; otherwise it loads the selected composite, color, alpha or vector mask channel. | | Path thumbnails | `vector_ui.rs` | Ctrl/Cmd-click the thumbnail of a Work Path, saved path or layer path to load it as a selection; Shift adds, Alt subtracts, Shift+Alt intersects. Clicking the row name only selects the path. | | Levels / Curves | `tone.rs` | Histogram of the image *below* the adjustment. Curves: click to add a point, drag out to delete. Every change is a coalesced `layer.setAdjustment`, so one drag = one undo step and the canvas updates at full resolution on the GPU. | | Shape Stroke Options | `shape_stroke_ui.rs`, `vector_ui.rs` | Direct editing: valid changes apply immediately, with one numeric drag per undo step in Properties. Escape/outside click closes the popup and retains changes; a child dropdown keeps the parent open. The options bar sets new-shape defaults; Properties edits the selected shape. | From b404d505815792bed4259755c7891cb3f462a16b Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 05:49:20 +0200 Subject: [PATCH 24/37] Type: Swap and Default Colors recolour the selected text (#5690) (#5808) The toolbar's Switch Colors and Default Colors buttons ran their commands without type_tool::foreground_changed, so characters highlighted in the type layer being edited kept their colour. As in Photoshop, they now take the new foreground, like picking a colour in the Color or Swatches panel. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/panels.rs | 70 ++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 9fbb765a913..f5b29d06d1e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -546,10 +546,18 @@ fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, two_columns: bool) { } s.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Swap colours (X)"))); if s.on_hover_text(tl!("Swap colours (X)")).clicked() { - let _ = app.run("tools.swapColors", json!({})); + chip_command(app, "tools.swapColors"); } if d.is_some_and(|d| d.on_hover_text(tl!("Default colours (D)")).clicked()) { - let _ = app.run("tools.defaultColors", json!({})); + chip_command(app, "tools.defaultColors"); + } +} + +/// Run Switch Colors or Default Colors from the chips. As in Photoshop, characters highlighted +/// in the type layer being edited take the new foreground colour, like picking one (#5690). +fn chip_command(app: &mut PhotocraftApp, id: &str) { + if app.run(id, json!({})).is_ok() { + crate::type_tool::foreground_changed(app); } } @@ -4308,6 +4316,64 @@ mod color_tests { } } + /// While characters are highlighted in a type layer being edited, the Switch Colors and + /// Default Colors buttons recolour them with the new foreground (#5690); without a selection + /// they only change the tool colours, as before. + #[test] + fn swap_and_default_colors_recolour_selected_type() { + use egui_kittest::kittest::Queryable; + use photocraft_doc::LayerId; + let rgb = |app: &PhotocraftApp, id: LayerId, ci: usize| { + let doc = &app.session.active().unwrap().doc; + let photocraft_doc::LayerContent::Text(t) = &doc.layer(id).unwrap().content else { panic!("not a type layer") }; + let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b); + let mut at = 0; + for r in t.char_runs() { + if b < at + r.len { + return r.style.color.to_rgba8(); + } + at += r.len; + } + [0; 4] + }; + for selected in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let made = app.run("type.create", json!({"text": "Hello world", "size": 40, "x": 50, "y": 150, "color": "#000000"})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + let anchor = if selected { 6 } else { 11 }; + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id.0, + caret: 11, + anchor, + session: "s".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state(|ui, app: &mut PhotocraftApp| color_chips(app, ui, false), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + h.get_by_label("Swap colours (X)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]); + assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0]); + let blue = if selected { [0, 0, 255, 255] } else { [0, 0, 0, 255] }; + assert_eq!(rgb(h.state(), id, 0), [0, 0, 0, 255], "unselected characters keep their colour"); + assert_eq!((rgb(h.state(), id, 6), rgb(h.state(), id, 10)), (blue, blue), "selected: {selected}"); + // Default Colors: the selection takes black, the new foreground. + h.state_mut().run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + h.get_by_label("Default colours (D)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(rgb(h.state(), id, 6), [0, 0, 0, 255], "selected: {selected}"); + } + } + /// The Studio layout (chips stacked, icons below) fits the height the toolbar reserves for /// the chips, so the two-column check does not change with the theme. #[test] From 82261398063d61d708ed8d2e67ab7bf0697aaffb Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 05:49:25 +0200 Subject: [PATCH 25/37] Image Size, Canvas Size: points and picas follow the Point/Pica Size preference (#5756) (#5757) The dialogs converted points and picas at a fixed 72 pt/in, while the rulers, Info, layer properties and the shape dialog use Preferences > Units & Rulers > Point/Pica Size. With Traditional (72.27) a document showed different point sizes in the rulers and in Image Size. The dialog now stores the preference's points per inch when it opens (__ptPerIn, 72 when missing) and uses it for points, picas (points / 12) and typed units in the Width/Height fields. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/sizing.rs | 89 +++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index 6cce7e0a5c0..3c48e041f48 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -71,6 +71,7 @@ pub fn reset(f: &mut Map) { pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { let unit = pref_unit(app.session.prefs().units_and_rulers.rulers); let resample = pref_resample(app.session.prefs().general.image_interpolation); + let pt_per_in = app.session.prefs().units_and_rulers.point_size.per_inch(); let d = &app.session.active()?.doc; let (w, h, res) = (d.size.width as f64, d.size.height as f64, d.resolution_dpi as f64); let label = photocraft_engine::commands::find(command).map(|c| c.label).unwrap_or("Image Size…"); @@ -82,6 +83,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { f.insert("__origH".into(), json!(h)); f.insert("__origRes".into(), json!(res)); f.insert("__unit".into(), json!(unit)); + f.insert("__ptPerIn".into(), json!(pt_per_in)); f.insert("__bytesPerPixel".into(), json!(d.layers.first().and_then(|l| l.surface()).map_or(4, |s| s.format().bytes_per_pixel()))); f.insert("width".into(), json!(w)); f.insert("height".into(), json!(h)); @@ -102,27 +104,33 @@ fn num(f: &Map, k: &str) -> f64 { f.get(k).and_then(Value::as_f64).unwrap_or(0.0) } -/// Pixels → display unit. -fn to_unit(px: f64, unit: &str, orig: f64, res: f64) -> f64 { +/// Points per inch from Preferences › Units & Rulers › Point/Pica Size, stored when the dialog +/// opens: 72 (PostScript) when missing or not a positive finite number. +fn pt_per_in(f: &Map) -> f64 { + f.get("__ptPerIn").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(72.0) +} + +/// Pixels → display unit; `ppi` is points per inch (a pica is 12 points). +fn to_unit(px: f64, unit: &str, orig: f64, res: f64, ppi: f64) -> f64 { match unit { "percent" => px / orig.max(1.0) * 100.0, "in" => px / res.max(1.0), "cm" => px / res.max(1.0) * 2.54, "mm" => px / res.max(1.0) * 25.4, - "pt" => px / res.max(1.0) * 72.0, - "pica" => px / res.max(1.0) * 6.0, + "pt" => px / res.max(1.0) * ppi, + "pica" => px / res.max(1.0) * ppi / 12.0, _ => px, } } -fn from_unit(v: f64, unit: &str, orig: f64, res: f64) -> f64 { +fn from_unit(v: f64, unit: &str, orig: f64, res: f64, ppi: f64) -> f64 { match unit { "percent" => v * orig / 100.0, "in" => v * res, "cm" => v / 2.54 * res, "mm" => v / 25.4 * res, - "pt" => v / 72.0 * res, - "pica" => v / 6.0 * res, + "pt" => v / ppi * res, + "pica" => v / ppi * 12.0 * res, _ => v, } } @@ -165,18 +173,19 @@ fn dim_field(ui: &mut egui::Ui, f: &mut Map, key: &str, orig_key: let res = f.get("resolution").and_then(Value::as_f64).unwrap_or(num(f, "__origRes")); let orig = num(f, orig_key); let px = num(f, key); - let mut v = to_unit(px, &unit, orig, res) as f32; + let ppi = pt_per_in(f); + let mut v = to_unit(px, &unit, orig, res, ppi) as f32; // The engine's 300000 px limit in this unit (never below 30000), so a large document's size // isn't clamped when the field is drawn: egui clamps the shown value to the range, and the // field reports that as an edit (#4162). - let lim = if unit == "px" { 300000.0 } else { to_unit(300000.0, &unit, orig, res).max(30000.0) as f32 }; + let lim = if unit == "px" { 300000.0 } else { to_unit(300000.0, &unit, orig, res, ppi).max(30000.0) as f32 }; let range = -lim..=lim; // Each unit keeps its own precision: whole pixels, 3 places for inches, 2 for cm/mm/picas (#2434). // A typed unit (`2in` while in pixels) converts at the dialog's resolution. - let units = crate::widgets::FieldUnits { unit: crate::widgets::unit_of_key(&unit), dpi: res, ppi: 72.0 }; + let units = crate::widgets::FieldUnits { unit: crate::widgets::unit_of_key(&unit), dpi: res, ppi }; let changed = crate::widgets::value_field_units(ui, &mut v, range, 90.0, crate::widgets::unit_decimals(&unit), units).changed(); if changed { - let px = from_unit(v as f64, &unit, orig, res); + let px = from_unit(v as f64, &unit, orig, res, ppi); f.insert(key.into(), json!(if unit == "px" { px.round() } else { px })); } let _ = id; @@ -442,15 +451,36 @@ mod tests { #[test] fn unit_conversions_round_trip() { - for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] { - let v = to_unit(1500.0, unit, 3000.0, 300.0); - assert!((from_unit(v, unit, 3000.0, 300.0) - 1500.0).abs() < 1e-9, "{unit}"); + for ppi in [72.0, 72.27] { + for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] { + let v = to_unit(1500.0, unit, 3000.0, 300.0, ppi); + assert!((from_unit(v, unit, 3000.0, 300.0, ppi) - 1500.0).abs() < 1e-9, "{unit} at {ppi} pt/in"); + } } - assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0), 50.0); - assert_eq!(to_unit(600.0, "in", 3000.0, 300.0), 2.0); + assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0, 72.0), 50.0); + assert_eq!(to_unit(600.0, "in", 3000.0, 300.0, 72.0), 2.0); assert_eq!(human_bytes(6016.0 * 6016.0 * 4.0), "138.1M"); } + /// #5756: points and picas use the Point/Pica Size preference (Traditional is 72.27 pt/in), + /// and a dialog without the field (or with a bad one) falls back to PostScript's 72. + #[test] + fn points_and_picas_use_the_points_per_inch() { + assert!((to_unit(72.0, "pt", 72.0, 72.0, 72.27) - 72.27).abs() < 1e-9); + assert!((to_unit(72.0, "pica", 72.0, 72.0, 72.27) - 72.27 / 12.0).abs() < 1e-9); + assert_eq!(to_unit(72.0, "pt", 72.0, 72.0, 72.0), 72.0); + assert_eq!(to_unit(72.0, "pica", 72.0, 72.0, 72.0), 6.0); + assert!((from_unit(72.27, "pt", 72.0, 72.0, 72.27) - 72.0).abs() < 1e-9); + let mut f = Map::new(); + assert_eq!(pt_per_in(&f), 72.0); + for bad in [json!(0.0), json!(-3.0), json!("x")] { + f.insert("__ptPerIn".into(), bad); + assert_eq!(pt_per_in(&f), 72.0); + } + f.insert("__ptPerIn".into(), json!(72.27)); + assert_eq!(pt_per_in(&f), 72.27); + } + #[test] fn dialog_maps_to_engine_command() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -547,6 +577,33 @@ mod tests { (h, id) } + /// #5756: points and picas follow Preferences › Units & Rulers › Point/Pica Size. With + /// Traditional (72.27 pt/in) and Resample off, 100 px typed as 72.27 pt wide is 100 ppi. + #[test] + fn traditional_point_size_drives_points_and_picas() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap(); + app.session.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); + for command in ["image.imageSize", "image.canvasSize"] { + let id = open(&mut app, command).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields.get("__ptPerIn"), Some(&json!(72.27)), "{command}"); + app.ui.close_dialog(id); + } + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.imageSize").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("resample".into(), json!("none")); + d.fields.insert("__unit".into(), json!("pt")); + h.run_steps(3); + type_width(&mut h, "72.27"); + let f = fields(&h); + assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}"); + assert!((num(&f, "resolution") - 100.0).abs() < 1e-2, "{f:?}"); + } + /// Types `text` into the Width field and leaves it with Tab. fn type_width(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) { use egui::accesskit::Role; From 56d3b7f983afa2d85a53b1f1e4fc8cc2436faefa Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:49:30 -0400 Subject: [PATCH 26/37] Pen and Path Selection: Delete deletes the finished work path (#5702) (#5732) A finished work path is drawn whenever the Pen, Freeform Pen or Path Selection tool is active, and it is saved with the document, as in Photoshop. But once the path was finished, Delete/Backspace fell through to Edit > Clear (the pixels under it), so the only ways to remove it were the right-click Delete Path and the Paths panel, and it looked impossible to delete. With those tools, no path being drawn and the work path the one they edit (no shape layer or targeted vector mask in front of it), an unmodified Delete/Backspace now runs path.delete on the work path: one undoable Delete Path step. Direct Selection and the Curvature Pen are left alone, since Photoshop deletes their selected anchors, not the path. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/pen_draw_tests.rs | 48 ++++++++++++++++++++++++++++ crates/ui-egui/src/shortcuts.rs | 13 ++++++++ crates/ui-egui/src/vector_ui.rs | 13 ++++++++ 3 files changed, 74 insertions(+) diff --git a/crates/ui-egui/src/pen_draw_tests.rs b/crates/ui-egui/src/pen_draw_tests.rs index d8bb39d82f4..155450eac62 100644 --- a/crates/ui-egui/src/pen_draw_tests.rs +++ b/crates/ui-egui/src/pen_draw_tests.rs @@ -171,3 +171,51 @@ fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() { assert!(sp.closed && sp.knots.len() == 3); assert!(near([k.in_ctrl.x, k.in_ctrl.y], [0.0, 20.0]) && near([k.out_ctrl.x, k.out_ctrl.y], [40.0, 20.0]), "{k:?}"); } + +/// #5702: a finished work path showed again whenever the Pen came back, and ⌫ / Delete reached +/// Edit › Clear (the pixels under it) instead, so the path looked impossible to delete. With the +/// Pen the key deletes the path, in one undoable step, and leaves the pixels; other tools keep +/// Edit › Clear. +#[test] +fn delete_with_the_pen_deletes_the_finished_work_path_not_the_pixels() { + let mut h = harness(); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut() + .session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 200, 150), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + for p in [[20.0, 20.0], [120.0, 20.0], [120.0, 100.0]] { + click(&mut h, p); + } + h.key_press(Key::Enter); + h.run_steps(2); + let work = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().doc.work_path.is_some(); + let red = |h: &Harness<'static, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 60) == [1.0, 0.0, 0.0, 1.0] + }; + assert!(work(&h) && h.state().ui.pen.is_none(), "a finished work path"); + let steps = h.state().session.active().unwrap().history.past_len(); + + h.key_press(Key::Delete); + h.run_steps(2); + assert!(!work(&h), "Delete deletes the work path"); + assert!(red(&h), "and leaves the pixels under it"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one History step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(work(&h), "Undo brings it back"); + + h.state_mut().ui.tool = Tool::PathSelection; + h.key_press(Key::Backspace); + h.run_steps(2); + assert!(!work(&h), "Backspace with Path Selection deletes it too"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + + h.state_mut().ui.tool = Tool::Brush; + h.key_press(Key::Delete); + h.run_steps(2); + assert!(work(&h), "another tool's Delete is Edit › Clear, not Delete Path"); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index a2f3f17c1b0..e8645a1511e 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -477,6 +477,19 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::vector_ui::pen_commit(app, false); return; } + // A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in + // Photoshop (#5702), never Edit › Clear on the pixels under it. + if focus != Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { + let mods = ctx.input(|i| i.modifiers); + if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) + { + if let Err(e) = app.run("path.delete", json!({"name": "work"})) { + app.ui.status = e; + app.ui.status_error = true; + } + return; + } + } // Magnetic Lasso: ↩ closes, Esc cancels, ⌫ removes a fastening point (not Edit › Clear), // [ ] change the detection width (not the brush size). if crate::magnetic_lasso_ui::keys(app, ctx) { diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index f68a4a6a4e8..9682ba2ed07 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -725,6 +725,19 @@ pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { } } +/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen or Path Selection tool, no +/// path being drawn and the work path the one these tools show and edit (no shape layer or +/// targeted vector mask in front of it), as in Photoshop (#5702). It was drawn whenever one of +/// these tools was active, but the key reached Edit › Clear, so it looked impossible to delete. +/// Direct Selection and the Curvature Pen delete selected anchors in Photoshop, not the path. +pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { + matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::PathSelection) + && app.ui.pen.is_none() + && app.ui.transform.is_none() + && app.ui.view.shows(app.ui.view.show.target_path) + && matches!(target_path(app), Some((PathTarget::Work, _))) +} + /// The path Path Selection edits: the targeted vector mask, the active shape layer's path, else /// the work path. fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { From 6729fa1e50c5482685ba150d158bb86b32aa5bd8 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:49:36 -0400 Subject: [PATCH 27/37] Layer Style: drag on the image to move a drop or inner shadow (#5701) (#5893) As in Photoshop, with the Layer Style dialog on a Drop Shadow or Inner Shadow page, dragging on the image moves the shadow: its offset follows the pointer and is stored as the effect's angle and distance (whole degrees and pixels), moving the shared global light angle when the effect uses it. Space and the middle button still pan; colour pickers still sample. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 14 ++++++- crates/ui-egui/src/layer_style.rs | 65 +++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8e38d1d57e1..b3693f7d8fa 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3312,7 +3312,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields)); // Field Blur's pins are placed and dragged on the image (`blur_pins`). let pinning = primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields)); - let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning; + // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). + let shadow_drag = + !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); + let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag; if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) { let d = xf.unmap_vec(d) / (view.zoom / ppp); view.center[0] -= d.x; @@ -3320,6 +3323,15 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true)); } else if free_hover && (space_pan || hand) { ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, false)); + } else if shadow_drag && !middle && crate::dialogs::free_pointer_over(&ctx, rect).is_some() { + ctx.set_cursor_icon(egui::CursorIcon::Move); + if let Some(p) = crate::dialogs::free_press(&ctx, rect) { + let (start, origin) = ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.press_origin().unwrap_or(p))); + let total = xf.unmap_vec(p - origin) / (view.zoom / ppp); + if let Some(d) = app.ui.dialogs.last_mut() { + crate::layer_style::drag_shadow(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)]); + } + } } else if picking && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) { if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { ctx.set_cursor_icon(egui::CursorIcon::Crosshair); diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs index 3a1807cf18a..d876c182789 100644 --- a/crates/ui-egui/src/layer_style.rs +++ b/crates/ui-egui/src/layer_style.rs @@ -461,6 +461,39 @@ fn remove_instance(f: &mut Map, id: &str) { /// the layer's order), the blending options and the selected page. `select` /// names a kind to open: its first instance is selected (and enabled), or one /// is created. `light` is the document's global light angle. +/// Whether the selected page is a Drop Shadow or Inner Shadow, which a drag on the image moves +/// while the dialog is open, as in Photoshop (#5701; [`drag_shadow`]). +pub fn drags_shadow(f: &Map) -> bool { + let selected = f.get("selected").and_then(Value::as_str).unwrap_or_default(); + entry(f, selected).and_then(|e| e.get("kind")).and_then(Value::as_str).is_some_and(|k| matches!(k, "dropShadow" | "innerShadow")) +} + +/// A drag on the image with a shadow page selected: `start` is true on the press (it records the +/// shadow's angle and distance then), `total` the pointer's movement since in document pixels. +/// The shadow's offset follows the pointer, kept as Photoshop's whole-degree angle and whole-pixel +/// distance (offset = (−cos angle, sin angle) × distance, the light opposite the shadow); with +/// Use Global Light the shared angle moves too ([`set_param`]). +pub fn drag_shadow(f: &mut Map, start: bool, total: [f64; 2]) { + const KEY: &str = "__shadowDrag"; + let Some(id) = f.get("selected").and_then(Value::as_str).map(str::to_string).filter(|_| drags_shadow(f)) else { return }; + let Some(p) = entry(f, &id).and_then(|e| e.get("params")) else { return }; + if start || f.get(KEY).is_none() { + let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(120.0); + let distance = p.get("distance").and_then(Value::as_f64).unwrap_or(0.0); + f.insert(KEY.into(), json!([angle, distance])); + } + let Some([angle, distance]) = f.get(KEY).and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])) else { return }; + let a = angle.to_radians(); + let (ox, oy) = (-a.cos() * distance + total[0], a.sin() * distance + total[1]); + let d = ox.hypot(oy); + if !d.is_finite() { + return; + } + let new_angle = if d >= 0.5 { oy.atan2(-ox).to_degrees().round() } else { angle }; + set_param(f, &id, "angle", json!(new_angle)); + set_param(f, &id, "distance", json!(d.round().clamp(0.0, 30000.0))); +} + pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map { let mut f = Map::new(); f.insert("layer".into(), json!(layer.id.0)); @@ -1346,6 +1379,38 @@ mod tests { use super::*; use photocraft_doc::StrokeFx; + /// #5701: with a shadow page selected, a drag on the image moves the shadow: its offset + /// follows the pointer, as whole degrees and pixels, the global light angle with it. + #[test] + fn dragging_on_the_image_moves_the_selected_shadow() { + let shadow = |id: &str, kind: &str, global: bool| json!({"id": id, "kind": kind, "on": true, "params": {"angle": 120.0, "distance": 10.0, "useGlobalLight": global}}); + let mut f = Map::new(); + f.insert("selected".into(), json!("fx1")); + f.insert("globalLight".into(), json!(120.0)); + f.insert("effects".into(), json!([shadow("fx1", "dropShadow", true), shadow("fx2", "innerShadow", true), shadow("fx3", "dropShadow", false)])); + assert!(drags_shadow(&f)); + let params = |f: &Map, id: &str| { + let p = &entry(f, id).unwrap()["params"]; + (p["angle"].as_f64().unwrap(), p["distance"].as_f64().unwrap()) + }; + // The press keeps the shadow where it is: (5, 8.66) px. + drag_shadow(&mut f, true, [0.0, 0.0]); + assert_eq!(params(&f, "fx1"), (120.0, 10.0)); + // Dragged to (15, 0): straight right of the layer, the light from the left (180°). + drag_shadow(&mut f, false, [10.0, -8.660_254]); + assert_eq!(params(&f, "fx1"), (180.0, 15.0)); + assert_eq!(params(&f, "fx2").0, 180.0, "the global light angle is shared"); + assert_eq!(params(&f, "fx3"), (120.0, 10.0), "an instance with its own angle is left alone"); + // Back onto the layer: no offset, and the angle the drag started with. + drag_shadow(&mut f, false, [-5.0, -8.660_254]); + assert_eq!(params(&f, "fx1"), (120.0, 0.0)); + // Not on a shadow page: nothing moves. + f.insert("selected".into(), json!(BLENDING)); + assert!(!drags_shadow(&f)); + drag_shadow(&mut f, true, [50.0, 50.0]); + assert_eq!(params(&f, "fx1"), (120.0, 0.0)); + } + fn session() -> photocraft_engine::Session { let mut s = photocraft_engine::Session::new(); s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); From 0c5709e9bde02773d838032071201611af9c588f Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:49:42 -0400 Subject: [PATCH 28/37] Free Transform: shapes and paths stay on whole pixels (#5751) (#5841) * Free Transform: shapes and paths stay on whole pixels (#5751) With Snap Vector Tools and Transforms to Pixel Grid on, only the pointer was rounded, and only while a shape tool was active. Under the Move tool, or with a grab offset or a proportional scale, the box landed between pixels (a rectangle dragged to 540 px came out 539.6). An upright box on a shape layer or path now keeps whole-pixel edges whatever the tool. Co-Authored-By: Claude Opus 5.5 * Format (cargo fmt) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/snap_ui.rs | 46 ++++++++++++++++++++++++++++ crates/ui-egui/src/transform_tool.rs | 35 +++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index b41383c0280..8ef7207fb67 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -1019,6 +1019,52 @@ mod tests { assert_eq!(mover_bounds(&app).x0, 300); } + /// #5751: a Rectangle drawn on a 1080 px canvas, then resized with Free Transform under the + /// Move tool. With Snap Vector Tools and Transforms to Pixel Grid on (the default) the box's + /// edges stay on whole pixels: the grab offset and a proportional scale used to leave them at + /// 20.6 and 1040.4. Off, the box follows the pointer exactly. + #[test] + fn free_transform_of_a_shape_keeps_whole_pixels() { + for grid in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72})).unwrap(); + app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": grid})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 0.6; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Rectangle; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 31.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 700.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 481.0, y: 1000.0 }, m); + app.ui.tool = Tool::Move; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let whole = |q: [[f64; 2]; 4]| q.iter().flatten().all(|v| v.fract() == 0.0); + // The left edge handle, grabbed 1.3 px inside, dropped away from any snap target. + let q = app.ui.transform.as_ref().unwrap().quad; + let mid_y = (q[0][1] + q[3][1]) / 2.0; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[0][0] + 1.3, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 60.0, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 80.6, y: mid_y }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: left edge {q:?}"); + // The bottom-right corner scaled proportionally (the default), off any snap target. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[2][0], y: q[2][1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 450.4, y: 900.1 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: corner {q:?}"); + crate::transform_tool::commit(&mut app); + let st = app.session.active().unwrap(); + let photocraft_doc::LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + if grid { + for v in [x0, y0, x1, y1] { + assert!((v - v.round()).abs() < 1e-6, "committed shape {:?}", (x0, y0, x1, y1)); + } + } + } + } + #[test] fn guides_snap_to_layer_edges() { let mut app = app_with_box(); diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 13f92b1d5f4..330047cfd94 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -1435,6 +1435,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> } else { apply_mode_drag(s, g, [x, y], mode, type_layer, mods); } + round_to_pixel_grid(app); } } } @@ -1442,6 +1443,40 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> true } +/// Preferences › Tools › Snap Vector Tools and Transforms to Pixel Grid (#5751): while a shape +/// layer or a path is moved or scaled (the box still an upright rectangle), its edges stay on +/// whole pixels, whatever the tool. Rounding the pointer alone left the edges off by the grab +/// offset, and a proportional scale off by its ratio: a shape dragged to 540 px came out 539.6. +/// Rotated, skewed and distorted boxes are left as dragged. +fn round_to_pixel_grid(app: &mut PhotocraftApp) { + if !app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid { + return; + } + let Some(t) = app.ui.transform.as_ref() else { return }; + if t.selection || t.warp.is_some() || t.content_aware.is_some() || t.target.is_some() { + return; + } + let vector = + t.path.is_some() || app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))); + if !vector || !upright(&t.quad) { + return; + } + let q = t.quad.map(|p| p.map(f64::round)); + // A box narrower than a pixel keeps its size rather than collapsing. + if (q[1][0] - q[0][0]).abs() < 1.0 || (q[3][1] - q[0][1]).abs() < 1.0 || q.iter().flatten().any(|v| !v.is_finite()) { + return; + } + if let Some(s) = app.ui.transform.as_mut() { + s.quad = q; + } +} + +/// Whether corners clockwise from top-left form an axis-aligned rectangle (flips included). +fn upright(q: &[[f64; 2]; 4]) -> bool { + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + near(q[0][1], q[1][1]) && near(q[2][1], q[3][1]) && near(q[0][0], q[3][0]) && near(q[1][0], q[2][0]) +} + /// The same effective modifiers drive the geometry and decide whether Ctrl is a distortion /// gesture rather than the ordinary snap override. Keep type and Content-Aware Scale refusals. fn drag_mods(app: &PhotocraftApp, t: &TransformSession, hit: Hit, mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) { From 0c7308adc529a2b28e6fb9dee835f6390937b4ab Mon Sep 17 00:00:00 2001 From: WendelVolm <26125511+WendelVolm@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:49:47 +0200 Subject: [PATCH 29/37] Snapping: snap a drawn marquee, Object Selection box or shape by its edges while Space repositions it (#5748) --- crates/ui-egui/src/snap_ui.rs | 72 ++++++++++++++++++++++++++++++++- crates/ui-egui/src/vector_ui.rs | 13 ++++++ 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index 8ef7207fb67..e0b122c3731 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -31,6 +31,9 @@ pub enum Gesture { /// A selection outline (or its floating piece) dragged with a selection tool: its bounds at /// the start of the drag. SelectionMove { rect: [f64; 4] }, + /// A marquee, Object Selection box or shape being drawn, repositioned with Space held + /// (`hold_keys`): its bounds when Space went down. + DrawMove { rect: [f64; 4] }, /// A guide being moved with the Move tool. Guide, } @@ -292,7 +295,7 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> [f64; 2 } Gesture::TransformCorner { .. } => snap.targets.snap_point(p, tol), Gesture::Guide => snap.targets.snap_point(p, tol), - Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } => { + Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } | Gesture::DrawMove { rect } => { let d = [p[0] - snap.start[0], p[1] - snap.start[1]]; let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]]; let set = if snap.targets.is_empty() { &snap.smart } else { &snap.targets }; @@ -388,6 +391,40 @@ fn crop_handle(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers, targets: Some((view.map_or(q, |view| crate::crop_mode::from_press(app, view, q)), lines)) } +/// The bounds `[x0, y0, x1, y1]` of what drag `d` draws so far, for the tools whose drag Space +/// repositions and that snap (`None` for the rest, or a shape still too small to draw). +fn drawn_rect(app: &PhotocraftApp, d: &crate::canvas::Drag) -> Option<[f64; 4]> { + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = match d.tool { + Tool::RectMarquee | Tool::EllipseMarquee => crate::canvas::marquee_corners(&app.ui.tool_options, d, last), + Tool::ObjectSelection => (d.start, last), + t if crate::vector_ui::is_shape_tool(t) => return crate::vector_ui::shape_bounds(&app.ui.tool_options, t, d.start, last, d.live), + _ => return None, + }; + Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]) +} + +/// Space held while a marquee, Object Selection box or shape is drawn moves the whole of it +/// (`hold_keys`): its edges and centre snap, as a moved selection's do, not just the corner under +/// the pointer. Releasing Space goes back to snapping that corner. +fn follow_reposition(app: &mut PhotocraftApp) { + let Some(d) = app.drag.as_ref() else { return }; + let Some(snap) = app.prefs_rt.snap.as_ref() else { return }; + let gesture = match (&snap.gesture, d.reposition) { + (Gesture::Point, true) => match drawn_rect(app, d) { + Some(rect) => Gesture::DrawMove { rect }, + None => return, + }, + (Gesture::DrawMove { .. }, false) => Gesture::Point, + _ => return, + }; + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + if let Some(snap) = app.prefs_rt.snap.as_mut() { + snap.gesture = gesture; + snap.start = last; + } +} + /// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it). pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent { match ev { @@ -415,6 +452,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } + follow_reposition(app); let disabled = override_for_gesture(app, mods); if let Some(s) = app.prefs_rt.snap.as_mut() { s.disabled = disabled; @@ -427,6 +465,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } + follow_reposition(app); let disabled = override_for_gesture(app, mods); if let Some(s) = app.prefs_rt.snap.as_mut() { s.disabled = disabled; @@ -661,6 +700,37 @@ mod tests { assert_eq!(sel.x1, 116); } + /// Space while drawing a marquee, Object Selection box or shape moves it: its edges snap, not + /// only the corner under the pointer; with Space released the corner snaps again. + #[test] + fn drawing_repositioned_with_space_snaps_its_edges() { + for tool in [Tool::RectMarquee, Tool::EllipseMarquee, Tool::ObjectSelection, Tool::Rectangle, Tool::Line] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 140.0, pressure: 1.0 }, m); + // Space down: the 50 × 40 box moves so its left edge lands 4 px short of the guide; + // the pointer corner (x = 266) is near nothing. + app.drag.as_mut().unwrap().reposition = true; + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 266.0, y: 140.0, pressure: 1.0 }, m); + assert_eq!(app.drag.as_ref().unwrap().start, [220.0, 100.0], "{tool:?}"); + if tool != Tool::RectMarquee { + continue; + } + // Space up: sizing resumes and the corner snaps to the document's right edge. + app.drag.as_mut().unwrap().reposition = false; + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 397.0, y: 140.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (220, 100, 400, 140)); + } + } + /// Dragging inside a selection with a marquee or lasso moves the outline (⌘ cuts the pixels /// into a floating piece): its bounds snap, not the pointer. #[test] diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 9682ba2ed07..01bb3c133b8 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -104,6 +104,19 @@ fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], m }) } +/// The box `[x0, y0, x1, y1]` a Shape-tool drag draws (a line's: its ends'), which snaps while +/// Space repositions it (`snap_ui`). None when too small to draw. +pub fn shape_bounds(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 4]> { + let g = shape_geometry(o, tool, start, end, mods)?; + if tool == Tool::Line { + let a: [f64; 2] = serde_json::from_value(g["from"].clone()).ok()?; + let b: [f64; 2] = serde_json::from_value(g["to"].clone()).ok()?; + return Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]); + } + let [x, y, w, h]: [f64; 4] = serde_json::from_value(g["rect"].clone()).ok()?; + Some([x, y, x + w, y + h]) +} + /// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre. pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return }; From 38b96f273aa5a49ed1cafa13dbd65237ad408bf5 Mon Sep 17 00:00:00 2001 From: baz <57290335+bazmarth@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:49:52 +0000 Subject: [PATCH 30/37] Move: Show Transform Controls frames every selected layer (#5917) As in Photoshop, with several layers selected (Shift-click with Auto-Select, or the Move marquee) Show Transform Controls draws one frame around all of them (the Background excluded) and outlines every selected shape layer. Before, the frame showed only the active layer, so the other selected layers had no feedback on the canvas. The frame joins the boxes Free Transform would open on each layer (transform_frame), and it hides while a corner radius widget is dragged. Free Transform works on one layer, so the shared frame has no handles and a press on it doesn't start Free Transform; a drag inside still moves every selected layer. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 83 +++++++++++++++++--- crates/ui-egui/src/move_auto_select_tests.rs | 21 +++++ docs/ui-parity.md | 4 +- 3 files changed, 95 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b3693f7d8fa..9227c2a0fef 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3842,8 +3842,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // corner badge, as Photoshop's corner radius cursor. ui.ctx().set_cursor_icon(egui::CursorIcon::Default); crate::icons::cursor_badge(&ctx, "scan", p); - } else if let Some((r, p, c)) = - response.hover_pos().and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) + } else if let Some((r, p, c)) = response + .hover_pos() + .filter(|_| !transform_controls_several(app)) + .and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c)))) { // The Move tool draws handles without opening a Free Transform session. // Give them their resize/rotate cursors before the first pointer press (#2871). @@ -4677,23 +4679,36 @@ pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option Option { - // A corner radius drag hides the box, as in Photoshop. +/// The layers Move › Show Transform Controls frames: every selected layer but the Background. +/// A corner radius drag hides the box, as in Photoshop. +fn transform_controls_layers(app: &PhotocraftApp) -> Vec<&photocraft_doc::Layer> { if app.ui.tool != Tool::Move || !app.ui.tool_options.move_show_transform || app.ui.transform.is_some() || app.drag.is_some() || app.ui.corner_radius.is_some() { - return None; + return Vec::new(); } + let Some(st) = app.session.active() else { return Vec::new() }; + st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).filter(|l| !crate::doc_props_ui::is_background(&st.doc, l)).collect() +} + +/// Several layers are selected: Show Transform Controls frames them all, as Photoshop does, but +/// Free Transform works on one layer, so the frame has no handles to scale or rotate them. +fn transform_controls_several(app: &PhotocraftApp) -> bool { + transform_controls_layers(app).len() > 1 +} + +/// Move tool › Show Transform Controls: the boxes Free Transform would open on the selected +/// layers, joined into one. +fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option { let st = app.session.active()?; - let l = st.active_layer.and_then(|id| st.doc.layer(id))?; - if crate::doc_props_ui::is_background(&st.doc, l) { - return None; - } - let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, l); + let b = transform_controls_layers(app) + .into_iter() + .map(|l| photocraft_engine::transform_cmds::transform_frame(&st.doc, l)) + .filter(|b| !b.is_empty()) + .reduce(|a, b| a.union(&b))?; let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0)); let b = b.translate(dx, dy); if b.is_empty() { @@ -4750,6 +4765,9 @@ fn transform_controls_hit(r: Rect, p: Pos2) -> bool { /// Enter the existing Free Transform session when a Move-tool transform control is pressed. fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, p: Pos2) -> bool { + if transform_controls_several(app) { + return false; + } let Some(r) = transform_controls_rect(app, xf) else { return false }; if !transform_controls_hit(r, p) { return false; @@ -4763,11 +4781,21 @@ fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: } } -/// Move tool › Show Transform Controls: the active layer's bounding box with its eight handles. +/// Move tool › Show Transform Controls: the selected layers' bounding box, with its eight handles +/// for one layer, and the outline of every selected shape layer, as in Photoshop. fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { let Some(r) = transform_controls_rect(app, xf) else { return }; let accent = crate::theme::Tokens::get(painter.ctx()).accent; + let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + for l in transform_controls_layers(app) { + if let LayerContent::Shape(sh) = &l.content { + crate::vector_ui::draw_outline(painter, &sh.path, &to_scr, accent); + } + } painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle); + if transform_controls_several(app) { + return; + } for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] { let h = Rect::from_center_size(p, vec2(7.0, 7.0)); painter.rect_filled(h, 0.0, Color32::WHITE); @@ -8109,6 +8137,37 @@ mod transform_controls_tests { use super::*; use serde_json::json; + #[test] + fn several_selected_layers_share_one_frame_without_handles() { + // As in Photoshop: Show Transform Controls frames every selected layer. Free Transform + // works on one layer, so the shared frame doesn't start it. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 40, 40], "fill": "#ff0000"})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [100, 120, 50, 30], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let one = transform_controls_rect(&app, &xf).unwrap(); + assert!(!transform_controls_several(&app)); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + assert!(transform_controls_several(&app)); + let both = transform_controls_rect(&app, &xf).unwrap(); + assert!(both.contains_rect(one) && both.width() > one.width() && both.height() > one.height(), "{both:?} frames both"); + let (lt, rb) = (xf.to_doc(both.left_top()), xf.to_doc(both.right_bottom())); + assert!((lt[0] - 20.0).abs() < 1e-3 && (lt[1] - 30.0).abs() < 1e-3 && (rb[0] - 150.0).abs() < 1e-3 && (rb[1] - 150.0).abs() < 1e-3, "{lt:?} {rb:?}"); + let ctx = egui::Context::default(); + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, both.right_bottom())); + assert!(app.ui.transform.is_none()); + // The Background never joins the frame. + let bg = app.session.active().unwrap().doc.layers[0].id; + app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap(); + assert_eq!(transform_controls_layers(&app).len(), 2); + } + #[test] fn move_transform_controls_start_free_transform_for_vector_shapes() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/move_auto_select_tests.rs b/crates/ui-egui/src/move_auto_select_tests.rs index 3d635922e34..403ab28cd12 100644 --- a/crates/ui-egui/src/move_auto_select_tests.rs +++ b/crates/ui-egui/src/move_auto_select_tests.rs @@ -236,3 +236,24 @@ fn every_theme_shows_the_gradient_options() { assert!(combos.iter().any(|c| c.contains("Normal")), "{theme:?}: the blend mode picker shows; combo boxes: {combos:?}"); } } + +#[test] +fn shift_click_adds_shape_layers_one_after_another() { + // Shapes, as in Photoshop: a click selects one, each ⇧-click adds the one under it. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + for rect in [[10, 10, 40, 40], [80, 10, 40, 40], [10, 100, 40, 40]] { + app.session.execute("shape.create", json!({"kind": "rect", "rect": rect, "fill": "#ff0000"})).unwrap(); + } + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let ids: Vec = app.session.active().unwrap().doc.layers.iter().skip(1).map(|l| l.id).collect(); + drag(&mut app, [30.0, 30.0], [0.0, 0.0], egui::Modifiers::NONE); + drag(&mut app, [100.0, 30.0], [0.0, 0.0], egui::Modifiers::SHIFT); + drag(&mut app, [30.0, 120.0], [0.0, 0.0], egui::Modifiers::SHIFT); + let mut selected = app.session.active().unwrap().selected_layers(); + selected.sort_by_key(|l| l.0); + assert_eq!(selected, ids); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7fbe8932cc1..d8d29122c49 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -96,6 +96,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` | | Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 | | Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) | +| Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline | partial: the shared frame has no handles, since Free Transform works on one layer (`canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_without_handles`; `move_auto_select_tests.rs`) | | | ⌘-drag temporary Move shows the box and snaps | partial | #2681 | | ⌘-right-click layer list under the pointer | done | `layer_pick_ui.rs` | | Double-click type to edit it (caret at the pointer, Type tool) | done | #1132, `type_tool::edit_at` | @@ -253,3 +254,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) | | 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit | | 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) | +| 2026-10-14 | minor | Move › Show Transform Controls frames every selected layer and outlines the selected shapes | From 94b1f0a4cb71e3f9b5a59db281bf19e9e0b67be1 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Thu, 15 Oct 2026 05:49:58 +0200 Subject: [PATCH 31/37] Warp: a thin layer stretched and bent keeps its curve on commit (#5793) (#5810) * Warp: a thin layer stretched and bent keeps its curve on commit (#5793) The mesh warp sized its triangle grid by the source rectangle only (one cell per 4 source px). A 3 px column scaled into a wide band and then warped got a single cell across, so the committed result was a straight, affine band while the preview showed the curve. The grid now also follows the destination length of the mapped rows and columns. Co-Authored-By: Claude Opus 5.5 * Warp: module doc describes the grid sized on both sides of the map (#5793) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/algo/src/warp.rs | 72 ++++++++++++++++++++++++++-- crates/ui-egui/src/transform_tool.rs | 26 ++++++++++ 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rs index 01c54e7643e..188de07d472 100644 --- a/crates/algo/src/warp.rs +++ b/crates/algo/src/warp.rs @@ -4,8 +4,10 @@ //! The source rectangle is subdivided into a fine grid whose vertices are mapped forward; each //! cell's two triangles are rasterized in destination space with the source position //! interpolated barycentrically, then the source is sampled there (premultiplied, nearest / -//! bilinear / Photoshop's Keys bicubic, like Free Transform). Cells are a few source pixels across, so -//! the piecewise-affine inverse is within a small fraction of a pixel of the true one; affine +//! bilinear / Photoshop's Keys bicubic, like Free Transform). Cells are a few pixels across in +//! both the source and the destination (a thin layer stretched far gets as many cells as its +//! warped size needs), so the piecewise-affine inverse is within a small fraction of a pixel of +//! the true one; affine //! maps (the identity included) are reproduced exactly. Where the warp shrinks the source, each //! pixel instead averages a grid of bilinear subsamples over its source footprint (about one per //! source pixel), so thin lines don't alias. Where the warp folds over itself the @@ -77,8 +79,11 @@ pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> return Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true)); } let (sw, sh) = (f64::from(src_rect.width()), f64::from(src_rect.height())); - let nx = ((sw / CELL).ceil() as usize).clamp(1, MAX_CELLS); - let ny = ((sh / CELL).ceil() as usize).clamp(1, MAX_CELLS); + // Cells are a few pixels across on both sides of the map: a thin source stretched far (a + // 3 px column scaled into a wide band, then bent) needs many cells, or it comes out straight. + let (lu, lv) = mapped_lengths(src_rect, f); + let cells = |s: f64, d: f64| ((s.max(d) / CELL).ceil() as usize).clamp(1, MAX_CELLS); + let (nx, ny) = (cells(sw, lu), cells(sh, lv)); // Forward-mapped vertices (and their source positions). let mut verts = Vec::with_capacity((nx + 1) * (ny + 1)); for j in 0..=ny { @@ -101,6 +106,43 @@ pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> warp_triangles(src, src_rect, &verts, &tris, interp) } +/// Probe lines per axis [`mapped_lengths`] follows through the map. +const PROBE: usize = 16; + +/// The longest destination length of a source row and of a source column under `f`, measured +/// along polylines through a [`PROBE`]-step grid. Non-finite steps count as zero. +fn mapped_lengths(src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync)) -> (f64, f64) { + let (x0, y0) = (f64::from(src_rect.x0), f64::from(src_rect.y0)); + let (sw, sh) = (f64::from(src_rect.width()), f64::from(src_rect.height())); + let n = PROBE + 1; + let mut pts = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + let (dx, dy) = f(x0 + sw * i as f64 / PROBE as f64, y0 + sh * j as f64 / PROBE as f64); + pts.push([dx, dy]); + } + } + let step = |a: [f64; 2], b: [f64; 2]| { + let d = (b[0] - a[0]).hypot(b[1] - a[1]); + if d.is_finite() { d } else { 0.0 } + }; + let (mut lu, mut lv) = (0.0f64, 0.0f64); + for k in 0..n { + let (mut row, mut col) = (0.0, 0.0); + for m in 1..n { + if let (Some(&a), Some(&b)) = (pts.get(k * n + m - 1), pts.get(k * n + m)) { + row += step(a, b); + } + if let (Some(&a), Some(&b)) = (pts.get((m - 1) * n + k), pts.get(m * n + k)) { + col += step(a, b); + } + } + lu = lu.max(row); + lv = lv.max(col); + } + (lu, lv) +} + /// Rasterizes textured triangles: each vertex is `(destination, source)` in document pixels and /// each triangle samples `src` (restricted to `src_rect`) through the barycentric /// interpolation of its source positions. Later triangles in `tris` draw over earlier ones (the @@ -399,6 +441,28 @@ mod tests { surf } + #[test] + fn a_thin_layer_stretched_into_a_curve_keeps_the_curve() { + // #5793: a 3 px wide column stretched 100x and bent into an arch. The grid was sized in + // source pixels (one cell across), so the arch came out as a straight band. + let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + src.fill_rect(Rect::new(0, 0, 3, 40), &[1.0, 0.0, 0.0, 1.0]); + let arch = |x: f64, y: f64| { + let dx = x * 100.0; + let t = (dx - 150.0) / 150.0; + (dx, y + 40.0 * (1.0 - t * t)) + }; + let out = warp_mesh_surface(&src, Rect::new(0, 0, 3, 40), &arch, Interp::Bilinear); + let alpha = |x: i32, y: i32| { + let mut p = [0.0f32; 4]; + out.read_pixel(x, y, &mut p); + p[3] + }; + // The band follows the arch: 40 px lower in the middle, about 36 px a third of the way in. + assert!(alpha(150, 60) > 0.99 && alpha(150, 20) < 0.01, "mid {} {}", alpha(150, 60), alpha(150, 20)); + assert!(alpha(100, 55) > 0.99 && alpha(100, 20) < 0.01, "third {} {}", alpha(100, 55), alpha(100, 20)); + } + #[test] fn a_mesh_warp_far_off_canvas_writes_only_the_two_regions() { // #995: the old and warped regions were cleared as one dense `src ∪ warped` buffer, about diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 330047cfd94..d46ef189bcc 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -4952,6 +4952,32 @@ mod tests { assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); } + #[test] + fn a_thin_layer_scaled_then_warped_commits_the_curve() { + // #5793: a 3 px column stretched wide, switched to Warp and pulled down in the middle. + // The commit came out straight: the warp's grid was one cell across the 3 source pixels. + let mut app = app_with_square(128, photocraft_geom::Rect::new(40, 20, 43, 60)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + scale_about_pivot(&mut app, 30.0, 1.0); + enter_warp(&mut app, &ctx); + warp_pointer(&mut app, ToolEvent::Down { x: 41.5, y: 40.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Move { x: 41.5, y: 70.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 41.5, y: 70.0 }, 2.0, egui::Modifiers::NONE); + commit(&mut app); + assert!(app.ui.transform.is_none(), "{}", app.ui.status); + let st = app.session.active().unwrap(); + let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let alpha = |x: i32, y: i32| { + let mut p = [0.0f32; 4]; + s.read_pixel(x, y, &mut p); + p[3] + }; + // The middle sags below the band's old bottom edge (y 60); the ends stay put. + assert!(alpha(41, 70) > 0.99, "middle {}", alpha(41, 70)); + assert!(alpha(15, 70) < 0.01 && alpha(15, 40) > 0.99, "end {} {}", alpha(15, 70), alpha(15, 40)); + } + fn warping_square() -> PhotocraftApp { let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); begin_warp(&mut app, &egui::Context::default()).unwrap(); From 8987980d1614cfd4fc01f72066dcc6a9fd00e36e Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 05:50:03 +0200 Subject: [PATCH 32/37] Dialogs: a close box in the title bar cancels like Cancel (#5496) (#5505) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dialogs drawn by the shared renderer had no close box: the only ways out were Cancel/OK or Esc. As in Photoshop on Windows, the title band now ends in a × (the icon button the floating panels close with) on Windows, Linux and the web, none on macOS. A click on it joins Esc in the single cancel path of `dialogs::show` (outcome = Cancel -> `cancel()`), so the live preview goes and nothing reaches the document or history. The × is left out of the title band's drag area, so a drag starting on it neither moves nor closes the dialog; the rest of the band still drags. Check Spelling (an untitled window) gets the same close box; it is Done, as every change there is already made. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/dialogs.rs | 115 ++++++++++++++++++++++++++- crates/ui-egui/src/type_panels_ui.rs | 41 +++++++++- 2 files changed, 151 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2930889bab4..013c79e8257 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -135,6 +135,26 @@ fn show_modal( }) } +/// Whether dialogs have a close box (×) in their title bar (#5496). Photoshop's modal dialogs have +/// one on Windows, where clicking it is Cancel, and none on macOS; Linux and the web follow Windows. +pub(crate) const CLOSE_BOX: bool = !cfg!(target_os = "macos"); + +/// The side of the close box's square, in points. +const CLOSE_BOX_SIZE: f32 = 20.0; + +/// The close box's square: flush with the title band's right end `right`, centred on the title +/// row at height `centre_y`. +fn close_box_rect(right: f32, centre_y: f32) -> egui::Rect { + egui::Rect::from_min_size(egui::pos2(right - CLOSE_BOX_SIZE, centre_y - CLOSE_BOX_SIZE / 2.0), egui::vec2(CLOSE_BOX_SIZE, CLOSE_BOX_SIZE)) +} + +/// Draws a title bar's close box in `rect`, the same × icon button the floating panels close with, +/// and says whether it was clicked. Its own child `Ui`, so the title row's layout is unchanged. +pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + crate::icons::button(&mut child, "x", CLOSE_BOX_SIZE, false, tl!("Close")).clicked() +} + pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::layer_style::color_picker::prune(app); crate::type_panels_ui::color_picker::prune(app); @@ -163,6 +183,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let place = place_id(&d); let start = pinned.or_else(|| ctx.data_mut(|m| m.get_persisted::(place))).or_else(|| crate::blur_pins::first_place(&d.fields, ctx)); let mut drag = egui::Vec2::ZERO; + let mut close_clicked = false; let mut sizing = false; let area = match start { Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset), @@ -242,8 +263,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let t = if crate::color_picker_ui::owns(&fields) { ui.add_sized(egui::vec2(ui.available_width(), 22.0), label).rect } else { ui.add(label).rect }; // The whole title band drags (#1921): the full width plus a little of the popup's // padding around it and the gap above the hairline, but none of the controls below. - let bar = egui::Rect::from_min_max(t.min - egui::vec2(7.0, 7.0), egui::pos2(ui.max_rect().right() + 7.0, t.bottom() + 4.0)); + // The close box (#5496) sits at the band's right end and is left out of the drag area: + // egui would let a drag that starts on a button move the dialog. + let close_rect = CLOSE_BOX.then(|| close_box_rect(ui.max_rect().right(), t.center().y)); + let bar_right = close_rect.map_or(ui.max_rect().right() + 7.0, |r| r.left()); + let bar = egui::Rect::from_min_max(t.min - egui::vec2(7.0, 7.0), egui::pos2(bar_right, t.bottom() + 4.0)); drag = ui.interact(bar, id.with("title"), egui::Sense::drag()).drag_delta(); + if let Some(r) = close_rect { + close_clicked = close_box(ui, r); + } ui.add_space(4.0); crate::widgets::hairline(ui); ui.add_space(8.0); @@ -458,11 +486,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.data_mut(|m| m.insert_persisted(place, offset)); } } - // Esc cancels (topmost dialog, no popup open). A click outside does nothing: Photoshop keeps - // the dialog, and the pointer may be panning or zooming the canvas under it. + // Esc and the title bar's close box cancel (topmost dialog, no popup open for Esc). A click + // outside does nothing: Photoshop keeps the dialog, and the pointer may be panning or + // zooming the canvas under it. if interactive && outcome.is_none() - && (modal.response.should_close() + && (close_clicked + || modal.response.should_close() || (modal.is_top_modal && !modal.any_popup_open && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)))) { outcome = Some(false); @@ -735,6 +765,83 @@ mod tests { assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), None); } + /// #5496: a pointer click on the title bar's close box does what Cancel does: the dialog + /// closes, the live preview goes and nothing reaches the document or the journal. On macOS + /// dialogs have no close box. + #[test] + fn the_title_bar_close_box_cancels_like_cancel() { + use egui_kittest::kittest::Queryable; + let close = |button: &str| { + let (mut app, _) = filter_dialog_with_preview(false); + let revision = app.session.active().unwrap().revision; + let journal = app.session.journal.len(); + // The fonts are set up after the harness's first frame: the dialog appears after it. + let dialogs = std::mem::take(&mut app.ui.dialogs); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.dialogs = dialogs; + h.run_steps(4); + assert!(h.state().filter_preview.is_some(), "the preview is on screen"); + if !CLOSE_BOX { + assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS"); + } + let target = h.query_by_label(button).map(|n| n.rect().center())?; + h.hover_at(target); + h.drag_at(target); + h.drop_at(target); + h.run_steps(3); + let app = h.state(); + Some(( + app.ui.dialogs.is_empty(), + app.filter_preview.is_none(), + app.session.active().unwrap().revision == revision, + app.session.journal.len() == journal, + )) + }; + let cancel = close("Cancel"); + assert_eq!(cancel, Some((true, true, true, true)), "Cancel closes, drops the preview and changes nothing"); + if CLOSE_BOX { + assert_eq!(close("Close"), cancel, "the × is Cancel"); + } + } + + /// #5496: the close box sits at the title band's right end, and the band stays a drag handle + /// around it: a drag that starts on the × neither moves nor closes the dialog, and the band + /// just left of the × still moves it. + #[test] + fn the_close_box_and_the_title_drag_keep_apart() { + use egui_kittest::kittest::Queryable; + if !CLOSE_BOX { + return; + } + let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.gaussianBlur"); + let title = h.get_by_label("Gaussian Blur").rect(); + let x = h.get_by_label("Close").rect(); + let frame = rects(&h.ctx)[0]; + assert!((x.center().y - title.center().y).abs() < 2.0 && x.left() > title.right(), "the × is on the title row: {x:?}, {title:?}"); + assert!(frame.right() - x.right() < 16.0, "at its right end: {x:?} in {frame:?}"); + let drag = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2| { + h.hover_at(from); + h.drag_at(from); + h.run_steps(2); + for i in 1..=8 { + h.hover_at(from + (to - from) * (i as f32 / 8.0)); + h.run_steps(1); + } + h.drop_at(to); + h.run_steps(3); + }; + drag(&mut h, x.center(), x.center() + egui::vec2(-80.0, 60.0)); + assert_eq!(h.state().ui.dialogs.len(), 1, "a drag from the × doesn't close the dialog"); + assert!((h.get_by_label("Gaussian Blur").rect().min - title.min).length() < 1.0, "nor move it"); + let x = h.get_by_label("Close").rect(); + let beside = x.left_center() - egui::vec2(4.0, 0.0); + drag(&mut h, beside, beside + egui::vec2(-120.0, 40.0)); + assert_eq!(h.state().ui.dialogs.len(), 1, "a title drag doesn't close the dialog"); + let moved = h.get_by_label("Gaussian Blur").rect().min - title.min; + assert!((moved - egui::vec2(-120.0, 40.0)).length() < 2.0, "the band beside the × moved the dialog: {moved:?}"); + } + #[test] fn color_picker_has_inset_content_and_actions_at_the_right_edge() { use egui_kittest::{Harness, kittest::Queryable}; diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rs index 499e8eac44e..d97a649fba3 100644 --- a/crates/ui-egui/src/type_panels_ui.rs +++ b/crates/ui-egui/src/type_panels_ui.rs @@ -768,7 +768,17 @@ fn spelling_window(app: &mut PhotocraftApp, ctx: &egui::Context) { .anchor(Align2::CENTER_CENTER, vec2(0.0, -40.0)) .show(ctx, |ui| { ui.set_width(380.0); - ui.label(RichText::new(tl!("Check Spelling")).color(t.text).size(13.0).strong()); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Check Spelling")).color(t.text).size(13.0).strong()); + // The close box (#5496) is Done, as in Photoshop: every change is already made. + if crate::dialogs::CLOSE_BOX { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "x", 20.0, false, tl!("Close")).clicked() { + act = Some("done"); + } + }); + } + }); ui.add_space(6.0); ui.horizontal_top(|ui| { ui.vertical(|ui| { @@ -930,4 +940,33 @@ mod tests { // Headless calls with an action go to the engine. assert!(menu(&mut app, "edit.checkSpelling", &json!({"action": "list"})).is_none()); } + + /// #5496: Check Spelling's close box is Done, as in Photoshop on Windows: the window closes + /// and the text keeps what it had. None on macOS. + #[test] + fn check_spellings_close_box_is_done() { + use egui_kittest::kittest::Queryable; + let mut app = app_with_text("Teh cat"); + menu(&mut app, "edit.checkSpelling", &json!({})).unwrap().unwrap(); + let revision = app.session.active().unwrap().revision; + // The fonts are set up after the harness's first frame: the window appears after it. + let spell = app.ui.type_panels.spell.take(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state(|ui, app| windows(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.type_panels.spell = spell; + h.run_steps(3); + if !crate::dialogs::CLOSE_BOX { + assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS"); + return; + } + let x = h.get_by_label("Close").rect(); + let done = h.get_by_label("Done").rect(); + assert!(x.bottom() <= done.top() && x.right() >= done.right(), "the × ends the title row: {x:?} over {done:?}"); + h.hover_at(x.center()); + h.drag_at(x.center()); + h.drop_at(x.center()); + h.run_steps(2); + assert!(h.state().ui.type_panels.spell.is_none(), "the × closed Check Spelling"); + assert_eq!(h.state().session.active().unwrap().revision, revision, "and changed nothing"); + } } From be32a7c651e4066c283284050b12ca8896f6f7ef Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:50:08 +0200 Subject: [PATCH 33/37] fix: commit type editing on Layers-panel selection (#5584) (#5612) --- crates/ui-egui/src/layer_row_ui/edit_tests.rs | 7 +- crates/ui-egui/src/panels.rs | 113 ++++++++++++++++++ 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/layer_row_ui/edit_tests.rs b/crates/ui-egui/src/layer_row_ui/edit_tests.rs index 829df351c7f..0c217dd3d04 100644 --- a/crates/ui-egui/src/layer_row_ui/edit_tests.rs +++ b/crates/ui-egui/src/layer_row_ui/edit_tests.rs @@ -174,7 +174,7 @@ fn edit_type_command_rejects_missing_or_non_type_layers_without_changes() { } #[test] -fn reentering_type_edit_keeps_the_session_and_cancel_restores_cached_pixels() { +fn layer_reselection_commits_type_edit_and_cancel_preserves_committed_text() { let mut s = session(); let id = s.execute("type.create", json!({"text": "Hello", "size": 48, "x": 100, "y": 180})).unwrap()["layer"].as_u64().unwrap(); // Stand-in for a PSD's retained Photoshop rendering, displaced from our glyph layout. @@ -197,10 +197,13 @@ fn reentering_type_edit_keeps_the_session_and_cancel_restores_cached_pixels() { let key = h.state().ui.text_edit.as_ref().expect("inline text editor").session.clone(); h.event(Event::Text("Changed".into())); h.run_steps(2); + // The first row click commits the edit; the second opens a new session (#5584). double_click(&mut h, at); - assert_eq!(h.state().ui.text_edit.as_ref().unwrap().session, key); + assert_ne!(h.state().ui.text_edit.as_ref().unwrap().session, key); assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1); crate::type_tool::cancel(h.state_mut()); + assert_eq!(text(&h, id), "Changed"); + assert!(h.state_mut().session.undo()); assert_eq!(text(&h, id), "Hello"); let st = h.state().session.active().unwrap(); let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("text") }; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f5b29d06d1e..a7187c91418 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2551,6 +2551,11 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); for (id, p) in actions { + // A row click commits even when it selects the layer already being edited (#5584). + // Finish before selection changes so the existing type session keeps its own target. + if id == "layer.select" && app.ui.text_edit.is_some() { + crate::type_tool::commit(app); + } if id == "ui.maskTarget" { app.ui.mask_target = p.as_bool().unwrap_or(false); app.ui.vector_mask_target = false; @@ -6311,6 +6316,114 @@ mod properties_target_regressions { #[cfg(test)] #[path = "history_panel_select_tests.rs"] mod history_panel_select_tests; +#[cfg(test)] +mod layer_click_type_commit_tests { + use super::*; + use egui_kittest::{Harness, kittest::Queryable}; + + fn harness(kind: theme::ThemeKind) -> (Harness<'static, PhotocraftApp>, LayerId, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let text = LayerId(app.run("type.create", json!({"text": "Before", "size": 24, "x": 20, "y": 80})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.setProps", json!({"layer": text.0, "name": "Edited type"})).unwrap(); + let other = LayerId(app.run("layer.new.layer", json!({"name": "Other pixels"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": text.0})).unwrap(); + crate::type_tool::edit_active(&mut app).unwrap(); + let session = app.ui.text_edit.as_ref().unwrap().session.clone(); + app.run("type.edit", json!({"layer": text.0, "text": "Preserved edit", "coalesce": session})).unwrap(); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(360.0, 650.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), kind); + ready = true; + return; + } + layers(app, ui); + }, + app, + ); + h.run_steps(4); + (h, text, other) + } + + fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, modifiers: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(modifiers)); + h.hover_at(at); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); + } + } + + fn preserved(app: &PhotocraftApp, id: LayerId) { + let layer = app.session.active().unwrap().doc.layer(id).unwrap(); + let LayerContent::Text(text) = &layer.content else { panic!("type must remain editable") }; + assert_eq!(text.text, "Preserved edit"); + } + + #[test] + fn layer_name_and_thumbnail_clicks_commit_same_or_other_type_selection() { + for kind in theme::ThemeKind::ALL { + for same in [true, false] { + for thumbnail in [true, false] { + let (mut h, text, other) = harness(kind); + let label = if same { "Edited type" } else { "Other pixels" }; + let row = h.get_by_label(label).rect(); + let at = pos2(row.left() + if thumbnail { 43.0 } else { 120.0 }, row.center().y); + click(&mut h, at, egui::Modifiers::NONE); + assert!(h.state().ui.text_edit.is_none(), "{kind:?}, same={same}, thumbnail={thumbnail}"); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(if same { text } else { other })); + preserved(h.state(), text); + } + } + } + } + + #[test] + fn layer_click_commits_without_breaking_modifier_selection_or_double_click_editing() { + for kind in theme::ThemeKind::ALL { + let (mut h, text, other) = harness(kind); + let row = h.get_by_label("Other pixels").rect(); + click(&mut h, pos2(row.left() + 120.0, row.center().y), egui::Modifiers { command: true, ..Default::default() }); + assert!(h.state().ui.text_edit.is_none()); + let selected = h.state().session.active().unwrap().selected_layers(); + assert!(selected.contains(&text) && selected.contains(&other)); + preserved(h.state(), text); + + let (mut h, text, _) = harness(kind); + let row = h.get_by_label("Edited type").rect(); + let thumb = pos2(row.left() + 43.0, row.center().y); + click(&mut h, thumb, egui::Modifiers::NONE); + assert!(h.state().ui.text_edit.is_none()); + click(&mut h, thumb, egui::Modifiers::NONE); + assert_eq!(h.state().ui.text_edit.as_ref().map(|ed| ed.layer), Some(text.0)); + preserved(h.state(), text); + } + } + + #[test] + #[ignore = "offscreen visual evidence for #5584"] + fn layer_click_synthetic_visual_evidence() { + let (h, text, _) = harness(theme::ThemeKind::ProMedium); + let mut app = h.into_state(); + app.ui.tool = Tool::Type; + let mut h = Harness::builder().with_size(vec2(1280.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, theme::ThemeKind::ProMedium); + app + }); + h.run_steps(4); + assert!(h.state().ui.text_edit.is_some()); + h.render().unwrap().save("5584-before.png").unwrap(); + let row = h.get_by_label("Other pixels").rect(); + click(&mut h, pos2(row.left() + 120.0, row.center().y), egui::Modifiers::NONE); + assert!(h.state().ui.text_edit.is_none()); + preserved(h.state(), text); + h.run_steps(4); + h.render().unwrap().save("5584-after.png").unwrap(); + } +} #[cfg(test)] mod sampler_readout_tests { From 96c683b25db7a1e52eac7e5046b3a2ff952c4cec Mon Sep 17 00:00:00 2001 From: nrq6993-a11y Date: Thu, 15 Oct 2026 06:50:14 +0300 Subject: [PATCH 34/37] Info panel: show guide coordinates while dragging outside the canvas (#5728) (#5768) * Fix Info panel guide coordinates during ruler drags (storytold/photocraft#5728). Show the dragged guide position on one axis while the pointer is outside the canvas, matching Photoshop. Co-authored-by: Cursor * Merge main; fill GuideDrag's new press field in the test; cargo fmt Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Cursor Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/panels.rs | 11 +++++++++-- crates/ui-egui/src/rulers.rs | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a7187c91418..522c74dc151 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1797,6 +1797,13 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { .hover_doc .map(|p| (p[0].floor() as i32, p[1].floor() as i32)) .filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32); + // While a guide is dragged (#5728), the Info panel shows its position in one axis only, even + // when the pointer is outside the canvas (ruler drags do not update `hover_doc` there). + let (guide_x, guide_y) = match app.guide_drag { + Some(d) if d.vertical => (Some(d.pos), None), + Some(d) => (None, Some(d.pos)), + None => (None, None), + }; // The readout averages the Eyedropper's Sample Size, as in Photoshop (#1649). let sample_size = app.ui.tool_options.eyedropper_size; let rgba = pos.and_then(|(x, y)| { @@ -1835,8 +1842,8 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.columns(2, |cols| { let dash = || "—".to_string(); // Measured from the rulers' zero point (#2955). - row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64 - origin[0]))); - row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64 - origin[1]))); + row(&mut cols[0], "X:", guide_x.map(|p| fx(p - origin[0])).or_else(|| pos.map(|p| fx(p.0 as f64 - origin[0]))).unwrap_or_else(dash)); + row(&mut cols[0], "Y:", guide_y.map(|p| fy(p - origin[1])).or_else(|| pos.map(|p| fy(p.1 as f64 - origin[1]))).unwrap_or_else(dash)); row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64))); row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64))); }); diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs index 972d7c0346b..61ea25d96f9 100644 --- a/crates/ui-egui/src/rulers.rs +++ b/crates/ui-egui/src/rulers.rs @@ -668,6 +668,24 @@ mod tests { assert!(h.query_by_label("50").is_none(), "not the raw image x"); } + /// #5728: dragging a guide shows its coordinate in the Info panel on one axis only. + #[test] + fn info_panel_shows_guide_drag_position_outside_canvas() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.hover_doc = None; + app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0 }); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(260.0, 240.0)) + .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); + h.run_steps(2); + assert!(h.query_by_label("42").is_some(), "vertical guide: X readout"); + h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0 }); + h.run_steps(2); + assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout"); + } + #[test] fn percentage_grid_spacing_uses_both_canvas_dimensions() { let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() }; From 17c85e41751f63027345c323b19058c56640da83 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 15 Oct 2026 09:20:19 +0530 Subject: [PATCH 35/37] fix(ui): brush outline matches the stroke on Wayland at fractional scales (#5796) * fix(ui): brush outline matches the stroke on Wayland at fractional scales On Hyprland at 1.25 the brush outline was 1.25x too large and sat right of and below where the brush painted, by more the larger the brush. The engine places dabs exactly; the OS cursor bitmap was wrong. winit 0.30 sizes custom cursor bitmaps on Wayland with a wp_viewport destination whenever the scale isn't 1, and Hyprland (like Mutter before GNOME 48) ignores viewports on cursor surfaces: it shows the bitmap one pixel per logical pixel with the hotspot winit divided by the scale. A client can't tell which compositors do this, so on Wayland at any scale but 1 the brush outline and crosshairs are painted in-app, as on the web. Other platforms and Wayland at scale 1 keep the low-latency OS bitmap. Measured on Hyprland 0.56.2 at 1.25 (100 % zoom, 100 px brush): dab centre (288.5, 560.5), diameter 97 px; outline before (303, 574.5), ~130 px; after (288.5, 562), 107 px including its border. Co-Authored-By: Claude Opus 5.5 * Merge main; cargo fmt Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/tool_cursor.rs | 20 +++++++++++++-- crates/ui-egui/src/tool_cursor/tests.rs | 34 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9c75ec3a368..5d95f2d6627 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1771,6 +1771,7 @@ impl eframe::App for PhotocraftApp { // Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas // cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`. self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f()); + tool_cursor::set_wayland(ctx, self.services.is_wayland); if !self.styled { Self::setup_context(ctx, self.ui.theme); self.styled = true; diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rs index 32f6aed82e6..8b67b96d602 100644 --- a/crates/ui-egui/src/tool_cursor.rs +++ b/crates/ui-egui/src/tool_cursor.rs @@ -93,9 +93,25 @@ fn close_ring() -> Vec { } /// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration -/// don't upload cursor images; every desktop root viewport does (winit custom cursors). +/// don't upload cursor images; every desktop root viewport does (winit custom cursors). Wayland at +/// any scale but 1 doesn't either: winit sizes the bitmap there with a `wp_viewport` destination +/// that some compositors ignore on cursor surfaces (Hyprland 0.56; Mutter before GNOME 48). They +/// show it one bitmap pixel per logical pixel, so at 1.25 a brush outline was 1.25× too large and +/// its centre sat 0.2 × its half-width right of and below the pointer, which is where the brush +/// painted. Nothing tells the app which compositor does what, so the outline is painted instead. fn native(ctx: &egui::Context) -> bool { - cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT + cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT && !scaled_wayland(ctx) +} + +/// Mark this window as a Wayland surface (or not), for [`native`]; the shell calls it every pass. +pub(crate) fn set_wayland(ctx: &egui::Context, wayland: bool) { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("photocraft-cursor-wayland"), wayland)); +} + +/// A Wayland window whose scale is not 1, where winit's cursor bitmaps are unreliable. +fn scaled_wayland(ctx: &egui::Context) -> bool { + let wayland = cfg!(target_os = "linux") && ctx.data(|d| d.get_temp::(egui::Id::new("photocraft-cursor-wayland"))).unwrap_or(false); + wayland && ctx.native_pixels_per_point().unwrap_or_else(|| ctx.pixels_per_point() / ctx.zoom_factor()) != 1.0 } /// Bitmap pixels per egui point. winit takes an `NSCursor` image's dimensions as logical points on diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rs index 409d528b95c..d68be241f50 100644 --- a/crates/ui-egui/src/tool_cursor/tests.rs +++ b/crates/ui-egui/src/tool_cursor/tests.rs @@ -272,6 +272,40 @@ fn ordinary_brush_cursor_is_not_part_of_the_canvas_draw_list() { assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Circle(_))), "the full tip is not silently shrunk"); } +#[test] +#[cfg(target_os = "linux")] +fn scaled_wayland_paints_the_brush_outline_instead_of_an_os_bitmap() { + // Hyprland ignores the viewport winit sizes cursor bitmaps with: at 1.25 the outline was + // 1.25× too large and its centre 0.2 × its half-width right of and below where the brush + // painted. Off scale 1 on Wayland the outline is painted at the pointer, at its true size. + let run = |ctx: &egui::Context, native_ppp: f32| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(native_ppp); + let mut output = ctx.run_ui(input, |ui| { + let icon = circle(ui.painter(), pos2(100.0, 100.0), 20.0, false); + ui.ctx().set_cursor_icon(icon); + }); + output.textures_delta.clear(); + let circles: Vec<_> = + output.shapes.iter().filter_map(|s| if let egui::Shape::Circle(c) = &s.shape { Some((c.center, c.radius)) } else { None }).collect(); + (output.platform_output.cursor_image.is_some(), output.platform_output.cursor_icon, circles) + }; + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + set_wayland(&ctx, true); + for ppp in [1.25, 1.5, 2.0] { + let (bitmap, icon, circles) = run(&ctx, ppp); + assert!(!bitmap, "{ppp}: no OS bitmap"); + assert_eq!(icon, CursorIcon::None, "{ppp}: the painted outline is the pointer"); + assert!(!circles.is_empty() && circles.iter().all(|&(c, r)| c == pos2(100.0, 100.0) && r == 20.0), "{ppp}: {circles:?}"); + } + let (bitmap, _, circles) = run(&ctx, 1.0); + assert!(bitmap && circles.is_empty(), "Wayland at scale 1 keeps the low-latency bitmap"); + set_wayland(&ctx, false); + let (bitmap, _, circles) = run(&ctx, 1.25); + assert!(bitmap && circles.is_empty(), "X11 at 1.25 keeps the bitmap"); +} + /// Run explicitly for visual QA: native cursors are absent from GPU screenshots. #[test] #[ignore = "writes target/tool-cursor-preview.png for visual inspection"] From 7edc7aa03df5aef247a41c1bf71d5aabd7f67ebe Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Thu, 15 Oct 2026 15:22:48 +1100 Subject: [PATCH 36/37] Raw: measure the Nikon D90 image area (4288x2848 at (10, 10)) (#4323) Aligning the decoded D90 sensor plane with the camera's own JPEG puts the image at (10, 10) in the 4352x2868 sensor plane, giving the camera's 4288x2848 frame (10-pixel margins; the right border reads the camera's flat 255 from column 4310). Add the measured ImageArea so a D90 NEF opens on the camera's frame instead of the uncropped plane, and make a measured profile leave a file that carries its own colour calibration (a DNG) untouched. Co-authored-by: Brandon Thomas --- crates/raw/README.md | 3 ++- crates/raw/src/cameras.rs | 40 ++++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 2 +- docs/gaps.md | 5 +++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/raw/README.md b/crates/raw/README.md index fda140d75bf..b66b533616e 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -123,7 +123,8 @@ smallest preview at least 512 pixels long, fits and develops in one go. Camera Raw's tuned import fits at the default exposure and as-shot white balance first, then applies the user's Exposure, Temperature and Tint to that same rendering. The D5100's measured image area is 4928 × 3264 at (8, 8) in a 4992 × 3280 -sensor plane; it removes the border without changing levels, WB or calibration. +sensor plane; the D90's is 4288 × 2848 at (10, 10) in a 4352 × 2868 plane; each +removes the border without changing levels, WB or calibration. Measured image areas preserve an explicit file crop. For a slightly tighter camera JPEG, fitting can align the reference proxy using a bounded diff --git a/crates/raw/src/cameras.rs b/crates/raw/src/cameras.rs index 7439433c3e2..84204c6bce5 100644 --- a/crates/raw/src/cameras.rs +++ b/crates/raw/src/cameras.rs @@ -127,6 +127,10 @@ const PROFILES: &[Profile] = &[Profile { /// 4992 x 3280 sensor data, giving the camera JPEG's 4928 x 3264 frame. /// * **ILCE-7** (2 files): 12 x 12 pixels in from the left and top of the /// 6048 x 4024 cRAW data (36 and 12 pixels of margin on the right and bottom). +/// * **D90** (1 file): 10 x 10 pixels in from the left and top of the +/// 4352 x 2868 sensor data, giving the camera JPEG's 4288 x 2848 frame +/// (10 pixels of margin on the right and bottom; the right border reads the +/// camera's flat 255 from column 4310 on). struct ImageArea { make: &'static str, model: &'static str, @@ -137,6 +141,7 @@ struct ImageArea { } const IMAGE_AREAS: &[ImageArea] = &[ + ImageArea { make: "NIKON CORPORATION", model: "NIKON D90", size: (4352, 2868), crop: (10, 10, 4288, 2848) }, ImageArea { make: "NIKON CORPORATION", model: "NIKON D5100", size: (4992, 3280), crop: (8, 8, 4928, 3264) }, ImageArea { make: "NIKON CORPORATION", model: "NIKON D800E", size: (7424, 4924), crop: (8, 6, 7360, 4912) }, ImageArea { make: "SONY", model: "ILCE-7", size: (6048, 4024), crop: (12, 12, 6000, 4000) }, @@ -152,6 +157,11 @@ pub(crate) fn apply(s: &mut Sensor) { s.crop = Rect::new(x, y, w, h); } let Some(p) = PROFILES.iter().find(|p| make == p.make && model == p.model && (s.width, s.height) == p.size) else { return }; + // A raw with its own colour calibration (a DNG) keeps it: only the measured image area + // above applies. The measured profile stands in for files that carry no matrix themselves. + if !s.color.calibrations.is_empty() { + return; + } let (x, y, w, h) = p.crop; s.crop = Rect::new(x, y, w, h); s.white = [p.white; 3]; @@ -265,6 +275,36 @@ mod tests { assert_eq!(s.crop, Rect::new(0, 0, 7424, 4924)); } + #[test] + fn d90_image_area_matches_the_camera_jpeg() { + let mut s = nef("NIKON D90", 4352, 2868); + apply(&mut s); + assert_eq!(s.crop, Rect::new(10, 10, 4288, 2848)); + // Only the image area is measured: levels, colour and tone stay untouched. + assert!(s.color.calibrations.is_empty() && s.tone_curve.is_empty()); + assert_eq!(s.white, [16383.0; 3]); + // An explicit crop in the file wins over the measured area. + s.crop = Rect::new(0, 0, 4288, 2848); + apply(&mut s); + assert_eq!(s.crop, Rect::new(0, 0, 4288, 2848)); + } + + #[test] + fn a_file_with_its_own_calibration_keeps_it() { + // A file that carries its own colour calibration (a DNG, or any calibrated raw) keeps + // it: the measured profile must not override it (only the image area would apply). + let mut s = nef("NIKON D4", 4992, 3292); + s.color = ColorInfo { + calibrations: vec![Calibration { temperature: 6504.0, color_matrix: IDENTITY, forward_matrix: None, camera_calibration: IDENTITY }], + ..ColorInfo::default() + }; + apply(&mut s); + assert_eq!(s.color.calibrations.len(), 1); + assert_eq!(s.color.calibrations[0].temperature, 6504.0, "the file's own calibration stands"); + assert!(s.tone_curve.is_empty() && s.black_point == 0.0); + assert_eq!(s.crop, Rect::new(0, 0, 4992, 3292), "the D4 has no measured image area"); + } + #[test] fn other_cameras_and_sizes_are_left_alone() { for (model, w, h) in [("NIKON D4S", 4992, 3292), ("NIKON D4", 2496, 1646), ("NIKON D800", 7424, 4924)] { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2651f4c4d1a..ae0806374dc 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -66,7 +66,7 @@ supports many more, including CR3). | DNG (incl. LJPEG and JPEG XL tiles) | yes; lossy DNG no | FILE-215-11 | | Canon CR2 | yes | | | Canon CR3 | detected, unsupported | `crates/raw/src/lib.rs:219` | -| Nikon NEF/NRW (lossless, lossy) | yes; "lossy after split" no | #50; D5100 image area measured on three 14-bit lossy NEFs; [validation](nikon-nef-development.md) | +| Nikon NEF/NRW (lossless, lossy) | yes; "lossy after split" no | #50; D5100 and D90 image areas measured (14-bit NEFs); [validation](nikon-nef-development.md) | | Sony ARW/SR2/SRF (incl. compressed) | yes | | | Panasonic RW2, Pentax PEF | yes | | | Olympus ORF | uncompressed only | | diff --git a/docs/gaps.md b/docs/gaps.md index 52b467b2dd7..d90ce1b74d4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -129,6 +129,10 @@ what an agent can't finish alone. tuning retains the fitted look and applies user gains afterwards. Three D5100 NEFs establish a guarded 4928 × 3264 image area. This is an estimated rendering, not a measured D5100 colour calibration; [validation](nikon-nef-development.md). +- **Progress (2026-10-13):** the D90's image area (4288 × 2848 at (10, 10) in a + 4352 × 2868 plane) is measured by aligning the decoded plane with the camera's own + JPEG, so a D90 NEF opens on the camera's frame instead of the uncropped sensor plane; + `crates/raw/src/cameras.rs` (`IMAGE_AREAS`). - **Estimate:** 120–200 h. ### G15. AI and generative features @@ -263,6 +267,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 | | 2026-10-13 | minor | G1: CMYK Hue/Saturation and Color Balance work on C, M and Y as inverted RGB with black kept, as Photoshop does; cmyk hue-saturation 100% → 0.4–0.7% bad pixels, color-balance 74% → 25%; floor unchanged | | 2026-10-13 | minor | G1: CMYK Posterize works on the stored values (1 − ink); psd-tools posterize_cmyk passes; psd-tools floor → 242 of 309 | From 5dafbeeafcb7bc59042a8691bd3bce607969a121 Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Thu, 15 Oct 2026 15:23:03 +1100 Subject: [PATCH 37/37] Codecs: open Cineon (.cin) film frames read-only (#4691) * Raw: measure the Nikon D90 image area (4288x2848 at (10, 10)) Aligning the decoded D90 sensor plane with the camera's own JPEG puts the image at (10, 10) in the 4352x2868 sensor plane, giving the camera's 4288x2848 frame (10-pixel margins; the right border reads the camera's flat 255 from column 4310). Add the measured ImageArea so a D90 NEF opens on the camera's frame instead of the uncropped plane, and make a measured profile leave a file that carries its own colour calibration (a DNG) untouched. * Codecs: open Cineon (.cin) film frames read-only Cineon is the 10-bit logarithmic film-scan format DPX grew from. Read it from the same Kodak header family: the generic header (big-endian, orientation at 192, channel count at 193, the channel-1 bits/dimensions), one or three channels, three 10-bit samples packed into each 32-bit word on a word boundary. The 10-bit code values open as U16 (round(c x 65535 / 1023)); the file's log black/white points are a display choice and are not applied. A depth other than 10 bits or a channel count other than 1/3 is Unsupported; truncation errors rather than panicking. Read-only (no Cineon writer), so .cin joins the open filters and Cineon read closes part of #1049's G10 gap. * cargo fmt the extension lists Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- apps/photocraft-web/src/web.rs | 4 +- apps/photocraft/src/services.rs | 4 +- crates/codecs/README.md | 11 ++- crates/codecs/src/codecs/dpx.rs | 128 +++++++++++++++++++++++++++++ crates/codecs/src/format.rs | 17 +++- crates/codecs/src/lib.rs | 3 + crates/codecs/tests/detect_caps.rs | 11 +++ docs/file-format-parity.md | 2 +- docs/gaps.md | 7 +- 9 files changed, 178 insertions(+), 9 deletions(-) diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs index d5004334c19..eb350d17eb1 100644 --- a/apps/photocraft-web/src/web.rs +++ b/apps/photocraft-web/src/web.rs @@ -18,8 +18,8 @@ type Inbox = Arc)>>>; /// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries. const OPEN_EXTS: &[&str] = &[ "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", - "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", - "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub", + "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", + "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; const CANVAS_ID: &str = "photocraft_canvas"; diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 36c7c2ccf5b..ae2b3fae844 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -21,8 +21,8 @@ mod recovery_tests; /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", - "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", - "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", + "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 7486d465048..d4f7094894d 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -47,6 +47,7 @@ let out = encode(&img, Format::Tiff, &EncodeOptions::default())?; | Radiance HDR | yes | yes | F32 | RGB | no | no | no | no | no | no | yes (RGBE) | `image` | | FITS | yes | yes | U8, U16, F32 | Gray, RGB | no | no | no | no | no | yes (header cards) | no | built in | | DPX | yes | yes | U8, U16 (10/12-bit code values read and written exactly through U16) | Gray, RGB, RGBA | yes | no | no | no | no | DPX header fields only (creator, project, copyright, creation time, transfer, colorimetric, frame position, frame rate, time code) | no | built in | +| Cineon | yes | **no** | U16 (10-bit code values) | Gray, RGB | no | no | no | no | no | no | n/a | built in | | AVIF | **no** | only with feature `avif` | U8 | RGB, RGBA | yes | no | no | no | no | no | yes | `image` + `ravif` | | HEIF/HEIC | with feature `heif` | **no** | U8, U16 (10/12-bit decodes to U16) | RGB, RGBA | yes (auxiliary alpha) | yes (`colr` prof) | yes | yes | no | no | n/a | `heic-rs` | @@ -93,7 +94,15 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them big-endian, one unencoded element, at `EncodeOptions::dpx_bits` (8/10/12/16; by default 8 for U8 and 16 otherwise), packing 1 for 10 and 12 bits; gray with alpha is written as luma. Other descriptors, signed or run-length-encoded data and other bit depths return - `CodecError::Unsupported` naming the field. Cineon (`.cin`) is not supported. + `CodecError::Unsupported` naming the field. + +* **Cineon (read-only).** Kodak's 10-bit logarithmic film-scan format (the one DPX grew from), + read from the same Kodak header family: the generic 1024-byte header, big-endian, one (Gray) + or three (RGB) channels, three 10-bit samples packed into each 32-bit word, lines on a word + boundary. The 10-bit code values open as U16 `round(c × 65535 / 1023)`; the file's black/white + reference points are a log-conversion choice and are not applied. A depth other than 10 bits or + a channel count other than 1/3 returns `CodecError::Unsupported`; truncation errors rather than + panicking. There is no Cineon writer (`ASYMMETRIC_EXCEPTIONS`); save as DPX, TIFF or EXR. * **Camera raw files** (DNG, CR2, NEF, ARW… which are TIFF-structured) are recognised and refused with `CodecError::Unsupported`: they are sensor data, not flat images. `photocraft-raw` decodes diff --git a/crates/codecs/src/codecs/dpx.rs b/crates/codecs/src/codecs/dpx.rs index 8b772707cca..091403d641c 100644 --- a/crates/codecs/src/codecs/dpx.rs +++ b/crates/codecs/src/codecs/dpx.rs @@ -337,6 +337,78 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result Ok(img) } +// ---------------------------------------------------------------- Cineon (Kodak .cin) +// +// Cineon is the 10-bit film-scan format DPX grew from (same Kodak header family, big-endian). +// The generic header is 1024 bytes: the file information fields, then at offset 192 the image +// orientation (1 byte), the channel count (1 byte) and up to eight 28-byte channel descriptors +// (the first carries the bits per pixel and the line/image dimensions). Image data is three +// 10-bit samples packed into each 32-bit word, lines on a word boundary — the same layout as +// DPX's 10-bit packing method A, so the unpacking is shared. + +/// The Cineon magic number (`802A5FD7` hex), big-endian. +pub(crate) fn is_cineon(b: &[u8]) -> bool { + b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7]) +} + +/// The EXIF orientation (1–8) for a Cineon header's orientation code (the same 0–7 order as DPX). +pub(crate) fn cineon_orientation(b: &[u8]) -> u16 { + let Some(code) = b.get(192).copied() else { return 1 }; + match code { + 1 => 2, + 2 => 4, + 3 => 3, + 4 => 5, + 5 => 6, + 6 => 8, + 7 => 7, + _ => 1, + } +} + +/// Decode a Cineon (`.cin`) frame: 10-bit logarithmic film scans, big-endian, one (gray) or +/// three (RGB) channels. The 10-bit code values become U16 as `round(c × 65535 / 1023)`; the +/// file's black/white reference points are not applied (a log conversion is a display choice). +pub(crate) fn decode_cineon(bytes: &[u8], limits: &Limits) -> Result { + if !is_cineon(bytes) { + return Err(err("missing the Cineon magic number (802A5FD7)")); + } + let o = Order::Big; + let missing = |what: &str| err(format!("the header ends before {what}")); + let image_offset = usize::try_from(o.u32(bytes, 4).ok_or_else(|| missing("the image data offset"))?).map_err(|_| err("image data offset out of range"))?; + let channels = *bytes.get(193).ok_or_else(|| missing("the channel count"))?; + let bits = *bytes.get(198).ok_or_else(|| missing("the bits per pixel"))?; + if bits != 10 { + return Err(unsupported(format!("{bits}-bit samples (Cineon frames are 10-bit)"))); + } + let layout = match channels { + 1 => ChannelLayout::Gray, + 3 => ChannelLayout::Rgb, + n => return Err(unsupported(format!("{n} channels (Cineon frames have 1 or 3)"))), + }; + let width = o.u32(bytes, 200).ok_or_else(|| missing("the pixels per line"))?; + let height = o.u32(bytes, 204).ok_or_else(|| missing("the lines per image"))?; + limits.check(width, height, layout, SampleType::U16)?; + + let (w, h) = (width as usize, height as usize); + let per_line = w.checked_mul(layout.channels()).ok_or_else(|| CodecError::LimitExceeded("line too long".into()))?; + // Three 10-bit samples per 32-bit word, lines on a word boundary (DPX packing 1). + let line_len = line_bytes(per_line, 10, 1).ok_or_else(|| CodecError::LimitExceeded("line too long".into()))?; + let data = bytes.get(image_offset..).ok_or_else(|| err("the image data offset is past the end of the file"))?; + let need = line_len.checked_mul(h).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; + if data.len() < need { + return Err(err("truncated image data")); + } + let mut codes = vec![0u16; per_line.checked_mul(h).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?]; + for (y, row) in codes.chunks_exact_mut(per_line).enumerate() { + let start = y * line_len; + let line = data.get(start..start + line_len).ok_or_else(|| err("truncated image data"))?; + unpack_line(line, o, 10, 1, row)?; + } + let wide: Vec = codes.iter().map(|&c| widen(c, 1023)).collect(); + Image::from_u16(width, height, layout, &wide) +} + /// The kept header fields as text metadata, in [`KEYS`] order; undefined ones are left out. fn header_text(b: &[u8], o: Order, e: Element) -> Vec<(String, String)> { let mut text = Vec::new(); @@ -653,4 +725,60 @@ mod tests { let img = decode(&b, &Limits::default()).unwrap(); assert_eq!(img.data(), &[1, 2, 3, 4, 5, 6]); } + + /// A minimal Cineon: a 1024-byte generic header, then `w × h` 10-bit samples packed three + /// to a 32-bit word (RGB in word order, or gray three pixels per word). + fn cineon(w: u32, h: u32, channels: u8, px: &[[u16; 3]]) -> Vec { + let mut b = vec![0u8; 1024]; + b[0..4].copy_from_slice(&[0x80, 0x2A, 0x5F, 0xD7]); // magic (802A5FD7) + b[4..8].copy_from_slice(&1024u32.to_be_bytes()); // image data offset + b[192] = 0; // orientation: left-to-right, top-to-bottom + b[193] = channels; + b[198] = 10; // bits per pixel (channel 1) + b[200..204].copy_from_slice(&w.to_be_bytes()); // pixels per line + b[204..208].copy_from_slice(&h.to_be_bytes()); // lines per image + let word = |a: u16, c: u16, e: u16| ((u32::from(a) << 22) | (u32::from(c) << 12) | (u32::from(e) << 2)).to_be_bytes(); + if channels == 3 { + for p in px { + b.extend_from_slice(&word(p[0], p[1], p[2])); + } + } else { + let g = |i: usize| px.get(i).map_or(0, |p| p[0]); + for i in (0..px.len()).step_by(3) { + b.extend_from_slice(&word(g(i), g(i + 1), g(i + 2))); + } + } + b + } + + #[test] + fn cineon_reads_ten_bit_rgb() { + let px = [[0, 512, 1023], [1023, 0, 256]]; + let b = cineon(2, 1, 3, &px); + assert!(is_cineon(&b)); + assert_eq!(order(&b), None, "Cineon is not DPX"); + let img = decode_cineon(&b, &Limits::default()).unwrap(); + assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); + assert_eq!( + img.to_u16_samples().unwrap(), + vec![widen(0, 1023), widen(512, 1023), widen(1023, 1023), widen(1023, 1023), widen(0, 1023), widen(256, 1023)] + ); + } + + #[test] + fn cineon_reads_grayscale_and_rejects_other_depths() { + let px = [[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]]; + let b = cineon(4, 1, 1, &px); + let img = decode_cineon(&b, &Limits::default()).unwrap(); + assert_eq!(img.layout(), ChannelLayout::Gray); + assert_eq!(img.to_u16_samples().unwrap(), vec![widen(10, 1023), widen(20, 1023), widen(30, 1023), widen(40, 1023)]); + // A depth other than 10 is unsupported, and truncation errors rather than panicking. + let mut bad = cineon(1, 1, 3, &[[0, 0, 0]]); + bad[198] = 8; + assert!(matches!(decode_cineon(&bad, &Limits::default()), Err(CodecError::Unsupported { .. }))); + let full = cineon(4, 4, 3, &[[0; 3]; 16]); + for cut in [0, 4, 200, 1024, full.len() - 1] { + assert!(decode_cineon(&full[..cut.min(full.len())], &Limits::default()).is_err(), "cut {cut}"); + } + } } diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index d3730c08fb4..2d330cc976b 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -33,6 +33,8 @@ pub enum Format { Fits, /// DPX (SMPTE 268M Digital Picture Exchange): luma, RGB or RGBA film and video frames. Dpx, + /// Kodak Cineon (`.cin`, the 10-bit film-scan format DPX grew from): read-only. + Cineon, } /// What a format can hold **and** what this crate reads/writes for it. @@ -78,6 +80,11 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ until a pure-Rust AV1 decoder is viable. Only enabled with the non-default `avif` feature.", ), + ( + Format::Cineon, + "Cineon frames are imported for film work; this crate has no Cineon writer, so save an \ + imported frame as DPX, TIFF or EXR instead.", + ), ( Format::Heif, "HEIC decode uses heic-rs (pure Rust, in the optional photocraft-heif crate behind the \ @@ -95,7 +102,7 @@ const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::C impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 19] = [ + pub const ALL: [Format; 20] = [ Format::Png, Format::Jpeg, Format::Tiff, @@ -115,6 +122,7 @@ impl Format { Format::Heif, Format::Fits, Format::Dpx, + Format::Cineon, ]; pub fn caps(self) -> FormatCaps { @@ -148,6 +156,7 @@ impl Format { Format::Heif => "HEIF", Format::Fits => "FITS", Format::Dpx => "DPX", + Format::Cineon => "Cineon", } } @@ -174,6 +183,7 @@ impl Format { Format::Heif => &["heic", "heif", "hif"], Format::Fits => &["fits", "fit", "fts"], Format::Dpx => &["dpx"], + Format::Cineon => &["cin"], } } @@ -198,6 +208,7 @@ impl Format { Format::Heif => "image/heif", Format::Fits => "image/fits", Format::Dpx => "image/x-dpx", + Format::Cineon => "image/x-cin", } } @@ -253,6 +264,7 @@ pub fn caps(format: Format) -> FormatCaps { Format::Fits => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: &[L::Gray, L::Rgb], alpha: false, text: true, ..base }, // `text`: the DPX header fields only (see `fidelity_warnings_with`). Format::Dpx => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], text: true, ..base }, + Format::Cineon => FormatCaps { read: true, write: false, depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, } } @@ -307,6 +319,9 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(b"SDPX") || b.starts_with(b"XPDS") { return Some(Format::Dpx); } + if crate::codecs::dpx::is_cineon(b) { + return Some(Format::Cineon); + } if b.starts_with(b"SIMPLE =") { return Some(Format::Fits); } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 3831cf654f3..eb010a758fc 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -79,6 +79,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Dds => dds::decode(bytes, l), Format::Fits => fits::decode(bytes, l), Format::Dpx => dpx::decode(bytes, l), + Format::Cineon => dpx::decode_cineon(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), @@ -97,6 +98,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Tiff => tiff::orientation(bytes, None), Format::Heif => 1, Format::Dpx => dpx::orientation(bytes), + Format::Cineon => dpx::cineon_orientation(bytes), _ => img.meta.exif.as_deref().map_or(1, exif_orientation), }; finish_decode(img, o, opts) @@ -252,6 +254,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result Err(CodecError::unsupported(format, "DDS is import-only; save as PNG instead")), Format::Fits => fits::encode(image, plan, opts), Format::Dpx => dpx::encode(image, plan, opts), + Format::Cineon => Err(CodecError::unsupported(format, "Cineon is import-only; save as DPX, TIFF or EXR instead")), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::encode(format, image, plan, opts), diff --git a/crates/codecs/tests/detect_caps.rs b/crates/codecs/tests/detect_caps.rs index 22bf227eb8f..f2191e05f17 100644 --- a/crates/codecs/tests/detect_caps.rs +++ b/crates/codecs/tests/detect_caps.rs @@ -187,6 +187,17 @@ fn detect_magic_hdr() { assert_eq!(detect(b"#?RGBE\n"), Some(Format::Hdr)); } #[test] +fn detect_magic_cineon() { + let mut b = vec![0u8; 208]; + b[0..4].copy_from_slice(&[0x80, 0x2A, 0x5F, 0xD7]); + assert_eq!(detect(&b), Some(Format::Cineon)); + assert_eq!(from_extension("scan.CIN"), Some(Format::Cineon)); + assert!(caps(Format::Cineon).read && !caps(Format::Cineon).write, "Cineon is read-only"); + assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Cineon)); + // A bare magic is an error, never a panic. + assert!(decode_as(Format::Cineon, &b).is_err()); +} +#[test] fn detect_magic_avif() { assert_eq!(detect(b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf"), Some(Format::Avif)); assert_eq!(detect(b"\0\0\0\x1cftypavis\0\0\0\0avismsf1miaf"), Some(Format::Avif)); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ae0806374dc..382034e3206 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -43,7 +43,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | | JPEG 2000 | R/W | no (#1047) | no | | -| Cineon / DPX | R (DPX), R/W (CIN) | DPX: luma, RGB, RGBA at 8/10/12/16 bits, both byte orders (#1049); Cineon no | DPX: 8/10/12/16 bits (`dpxBits`, `--dpx-bits`); Cineon no | Writes DPX, which Photoshop only reads; header fields (creator, project, copyright, transfer, frame rate, time code…) round-trip; no Cineon, no RLE | +| Cineon / DPX | R (DPX), R/W (CIN) | DPX: luma, RGB, RGBA at 8/10/12/16 bits, both byte orders (#1049); Cineon: 10-bit gray/RGB, read-only | DPX: 8/10/12/16 bits (`dpxBits`, `--dpx-bits`); Cineon no | Writes DPX, which Photoshop only reads; header fields (creator, project, copyright, transfer, frame rate, time code…) round-trip; Cineon read-only, no RLE | | DICOM | R/W | no | no | | | PCX | R/W | no | no | | | Pixar | R/W | no | no | | diff --git a/docs/gaps.md b/docs/gaps.md index d90ce1b74d4..d964b01eb52 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -224,10 +224,12 @@ what an agent can't finish alone. ### G10. Missing and partial file formats - **Missing:** JPEG Options dialog (FILE-215-19), Photoshop PDF read and write and multi-page PDF (FILE-215-10, #2541), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047), - Cineon (DPX landed, #1049), DICOM, EPS/DCS, PCX, Pixar, IFF, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop + Cineon write (read landed), DICOM, EPS/DCS, Pixar, IFF, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop Raw; layered TIFF extra alpha channels (FILE-215-7); spot plates (FILE-215-17); .atn, .asl, .shc, .csh presets (FILE-215-15); C2PA (#1050). - **Detail:** [`file-format-parity.md`](file-format-parity.md). +- **Progress (2026-10-13):** Cineon (`.cin`) 10-bit gray/RGB frames open read-only, sharing the + DPX header/unpacking (`crates/codecs/src/codecs/dpx.rs`); writing is still open. - **Estimate:** 120–220 h. ## Hardware gaps @@ -292,6 +294,7 @@ what an agent can't finish alone. | 2026-10-12 | minor | G1: #2465 (CS2 `PlLd`-only smart objects) marked fixed | | 2026-10-12 | minor | G1: CMYK Invert, Posterize and Threshold work on the inks, 16-bit Lab Invert keeps greys neutral; Photoshop-oracle floor 133 → 145 of 258 (145 already passed on main) | | 2026-10-12 | minor | G5: spring-loaded tool letters done (#2672) | +| 2026-10-13 | minor | G10: Cineon read landed (10-bit gray/RGB, shares the DPX path); Cineon write remains open | | 2026-10-12 | minor | G10: DPX read and write (#1049); Cineon remains open | | 2026-10-12 | minor | G4: checkbox-only Brush Settings rows preserve the open controls and Smoothing settings (#4283); no readiness percentage or estimate changed | | 2026-10-12 | minor | G11: Load/Save Actions `.atn` landed (AUTO-219-2 partial); remaining panel work listed |