PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Crop tool: Show Cropped Area (H) and Crop Shield colour/opacity options (#1919) (#2128)
David Mannc7287703a316
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsindex ce769065a..7e57fe270 100644--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@ -235,7 +235,9 @@ pub struct UiSetParams {/// ("point" or 1, 3, 5, 11, 31, 51, 101), eyedropperSample (current, currentAndBelow, all,/// allNoAdjustments, currentAndBelowNoAdjustments), eyedropperRing (bool), cropOverlay (thirds,/// grid, diagonal, triangle, goldenRatio, goldenSpiral), cropOverlayShow (auto, always, never),- /// cropOverlayOrientation (0..3). Other fields are an error.+ /// cropOverlayOrientation (0..3), cropShield (an object patching show_cropped_area, enabled,+ /// color ("matchCanvas" or "custom"), custom_color ([r, g, b]), opacity (0..100) and+ /// auto_adjust). Other fields are an error.pub fields: Value,}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 52d25d341..5635928fb 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2800,8 +2800,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:crate::layer_pick_ui::show(app, &ctx);crate::canvas_tool_menu::show(app, &ctx);crate::snap_ui::draw(app, &painter, &xf);- // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview).- if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond {+ // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview),+ // nor while the Crop tool hides everything outside its box (Show Cropped Area off).+ if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) {painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);}crate::type_tool::draw_overlay(app, &painter, &xf);@@ -3067,18 +3068,20 @@ fn marching_ants(painter: &egui::Painter, r: Rect, time: f64) {}}-/// Photoshop crop overlay: dimmed outside, bright frame, the composition `guides` (unit-square-/// polylines, `crop_overlay::guides`), corner and edge handles.-fn crop_overlay(painter: &egui::Painter, r: Rect, guides: &[crate::crop_overlay::Polyline]) {+/// Photoshop crop overlay: the `shield` outside (`crop_shield::fill`; none when disabled), bright+/// frame, the composition `guides` (unit-square polylines, `crop_overlay::guides`), corner and+/// edge handles.+fn crop_overlay(painter: &egui::Painter, r: Rect, shield: Option<Color32>, guides: &[crate::crop_overlay::Polyline]) {let clip = painter.clip_rect();- let dim = Color32::from_black_alpha(130);- for band in [- Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)),- Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max),- Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)),- Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)),- ] {- painter.rect_filled(band, 0.0, dim);+ if let Some(dim) = shield {+ for band in [+ Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)),+ Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max),+ Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)),+ Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)),+ ] {+ painter.rect_filled(band, 0.0, dim);+ }}painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle);draw_crop_guides(painter, guides, |a, b| r.min + r.size() * vec2(a, b));@@ -3098,7 +3101,7 @@ fn crop_overlay(painter: &egui::Painter, r: Rect, guides: &[crate::crop_overlay:/// [`crop_overlay`] for a turned frame (or a rotated view): `q` is the frame's top-left, top-right,/// bottom-right and bottom-left corner on screen, a parallelogram.-fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], guides: &[crate::crop_overlay::Polyline]) {+fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], shield: Option<Color32>, guides: &[crate::crop_overlay::Polyline]) {let (u, v) = (q[1] - q[0], q[3] - q[0]);let (lu, lv) = (u.length(), v.length());if !(lu.is_finite() && lv.is_finite()) || lu < 1e-3 || lv < 1e-3 {@@ -3110,17 +3113,18 @@ fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], guides: &[crate::clet reach = clip.size().length() + (clip.center() - at(0.5, 0.5)).length();let (eu, ev) = (reach / lu, reach / lv);let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)];- let dim = Color32::from_black_alpha(130);- let mut mesh = egui::Mesh::default();- for p in q.iter().chain(outer.iter()) {- mesh.colored_vertex(*p, dim);- }- for i in 0..4u32 {- let j = (i + 1) % 4;- mesh.add_triangle(i, j, 4 + j);- mesh.add_triangle(i, 4 + j, 4 + i);+ if let Some(dim) = shield {+ let mut mesh = egui::Mesh::default();+ for p in q.iter().chain(outer.iter()) {+ mesh.colored_vertex(*p, dim);+ }+ for i in 0..4u32 {+ let j = (i + 1) % 4;+ mesh.add_triangle(i, j, 4 + j);+ mesh.add_triangle(i, 4 + j, 4 + i);+ }+ painter.add(egui::Shape::mesh(mesh));}- painter.add(egui::Shape::mesh(mesh));painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, Color32::WHITE)));draw_crop_guides(painter, guides, at);let h = Stroke::new(3.0, Color32::WHITE);@@ -3294,12 +3298,13 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover);if let Some(c) = app.ui.crop_rect {let deg = crate::crop_ui::angle(app);+ let shield = crate::crop_shield::current(app, painter.ctx());if deg == 0.0 && xf.rotation == 0.0 {let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32));- crop_overlay(painter, r, &crate::crop_overlay::current_guides(app, r.width(), r.height()));+ crop_overlay(painter, r, shield, &crate::crop_overlay::current_guides(app, r.width(), r.height()));} else {let q = crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32));- crop_overlay_turned(painter, q, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3])));+ crop_overlay_turned(painter, q, shield, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3])));}// The frame's angle beside the pointer while it turns (#1792).if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) {diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rsindex c5b8b6fbe..74608a8a3 100644--- a/crates/ui-egui/src/color_picker_ui.rs+++ b/crates/ui-egui/src/color_picker_ui.rs@@ -216,6 +216,21 @@ pub fn open_for_field(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], dialoapp.ui.open_dialog(DialogKind::Command, f)}+/// Open the picker on `rgb` for a colour the shell keeps itself (e.g. the Crop shield's custom+/// colour): OK hands `"#rrggbb"` to `target`'s setter in [`confirm`]; Cancel leaves it alone.+pub fn open_for_target(app: &mut PhotocraftApp, target: &str, label: &str, rgb: [f32; 3]) -> u64 {+ let hsv = rgb_to_hsv(rgb);+ let mut f = Map::new();+ f.insert("__colorPicker".into(), json!(target));+ f.insert("__label".into(), json!(label));+ f.insert("color".into(), json!(hex(rgb)));+ f.insert("__orig".into(), json!(hex(rgb)));+ f.insert("__hsv".into(), json!(hsv));+ f.insert("__mode".into(), json!("h"));+ f.insert("__webOnly".into(), json!(false));+ app.ui.open_dialog(DialogKind::Command, f)+}+/// Set by a dialog body (to the picker's title) to open the Color Picker on its `color` field.const REQUEST: &str = "__pickColor";@@ -641,6 +656,10 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,d.fields.insert(field.into(), json!(color));return Ok(json!({ "color": color }));}+ if target == "cropShield" {+ crate::crop_shield::set_custom_color(app, color)?;+ return Ok(json!({ "color": color }));+ }let r = app.run("tools.setColors", json!({ target: color }))?;if target == "foreground" {crate::type_tool::foreground_changed(app);diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex b26290840..c8d4a751e 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -74,7 +74,7 @@ pub enum Outcome {/// field's value is validated before the first one is applied, so a typo, an unknown field, a/// bad value or a bad nested key can't reply with success while nothing — or only half of it —/// changed (#412).-pub const UI_SET_FIELDS: [&str; 28] = [+pub const UI_SET_FIELDS: [&str; 29] = ["tool","panels","dock",@@ -103,6 +103,7 @@ pub const UI_SET_FIELDS: [&str; 28] = ["cropOverlay","cropOverlayShow","cropOverlayOrientation",+ "cropShield",];/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app@@ -350,6 +351,11 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)Some(_) => return Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()),None => None,};+ // The Crop tool's gear menu: Show Cropped Area and the shield (#1919).+ let crop_shield = merged_object(&app.ui.tool_options.crop_shield, p.get("cropShield"), "cropShield")?;+ if crop_shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) {+ return Err("cropShield.opacity must be 0..100".into());+ }let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?;let mask_target = bool_field(p, "maskTarget")?;let vector_mask_target = bool_field(p, "vectorMaskTarget")?;@@ -459,6 +465,9 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)if let Some(o) = crop_overlay_orientation {app.ui.tool_options.crop_overlay_orientation = o;}+ if let Some(s) = crop_shield {+ app.ui.tool_options.crop_shield = s;+ }if let Some(v) = panels {app.ui.panels = v;}@@ -1246,6 +1255,37 @@ mod tests {assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::GoldenSpiral, "a rejected call applies none of its fields");}+ /// #1919: the Crop tool's gear menu (Show Cropped Area, crop shield) over the control channel.+ #[test]+ fn ui_set_drives_the_crop_shield_options() {+ use crate::crop_shield::{CropShield, ShieldColor};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let good = call(&mut app, &ctx, "ui.set", json!({"cropShield": {"color": "custom", "custom_color": [255, 0, 0], "opacity": 40}}));+ assert_eq!(good["ok"], true, "{good}");+ let want = CropShield { color: ShieldColor::Custom, custom_color: [255, 0, 0], opacity: 40.0, ..Default::default() };+ assert_eq!(app.ui.tool_options.crop_shield, want);+ // A patch: the other fields stay.+ assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropShield": {"show_cropped_area": false}}))["ok"], true);+ assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want.clone() });+ let t = &call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["crop_shield"];+ assert_eq!((t["color"].as_str(), t["opacity"].as_f64(), t["show_cropped_area"].as_bool()), (Some("custom"), Some(40.0), Some(false)));+ for bad in [+ json!({"cropShield": true}),+ json!({"cropShield": {"opacity": 101}}),+ json!({"cropShield": {"opacity": -1}}),+ json!({"cropShield": {"opacity": "50"}}),+ json!({"cropShield": {"color": "red"}}),+ json!({"cropShield": {"custom_color": [256, 0, 0]}}),+ json!({"cropShield": {"shield": true}}),+ json!({"cropShield": {"enabled": false}, "cropOverlay": "nope"}),+ ] {+ let r = call(&mut app, &ctx, "ui.set", bad.clone());+ assert_eq!(r["ok"], false, "{bad}: {r}");+ }+ assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want }, "a rejected call applies none of its fields");+ }+#[test]fn ui_set_opens_the_brush_preset_picker_and_sets_its_view() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/crop_shield.rs b/crates/ui-egui/src/crop_shield.rsnew file mode 100644index 000000000..e97bff2d1--- /dev/null+++ b/crates/ui-egui/src/crop_shield.rs@@ -0,0 +1,312 @@+//! The Crop tool's shield options (Photoshop's options-bar gear menu, "Set additional Crop+//! options", #1919): whether the area outside the crop box shows at all (Show Cropped Area, H),+//! and the shield dimming it (Enable Crop Shield: Match Canvas or a custom colour, an opacity, and+//! Auto Adjust Opacity, which lightens it while the box is dragged). Photoshop's defaults: all on,+//! Match Canvas, 75 %. PhotoCraft always works like Photoshop's Classic Mode, so the menu has no+//! Use Classic Mode or Auto Center Preview.+//!+//! The state lives in `ToolOptions::crop_shield` ([`CropShield`]), which `ui.inspect` reports and+//! `ui.set {cropShield: {...}}` patches. [`fill`] resolves it to the colour the canvas paints over+//! the area outside the box.++use egui::{Color32, Key, Modifiers};+use serde::{Deserialize, Serialize};++use crate::PhotocraftApp;+use crate::state::Tool;++/// Photoshop's default shield opacity, percent.+pub const DEFAULT_OPACITY: f32 = 75.0;+/// Auto Adjust Opacity: the share of the opacity the shield keeps while the box is dragged.+pub const EDITING_FACTOR: f32 = 0.5;++/// The shield's colour.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum ShieldColor {+ /// The pasteboard's colour (Preferences › Interface, or the theme's canvas).+ #[default]+ MatchCanvas,+ /// [`CropShield::custom_color`].+ Custom,+}++/// The gear menu's options. Every field defaults on its own, so older settings load.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct CropShield {+ /// Show Cropped Area (H): off hides everything outside the box behind the canvas colour.+ pub show_cropped_area: bool,+ /// Enable Crop Shield: off shows the area outside the box undimmed.+ pub enabled: bool,+ pub color: ShieldColor,+ /// sRGB, used when `color` is `Custom`.+ pub custom_color: [u8; 3],+ /// Percent, 0..=100 ([`CropShield::opacity`] clamps a stray value).+ pub opacity: f32,+ /// Auto Adjust Opacity: lighter while the box is dragged.+ pub auto_adjust: bool,+}++impl Default for CropShield {+ fn default() -> Self {+ Self { show_cropped_area: true, enabled: true, color: ShieldColor::MatchCanvas, custom_color: [0, 0, 0], opacity: DEFAULT_OPACITY, auto_adjust: true }+ }+}++impl CropShield {+ /// The opacity as a fraction in 0..=1: a non-finite value (a hand-edited settings file) is+ /// the default, an out-of-range one is clamped.+ pub fn opacity(&self) -> f32 {+ let o = if self.opacity.is_finite() { self.opacity } else { DEFAULT_OPACITY };+ o.clamp(0.0, 100.0) / 100.0+ }+}++/// What to paint over the area outside the crop box, `canvas` being the pasteboard colour and+/// `editing` a crop drag in progress: the opaque canvas colour when Show Cropped Area is off, no+/// shield when it is disabled (or fully transparent), otherwise its colour at its opacity.+pub fn fill(s: &CropShield, canvas: Color32, editing: bool) -> Option<Color32> {+ let [r, g, b, _] = canvas.to_srgba_unmultiplied();+ if !s.show_cropped_area {+ return Some(Color32::from_rgb(r, g, b));+ }+ if !s.enabled {+ return None;+ }+ let [r, g, b] = match s.color {+ ShieldColor::MatchCanvas => [r, g, b],+ ShieldColor::Custom => s.custom_color,+ };+ let a = s.opacity() * if s.auto_adjust && editing { EDITING_FACTOR } else { 1.0 };+ let a = (a * 255.0).round().clamp(0.0, 255.0) as u8;+ (a > 0).then(|| Color32::from_rgba_unmultiplied(r, g, b, a))+}++/// The pasteboard colour the shield matches: Preferences › Interface's, else the theme's canvas.+pub fn canvas_color(app: &PhotocraftApp, ctx: &egui::Context) -> Color32 {+ crate::prefs_ui::pasteboard_color(app).unwrap_or_else(|| crate::theme::Tokens::get(ctx).canvas)+}++/// The shield over the pending crop box now ([`fill`]).+pub fn current(app: &PhotocraftApp, ctx: &egui::Context) -> Option<Color32> {+ fill(&app.ui.tool_options.crop_shield, canvas_color(app, ctx), app.crop.drag.is_some())+}++/// Show Cropped Area is off with the Crop tool showing a box: nothing outside it shows.+pub fn hides_outside(app: &PhotocraftApp) -> bool {+ app.ui.tool == Tool::Crop && app.ui.crop_rect.is_some() && !app.ui.tool_options.crop_shield.show_cropped_area+}++/// H with the Crop tool showing a box and no drag in progress toggles Show Cropped Area. Returns+/// true when the key was used; otherwise H stays the Hand tool key.+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {+ if app.ui.tool != Tool::Crop || app.ui.crop_rect.is_none() || app.crop.drag.is_some() {+ return false;+ }+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::H)) {+ let s = &mut app.ui.tool_options.crop_shield;+ s.show_cropped_area = !s.show_cropped_area;+ return true;+ }+ false+}++/// The options bar's gear button and its menu. Returns true when Custom… asks for the Color+/// Picker ([`pick_custom_color`], which needs the app).+pub fn options_button(s: &mut CropShield, ui: &mut egui::Ui) -> bool {+ let mut pick = false;+ let r = crate::icons::button(ui, "settings", 24.0, false, tl!("Set additional Crop options"));+ egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ ui.set_min_width(240.0);+ ui.set_max_width(300.0);+ ui.horizontal(|ui| {+ crate::widgets::checkbox(ui, &mut s.show_cropped_area, tl!("Show Cropped Area"));+ ui.weak(crate::shortcuts::pretty("H"));+ });+ ui.separator();+ crate::widgets::checkbox(ui, &mut s.enabled, tl!("Enable Crop Shield"));+ ui.add_enabled_ui(s.enabled, |ui| {+ ui.indent("crop-shield", |ui| {+ ui.horizontal(|ui| {+ ui.label(tl!("Color:"));+ ui.radio_value(&mut s.color, ShieldColor::MatchCanvas, tl!("Match Canvas"));+ if ui.radio(s.color == ShieldColor::Custom, tl!("Custom…")).clicked() {+ s.color = ShieldColor::Custom;+ pick = true;+ }+ if s.color == ShieldColor::Custom {+ let [r, g, b] = s.custom_color;+ if crate::widgets::color_swatch_button(ui, Color32::from_rgb(r, g, b), tl!("Crop Shield color")).clicked() {+ pick = true;+ }+ }+ });+ if !s.opacity.is_finite() {+ s.opacity = DEFAULT_OPACITY;+ }+ crate::widgets::slider_row(ui, tl!("Opacity:"), &mut s.opacity, 0.0..=100.0, "%", None);+ crate::widgets::checkbox(ui, &mut s.auto_adjust, tl!("Auto Adjust Opacity"));+ });+ });+ });+ pick+}++/// Custom…: PhotoCraft's Color Picker on the custom shield colour; OK sets it+/// (`color_picker_ui::confirm`, target `cropShield`).+pub fn pick_custom_color(app: &mut PhotocraftApp) -> u64 {+ let rgb = app.ui.tool_options.crop_shield.custom_color.map(|v| v as f32 / 255.0);+ crate::color_picker_ui::open_for_target(app, "cropShield", "Color Picker (Crop Shield Color)", rgb)+}++/// The Color Picker's OK for the custom shield colour (`"#rrggbb"`).+pub fn set_custom_color(app: &mut PhotocraftApp, hex: &str) -> Result<(), String> {+ let rgb = crate::color_picker_ui::parse_hex(hex).ok_or_else(|| format!("not a colour: {hex}"))?;+ let s = &mut app.ui.tool_options.crop_shield;+ s.custom_color = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);+ s.color = ShieldColor::Custom;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ const CANVAS: Color32 = Color32::from_rgb(40, 40, 40);++ #[test]+ fn defaults_match_photoshop() {+ let s = CropShield::default();+ assert!(s.show_cropped_area && s.enabled && s.auto_adjust);+ assert_eq!((s.color, s.opacity), (ShieldColor::MatchCanvas, 75.0));+ assert_eq!(fill(&s, CANVAS, false), Some(Color32::from_rgba_unmultiplied(40, 40, 40, 191)));+ }++ #[test]+ fn auto_adjust_lightens_the_shield_while_dragging() {+ let mut s = CropShield::default();+ let still = fill(&s, CANVAS, false).unwrap();+ let dragging = fill(&s, CANVAS, true).unwrap();+ assert!(dragging.a() < still.a(), "{dragging:?} {still:?}");+ assert_eq!(dragging.to_srgba_unmultiplied()[3], 96);+ s.auto_adjust = false;+ assert_eq!(fill(&s, CANVAS, true), Some(still), "without Auto Adjust the opacity holds");+ }++ #[test]+ fn a_disabled_shield_leaves_the_outside_undimmed() {+ let s = CropShield { enabled: false, ..Default::default() };+ assert_eq!(fill(&s, CANVAS, false), None);+ assert_eq!(fill(&s, CANVAS, true), None);+ let s = CropShield { opacity: 0.0, ..Default::default() };+ assert_eq!(fill(&s, CANVAS, false), None, "0 % draws nothing");+ }++ #[test]+ fn custom_colour_and_match_canvas() {+ let s = CropShield { color: ShieldColor::Custom, custom_color: [200, 10, 30], opacity: 100.0, ..Default::default() };+ assert_eq!(fill(&s, CANVAS, false), Some(Color32::from_rgb(200, 10, 30)));+ let s = CropShield { opacity: 100.0, ..Default::default() };+ assert_eq!(fill(&s, Color32::from_rgb(184, 184, 184), false), Some(Color32::from_rgb(184, 184, 184)));+ }++ #[test]+ fn hidden_cropped_area_is_opaque_canvas_whatever_the_shield() {+ for enabled in [true, false] {+ let s =+ CropShield { show_cropped_area: false, enabled, color: ShieldColor::Custom, custom_color: [255, 0, 0], opacity: 10.0, ..Default::default() };+ assert_eq!(fill(&s, CANVAS, false), Some(CANVAS));+ assert_eq!(fill(&s, CANVAS, true), Some(CANVAS));+ }+ }++ #[test]+ fn stray_opacities_are_clamped() {+ for (o, want) in [(f32::NAN, 0.75), (f32::INFINITY, 0.75), (f32::NEG_INFINITY, 0.75), (-20.0, 0.0), (250.0, 1.0), (40.0, 0.4)] {+ let s = CropShield { opacity: o, ..Default::default() };+ assert!((s.opacity() - want).abs() < 1e-6, "{o}");+ assert_eq!(fill(&s, CANVAS, false).map_or(0, |c| c.to_srgba_unmultiplied()[3]), (want * 255.0f32).round() as u8, "{o}");+ }+ // From JSON: out-of-range numbers load and are clamped when drawn.+ let s: CropShield = serde_json::from_str(r#"{"opacity": 1e9}"#).unwrap();+ assert_eq!(s.opacity(), 1.0);+ assert!(serde_json::from_str::<CropShield>(r#"{"opacity": "high"}"#).is_err());+ }++ #[test]+ fn older_settings_without_the_shield_get_the_defaults() {+ let o: crate::state::ToolOptions = serde_json::from_str(r#"{"crop_delete": false}"#).unwrap();+ assert_eq!(o.crop_shield, CropShield::default());+ assert!(!o.crop_delete);+ let s: CropShield = serde_json::from_str(r#"{"enabled": false}"#).unwrap();+ assert_eq!(s, CropShield { enabled: false, ..Default::default() });+ let back: CropShield = serde_json::from_value(serde_json::to_value(&s).unwrap()).unwrap();+ assert_eq!(back, s);+ assert_eq!(serde_json::to_value(ShieldColor::MatchCanvas).unwrap(), "matchCanvas");+ }++ fn press_h(app: &mut PhotocraftApp) {+ let ctx = egui::Context::default();+ ctx.input_mut(|i| i.events.push(egui::Event::Key { key: Key::H, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }));+ crate::shortcuts::handle(app, &ctx);+ }++ fn crop_app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({"width": 200, "height": 120})).unwrap();+ app.ui.tool = Tool::Crop;+ crate::crop_ui::ensure_frame(&mut app);+ assert!(app.ui.crop_rect.is_some());+ app+ }++ #[test]+ fn h_toggles_show_cropped_area_while_the_crop_tool_shows_a_box() {+ let mut app = crop_app();+ assert!(!hides_outside(&app));+ press_h(&mut app);+ assert_eq!(app.ui.tool, Tool::Crop, "H doesn't switch to the Hand tool");+ assert!(!app.ui.tool_options.crop_shield.show_cropped_area);+ assert!(hides_outside(&app));+ press_h(&mut app);+ assert!(app.ui.tool_options.crop_shield.show_cropped_area);+ }++ #[test]+ fn h_stays_the_hand_key_without_a_crop_box() {+ // No document: no box, so H picks the Hand tool.+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.ui.tool = Tool::Crop;+ press_h(&mut app);+ assert_eq!(app.ui.tool, Tool::Hand);+ assert!(app.ui.tool_options.crop_shield.show_cropped_area);+ // Another tool.+ let mut app = crop_app();+ app.ui.tool = Tool::Brush;+ press_h(&mut app);+ assert_eq!(app.ui.tool, Tool::Hand);+ assert!(app.ui.tool_options.crop_shield.show_cropped_area);+ // A crop drag in progress.+ let mut app = crop_app();+ app.crop.drag = Some(crate::crop_ui::CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] });+ let ctx = egui::Context::default();+ ctx.input_mut(|i| i.events.push(egui::Event::Key { key: Key::H, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }));+ assert!(!keys(&mut app, &ctx));+ assert!(app.ui.tool_options.crop_shield.show_cropped_area);+ }++ #[test]+ fn the_color_picker_sets_the_custom_colour() {+ let mut app = crop_app();+ let id = pick_custom_color(&mut app);+ let f = app.ui.dialog_mut(id).map(|d| d.fields.clone()).unwrap();+ let mut f = f;+ f.insert("color".into(), serde_json::json!("#ff8000"));+ crate::color_picker_ui::confirm(&mut app, &f).unwrap();+ let s = &app.ui.tool_options.crop_shield;+ assert_eq!((s.color, s.custom_color), (ShieldColor::Custom, [255, 128, 0]));+ assert!(set_custom_color(&mut app, "nope").is_err());+ assert_eq!(app.ui.tool_options.crop_shield.custom_color, [255, 128, 0]);+ }+}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 85adb69f4..70bd1888a 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2294,3 +2294,10 @@ fontWeight Italic KurzívaSet the overlay options for the Crop tool Nastavit volby překryvu pro nástroj OříznutíAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+klik převzalo pracovní prostředí, které pomocí Alt+tažení přesouvá okna. Nastavte jeho klávesu pro přesun oken na Super, nebo zamkněte Alt v nabídce Okno › Modifikační klávesy.Straighten the image by drawing a line on it Narovnat obraz nakreslením čáry+ Set additional Crop options Nastavit další volby oříznutí+ Show Cropped Area Zobrazit oříznutou oblast+ Enable Crop Shield Povolit stínění oříznutí+ Match Canvas Podle plátna+ Auto Adjust Opacity Automaticky upravit krytí+ Crop Shield color Barva stínění oříznutí+ Color Picker (Crop Shield Color) Výběr barvy (Barva stínění oříznutí)diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex fd02bff73..9f28f9fee 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2332,3 +2332,10 @@ fontWeight Italic KursivSet the overlay options for the Crop tool Überlagerungsoptionen für das Freistellungswerkzeug festlegenAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Der Alt-Klick ging an die Arbeitsumgebung, die Fenster mit Alt-Ziehen verschiebt. Stelle dort die Taste zum Verschieben von Fenstern auf Super oder raste Alt unter Fenster › Modifikatortasten ein.Straighten the image by drawing a line on it Bild durch Ziehen einer Linie gerade ausrichten+ Set additional Crop options Zusätzliche Freistellungsoptionen festlegen+ Show Cropped Area Freigestellten Bereich anzeigen+ Enable Crop Shield Freistellungsschutz aktivieren+ Match Canvas An Arbeitsfläche anpassen+ Auto Adjust Opacity Deckkraft automatisch anpassen+ Crop Shield color Farbe des Freistellungsschutzes+ Color Picker (Crop Shield Color) Farbwähler (Farbe des Freistellungsschutzes)diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 56b2938e5..3ce3f3068 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3403,3 +3403,10 @@ fontWeight Thin Πολύ λεπτάSet the overlay options for the Crop tool Ορισμός επιλογών επικάλυψης για το εργαλείο ΠερικοπήAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Το Alt-κλικ πήγε στο περιβάλλον εργασίας, που μετακινεί παράθυρα με Alt-σύρσιμο. Ορίστε το πλήκτρο μετακίνησης παραθύρων του σε Super ή κλειδώστε το Alt στο Παράθυρο › Πλήκτρα τροποποίησης.Straighten the image by drawing a line on it Ευθυγράμμιση της εικόνας σχεδιάζοντας μια γραμμή πάνω της+ Set additional Crop options Ορισμός πρόσθετων επιλογών περικοπής+ Show Cropped Area Εμφάνιση περιοχής περικοπής+ Enable Crop Shield Ενεργοποίηση ασπίδας περικοπής+ Match Canvas Ταίριασμα με τον καμβά+ Auto Adjust Opacity Αυτόματη προσαρμογή αδιαφάνειας+ Crop Shield color Χρώμα ασπίδας περικοπής+ Color Picker (Crop Shield Color) Επιλογέας χρώματος (Χρώμα ασπίδας περικοπής)diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex ef5fe91d5..7c06a08e2 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2362,3 +2362,10 @@ fontWeight Italic CursivaSet the overlay options for the Crop tool Definir las opciones de superposición de la herramienta RecortarAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. El Alt+clic lo recibió el escritorio, que mueve ventanas con Alt+arrastrar. Cambia su tecla para mover ventanas a Super o bloquea Alt en Ventana › Teclas modificadoras.Straighten the image by drawing a line on it Enderezar la imagen dibujando una línea en ella+ Set additional Crop options Definir opciones de recorte adicionales+ Show Cropped Area Mostrar área recortada+ Enable Crop Shield Activar escudo de recorte+ Match Canvas Igualar lienzo+ Auto Adjust Opacity Ajustar opacidad automáticamente+ Crop Shield color Color del escudo de recorte+ Color Picker (Crop Shield Color) Selector de color (Color del escudo de recorte)diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 28bf67888..7c7127fbd 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2715,3 +2715,10 @@ fontWeight Italic ItaliqueSet the overlay options for the Crop tool Définir les options de superposition de l’outil RecadrageAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-clic a été intercepté par le bureau, qui déplace les fenêtres avec Alt-glisser. Réglez sa touche de déplacement des fenêtres sur Super, ou verrouillez Alt dans Fenêtre › Touches de modification.Straighten the image by drawing a line on it Redresser l’image en traçant une ligne dessus+ Set additional Crop options Définir d’autres options de recadrage+ Show Cropped Area Afficher la zone recadrée+ Enable Crop Shield Activer le masque de recadrage+ Match Canvas Identique à la zone de travail+ Auto Adjust Opacity Réglage automatique de l’opacité+ Crop Shield color Couleur du masque de recadrage+ Color Picker (Crop Shield Color) Sélecteur de couleurs (Couleur du masque de recadrage)diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 65847f646..4ec5c0b03 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2702,3 +2702,10 @@ fontWeight Italic MiringSet the overlay options for the Crop tool Atur opsi overlay untuk alat CropAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-klik diambil oleh desktop, yang memindahkan jendela dengan Alt-seret. Atur tombol pemindah jendelanya ke Super, atau kunci Alt di Jendela › Tombol Pengubah.Straighten the image by drawing a line on it Luruskan gambar dengan menggambar garis di atasnya+ Set additional Crop options Atur opsi Crop tambahan+ Show Cropped Area Tampilkan Area yang Di-crop+ Enable Crop Shield Aktifkan Perisai Crop+ Match Canvas Sesuaikan dengan Kanvas+ Auto Adjust Opacity Sesuaikan Opasitas Otomatis+ Crop Shield color Warna perisai crop+ Color Picker (Crop Shield Color) Pemilih Warna (Warna Perisai Crop)diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex a2e30cdb0..247641894 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2363,3 +2363,10 @@ fontWeight Italic CorsivoSet the overlay options for the Crop tool Imposta le opzioni di sovrapposizione dello strumento TaglierinaAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-click è andato al desktop, che sposta le finestre con Alt-trascina. Imposta il suo tasto per spostare le finestre su Super, oppure blocca Alt in Finestra › Tasti modificatori.Straighten the image by drawing a line on it Raddrizza l’immagine tracciando una linea+ Set additional Crop options Imposta opzioni di ritaglio aggiuntive+ Show Cropped Area Mostra area ritagliata+ Enable Crop Shield Attiva schermo di ritaglio+ Match Canvas Come la tela+ Auto Adjust Opacity Regola automaticamente opacità+ Crop Shield color Colore dello schermo di ritaglio+ Color Picker (Crop Shield Color) Selettore colore (Colore dello schermo di ritaglio)diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 05538638c..48f740f30 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3318,3 +3318,10 @@ fontWeight Italic 斜体Set the overlay options for the Crop tool 切り抜きツールのオーバーレイオプションを設定Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+クリックはデスクトップに取られました(Alt+ドラッグでウィンドウを移動する設定です)。デスクトップのウィンドウ移動キーを Super に変更するか、ウィンドウ › 修飾キーで Alt を固定してください。Straighten the image by drawing a line on it 画像上に線を描いて角度を補正+ Set additional Crop options 切り抜きの追加オプションを設定+ Show Cropped Area 切り抜かれた領域を表示+ Enable Crop Shield 切り抜きシールドを有効にする+ Match Canvas カンバスに合わせる+ Auto Adjust Opacity 不透明度を自動調整+ Crop Shield color 切り抜きシールドのカラー+ Color Picker (Crop Shield Color) カラーピッカー(切り抜きシールドのカラー)diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex a6ab44da1..cf343007b 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2872,3 +2872,10 @@ fontWeight Italic 기울임Set the overlay options for the Crop tool 자르기 도구의 오버레이 옵션 설정Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 클릭이 데스크톱으로 전달되었습니다. 데스크톱이 Alt 드래그로 창을 이동합니다. 창 이동 키를 Super로 바꾸거나 창 › 보조 키에서 Alt를 고정하세요.Straighten the image by drawing a line on it 이미지에 선을 그려 수평 맞추기+ Set additional Crop options 추가 자르기 옵션 설정+ Show Cropped Area 잘린 영역 표시+ Enable Crop Shield 자르기 방패 사용+ Match Canvas 캔버스와 일치+ Auto Adjust Opacity 자동으로 불투명도 조정+ Crop Shield color 자르기 방패 색상+ Color Picker (Crop Shield Color) 색상 선택기 (자르기 방패 색상)diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 833efb366..afb97c92c 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3478,3 +3478,10 @@ cameraRaw Whites WittenSet the overlay options for the Crop tool Overlay-opties voor het gereedschap Uitsnijden instellenAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. De Alt-klik ging naar het bureaublad, dat vensters verplaatst met Alt-slepen. Stel daar de toets voor het verplaatsen van vensters in op Super, of vergrendel Alt via Venster › Wijzigingstoetsen.Straighten the image by drawing a line on it Recht de afbeelding uit door er een lijn op te tekenen+ Set additional Crop options Aanvullende uitsnijopties instellen+ Show Cropped Area Uitgesneden gebied tonen+ Enable Crop Shield Uitsnijscherm inschakelen+ Match Canvas Gelijk aan canvas+ Auto Adjust Opacity Dekking automatisch aanpassen+ Crop Shield color Kleur van uitsnijscherm+ Color Picker (Crop Shield Color) Kleurkiezer (kleur van uitsnijscherm)diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 215008d7c..667ecacac 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3316,3 +3316,10 @@ cameraRaw Roughness ChropowatośćSet the overlay options for the Crop tool Ustaw opcje nakładki narzędzia KadrowanieAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+kliknięcie przejęło środowisko pulpitu, które przesuwa okna przez Alt+przeciąganie. Ustaw w nim klawisz przesuwania okien na Super lub zablokuj Alt w Okno › Klawisze modyfikujące.Straighten the image by drawing a line on it Wyprostuj obraz, rysując na nim linię+ Set additional Crop options Ustaw dodatkowe opcje kadrowania+ Show Cropped Area Pokaż wykadrowany obszar+ Enable Crop Shield Włącz osłonę kadrowania+ Match Canvas Dopasuj do obszaru roboczego+ Auto Adjust Opacity Automatycznie dopasuj krycie+ Crop Shield color Kolor osłony kadrowania+ Color Picker (Crop Shield Color) Próbnik kolorów (Kolor osłony kadrowania)diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 282d74d58..fbcb12197 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2722,3 +2722,10 @@ fontWeight Italic ItálicoSet the overlay options for the Crop tool Definir as opções de sobreposição da ferramenta Corte demarcadoAlt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. O Alt-clique foi para o desktop, que move janelas com Alt-arrastar. Mude a tecla de mover janelas dele para Super ou trave o Alt em Janela › Teclas modificadoras.Straighten the image by drawing a line on it Endireitar a imagem desenhando uma linha sobre ela+ Set additional Crop options Definir opções adicionais de corte+ Show Cropped Area Mostrar área cortada+ Enable Crop Shield Ativar proteção de corte+ Match Canvas Corresponder à tela de pintura+ Auto Adjust Opacity Ajustar opacidade automaticamente+ Crop Shield color Cor da proteção de corte+ Color Picker (Crop Shield Color) Seletor de cores (Cor da proteção de corte)diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 7069ccfd4..388bbc068 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2568,3 +2568,10 @@ fontWeight Italic КурсивSet the overlay options for the Crop tool Задать параметры перекрытия для инструмента «Рамка»Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+щелчок перехватило окружение рабочего стола: оно перемещает окна через Alt+перетаскивание. Назначьте для перемещения окон клавишу Super или зафиксируйте Alt в меню Окно › Клавиши-модификаторы.Straighten the image by drawing a line on it Выровнять изображение, нарисовав на нем линию+ Set additional Crop options Задать дополнительные параметры кадрирования+ Show Cropped Area Показать отсекаемую область+ Enable Crop Shield Включить экран кадрирования+ Match Canvas Как у холста+ Auto Adjust Opacity Автоматически настраивать непрозрачность+ Crop Shield color Цвет экрана кадрирования+ Color Picker (Crop Shield Color) Палитра цветов (Цвет экрана кадрирования)diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 48803b39a..b7b199527 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3403,3 +3403,10 @@ cameraRaw Masking МаскуванняSet the overlay options for the Crop tool Задати параметри накладання для інструмента «Рамка»Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-клік перехопило робоче середовище, яке переміщує вікна через Alt-перетягування. Призначте для переміщення вікон клавішу Super або зафіксуйте Alt у меню Вікно › Клавіші-модифікатори.Straighten the image by drawing a line on it Вирівняти зображення, намалювавши на ньому лінію+ Set additional Crop options Задати додаткові параметри кадрування+ Show Cropped Area Показати відсічену область+ Enable Crop Shield Увімкнути екран кадрування+ Match Canvas Як у полотна+ Auto Adjust Opacity Автоматично налаштовувати непрозорість+ Crop Shield color Колір екрана кадрування+ Color Picker (Crop Shield Color) Вибір кольору (колір екрана кадрування)diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 51853f038..0ed80bf5b 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2302,3 +2302,10 @@ fontWeight Italic 斜体Set the overlay options for the Crop tool 设置裁剪工具的叠加选项Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 单击被桌面环境截获了,它用 Alt 拖动来移动窗口。请把桌面的窗口移动键改为 Super,或在 窗口 › 修饰键 中锁定 Alt。Straighten the image by drawing a line on it 通过在图像上画一条线来拉直图像+ Set additional Crop options 设置其他裁剪选项+ Show Cropped Area 显示裁剪区域+ Enable Crop Shield 启用裁剪屏蔽+ Match Canvas 匹配画布+ Auto Adjust Opacity 自动调整不透明度+ Crop Shield color 裁剪屏蔽颜色+ Color Picker (Crop Shield Color) 拾色器(裁剪屏蔽颜色)diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 2b2bdf4ea..5cd9837e8 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2271,3 +2271,10 @@ fontWeight Italic 斜體Set the overlay options for the Crop tool 設定裁切工具的覆蓋選項Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 按一下被桌面環境攔截了,它用 Alt 拖曳來移動視窗。請把桌面的視窗移動鍵改為 Super,或在 視窗 › 輔助鍵 中鎖定 Alt。Straighten the image by drawing a line on it 在影像上繪製一條線以拉直影像+ Set additional Crop options 設定其他裁切選項+ Show Cropped Area 顯示裁切區域+ Enable Crop Shield 啟用裁切遮蔽+ Match Canvas 符合畫布+ Auto Adjust Opacity 自動調整不透明度+ Crop Shield color 裁切遮蔽顏色+ Color Picker (Crop Shield Color) 檢色器(裁切遮蔽顏色)diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex aaf809fab..38e8de212 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -47,6 +47,7 @@ pub mod comps_ui;pub mod control;pub mod credits;pub mod crop_overlay;+pub mod crop_shield;pub mod crop_straighten;pub mod crop_ui;pub mod dialog_blend_ui;diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 609ddacf8..800399a87 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -992,7 +992,11 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}crate::crop_straighten::options_button(&mut app.crop.straighten, ui);crate::crop_overlay::options_button(o, ui);+ let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui);widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels"));+ if pick_shield_color {+ crate::crop_shield::pick_custom_color(app);+ }ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if icons::button(ui,diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex d303b0297..f2962ac9b 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -374,6 +374,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {if crate::crop_overlay::keys(app, ctx) {return;}+ // ... and H toggles Show Cropped Area.+ if crate::crop_shield::keys(app, ctx) {+ return;+ }// Single-key tools (no modifiers). D and X (`tools.defaultColors` / `tools.swapColors`) and the// brush keys [ ] ⇧[ ⇧] (`tools.decreaseBrushSize`…) are commands, dispatched above with any// Keyboard Shortcuts override.diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex e04712532..5b8e4a162 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -514,6 +514,9 @@ pub struct ToolOptions {pub crop_overlay_show: crate::crop_overlay::OverlayShow,#[serde(default)]pub crop_overlay_orientation: u8,+ /// Crop gear menu (#1919): Show Cropped Area and the crop shield. See `crop_shield`.+ #[serde(default)]+ pub crop_shield: crate::crop_shield::CropShield,/// Magic Eraser opacity % (tolerance, anti-alias, contiguous and sample-all are shared with the/// Magic Wand and Paint Bucket).pub magic_eraser_opacity: f32,@@ -644,6 +647,7 @@ impl Default for ToolOptions {crop_overlay: Default::default(),crop_overlay_show: Default::default(),crop_overlay_orientation: 0,+ crop_shield: Default::default(),magic_eraser_opacity: 100.0,bg_sampling: "continuous".into(),bg_limits: "contiguous".into(),diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 8aa60c07a..4fb0a680f 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -45,6 +45,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks.- `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`auto`: only while the crop box is dragged, Photoshop's default; `always`; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box.Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them.+- `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75) and `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged). `ui.inspect` reports it as `toolOptions.crop_shield`.- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once- The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails- Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor`diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 5c021e556..9f8dae6d8 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js|---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 14 | 48 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 7 not run, 7 not measurable yet (baseline 2026-10-05) || [File compatibility](#file-compatibility) | 4 | 12 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |-| [Tools](#tools) | 16 | 14 | 8 | |+| [Tools](#tools) | 17 | 14 | 8 | || [Workspace and UI](#workspace-and-ui) | 5 | 7 | 11 | settings that do nothing: 48 of 141 (target 0) || [Type](#type) | 0 | 3 | 6 | || [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |@@ -160,6 +160,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| TOOL-214-18 | Crop: drag outside the frame to rotate it (Shift 15 deg steps, angle readout); Enter rotates and crops in one step | done | [#1792](https://github.com/storytold/photocraft/issues/1792) | image.crop angle param (image_cmds.rs: Image Rotation > Arbitrary + crop, one undo step); crop_ui.rs turns, moves and resizes the frame along its axes (Classic Mode visuals); UiState.crop_angle || TOOL-214-19 | Crop: arrow keys nudge the crop box (Shift 10 px), X swaps portrait/landscape, W x H readout while drawing or resizing | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_ui.rs keys/nudge/swap_orientation (ahead of the selection nudge and tools.swapColors in shortcuts.rs; X also swaps the options-bar ratio) and sizing (canvas.rs draws it with the marquee readout); turned frames included || TOOL-214-21 | Crop: Straighten button in the options bar and Cmd/Ctrl-drag draw a line; the frame turns so the line ends up level (or plumb when nearer vertical), with an angle readout | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_straighten.rs: one-shot options-bar button, Cmd/Ctrl held is a temporary Straighten (ui.pointer command flag); the Ruler's straighten_angle convention; the frame is fitted to the largest of its proportions inside the image (Classic Mode); a pending edit committed by Enter |+| TOOL-214-22 | Crop gear menu: Show Cropped Area (H), Enable Crop Shield with Match Canvas / custom colour, opacity and Auto Adjust Opacity | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. No Classic Mode / Auto Center Preview (PhotoCraft is always Classic Mode) |## Workspace and UIdiff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex 80b6ee1c8..746321362 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -270,3 +270,10 @@ target = "Crop: Straighten button in the options bar and Cmd/Ctrl-drag draw a listatus = "done"issue = 1919note = "crop_straighten.rs: one-shot options-bar button, Cmd/Ctrl held is a temporary Straighten (ui.pointer command flag); the Ruler's straighten_angle convention; the frame is fitted to the largest of its proportions inside the image (Classic Mode); a pending edit committed by Enter"++[[item]]+id = "TOOL-214-22"+target = "Crop gear menu: Show Cropped Area (H), Enable Crop Shield with Match Canvas / custom colour, opacity and Auto Adjust Opacity"+status = "done"+issue = 1919+note = "crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. No Classic Mode / Auto Center Preview (PhotoCraft is always Classic Mode)"