diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index cafe709769..e52343b69e 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -183,10 +183,12 @@ pub struct MenuParams { #[derive(Debug, Deserialize, JsonSchema)] pub struct UiSetParams { - /// Fields for the control method `ui.set`: tool, panels, dock, dockTabs, dockWidth, maskTarget, - /// vectorMaskTarget, selectionMode, zoom, center, fit, theme (pro, proMedium, studio, + /// Fields for the control method `ui.set`: tool, panels, dock, dockTabs, dockWidth, colorPanel + /// ({background: bool} picks which swatch the Color panel edits), maskTarget, + /// vectorMaskTarget, selectionMode, zoom, center, rotation (view angle in degrees), fit, theme (pro, proMedium, studio, /// studioLight, classic), brushSection, brushTab, brushesView, brushPicker ([x, y] opens the - /// Brush Preset picker there, null closes it), brushPickerView, brushSize. Other fields are an + /// Brush Preset picker there, null closes it), brushPickerView, brushSize, gradientBlendMode + /// (a blend mode name, for the Gradient tool), gradientClassic (bool). Other fields are an /// error. pub fields: Value, } diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index ccd9b9221b..f3effb0359 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -202,6 +202,37 @@ async fn command_ids_in_tool_schemas_exist() { client.cancel().await.unwrap(); } +/// `UI_SET_FIELDS` in `crates/ui-egui/src/control.rs`, read from source. The desktop shell owns the +/// list; this crate describes it over MCP without depending on the UI crate (both are L6). +/// Anchored on the declaration, not on the doc comment that mentions it first, and checked against +/// the declared array length so a mis-parse fails loudly instead of testing the wrong names. +fn ui_set_fields() -> Vec { + let src = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../ui-egui/src/control.rs")).expect("ui-egui control.rs"); + let (_, rest) = src.split_once("UI_SET_FIELDS: [&str; ").expect("UI_SET_FIELDS is declared"); + let declared: usize = rest.split_once(']').expect("declared length").0.parse().expect("declared length"); + let body = rest.split_once('[').expect("field array").1.split_once("];").expect("terminated array").0; + let fields: Vec = body.split('"').skip(1).step_by(2).map(str::to_string).collect(); + assert_eq!(fields.len(), declared, "parsed {fields:?} from UI_SET_FIELDS; its source shape changed"); + fields +} + +/// #1548: `ui_set` must name every field `ui.set` accepts. An agent copies this list out of +/// `tools/list`, and it ends "Other fields are an error", so an omission reads as a rejection of +/// a field that in fact works. This guards the whole list against future drift, not only the +/// three fields missing when the issue was filed. +#[tokio::test(flavor = "multi_thread")] +async fn ui_set_description_names_every_accepted_field() { + let client = connect(PhotocraftMcp::headless()).await; + let tools = client.list_all_tools().await.unwrap(); + let tool = tools.iter().find(|t| t.name == "ui_set").expect("ui_set tool"); + let schema = Value::Object((*tool.input_schema).clone()); + let description = schema["properties"]["fields"]["description"].as_str().expect("ui_set fields description").to_string(); + for field in ui_set_fields() { + assert!(description.contains(&field), "ui_set's description omits `{field}`, which ui.set accepts:\n{description}"); + } + client.cancel().await.unwrap(); +} + #[tokio::test(flavor = "multi_thread")] async fn errors_are_tool_errors_not_crashes() { let client = connect(PhotocraftMcp::headless()).await; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index bba8bb344a..ab12a34d9e 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -865,7 +865,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "enhancedControls.scrubbySliderAcceleration", "enhancedControls.touchGestures", "enhancedControls.zoomWithTrackpadPinch", - "enhancedControls.rotateViewWithTrackpad", "rawDefaults.colorSpace", "rawDefaults.bitDepth", "rawDefaults.resolution", diff --git a/crates/ui-egui/examples/layout_bench.rs b/crates/ui-egui/examples/layout_bench.rs index 20d489acf9..e1b625570f 100644 --- a/crates/ui-egui/examples/layout_bench.rs +++ b/crates/ui-egui/examples/layout_bench.rs @@ -86,7 +86,7 @@ fn screen(h: &H, x: f64, y: f64) -> Pos2 { let idx = app.session.active_index().unwrap_or(0); let v = &app.ui.views[idx]; let rect = photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect); - ViewXform { rect, zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }.to_screen(x as f32, y as f32) + ViewXform { rect, zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal, rotation: v.rotation }.to_screen(x as f32, y as f32) } fn select(h: &mut H, id: LayerId) { diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rs index 7fd8351656..8e74c8e0ca 100644 --- a/crates/ui-egui/src/artboard_ui.rs +++ b/crates/ui-egui/src/artboard_ui.rs @@ -165,7 +165,7 @@ mod tests { app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap(); app.run("layer.new.artboard", json!({"rect": [60, 10, 40, 30]})).unwrap(); let doc = app.session.active().unwrap().doc.clone(); - let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, egui::vec2(100.0, 50.0)), zoom: 1.0, center: [50.0, 25.0], flip: false }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, egui::vec2(100.0, 50.0)), zoom: 1.0, center: [50.0, 25.0], flip: false, rotation: 0.0 }; let rects = pasteboard_rects(&xf, &doc); let area: f32 = rects.iter().map(|r| r.area()).sum(); // 100×50 canvas − 40×50 − 40×30 boards. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4d7c41ddab..1de6045721 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4,7 +4,7 @@ //! update only their damage rectangle (`set_partial`). The wgpu compositor (M5) will replace this //! with direct GPU rendering behind the same `CanvasCache` interface. -use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, TextureOptions, Vec2, pos2, vec2}; +use egui::{Color32, Mesh, PointerButton, Pos2, Rect, Sense, Stroke, TextureOptions, Vec2, pos2, vec2}; use photocraft_doc::{Document, LayerContent}; use photocraft_geom::Rect as DRect; use serde_json::json; @@ -548,25 +548,68 @@ pub struct ViewXform { pub center: [f32; 2], /// View › Flip Horizontal: the view is mirrored left-right (the document is not). pub flip: bool, + /// Camera rotation in degrees around [`Self::center`]. Clockwise (Y-down) is positive; applied + /// before flip. + pub rotation: f32, } impl ViewXform { /// The main canvas's mapping for the active document as last laid out (inside the rulers). pub fn active(app: &PhotocraftApp) -> Option { let v = app.ui.views.get(app.session.active_index()?)?; - Some(Self { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }) + Some(Self { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }) } + + fn sincos(self) -> (f32, f32) { + if self.rotation.abs() < 1e-8 { + (1.0, 0.0) + } else { + let r = self.rotation.to_radians(); + (r.cos(), r.sin()) + } + } + + /// Unflip then unrotate a screen-space vector (no zoom). Hand pan and zoom-about use this. + pub fn unmap_vec(self, d: Vec2) -> Vec2 { + let d = if self.flip { vec2(-d.x, d.y) } else { d }; + let (c, s) = self.sincos(); + vec2(d.x * c + d.y * s, -d.x * s + d.y * c) + } + pub fn to_screen(&self, x: f32, y: f32) -> Pos2 { + let (c, s) = self.sincos(); + let dx = x - self.center[0]; + let dy = y - self.center[1]; + let rx = dx * c - dy * s; + let ry = dx * s + dy * c; let sx = if self.flip { -1.0 } else { 1.0 }; - self.rect.center() + vec2((x - self.center[0]) * self.zoom * sx, (y - self.center[1]) * self.zoom) + self.rect.center() + vec2(rx * self.zoom * sx, ry * self.zoom) } pub fn to_doc(&self, p: Pos2) -> [f64; 2] { let d = (p - self.rect.center()) / self.zoom; - let dx = if self.flip { -d.x } else { d.x }; - [(dx + self.center[0]) as f64, (d.y + self.center[1]) as f64] + let u = self.unmap_vec(d); + [(u.x + self.center[0]) as f64, (u.y + self.center[1]) as f64] } pub fn doc_rect(&self, r: DRect) -> Rect { - Rect::from_two_pos(self.to_screen(r.x0 as f32, r.y0 as f32), self.to_screen(r.x1 as f32, r.y1 as f32)) + let pts = [ + self.to_screen(r.x0 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y1 as f32), + self.to_screen(r.x0 as f32, r.y1 as f32), + ]; + let mut min = pts[0]; + let mut max = pts[0]; + for p in pts { + min = min.min(p); + max = max.max(p); + } + Rect::from_min_max(min, max) } } @@ -1079,11 +1122,23 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u6 Some((preview.k, key, [result.size.width, result.size.height])) } -/// The document pixels a (non-rotated) view shows, with a margin for filtering. +/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners +/// so a rotated camera still covers the visible tiles. fn visible_doc_rect(xf: &ViewXform) -> DRect { - let (a, b) = (xf.to_doc(xf.rect.min), xf.to_doc(xf.rect.max)); + let r = xf.rect; + let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } let c = |v: f64| v.clamp(-1e9, 1e9) as i32; - DRect::new(c(a[0].min(b[0]).floor()) - 2, c(a[1].min(b[1]).floor()) - 2, c(a[0].max(b[0]).ceil()) + 2, c(a[1].max(b[1]).ceil()) + 2) + DRect::new(c(x0.floor()) - 2, c(y0.floor()) - 2, c(x1.ceil()) + 2, c(y1.ceil()) + 2) } /// Zoomed-out Image › Adjustments preview on a large document: the wgpu compositor renders the @@ -1873,7 +1928,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: ctx.request_repaint(); } let flip = app.ui.view.flip_horizontal; - let xf = ViewXform { rect, zoom: view.zoom, center: view.center, flip }; + let xf = ViewXform { rect, zoom: view.zoom, center: view.center, flip, rotation: view.rotation }; let pixel_grid = app.ui.view.shows(app.ui.view.show.pixel_grid); let response = ui.allocate_rect(rect, Sense::click_and_drag()); let painter = ui.painter_at(rect); @@ -1896,8 +1951,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Preferences › Performance › Low Resolution Previews is off. let mut on_gpu = false; // A flipped view draws through the CPU path (the GPU canvas shader has no mirroring). + // Rotation stays on the GPU: it is a view uniform, not a CPU blit. + let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation); if app.gpu.is_some() - && !flip + && gpu_ok && let Some((k, key, preview_size)) = ensure_adjust_proxy(app, idx, view.zoom * ctx.pixels_per_point()) .or_else(|| ensure_filter_preview(app, idx)) .or_else(|| ensure_proxy_preview(app, idx)) @@ -1913,6 +1970,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: view.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0, view.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0, ], + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro && drop_shadow @@ -1924,7 +1982,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: hdr: hdr_preview(app, &doc), }; crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params); - } else if !flip && ensure_gpu(app, idx, visible_doc_rect(&xf)) { + } else if gpu_ok && ensure_gpu(app, idx, visible_doc_rect(&xf)) { on_gpu = true; app.perf.gpu = true; // Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs). @@ -1933,6 +1991,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: doc_size: [doc.size.width, doc.size.height], zoom: view.zoom, center: view.center, + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, shadow: { let t = crate::theme::Tokens::get(&ctx); !t.bevel && !t.pro && drop_shadow @@ -1948,25 +2007,51 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0)); } + let rotated = view.rotation.abs() > 0.05; + let size = [doc.size.width as f32, doc.size.height as f32]; match app.session.prefs().transparency_and_gamut.square() { Some(square) => { let checker_id = checker(app, &ctx); - let tiles = img_rect.size() / (2.0 * square); - painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + if rotated { + let tiles = vec2(size[0], size[1]) / (2.0 * square); + paint_mapped_image(&painter, &xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE); + } else { + let tiles = img_rect.size() / (2.0 * square); + painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + } } None => { - painter.rect_filled(img_rect, 0.0, Color32::WHITE); + if rotated { + paint_mapped_quad(&painter, &xf, size, Color32::WHITE); + } else { + painter.rect_filled(img_rect, 0.0, Color32::WHITE); + } } } if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) { - let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, img_rect, uv, Color32::WHITE); + if rotated { + paint_mapped_image(&painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE); + } else { + let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, img_rect, uv, Color32::WHITE); + } } } // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) { - let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, img_rect, uv, Color32::WHITE); + if view.rotation.abs() > 0.05 { + paint_mapped_image( + &painter, + &xf, + tex, + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + [doc.size.width as f32, doc.size.height as f32], + Color32::WHITE, + ); + } else { + let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, img_rect, uv, Color32::WHITE); + } } crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). @@ -2001,16 +2086,24 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Pixel grid at high zoom (the GPU path draws its own). if !on_gpu && pixel_grid && view.zoom > 5.0 { let vis = img_rect.intersect(rect); - let a = xf.to_doc(vis.min); - let b = xf.to_doc(vis.max); - let grid = Stroke::new(1.0, Color32::from_white_alpha(64)); - for x in (a[0].floor() as i32)..=(b[0].ceil() as i32) { - let sx = xf.to_screen(x as f32, 0.0).x; - painter.line_segment([pos2(sx, vis.top()), pos2(sx, vis.bottom())], grid); + let corners = [vis.min, pos2(vis.max.x, vis.min.y), vis.max, pos2(vis.min.x, vis.max.y)]; + let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); } - for y in (a[1].floor() as i32)..=(b[1].ceil() as i32) { - let sy = xf.to_screen(0.0, y as f32).y; - painter.line_segment([pos2(vis.left(), sy), pos2(vis.right(), sy)], grid); + let grid = Stroke::new(1.0, Color32::from_white_alpha(64)); + for x in (x0.floor() as i32)..=(x1.ceil() as i32) { + painter.line_segment([xf.to_screen(x as f32, y0 as f32), xf.to_screen(x as f32, y1 as f32)], grid); + } + for y in (y0.floor() as i32)..=(y1.ceil() as i32) { + painter.line_segment([xf.to_screen(x0 as f32, y as f32), xf.to_screen(x1 as f32, y as f32)], grid); } } @@ -2028,17 +2121,27 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Trace at display resolution over the visible part only; key by the mask's tile identity // (not the document revision) so unrelated edits don't re-trace it. let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32; - let tl = xf.to_doc(rect.min); - let br = xf.to_doc(rect.max); + let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)]; + let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } let q = 256 * step as i32; // quantise the region so small pans reuse the cache // The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document // to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there. let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; let vis = photocraft_geom::Rect::new( - px(tl[0].floor()).div_euclid(q) * q - q, - px(tl[1].floor()).div_euclid(q) * q - q, - (px(br[0].ceil()).div_euclid(q) + 2) * q, - (px(br[1].ceil()).div_euclid(q) + 2) * q, + px(x0.floor()).div_euclid(q) * q - q, + px(y0.floor()).div_euclid(q) * q - q, + (px(x1.ceil()).div_euclid(q) + 2) * q, + (px(y1.ceil()).div_euclid(q) + 2) * q, ); let key = crate::surface_fingerprint(sel) ^ (step as u64) << 56 @@ -2083,11 +2186,19 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: zoom_about(&mut view, &xf, p, nz, false); } (Some(crate::wheel_nav::Wheel::Pan(scroll)), _) => { - view.center[0] -= scroll.x / view.zoom * if flip { -1.0 } else { 1.0 }; - view.center[1] -= scroll.y / view.zoom; + let d = xf.unmap_vec(scroll) / view.zoom; + view.center[0] -= d.x; + view.center[1] -= d.y; } _ => {} } + let rotate_trackpad = app.session.prefs().enhanced_controls.rotate_view_with_trackpad; + if let Some(delta) = crate::rotate_view::trackpad_delta(&ctx, rotate_trackpad) { + let next = view.rotation + delta; + if next.is_finite() { + view.rotation = crate::rotate_view::wrap_deg(next); + } + } } // Pen pressure/tilt for this frame's tool events (mouse = 1.0), unless Preferences › Tools › @@ -2132,8 +2243,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling); let hand = app.ui.tool == Tool::Hand && !picking && !range_picking; if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) { - view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 }; - view.center[1] -= d.y / view.zoom; + let d = xf.unmap_vec(d) / view.zoom; + view.center[0] -= d.x; + view.center[1] -= d.y; ctx.set_cursor_icon(egui::CursorIcon::Grabbing); } else if free_hover && (space_pan || hand) { ctx.set_cursor_icon(egui::CursorIcon::Grab); @@ -2163,9 +2275,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } } if tool == Tool::Hand && response.dragged() { - let d = response.drag_delta(); - view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 }; - view.center[1] -= d.y / view.zoom; + let d = xf.unmap_vec(response.drag_delta()) / view.zoom; + view.center[0] -= d.x; + view.center[1] -= d.y; } else if primary { let mods = ui.input(|i| i.modifiers); // Tools follow the left button; the right one opens the Brush Preset picker or erases @@ -2239,6 +2351,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if tool == Tool::Hand { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); } + // Rotate View: drag around the view centre. Compass clicks are not a rotate drag. + let over_compass = crate::rotate_view::compass_visible(view.rotation) + && response.interact_pointer_pos().is_some_and(|p| crate::rotate_view::compass_rect(xf.rect).contains(p)); + if tool == Tool::RotateView && !over_compass && crate::rotate_view::drag(&ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { + (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); + } // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. if tool == Tool::Zoom && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); @@ -2353,7 +2471,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: zoom_about(&mut view, &xf, p, nz, center); } // A click with the (temporary) Hand does nothing, never the tool underneath. - Tool::Hand => {} + Tool::Hand | Tool::RotateView => {} // Double-clicking closes the polygonal lasso: the first click placed the last // vertex (or already closed it), so the second never starts a new polygon. egui // reports it as a triple click when a vertex went down shortly before. @@ -2507,6 +2625,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: egui::CursorIcon::Grab } } + Tool::RotateView => crate::rotate_view::cursor(response.dragged()), Tool::Zoom => { if zoom_out(alt) { egui::CursorIcon::ZoomOut @@ -2559,6 +2678,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if primary && app.ui.extras.rulers { crate::rulers::draw_rulers(app, ui, full, &xf); } + crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response); if primary { app.ui.views[idx] = view.clone(); } @@ -2575,9 +2695,28 @@ fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on view.center = [before[0] as f32, before[1] as f32]; return; } - let d = (p - xf.rect.center()) / new_zoom; - let dx = if xf.flip { -d.x } else { d.x }; - view.center = [before[0] as f32 - dx, before[1] as f32 - d.y]; + let u = xf.unmap_vec((p - xf.rect.center()) / new_zoom); + view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y]; +} + +/// Textured document quad whose corners follow [`ViewXform`] (rotation + flip). +fn paint_mapped_image(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, size: [f32; 2], tint: Color32) { + let [w, h] = size; + let pts = [xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)]; + let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)]; + let mut mesh = Mesh::with_texture(tex); + for i in 0..4 { + mesh.vertices.push(egui::epaint::Vertex { pos: pts[i], uv: uvs[i], color: tint }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, size: [f32; 2], color: Color32) { + let [w, h] = size; + let pts = vec![xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)]; + painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); } /// Draw boundary segments as marching ants: white base, black dashes phased along x + y. @@ -3842,7 +3981,7 @@ mod tests { app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); app.ui.tool = Tool::CloneStamp; app.session.tools.brush.size = 20.0; - let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0 }; let revision = app.session.active().unwrap().revision; let mut output = ctx.run_ui(Default::default(), |ui| { let ctx = ui.ctx(); @@ -3946,7 +4085,7 @@ mod tests { #[test] fn view_transform_roundtrip() { for flip in [false, true] { - let xf = ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0], flip }; + let xf = ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0], flip, rotation: 0.0 }; let s = xf.to_screen(10.0, 20.0); let d = xf.to_doc(s); assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3); @@ -4188,7 +4327,7 @@ mod tests { let ctx = ui.ctx(); let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false }; + let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false, rotation: 0.0 }; draw_drag_preview(app, &painter, &xf); }); let egui::FullOutput { mut textures_delta, shapes, .. } = out; @@ -4335,13 +4474,13 @@ mod tests { #[test] fn zoom_about_centres_the_clicked_point_with_the_preference() { let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false }; + let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0 }; let p = pos2(600.0, 200.0); let doc = xf.to_doc(p); // Off: the document point under the pointer stays under it. let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; zoom_about(&mut view, &xf, p, 2.0, false); - let after = ViewXform { rect, zoom: 2.0, center: view.center, flip: false }; + let after = ViewXform { rect, zoom: 2.0, center: view.center, flip: false, rotation: 0.0 }; let s = after.to_screen(doc[0] as f32, doc[1] as f32); assert!((s - p).length() < 0.5, "{s:?} vs {p:?}"); // On: the clicked point is the view centre. @@ -4383,7 +4522,7 @@ mod transform_controls_tests { 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 }; + 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 }; let r = transform_controls_rect(&app, &xf).expect("shape layers have transform bounds"); assert!(transform_controls_hit(r, r.right_bottom())); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e419f4cd46..2e682504ce 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -8,8 +8,7 @@ //! - `engine.commands`: list commands with enablement //! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size); the menu //! tree is `ui.menu.list` -//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, brushSize?}`: -//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushSize?}`: +//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, brushSize?}`: //! change UI state; any other field is an error ([`UI_SET_FIELDS`]) //! - `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}` //! - `ui.dialog.apply {dialog}`: commit Preferences changes without closing the dialog @@ -75,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; 21] = [ +pub const UI_SET_FIELDS: [&str; 22] = [ "tool", "panels", "dock", @@ -87,6 +86,7 @@ pub const UI_SET_FIELDS: [&str; 21] = [ "selectionMode", "zoom", "center", + "rotation", "fit", "theme", "brushSection", @@ -308,6 +308,10 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) let color_panel = whole_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?; let dock_width = num_field(p, "dockWidth")?; let zoom = num_field(p, "zoom")?; + let rotation = num_field(p, "rotation")?; + if rotation.is_some() && app.session.active_index().is_none() { + return Err("no document open".into()); + } let center = match p.get("center") { Some(v) => { let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?; @@ -426,6 +430,9 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) app.ui.views[i].fit_pending = true; app.ui.views[i].fill_pending = false; } + if let Some(r) = rotation { + app.ui.views[i].rotation = crate::rotate_view::wrap_deg(r as f32); + } } if let Some(k) = theme { app.set_theme(ctx, k); diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index d6971fe6fc..19062f3b8e 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -502,7 +502,7 @@ mod tests { fn space_on_the_canvas_moves_the_frame_not_the_view() { use egui::{Event, Key, PointerButton, pos2}; let mut a = app(SampleType::U8); - let view = crate::state::View { zoom: 2.0, center: [100.0, 50.0], fit_pending: false, fill_pending: false, doc_size: [200, 100] }; + let view = crate::state::View { zoom: 2.0, center: [100.0, 50.0], fit_pending: false, fill_pending: false, doc_size: [200, 100], rotation: 0.0 }; a.ui.views = vec![view.clone()]; let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index d6c71fc66c..defbf1e9c9 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -43,10 +43,15 @@ const FORMAT_HIGH: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; /// documents (a 14000² one would need 2.1 GB) use `Rgba8Unorm`, so they stay on the GPU like /// 8-bit ones. `PHOTOCRAFT_CANVAS_F16=0` turns the float canvas off, `=1` ignores this budget. pub const F16_BUDGET_PX: u64 = 100_000_000; -const VIEW_UNIFORM_SIZE: u64 = 112; -const VIEW_FLOATS: usize = 28; +const VIEW_UNIFORM_SIZE: u64 = 128; +const VIEW_FLOATS: usize = 32; const TILE_UNIFORM_SIZE: u64 = 16; +/// Whether this view can use the GPU canvas. Flip is still a CPU blit; rotation is a shader uniform. +pub fn gpu_view_ok(flip: bool, _rotation: f32) -> bool { + !flip +} + /// Parameters for drawing one document view. Positions are in egui points. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ViewParams { @@ -58,6 +63,9 @@ pub struct ViewParams { pub zoom: f32, /// Document point shown at the centre of the canvas rect. pub center: [f32; 2], + /// Camera rotation in radians, clockwise in Y-down screen space. Rotate around [`Self::center`] + /// before sampling. Flip stays on the CPU path. + pub rotation: f32, /// Draw the drop shadow on the pasteboard. pub shadow: bool, /// Draw the pixel grid at high zoom. @@ -1580,6 +1588,40 @@ fn filter_mode(scale: f32) -> (f32, f32) { } } +fn map_doc_px(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, x: f32, y: f32) -> [f32; 2] { + let dx = x - center[0]; + let dy = y - center[1]; + let rx = dx * cos - dy * sin; + let ry = dx * sin + dy * cos; + [origin[0] + center[0] * scale + rx * scale, origin[1] + center[1] * scale + ry * scale] +} + +fn tile_screen_aabb(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, tile: [f32; 4]) -> (f32, f32, f32, f32) { + let [tx, ty, tw, th] = tile; + if sin.abs() < 1e-8 && (cos - 1.0).abs() < 1e-8 { + let x0 = origin[0] + tx * scale; + let y0 = origin[1] + ty * scale; + return (x0, y0, x0 + tw * scale, y0 + th * scale); + } + let pts = [ + map_doc_px(origin, scale, center, cos, sin, tx, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty + th), + map_doc_px(origin, scale, center, cos, sin, tx, ty + th), + ]; + let mut x0 = pts[0][0]; + let mut y0 = pts[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for p in pts { + x0 = x0.min(p[0]); + y0 = y0.min(p[1]); + x1 = x1.max(p[0]); + y1 = y1.max(p[1]); + } + (x0, y0, x1, y1) +} + impl CanvasCallback { /// Screen-pixel origin of document (0, 0) (snapped to whole pixels) and device px per doc px. fn placement(&self, ppp: f32) -> ([f32; 2], f32) { @@ -1633,6 +1675,16 @@ impl CanvasCallback { g[1], g[2], inv_gamma, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 1.0 } else { r.cos() } + }, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 0.0 } else { r.sin() } + }, + p.center[0], + p.center[1], ] } } @@ -1702,12 +1754,14 @@ impl CallbackTrait for CanvasCallback { let (origin, scale) = self.placement(info.pixels_per_point); let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32); let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32); + let rot = if self.params.rotation.is_finite() { self.params.rotation } else { 0.0 }; + let (cos, sin) = if rot.abs() < 1e-8 { (1.0, 0.0) } else { (rot.cos(), rot.sin()) }; + let cen = self.params.center; pass.set_pipeline(&res.tile_pipeline); pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]); for t in &doc.tiles { let [tx, ty, tw, th] = t.rect.map(|v| v as f32); - let (x0, y0) = (origin[0] + tx * scale, origin[1] + ty * scale); - let (x1, y1) = (x0 + tw * scale, y0 + th * scale); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, cen, cos, sin, [tx, ty, tw, th]); if x1 < cx0 || y1 < cy0 || x0 > cx1 || y0 > cy1 { continue; } @@ -1726,6 +1780,7 @@ struct View { e: vec4, // checker light rgb, gamut warning opacity f: vec4, // checker dark rgb, 32-bit preview gain (2^exposure; 0 = off) g: vec4, // gamut warning rgb, 32-bit preview 1 / gamma + h: vec4, // cos, sin, center_doc_x, center_doc_y }; struct Tile { r: vec4 }; // x, y, w, h in doc px @@ -1747,6 +1802,23 @@ fn px_to_clip(p: vec2) -> vec4 { return vec4(n.x, -n.y, 0.0, 1.0); } +fn screen_center() -> vec2 { + return view.b.xy + view.h.zw * view.a.z; +} + +fn doc_to_px(d: vec2) -> vec2 { + let cs = view.h.xy; + let q = d - view.h.zw; + let r = vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); + return screen_center() + r * view.a.z; +} + +fn px_to_doc(p: vec2) -> vec2 { + let cs = view.h.xy; + let q = (p - screen_center()) / view.a.z; + return vec2(q.x * cs.x + q.y * cs.y, -q.x * cs.y + q.y * cs.x) + view.h.zw; +} + fn doc_min() -> vec2 { return view.b.xy; } fn doc_max() -> vec2 { return view.b.xy + view.b.zw * view.a.z; } @@ -1781,21 +1853,29 @@ fn box_blur(p: vec2, lo: vec2, hi: vec2, sigma: f32) -> f32 { @vertex fn vs_shadow(@builtin(vertex_index) vi: u32) -> VOut { let pad = 64.0 * view.a.w; - let p = mix(doc_min() - vec2(pad), doc_max() + vec2(pad), corner(vi)); + let c0 = doc_to_px(vec2(0.0, 0.0)); + let c1 = doc_to_px(vec2(view.b.z, 0.0)); + let c2 = doc_to_px(vec2(view.b.z, view.b.w)); + let c3 = doc_to_px(vec2(0.0, view.b.w)); + let lo = min(min(c0, c1), min(c2, c3)) - vec2(pad); + let hi = max(max(c0, c1), max(c2, c3)) + vec2(pad); + let p = mix(lo, hi, corner(vi)); return VOut(px_to_clip(p)); } @fragment fn fs_shadow(in: VOut) -> @location(0) vec4 { let p = in.pos.xy; - let lo = doc_min(); - let hi = doc_max(); - if (all(p >= lo) && all(p < hi)) { + let d = px_to_doc(p); + if (all(d >= vec2(0.0)) && all(d < view.b.zw)) { discard; } + let p_align = view.b.xy + d * view.a.z; + let lo = doc_min(); + let hi = doc_max(); let u = view.a.w; - let ambient = box_blur(p - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40; - let contact = box_blur(p - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30; + let ambient = box_blur(p_align - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40; + let contact = box_blur(p_align - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30; let a = 1.0 - (1.0 - ambient) * (1.0 - contact); return vec4(0.0, 0.0, 0.0, a); } @@ -1804,7 +1884,7 @@ fn fs_shadow(in: VOut) -> @location(0) vec4 { @vertex fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut { - let p = view.b.xy + (tile.r.xy + tile.r.zw * corner(vi)) * view.a.z; + let p = doc_to_px(tile.r.xy + tile.r.zw * corner(vi)); return VOut(px_to_clip(p)); } @@ -1814,7 +1894,8 @@ fn checker(p: vec2) -> vec3 { if (view.c.w <= 0.0) { return vec3(1.0); } - let c = floor((p - view.b.xy) / view.c.w); + let d = px_to_doc(p); + let c = floor(d * view.a.z / view.c.w); let odd = fract((c.x + c.y) * 0.5) > 0.25; return select(view.e.xyz, view.f.xyz, odd); } @@ -1823,7 +1904,7 @@ fn checker(p: vec2) -> vec3 { fn fs_tile(in: VOut) -> @location(0) vec4 { let p = in.pos.xy; let scale = view.a.z; - let d = (p - view.b.xy) / scale; // document pixel coordinates + let d = px_to_doc(p); // document pixel coordinates let size = tile.r.zw; let t = d - tile.r.xy; // texel coordinates within this tile let mode = view.c.x; @@ -1944,6 +2025,25 @@ mod tests { assert!(physical_memory().is_none_or(|b| b >= 256 << 20)); } + #[test] + fn view_uniform_packs_rotation() { + assert_eq!(VIEW_FLOATS, 32); + assert_eq!(VIEW_UNIFORM_SIZE, 128); + assert_eq!(VIEW_FLOATS * 4, VIEW_UNIFORM_SIZE as usize); + assert!(gpu_view_ok(false, 0.0)); + assert!(gpu_view_ok(false, 45.0_f32.to_radians())); + assert!(!gpu_view_ok(true, 45.0_f32.to_radians())); + // Identity packing: rotation 0 matches the unrotated origin + scale map. + let origin = [10.0, 20.0]; + let (scale, center) = (2.0, [40.0, 8.0]); + let a = map_doc_px(origin, scale, center, 1.0, 0.0, 5.0, 9.0); + assert!((a[0] - (origin[0] + 5.0 * scale)).abs() < 1e-4); + assert!((a[1] - (origin[1] + 9.0 * scale)).abs() < 1e-4); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, center, 1.0, 0.0, [0.0, 0.0, 10.0, 4.0]); + assert!((x0 - origin[0]).abs() < 1e-4 && (y0 - origin[1]).abs() < 1e-4); + assert!((x1 - (origin[0] + 20.0)).abs() < 1e-4 && (y1 - (origin[1] + 8.0)).abs() < 1e-4); + } + #[test] fn filter_modes() { assert_eq!(filter_mode(0.25), (0.0, 2.0)); diff --git a/crates/ui-egui/src/hold_keys/tests.rs b/crates/ui-egui/src/hold_keys/tests.rs index aed70a41a7..26e573b845 100644 --- a/crates/ui-egui/src/hold_keys/tests.rs +++ b/crates/ui-egui/src/hold_keys/tests.rs @@ -40,7 +40,13 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }; xf.to_screen(x, y) } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 52cb21ce27..5b9feab5c3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2241,3 +2241,7 @@ fontWeight Italic Kurzíva Pattern Stamp Tool Nástroj razítko vzorku Pattern Stamp Razítko vzorku Impressionist Impresionista + Rotate View Otočit zobrazení + Rotate View Tool Nástroj otočení zobrazení + Reset View Obnovit zobrazení + Drag around the centre to rotate the view · Shift constrains to 15° Tažením kolem středu otočíte zobrazení · Shift omezí na 15° diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 15aacf45e4..1d336fd211 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2280,3 +2280,7 @@ fontWeight Italic Kursiv Pattern Stamp Tool Musterstempel-Werkzeug Pattern Stamp Musterstempel Impressionist Impressionistisch + Rotate View Ansicht drehen + Rotate View Tool Ansicht drehen-Werkzeug + Reset View Ansicht zurücksetzen + Drag around the centre to rotate the view · Shift constrains to 15° Ziehen Sie um die Mitte, um die Ansicht zu drehen · Umschalt rastet auf 15° ein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 370322868f..38ee0c14d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2199,6 +2199,7 @@ Down Κάτω Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Σύρετε για λάσο ή κάντε κλικ για πολυγωνική επιλογή · {add} προσθήκη · {sub} αφαίρεση Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · {commit} commits · Esc cancels Σύρετε για περιοχή περικοπής · σύρετε στο εσωτερικό για μετακίνηση · από τα άκρα αλλάζει μέγεθος ({ratio} αναλογία, {centre} κέντρο) · Space για μετακίνηση κατά τη σχεδίαση · {commit} εφαρμογή · Esc ακύρωση + Drag around the centre to rotate the view · Shift constrains to 15° Σύρετε γύρω από το κέντρο για να περιστρέψετε την προβολή · Shift περιορίζει στις 15° Drag on the image to add a constraint; Shift for horizontal/vertical; right-click to delete. Σύρετε πάνω στην εικόνα για προσθήκη περιορισμού· Shift για οριζόντιο/κατακόρυφο· δεξί κλικ για διαγραφή. Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Σύρετε ή κάντε κλικ για πολυγωνικά σημεία · κρατήστε Alt κατά το λάσο για ευθείες · {add} προσθήκη · {sub} αφαίρεση πριν από τη σχεδίαση Drag to draw a gradient Σύρετε για να σχεδιάσετε διαβάθμιση @@ -2780,6 +2781,7 @@ Reset GPU Backend Επαναφορά συστήματος απόδοσης GPU Reset Section Επαναφορά ενότητας Reset Transform Επαναφορά μετασχηματισμού + Reset View Επαναφορά προβολής Reset Workspace Επαναφορά χώρου εργασίας Reset to defaults Επαναφορά προεπιλογών Resize image during place Αλλαγή μεγέθους εικόνας κατά την τοποθέτηση @@ -2802,6 +2804,8 @@ Roman Hanging Punctuation Κρεμαστή στίξη όρθιας γραφής Rotate Auto Αυτόματη περιστροφή Rotate Fixed Σταθερή περιστροφή + Rotate View Περιστροφή προβολής + Rotate View Tool Εργαλείο περιστροφής προβολής Rotate view with trackpad Περιστροφή προβολής με επιφάνεια αφής Rotate: Περιστροφή: Rough Pastels Τραχιά παστέλ diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2661b96f3c..f9e7c1b07f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2310,3 +2310,7 @@ fontWeight Italic Cursiva Pattern Stamp Tool Herramienta Sello de motivo Pattern Stamp Sello de motivo Impressionist Impresionista + Rotate View Rotar vista + Rotate View Tool Herramienta Rotar vista + Reset View Restablecer vista + Drag around the centre to rotate the view · Shift constrains to 15° Arrastre alrededor del centro para rotar la vista · Mayús fija a 15° diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e0dcbca668..8e683c025f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2665,3 +2665,6 @@ fontWeight Italic Italique # Pattern Stamp tool Pattern Stamp Tool Outil Tampon de motif Impressionist Impressionniste + Rotate View Tool Outil Rotation de la vue + Reset View Réinitialiser la vue + Drag around the centre to rotate the view · Shift constrains to 15° Faites glisser autour du centre pour tourner la vue · Maj contraint à 15° diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f415e69aa6..101e242306 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2652,3 +2652,6 @@ fontWeight Italic Miring # Pattern Stamp tool Pattern Stamp Tool Alat Stempel Pola Impressionist Impresionis + Rotate View Tool Alat Putar Tampilan + Reset View Atur Ulang Tampilan + Drag around the centre to rotate the view · Shift constrains to 15° Seret di sekitar pusat untuk memutar tampilan · Shift membatasi ke 15° diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7257394cc3..d1da7e0788 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2311,4 +2311,7 @@ fontWeight Italic Corsivo Pattern Stamp Tool Strumento Timbro motivo Pattern Stamp Timbro motivo Impressionist Impressionista - + Rotate View Ruota vista + Rotate View Tool Strumento Ruota vista + Reset View Reimposta vista + Drag around the centre to rotate the view · Shift constrains to 15° Trascina intorno al centro per ruotare la vista · Maiusc vincola a 15° diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dd73d83c4c..1e1bfda882 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2224,3 +2224,7 @@ fontWeight Italic 斜体 Pattern Stamp Tool パターンスタンプツール Pattern Stamp パターンスタンプ Impressionist 印象派 + Rotate View 表示を回転 + Rotate View Tool 表示回転ツール + Reset View 表示をリセット + Drag around the centre to rotate the view · Shift constrains to 15° 中心の周りをドラッグして表示を回転 · Shift で 15° 単位 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b56cbe74e0..c61d036051 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2820,3 +2820,7 @@ fontWeight Italic 기울임 Pattern Stamp Tool 패턴 스탬프 도구 Pattern Stamp 패턴 스탬프 Impressionist 인상파 + Rotate View 보기 회전 + Rotate View Tool 보기 회전 도구 + Reset View 보기 재설정 + Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기를 회전합니다 · Shift는 15°로 제한 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index cfd51513ea..f12906d1f5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3266,3 +3266,6 @@ cameraRaw Roughness Chropowatość # Pattern Stamp tool Pattern Stamp Tool Narzędzie Pieczątka wzoru Impressionist Impresjonistyczny + Rotate View Tool Narzędzie Obróć widok + Reset View Resetuj widok + Drag around the centre to rotate the view · Shift constrains to 15° Przeciągnij wokół środka, aby obrócić widok · Shift ogranicza do 15° diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00bb7b3a01..9dfb1cbcd8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2672,3 +2672,6 @@ fontWeight Italic Itálico # Pattern Stamp tool Pattern Stamp Tool Ferramenta Carimbo de padrão Impressionist Impressionista + Rotate View Tool Ferramenta Girar visualização + Reset View Redefinir visualização + Drag around the centre to rotate the view · Shift constrains to 15° Arraste ao redor do centro para girar a visualização · Shift restringe a 15° diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 425f14da54..b91748719f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2513,3 +2513,6 @@ fontWeight Italic Курсив # Pattern Stamp tool Pattern Stamp Tool Инструмент узорный штамп Impressionist Импрессионист + Rotate View Tool Инструмент поворота вида + Reset View Сбросить вид + Drag around the centre to rotate the view · Shift constrains to 15° Перетащите вокруг центра, чтобы повернуть вид · Shift фиксирует шаг 15° diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e3c5092727..6f3718676f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2249,3 +2249,7 @@ fontWeight Italic 斜体 Pattern Stamp Tool 图案图章工具 Pattern Stamp 图案图章 Impressionist 印象派 + Rotate View 旋转视图 + Rotate View Tool 旋转视图工具 + Reset View 重置视图 + Drag around the centre to rotate the view · Shift constrains to 15° 绕中心拖动以旋转视图 · Shift 限制为 15° diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4b7741ad20..edae3d5ffb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2218,3 +2218,7 @@ fontWeight Italic 斜體 Pattern Stamp Tool 圖案圖章工具 Pattern Stamp 圖案圖章 Impressionist 印象派 + Rotate View 旋轉檢視 + Rotate View Tool 旋轉檢視工具 + Reset View 重設檢視 + Drag around the centre to rotate the view · Shift constrains to 15° 繞中心拖曳以旋轉檢視 · Shift 限制為 15° diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index d911087712..10faa4058c 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -83,6 +83,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::PaintBucket => "paint-bucket", Tool::Type | Tool::VerticalType => "type", Tool::Hand => "hand", + Tool::RotateView => "compass", Tool::Zoom => "zoom-in", Tool::SpotHealing | Tool::Healing => "bandage", Tool::Patch => "lasso-select", diff --git a/crates/ui-egui/src/lasso_ui/tests.rs b/crates/ui-egui/src/lasso_ui/tests.rs index 0e2d03f4af..e76355b56f 100644 --- a/crates/ui-egui/src/lasso_ui/tests.rs +++ b/crates/ui-egui/src/lasso_ui/tests.rs @@ -153,7 +153,7 @@ fn harness() -> egui_kittest::Harness<'static, PhotocraftApp> { fn mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f32, y: f32, mods: Modifiers) { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: false }; + let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: false, rotation: v.rotation }; let pos = xf.to_screen(x, y); h.event(Event::ModifiersChanged(mods)); h.event(Event::PointerMoved(pos)); @@ -265,7 +265,7 @@ fn real_canvas_backspace_and_right_click_retract_polygonal_points() { let state = h.state(); let view = &state.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(state, state.last_canvas_rect), zoom: view.zoom, center: view.center, flip: false }; + let xf = ViewXform { rect: crate::rulers::content_rect(state, state.last_canvas_rect), zoom: view.zoom, center: view.center, flip: false, rotation: 0.0 }; let pos = xf.to_screen(155.0, 100.0); h.event(Event::PointerMoved(pos)); h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::ALT }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9ee5681d62..fe439ec477 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -111,6 +111,7 @@ pub mod quick_pick; pub mod rasterize_prompt; pub mod retouch_ui; mod rgb_histogram; +pub mod rotate_view; pub mod rulers; pub mod screen_picker; pub mod scrollbars; diff --git a/crates/ui-egui/src/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/magnetic_lasso_ui/tests.rs index f1393a0786..9aec5110b2 100644 --- a/crates/ui-egui/src/magnetic_lasso_ui/tests.rs +++ b/crates/ui-egui/src/magnetic_lasso_ui/tests.rs @@ -310,7 +310,13 @@ fn harness() -> Harness<'static, PhotocraftApp> { fn screen(h: &Harness<'static, PhotocraftApp>, x: f64, y: f64) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }; xf.to_screen(x as f32, y as f32) } diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index b3dc81c4a0..0a0c4a003e 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -43,7 +43,13 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }; xf.to_screen(x, y) } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9ee9cfd1d8..01fad74b19 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -37,6 +37,8 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")), ("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")), ("view.actualPixels", "100%", &["View"], Some("Cmd+1")), + ("view.rotateView", "Rotate View", &[], None), + ("view.resetView", "Reset View", &["View"], None), ("window.newWindowForDocument", "New Window for Document", &["Window", "Arrange"], None), ("window.toggle.layers", "Layers", &["Window"], Some("F7")), ("window.toggle.history", "History", &["Window"], None), @@ -670,7 +672,8 @@ pub fn is_live(id: &str) -> bool { } /// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`. -const PLACE_AFTER: &[(&str, &str)] = &[("file.newFromClipboard", "file.new"), ("filter.render.relight", "filter.render.lightingEffects")]; +const PLACE_AFTER: &[(&str, &str)] = + &[("file.newFromClipboard", "file.new"), ("filter.render.relight", "filter.render.lightingEffects"), ("view.resetView", "view.flipHorizontal")]; pub fn menu_items(app: &PhotocraftApp) -> Vec { // 1) Photoshop's full menu tree, in Photoshop order; live where we implement the command. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 3a72f74b93..d5674ad5eb 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -39,7 +39,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::PathSelection, Tool::DirectSelection], &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape], ], - &[&[Tool::Hand], &[Tool::Zoom]], + &[&[Tool::Hand, Tool::RotateView], &[Tool::Zoom]], ]; /// The tool a slot shows: the current tool if it belongs to the slot, else the last one used. @@ -897,6 +897,23 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.views[i].zoom = 1.0; } } + Tool::RotateView => { + hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); + if let Some(i) = app.session.active_index() { + ui.label(tl!("Angle")); + let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); + if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = crate::rotate_view::wrap_deg(angle); + } + if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = 0.0; + } + } + } Tool::Hand => { hint(ui, tl!("Drag to pan · hold Space with any tool")); if widgets::secondary_button(ui, "100%", 0.0).clicked() @@ -3212,6 +3229,13 @@ mod type_flyout_tests { frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); assert_eq!(app.ui.tool, Tool::PatternStamp); } + + #[test] + fn rotate_view_is_in_the_hand_flyout() { + let hand = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::Hand)).expect("Hand group"); + assert_eq!(*hand, [Tool::Hand, Tool::RotateView]); + assert_eq!(Tool::RotateView.key(), 'R'); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index f1919619c4..995f3ffc81 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -110,7 +110,7 @@ fn ctrl_alt_drag_resizes_the_pencil_without_painting() { #[test] fn square_cursor_sits_on_the_pixel_grid() { let rect = Rect::from_min_size(Pos2::new(0.0, 0.0), vec2(800.0, 600.0)); - let xf = ViewXform { rect, zoom: 8.0, center: [50.0, 37.5], flip: false }; + let xf = ViewXform { rect, zoom: 8.0, center: [50.0, 37.5], flip: false, rotation: 0.0 }; // 1 px at 800 %: the 8-point square of the pixel under the pointer. let r = pencil_cursor_rect(&xf, [10.3, 5.7], 1.0, 1.0); assert_eq!(r, Rect::from_two_pos(xf.to_screen(10.0, 5.0), xf.to_screen(11.0, 6.0))); @@ -122,7 +122,7 @@ fn square_cursor_sits_on_the_pixel_grid() { assert_eq!(r, Rect::from_two_pos(xf.to_screen(9.0, 4.0), xf.to_screen(12.0, 7.0))); // At 2× and at an odd zoom the edges land on physical pixels. for (zoom, ppp) in [(3.3, 2.0), (0.5, 2.0), (1.0, 1.0), (13.7, 1.5)] { - let xf = ViewXform { rect: Rect::from_min_size(Pos2::new(0.3, 0.7), vec2(800.0, 600.0)), zoom, center: [50.2, 37.9], flip: true }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::new(0.3, 0.7), vec2(800.0, 600.0)), zoom, center: [50.2, 37.9], flip: true, rotation: 0.0 }; let r = pencil_cursor_rect(&xf, [20.4, 30.6], 5.0, ppp); for v in [r.min.x, r.min.y, r.max.x, r.max.y] { assert!((v * ppp - (v * ppp).round()).abs() < 1e-3, "zoom {zoom} ppp {ppp}: {v}"); diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs index 62da06b563..2dbfd0605f 100644 --- a/crates/ui-egui/src/polygon_lasso_tests.rs +++ b/crates/ui-egui/src/polygon_lasso_tests.rs @@ -43,7 +43,13 @@ fn harness() -> Harness<'static, PhotocraftApp> { fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }; xf.to_screen(x, y) } diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index df3551b573..503d6985b5 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -1800,9 +1800,13 @@ mod tests { assert!(has_visible_fields(&values, "general")); assert!(has_visible_fields(&values, "fileHandling")); // Every setting of these sections is still unimplemented. - for section in ["type", "enhancedControls", "integrations", "scratchDisks"] { + for section in ["type", "integrations", "scratchDisks"] { assert!(!has_visible_fields(&values, section), "{section}"); } + // Rotate View with Trackpad is live; the other Enhanced Controls rows stay hidden. + assert!(has_visible_fields(&values, "enhancedControls")); + assert!(!prefs::is_hidden("enhancedControls.rotateViewWithTrackpad")); + assert!(prefs::is_hidden("enhancedControls.zoomWithTrackpadPinch")); // Camera Raw Defaults shows only "Open in Camera Raw" so far. assert!(has_visible_fields(&values, "rawDefaults")); assert!(!prefs::is_hidden("rawDefaults.openInCameraRaw")); diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs index 2dc7282952..6e9e61aa3b 100644 --- a/crates/ui-egui/src/preset_panels.rs +++ b/crates/ui-egui/src/preset_panels.rs @@ -475,7 +475,7 @@ fn empty(ui: &mut egui::Ui, s: &str) { fn doc_point(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> { let i = app.session.active_index()?; let v = app.ui.views.get(i)?; - let xf = crate::canvas::ViewXform { rect: app.last_canvas_rect, zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = crate::canvas::ViewXform { rect: app.last_canvas_rect, zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal, rotation: v.rotation }; Some(xf.to_doc(pos)) } diff --git a/crates/ui-egui/src/rotate_view.rs b/crates/ui-egui/src/rotate_view.rs new file mode 100644 index 0000000000..5ef742cb62 --- /dev/null +++ b/crates/ui-egui/src/rotate_view.rs @@ -0,0 +1,528 @@ +//! Rotate View tool: turn the canvas camera around its centre without rewriting pixels. +//! +//! Drag around the view centre (clockwise increases the angle). Shift snaps to 15°. Reset View, +//! Escape, a double-click, or the on-canvas compass put the angle back to 0. History is not +//! recorded. Trackpad rotate is gated by Preferences › Enhanced Controls › Rotate View with +//! Trackpad. + +use egui::{Align2, Pos2, Rect, Stroke, pos2, vec2}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::paint_mouse::Buttons; +use crate::state::View; +use crate::theme::Tokens; + +/// Snap increment, in degrees, while Shift is held. +pub const SNAP_DEG: f32 = 15.0; + +/// A Rotate View drag in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +struct RotateDrag { + /// Screen point of the view centre when the drag began. + pivot: Pos2, + /// Pointer angle, in degrees, at the press (atan2, Y-down: clockwise is positive). + start_pointer: f32, + /// View rotation, in degrees, at the press. + start_rotation: f32, +} + +fn id() -> egui::Id { + egui::Id::new("pc-rotate-view-drag") +} + +fn compass_id() -> egui::Id { + egui::Id::new("pc-rotate-view-compass") +} + +/// Wrap `a` degrees into (−180, 180]. Non-finite values become 0 so a hostile angle never +/// propagates into the camera. +pub fn wrap_deg(a: f32) -> f32 { + if !a.is_finite() { + return 0.0; + } + let mut x = f64::from(a) % 360.0; + if x > 180.0 { + x -= 360.0; + } else if x <= -180.0 { + x += 360.0; + } + x as f32 +} + +/// Nearest multiple of `step` degrees, wrapped. A non-positive or non-finite step is ignored. +pub fn snap_deg(a: f32, step: f32) -> f32 { + if !(step.is_finite() && step > 0.0) { + return wrap_deg(a); + } + wrap_deg((a / step).round() * step) +} + +/// Pointer angle in degrees around `pivot` (Y-down, so clockwise is positive). +pub fn pointer_deg(p: Pos2, pivot: Pos2) -> f32 { + let d = p - pivot; + if !(d.x.is_finite() && d.y.is_finite()) || d.length_sq() < 1e-8 { + return 0.0; + } + d.y.atan2(d.x).to_degrees() +} + +fn finite_number(p: &Value, key: &str) -> Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) => v.as_f64().filter(|n| n.is_finite()).map(|n| Some(n as f32)).ok_or_else(|| format!("{key} must be a finite number")), + } +} + +/// Apply `view.rotateView` params to `current`. Empty params, a non-object, or a missing +/// `angle`/`delta`/`reset` are errors (never a silent no-op). +pub fn apply_params(current: f32, p: &Value) -> Result { + let obj = p.as_object().ok_or("params must be an object")?; + for k in obj.keys() { + if !matches!(k.as_str(), "angle" | "delta" | "reset") { + return Err(format!("unknown field `{k}`")); + } + } + let reset = match obj.get("reset") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| "reset must be a boolean".to_string())?, + }; + let angle = finite_number(p, "angle")?; + let delta = finite_number(p, "delta")?; + if !reset && angle.is_none() && delta.is_none() { + return Err("expected angle, delta, or reset".into()); + } + if reset { + return Ok(0.0); + } + let mut r = angle.unwrap_or(current); + if let Some(d) = delta { + r += d; + if !r.is_finite() { + return Err("delta overflowed the angle".into()); + } + } + Ok(wrap_deg(r)) +} + +/// Trackpad rotate: `delta_rad` is egui's rotation delta (radians, same sign as [`wrap_deg`]). +/// Returns the new angle when the preference is on and the delta is a finite non-zero value. +pub fn apply_trackpad(current: f32, enabled: bool, delta_rad: f32) -> Option { + if !enabled || !delta_rad.is_finite() || delta_rad == 0.0 { + return None; + } + let deg = delta_rad.to_degrees(); + if !deg.is_finite() { + return None; + } + let next = current + deg; + if !next.is_finite() { + return None; + } + Some(wrap_deg(next)) +} + +/// This frame's trackpad rotation in degrees, if the preference is on and egui reported a delta. +pub fn trackpad_delta(ctx: &egui::Context, enabled: bool) -> Option { + if !enabled { + return None; + } + let rad = ctx.input(|i| { + let from_events: f32 = i + .events + .iter() + .filter_map(|e| match e { + egui::Event::Rotate(r) if r.is_finite() => Some(*r), + _ => None, + }) + .sum(); + if from_events != 0.0 { from_events } else { i.rotation_delta() } + }); + apply_trackpad(0.0, true, rad).filter(|_| rad != 0.0) +} + +/// `view.rotateView`: set or add degrees on the active document's camera. +pub fn command(app: &mut PhotocraftApp, p: &Value) -> Result { + let i = app.session.active_index().ok_or("no document open")?; + let current = app.ui.views.get(i).map(|v| v.rotation).ok_or("no document open")?; + let rotation = apply_params(current, p)?; + let v = app.ui.views.get_mut(i).ok_or("no document open")?; + v.rotation = rotation; + Ok(json!({"rotation": v.rotation})) +} + +/// `view.resetView`: angle 0, zoom and centre unchanged. +pub fn reset(app: &mut PhotocraftApp) -> Result { + let i = app.session.active_index().ok_or("no document open")?; + let v = app.ui.views.get_mut(i).ok_or("no document open")?; + v.rotation = 0.0; + Ok(json!({"rotation": 0.0, "zoom": v.zoom, "center": v.center})) +} + +/// Route canvas buttons for Rotate View. Returns true when the drag is owned (the canvas then +/// ignores the tool underneath). +pub fn drag(ctx: &egui::Context, view: &mut View, xf: &ViewXform, b: &Buttons, pointer: Option) -> bool { + if b.started { + let pivot = xf.rect.center(); + let origin = ctx.input(|i| i.pointer.press_origin()).filter(|p| xf.rect.contains(*p)).or(pointer); + if let Some(p) = origin { + ctx.data_mut(|d| { + d.insert_temp(id(), RotateDrag { pivot, start_pointer: pointer_deg(p, pivot), start_rotation: view.rotation }); + }); + } + } + let Some(z) = ctx.data(|d| d.get_temp::(id())) else { + return b.started || b.dragged || b.stopped; + }; + if let Some(p) = pointer.filter(|_| b.dragged || b.stopped) { + let delta = wrap_deg(pointer_deg(p, z.pivot) - z.start_pointer); + let mut angle = z.start_rotation + delta; + if !angle.is_finite() { + angle = z.start_rotation; + } + if ctx.input(|i| i.modifiers.shift) { + angle = snap_deg(angle, SNAP_DEG); + } + view.rotation = wrap_deg(angle); + } + if b.stopped { + ctx.data_mut(|d| d.remove::(id())); + } + true +} + +/// Compass in the top-right of the canvas (north = document up). Hidden at 0°. +pub fn compass_rect(canvas: Rect) -> Rect { + const S: f32 = 36.0; + const M: f32 = 10.0; + Rect::from_min_size(pos2(canvas.right() - M - S, canvas.top() + M), vec2(S, S)) +} + +/// True when the compass is showing (angle is not ~0). +pub fn compass_visible(rotation: f32) -> bool { + rotation.is_finite() && rotation.abs() > 0.05 +} + +/// Draw the compass and handle a click / Escape / double-click reset. Returns true when the +/// pointer over the compass should not start a rotate drag. +pub fn overlay(app: &PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, view: &mut View, response: &egui::Response) -> bool { + if app.ui.tool == crate::state::Tool::RotateView && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) && view.rotation != 0.0 { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + } + if app.ui.tool == crate::state::Tool::RotateView && (response.double_clicked() || response.triple_clicked()) { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + } + if !compass_visible(view.rotation) { + ctx.data_mut(|d| d.remove::(compass_id())); + return false; + } + let r = compass_rect(xf.rect); + ctx.data_mut(|d| d.insert_temp(compass_id(), r)); + let t = Tokens::get(ctx); + let hover = response.hover_pos().is_some_and(|p| r.contains(p)); + painter.circle_filled(r.center(), r.width() * 0.5, if hover { t.hover } else { t.chrome }); + painter.circle_stroke(r.center(), r.width() * 0.5 - 0.5, Stroke::new(1.0, t.separator)); + // Document up: (0, −1) in document space, rotated then flipped like [`ViewXform::to_screen`]. + let rad = view.rotation.to_radians(); + let (c, s) = if view.rotation.abs() < 1e-6 { (1.0, 0.0) } else { (rad.cos(), rad.sin()) }; + let (rx, ry) = (s, -c); + let sx = if xf.flip { -1.0 } else { 1.0 }; + let needle = vec2(rx * sx, ry) * (r.width() * 0.32); + let tip = r.center() + needle; + painter.line_segment([r.center(), tip], Stroke::new(2.0, t.accent)); + painter.circle_filled(tip, 2.5, t.accent); + painter.text(r.center() + vec2(0.0, r.width() * 0.18), Align2::CENTER_CENTER, "N", egui::FontId::proportional(9.0), t.text_faint); + if response.clicked() && response.interact_pointer_pos().is_some_and(|p| r.contains(p)) { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + return true; + } + hover +} + +/// Cursor for the Rotate View tool. +pub fn cursor(dragged: bool) -> egui::CursorIcon { + if dragged { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Event, PointerButton, pos2}; + use egui_kittest::Harness; + use serde_json::json; + + #[test] + fn wrap_deg_folds_huge_and_hostile_angles() { + assert_eq!(wrap_deg(0.0), 0.0); + assert_eq!(wrap_deg(180.0), 180.0); + assert_eq!(wrap_deg(-180.0), 180.0); + assert!((wrap_deg(190.0) + 170.0).abs() < 1e-4); + assert!((wrap_deg(-190.0) - 170.0).abs() < 1e-4); + assert!((wrap_deg(360.0)).abs() < 1e-4); + assert!((wrap_deg(1.0e10)).abs() <= 180.0); + assert_eq!(wrap_deg(f32::NAN), 0.0); + assert_eq!(wrap_deg(f32::INFINITY), 0.0); + assert_eq!(wrap_deg(f32::NEG_INFINITY), 0.0); + } + + #[test] + fn snap_deg_lands_on_fifteens() { + assert_eq!(snap_deg(0.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(8.0, SNAP_DEG), 15.0); + assert_eq!(snap_deg(-7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(-8.0, SNAP_DEG), -15.0); + assert_eq!(snap_deg(40.0, SNAP_DEG), 45.0); + assert_eq!(snap_deg(f32::NAN, SNAP_DEG), 0.0); + assert_eq!(snap_deg(40.0, 0.0), wrap_deg(40.0)); + assert_eq!(snap_deg(40.0, f32::NAN), wrap_deg(40.0)); + } + + #[test] + fn apply_params_sets_adds_resets_and_rejects() { + assert_eq!(apply_params(0.0, &json!({"angle": 30.0})).unwrap(), 30.0); + assert_eq!(apply_params(30.0, &json!({"delta": 15.0})).unwrap(), 45.0); + assert_eq!(apply_params(45.0, &json!({"reset": true})).unwrap(), 0.0); + assert_eq!(apply_params(170.0, &json!({"delta": 20.0})).unwrap(), -170.0); + assert!(apply_params(0.0, &json!({})).is_err()); + assert!(apply_params(0.0, &Value::Null).is_err()); + assert!(apply_params(0.0, &json!("30")).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::NAN})).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::INFINITY})).is_err()); + assert!(apply_params(0.0, &json!({"delta": f64::INFINITY})).is_err()); + assert!(apply_params(0.0, &json!({"reset": "yes"})).is_err()); + assert!(apply_params(0.0, &json!({"zoom": 1})).is_err()); + let huge = apply_params(0.0, &json!({"angle": 1.0e20})).unwrap(); + assert!(huge.is_finite() && huge.abs() <= 180.0); + } + + #[test] + fn trackpad_pref_gates_rotation() { + assert_eq!(apply_trackpad(10.0, false, 0.5), None); + assert_eq!(apply_trackpad(10.0, true, 0.0), None); + assert_eq!(apply_trackpad(10.0, true, f32::NAN), None); + assert_eq!(apply_trackpad(10.0, true, f32::INFINITY), None); + let a = apply_trackpad(10.0, true, std::f32::consts::FRAC_PI_2).expect("finite delta"); + assert!((a - 100.0).abs() < 0.05, "{a}"); + } + + #[test] + fn view_xform_identity_matches_unrotated_mapping() { + for zoom in [0.5, 1.0, 2.5] { + for center in [[0.0, 0.0], [320.0, 240.0], [10.0, -4.0]] { + for flip in [false, true] { + let rect = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)); + let a = ViewXform { rect, zoom, center, flip, rotation: 0.0 }; + let sx = if flip { -1.0 } else { 1.0 }; + let want = rect.center() + vec2((10.0 - center[0]) * zoom * sx, (20.0 - center[1]) * zoom); + let got = a.to_screen(10.0, 20.0); + assert!((got.x - want.x).abs() < 1e-4 && (got.y - want.y).abs() < 1e-4, "{got:?} vs {want:?}"); + } + } + } + } + + #[test] + fn view_xform_roundtrip_and_ninety_degrees() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + for rot in [15.0, 90.0, -45.0, 180.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 2.0, center: [80.0, 40.0], flip, rotation: rot }; + let s = xf.to_screen(10.0, 20.0); + let d = xf.to_doc(s); + assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3, "rot={rot} flip={flip} {d:?}"); + } + } + // 90°: a point on +X in document space lands on +Y on screen (Y-down = clockwise). + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: false, rotation: 90.0 }; + let s = xf.to_screen(1.0, 0.0); + let c = rect.center(); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "{s:?} vs {c:?}"); + // Flip after rotate: 0° +X goes left. + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 0.0 }; + assert!(xf.to_screen(1.0, 0.0).x < rect.center().x); + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 90.0 }; + let s = xf.to_screen(1.0, 0.0); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "flip then rotate {s:?}"); + } + + fn app_docs(n: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..n { + app.run("file.new", json!({"width": 200 + i as u32 * 10, "height": 100})).unwrap(); + } + app.sync_views(); + app + } + + #[test] + fn commands_rotate_reset_and_reject_without_a_document() { + let ctx = egui::Context::default(); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.rotateView", json!({"angle": 30})).unwrap_err(), "no document open"); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.resetView", json!({})).unwrap_err(), "no document open"); + + let mut app = app_docs(1); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 30})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert_eq!(app.ui.views[0].rotation, 30.0); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"delta": 15})).unwrap(); + assert_eq!(r["rotation"], 45.0); + let z = app.ui.views[0].zoom; + let c = app.ui.views[0].center; + let r = crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(r["rotation"], 0.0); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.ui.views[0].zoom, z); + assert_eq!(app.ui.views[0].center, c); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({})).is_err()); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": f64::NAN})).is_err()); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + } + + #[test] + fn ui_set_selects_the_tool_and_sets_rotation() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView", "rotation": 30})); + let out = crate::control::handle(&mut app, &ctx, &req); + let crate::control::Outcome::Done(v) = out else { panic!("done") }; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(app.ui.tool, crate::state::Tool::RotateView); + assert_eq!(app.ui.views[0].rotation, 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.inspect", json!({})); + let crate::control::Outcome::Done(ins) = crate::control::handle(&mut app, &ctx, &req) else { panic!("inspect") }; + assert_eq!(ins["result"]["tool"], "RotateView"); + assert_eq!(ins["result"]["views"][0]["rotation"], 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": f64::NAN})); + let crate::control::Outcome::Done(bad) = crate::control::handle(&mut app, &ctx, &req) else { panic!("nan") }; + assert_eq!(bad["ok"], false); + assert_eq!(app.ui.views[0].rotation, 30.0); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView"})); + let crate::control::Outcome::Done(ok) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("tool") }; + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(empty.ui.tool, crate::state::Tool::RotateView); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": 15})); + let crate::control::Outcome::Done(err) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("no doc") }; + assert_eq!(err["ok"], false); + assert!(err["error"].as_str().unwrap().contains("no document open"), "{err}"); + } + + #[test] + fn match_rotation_copies_the_angle_and_needs_two_documents() { + let ctx = egui::Context::default(); + let one = app_docs(1); + assert_eq!(crate::view_cmds::is_enabled(&one, "window.arrange.matchRotation"), Some(false)); + let mut app = app_docs(2); + assert_eq!(crate::view_cmds::is_enabled(&app, "window.arrange.matchRotation"), Some(true)); + app.ui.views[1].rotation = 30.0; + let r = crate::menus::invoke(&mut app, &ctx, "window.arrange.matchRotation", json!({})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert!(app.ui.views.iter().all(|v| (v.rotation - 30.0).abs() < 1e-4)); + app.ui.views[1].rotation = 12.0; + app.ui.views[1].zoom = 2.0; + crate::menus::invoke(&mut app, &ctx, "window.arrange.matchAll", json!({})).unwrap(); + assert!(app.ui.views.iter().all(|v| (v.rotation - 12.0).abs() < 1e-4 && (v.zoom - 2.0).abs() < 1e-4)); + } + + fn harness() -> Harness<'static, PhotocraftApp> { + 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.extras.rulers = false; + app.ui.tool = crate::state::Tool::RotateView; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h + } + + fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, shift: bool) { + let modifiers = egui::Modifiers { shift, ..Default::default() }; + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers }); + h.step(); + } + + #[test] + fn shift_drag_snaps_to_fifteen_degrees() { + let mut h = harness(); + let r = h.state().last_canvas_rect; + let c = r.center(); + let p0 = c + vec2(120.0, 0.0); + h.event(Event::PointerMoved(p0)); + h.step(); + h.event(Event::ModifiersChanged(egui::Modifiers::SHIFT)); + h.step(); + press(&mut h, p0, true, true); + // ~40° clockwise: Shift rounds to 45°. + let p1 = c + vec2(120.0 * 40f32.to_radians().cos(), 120.0 * 40f32.to_radians().sin()); + h.event(Event::PointerMoved(p1)); + h.step(); + let rot = h.state().ui.views[0].rotation; + assert!((rot - 45.0).abs() < 0.75, "{rot}"); + press(&mut h, p1, false, true); + h.run_steps(2); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + assert_eq!(crate::state::Tool::from_name("RotateView"), Some(crate::state::Tool::RotateView)); + assert_eq!(crate::state::Tool::RotateView.key(), 'R'); + } + + #[test] + fn escape_and_reset_zero_the_angle_without_history() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 33})).unwrap(); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + + let mut h = harness(); + h.state_mut().ui.views[0].rotation = 40.0; + h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.step(); + h.run_steps(2); + assert!((h.state().ui.views[0].rotation).abs() < 0.05, "{}", h.state().ui.views[0].rotation); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + } + + #[test] + fn rotated_view_keeps_engine_selection_in_document_space() { + let mut app = app_docs(1); + app.ui.views[0].rotation = 30.0; + app.run("select.rect", json!({"x": 10, "y": 20, "width": 40, "height": 10})).unwrap(); + let st = app.session.active().unwrap(); + let b = st.doc.selection.as_ref().and_then(|s| photocraft_compose::bounds::content_bounds(s).into()).expect("selection"); + // Axis-aligned in the file: the outline is drawn rotated via ViewXform. + assert!(b.width() >= 40 && b.height() >= 10, "{b:?}"); + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 30.0 }; + let a = xf.to_screen(10.0, 20.0); + let c = xf.to_screen(50.0, 20.0); + let v = c - a; + let ang = v.y.atan2(v.x).to_degrees(); + assert!((wrap_deg(ang) - 30.0).abs() < 0.5, "{ang}"); + assert_eq!(st.history.past_len(), 1, "only the selection is a history step"); + } + + #[test] + fn gpu_path_stays_on_with_rotation() { + // Flip is the only CPU-blit fallback; rotation is a shader uniform. + assert!(crate::gpu_canvas::gpu_view_ok(false, 45.0)); + assert!(!crate::gpu_canvas::gpu_view_ok(true, 45.0)); + assert!(crate::gpu_canvas::gpu_view_ok(false, 0.0)); + } +} diff --git a/crates/ui-egui/src/scrollbars.rs b/crates/ui-egui/src/scrollbars.rs index 73e2edbdef..f8c22e79b2 100644 --- a/crates/ui-egui/src/scrollbars.rs +++ b/crates/ui-egui/src/scrollbars.rs @@ -280,7 +280,7 @@ mod tests { assert_eq!(clamp_axis(600.0, 1000.0, 500.0, 1.0), 600.0); // Smaller than the view: centred. assert_eq!(clamp_axis(-90.0, 1000.0, 500.0, 0.2), 500.0); - let mut v = View { zoom: 1.0, center: [-500.0, 20.0], fit_pending: false, fill_pending: false, doc_size: [1000, 800] }; + let mut v = View { zoom: 1.0, center: [-500.0, 20.0], fit_pending: false, fill_pending: false, doc_size: [1000, 800], rotation: 0.0 }; assert!(clamp_view(&mut v, vec2(500.0, 400.0))); assert_eq!(v.center, [250.0, 200.0]); assert!(!clamp_view(&mut v, vec2(500.0, 400.0)), "stable: no repaint loop"); @@ -299,7 +299,7 @@ mod tests { let (at, len) = s.thumb((0.0, 1000.0), 0.0); assert!(at.is_finite() && len.is_finite()); assert_eq!(s.doc_per_point((0.0, 1000.0), 0.0), 0.0); - let mut v = View { zoom: 1.0, center: [0.0, 0.0], fit_pending: false, fill_pending: false, doc_size: [0, 0] }; + let mut v = View { zoom: 1.0, center: [0.0, 0.0], fit_pending: false, fill_pending: false, doc_size: [0, 0], rotation: 0.0 }; assert!(!clamp_view(&mut v, vec2(500.0, 400.0))); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b8e26271f3..e20f79e9f7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -85,6 +85,7 @@ pub enum Tool { Type, VerticalType, Hand, + RotateView, Zoom, SpotHealing, Healing, @@ -116,7 +117,7 @@ pub enum Tool { } impl Tool { - pub const ALL: [Tool; 51] = [ + pub const ALL: [Tool; 52] = [ Tool::Move, Tool::RectMarquee, Tool::EllipseMarquee, @@ -140,6 +141,7 @@ impl Tool { Tool::Type, Tool::VerticalType, Tool::Hand, + Tool::RotateView, Tool::Zoom, Tool::SpotHealing, Tool::Healing, @@ -197,6 +199,7 @@ impl Tool { Tool::Type => "Horizontal Type Tool", Tool::VerticalType => "Vertical Type Tool", Tool::Hand => "Hand Tool", + Tool::RotateView => "Rotate View Tool", Tool::Zoom => "Zoom Tool", Tool::SpotHealing => "Spot Healing Brush Tool", Tool::Healing => "Healing Brush Tool", @@ -265,6 +268,7 @@ impl Tool { Tool::Gradient | Tool::PaintBucket => 'G', Tool::Type | Tool::VerticalType => 'T', Tool::Hand => 'H', + Tool::RotateView => 'R', Tool::Zoom => 'Z', Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye => 'J', Tool::CloneStamp | Tool::PatternStamp => 'S', @@ -293,6 +297,7 @@ impl Tool { Tool::Gradient | Tool::PaintBucket => "G", Tool::Type | Tool::VerticalType => "T", Tool::Hand => "✋", + Tool::RotateView => "🧭", Tool::Zoom => "🔍", _ => "•", } @@ -388,11 +393,14 @@ pub struct View { /// Document size this view last showed; a change (Image/Canvas Size, crop) re-centres it. #[serde(default)] pub doc_size: [u32; 2], + /// Canvas camera rotation in degrees, wrapped to (−180, 180]. Turns the view, not the pixels. + #[serde(default)] + pub rotation: f32, } impl Default for View { fn default() -> Self { - Self { zoom: 1.0, center: [0.0, 0.0], fit_pending: true, fill_pending: false, doc_size: [0, 0] } + Self { zoom: 1.0, center: [0.0, 0.0], fit_pending: true, fill_pending: false, doc_size: [0, 0], rotation: 0.0 } } } @@ -1024,7 +1032,10 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 51); + assert_eq!(Tool::ALL.len(), 52); + assert_eq!(Tool::from_name("RotateView"), Some(Tool::RotateView)); + assert_eq!(Tool::from_name("Rotate View Tool"), Some(Tool::RotateView)); + assert_eq!(Tool::RotateView.key(), 'R'); assert_eq!(Tool::from_name("nope"), None); } diff --git a/crates/ui-egui/src/stroke_constraint.rs b/crates/ui-egui/src/stroke_constraint.rs index 73f290c3d6..731b79d570 100644 --- a/crates/ui-egui/src/stroke_constraint.rs +++ b/crates/ui-egui/src/stroke_constraint.rs @@ -355,7 +355,7 @@ mod tests { let xf = { let st = h.state(); let v = st.ui.views[st.session.active_index().unwrap()].clone(); - crate::canvas::ViewXform { rect: st.last_canvas_rect, zoom: v.zoom, center: v.center, flip: false } + crate::canvas::ViewXform { rect: st.last_canvas_rect, zoom: v.zoom, center: v.center, flip: false, rotation: v.rotation } }; let from = xf.to_screen(end[0] as f32, end[1] as f32); h.event(Event::PointerMoved(target)); diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 495627046c..64107a4770 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -2413,7 +2413,13 @@ mod tests { let t0 = std::time::Instant::now(); let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()); - let xf = ViewXform { rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0)), zoom, center: [3000.0, 2000.0], flip: false }; + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0)), + zoom, + center: [3000.0, 2000.0], + flip: false, + rotation: 0.0, + }; draw_overlay(&app, &painter, &xf); }); t0.elapsed().as_secs_f64() * 1e3 diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 0d39fe87bf..7e290f8904 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -46,7 +46,13 @@ fn harness() -> Harness<'static, PhotocraftApp> { fn screen(h: &Harness<'static, PhotocraftApp>, p: [f64; 2]) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal }; + let xf = ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + }; xf.to_screen(p[0] as f32, p[1] as f32) } diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index 271687e518..c17bc0c710 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -48,7 +48,13 @@ fn new_app() -> PhotocraftApp { fn xf(app: &PhotocraftApp) -> ViewXform { let v = &app.ui.views[0]; - ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal } + ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + } } /// Screen position of a text-space point of layer `id`. diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 2a64291b5e..ef7c3683ef 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -289,6 +289,8 @@ pub fn handles(id: &str) -> bool { | "view.pixelAspectRatioCorrection" | "view.patternPreview" | "view.pixelArtPreview" + | "view.rotateView" + | "view.resetView" | "window.panel.layers" | "window.panel.history" | "window.panel.navigator" @@ -315,7 +317,7 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { let doc = app.session.active().is_some(); Some(match id { "view.screenMode.cycle" => app.ui.text_edit.is_none(), - "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" => doc, + "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" | "view.rotateView" | "view.resetView" => doc, "view.fitArtboardOnScreen" => app.session.active().is_some_and(|d| d.doc.has_artboards()), i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] { "consolidateAllToTabs" => true, @@ -484,6 +486,12 @@ fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Res } return Ok(json!({"panel": panel, "tab": tab, "visible": visible})); } + if id == "view.rotateView" { + return crate::rotate_view::command(app, p); + } + if id == "view.resetView" { + return crate::rotate_view::reset(app); + } let o = &mut app.ui.view; if let Some(k) = id.strip_prefix("view.show.") { if k == "all" { @@ -632,8 +640,9 @@ fn arrange(app: &mut PhotocraftApp, k: &str) -> Result { } "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => { let i = app.session.active_index().ok_or("no document")?; - let src = app.ui.views[i].clone(); - let (zoom, loc) = (matches!(k, "matchZoom" | "matchAll"), matches!(k, "matchLocation" | "matchAll")); + let src = app.ui.views.get(i).cloned().ok_or("no document")?; + let (zoom, loc, rot) = + (matches!(k, "matchZoom" | "matchAll"), matches!(k, "matchLocation" | "matchAll"), matches!(k, "matchRotation" | "matchAll")); let apply = |v: &mut crate::state::View| { if zoom { v.zoom = src.zoom; @@ -641,12 +650,14 @@ fn arrange(app: &mut PhotocraftApp, k: &str) -> Result { if loc { v.center = src.center; } + if rot { + v.rotation = src.rotation; + } v.fit_pending = false; }; app.ui.views.iter_mut().for_each(apply); app.ui.windows.iter_mut().for_each(|w| apply(&mut w.view)); - // Views never rotate in Photocraft, so Match Rotation has nothing to align. - Ok(json!({"zoom": src.zoom, "center": src.center, "rotation": 0})) + Ok(json!({"zoom": src.zoom, "center": src.center, "rotation": src.rotation})) } _ => Err(format!("unknown arrangement {k}")), } diff --git a/crates/ui-egui/src/zoom_tool.rs b/crates/ui-egui/src/zoom_tool.rs index 7d9ddf9066..de8a16b448 100644 --- a/crates/ui-egui/src/zoom_tool.rs +++ b/crates/ui-egui/src/zoom_tool.rs @@ -146,7 +146,7 @@ mod tests { fn view_xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { let app = h.state(); let v = &app.ui.views[0]; - ViewXform { rect: app.last_canvas_rect, zoom: v.zoom, center: v.center, flip: false } + ViewXform { rect: app.last_canvas_rect, zoom: v.zoom, center: v.center, flip: false, rotation: v.rotation } } fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool) { diff --git a/crates/ui-egui/tests/crop_beyond_canvas.rs b/crates/ui-egui/tests/crop_beyond_canvas.rs index bb579daa5e..e4d4e8fb35 100644 --- a/crates/ui-egui/tests/crop_beyond_canvas.rs +++ b/crates/ui-egui/tests/crop_beyond_canvas.rs @@ -68,6 +68,7 @@ fn screen(h: &Harness, x: f32, y: f32) -> Pos2 { zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal, + rotation: v.rotation, }; xf.to_screen(x, y) } diff --git a/crates/ui-egui/tests/drag_preview_canvas.rs b/crates/ui-egui/tests/drag_preview_canvas.rs index bc04fd9d3f..32c32f2959 100644 --- a/crates/ui-egui/tests/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/drag_preview_canvas.rs @@ -86,7 +86,13 @@ fn setup(h: &mut Harness, background: &str, tool: &str) { fn xf(h: &Harness) -> ViewXform { let app = h.state(); let v = &app.ui.views[0]; - ViewXform { rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal } + ViewXform { + rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + } } /// Screen point (egui points) of document point `(x, y)`. diff --git a/crates/ui-egui/tests/layout_perf.rs b/crates/ui-egui/tests/layout_perf.rs index d8849e8940..b35eb8c59d 100644 --- a/crates/ui-egui/tests/layout_perf.rs +++ b/crates/ui-egui/tests/layout_perf.rs @@ -46,7 +46,7 @@ fn screen(h: &H, p: [f64; 2]) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; let rect = photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect); - ViewXform { rect, zoom: v.zoom, center: v.center, flip: false }.to_screen(p[0] as f32, p[1] as f32) + ViewXform { rect, zoom: v.zoom, center: v.center, flip: false, rotation: v.rotation }.to_screen(p[0] as f32, p[1] as f32) } /// A point where `id` (or, for a group, one of its layers) is the topmost layer with pixels. diff --git a/crates/ui-egui/tests/paint_bucket_all_layers.rs b/crates/ui-egui/tests/paint_bucket_all_layers.rs index 789a00ee23..e55277d3f6 100644 --- a/crates/ui-egui/tests/paint_bucket_all_layers.rs +++ b/crates/ui-egui/tests/paint_bucket_all_layers.rs @@ -67,8 +67,14 @@ fn setup(h: &mut Harness) -> LayerId { fn screen(h: &Harness, x: f32, y: f32) -> Pos2 { let app = h.state(); let v = &app.ui.views[0]; - ViewXform { rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal } - .to_screen(x, y) + ViewXform { + rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + } + .to_screen(x, y) } fn pixels(h: &Harness, layer: LayerId) -> Vec<[f32; 4]> { diff --git a/docs/roadmap.md b/docs/roadmap.md index 7fb0555ed0..dc0495400a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -70,7 +70,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either | Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. | | Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. | | UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418) | low–medium | Needs recurring visual QA with realistic documents. | -| Tools | 2026-10-08: Pencil, Mixer Brush, Patch, Content-Aware Move and Vertical Type are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, Rotate View, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). | +| Tools | 2026-10-09: Pencil, Mixer Brush, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. | | Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. | | Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. | | Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. | @@ -124,9 +124,9 @@ unchanged. effects, composite with masks and adjustment layers, CMYK print prep…) scripted end to end and checked against Photoshop's output on every build. Their pass rate becomes the headline parity number. -4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790), Rotate View - and Perspective Crop; finish Content-Aware Move's Transform On Drop and live result preview. - Pencil, Mixer Brush, Patch and Vertical Type are already available on the toolbar. +4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790) and + Perspective Crop; finish Content-Aware Move's Transform On Drop and live result preview. + Pencil, Mixer Brush, Patch, Vertical Type, Pattern Stamp and Rotate View are already available on the toolbar. 5. **Complex-document performance** (#125/#128) and GPU tiling beyond the texture limit (#49). 6. **Recurring visual QA** (`cargo run -p photocraft-engine --example designer_psd`) and fast turnaround on user reports (OS, document size, layer count, screenshot). diff --git a/docs/scorecard.md b/docs/scorecard.md index 36d4cb6796..7c7d9e68cd 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,8 +8,8 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 13 | 47 scenarios: 3 within budget, 22 over budget or failing, 15 tracked only, 6 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) | 10 | 14 | 8 | | -| [Workspace and UI](#workspace-and-ui) | 0 | 7 | 16 | settings that do nothing: 56 of 140 (target 0) | +| [Tools](#tools) | 11 | 14 | 8 | | +| [Workspace and UI](#workspace-and-ui) | 0 | 7 | 16 | settings that do nothing: 55 of 140 (target 0) | | [Type](#type) | 0 | 3 | 6 | | | [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) | | [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present | @@ -153,12 +153,13 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | +| TOOL-214-17 | Rotate View tool: drag to turn the view, Reset View, Match Rotation copies the angle | done | [#214](https://github.com/storytold/photocraft/issues/214) | Tool::RotateView in the Hand flyout; view.rotateView / view.resetView; Match Rotation copies views[].rotation; enhanced_controls.rotate_view_with_trackpad is read | ## Workspace and UI -**Settings that do nothing: 56 of 140** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 55 of 140** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipboard`, `general.resize_image_during_place`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `interface.show_channels_in_color`, `interface.dynamic_color_sliders`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.open_documents_as_tabs`, `workspace.enable_floating_document_window_docking`, `workspace.large_tabs`, `workspace.enable_narrow_options_bar`, `tools.enable_flick_panning`, `tools.vary_round_brush_hardness_on_hud`, `tools.show_transformation_values`, `tools.double_click_layer_mask_launches_select_and_mask`, `file_handling.image_previews`, `file_handling.lowercase_extension`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `cursors.brush_preview_color`, `units_and_rulers.type_units`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `units_and_rulers.screen_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.smart_quotes`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.use_esc_to_commit`, `type_.text_engine`, `type_.font_preview`, `type_.fill_new_type_layers_with_placeholder`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `enhanced_controls.zoom_with_trackpad_pinch`, `enhanced_controls.rotate_view_with_trackpad`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipboard`, `general.resize_image_during_place`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `interface.show_channels_in_color`, `interface.dynamic_color_sliders`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.open_documents_as_tabs`, `workspace.enable_floating_document_window_docking`, `workspace.large_tabs`, `workspace.enable_narrow_options_bar`, `tools.enable_flick_panning`, `tools.vary_round_brush_hardness_on_hud`, `tools.show_transformation_values`, `tools.double_click_layer_mask_launches_select_and_mask`, `file_handling.image_previews`, `file_handling.lowercase_extension`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `cursors.brush_preview_color`, `units_and_rulers.type_units`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `units_and_rulers.screen_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.smart_quotes`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.use_esc_to_commit`, `type_.text_engine`, `type_.font_preview`, `type_.fill_new_type_layers_with_placeholder`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `enhanced_controls.zoom_with_trackpad_pinch`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 2c5f53419b..23197fe148 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -228,3 +228,10 @@ target = "Red Eye tool: click a pupil to neutralize the red reflection" status = "done" issue = 213 note = "paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error" + +[[item]] +id = "TOOL-214-17" +target = "Rotate View tool: drag to turn the view, Reset View, Match Rotation copies the angle" +status = "done" +issue = 214 +note = "Tool::RotateView in the Hand flyout; view.rotateView / view.resetView; Match Rotation copies views[].rotation; enhanced_controls.rotate_view_with_trackpad is read"