mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-27 13:57:35 +00:00
Fix-up for #11756: Align Edges as the reference application renders it
The PR snapped shapes with a per-edge heuristic (pixel_align.rs, dash-cap tie rules, a PSD coordinate-frame field threaded through engine, format and caches), defaulted the option to off, and renamed the existing Rectangle/Triangle "Align Edges" checkbox to "Snap Bounding Box" next to a second checkbox. The reference application fits the whole shape at render time: the bounds of what it paints (fill, or the stroke's outer edge) get a whole-pixel left/top (a half rounds up) and a whole width/height, and the path is translated and scaled into that box. Fill and stroke take one transform; curves stay antialiased; inner edges of several subpaths are not snapped. - photocraft_vector::align_edges implements that rule; CompiledShape applies it, so caches, the compositor, previews and extents agree; the fill/stroke split under layer effects starts from the whole shape's transform. - Removed pixel_align.rs, the rasterizer helpers it needed, the document-space drag preview and psd_coordinate_frame (rounding the bounds absorbs the PSD quantization it was for). - One Align Edges checkbox (ToolOptions::align_edges, stored and scripted as useAlignedRendering, older align_edges still read) on every shape tool and the Pen, on by default and after Reset Tool; it snaps the drag and sets the layer. - PSD sn2P: written as 1 when on and left out when off, as the reference saves it. - Dropped the dead path.set param, moved the control-protocol paragraph, rewrote docs/pixel-aligned-strokes.md, reverted the unrelated raw, font, Cargo and test-harness changes. - Tests reproduce the measured cases (rectangles at .25/.4/.5/.6/.75, ellipse extremes and curve symmetry, 1/2/3 px strokes, rotated rect, Pen triangle, two subpaths, toggle off, stored path unchanged, one checkbox, Reset Tool). Co-Authored-By: superplay2021 <347501738+superplay2021@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
superplay2021
Claude Opus 5.5
parent
ff0a368ce0
commit
f2ac09d2ec
Generated
-1
@@ -2422,7 +2422,6 @@ dependencies = [
|
||||
"egui_kittest",
|
||||
"epaint_default_fonts",
|
||||
"flate2",
|
||||
"fontique",
|
||||
"image",
|
||||
"inventory",
|
||||
"libtest-mimic",
|
||||
|
||||
@@ -62,7 +62,7 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::
|
||||
LayerContent::Shape(shape) => {
|
||||
layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h);
|
||||
format!("{:?}{:?}{:?}{:?}", shape.path, shape.fill, shape.stroke, shape.live).hash(h);
|
||||
(shape.use_aligned_rendering, shape.psd_coordinate_frame, shape.psd_raw.is_some()).hash(h);
|
||||
shape.use_aligned_rendering.hash(h);
|
||||
(shape.density.to_bits(), shape.feather.to_bits()).hash(h);
|
||||
}
|
||||
_ => layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h),
|
||||
|
||||
@@ -95,9 +95,8 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac
|
||||
depth.hash(&mut h);
|
||||
format!("{:?}{:?}{:?}{:?}", sh.path, sh.fill, sh.stroke, sh.live).hash(&mut h);
|
||||
(sh.density.to_bits(), sh.feather.to_bits()).hash(&mut h);
|
||||
// Align Edges moves both parts at render time without touching the path.
|
||||
sh.use_aligned_rendering.hash(&mut h);
|
||||
sh.psd_raw.is_some().hash(&mut h);
|
||||
sh.psd_coordinate_frame.hash(&mut h);
|
||||
if let Some(c) = &sh.cache {
|
||||
format!("{:?}{:?}", c.format(), c.default_pixel()).hash(&mut h);
|
||||
for (k, t) in c.tiles() {
|
||||
@@ -109,13 +108,12 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac
|
||||
return Some(parts);
|
||||
}
|
||||
let fmt = PixelFormat::RGBA8.with_sample(depth);
|
||||
// Evaluate the special live-line shift before removing its outline. Then drop
|
||||
// live metadata to avoid newly qualifying it, while retaining whole-shape
|
||||
// alignment for rectangle, ellipse and custom-path fills.
|
||||
let align_live_fill = photocraft_vector::pixel_aligned_line_fill_path(sh).is_some();
|
||||
let live = if align_live_fill { sh.live.clone() } else { None };
|
||||
let fill_only = ShapeLayer { live, stroke: None, cache: None, ..sh.clone() };
|
||||
let stroke_only = ShapeLayer { fill: None, cache: None, ..sh.clone() };
|
||||
// Align Edges fits the whole shape (the stroke's outer edge) to pixels: both parts take that
|
||||
// one transform, never each their own bounds.
|
||||
let aligned = photocraft_vector::align_edges::aligned_shape(sh, photocraft_vector::DEFAULT_TOLERANCE);
|
||||
let base = aligned.as_ref().unwrap_or(sh);
|
||||
let fill_only = ShapeLayer { stroke: None, cache: None, ..base.clone() };
|
||||
let stroke_only = ShapeLayer { fill: None, cache: None, ..base.clone() };
|
||||
let mut parts = (photocraft_vector::render_shape(&fill_only, fmt, canvas), photocraft_vector::render_shape(&stroke_only, fmt, canvas));
|
||||
if let Some(cache) = &sh.cache {
|
||||
fit_stroke(&parts.0, &mut parts.1, cache, canvas);
|
||||
@@ -360,89 +358,6 @@ mod tests {
|
||||
assert!(c.0.contains_key(&1), "keep the later completion");
|
||||
}
|
||||
|
||||
/// Splitting must not make a live fill eligible by removing its visible outline.
|
||||
#[test]
|
||||
fn align_edges_split_live_fill_keeps_original_outline_eligibility() {
|
||||
let canvas = Rect::new(0, 0, 100, 100);
|
||||
for (vertical, transparent) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let to = if vertical { [10.0, 70.0] } else { [70.0, 10.0] };
|
||||
let live = photocraft_doc::LiveShape::Line { from: [10.0, 10.0], to, weight: 1.0 };
|
||||
let sh = ShapeLayer {
|
||||
path: photocraft_vector::shapes::live_path(&live),
|
||||
live: Some(live),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
stroke: Some(ShapeStroke { width: 2.0, paint: Fill::Solid(if transparent { Color::TRANSPARENT } else { Color::BLACK }), ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let path = sh.path.clone();
|
||||
let (fill, _) = split(&sh, canvas, SampleType::U8).unwrap();
|
||||
let expected = ShapeLayer {
|
||||
path: sh.path.transform(&photocraft_geom::Affine::translate(if vertical { 0.5 } else { 0.0 }, if vertical { 0.0 } else { 0.5 })),
|
||||
live: None,
|
||||
stroke: None,
|
||||
use_aligned_rendering: false,
|
||||
..sh.clone()
|
||||
};
|
||||
let expected = photocraft_vector::render_shape(&expected, PixelFormat::RGBA8, canvas);
|
||||
for y in 0..100 {
|
||||
for x in 0..100 {
|
||||
assert_eq!(fill.pixel(x, y), expected.pixel(x, y), "vertical={vertical}, transparent={transparent}, ({x},{y})");
|
||||
}
|
||||
}
|
||||
assert_eq!(sh.path, path);
|
||||
assert!(sh.cache.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggling only alignment must invalidate both directions of a cached split.
|
||||
#[test]
|
||||
fn split_cache_tracks_pixel_alignment_without_a_shape_cache() {
|
||||
let canvas = Rect::new(0, 0, 64, 64);
|
||||
let mut sh = ShapeLayer {
|
||||
path: Path::new(vec![Subpath::polyline(&[(13.0, 23.0), (53.0, 23.0)])]),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..ShapeStroke::default() }),
|
||||
..ShapeLayer::default()
|
||||
};
|
||||
for aligned in [false, true, false] {
|
||||
sh.use_aligned_rendering = aligned;
|
||||
let (_, stroke) = split(&sh, canvas, SampleType::U8).expect("stroked shape");
|
||||
let alpha = |y| photocraft_raster::to_rgba(&stroke.format(), &stroke.pixel(31, y))[3];
|
||||
if aligned {
|
||||
assert_eq!(alpha(22), 0.0);
|
||||
assert_eq!(alpha(23), 1.0);
|
||||
} else {
|
||||
assert!((alpha(22) - 0.5).abs() < 0.01);
|
||||
assert!((alpha(23) - 0.5).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fractional edges align independently of PSD provenance and cached prior toggles.
|
||||
#[test]
|
||||
fn split_cache_distinguishes_psd_quantization_allowance() {
|
||||
let canvas = Rect::new(0, 0, 64, 64);
|
||||
let mut sh = ShapeLayer {
|
||||
path: Path::new(vec![Subpath::polyline(&[(13.0, 27.0000005), (53.0, 27.0000005)])]),
|
||||
use_aligned_rendering: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..ShapeStroke::default() }),
|
||||
psd_raw: Some(std::sync::Arc::new(Vec::new())),
|
||||
..ShapeLayer::default()
|
||||
};
|
||||
for imported in [false, true, false] {
|
||||
sh.psd_coordinate_frame = imported.then_some([64, 64]);
|
||||
sh.use_aligned_rendering = imported;
|
||||
let (_, stroke) = split(&sh, canvas, SampleType::U8).expect("stroked shape");
|
||||
let alpha = photocraft_raster::to_rgba(&stroke.format(), &stroke.pixel(31, 26))[3];
|
||||
if imported {
|
||||
assert_eq!(alpha, 0.0);
|
||||
} else {
|
||||
assert!((alpha - 0.5).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The split cache stays within its byte budget, evicting the least recently used, and
|
||||
/// Edit › Purge › All empties it (#4530).
|
||||
#[test]
|
||||
@@ -456,65 +371,27 @@ mod tests {
|
||||
// Other tests share the cache, so only what this test can rely on: a purge frees bytes.
|
||||
assert!(purge_cache() > 0, "something to purge");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod align_edges_fill_tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{Color, Fill, ShapeStroke};
|
||||
|
||||
/// Align Edges: the fill and stroke parts (used under layer effects) both take the whole
|
||||
/// shape's transform. A 1 px stroke on 10..30 has its outer edge at 9.5..30.5, so the whole
|
||||
/// shape moves by +0.5: the fill must move too, though its own bounds are already whole.
|
||||
#[test]
|
||||
fn align_edges_split_preserves_fractional_rectangle_and_custom_fills() {
|
||||
fn align_edges_split_parts_share_the_whole_shape_transform() {
|
||||
let canvas = Rect::new(0, 0, 48, 48);
|
||||
for custom in [false, true] {
|
||||
let mut shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(10.5, 10.5, 20.0, 20.0),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
stroke: Some(ShapeStroke::default()),
|
||||
..Default::default()
|
||||
};
|
||||
if custom {
|
||||
shape.path.subpaths.push(photocraft_doc::Subpath::polygon(&[(34.5, 10.5), (40.5, 10.5), (40.5, 30.5), (34.5, 30.5)]));
|
||||
}
|
||||
let stored = shape.path.clone();
|
||||
for enabled in [false, true, false] {
|
||||
shape.use_aligned_rendering = enabled;
|
||||
let (fill, _) = split(&shape, canvas, SampleType::U8).unwrap();
|
||||
let alpha = |x| photocraft_raster::to_rgba(&fill.format(), &fill.pixel(x, 20))[3];
|
||||
if enabled {
|
||||
assert_eq!(alpha(10), 0.0);
|
||||
assert_eq!(alpha(30), 1.0);
|
||||
if custom {
|
||||
assert_eq!(alpha(34), 0.0);
|
||||
assert_eq!(alpha(40), 1.0);
|
||||
}
|
||||
} else {
|
||||
assert!(alpha(10) > 0.0 && alpha(10) < 1.0);
|
||||
assert!(alpha(30) > 0.0 && alpha(30) < 1.0);
|
||||
}
|
||||
assert_eq!(shape.path, stored);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_edges_split_matches_unsplit_ellipse_fill() {
|
||||
let canvas = Rect::new(0, 0, 64, 64);
|
||||
let mut shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::ellipse(10.5, 10.5, 40.0, 40.0),
|
||||
let sh = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(10.0, 10.0, 20.0, 20.0),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
stroke: Some(ShapeStroke::default()),
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
for enabled in [false, true] {
|
||||
shape.use_aligned_rendering = enabled;
|
||||
let (fill, _) = split(&shape, canvas, SampleType::U8).unwrap();
|
||||
let expected = photocraft_vector::render_shape(&ShapeLayer { stroke: None, ..shape.clone() }, PixelFormat::RGBA8, canvas);
|
||||
for y in 0..64 {
|
||||
for x in 0..64 {
|
||||
assert_eq!(fill.pixel(x, y), expected.pixel(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fill, stroke) = split(&sh, canvas, SampleType::U8).unwrap();
|
||||
let alpha = |s: &Surface, x| photocraft_raster::to_rgba(&s.format(), &s.pixel(x, 20))[3];
|
||||
// Stroke on columns 10 and 30 (its outer edge 10..31), the fill 10.5..30.5 inside it.
|
||||
assert_eq!([alpha(&stroke, 9), alpha(&stroke, 10), alpha(&stroke, 11), alpha(&stroke, 30), alpha(&stroke, 31)], [0.0, 1.0, 0.0, 1.0, 0.0]);
|
||||
assert!((alpha(&fill, 10) - 0.5).abs() < 0.01 && (alpha(&fill, 30) - 0.5).abs() < 0.01, "the fill moved with the stroke");
|
||||
// Off: both parts at their stored place.
|
||||
let (fill, _) = split(&ShapeLayer { use_aligned_rendering: false, ..sh.clone() }, canvas, SampleType::U8).unwrap();
|
||||
assert_eq!([alpha(&fill, 9), alpha(&fill, 10), alpha(&fill, 29), alpha(&fill, 30)], [0.0, 1.0, 1.0, 0.0]);
|
||||
}
|
||||
}
|
||||
|
||||
+27
-114
@@ -1580,54 +1580,6 @@ fn fx_doc(effects: Vec<Effect>) -> Document {
|
||||
d
|
||||
}
|
||||
|
||||
/// Interior effects must not shift the fill away from a live line's visible outline.
|
||||
#[test]
|
||||
fn pixel_align_live_line_with_effect_keeps_fill_and_outline_registered() {
|
||||
use photocraft_doc::{LiveShape, ShapeLayer, ShapeStroke};
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
for arrow in [false, true] {
|
||||
let live = if arrow {
|
||||
LiveShape::ArrowLine { from: [10.0, 20.0], to: [70.0, 20.0], weight: 1.0, start: false, end: true, width: 5.0, length: 8.0, concavity: 0.0 }
|
||||
} else {
|
||||
LiveShape::Line { from: [10.0, 20.0], to: [70.0, 20.0], weight: 1.0 }
|
||||
};
|
||||
let mut doc = Document::new("line", Size::new(100, 50), ColorMode::Rgb, depth);
|
||||
let shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::live_path(&live),
|
||||
live: Some(live),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
stroke: Some(ShapeStroke { width: 0.5, opacity: 0.5, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let path = shape.path.clone();
|
||||
let mut layer = Layer::new("line", LayerContent::Shape(shape));
|
||||
layer.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(0.0, 1.0, 0.0) });
|
||||
doc.layers.push(layer);
|
||||
let LayerContent::Shape(shape) = &mut doc.layers[0].content else { panic!("shape") };
|
||||
shape.use_aligned_rendering = true;
|
||||
assert_eq!(shape.path, path);
|
||||
assert!(shape.cache.is_none());
|
||||
// A full-opacity Color Overlay makes the aligned fill green, then the
|
||||
// independent vector outline paints above it. Build that reference
|
||||
// explicitly, rather than expecting alignment to retain legacy pixels.
|
||||
let mut reference = Document::new("reference", Size::new(100, 50), ColorMode::Rgb, depth);
|
||||
for part in [
|
||||
ShapeLayer { live: None, stroke: None, fill: Some(Fill::Solid(Color::rgb(0.0, 1.0, 0.0))), ..shape.clone() },
|
||||
ShapeLayer { fill: None, ..shape.clone() },
|
||||
] {
|
||||
let surface = photocraft_vector::render_shape(&part, PixelFormat::RGBA8.with_sample(depth), Rect::new(0, 0, 100, 50));
|
||||
reference.layers.push(Layer::new("part", LayerContent::Raster(surface)));
|
||||
}
|
||||
let expected = flatten(&reference);
|
||||
assert!(expected.get(35, 20)[1] > 0.0, "fixture must paint the aligned green fill");
|
||||
let actual = flatten(&doc);
|
||||
for (i, (actual, expected)) in actual.px.iter().zip(&expected.px).enumerate() {
|
||||
assert!(close4(*actual, *expected), "depth={depth:?}, arrow={arrow}, pixel={i}: {actual:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(size: f32, position: StrokePosition) -> Effect {
|
||||
Effect::Stroke(StrokeFx {
|
||||
common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
|
||||
@@ -4971,76 +4923,37 @@ fn softer_outer_glow_fades_out_before_its_size() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Align Edges on a shape with a layer effect (the compositor's fill/stroke split and the effect
|
||||
/// cache): toggling the flag alone re-renders, and the stroke and the fill move together. A 1 px
|
||||
/// stroke on 10..30 moves to columns 10 and 30 (reference measurement), the fill with it.
|
||||
#[test]
|
||||
fn pixel_align_psd_effect_layer_roi_matches_document_frame() {
|
||||
use photocraft_doc::effects::{Effect, FxCommon};
|
||||
fn align_edges_toggle_rerenders_a_shape_under_a_layer_effect() {
|
||||
use photocraft_doc::{ShapeLayer, ShapeStroke};
|
||||
let quantize = |v: f64| (v / 1000.0 * 16_777_216.0).round() / 16_777_216.0 * 1000.0;
|
||||
let shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(quantize(10.0), quantize(10.0), quantize(70.0) - quantize(10.0), quantize(70.0) - quantize(10.0)),
|
||||
fill: Some(Fill::Solid(Color::WHITE)),
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
psd_raw: Some(std::sync::Arc::new(Vec::new())),
|
||||
psd_coordinate_frame: Some([1000, 1000]),
|
||||
let shape = |aligned| ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(10.0, 10.0, 20.0, 20.0),
|
||||
fill: Some(Fill::Solid(Color::rgb(1.0, 0.0, 0.0))),
|
||||
stroke: Some(ShapeStroke { width: 1.0, paint: Fill::Solid(Color::BLACK), ..Default::default() }),
|
||||
use_aligned_rendering: aligned,
|
||||
..Default::default()
|
||||
};
|
||||
let mut layer = Layer::new("PSD rectangle", LayerContent::Shape(shape));
|
||||
layer.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 0.25), color: Color::BLACK });
|
||||
let full = render_layer(&layer, Rect::new(0, 0, 1000, 1000));
|
||||
let roi = render_layer(&layer, Rect::new(0, 0, 80, 80));
|
||||
for y in 0..80 {
|
||||
for x in 0..80 {
|
||||
assert_eq!(roi.px[y * 80 + x], full.px[y * 1000 + x], "{x},{y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_round2_effect_identity_tracks_alignment_provenance() {
|
||||
use std::hash::Hasher;
|
||||
let mut layer = Layer::new("shape", LayerContent::Shape(photocraft_doc::ShapeLayer::default()));
|
||||
let key = |layer: &Layer| {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
super::fx_cache::layer_identity(layer, &mut h, &mut |_| {});
|
||||
h.finish()
|
||||
let doc = |aligned| {
|
||||
let mut d = doc_white(48, 48);
|
||||
let mut l = Layer::new("shape", LayerContent::Shape(shape(aligned)));
|
||||
l.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 0.5), color: Color::rgb(0.0, 0.0, 1.0) });
|
||||
d.layers.push(l);
|
||||
d
|
||||
};
|
||||
let original = key(&layer);
|
||||
let LayerContent::Shape(sh) = &mut layer.content else { panic!() };
|
||||
let mut d = doc(false);
|
||||
let off = flatten(&d).px.clone();
|
||||
let LayerContent::Shape(sh) = &mut d.layers.last_mut().unwrap().content else { panic!("shape") };
|
||||
sh.use_aligned_rendering = true;
|
||||
let aligned = key(&layer);
|
||||
assert_ne!(original, aligned);
|
||||
let LayerContent::Shape(sh) = &mut layer.content else { panic!() };
|
||||
sh.psd_coordinate_frame = Some([1000, 2000]);
|
||||
let framed = key(&layer);
|
||||
assert_ne!(aligned, framed);
|
||||
let LayerContent::Shape(sh) = &mut layer.content else { panic!() };
|
||||
sh.psd_raw = Some(std::sync::Arc::new(Vec::new()));
|
||||
assert_ne!(framed, key(&layer));
|
||||
}
|
||||
|
||||
/// Reference: a black no-stroke rectangle at 10.5..30.5 on white has a white
|
||||
/// column 10 and black column 30 with Align Edges enabled.
|
||||
#[test]
|
||||
fn align_edges_no_stroke_rectangle_matches_reference_columns() {
|
||||
for enabled in [false, true] {
|
||||
let mut doc = doc_white(48, 48);
|
||||
let mut shape = photocraft_doc::ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(10.5, 10.5, 20.0, 20.0),
|
||||
fill: Some(Fill::Solid(Color::BLACK)),
|
||||
use_aligned_rendering: enabled,
|
||||
..Default::default()
|
||||
};
|
||||
// The engine supplies vector rasterization to the compositor as the shape cache.
|
||||
shape.cache = Some(photocraft_vector::render_shape(&shape, PixelFormat::RGBA8, Rect::new(0, 0, 48, 48)));
|
||||
doc.layers.push(Layer::new("rectangle", LayerContent::Shape(shape)));
|
||||
let (left, right) = (px(&doc, 10, 20), px(&doc, 30, 20));
|
||||
if enabled {
|
||||
assert_eq!(left, [1.0; 4]);
|
||||
assert_eq!(right, [0.0, 0.0, 0.0, 1.0]);
|
||||
} else {
|
||||
assert!(left[0] > 0.0 && left[0] < 1.0);
|
||||
assert!(right[0] > 0.0 && right[0] < 1.0);
|
||||
}
|
||||
}
|
||||
let on = flatten(&d).px.clone();
|
||||
assert_ne!(on, off, "the flag alone must not hit a stale cache");
|
||||
assert_eq!(on, flatten(&doc(true)).px, "same as a fresh aligned layer");
|
||||
// Row 20: column 9 white, 10 the stroke's colour under the overlay, 11 the fill's.
|
||||
let at = |px: &[[f32; 4]], x: usize| px[20 * 48 + x];
|
||||
assert!(close4(at(&on, 9), [1.0; 4]));
|
||||
assert!(close4(at(&on, 10), at(&on, 30)), "both stroke columns alike");
|
||||
assert!(!close4(at(&on, 10), at(&on, 11)), "stroke, then fill");
|
||||
assert!(!close4(at(&off, 9), [1.0; 4]), "unaligned the stroke covers half of column 9");
|
||||
}
|
||||
|
||||
@@ -55,7 +55,6 @@ impl Frame {
|
||||
fill: None,
|
||||
stroke: Some(stroke),
|
||||
use_aligned_rendering: false,
|
||||
psd_coordinate_frame: None,
|
||||
cache: None,
|
||||
psd_raw: None,
|
||||
live: None,
|
||||
|
||||
@@ -347,11 +347,9 @@ pub struct ShapeLayer {
|
||||
/// `None` = no fill (Photoshop's fill "none").
|
||||
pub fill: Option<Fill>,
|
||||
pub stroke: Option<ShapeStroke>,
|
||||
/// Align Edges: snap fill and stroke edges to document pixels at render time.
|
||||
/// Align Edges (PSD `sn2P`, scripting `useAlignedRendering`): at render time the whole shape
|
||||
/// is fitted to whole document pixels (`photocraft_vector::align_edges`); `path` is unchanged.
|
||||
pub use_aligned_rendering: bool,
|
||||
/// Original PSD coordinate grid, retained independently of the export block.
|
||||
/// Supplies the half-quantum alignment allowance after an integer translation.
|
||||
pub psd_coordinate_frame: Option<[u32; 2]>,
|
||||
pub live: Option<LiveShape>,
|
||||
/// Rasterized appearance (from PSD or `photocraft-vector`).
|
||||
pub cache: Option<Surface>,
|
||||
@@ -372,7 +370,6 @@ impl Default for ShapeLayer {
|
||||
fill: None,
|
||||
stroke: None,
|
||||
use_aligned_rendering: false,
|
||||
psd_coordinate_frame: None,
|
||||
live: None,
|
||||
cache: None,
|
||||
psd_raw: None,
|
||||
|
||||
@@ -215,17 +215,6 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
|
||||
|
||||
sh.path = sh.path.transform(a);
|
||||
let [m0, m1, m2, m3, tx, ty] = a.m;
|
||||
// Signed axis permutations preserve the original quantization error.
|
||||
let near = |x: f64, target: f64| (x - target).abs() <= 1e-12;
|
||||
let unit = |x: f64| near(x.abs(), 1.0);
|
||||
let translation = tx.is_finite() && ty.is_finite() && near(tx, tx.round()) && near(ty, ty.round());
|
||||
if translation && unit(m0) && unit(m3) && near(m1, 0.0) && near(m2, 0.0) {
|
||||
// Translation or reflection keeps the original axes.
|
||||
} else if translation && unit(m1) && unit(m2) && near(m0, 0.0) && near(m3, 0.0) {
|
||||
sh.psd_coordinate_frame = sh.psd_coordinate_frame.map(|[w, h]| [h, w]);
|
||||
} else {
|
||||
sh.psd_coordinate_frame = None;
|
||||
}
|
||||
let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0;
|
||||
// The path has already received the exact affine transform. Drop live arrow
|
||||
// parameters if later edits would regenerate a different, unskewed head.
|
||||
@@ -388,11 +377,9 @@ pub(crate) fn map_shape(sh: &mut ShapeLayer, h: Option<&photocraft_algo::transfo
|
||||
sh.path = map_path(&sh.path, h, warp)?;
|
||||
sh.live = None;
|
||||
sh.psd_raw = None;
|
||||
sh.psd_coordinate_frame = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Report a shape layer's geometry, appearance, Align Edges state and optional cached bounds.
|
||||
pub(super) fn shape_info(s: &Session, id: LayerId) -> Result<Value> {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
@@ -413,8 +400,6 @@ pub(super) fn shape_info(s: &Session, id: LayerId) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Run a lock-checked shape edit in one history step, restoring the layer content afterward.
|
||||
/// Recover missing PSD provenance before the edit and refresh cached pixels on success.
|
||||
pub fn with_shape<R>(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result<R>) -> Result<R> {
|
||||
if let Some(st) = s.active() {
|
||||
let locks = st.doc.effective_locks(id);
|
||||
@@ -431,9 +416,6 @@ pub fn with_shape<R>(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&
|
||||
let LayerContent::Shape(mut sh) = std::mem::replace(&mut l.content, LayerContent::Fill(Fill::Solid(Color::BLACK))) else {
|
||||
return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0)));
|
||||
};
|
||||
if sh.psd_coordinate_frame.is_none() && sh.psd_raw.is_some() {
|
||||
sh.psd_coordinate_frame = Some([snapshot.size.width, snapshot.size.height]);
|
||||
}
|
||||
let r = f(&mut sh, l);
|
||||
if r.is_ok() {
|
||||
refresh_shape(&snapshot, &mut sh);
|
||||
@@ -457,8 +439,16 @@ fn default_name(kind: &str) -> &'static str {
|
||||
}
|
||||
|
||||
/// Creates a shape layer, or adds path components to the shape identified by `addTo`.
|
||||
/// Applies alignment to additions only when explicitly supplied.
|
||||
/// Line Tool additions keep the tool's History name. Other shape additions use Add Shape.
|
||||
/// The optional `useAlignedRendering` param (a shape layer's Align Edges): `None` when omitted.
|
||||
fn aligned_param(cmd: &str, p: &Value) -> Result<Option<bool>> {
|
||||
match p.get("useAlignedRendering") {
|
||||
None => Ok(None),
|
||||
Some(Value::Bool(enabled)) => Ok(Some(*enabled)),
|
||||
Some(_) => Err(bad(cmd, "`useAlignedRendering` must be a boolean")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "shape.create";
|
||||
let add_to = p.get("addTo").and_then(Value::as_u64);
|
||||
@@ -474,17 +464,14 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
|
||||
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
let use_aligned_rendering = match p.get("useAlignedRendering") {
|
||||
None => None,
|
||||
Some(Value::Bool(enabled)) => Some(*enabled),
|
||||
Some(_) => return Err(bad(CMD, "`useAlignedRendering` must be a boolean")),
|
||||
};
|
||||
let use_aligned_rendering = aligned_param(CMD, p)?;
|
||||
// Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).
|
||||
if let Some(target) = add_to {
|
||||
let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?;
|
||||
let id = LayerId(target);
|
||||
let label = if kind == "line" && label == "Line Tool" { label } else { "Add Shape" };
|
||||
with_shape(s, id, label, |sh, _| {
|
||||
// An addition keeps the target layer's Align Edges unless the param says otherwise.
|
||||
if let Some(enabled) = use_aligned_rendering {
|
||||
sh.use_aligned_rendering = enabled;
|
||||
}
|
||||
@@ -497,7 +484,6 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
sh.live = None;
|
||||
sh.psd_raw = None;
|
||||
sh.psd_coordinate_frame = None;
|
||||
vector::flatten::validate_shape(&sh.path, sh.stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -538,11 +524,7 @@ fn new_fill_stroke(s: &Session, cmd: &str, p: &Value) -> Result<(Option<Fill>, O
|
||||
/// that would duplicate the selected shape or vector mask.
|
||||
pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.toShape";
|
||||
let use_aligned_rendering = match p.get("useAlignedRendering") {
|
||||
None => false,
|
||||
Some(Value::Bool(enabled)) => *enabled,
|
||||
Some(_) => return Err(bad(CMD, "`useAlignedRendering` must be a boolean")),
|
||||
};
|
||||
let use_aligned_rendering = aligned_param(CMD, p)?.unwrap_or(false);
|
||||
let name = match p.get("name") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(n)) => Some(n.as_str()),
|
||||
@@ -572,8 +554,7 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.clone()),
|
||||
Some(_) => return Err(bad(CMD, "`layerName` must be a name that isn't empty")),
|
||||
};
|
||||
let psd_coordinate_frame = if p.get("path").is_none_or(Value::is_null) { converted_path_frame(s, name, &path) } else { None };
|
||||
let mut sh = ShapeLayer { path, fill, stroke, use_aligned_rendering, psd_coordinate_frame, ..Default::default() };
|
||||
let mut sh = ShapeLayer { path, fill, stroke, use_aligned_rendering, ..Default::default() };
|
||||
let id = s.edit("New Shape Layer", |doc, active| {
|
||||
refresh_shape(doc, &mut sh);
|
||||
let name = layer_name.unwrap_or_else(|| doc.next_layer_name(default_name("path")));
|
||||
@@ -587,30 +568,6 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
shape_info(s, id)
|
||||
}
|
||||
|
||||
/// Reuse a source grid only when retained PSD bytes still describe the copied path.
|
||||
fn converted_path_frame(s: &Session, name: Option<&str>, path: &Path) -> Option<[u32; 2]> {
|
||||
let st = s.active()?;
|
||||
let [w, h] = [st.doc.size.width, st.doc.size.height];
|
||||
if name == Some("layer") {
|
||||
let layer = st.doc.layer(st.active_layer?)?;
|
||||
if let LayerContent::Shape(source) = &layer.content {
|
||||
return source.psd_coordinate_frame.or_else(|| source.psd_raw.as_ref().map(|_| [w, h]));
|
||||
}
|
||||
return layer
|
||||
.psd_blocks
|
||||
.iter()
|
||||
.filter(|(key, _)| key == b"vsms" || key == b"vmsk")
|
||||
.any(|(_, data)| photocraft_io::vector_map::vector_mask_from_block(data, w, h).is_some_and(|mask| mask.path == *path))
|
||||
.then_some([w, h]);
|
||||
}
|
||||
if super::is_work(name) {
|
||||
return None;
|
||||
}
|
||||
let saved = st.doc.paths.iter().find(|p| Some(p.name.as_str()) == name)?;
|
||||
let raw = saved.psd_raw.as_ref()?;
|
||||
(photocraft_io::vector_map::path_from_resource(raw, w, h).as_ref() == Some(path)).then_some([w, h])
|
||||
}
|
||||
|
||||
/// The History name of a `shape.edit` of layer `id`: an edit of one arrowhead setting of a line
|
||||
/// is named after it, "Change Arrowhead End" (#13267). The reference application was measured for
|
||||
/// End and Width; Start, Length and Concavity follow the same pattern. Rounding a live triangle
|
||||
@@ -637,7 +594,6 @@ fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply geometry and appearance edits in one history step, rebuilding derived shape data as needed.
|
||||
pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "shape.edit";
|
||||
let id = layer_id(s, p)?;
|
||||
@@ -647,9 +603,7 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = edit_history_name(s, id, p);
|
||||
with_shape(s, id, label, |sh, layer| {
|
||||
if let Some(v) = p.get("path") {
|
||||
let path = parse_path(v).map_err(|e| bad(CMD, e))?;
|
||||
sh.psd_coordinate_frame = (path == sh.path).then_some(sh.psd_coordinate_frame).flatten();
|
||||
sh.path = path;
|
||||
sh.path = parse_path(v).map_err(|e| bad(CMD, e))?;
|
||||
sh.live = None;
|
||||
sh.psd_raw = None;
|
||||
}
|
||||
@@ -683,7 +637,6 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sh.path = vector::shapes::live_path(&l);
|
||||
sh.live = Some(l);
|
||||
sh.psd_raw = None;
|
||||
sh.psd_coordinate_frame = None;
|
||||
}
|
||||
}
|
||||
if let Some(m) = nums::<6>(p, "transform") {
|
||||
@@ -710,8 +663,8 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("stroke") {
|
||||
sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?;
|
||||
}
|
||||
if let Some(value) = p.get("useAlignedRendering") {
|
||||
sh.use_aligned_rendering = value.as_bool().ok_or_else(|| bad(CMD, "`useAlignedRendering` must be a boolean"))?;
|
||||
if let Some(enabled) = aligned_param(CMD, p)? {
|
||||
sh.use_aligned_rendering = enabled;
|
||||
}
|
||||
if let Some(n) = name {
|
||||
layer.name = n;
|
||||
@@ -759,7 +712,6 @@ fn bake_components(sh: &mut ShapeLayer, tol: f64) -> Result<()> {
|
||||
sh.path = bake_path(&sh.path, tol)?;
|
||||
sh.live = None;
|
||||
sh.psd_raw = None;
|
||||
sh.psd_coordinate_frame = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -844,7 +796,7 @@ fn merge_shape_layers(s: &mut Session, ids: &[LayerId], op: Option<PathOp>, labe
|
||||
let LayerContent::Shape(sh) = &mut l.content else {
|
||||
return Err(EngineError::Other(format!("layer {} is not a shape layer", keep.0)));
|
||||
};
|
||||
let mut merged = ShapeLayer { path, live: None, psd_raw: None, psd_coordinate_frame: None, cache: None, ..sh.clone() };
|
||||
let mut merged = ShapeLayer { path, live: None, psd_raw: None, cache: None, ..sh.clone() };
|
||||
if let Some(tol) = bake {
|
||||
bake_components(&mut merged, tol)?;
|
||||
}
|
||||
|
||||
@@ -94,11 +94,7 @@ fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(
|
||||
let shape = layer.filter(|id| s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))));
|
||||
let path = match shape {
|
||||
Some(id) => with_shape(s, id, label, |sh, _| {
|
||||
let previous = sh.path.clone();
|
||||
f(&mut sh.path).map_err(|e| bad(cmd, e))?;
|
||||
if !preserves_psd_grid(&previous, &sh.path) {
|
||||
sh.psd_coordinate_frame = None;
|
||||
}
|
||||
sh.live = None;
|
||||
sh.psd_raw = None;
|
||||
Ok(path_json(&sh.path))
|
||||
@@ -112,24 +108,6 @@ fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(
|
||||
Ok(json!({ "name": name, "path": path }))
|
||||
}
|
||||
|
||||
/// Only a verified whole-path integer translation retains the source quantization grid.
|
||||
fn preserves_psd_grid(before: &Path, after: &Path) -> bool {
|
||||
if before == after {
|
||||
return true;
|
||||
}
|
||||
let first = |path: &Path| path.subpaths.first().and_then(|s| s.knots.first()).map(|k| k.anchor);
|
||||
let (Some(a), Some(b)) = (first(before), first(after)) else { return false };
|
||||
let integer_offset = |from: f64, to: f64| {
|
||||
let delta = to - from;
|
||||
// Recover subtraction roundoff, including when a move crosses a binade.
|
||||
// The exact whole-path check below still rejects genuine fractional edits.
|
||||
let tolerance = 1e-12_f64.max(4.0 * f64::EPSILON * from.abs().max(to.abs()));
|
||||
(delta.is_finite() && (delta - delta.round()).abs() <= tolerance).then_some(delta.round())
|
||||
};
|
||||
let (Some(dx), Some(dy)) = (integer_offset(a.x, b.x), integer_offset(a.y, b.y)) else { return false };
|
||||
before.transform(&photocraft_geom::Affine::translate(dx, dy)) == *after
|
||||
}
|
||||
|
||||
fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.moveAnchors";
|
||||
let anchors: Vec<[usize; 2]> = p
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
/// Make Shape preserves source geometry, defaults to legacy, and records conversion atomically.
|
||||
#[test]
|
||||
fn pixel_align_make_shape_supports_work_saved_and_inline_paths() {
|
||||
for source in ["work", "saved", "inline"] {
|
||||
for enabled in [None, Some(false), Some(true)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let path = json!({"subpaths":[{"closed":true,"knots":[[10,10],[50,10],[50,50]]}]});
|
||||
s.execute("path.set", json!({"name":"work","path":path})).unwrap();
|
||||
let expected = s.active().unwrap().doc.work_path.clone().unwrap();
|
||||
let mut params = json!({"fill":null,"stroke":{"width":1}});
|
||||
match source {
|
||||
"work" => params["name"] = json!("work"),
|
||||
"saved" => {
|
||||
s.execute("path.set", json!({"name":"Saved","path":path})).unwrap();
|
||||
params["name"] = json!("Saved");
|
||||
}
|
||||
_ => params["path"] = path,
|
||||
}
|
||||
if let Some(value) = enabled {
|
||||
params["useAlignedRendering"] = json!(value);
|
||||
}
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let info = s.execute("path.toShape", params).unwrap();
|
||||
assert_eq!(info["useAlignedRendering"], enabled.unwrap_or(false), "source={source}");
|
||||
let st = s.active().unwrap();
|
||||
let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
assert_eq!(shape.path, expected);
|
||||
assert_eq!(st.doc.paths, before.paths);
|
||||
assert_eq!(st.doc.work_path.is_none(), source == "work");
|
||||
assert_eq!(st.history.past_len(), history + 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.work_path, before.work_path);
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len());
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
let redone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(redone["useAlignedRendering"], enabled.unwrap_or(false));
|
||||
assert_eq!(redone["path"], info["path"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid alignment values cannot consume a Work Path or alter document/history.
|
||||
#[test]
|
||||
fn pixel_align_make_shape_rejects_invalid_flag_atomically() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("path.set", json!({"path":{"subpaths":[{"knots":[[10,10],[40,10],[40,40]]}]}})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
for invalid in [json!(null), json!("true"), json!(1), json!([]), json!({})] {
|
||||
assert!(s.execute("path.toShape", json!({"name":"work","useAlignedRendering":invalid})).is_err());
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete Stroke copies a snapshot of alignment and style, and pastes both in one undo step.
|
||||
#[test]
|
||||
fn complete_stroke_clipboard_preserves_pixel_alignment_and_geometry() {
|
||||
for enabled in [false, true] {
|
||||
for new_document in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let source = s
|
||||
.execute(
|
||||
"shape.create",
|
||||
json!({"kind":"rect","rect":[10,10,20,20],
|
||||
"useAlignedRendering":enabled,"stroke":{"width":1,"color":"#ff0000"}}),
|
||||
)
|
||||
.unwrap();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
s.execute("path.style.copyStroke", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history, "copy must not add history");
|
||||
// Editing the source after copying must not change the clipboard snapshot.
|
||||
s.execute("shape.edit", json!({"useAlignedRendering":!enabled,"stroke":null})).unwrap();
|
||||
assert!(s.execute("path.style.copyStroke", json!({})).is_err());
|
||||
if new_document {
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
}
|
||||
let before = s
|
||||
.execute(
|
||||
"shape.create",
|
||||
json!({"kind":"ellipse","rect":[40,40,30,30],
|
||||
"useAlignedRendering":!enabled,"fill":"#00ff00","stroke":{"width":3,"color":"#0000ff"}}),
|
||||
)
|
||||
.unwrap();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let after = s.execute("path.style.pasteStroke", json!({})).unwrap();
|
||||
assert_eq!(after["useAlignedRendering"], enabled, "new_document={new_document}");
|
||||
assert_eq!(after["stroke"], source["stroke"]);
|
||||
assert_eq!(after["path"], before["path"]);
|
||||
assert_eq!(after["fill"], before["fill"]);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let undone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(undone["useAlignedRendering"], !enabled);
|
||||
assert_eq!(undone["stroke"], before["stroke"]);
|
||||
assert_eq!(undone["path"], before["path"]);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
let redone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(redone["useAlignedRendering"], enabled);
|
||||
assert_eq!(redone["stroke"], source["stroke"]);
|
||||
assert_eq!(redone["path"], before["path"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Appending honors an explicit flag, preserves an omitted flag, and undoes both atomically.
|
||||
#[test]
|
||||
fn pixel_align_append_honors_explicit_values_and_preserves_omission() {
|
||||
for initial in [false, true] {
|
||||
for explicit in [None, Some(false), Some(true)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let before = s.execute("shape.create", json!({"kind":"rect","rect":[10,10,20,20],"useAlignedRendering":initial})).unwrap();
|
||||
let mut params = json!({"kind":"rect","rect":[50,50,20,20],"addTo":before["layer"]});
|
||||
if let Some(value) = explicit {
|
||||
params["useAlignedRendering"] = json!(value);
|
||||
}
|
||||
let after = s.execute("shape.create", params).unwrap();
|
||||
assert_eq!(after["useAlignedRendering"], explicit.unwrap_or(initial));
|
||||
assert_ne!(after["path"], before["path"]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let undone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(undone["useAlignedRendering"], initial);
|
||||
assert_eq!(undone["path"], before["path"]);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], explicit.unwrap_or(initial));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid flag types leave history intact, and undo/redo changes only the rendering option.
|
||||
#[test]
|
||||
fn pixel_align_shape_commands_preserve_path_and_undo_and_validate_bool() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100,"background":"transparent"})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60],"stroke":{"width":1}})).unwrap();
|
||||
let legacy = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(legacy["useAlignedRendering"], false);
|
||||
let path = legacy["path"].clone();
|
||||
let on = s.execute("shape.edit", json!({"useAlignedRendering":true})).unwrap();
|
||||
assert_eq!(on["useAlignedRendering"], true);
|
||||
assert_eq!(on["path"], path);
|
||||
assert!(s.execute("shape.edit", json!({"useAlignedRendering":"true"})).is_err());
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], true);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], false);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], true);
|
||||
}
|
||||
|
||||
/// Placement forwards either explicit alignment value through the custom-shape preset command.
|
||||
#[test]
|
||||
fn custom_shape_presets_forward_pixel_alignment_without_changing_preset_geometry() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60]})).unwrap();
|
||||
let preset = s.execute("shape.presets.new", json!({"name":"Pixel Alignment Regression"})).unwrap();
|
||||
let mut placed_path = None;
|
||||
for (index, value) in [true, false].into_iter().enumerate() {
|
||||
s.execute("shape.presets.place", json!({"preset":preset["name"],"rect":[10,10,60,60],"useAlignedRendering":value,"stroke":{"width":1}})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], value);
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, format!("{} {}", preset["name"].as_str().unwrap(), index + 1));
|
||||
let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
if let Some(expected) = &placed_path {
|
||||
assert_eq!(&shape.path, expected, "alignment must not alter placed preset geometry");
|
||||
} else {
|
||||
placed_path = Some(shape.path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The rendering rule, against the reference application's measured pixels: a black shape on a
|
||||
// white 64x64 canvas, the red channel 0 = covered, 255 = empty. Our antialiasing is plain area
|
||||
// coverage, so a half-covered pixel reads 128 where the reference reads 120-135: those cases check
|
||||
// the structure (partly covered) rather than the exact byte.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Every red value (0..255) of the flattened document, row by row.
|
||||
fn reds(s: &Session) -> Vec<u8> {
|
||||
photocraft_compose::flatten(&s.active().unwrap().doc).px.iter().map(|p| (p[0].clamp(0.0, 1.0) * 255.0).round() as u8).collect()
|
||||
}
|
||||
|
||||
/// The red value at (x, y).
|
||||
fn red(s: &Session, x: usize, y: usize) -> u8 {
|
||||
reds(s)[y * 64 + x]
|
||||
}
|
||||
|
||||
/// The red values of row `y` at `cols`.
|
||||
fn row(s: &Session, y: usize, cols: &[usize]) -> Vec<u8> {
|
||||
let px = reds(s);
|
||||
cols.iter().map(|&x| px[y * 64 + x]).collect()
|
||||
}
|
||||
|
||||
/// A white 64x64 document with one black shape made by `shape.create` with `params`, Align Edges as given.
|
||||
fn shape_doc(mut params: serde_json::Value, aligned: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":64,"height":64,"background":"white"})).unwrap();
|
||||
if params.get("fill").is_none() {
|
||||
params["fill"] = json!("#000000");
|
||||
}
|
||||
params["useAlignedRendering"] = json!(aligned);
|
||||
s.execute("shape.create", params).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// `[x0, y0, w, h]` filled black.
|
||||
fn rect_doc(rect: [f64; 4], aligned: bool) -> Session {
|
||||
shape_doc(json!({"kind":"rect","rect":rect}), aligned)
|
||||
}
|
||||
|
||||
/// Reference: rectangle 10.5..30.5, fill only. On: column 10 empty, column 30 covered (the shape
|
||||
/// moved to 11..31). Off: both soft (reference 135 / 120).
|
||||
#[test]
|
||||
fn align_edges_moves_a_half_pixel_rectangle_to_whole_pixels() {
|
||||
let on = rect_doc([10.5, 10.5, 20.0, 20.0], true);
|
||||
assert_eq!(row(&on, 20, &[10, 11, 30, 31]), [255, 0, 0, 255]);
|
||||
assert_eq!(red(&on, 20, 10), 255, "the top edge moved down too");
|
||||
assert_eq!(red(&on, 20, 11), 0);
|
||||
let off = rect_doc([10.5, 10.5, 20.0, 20.0], false);
|
||||
for v in row(&off, 20, &[10, 30]) {
|
||||
assert!((100..=160).contains(&v), "soft edge without Align Edges: {v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference: the left edge rounds to the nearest pixel (a half up) and the width rounds too.
|
||||
/// 10.25..30.75 covers 10..31; 10.4..30.6 covers 10..30; 10.75..30.25 and 10.6..30.4 cover 11..31.
|
||||
#[test]
|
||||
fn align_edges_rounds_the_left_edge_and_the_width() {
|
||||
for (x0, x1, first, last) in [(10.25, 30.75, 10, 30), (10.4, 30.6, 10, 29), (10.75, 30.25, 11, 30), (10.6, 30.4, 11, 30)] {
|
||||
let s = rect_doc([x0, 10.0, x1 - x0, 20.0], true);
|
||||
let got = row(&s, 20, &[first - 1, first, last, last + 1]);
|
||||
assert_eq!(got, [255, 0, 0, 255], "{x0}..{x1} covers {first}..={last}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference: ellipse 10.5..40.5 moves to 11..41 (columns 10/11/40/41 = 255/6/6/255 on the middle
|
||||
/// row) and is moved, not bent: the curve pixels (15,15) and (36,36), mirror images about the new
|
||||
/// centre (26,26), read the same (82/82). The curve keeps its antialiasing.
|
||||
#[test]
|
||||
fn align_edges_moves_an_ellipse_without_bending_its_curve() {
|
||||
let on = shape_doc(json!({"kind":"ellipse","rect":[10.5,10.5,30.0,30.0]}), true);
|
||||
let mid = row(&on, 25, &[10, 11, 40, 41]);
|
||||
assert_eq!((mid[0], mid[3]), (255, 255), "{mid:?}");
|
||||
assert!(mid[1] < 40 && mid[2] < 40, "almost covered at the extremes: {mid:?}");
|
||||
let (a, b) = (red(&on, 15, 15), red(&on, 36, 36));
|
||||
assert!(a.abs_diff(b) <= 2, "symmetric about the moved centre: {a} vs {b}");
|
||||
assert!((60..=110).contains(&a), "the curve stays antialiased (reference 82): {a}");
|
||||
// Without Align Edges the same two pixels are not mirror images (centre 25.5).
|
||||
let off = shape_doc(json!({"kind":"ellipse","rect":[10.5,10.5,30.0,30.0]}), false);
|
||||
assert!(red(&off, 15, 15).abs_diff(red(&off, 36, 36)) > 20);
|
||||
}
|
||||
|
||||
/// Reference: ellipse 10.75..40.25 covers 11..41, 10.4..40.6 covers 10..40, and an ellipse on whole
|
||||
/// pixels is unchanged.
|
||||
#[test]
|
||||
fn align_edges_ellipse_bounds_round_like_rectangles() {
|
||||
for (x0, x1, first, last) in [(10.75, 40.25, 11, 40), (10.4, 40.6, 10, 39)] {
|
||||
let s = shape_doc(json!({"kind":"ellipse","rect":[x0, x0, x1 - x0, x1 - x0]}), true);
|
||||
let y = (first + last + 1) / 2;
|
||||
let got = row(&s, y, &[first - 1, first, last, last + 1]);
|
||||
assert_eq!((got[0], got[3]), (255, 255), "{x0}..{x1}: {got:?}");
|
||||
assert!(got[1] < 60 && got[2] < 60, "{x0}..{x1}: {got:?}");
|
||||
}
|
||||
let on = shape_doc(json!({"kind":"ellipse","rect":[10.0,10.0,30.0,30.0]}), true);
|
||||
let off = shape_doc(json!({"kind":"ellipse","rect":[10.0,10.0,30.0,30.0]}), false);
|
||||
assert_eq!(reds(&on), reds(&off));
|
||||
}
|
||||
|
||||
/// Reference: a 1 px centred stroke on rectangle 10..30 (no fill) paints columns 10 and 30 (its
|
||||
/// outer edge 9.5..30.5 moves to 10..31); with a fill, column 30 is covered.
|
||||
#[test]
|
||||
fn align_edges_one_pixel_stroke_lands_on_whole_columns() {
|
||||
for fill in [false, true] {
|
||||
let mut p = json!({"kind":"rect","rect":[10.0,10.0,20.0,20.0],"stroke":{"width":1,"color":"#000000"}});
|
||||
if !fill {
|
||||
p["fill"] = serde_json::Value::Null;
|
||||
}
|
||||
let s = shape_doc(p, true);
|
||||
let got = row(&s, 20, &[9, 10, 11, 29, 30, 31]);
|
||||
let inside = if fill { 0 } else { 255 };
|
||||
assert_eq!(got, [255, 0, inside, inside, 0, 255], "fill={fill}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference: 1 px stroke on rectangle 10.25..30.25 paints columns 10 and 30; 2 px paints 9-10 and
|
||||
/// 29-30; 3 px on rectangle 10..30 paints 9-11 and 29-31.
|
||||
#[test]
|
||||
fn align_edges_strokes_snap_by_their_outer_edge() {
|
||||
let stroked =
|
||||
|x: f64, width: u32| shape_doc(json!({"kind":"rect","rect":[x, 10.0, 20.0, 20.0],"fill":null,"stroke":{"width":width,"color":"#000000"}}), true);
|
||||
let s = stroked(10.25, 1);
|
||||
assert_eq!(row(&s, 20, &[9, 10, 11, 29, 30, 31]), [255, 0, 255, 255, 0, 255]);
|
||||
let s = stroked(10.25, 2);
|
||||
assert_eq!(row(&s, 20, &[8, 9, 10, 11, 28, 29, 30, 31]), [255, 0, 0, 255, 255, 0, 0, 255]);
|
||||
let s = stroked(10.0, 3);
|
||||
assert_eq!(row(&s, 20, &[8, 9, 10, 11, 12, 28, 29, 30, 31, 32]), [255, 0, 0, 0, 255, 255, 0, 0, 0, 255]);
|
||||
}
|
||||
|
||||
/// Reference: fill + 1 px stroke at 10.5 is already on whole pixels (outer edge 10..31): column 10
|
||||
/// covered, the same on and off.
|
||||
#[test]
|
||||
fn align_edges_leaves_an_already_aligned_shape_alone() {
|
||||
let p = json!({"kind":"rect","rect":[10.5,10.5,20.0,20.0],"stroke":{"width":1,"color":"#000000"}});
|
||||
let on = shape_doc(p.clone(), true);
|
||||
assert_eq!(red(&on, 10, 20), 0);
|
||||
assert_eq!(reds(&on), reds(&shape_doc(p, false)));
|
||||
}
|
||||
|
||||
/// Reference: a rectangle rotated 30 degrees moves with its bounding box (row 20 columns 7/8 went
|
||||
/// 252 -> 130 and 44 -> 0); its diagonal edges keep their antialiasing. Here a 20 px square about
|
||||
/// (30, 30) rotated 30 degrees spans 16.34..43.66; aligned it spans 16..43.
|
||||
#[test]
|
||||
fn align_edges_moves_a_rotated_rectangle_by_its_bounding_box() {
|
||||
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let corner = |dx: f64, dy: f64| [30.0 + dx * c - dy * s, 30.0 + dx * s + dy * c];
|
||||
let knots = [corner(-10.0, -10.0), corner(10.0, -10.0), corner(10.0, 10.0), corner(-10.0, 10.0)];
|
||||
let p = json!({"kind":"path","path":{"subpaths":[{"closed":true,"knots":knots}]}});
|
||||
let columns = |sess: &Session| {
|
||||
let px = reds(sess);
|
||||
(0..64).map(|x| (0..64).map(|y| px[y * 64 + x]).min().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
let on = columns(&shape_doc(p.clone(), true));
|
||||
assert_eq!((on[15], on[43]), (255, 255), "nothing outside 16..43");
|
||||
assert!(on[16] < 255 && on[42] < 255);
|
||||
let off = columns(&shape_doc(p.clone(), false));
|
||||
assert!(off[43] < 255, "unaligned it reaches into column 43");
|
||||
let all = reds(&shape_doc(p, true));
|
||||
assert!(all.iter().filter(|v| **v > 0 && **v < 255).count() > 40, "diagonal edges stay antialiased");
|
||||
}
|
||||
|
||||
/// Reference: Pen triangle (10.5,10.5) (30.5,10.5) (10.5,30.5), row 15: column 25 covered, column
|
||||
/// 26 half (127). The whole triangle moved by half a pixel on both axes.
|
||||
#[test]
|
||||
fn align_edges_moves_a_pen_triangle() {
|
||||
let p = json!({"kind":"path","path":{"subpaths":[{"closed":true,"knots":[[10.5,10.5],[30.5,10.5],[10.5,30.5]]}]}});
|
||||
let s = shape_doc(p, true);
|
||||
assert_eq!(red(&s, 25, 15), 0);
|
||||
assert!(red(&s, 26, 15).abs_diff(127) <= 8, "{}", red(&s, 26, 15));
|
||||
}
|
||||
|
||||
/// Reference: two rectangles in one layer: only the outer bounds snap, the inner edges stay soft
|
||||
/// (225/225). Here 10.5..21.25 and 25.75..40.5 move by +0.5 to 11..21.75 and 26.25..41.
|
||||
#[test]
|
||||
fn align_edges_does_not_snap_inner_edges_of_several_subpaths() {
|
||||
let rect = |x0: f64, x1: f64| json!({"closed":true,"knots":[[x0,10.0],[x1,10.0],[x1,30.0],[x0,30.0]]});
|
||||
let p = json!({"kind":"path","path":{"subpaths":[rect(10.5, 21.25), rect(25.75, 40.5)]}});
|
||||
let s = shape_doc(p, true);
|
||||
assert_eq!(row(&s, 20, &[10, 11, 40, 41]), [255, 0, 0, 255], "outer edges on whole pixels");
|
||||
for x in [21, 26] {
|
||||
let v = red(&s, x, 20);
|
||||
assert!(v > 0 && v < 255, "inner edge at column {x} stays soft: {v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Predicted (the reference's Line tool could not be driven by script): a 1 px line at y = 20 paints
|
||||
/// the band 19.5..20.5, which Align Edges moves to row 20.
|
||||
#[test]
|
||||
fn align_edges_line_lands_on_one_row() {
|
||||
let s = shape_doc(json!({"kind":"line","from":[10.0,20.0],"to":[50.0,20.0],"weight":1}), true);
|
||||
let col: Vec<u8> = (18..23).map(|y| red(&s, 30, y)).collect();
|
||||
assert_eq!(col, [255, 255, 0, 255, 255]);
|
||||
}
|
||||
|
||||
/// Turning Align Edges on changes only the rendering: the stored path stays (10.5 stays 10.5), and
|
||||
/// turning it off again renders the original soft pixels.
|
||||
#[test]
|
||||
fn align_edges_is_render_only_and_off_restores_the_soft_pixels() {
|
||||
let mut s = rect_doc([10.5, 10.5, 20.0, 20.0], false);
|
||||
let soft = reds(&s);
|
||||
let path = s.execute("shape.info", json!({})).unwrap()["path"].clone();
|
||||
let on = s.execute("shape.edit", json!({"useAlignedRendering":true})).unwrap();
|
||||
assert_eq!(on["path"], path, "the anchors stay where they were");
|
||||
assert_ne!(reds(&s), soft);
|
||||
s.execute("shape.edit", json!({"useAlignedRendering":false})).unwrap();
|
||||
assert_eq!(reds(&s), soft);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_ne!(reds(&s), soft, "undo brings the aligned pixels back");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod actions_panel_menu;
|
||||
mod actions_record_again;
|
||||
mod actions_single_history;
|
||||
mod affinity;
|
||||
mod align_edges;
|
||||
mod artboard_export_names;
|
||||
mod artboard_move_overflow;
|
||||
mod atn_adjustment_make_props;
|
||||
@@ -165,7 +166,6 @@ mod path_transform_target;
|
||||
mod pdn;
|
||||
mod pen_path_append;
|
||||
mod photoshop_oracles;
|
||||
mod pixel_align_stroke;
|
||||
mod pixel_lock_edits;
|
||||
mod place_steps_measure;
|
||||
mod precheck;
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
/// Make Shape preserves source geometry, defaults to legacy, and records conversion atomically.
|
||||
#[test]
|
||||
fn pixel_align_make_shape_supports_work_saved_and_inline_paths() {
|
||||
for source in ["work", "saved", "inline"] {
|
||||
for enabled in [None, Some(false), Some(true)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let path = json!({"subpaths":[{"closed":true,"knots":[[10,10],[50,10],[50,50]]}]});
|
||||
s.execute("path.set", json!({"name":"work","path":path})).unwrap();
|
||||
let expected = s.active().unwrap().doc.work_path.clone().unwrap();
|
||||
let mut params = json!({"fill":null,"stroke":{"width":1}});
|
||||
match source {
|
||||
"work" => params["name"] = json!("work"),
|
||||
"saved" => {
|
||||
s.execute("path.set", json!({"name":"Saved","path":path})).unwrap();
|
||||
params["name"] = json!("Saved");
|
||||
}
|
||||
_ => params["path"] = path,
|
||||
}
|
||||
if let Some(value) = enabled {
|
||||
params["useAlignedRendering"] = json!(value);
|
||||
}
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let info = s.execute("path.toShape", params).unwrap();
|
||||
assert_eq!(info["useAlignedRendering"], enabled.unwrap_or(false), "source={source}");
|
||||
let st = s.active().unwrap();
|
||||
let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
assert_eq!(shape.path, expected);
|
||||
assert_eq!(st.doc.paths, before.paths);
|
||||
assert_eq!(st.doc.work_path.is_none(), source == "work");
|
||||
assert_eq!(st.history.past_len(), history + 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.work_path, before.work_path);
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len());
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
let redone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(redone["useAlignedRendering"], enabled.unwrap_or(false));
|
||||
assert_eq!(redone["path"], info["path"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid alignment values cannot consume a Work Path or alter document/history.
|
||||
#[test]
|
||||
fn pixel_align_make_shape_rejects_invalid_flag_atomically() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("path.set", json!({"path":{"subpaths":[{"knots":[[10,10],[40,10],[40,40]]}]}})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
for invalid in [json!(null), json!("true"), json!(1), json!([]), json!({})] {
|
||||
assert!(s.execute("path.toShape", json!({"name":"work","useAlignedRendering":invalid})).is_err());
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete Stroke copies a snapshot of alignment and style, and pastes both in one undo step.
|
||||
#[test]
|
||||
fn complete_stroke_clipboard_preserves_pixel_alignment_and_geometry() {
|
||||
for enabled in [false, true] {
|
||||
for new_document in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let source = s
|
||||
.execute(
|
||||
"shape.create",
|
||||
json!({"kind":"rect","rect":[10,10,20,20],
|
||||
"useAlignedRendering":enabled,"stroke":{"width":1,"color":"#ff0000"}}),
|
||||
)
|
||||
.unwrap();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
s.execute("path.style.copyStroke", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history, "copy must not add history");
|
||||
// Editing the source after copying must not change the clipboard snapshot.
|
||||
s.execute("shape.edit", json!({"useAlignedRendering":!enabled,"stroke":null})).unwrap();
|
||||
assert!(s.execute("path.style.copyStroke", json!({})).is_err());
|
||||
if new_document {
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
}
|
||||
let before = s
|
||||
.execute(
|
||||
"shape.create",
|
||||
json!({"kind":"ellipse","rect":[40,40,30,30],
|
||||
"useAlignedRendering":!enabled,"fill":"#00ff00","stroke":{"width":3,"color":"#0000ff"}}),
|
||||
)
|
||||
.unwrap();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let after = s.execute("path.style.pasteStroke", json!({})).unwrap();
|
||||
assert_eq!(after["useAlignedRendering"], enabled, "new_document={new_document}");
|
||||
assert_eq!(after["stroke"], source["stroke"]);
|
||||
assert_eq!(after["path"], before["path"]);
|
||||
assert_eq!(after["fill"], before["fill"]);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let undone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(undone["useAlignedRendering"], !enabled);
|
||||
assert_eq!(undone["stroke"], before["stroke"]);
|
||||
assert_eq!(undone["path"], before["path"]);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
let redone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(redone["useAlignedRendering"], enabled);
|
||||
assert_eq!(redone["stroke"], source["stroke"]);
|
||||
assert_eq!(redone["path"], before["path"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Appending honors an explicit flag, preserves an omitted flag, and undoes both atomically.
|
||||
#[test]
|
||||
fn pixel_align_append_honors_explicit_values_and_preserves_omission() {
|
||||
for initial in [false, true] {
|
||||
for explicit in [None, Some(false), Some(true)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
let before = s.execute("shape.create", json!({"kind":"rect","rect":[10,10,20,20],"useAlignedRendering":initial})).unwrap();
|
||||
let mut params = json!({"kind":"rect","rect":[50,50,20,20],"addTo":before["layer"]});
|
||||
if let Some(value) = explicit {
|
||||
params["useAlignedRendering"] = json!(value);
|
||||
}
|
||||
let after = s.execute("shape.create", params).unwrap();
|
||||
assert_eq!(after["useAlignedRendering"], explicit.unwrap_or(initial));
|
||||
assert_ne!(after["path"], before["path"]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let undone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(undone["useAlignedRendering"], initial);
|
||||
assert_eq!(undone["path"], before["path"]);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], explicit.unwrap_or(initial));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid flag types leave history intact, and undo/redo changes only the rendering option.
|
||||
#[test]
|
||||
fn pixel_align_shape_commands_preserve_path_and_undo_and_validate_bool() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100,"background":"transparent"})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60],"stroke":{"width":1}})).unwrap();
|
||||
let legacy = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(legacy["useAlignedRendering"], false);
|
||||
let path = legacy["path"].clone();
|
||||
let on = s.execute("shape.edit", json!({"useAlignedRendering":true})).unwrap();
|
||||
assert_eq!(on["useAlignedRendering"], true);
|
||||
assert_eq!(on["path"], path);
|
||||
assert!(s.execute("shape.edit", json!({"useAlignedRendering":"true"})).is_err());
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], true);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], false);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], true);
|
||||
}
|
||||
|
||||
/// Placement forwards either explicit alignment value through the custom-shape preset command.
|
||||
#[test]
|
||||
fn custom_shape_presets_forward_pixel_alignment_without_changing_preset_geometry() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.create", json!({"kind":"rect","rect":[10,10,60,60]})).unwrap();
|
||||
let preset = s.execute("shape.presets.new", json!({"name":"Pixel Alignment Regression"})).unwrap();
|
||||
let mut placed_path = None;
|
||||
for (index, value) in [true, false].into_iter().enumerate() {
|
||||
s.execute("shape.presets.place", json!({"preset":preset["name"],"rect":[10,10,60,60],"useAlignedRendering":value,"stroke":{"width":1}})).unwrap();
|
||||
assert_eq!(s.execute("shape.info", json!({})).unwrap()["useAlignedRendering"], value);
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, format!("{} {}", preset["name"].as_str().unwrap(), index + 1));
|
||||
let photocraft_doc::LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") };
|
||||
if let Some(expected) = &placed_path {
|
||||
assert_eq!(&shape.path, expected, "alignment must not alter placed preset geometry");
|
||||
} else {
|
||||
placed_path = Some(shape.path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_psd_integer_translation_retains_coordinate_allowance() {
|
||||
use photocraft_doc::{Color, Fill, LayerContent, ShapeLayer, ShapeStroke};
|
||||
use photocraft_geom::{Affine, Rect};
|
||||
use photocraft_vector::{CompiledShape, DEFAULT_TOLERANCE, shapes};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":1000,"height":1000})).unwrap();
|
||||
let result = s.execute("shape.create", json!({"rect":[10,10,60,60]})).unwrap();
|
||||
let id = photocraft_doc::LayerId(result["layer"].as_u64().unwrap());
|
||||
let quantize = |v: f64| (v / 1000.0 * 16_777_216.0).round() / 16_777_216.0 * 1000.0;
|
||||
let sh = ShapeLayer {
|
||||
path: shapes::rect(quantize(10.0), quantize(10.0), quantize(70.0) - quantize(10.0), quantize(70.0) - quantize(10.0)),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke { width: 1.0, paint: Fill::Solid(Color::BLACK), ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
psd_raw: Some(std::sync::Arc::new(Vec::new())),
|
||||
psd_coordinate_frame: Some([1000, 1000]),
|
||||
..Default::default()
|
||||
};
|
||||
std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().content = LayerContent::Shape(sh.clone());
|
||||
let canvas = Rect::new(0, 0, 1000, 1000);
|
||||
let before = CompiledShape::new(&sh, DEFAULT_TOLERANCE, canvas).render_rgba(Rect::new(0, 0, 80, 80));
|
||||
s.execute("shape.edit", json!({"layer":id.0,"transform":[1,0,0,1,3,5]})).unwrap();
|
||||
let LayerContent::Shape(moved) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("shape") };
|
||||
assert!(moved.psd_raw.is_none());
|
||||
assert_eq!(moved.psd_coordinate_frame, Some([1000, 1000]));
|
||||
assert_eq!(moved.path, sh.path.transform(&Affine::translate(3.0, 5.0)));
|
||||
assert_eq!(CompiledShape::new(moved, DEFAULT_TOLERANCE, canvas).render_rgba(Rect::new(3, 5, 83, 85)), before);
|
||||
s.undo();
|
||||
let LayerContent::Shape(restored) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("shape") };
|
||||
assert_eq!(restored.path, sh.path);
|
||||
s.redo();
|
||||
s.execute("shape.edit", json!({"layer":id.0,"transform":[1,0,0,1,0.25,0]})).unwrap();
|
||||
let LayerContent::Shape(fractional) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("shape") };
|
||||
assert!(fractional.psd_coordinate_frame.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_round2_grid_transforms_conversion_and_point_edits() {
|
||||
use photocraft_doc::LayerContent;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":1000,"height":2000})).unwrap();
|
||||
s.execute("shape.create", json!({"rect":[10,10,60,60],"useAlignedRendering":true})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let LayerContent::Shape(sh) = &mut std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().content else { panic!() };
|
||||
sh.psd_coordinate_frame = Some([1000, 2000]);
|
||||
for (matrix, frame) in [(json!([-1, 0, 0, 1, 100, 0]), [1000, 2000]), (json!([0, 1, -1, 0, 100, 0]), [2000, 1000])] {
|
||||
s.execute("shape.edit", json!({"layer":id.0,"transform":matrix})).unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!() };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some(frame));
|
||||
s.undo();
|
||||
}
|
||||
s.execute("path.toShape", json!({"name":"layer","useAlignedRendering":true,"stroke":{"width":1}})).unwrap();
|
||||
let copied = s.active().unwrap().active_layer.unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(copied).unwrap().content else { panic!() };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some([1000, 2000]));
|
||||
s.execute("path.moveAnchors", json!({"name":"layer","layer":copied.0,"anchors":[[0,0]],"move":[0.00001,0]})).unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(copied).unwrap().content else { panic!() };
|
||||
assert!(sh.psd_coordinate_frame.is_none());
|
||||
s.undo();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(copied).unwrap().content else { panic!() };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some([1000, 2000]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_unchanged_path_and_whole_path_grid_move_keep_provenance() {
|
||||
use photocraft_doc::LayerContent;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":1000,"height":1000})).unwrap();
|
||||
let info = s.execute("shape.create", json!({"rect":[10,10,60,60],"useAlignedRendering":true})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let LayerContent::Shape(sh) = &mut std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().content else { panic!() };
|
||||
sh.psd_coordinate_frame = Some([1000, 1000]);
|
||||
s.execute("shape.edit", json!({"layer":id.0,"path":info["path"]})).unwrap();
|
||||
s.execute("path.moveAnchors", json!({"name":"layer","anchors":[[0,0],[0,1],[0,2],[0,3]],"move":[3,5]})).unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!() };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some([1000, 1000]));
|
||||
}
|
||||
|
||||
/// Prior floating transforms can leave low mantissa bits while retaining PSD provenance.
|
||||
/// Whole-path integer edits must preserve that provenance across binade boundaries.
|
||||
#[test]
|
||||
fn pixel_align_grid_move_recovers_rounded_integer_offsets() {
|
||||
use photocraft_doc::LayerContent;
|
||||
for (coordinate, delta) in [(10.000000600000002_f64, 10.0), (-10.000000599999998, -10.0), (131070.00000003002, 10.0)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.create", json!({"rect":[coordinate,coordinate,20,20],"useAlignedRendering":true})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let LayerContent::Shape(sh) = &mut std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().content else { panic!("shape") };
|
||||
sh.psd_coordinate_frame = Some([300_000, 300_000]);
|
||||
let before = sh.path.clone();
|
||||
let first = before.subpaths[0].knots[0].anchor;
|
||||
assert_ne!((first.x + delta) - first.x, delta, "stored path must exercise subtraction roundoff");
|
||||
s.execute("path.moveAnchors", json!({"name":"layer","anchors":[[0,0],[0,1],[0,2],[0,3]],"move":[delta,delta]})).unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("shape") };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some([300_000, 300_000]));
|
||||
assert_eq!(sh.path, before.transform(&photocraft_geom::Affine::translate(delta, delta)), "stored coordinates must not be rounded");
|
||||
}
|
||||
}
|
||||
|
||||
/// A near-integer recovered delta alone does not prove a whole-path grid translation.
|
||||
#[test]
|
||||
fn pixel_align_grid_move_rejects_fractional_or_partial_offsets() {
|
||||
use photocraft_doc::LayerContent;
|
||||
for (anchors, dx) in [(json!([[0, 0], [0, 1], [0, 2], [0, 3]]), 10.0 + 5e-13), (json!([[0, 0]]), 10.0)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.create", json!({"rect":[10.0000006,10.0000006,20,20]})).unwrap();
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
let LayerContent::Shape(sh) = &mut std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().content else { panic!("shape") };
|
||||
sh.psd_coordinate_frame = Some([1000, 1000]);
|
||||
s.execute("path.moveAnchors", json!({"name":"layer","anchors":anchors,"move":[dx,10]})).unwrap();
|
||||
let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("shape") };
|
||||
assert!(sh.psd_coordinate_frame.is_none());
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,6 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
|
||||
path: s.path.clone(),
|
||||
stroke: s.stroke.clone(),
|
||||
use_aligned_rendering: s.use_aligned_rendering,
|
||||
psd_coordinate_frame: s.psd_coordinate_frame,
|
||||
// Older PhotoCraft versions cannot deserialize ArrowLine.
|
||||
// The saved path preserves the arrow's visual appearance.
|
||||
live: match &s.live {
|
||||
@@ -461,7 +460,7 @@ impl Loader<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
fn layer(&mut self, m: &LayerM, depth: usize, frame: [u32; 2]) -> Result<Layer> {
|
||||
fn layer(&mut self, m: &LayerM, depth: usize) -> Result<Layer> {
|
||||
if depth > MAX_GROUP_DEPTH {
|
||||
return Err(too_deep());
|
||||
}
|
||||
@@ -471,18 +470,10 @@ impl Loader<'_> {
|
||||
if let ContentM::Group { children: kids, .. } = &m.content {
|
||||
children.reserve(kids.len());
|
||||
for c in kids {
|
||||
children.push(self.layer(c, depth + 1, frame)?);
|
||||
children.push(self.layer(c, depth + 1)?);
|
||||
}
|
||||
}
|
||||
let mut layer = self.layer_with(m, children)?;
|
||||
// Older native files predate explicit PSD coordinate provenance.
|
||||
if let LayerContent::Shape(shape) = &mut layer.content
|
||||
&& shape.psd_raw.is_some()
|
||||
&& shape.psd_coordinate_frame.is_none()
|
||||
{
|
||||
shape.psd_coordinate_frame = Some(frame);
|
||||
}
|
||||
Ok(layer)
|
||||
self.layer_with(m, children)
|
||||
}
|
||||
|
||||
/// One layer, given its already converted group children.
|
||||
@@ -515,36 +506,24 @@ impl Loader<'_> {
|
||||
warp: warp.clone(),
|
||||
})
|
||||
}
|
||||
ContentM::Shape {
|
||||
fill,
|
||||
cache,
|
||||
psd_raw,
|
||||
path,
|
||||
stroke,
|
||||
use_aligned_rendering,
|
||||
psd_coordinate_frame,
|
||||
live,
|
||||
arrow_live,
|
||||
triangle_live,
|
||||
density,
|
||||
feather,
|
||||
} => LayerContent::Shape(ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: fill.clone(),
|
||||
stroke: stroke.clone(),
|
||||
use_aligned_rendering: *use_aligned_rendering,
|
||||
psd_coordinate_frame: *psd_coordinate_frame,
|
||||
live: arrow_live
|
||||
.as_ref()
|
||||
.filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. }))
|
||||
.or_else(|| triangle_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::Triangle { .. })))
|
||||
.cloned()
|
||||
.or_else(|| live.clone()),
|
||||
cache: self.opt_surface(cache)?,
|
||||
psd_raw: self.opt_blob(psd_raw)?,
|
||||
density: *density,
|
||||
feather: *feather,
|
||||
}),
|
||||
ContentM::Shape { fill, cache, psd_raw, path, stroke, use_aligned_rendering, live, arrow_live, triangle_live, density, feather } => {
|
||||
LayerContent::Shape(ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: fill.clone(),
|
||||
stroke: stroke.clone(),
|
||||
use_aligned_rendering: *use_aligned_rendering,
|
||||
live: arrow_live
|
||||
.as_ref()
|
||||
.filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. }))
|
||||
.or_else(|| triangle_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::Triangle { .. })))
|
||||
.cloned()
|
||||
.or_else(|| live.clone()),
|
||||
cache: self.opt_surface(cache)?,
|
||||
psd_raw: self.opt_blob(psd_raw)?,
|
||||
density: *density,
|
||||
feather: *feather,
|
||||
})
|
||||
}
|
||||
ContentM::Smart {
|
||||
contents_id,
|
||||
source,
|
||||
@@ -662,7 +641,7 @@ impl Loader<'_> {
|
||||
max_ids(&m.layers, 0, &mut max)?;
|
||||
self.preserve_ids = reserve_ids_through(max);
|
||||
}
|
||||
let layers = m.layers.iter().map(|l| self.layer(l, 0, [m.size.width, m.size.height])).collect::<Result<Vec<_>>>()?;
|
||||
let layers = m.layers.iter().map(|l| self.layer(l, 0)).collect::<Result<Vec<_>>>()?;
|
||||
let mut channels = Vec::with_capacity(m.channels.len());
|
||||
for c in &m.channels {
|
||||
channels.push(self.channel(c)?);
|
||||
|
||||
@@ -293,11 +293,10 @@ pub enum ContentM {
|
||||
path: Path,
|
||||
#[serde(default)]
|
||||
stroke: Option<ShapeStroke>,
|
||||
/// Optional pixel alignment; absent in legacy files.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not", alias = "pixel_align_stroke")]
|
||||
/// Align Edges. Absent in files from before it existed, which keep rendering as they did
|
||||
/// (off); written only when on, so files without it stay readable by older versions.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
use_aligned_rendering: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
psd_coordinate_frame: Option<[u32; 2]>,
|
||||
#[serde(default)]
|
||||
live: Option<LiveShape>,
|
||||
/// Arrow parameters stored separately for backward compatibility.
|
||||
|
||||
@@ -157,7 +157,6 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
|
||||
dash_offset: 0.5,
|
||||
}),
|
||||
use_aligned_rendering: false,
|
||||
psd_coordinate_frame: Some([300, 280]),
|
||||
live: Some(LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [4.0, 0.0, 4.0, 0.0] }),
|
||||
cache: Some(cache.clone()),
|
||||
psd_raw: Some(blob(10, 30)),
|
||||
|
||||
@@ -1385,7 +1385,6 @@ fn use_aligned_rendering_roundtrips_and_defaults_for_legacy_files() {
|
||||
path: photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(10.0, 10.0), (70.0, 10.0), (70.0, 70.0), (10.0, 70.0)])]),
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
psd_coordinate_frame: Some([1000, 2000]),
|
||||
..Default::default()
|
||||
}),
|
||||
));
|
||||
@@ -1418,27 +1417,6 @@ fn use_aligned_rendering_roundtrips_and_defaults_for_legacy_files() {
|
||||
assert!(disabled_json.get("use_aligned_rendering").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_align_round2_legacy_psd_provenance_is_migrated() {
|
||||
let mut doc = rich_doc(ColorMode::Rgb, SampleType::U8);
|
||||
let layer = Layer::new(
|
||||
"legacy PSD",
|
||||
LayerContent::Shape(photocraft_doc::ShapeLayer {
|
||||
use_aligned_rendering: false,
|
||||
psd_raw: Some(std::sync::Arc::new(vec![1, 2, 3])),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let id = layer.id;
|
||||
doc.layers.push(layer);
|
||||
let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
|
||||
let loaded = load_from_bytes(&bytes).unwrap();
|
||||
let LayerContent::Shape(sh) = &loaded.layer(id).unwrap().content else { panic!() };
|
||||
assert_eq!(sh.psd_coordinate_frame, Some([doc.size.width, doc.size.height]));
|
||||
let saved = save_to_bytes(&loaded, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(load_from_bytes(&saved).unwrap(), loaded);
|
||||
}
|
||||
|
||||
/// `FileEncoding::source_images` is kept in `.pcraft` with the other encoder settings (#5733):
|
||||
/// the crash-recovery autosave is a `.pcraft` bundle reopened at the document's original path, so
|
||||
/// dropping the count would let Save write one frame over a multi-image file. A manifest written
|
||||
|
||||
@@ -570,7 +570,7 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut(
|
||||
LayerContent::Adjustment(a) => format!("{a:?}").hash(h),
|
||||
LayerContent::Shape(sh) => {
|
||||
format!("{:?}{:?}{:?}{:?}", sh.path, sh.fill, sh.stroke, sh.live).hash(h);
|
||||
(sh.use_aligned_rendering, sh.psd_coordinate_frame, sh.psd_raw.is_some(), sh.density.to_bits(), sh.feather.to_bits()).hash(h);
|
||||
(sh.use_aligned_rendering, sh.density.to_bits(), sh.feather.to_bits()).hash(h);
|
||||
if let Some(s) = &sh.cache {
|
||||
surface_fp(s, h, pin);
|
||||
}
|
||||
|
||||
@@ -327,7 +327,6 @@ fn group_key_tracks_uncached_shape_alignment() {
|
||||
let LayerContent::Group(g) = &mut group.content else { unreachable!() };
|
||||
let LayerContent::Shape(sh) = &mut g.children[0].content else { unreachable!() };
|
||||
sh.use_aligned_rendering = true;
|
||||
sh.psd_coordinate_frame = Some([1000, 2000]);
|
||||
assert_ne!(before, group_key(&group, &light, &mut |_| {}));
|
||||
}
|
||||
|
||||
|
||||
@@ -1120,7 +1120,7 @@ fn bounded_embedded_svg_gets_only_the_nesting_depth_the_drawing_left() {
|
||||
/// Each level of embedded SVG image adds the parser's and renderer's frames on top of the one it
|
||||
/// sits in. Every chain the bounded path takes (base64 grows each level, so the XML byte budget
|
||||
/// ends it before [`MAX_EMBEDDED_SVG_DEPTH`]) parses and renders on a 1 MB thread stack (Windows'
|
||||
/// main-thread size); over-budget images are omitted by the non-strict renderer.
|
||||
/// main-thread size); deeper ones are refused.
|
||||
#[test]
|
||||
fn the_deepest_chain_of_embedded_svg_images_fits_a_small_stack() {
|
||||
let chain = |levels: usize| {
|
||||
|
||||
@@ -518,7 +518,7 @@ pub fn vogk_bytes(s: &LiveShape, dpi: f32) -> Option<Vec<u8>> {
|
||||
// Shape layers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Adobe's layer-level `sn2P` block is a four-byte, nonzero-is-true value.
|
||||
/// The layer-level `sn2P` block (Align Edges) is a four-byte, nonzero-is-true value.
|
||||
/// It is independent of the `vstk` descriptor's Stroke Adjust property.
|
||||
fn aligned_rendering(data: &[u8]) -> Option<bool> {
|
||||
Some(u32::from_be_bytes(data.try_into().ok()?) != 0)
|
||||
@@ -531,7 +531,6 @@ pub fn shape_from_blocks(sh: &mut ShapeLayer, block: &dyn Fn(&[u8; 4]) -> Option
|
||||
&& let Some((p, _)) = path_from_vmsk(&d, w, h)
|
||||
{
|
||||
sh.path = p;
|
||||
sh.psd_coordinate_frame = Some([w, h]);
|
||||
}
|
||||
if let Some(f) = block(b"vscg").and_then(|d| fill_from_vscg(&d)) {
|
||||
sh.fill = Some(f);
|
||||
@@ -558,9 +557,13 @@ fn has_fill_block(raw: &[([u8; 4], Vec<u8>)]) -> bool {
|
||||
pub fn shape_blocks(sh: &ShapeLayer, raw: &mut Vec<([u8; 4], Vec<u8>)>, w: u32, h: u32, dpi: f32) {
|
||||
let find = |raw: &Vec<([u8; 4], Vec<u8>)>, k: &[u8; 4]| raw.iter().position(|(key, _)| key == k);
|
||||
// The layer's Align Edges setting, not the stroke's Stroke Adjust setting.
|
||||
// The reference application writes `sn2P` = 1 for on and leaves the block out for off.
|
||||
match find(raw, b"sn2P") {
|
||||
Some(i) if aligned_rendering(&raw[i].1).unwrap_or(false) == sh.use_aligned_rendering => {}
|
||||
Some(i) => raw[i].1 = u32::from(sh.use_aligned_rendering).to_be_bytes().to_vec(),
|
||||
Some(i) if sh.use_aligned_rendering => raw[i].1 = 1u32.to_be_bytes().to_vec(),
|
||||
Some(i) => {
|
||||
raw.remove(i);
|
||||
}
|
||||
None if sh.use_aligned_rendering => raw.push((*b"sn2P", 1u32.to_be_bytes().to_vec())),
|
||||
None => {}
|
||||
}
|
||||
@@ -875,8 +878,9 @@ mod align_edges_tests {
|
||||
assert_eq!(raw, unchanged);
|
||||
imported.use_aligned_rendering = !enabled;
|
||||
shape_blocks(&imported, &mut raw, 64, 64, 72.0);
|
||||
let data = &raw.iter().find(|(key, _)| key == b"sn2P").unwrap().1;
|
||||
assert_eq!(data, &u32::from(!enabled).to_be_bytes());
|
||||
// As the reference application saves it: `sn2P` = 1 when on, no block when off.
|
||||
let data = raw.iter().find(|(key, _)| key == b"sn2P").map(|(_, d)| d.clone());
|
||||
assert_eq!(data, (!enabled).then(|| 1u32.to_be_bytes().to_vec()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -904,35 +908,4 @@ mod align_edges_tests {
|
||||
assert_eq!(raw[0].1, data, "unchanged true values stay byte-identical");
|
||||
}
|
||||
}
|
||||
/// Layer-wide snapping no longer needs the old canvas quantum to sharpen a rectangle.
|
||||
#[test]
|
||||
fn pixel_alignment_narrowed_psd_canvas_keeps_crisp_edges_after_recolor() {
|
||||
let shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(10.0, 10.0, 60.0, 60.0),
|
||||
use_aligned_rendering: true,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
let mut raw = Vec::new();
|
||||
shape_blocks(&shape, &mut raw, 300_000, 300_000, 72.0);
|
||||
let mut imported = ShapeLayer::default();
|
||||
shape_from_blocks(&mut imported, &|key| raw.iter().find(|(k, _)| k == key).map(|(_, bytes)| bytes.clone()), 300_000, 300_000, 72.0);
|
||||
assert_ne!(imported.path, shape.path, "fixture must exercise PSD path quantization");
|
||||
shape_blocks(&imported, &mut raw, 1000, 1000, 72.0);
|
||||
let mut reopened = ShapeLayer::default();
|
||||
shape_from_blocks(&mut reopened, &|key| raw.iter().find(|(k, _)| k == key).map(|(_, bytes)| bytes.clone()), 1000, 1000, 72.0);
|
||||
assert_eq!(reopened.psd_coordinate_frame, Some([1000, 1000]));
|
||||
assert!(reopened.use_aligned_rendering);
|
||||
reopened.stroke.as_mut().unwrap().paint = Fill::Solid(photocraft_doc::Color::rgb(0.4, 0.2, 0.7));
|
||||
let path = reopened.path.clone();
|
||||
let rect = photocraft_geom::Rect::new(0, 0, 80, 80);
|
||||
let pixels = photocraft_vector::CompiledShape::new(&reopened, photocraft_vector::DEFAULT_TOLERANCE, rect).render_rgba(rect);
|
||||
for y in 0..80 {
|
||||
for x in 0..80 {
|
||||
let edge = (10..70).contains(&x) && (y == 10 || y == 69) || (10..70).contains(&y) && (x == 10 || x == 69);
|
||||
assert_eq!(pixels[y * 80 + x][3], f32::from(edge), "({x},{y})");
|
||||
}
|
||||
}
|
||||
assert_eq!(reopened.path, path);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-12
@@ -1,17 +1,10 @@
|
||||
# photocraft-raw
|
||||
|
||||
A pure-Rust camera raw developer over the shared `craft-raw` decoder. It has no `unsafe`,
|
||||
does no I/O (`&[u8]` in) and builds for `wasm32-unknown-unknown` (sequential there,
|
||||
rayon-parallel on native). The adapter enforces pixel and allocation limits before decoding.
|
||||
|
||||
Floating-point samples retain their source units and signed/HDR values until development;
|
||||
linearization is applied by the decoder, while polynomial corrections remain deferred.
|
||||
Explicit decoder notices preserve calibration and CFA fallback provenance. Non-DNG samples
|
||||
are not rewritten by the app's separate DNG clipping policy.
|
||||
|
||||
The adapter and fixture corrections follow [PhotoCraft #11029](https://github.com/storytold/photocraft/pull/11029).
|
||||
The fixes in [craft-libs #1300](https://github.com/storytold/craft-libs/pull/1300) are now merged;
|
||||
`craft-raw` uses the shared immutable revision pinned in the workspace manifest.
|
||||
A clean-room, pure-Rust camera raw decoder and developer. The crate is standalone (no workspace
|
||||
dependencies; its decoding dependencies are `flate2` for Deflate DNG and `jxl-oxide`, a pure-Rust
|
||||
JPEG XL decoder, for DNG 1.7, native builds only), has no `unsafe`, does no I/O (`&[u8]` in), builds for `wasm32-unknown-unknown`
|
||||
(sequential there, rayon-parallel on native) and never panics on hostile input: every offset is
|
||||
bounds-checked and sizes are checked against `Limits` before allocating.
|
||||
|
||||
```rust
|
||||
use photocraft_raw::{develop, DevelopOptions, Demosaic};
|
||||
|
||||
@@ -87,7 +87,7 @@ fn warnings(image: &craft_raw::RawImage) -> Vec<String> {
|
||||
out.push("raw default crop was invalid, incomplete or out-of-range; adjusted within the active area".into());
|
||||
}
|
||||
if image.notices.assumed_cfa {
|
||||
out.push("raw colour filter phase (Bayer phase) was not recorded or recognized; the decoder's fallback pattern was assumed".into());
|
||||
out.push("raw colour filter phase (Bayer phase) was not recorded or recognized; the decoder's fallback pattern was used".into());
|
||||
}
|
||||
// Unknown means the decoder has not annotated provenance; it does not mean
|
||||
// the file omitted its levels. Report only an explicit fallback decision.
|
||||
@@ -99,17 +99,17 @@ fn warnings(image: &craft_raw::RawImage) -> Vec<String> {
|
||||
out.push("raw white level not recorded in a documented tag; assumed full sample range".into());
|
||||
}
|
||||
}
|
||||
if image.notices.gain_table_omitted {
|
||||
out.push("the raw camera profile's invalid gain table map was omitted".to_string());
|
||||
}
|
||||
for op in image.opcodes.list1.iter().chain(&image.opcodes.list2).chain(&image.opcodes.list3) {
|
||||
if !matches!(op, craft_raw::Opcode::GainMap { .. } | craft_raw::Opcode::MapPolynomial { .. }) {
|
||||
out.push("some raw correction opcodes are not applied by PhotoCraft".to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if image.notices.gain_table_omitted {
|
||||
out.push("the raw camera profile's invalid ProfileGainTableMap (gain table map) was omitted".to_string());
|
||||
}
|
||||
if image.color.profile.gain_table_map.is_some() {
|
||||
out.push("the raw camera profile's ProfileGainTableMap (gain table map) is not applied by PhotoCraft".to_string());
|
||||
if image.notices.gain_table_omitted || image.color.profile.gain_table_map.is_some() {
|
||||
out.push("the raw camera profile's ProfileGainTableMap is not applied by PhotoCraft".to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ rustc-hash = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# The tables of craft-host's `SectionStore` (`app/framework.rs`); already linked through craft-host.
|
||||
toml = { version = "1.1", default-features = false, features = ["std", "serde", "display"] }
|
||||
toml = { version = "1.1", default-features = false, features = ["std", "serde"] }
|
||||
log = { workspace = true }
|
||||
base64 = "0.23"
|
||||
web-time = { workspace = true }
|
||||
@@ -58,7 +58,7 @@ web-time = { workspace = true }
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# `FilePanels::pump_with`: rfd's folder picker and file paths exist on native only. Agents in the
|
||||
# open window (`craft::automation::agents`: the link, the launcher's switch, the Agents page) too.
|
||||
craft = { workspace = true, features = ["dialogs", "update", "automation-agents", "ui-system_fonts"] }
|
||||
craft = { workspace = true, features = ["dialogs", "update", "automation-agents"] }
|
||||
rayon = { workspace = true }
|
||||
# Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency.
|
||||
sys-locale = "=0.3.2"
|
||||
|
||||
@@ -13,7 +13,6 @@ impl PhotocraftApp {
|
||||
/// (`request_discard`, such as a sizing pass) leaves the record open, so a frame is one
|
||||
/// record across all its passes.
|
||||
pub(crate) fn finish_frame(&mut self, ctx: &egui::Context, ui_ms: f64) {
|
||||
crate::shape_stroke_ui::finish_frame(self, ctx);
|
||||
self.perf.stage.ui_ms += ui_ms;
|
||||
self.perf.stage.stroking |= self.live_stroke.is_some();
|
||||
if ctx.will_discard() {
|
||||
|
||||
@@ -487,7 +487,7 @@ impl ToolSet {
|
||||
crate::paint_mouse::sync_tool_brush(app);
|
||||
}
|
||||
if let Some(value) = self.use_aligned_rendering {
|
||||
app.ui.tool_options.use_aligned_rendering = value;
|
||||
app.ui.tool_options.align_edges = value;
|
||||
}
|
||||
self.apply_gradient_and_trace(app);
|
||||
let eyedropper = &mut app.ui.tool_options.eyedropper;
|
||||
|
||||
@@ -2269,10 +2269,10 @@ fn ui_set_align_edges_uses_scripted_tool_option_name() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(call(&mut app, &ctx, "ui.set", json!({"useAlignedRendering": true}))["ok"], true);
|
||||
assert!(app.ui.tool_options.use_aligned_rendering);
|
||||
assert!(app.ui.tool_options.align_edges);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["useAlignedRendering"], true);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.set", json!({"useAlignedRendering": "true"}))["ok"], false);
|
||||
assert!(app.ui.tool_options.use_aligned_rendering);
|
||||
assert!(app.ui.tool_options.align_edges);
|
||||
}
|
||||
|
||||
/// A fresh app with a document, as a control client finds it, and the context the control channel runs on.
|
||||
|
||||
@@ -1700,16 +1700,11 @@ fn error_titles(app: &PhotocraftApp) -> Vec<String> {
|
||||
fn files_dropped_with_no_document_open_all_open() {
|
||||
let dir = scratch("home");
|
||||
let names = ["a.png", "b.jpg", "c.psd", "d.tif"];
|
||||
// TIFF opens use the typed IO path, including with an injected importer.
|
||||
// Give that path a real file rather than the fake importer's placeholder.
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":4,"height":4,"background":"white"})).unwrap();
|
||||
let tiff = photocraft_io::export(&session.active().unwrap().doc, "d.tif", &Default::default()).unwrap().bytes;
|
||||
let files: Vec<_> = names
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let p = dir.join(n);
|
||||
std::fs::write(&p, if *n == "d.tif" { tiff.as_slice() } else { b"x" }).unwrap();
|
||||
std::fs::write(&p, b"x").unwrap();
|
||||
dropped(p, Err("read from the path".into()))
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -689,7 +689,7 @@ fn shape_fill(app: &PhotocraftApp) -> Value {
|
||||
/// The `shape.presets.place` params of `key`: at its default place, or in a square centred on the document point under
|
||||
/// the drop at `at`.
|
||||
fn shape_place(app: &PhotocraftApp, key: &str, at: Option<Pos2>) -> Value {
|
||||
let mut params = json!({"preset": key, "fill": shape_fill(app), "useAlignedRendering": app.ui.tool_options.use_aligned_rendering});
|
||||
let mut params = json!({"preset": key, "fill": shape_fill(app), "useAlignedRendering": app.ui.tool_options.align_edges});
|
||||
if let Some(pos) = at
|
||||
&& let (Some(c), Some(d)) = (crate::canvas::document_display::doc_point_at(app, pos), app.session.active())
|
||||
{
|
||||
@@ -761,7 +761,7 @@ pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool,
|
||||
let r = run(
|
||||
app,
|
||||
"shape.presets.place",
|
||||
json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering}),
|
||||
json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke, "useAlignedRendering": app.ui.tool_options.align_edges}),
|
||||
);
|
||||
if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) {
|
||||
let template = "No custom shape \"{name}\": pick one in the options bar or Window › Shapes";
|
||||
|
||||
@@ -87,7 +87,7 @@ fn each_panel_uses_a_preset_its_own_way() {
|
||||
(
|
||||
SHAPES,
|
||||
PresetEvent::activate(item("Star"), none),
|
||||
run("shape.presets.place", json!({"preset": "Star", "fill": shape_fill(&app), "useAlignedRendering": app.ui.tool_options.use_aligned_rendering})),
|
||||
run("shape.presets.place", json!({"preset": "Star", "fill": shape_fill(&app), "useAlignedRendering": app.ui.tool_options.align_edges})),
|
||||
),
|
||||
(TOOL_PRESETS, PresetEvent::select(item("T"), none), Some(Act::ToolPreset("T".into()))),
|
||||
(TOOL_PRESETS, PresetEvent::activate(item("T"), none), Some(Act::ToolPreset("T".into()))),
|
||||
@@ -100,7 +100,7 @@ fn each_panel_uses_a_preset_its_own_way() {
|
||||
let drop = canvas_drop_rect(&app).center();
|
||||
let c = crate::canvas::document_display::doc_point_at(&app, drop).expect("the drop is on the canvas");
|
||||
let side = (48.0_f64 * 0.3).max(8.0);
|
||||
let expected = json!({"preset": "Star", "fill": shape_fill(&app), "useAlignedRendering": app.ui.tool_options.use_aligned_rendering, "rect": [c.x - side / 2.0, c.y - side / 2.0, side, side]});
|
||||
let expected = json!({"preset": "Star", "fill": shape_fill(&app), "useAlignedRendering": app.ui.tool_options.align_edges, "rect": [c.x - side / 2.0, c.y - side / 2.0, side, side]});
|
||||
assert_eq!(panel_act(&app, SHAPES, &PresetEvent::drop_at(item("Star"), drop, none)), run("shape.presets.place", expected));
|
||||
}
|
||||
|
||||
|
||||
@@ -146,10 +146,6 @@ pub struct ToolOptions {
|
||||
/// radius, polygon sides, line weight.
|
||||
pub shape_fill: bool,
|
||||
pub stroke_width: f32,
|
||||
/// Align fill and stroke edges of new shapes to document pixels.
|
||||
#[serde(default)]
|
||||
#[serde(rename = "useAlignedRendering", alias = "pixel_align_stroke")]
|
||||
pub use_aligned_rendering: bool,
|
||||
#[serde(default)]
|
||||
pub shape_stroke: crate::shape_stroke_ui::StrokeOptions,
|
||||
/// Shape tools: the gradient the next shape's fill / stroke takes (the swatches' Gradient
|
||||
@@ -157,9 +153,12 @@ pub struct ToolOptions {
|
||||
pub shape_fill_gradient: Option<photocraft_doc::Fill>,
|
||||
pub shape_stroke_gradient: Option<photocraft_doc::Fill>,
|
||||
pub corner_radius: f32,
|
||||
/// Shape tools' Align Edges: snap the drawn shape's box to whole pixels. On by default; the
|
||||
/// Triangle (#13370) and Rectangle (#13346) tools show it, enabled in Shape mode only; the other
|
||||
/// shape tools always snap.
|
||||
/// The shape tools' and the Pen's (Shape mode) one Align Edges checkbox, as in the reference
|
||||
/// application: a drag lands on whole pixels, and the new shape layer gets Align Edges
|
||||
/// (`ShapeLayer::use_aligned_rendering`), which fits it to whole pixels at render time. On by
|
||||
/// default and after Reset Tool; enabled in Shape mode only. Scripted and stored by the
|
||||
/// reference's name, `useAlignedRendering` (`align_edges` in older settings and presets).
|
||||
#[serde(rename = "useAlignedRendering", alias = "align_edges")]
|
||||
pub align_edges: bool,
|
||||
pub polygon_sides: u32,
|
||||
/// The Polygon tool's corner radius in px for the next polygon (#13302): its own, not the
|
||||
@@ -502,7 +501,6 @@ impl Default for ToolOptions {
|
||||
shape_mode: VectorMode::Shape,
|
||||
shape_fill: true,
|
||||
stroke_width: 0.0,
|
||||
use_aligned_rendering: false,
|
||||
shape_stroke: Default::default(),
|
||||
shape_fill_gradient: None,
|
||||
shape_stroke_gradient: None,
|
||||
|
||||
@@ -987,12 +987,6 @@ fn ui_fonts(ctx: &egui::Context, ui_language: &str) -> UiFonts<'static> {
|
||||
.craft_faces(&crate::cjk_fonts::craft_faces())
|
||||
.ui_language(ui_language)
|
||||
.emoji(emoji);
|
||||
// Headless passes cannot wait for the native index's repaint before strict glyph checks.
|
||||
// Use the same system faces, with a blocking lookup only in the test fixture.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
if let Some(provider) = craft::ui::fonts::system_font_provider(ui_language) {
|
||||
fonts = fonts.system_provider(provider);
|
||||
}
|
||||
if let Some(locale) = crate::cjk_fonts::os_locale() {
|
||||
fonts = fonts.os_locale(locale);
|
||||
}
|
||||
|
||||
@@ -158,18 +158,9 @@ fn tool_settings(o: &crate::state::ToolOptions, live: Option<&photocraft_doc::Li
|
||||
settings
|
||||
}
|
||||
|
||||
/// What the bar shows after the framework's cells for one tool: the Triangle's Align Edges and the
|
||||
/// Polygon's own corner radius.
|
||||
/// What the bar shows after the framework's cells for one tool: the Polygon's own corner radius.
|
||||
/// (Align Edges, every shape tool's, sits at the bar's right end: `vector_ui::alignment`.)
|
||||
fn tool_extras(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) {
|
||||
if tool == Tool::Triangle {
|
||||
Divider::vertical().show(ui);
|
||||
// Only a shape layer has pixel edges to align: greyed in Path mode (#13370).
|
||||
let shape_mode = app.ui.tool_options.shape_mode == VectorMode::Shape;
|
||||
let on = Checkbox::new(Bind::given(app.ui.tool_options.align_edges)).label(tl!("Snap Bounding Box").to_owned()).enabled(shape_mode).show(ui);
|
||||
if let Some(next) = on.value().copied() {
|
||||
app.ui.tool_options.align_edges = next;
|
||||
}
|
||||
}
|
||||
if tool == Tool::Polygon {
|
||||
// The tool's own corner radius for the next polygon, after Sides (#13302); the active shape is not touched.
|
||||
// A value typed past the Rectangle Radius's range takes the closest one and says so.
|
||||
@@ -363,7 +354,6 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
|
||||
// An `Err` is the alert that was not opened because one is already up.
|
||||
let _ = app.framework.dialogs.open_unless_open(HostedAlert::new(alert));
|
||||
}
|
||||
crate::vector_ui::alignment::shape_option(app, ui, target.as_ref().map(|s| s.layer), paint);
|
||||
if tool == Tool::CustomShape {
|
||||
crate::preset_panels::shape_picker(app, ui);
|
||||
}
|
||||
|
||||
@@ -161,221 +161,5 @@ pub fn paint_shape_preview(painter: &egui::Painter, shape: &photocraft_doc::Shap
|
||||
}
|
||||
}
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
mod document_preview;
|
||||
use document_preview::{PreviewLayout, PreviewReduction};
|
||||
|
||||
/// Cache document pixels independently of zoom: the view only transforms the textured quad.
|
||||
#[derive(Clone)]
|
||||
struct DocumentDragCache {
|
||||
shape: photocraft_doc::ShapeLayer,
|
||||
visible: photocraft_geom::Rect,
|
||||
canvas: photocraft_geom::Rect,
|
||||
bounds: photocraft_geom::Rect,
|
||||
texture: egui::TextureHandle,
|
||||
options: egui::TextureOptions,
|
||||
size: [usize; 2],
|
||||
factor: u32,
|
||||
reduction: Option<Arc<Mutex<PreviewReduction>>>,
|
||||
painted_pass: u64,
|
||||
}
|
||||
|
||||
fn document_preview_id(viewport: egui::ViewportId, layer: egui::LayerId) -> egui::Id {
|
||||
egui::Id::unique("shape-document-drag-render").with((viewport, layer))
|
||||
}
|
||||
|
||||
fn document_preview_registry() -> egui::Id {
|
||||
egui::Id::unique("shape-document-drag-views")
|
||||
}
|
||||
|
||||
/// Clip source coverage before choosing its bounded texture layout.
|
||||
fn document_preview_bounds(compiled: &photocraft_vector::CompiledShape, visible: photocraft_geom::Rect) -> Option<photocraft_geom::Rect> {
|
||||
let source = compiled.bounds()?;
|
||||
let clipped = source.intersect(&visible);
|
||||
if clipped.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Linear filtering needs transparent neighbors outside the tight shape bounds.
|
||||
// Reserve one reduced texel too, without exceeding the existing texture limit.
|
||||
let padding = clipped.width().max(clipped.height()).div_ceil(document_preview::TEXTURE_EDGE - 2).max(1) as i32;
|
||||
let bounds = photocraft_geom::Rect::new(
|
||||
source.x0.saturating_sub(padding),
|
||||
source.y0.saturating_sub(padding),
|
||||
source.x1.saturating_add(padding),
|
||||
source.y1.saturating_add(padding),
|
||||
)
|
||||
.intersect(&visible);
|
||||
(!bounds.is_empty()).then_some(bounds)
|
||||
}
|
||||
|
||||
/// Preserve native coverage when reducing a large preview, with one bounded pass per frame.
|
||||
fn new_document_preview(
|
||||
painter: &egui::Painter,
|
||||
shape: &photocraft_doc::ShapeLayer,
|
||||
visible: photocraft_geom::Rect,
|
||||
canvas: photocraft_geom::Rect,
|
||||
options: egui::TextureOptions,
|
||||
) -> Option<DocumentDragCache> {
|
||||
let compiled = photocraft_vector::CompiledShape::with_frames(shape, photocraft_vector::DEFAULT_TOLERANCE, visible, canvas);
|
||||
let bounds = document_preview_bounds(&compiled, visible)?;
|
||||
let layout = PreviewLayout::new(bounds)?;
|
||||
let (image, reduction, options) = if layout.factor == 1 {
|
||||
let rgba = compiled.render_rgba(bounds);
|
||||
let bytes: Vec<u8> = rgba.iter().flat_map(|p| p.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect();
|
||||
(egui::ColorImage::from_rgba_unmultiplied(layout.size, &bytes), None, options)
|
||||
} else {
|
||||
let mut work = PreviewReduction::new(compiled, layout);
|
||||
work.advance();
|
||||
if !work.complete() {
|
||||
// Keep the whole changing shape visible while exact document coverage is streamed.
|
||||
// Cap this extra raster at 512 pixels per axis, independently of document dimensions.
|
||||
let preview_factor = bounds.width().max(bounds.height()).div_ceil(512).max(layout.factor);
|
||||
let size = [bounds.width().div_ceil(preview_factor) as usize, bounds.height().div_ceil(preview_factor) as usize];
|
||||
let scale = 1.0 / f64::from(preview_factor);
|
||||
let mut proxy = shape.clone();
|
||||
proxy.path =
|
||||
proxy.path.transform(&photocraft_geom::Affine { m: [scale, 0.0, 0.0, scale, -f64::from(bounds.x0) * scale, -f64::from(bounds.y0) * scale] });
|
||||
proxy.live = None;
|
||||
proxy.use_aligned_rendering = false;
|
||||
proxy.feather *= scale as f32;
|
||||
if let Some(stroke) = &mut proxy.stroke {
|
||||
stroke.width *= scale as f32;
|
||||
}
|
||||
let output = photocraft_geom::Rect::new(0, 0, size[0] as i32, size[1] as i32);
|
||||
let frame = photocraft_geom::Rect::new(
|
||||
((f64::from(canvas.x0) - f64::from(bounds.x0)) * scale).floor() as i32,
|
||||
((f64::from(canvas.y0) - f64::from(bounds.y0)) * scale).floor() as i32,
|
||||
((f64::from(canvas.x1) - f64::from(bounds.x0)) * scale).ceil() as i32,
|
||||
((f64::from(canvas.y1) - f64::from(bounds.y0)) * scale).ceil() as i32,
|
||||
);
|
||||
let fallback = photocraft_vector::CompiledShape::with_frames(&proxy, photocraft_vector::DEFAULT_TOLERANCE, output, frame).render_rgba(output);
|
||||
let bytes: Vec<u8> = fallback
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
let mut rgba = p.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// A 1px document stroke can be below half an alpha byte in this
|
||||
// coarse proxy. Keep positive coverage until native pixels replace it.
|
||||
if p[3] > 0.0 && rgba[3] == 0 {
|
||||
rgba[3] = 1;
|
||||
}
|
||||
rgba
|
||||
})
|
||||
.collect();
|
||||
work.set_fallback(egui::ColorImage::from_rgba_unmultiplied(size, &bytes));
|
||||
}
|
||||
let image = work.image();
|
||||
let reduction = (!work.complete()).then(|| Arc::new(Mutex::new(work)));
|
||||
(image, reduction, egui::TextureOptions::LINEAR)
|
||||
};
|
||||
let texture = painter.ctx().load_texture("shape-document-drag", image, options);
|
||||
Some(DocumentDragCache {
|
||||
shape: shape.clone(),
|
||||
visible,
|
||||
canvas,
|
||||
bounds,
|
||||
texture,
|
||||
options,
|
||||
size: layout.size,
|
||||
factor: layout.factor,
|
||||
reduction,
|
||||
painted_pass: painter.ctx().cumulative_pass_nr_for(egui::ViewportId::ROOT),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rasterize aligned strokes in document pixels, then project that coverage into the view.
|
||||
/// Curves, diagonals and ineligible widths therefore retain committed antialiasing at any zoom.
|
||||
pub(crate) fn paint_document_shape_preview(
|
||||
painter: &egui::Painter,
|
||||
shape: &photocraft_doc::ShapeLayer,
|
||||
transform: &photocraft_geom::Affine,
|
||||
canvas: photocraft_geom::Rect,
|
||||
) {
|
||||
use photocraft_geom::{Point, Rect};
|
||||
let clip = painter.clip_rect();
|
||||
let Some(inverse) = transform.inverse() else { return };
|
||||
if !clip.is_finite() || clip.is_negative() {
|
||||
return;
|
||||
}
|
||||
let points = [clip.left_top(), clip.right_top(), clip.right_bottom(), clip.left_bottom()].map(|p| inverse.apply(Point::new(p.x as f64, p.y as f64)));
|
||||
let visible = Rect::new(
|
||||
(points.iter().map(|p| p.x).fold(f64::INFINITY, f64::min).floor() as i32).saturating_sub(1),
|
||||
(points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min).floor() as i32).saturating_sub(1),
|
||||
(points.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max).ceil() as i32).saturating_add(1),
|
||||
(points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max).ceil() as i32).saturating_add(1),
|
||||
);
|
||||
let id = document_preview_id(painter.ctx().viewport_id(), painter.layer_id());
|
||||
painter.ctx().data_mut(|d| {
|
||||
let views = d.get_temp_mut_or_default::<Vec<egui::Id>>(document_preview_registry());
|
||||
if !views.contains(&id) {
|
||||
views.push(id);
|
||||
}
|
||||
});
|
||||
// Exact pixel-grid zooms stay crisp. Other transforms filter document coverage just as
|
||||
// displaying a rotated or fractionally positioned rasterized document requires.
|
||||
let integer = |v: f64| (v - v.round()).abs() < 1e-6;
|
||||
let options = if transform.m[1].abs() < 1e-6
|
||||
&& transform.m[2].abs() < 1e-6
|
||||
&& transform.m[0].abs() >= 1.0
|
||||
&& transform.m[3].abs() >= 1.0
|
||||
&& [transform.m[0], transform.m[3], transform.m[4], transform.m[5]].into_iter().all(integer)
|
||||
{
|
||||
egui::TextureOptions::NEAREST
|
||||
} else {
|
||||
egui::TextureOptions::LINEAR
|
||||
};
|
||||
let cached = painter.ctx().data(|d| d.get_temp::<DocumentDragCache>(id));
|
||||
let cached = cached.filter(|c| c.shape == *shape && c.visible == visible && c.canvas == canvas && (c.factor > 1 || c.options == options));
|
||||
let was_cached = cached.is_some();
|
||||
if !was_cached {
|
||||
// Release an obsolete progressive accumulator before allocating its replacement.
|
||||
painter.ctx().data_mut(|d| d.remove::<DocumentDragCache>(id));
|
||||
}
|
||||
let Some(mut cache) = cached.or_else(|| new_document_preview(painter, shape, visible, canvas, options)) else { return };
|
||||
if was_cached && let Some(reduction) = &cache.reduction {
|
||||
let (image, complete) = {
|
||||
let mut work = reduction.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
work.advance();
|
||||
(work.image(), work.complete())
|
||||
};
|
||||
cache.texture.set(image, cache.options);
|
||||
if complete {
|
||||
cache.reduction = None;
|
||||
}
|
||||
}
|
||||
if cache.reduction.is_some() {
|
||||
painter.ctx().request_repaint();
|
||||
}
|
||||
let b = cache.bounds;
|
||||
let mut mesh = egui::Mesh::with_texture(cache.texture.id());
|
||||
for (u, v) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {
|
||||
let p = transform.apply(Point::new(
|
||||
f64::from(b.x0) + u * cache.size[0] as f64 * f64::from(cache.factor),
|
||||
f64::from(b.y0) + v * cache.size[1] as f64 * f64::from(cache.factor),
|
||||
));
|
||||
mesh.vertices.push(egui::epaint::Vertex { pos: egui::pos2(p.x as f32, p.y as f32), uv: egui::pos2(u as f32, v as f32), color: egui::Color32::WHITE });
|
||||
}
|
||||
mesh.indices.extend([0, 1, 2, 0, 2, 3]);
|
||||
painter.add(egui::Shape::mesh(mesh));
|
||||
cache.painted_pass = painter.ctx().cumulative_pass_nr_for(egui::ViewportId::ROOT);
|
||||
painter.ctx().data_mut(|d| d.insert_temp(id, cache));
|
||||
}
|
||||
|
||||
pub(crate) fn finish_frame(_app: &mut crate::PhotocraftApp, ctx: &egui::Context) {
|
||||
// A released/cancelled drag must not retain a large, unfinished accumulator.
|
||||
// Floating document viewports have independent pass counters.
|
||||
let pass = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT);
|
||||
ctx.data_mut(|d| {
|
||||
let mut views = d.get_temp::<Vec<egui::Id>>(document_preview_registry()).unwrap_or_default();
|
||||
views.retain(|id| {
|
||||
let current = d.get_temp::<DocumentDragCache>(*id).is_some_and(|c| c.painted_pass == pass);
|
||||
if !current {
|
||||
d.remove::<DocumentDragCache>(*id);
|
||||
}
|
||||
current
|
||||
});
|
||||
d.insert_temp(document_preview_registry(), views);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
//! Bounded box reduction of committed document pixels for large drag previews.
|
||||
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_vector::CompiledShape;
|
||||
|
||||
pub(super) const TEXTURE_EDGE: u32 = 2048;
|
||||
const TILE_EDGE: u32 = 256;
|
||||
pub(super) const PIXELS_PER_PASS: u64 = 4_194_304;
|
||||
|
||||
/// Integer document-pixel footprints keep native coverage and a bounded texture allocation.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct PreviewLayout {
|
||||
pub bounds: Rect,
|
||||
pub size: [usize; 2],
|
||||
pub factor: u32,
|
||||
}
|
||||
|
||||
impl PreviewLayout {
|
||||
/// Select an integer reduction factor with at most 2048 texels per dimension.
|
||||
pub fn new(bounds: Rect) -> Option<Self> {
|
||||
if bounds.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let factor = bounds.width().max(bounds.height()).div_ceil(TEXTURE_EDGE).max(1);
|
||||
let size = [bounds.width().div_ceil(factor) as usize, bounds.height().div_ceil(factor) as usize];
|
||||
// Even i32-extreme document bounds cannot create an oversized allocation.
|
||||
(size[0] <= TEXTURE_EDGE as usize && size[1] <= TEXTURE_EDGE as usize && size[0].checked_mul(size[1])? <= PIXELS_PER_PASS as usize).then_some(Self {
|
||||
bounds,
|
||||
size,
|
||||
factor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream small native tiles into premultiplied sums, never rasterizing the entire source box.
|
||||
pub(super) struct PreviewReduction {
|
||||
compiled: CompiledShape,
|
||||
layout: PreviewLayout,
|
||||
sums: Vec<[f64; 4]>,
|
||||
weights: Vec<f64>,
|
||||
fallback: Option<egui::ColorImage>,
|
||||
cursor: [i32; 2],
|
||||
}
|
||||
|
||||
impl PreviewReduction {
|
||||
/// Allocate only the validated output grid, retaining the compiled document renderer.
|
||||
pub fn new(compiled: CompiledShape, layout: PreviewLayout) -> Self {
|
||||
Self {
|
||||
compiled,
|
||||
layout,
|
||||
sums: vec![[0.0; 4]; layout.size[0] * layout.size[1]],
|
||||
weights: vec![0.0; layout.size[0] * layout.size[1]],
|
||||
fallback: None,
|
||||
cursor: [layout.bounds.x0, layout.bounds.y0],
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded full-shape approximation fills pixels not yet visited by native reduction.
|
||||
pub fn set_fallback(&mut self, image: egui::ColorImage) {
|
||||
if image.size.into_iter().all(|side| side > 0) && image.size[0] <= self.layout.size[0] && image.size[1] <= self.layout.size[1] {
|
||||
self.fallback = Some(image);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every native source tile has contributed to the reduced image.
|
||||
pub fn complete(&self) -> bool {
|
||||
self.cursor[1] >= self.layout.bounds.y1
|
||||
}
|
||||
|
||||
/// Cap work as well as memory so hostile/extreme document bounds cannot freeze a frame.
|
||||
/// The caller requests another frame while there are unprocessed tiles.
|
||||
pub fn advance(&mut self) -> u64 {
|
||||
let mut used = 0;
|
||||
while !self.complete() {
|
||||
let tile = Rect::new(
|
||||
self.cursor[0],
|
||||
self.cursor[1],
|
||||
self.cursor[0].saturating_add(TILE_EDGE as i32).min(self.layout.bounds.x1),
|
||||
self.cursor[1].saturating_add(TILE_EDGE as i32).min(self.layout.bounds.y1),
|
||||
);
|
||||
let count = u64::from(tile.width()) * u64::from(tile.height());
|
||||
if count == 0 || count > PIXELS_PER_PASS - used {
|
||||
break;
|
||||
}
|
||||
let pixels = self.compiled.render_rgba(tile);
|
||||
self.accumulate(tile, &pixels);
|
||||
used += count;
|
||||
self.cursor[0] = tile.x1;
|
||||
if self.cursor[0] >= self.layout.bounds.x1 {
|
||||
self.cursor = [self.layout.bounds.x0, tile.y1];
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// Box filtering must average premultiplied colour, including transparent edge pixels.
|
||||
fn accumulate(&mut self, tile: Rect, pixels: &[[f32; 4]]) {
|
||||
let factor = self.layout.factor as usize;
|
||||
for (i, pixel) in pixels.iter().enumerate() {
|
||||
let x = i64::from(tile.x0) - i64::from(self.layout.bounds.x0) + (i % tile.width() as usize) as i64;
|
||||
let y = i64::from(tile.y0) - i64::from(self.layout.bounds.y0) + (i / tile.width() as usize) as i64;
|
||||
let index = (y as usize / factor) * self.layout.size[0] + x as usize / factor;
|
||||
let Some(sum) = self.sums.get_mut(index) else { continue };
|
||||
if let Some(weight) = self.weights.get_mut(index) {
|
||||
*weight += 1.0;
|
||||
}
|
||||
let alpha = f64::from(pixel[3].clamp(0.0, 1.0));
|
||||
for channel in 0..3 {
|
||||
sum[channel] += f64::from(pixel[channel].clamp(0.0, 1.0)) * alpha;
|
||||
}
|
||||
sum[3] += alpha;
|
||||
}
|
||||
}
|
||||
|
||||
/// Blend the complete approximation into unvisited pixels; completion uses native sums only.
|
||||
pub fn image(&self) -> egui::ColorImage {
|
||||
let area = f64::from(self.layout.factor).powi(2);
|
||||
let pixels = self
|
||||
.sums
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, sum)| {
|
||||
let mut sum = *sum;
|
||||
if !self.complete()
|
||||
&& let Some(pixel) = self.fallback.as_ref().and_then(|image| {
|
||||
let x = index % self.layout.size[0] * image.size[0] / self.layout.size[0];
|
||||
let y = index / self.layout.size[0] * image.size[1] / self.layout.size[1];
|
||||
image.pixels.get(y * image.size[0] + x)
|
||||
})
|
||||
{
|
||||
let missing = (area - self.weights.get(index).copied().unwrap_or(0.0)).max(0.0);
|
||||
let color = pixel.to_srgba_unmultiplied();
|
||||
let alpha = f64::from(color[3]) / 255.0;
|
||||
for channel in 0..3 {
|
||||
sum[channel] += f64::from(color[channel]) / 255.0 * alpha * missing;
|
||||
}
|
||||
sum[3] += alpha * missing;
|
||||
}
|
||||
if sum[3] <= 0.0 {
|
||||
return egui::Color32::TRANSPARENT;
|
||||
}
|
||||
let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
egui::Color32::from_rgba_unmultiplied(byte(sum[0] / sum[3]), byte(sum[1] / sum[3]), byte(sum[2] / sum[3]), byte(sum[3] / area))
|
||||
})
|
||||
.collect();
|
||||
egui::ColorImage::new(self.layout.size, pixels)
|
||||
}
|
||||
}
|
||||
@@ -8,364 +8,3 @@ fn options_serde_defaults_keep_old_tool_settings_and_full_stroke() {
|
||||
assert_eq!(StrokeOptions::from(&stroke), style);
|
||||
assert_eq!(serde_json::from_value::<StrokeOptions>(serde_json::to_value(&style).unwrap()).unwrap(), style);
|
||||
}
|
||||
|
||||
/// Filtered fill edges need transparent texels on every side of the projected quad.
|
||||
#[test]
|
||||
fn pixel_align_preview_pads_fill_texture_before_fractional_projection() {
|
||||
use photocraft_geom::{Affine, Rect as PixelRect};
|
||||
for side in [40.0, 4096.0] {
|
||||
let shape = photocraft_doc::ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(20.0, 20.0, side, 30.0),
|
||||
fill: Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let transform = Affine::scale(0.125).then(&Affine::translate(10.25, 10.25));
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 100.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &transform, PixelRect::new(0, 0, 5000, 200));
|
||||
});
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background()))).unwrap();
|
||||
let delta = output.textures_delta.set.get(&cache.texture.id()).unwrap().last().unwrap();
|
||||
let egui::ImageData::Color(image) = &delta.image;
|
||||
let [w, h] = image.size;
|
||||
assert!(w <= 2048 && h <= 2048);
|
||||
assert!(image.pixels[..w].iter().all(|p| p.a() == 0), "top border");
|
||||
assert!(image.pixels[(h - 1) * w..].iter().all(|p| p.a() == 0), "bottom border");
|
||||
assert!((0..h).all(|y| image.pixels[y * w].a() == 0 && image.pixels[y * w + w - 1].a() == 0), "side borders");
|
||||
assert!(image.pixels.iter().any(|p| p.a() > 0));
|
||||
assert!(cache.bounds.x0 <= 20 - cache.factor as i32);
|
||||
assert!(cache.bounds.y0 <= 20 - cache.factor as i32);
|
||||
let mesh = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Mesh(mesh) if mesh.texture_id == cache.texture.id() => Some(mesh),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let corner = transform.apply(photocraft_geom::Point::new(f64::from(cache.bounds.x0), f64::from(cache.bounds.y0)));
|
||||
assert_eq!(mesh.vertices[0].pos, egui::pos2(corner.x as f32, corner.y as f32));
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// A floating viewport can have a different pass count while a root frame owns cleanup.
|
||||
#[test]
|
||||
fn pixel_align_floating_preview_survives_root_cleanup_and_completes() {
|
||||
use photocraft_geom::{Affine, Rect as PixelRect};
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
egui::Context::set_immediate_viewport_renderer(|ctx, mut viewport| {
|
||||
let id = viewport.ids.this;
|
||||
let mut input = egui::RawInput { viewport_id: id, ..Default::default() };
|
||||
input.viewports.insert(id, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..Default::default() });
|
||||
let mut output = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui));
|
||||
output.textures_delta.clear();
|
||||
});
|
||||
let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
for _ in 0..3 {
|
||||
let mut output = ctx.run_ui(Default::default(), |_| {});
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
let shape = photocraft_doc::ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(0.0, 0.0, 2050.0, 2050.0),
|
||||
fill: Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let id = document_preview_id(egui::ViewportId::from_hash_of("floating-preview"), egui::LayerId::background());
|
||||
let mut accumulator = None;
|
||||
for frame in 0..2 {
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
ui.ctx().show_viewport_immediate(egui::ViewportId::from_hash_of("floating-preview"), Default::default(), |ui, _| {
|
||||
assert_ne!(ui.ctx().cumulative_pass_nr(), ui.ctx().cumulative_pass_nr_for(egui::ViewportId::ROOT));
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &Affine::scale(0.125).then(&Affine::translate(10.0, 10.0)), PixelRect::new(0, 0, 2050, 2050));
|
||||
});
|
||||
finish_frame(&mut app, ui.ctx());
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(id)).expect("root cleanup must retain the floating preview");
|
||||
if frame == 0 {
|
||||
accumulator = Some(Arc::downgrade(cache.reduction.as_ref().expect("unfinished first pass")));
|
||||
} else {
|
||||
assert!(cache.reduction.is_none(), "the second pass must finish rather than restart");
|
||||
}
|
||||
}
|
||||
assert!(accumulator.unwrap().upgrade().is_none(), "completion releases the accumulator");
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| finish_frame(&mut app, ui.ctx()));
|
||||
output.textures_delta.clear();
|
||||
assert!(ctx.data(|d| d.get_temp::<DocumentDragCache>(id)).is_none(), "ending the drag releases its texture");
|
||||
}
|
||||
|
||||
/// Canvas-aligned gradient paint must not use the clipped preview coverage as its frame.
|
||||
#[test]
|
||||
fn pixel_align_preview_preserves_canvas_gradient_frame() {
|
||||
use photocraft_doc::{Color, Fill, GradientStyle, ShapeLayer};
|
||||
use photocraft_geom::{Affine, Rect as PixelRect};
|
||||
let canvas = PixelRect::new(0, 0, 200, 120);
|
||||
let gradient = Fill::Gradient {
|
||||
stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))],
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
opacity_stops: vec![],
|
||||
midpoints: vec![],
|
||||
offset: (0.0, 0.0),
|
||||
dither: false,
|
||||
align: false,
|
||||
};
|
||||
let shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(20.0, 20.0, 140.0, 80.0),
|
||||
fill: Some(gradient.clone()),
|
||||
stroke: Some(ShapeStroke { width: 1.0, paint: gradient, ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_max(egui::pos2(30.0, 25.0), egui::pos2(90.0, 65.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &Affine::IDENTITY, canvas);
|
||||
});
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background()))).unwrap();
|
||||
assert_ne!(cache.visible, canvas, "test requires distinct coverage and paint frames");
|
||||
let image = &output.textures_delta.set.get(&cache.texture.id()).unwrap()[0].image;
|
||||
let egui::ImageData::Color(image) = image;
|
||||
let rgba = photocraft_vector::CompiledShape::with_frames(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible, canvas).render_rgba(cache.bounds);
|
||||
let wrong = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible).render_rgba(cache.bounds);
|
||||
assert_ne!(rgba, wrong, "test must detect a gradient laid out in the wrong frame");
|
||||
let expected: Vec<_> = rgba
|
||||
.iter()
|
||||
.map(|p| {
|
||||
egui::Color32::from_rgba_unmultiplied(
|
||||
(p[0] * 255.0).round() as u8,
|
||||
(p[1] * 255.0).round() as u8,
|
||||
(p[2] * 255.0).round() as u8,
|
||||
(p[3] * 255.0).round() as u8,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(image.pixels, expected);
|
||||
assert_eq!(cache.shape.path, shape.path);
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Crossing the preview texture limit must retain box-filtered aligned document coverage.
|
||||
#[test]
|
||||
fn pixel_align_oversized_preview_preserves_document_coverage() {
|
||||
use photocraft_doc::{Fill, ShapeLayer};
|
||||
use photocraft_geom::{Affine, Rect as PixelRect};
|
||||
for width in [2044.0, 2046.0, 2048.0, 4096.0] {
|
||||
for dashed in [false, true] {
|
||||
let shape = ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(0.0, 1.0, width, 6.0),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke {
|
||||
width: 1.0,
|
||||
paint: Fill::Solid(photocraft_doc::Color::BLACK),
|
||||
dashes: if dashed { vec![3.0, 2.0] } else { vec![] },
|
||||
dash_offset: -0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let transform = Affine::scale(0.125).then(&Affine::translate(10.0, 10.0));
|
||||
let canvas = PixelRect::new(0, 0, 5000, 100);
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 60.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &transform, canvas);
|
||||
});
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background())));
|
||||
let image = cache.as_ref().and_then(|c| output.textures_delta.set.get(&c.texture.id())).and_then(|d| d.last()).map(|d| d.image.clone());
|
||||
output.textures_delta.clear();
|
||||
let cache = cache.expect("large previews must keep aligned document coverage instead of using the legacy proxy");
|
||||
let egui::ImageData::Color(image) = image.expect("uploaded document preview");
|
||||
assert!(image.size.into_iter().all(|n| n <= 2048));
|
||||
let factor = cache.bounds.width().max(cache.bounds.height()).div_ceil(2048).max(1) as usize;
|
||||
let compiled = photocraft_vector::CompiledShape::with_frames(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible, canvas);
|
||||
let native = compiled.render_rgba(cache.bounds);
|
||||
let mut alpha = vec![0.0f64; image.pixels.len()];
|
||||
for (i, pixel) in native.iter().enumerate() {
|
||||
let x = i % cache.bounds.width() as usize;
|
||||
let y = i / cache.bounds.width() as usize;
|
||||
alpha[(y / factor) * image.size[0] + x / factor] += f64::from(pixel[3]);
|
||||
}
|
||||
let expected: Vec<u8> = alpha.iter().map(|a| (a / (factor * factor) as f64 * 255.0).round() as u8).collect();
|
||||
let actual: Vec<u8> = image.pixels.iter().map(|p| p.a()).collect();
|
||||
assert_eq!(actual, expected, "width={width}, dashed={dashed}");
|
||||
assert!(actual.iter().any(|a| *a > 0));
|
||||
assert_eq!(cache.shape.path, shape.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zoom and rotation project committed document coverage, including ineligible half-pixel strokes.
|
||||
#[test]
|
||||
fn pixel_align_preview_texture_matches_document_coverage_before_zoom() {
|
||||
use photocraft_doc::{Fill, ShapeLayer};
|
||||
use photocraft_geom::{Affine, Point, Rect as PixelRect};
|
||||
for (curved, path) in [(false, photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0)), (true, photocraft_vector::shapes::ellipse(20.0, 20.0, 40.0, 30.0))]
|
||||
{
|
||||
for width in [0.5, 1.0, 2.0] {
|
||||
for dashed in [false, true] {
|
||||
for zoom in [0.5, 1.0, 2.0, 3.0] {
|
||||
for angle in [0.0, 0.3] {
|
||||
let shape = ShapeLayer {
|
||||
path: path.clone(),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke {
|
||||
width,
|
||||
paint: Fill::Solid(photocraft_doc::Color::BLACK),
|
||||
dashes: if dashed { vec![3.0, 2.0] } else { vec![] },
|
||||
dash_offset: 0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let transform = Affine::scale(zoom).then(&Affine::rotate(angle)).then(&Affine::translate(40.0, 40.0));
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let ctx = ui.ctx();
|
||||
let painter =
|
||||
ctx.layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &transform, PixelRect::new(0, 0, 200, 200));
|
||||
});
|
||||
let cache = ctx
|
||||
.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background())))
|
||||
.expect("document preview cache");
|
||||
let image = output.textures_delta.set.get(&cache.texture.id()).expect("uploaded preview");
|
||||
let egui::ImageData::Color(image) = &image[0].image;
|
||||
let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible);
|
||||
let rgba = compiled.render_rgba(cache.bounds);
|
||||
let expected: Vec<_> = rgba
|
||||
.iter()
|
||||
.map(|p| {
|
||||
egui::Color32::from_rgba_unmultiplied(
|
||||
(p[0] * 255.0).round() as u8,
|
||||
(p[1] * 255.0).round() as u8,
|
||||
(p[2] * 255.0).round() as u8,
|
||||
(p[3] * 255.0).round() as u8,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(image.pixels, expected, "width={width}, angle={angle}");
|
||||
if curved {
|
||||
assert!(rgba.iter().any(|p| p[3] > 0.0 && p[3] < 1.0), "curve antialiasing");
|
||||
} else if !dashed {
|
||||
let edge = compiled.render_rgba(PixelRect::new(35, 20, 36, 21))[0][3];
|
||||
assert_eq!(edge, if width == 0.5 { 0.25 } else { 1.0 });
|
||||
}
|
||||
let mesh = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Mesh(mesh) if mesh.texture_id == cache.texture.id() => Some(mesh),
|
||||
_ => None,
|
||||
})
|
||||
.expect("projected quad");
|
||||
let corner = transform.apply(Point::new(f64::from(cache.bounds.x0), f64::from(cache.bounds.y0)));
|
||||
assert_eq!(mesh.vertices[0].pos, egui::pos2(corner.x as f32, corner.y as f32));
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Huge previews retain a bounded allocation instead of rasterizing an unbounded document.
|
||||
#[test]
|
||||
fn pixel_align_document_preview_rejects_oversized_raster_allocations() {
|
||||
let shape = photocraft_doc::ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(0.0, 0.0, 100_000.0, 100_000.0),
|
||||
fill: Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let visible = photocraft_geom::Rect::new(0, 0, 100_000, 100_000);
|
||||
let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, visible);
|
||||
for source in [visible, photocraft_geom::Rect::new(0, 0, 10_000, 1), photocraft_geom::Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX)] {
|
||||
let layout = PreviewLayout::new(source).unwrap();
|
||||
assert!(layout.size.into_iter().all(|n| n <= 2048));
|
||||
assert!(layout.size[0] * layout.size[1] <= 4_194_304);
|
||||
}
|
||||
assert_eq!(document_preview_bounds(&compiled, visible), Some(visible));
|
||||
}
|
||||
|
||||
/// Large reductions make bounded progress over frames and release their working buffers at completion.
|
||||
#[test]
|
||||
fn pixel_align_large_preview_completes_in_bounded_passes() {
|
||||
use photocraft_geom::{Affine, Rect as PixelRect};
|
||||
let bounds = PixelRect::new(0, 0, 2050, 2050);
|
||||
let shape = photocraft_doc::ShapeLayer {
|
||||
path: photocraft_vector::shapes::rect(0.0, 0.0, 2050.0, 2050.0),
|
||||
fill: Some(photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, bounds);
|
||||
let mut work = PreviewReduction::new(compiled, PreviewLayout::new(bounds).unwrap());
|
||||
assert!(work.advance() <= document_preview::PIXELS_PER_PASS);
|
||||
assert!(!work.complete(), "the source must not be rasterized in one unbounded pass");
|
||||
assert!(work.advance() <= document_preview::PIXELS_PER_PASS);
|
||||
assert!(work.complete());
|
||||
assert!(work.image().pixels.iter().all(|p| p.a() == 255));
|
||||
drop(work);
|
||||
let ctx = egui::Context::default();
|
||||
let transform = Affine::scale(0.125).then(&Affine::translate(10.0, 10.0));
|
||||
for frame in 0..3 {
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)));
|
||||
paint_document_shape_preview(&painter, &shape, &transform, bounds);
|
||||
});
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background()))).unwrap();
|
||||
let image = output.textures_delta.set.get(&cache.texture.id()).and_then(|d| d.last()).map(|d| d.image.clone());
|
||||
output.textures_delta.clear();
|
||||
if frame == 0 {
|
||||
assert!(cache.reduction.is_some());
|
||||
} else {
|
||||
assert!(cache.reduction.is_none(), "completed previews must release native buffers");
|
||||
if let Some(egui::ImageData::Color(image)) = image {
|
||||
let oracle = photocraft_vector::CompiledShape::with_frames(&shape, photocraft_vector::DEFAULT_TOLERANCE, cache.visible, bounds);
|
||||
for y in [0, 1, image.size[1] / 2, image.size[1] - 1] {
|
||||
for x in [0, 1, image.size[0] / 2, image.size[0] - 1] {
|
||||
let source = PixelRect::from_xywh(
|
||||
cache.bounds.x0 + (x as u32 * cache.factor) as i32,
|
||||
cache.bounds.y0 + (y as u32 * cache.factor) as i32,
|
||||
cache.factor,
|
||||
cache.factor,
|
||||
)
|
||||
.intersect(&cache.bounds);
|
||||
let alpha: f64 = oracle.render_rgba(source).iter().map(|p| f64::from(p[3])).sum();
|
||||
let expected = (alpha / f64::from(cache.factor).powi(2) * 255.0).round() as u8;
|
||||
assert_eq!(image.pixels[y * image.size[0] + x].a(), expected, "source padding at {x},{y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let mut changed = shape.clone();
|
||||
changed.path = photocraft_vector::shapes::rect(1.0, 0.0, 2050.0, 2050.0);
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)));
|
||||
paint_document_shape_preview(&painter, &changed, &transform, bounds);
|
||||
finish_frame(&mut app, ui.ctx());
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
let cache = ctx.data(|d| d.get_temp::<DocumentDragCache>(document_preview_id(egui::ViewportId::ROOT, egui::LayerId::background()))).unwrap();
|
||||
let unfinished = Arc::downgrade(cache.reduction.as_ref().expect("pending replacement preview"));
|
||||
drop(cache);
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| finish_frame(&mut app, ui.ctx()));
|
||||
output.textures_delta.clear();
|
||||
assert!(unfinished.upgrade().is_none(), "ending a drag must release the unfinished buffers");
|
||||
}
|
||||
|
||||
@@ -183,7 +183,8 @@ pub fn sample_all_key(tool: Tool) -> Option<String> {
|
||||
pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
// `reset!` names each field once; one that is misspelt or gone fails to compile.
|
||||
macro_rules! serialized_key {
|
||||
(use_aligned_rendering) => {
|
||||
// The one Align Edges checkbox goes by the reference application's script name.
|
||||
(align_edges) => {
|
||||
"useAlignedRendering"
|
||||
};
|
||||
($f:ident) => {
|
||||
@@ -245,14 +246,14 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones),
|
||||
Tool::Sponge => reset!(sponge_mode, sponge_flow, vibrance),
|
||||
Tool::Slice => reset!(slice_style, slice_width, slice_height),
|
||||
Tool::Pen => reset!(vector_mode, use_aligned_rendering, pen_path_op, pen_auto_add_delete, path_options),
|
||||
Tool::CurvaturePen => reset!(vector_mode, use_aligned_rendering, pen_path_op),
|
||||
Tool::FreeformPen => reset!(vector_mode, use_aligned_rendering, pen_path_op, curve_fit),
|
||||
Tool::Pen => reset!(vector_mode, align_edges, pen_path_op, pen_auto_add_delete, path_options),
|
||||
Tool::CurvaturePen => reset!(vector_mode, align_edges, pen_path_op),
|
||||
Tool::FreeformPen => reset!(vector_mode, align_edges, pen_path_op, curve_fit),
|
||||
Tool::Line => reset!(
|
||||
shape_mode,
|
||||
shape_path_op,
|
||||
shape_fill,
|
||||
use_aligned_rendering,
|
||||
align_edges,
|
||||
stroke_width,
|
||||
shape_stroke,
|
||||
shape_fill_gradient,
|
||||
@@ -271,7 +272,6 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
shape_mode,
|
||||
shape_path_op,
|
||||
shape_fill,
|
||||
use_aligned_rendering,
|
||||
stroke_width,
|
||||
shape_stroke,
|
||||
shape_fill_gradient,
|
||||
@@ -292,7 +292,6 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
|
||||
shape_mode,
|
||||
shape_path_op,
|
||||
shape_fill,
|
||||
use_aligned_rendering,
|
||||
stroke_width,
|
||||
shape_stroke,
|
||||
shape_fill_gradient,
|
||||
|
||||
@@ -60,13 +60,6 @@ fn layers(app: &PhotocraftApp) -> usize {
|
||||
|
||||
#[test]
|
||||
fn a_type_mask_click_on_text_edits_that_layer_as_the_type_tool_does() {
|
||||
// This unoptimized fixture moves several full app/harness states through two frames.
|
||||
// Windows test threads have only 2 MiB; reserve a bounded stack for the fixture,
|
||||
// keeping all three tools and their full frame/history assertions enabled.
|
||||
std::thread::Builder::new().stack_size(8 * 1024 * 1024).spawn(check_type_mask_click_on_text).unwrap().join().unwrap();
|
||||
}
|
||||
|
||||
fn check_type_mask_click_on_text() {
|
||||
let escape = key(egui::Key::Escape, Modifiers::NONE);
|
||||
let mut states = Vec::new();
|
||||
for tool in [Tool::Type, Tool::HorizontalTypeMask, Tool::VerticalTypeMask] {
|
||||
|
||||
@@ -298,7 +298,7 @@ pub(crate) fn capture_pen_owner(app: &PhotocraftApp) -> Option<PenOwner> {
|
||||
&& (pen::pen_path_op(&options).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.resumes.as_ref().is_some_and(|r| r.layer.is_some())))
|
||||
&& let Some(LayerContent::Shape(shape)) = st.active_layer.and_then(|id| st.doc.layer(id)).map(|layer| &layer.content)
|
||||
{
|
||||
options.use_aligned_rendering = shape.use_aligned_rendering;
|
||||
options.align_edges = shape.use_aligned_rendering;
|
||||
}
|
||||
Some(PenOwner {
|
||||
document: st.doc.id,
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
//! App policy for the shared framework checkbox.
|
||||
//! ShapeBar/ShapePanel do not expose the engine-specific useAlignedRendering field;
|
||||
//! compose the framework Checkbox here and keep document edits in engine commands.
|
||||
//! The one Align Edges checkbox of the shape tools, the Pen in Shape mode and a shape layer's
|
||||
//! Properties, as in the reference application. In the options bar it is the tool option
|
||||
//! (`ToolOptions::align_edges`): a drag lands on whole pixels and the new shape layer gets Align
|
||||
//! Edges. With a shape layer selected it shows and edits that layer's flag
|
||||
//! (`shape.edit {useAlignedRendering}`) too, as Fill and Stroke do. The flag only changes how the
|
||||
//! layer renders (`photocraft_vector::align_edges`); its path is never moved.
|
||||
use crate::PhotocraftApp;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _};
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
use serde_json::json;
|
||||
pub(crate) fn option(app: &mut PhotocraftApp, ui: &mut egui::Ui, target: Option<LayerId>, defaults: bool) {
|
||||
|
||||
/// The checkbox for `target` (a shape layer: shows and edits its flag) and, with `defaults`, the
|
||||
/// tool option the next shape takes. Greyed when not `enabled` or when the layer is locked.
|
||||
pub(crate) fn option(app: &mut PhotocraftApp, ui: &mut egui::Ui, target: Option<LayerId>, defaults: bool, enabled: bool) {
|
||||
let layer = target.and_then(|id| {
|
||||
app.session.active().and_then(|st| {
|
||||
let LayerContent::Shape(sh) = &st.doc.layer(id)?.content else { return None };
|
||||
@@ -14,13 +20,13 @@ pub(crate) fn option(app: &mut PhotocraftApp, ui: &mut egui::Ui, target: Option<
|
||||
Some((sh.use_aligned_rendering, locks.all || locks.pixels))
|
||||
})
|
||||
});
|
||||
let before = layer.map_or(app.ui.tool_options.use_aligned_rendering, |v| v.0);
|
||||
let before = layer.map_or(app.ui.tool_options.align_edges, |v| v.0);
|
||||
let mut value = before;
|
||||
Checkbox::new(Bind::bound(&mut value)).label(tl!("Align Edges").to_owned()).enabled(!layer.is_some_and(|v| v.1)).show(ui);
|
||||
Checkbox::new(Bind::bound(&mut value)).label(tl!("Align Edges").to_owned()).enabled(enabled && !layer.is_some_and(|v| v.1)).show(ui);
|
||||
if value == before {
|
||||
return;
|
||||
}
|
||||
if let Some(id) = target
|
||||
if let Some(id) = target.filter(|_| layer.is_some())
|
||||
&& let Err(e) = app.run("shape.edit", json!({"layer": id.0, "useAlignedRendering": value}))
|
||||
{
|
||||
app.ui.status = e;
|
||||
@@ -28,30 +34,38 @@ pub(crate) fn option(app: &mut PhotocraftApp, ui: &mut egui::Ui, target: Option<
|
||||
return;
|
||||
}
|
||||
if defaults {
|
||||
app.ui.tool_options.use_aligned_rendering = value;
|
||||
app.ui.tool_options.align_edges = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape tools' checkbox, at the options bar's right end: enabled in Shape mode only, where it
|
||||
/// also edits the selected shape layer.
|
||||
pub(super) fn shape_tool_option(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let shape_mode = app.ui.tool_options.shape_mode == super::VectorMode::Shape;
|
||||
let target = if shape_mode { super::options::selected_shape(&app.session) } else { None };
|
||||
option(app, ui, target, true, shape_mode);
|
||||
}
|
||||
|
||||
/// The Pen's checkbox: enabled in Shape mode only. While a path is being drawn it is the value the
|
||||
/// draft captured (the layer it joins, or the tool option it started with).
|
||||
pub(super) fn pen_option(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let draft = app.ui.pen.as_ref().and_then(|p| p.owner.as_ref()).filter(|o| o.valid(app)).map(|o| o.options.use_aligned_rendering);
|
||||
let shape_mode = app.ui.tool_options.vector_mode == super::VectorMode::Shape;
|
||||
let draft = app.ui.pen.as_ref().and_then(|p| p.owner.as_ref()).filter(|o| shape_mode && o.valid(app)).map(|o| o.options.align_edges);
|
||||
if let Some(before) = draft {
|
||||
let mut value = before;
|
||||
Checkbox::new(Bind::bound(&mut value)).label(tl!("Align Edges").to_owned()).show(ui);
|
||||
if value != before {
|
||||
app.ui.tool_options.use_aligned_rendering = value;
|
||||
app.ui.tool_options.align_edges = value;
|
||||
if let Some(owner) = app.ui.pen.as_mut().and_then(|p| p.owner.as_mut()) {
|
||||
owner.options.use_aligned_rendering = value;
|
||||
owner.options.align_edges = value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let target =
|
||||
if app.ui.pen.is_none() && super::pen::pen_path_op(&app.ui.tool_options).is_some() { super::options::selected_shape(&app.session) } else { None };
|
||||
option(app, ui, target, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shape mode edits paint; Path mode keeps the selected layer and paint defaults untouched.
|
||||
pub(crate) fn shape_option(app: &mut PhotocraftApp, ui: &mut egui::Ui, target: Option<LayerId>, paint: bool) {
|
||||
if paint {
|
||||
option(app, ui, target, true);
|
||||
let target = if shape_mode && app.ui.pen.is_none() && super::pen::pen_path_op(&app.ui.tool_options).is_some() {
|
||||
super::options::selected_shape(&app.session)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
option(app, ui, target, true, shape_mode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,15 +156,11 @@ fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut BarOpe
|
||||
crate::option_cells::range_alert(app, ui, &alert);
|
||||
}
|
||||
}
|
||||
// The Rectangle tool's Align Edges, at the bar's right end after the gear (#13346). Only a
|
||||
// shape layer has pixel edges to align: greyed in Path mode (and in a pixels mode).
|
||||
if tool == Tool::Rectangle {
|
||||
// Every shape tool's one Align Edges, at the bar's right end after the gear (#13346, #13370).
|
||||
// Only a shape layer has pixel edges to align: greyed in Path mode (and in a pixels mode).
|
||||
if is_shape_tool(tool) {
|
||||
Divider::vertical().show(ui);
|
||||
let shape_mode = app.ui.tool_options.shape_mode == VectorMode::Shape;
|
||||
let on = Checkbox::new(Bind::given(app.ui.tool_options.align_edges)).label(tl!("Snap Bounding Box").to_owned()).enabled(shape_mode).show(ui);
|
||||
if let Some(next) = on.value().copied() {
|
||||
app.ui.tool_options.align_edges = next;
|
||||
}
|
||||
super::alignment::shape_tool_option(app, ui);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,9 +199,8 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba
|
||||
crate::option_cells::range_alert(app, ui, &alert);
|
||||
}
|
||||
}
|
||||
if app.ui.tool_options.vector_mode == VectorMode::Shape {
|
||||
super::alignment::pen_option(app, ui);
|
||||
}
|
||||
// Align Edges, enabled in Shape mode only (greyed in Path mode).
|
||||
super::alignment::pen_option(app, ui);
|
||||
Divider::vertical().show(ui);
|
||||
path_operations_menu(app, ui);
|
||||
let o = &mut app.ui.tool_options;
|
||||
@@ -485,7 +480,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
|
||||
.show(ui);
|
||||
let fw::ShapePanelOutput { events, pick_color, out_of_range, .. } = output;
|
||||
let paint_gradients = [library.gradient(fw::ShapePaint::Fill), library.gradient(fw::ShapePaint::Stroke)];
|
||||
super::alignment::option(app, ui, Some(id), false);
|
||||
super::alignment::option(app, ui, Some(id), false, true);
|
||||
|
||||
let mut applied = false;
|
||||
let mut recent: Option<[f32; 3]> = None;
|
||||
|
||||
@@ -714,12 +714,14 @@ fn align_edges_framework_controls_edit_layers_and_preserve_undo() {
|
||||
let mut app = app("rgb", 8);
|
||||
app.run("shape.create", json!({"rect": [20.5,20.5,80.0,60.0], "useAlignedRendering": false})).unwrap();
|
||||
let original = shape(&app).path.clone();
|
||||
// The tool option starts off too, so the click shows where it lands.
|
||||
app.ui.tool_options.align_edges = false;
|
||||
let mut h = harness(app, properties);
|
||||
h.get_by_label("Align Edges").click();
|
||||
h.run_steps(3);
|
||||
assert!(shape(h.state()).use_aligned_rendering);
|
||||
assert_eq!(shape(h.state()).path, original);
|
||||
assert_eq!(h.state().ui.tool_options.use_aligned_rendering, !properties);
|
||||
assert_eq!(h.state().ui.tool_options.align_edges, !properties);
|
||||
if let Ok(dir) = std::env::var("PHOTOCRAFT_ALIGN_EDGES_SNAPSHOT_DIR") {
|
||||
let name = if properties { "align-edges-properties.png" } else { "align-edges-toolbar.png" };
|
||||
h.render().unwrap().save(std::path::Path::new(&dir).join(name)).unwrap();
|
||||
@@ -733,7 +735,7 @@ fn align_edges_framework_controls_edit_layers_and_preserve_undo() {
|
||||
fn align_edges_framework_creation_and_preview_keep_the_option() {
|
||||
for enabled in [false, true] {
|
||||
let mut app = app("rgb", 8);
|
||||
app.ui.tool_options.use_aligned_rendering = enabled;
|
||||
app.ui.tool_options.align_edges = enabled;
|
||||
let geometry = geometry(Tool::Rectangle, [10.0, 10.0], [30.0, 30.0]);
|
||||
let preview = shapes::shape_preview(&app, shapes::kind_of(Tool::Rectangle), &geometry).unwrap();
|
||||
assert_eq!(preview.use_aligned_rendering, enabled);
|
||||
@@ -748,9 +750,9 @@ fn align_edges_framework_pen_captures_and_edits_draft_option() {
|
||||
let mut app = app("rgb", 8);
|
||||
app.ui.tool = Tool::Pen;
|
||||
app.ui.tool_options.vector_mode = VectorMode::Shape;
|
||||
app.ui.tool_options.use_aligned_rendering = true;
|
||||
app.ui.tool_options.align_edges = true;
|
||||
app.ui.pen = Some(PenPath::corners(&[[20.5, 20.5], [80.5, 60.5]], super::capture_pen_owner(&app)));
|
||||
app.ui.tool_options.use_aligned_rendering = false;
|
||||
app.ui.tool_options.align_edges = false;
|
||||
assert!(pen_commit(&mut app, false));
|
||||
assert!(shape(&app).use_aligned_rendering, "the captured draft keeps its option");
|
||||
}
|
||||
@@ -776,7 +778,7 @@ fn align_edges_framework_tool_presets_use_the_canonical_key() {
|
||||
#[test]
|
||||
fn align_edges_framework_line_preview_matches_committed_pixels() {
|
||||
let mut app = app("rgb", 8);
|
||||
app.ui.tool_options.use_aligned_rendering = true;
|
||||
app.ui.tool_options.align_edges = true;
|
||||
let line = ShapeGeometry::Line { from: craft::behavior::kurbo::Point::new(20.0, 20.0), to: craft::behavior::kurbo::Point::new(80.0, 20.0), weight: 3.0 };
|
||||
let preview = shapes::shape_preview(&app, shapes::kind_of(Tool::Line), &line).unwrap();
|
||||
shapes::finish_drag(&mut app, shapes::kind_of(Tool::Line), &line, Mods::default());
|
||||
|
||||
@@ -105,7 +105,7 @@ pub fn make_shape(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
let r = app.run(
|
||||
"path.toShape",
|
||||
json!({"name": name, "fill": super::shapes::fill_param(app), "stroke": super::shapes::stroke_param(app),
|
||||
"useAlignedRendering": app.ui.tool_options.use_aligned_rendering}),
|
||||
"useAlignedRendering": app.ui.tool_options.align_edges}),
|
||||
)?;
|
||||
if name == "work" && app.ui.selected_path.as_deref() == Some("work") {
|
||||
app.ui.selected_path = None;
|
||||
|
||||
@@ -98,19 +98,16 @@ fn commit_path_current(app: &mut PhotocraftApp, pen: &PenPath, closed: bool, fre
|
||||
r
|
||||
} else if let (Some(op), Some(layer), true) = (op, into_shape, shape_mode) {
|
||||
// The selected shape layer keeps its fill and stroke; the new component cuts, intersects…
|
||||
app.run(
|
||||
"shape.create",
|
||||
json!({"kind": "path", "path": path, "addTo": layer, "op": op, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering}),
|
||||
)
|
||||
app.run("shape.create", json!({"kind": "path", "path": path, "addTo": layer, "op": op, "useAlignedRendering": app.ui.tool_options.align_edges}))
|
||||
} else if shape_mode {
|
||||
let fill = if closed { fill_param(app) } else { Value::Null };
|
||||
let stroke = if closed { stroke_param(app) } else { super::shapes::open_pen_stroke_param(app) };
|
||||
app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering, "historyName": freeform.then_some("Freeform Pen")}))
|
||||
app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke, "useAlignedRendering": app.ui.tool_options.align_edges, "historyName": freeform.then_some("Freeform Pen")}))
|
||||
} else if let Some((name, p)) =
|
||||
pen.resumes.as_ref().and_then(|r| app.session.active().and_then(|st| with_resumed_subpath(&st.doc, r, &path)).map(|p| (r.path.clone(), p)))
|
||||
{
|
||||
// The resumed subpath, carried on, takes its old place: one step, no second subpath.
|
||||
app.run("path.set", json!({"name": name, "path": p, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering, "historyName": freeform.then_some("Freeform Pen")})).inspect(|_| app.ui.selected_path = Some(name))
|
||||
app.run("path.set", json!({"name": name, "path": p, "historyName": freeform.then_some("Freeform Pen")})).inspect(|_| app.ui.selected_path = Some(name))
|
||||
} else if let Some((id, existing)) = targeted_vector_mask(app) {
|
||||
// A targeted vector mask takes the new subpath (#196), as in Photoshop.
|
||||
let mut p = path_json(&existing);
|
||||
@@ -360,7 +357,7 @@ fn commit_resumed_on_layer(app: &mut PhotocraftApp, pen: &PenPath, path: &Value,
|
||||
params["stroke"] = stroke_param(app);
|
||||
}
|
||||
if app.ui.tool_options.vector_mode == craft::draw::ui::shape::VectorMode::Shape {
|
||||
params["useAlignedRendering"] = json!(app.ui.tool_options.use_aligned_rendering);
|
||||
params["useAlignedRendering"] = json!(app.ui.tool_options.align_edges);
|
||||
}
|
||||
Some(app.run("shape.edit", params))
|
||||
}
|
||||
@@ -791,7 +788,7 @@ pub(super) fn make_shape_from_draft(app: &mut PhotocraftApp, pen: &PenPath) -> R
|
||||
let selected = app.ui.selected_path.clone();
|
||||
let params = |app: &mut PhotocraftApp| {
|
||||
let (path, consume) = draft_shape_path(app, pen).ok_or_else(|| tl!("No document").to_string())?;
|
||||
let params = json!({"path": path, "consumeWorkPath": consume, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering, "fill": fill_param(app), "stroke": stroke_param(app)});
|
||||
let params = json!({"path": path, "consumeWorkPath": consume, "useAlignedRendering": app.ui.tool_options.align_edges, "fill": fill_param(app), "stroke": stroke_param(app)});
|
||||
Ok::<_, String>((params, consume))
|
||||
};
|
||||
let made = match &owner {
|
||||
|
||||
@@ -130,17 +130,17 @@ fn options_bar_shows_align_edges_at_its_right_end() {
|
||||
// The Radius field.
|
||||
let radius = h.query_all_by_label("Radius").map(|n| n.rect().right()).fold(f32::MIN, f32::max);
|
||||
let gear = h.get_by_label(GEAR).rect();
|
||||
let node = h.get_by_label("Snap Bounding Box");
|
||||
let node = h.get_by_label("Align Edges");
|
||||
assert!(node.rect().left() > gear.right() && gear.left() > radius, "{:?} after {gear:?} after the radius ({radius})", node.rect());
|
||||
assert!((node.rect().center().y - gear.center().y).abs() < 4.0, "on the gear's row");
|
||||
assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode");
|
||||
assert_eq!(node.accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_label("Snap Bounding Box").click();
|
||||
h.get_by_label("Align Edges").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.tool_options.align_edges, "clicking toggles the option");
|
||||
assert_eq!(h.get_by_label("Snap Bounding Box").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert_eq!(h.get_by_label("Align Edges").accesskit_node().toggled(), Some(Toggled::False));
|
||||
|
||||
h.state_mut().ui.tool_options.shape_mode = VectorMode::Path;
|
||||
h.run_steps(4);
|
||||
assert!(h.get_by_label("Snap Bounding Box").accesskit_node().is_disabled(), "greyed in Path mode");
|
||||
assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode");
|
||||
}
|
||||
|
||||
@@ -123,9 +123,9 @@ fn whole_box(rect: &Rect, whole: bool) -> Option<Rect> {
|
||||
(w >= 1.0 && h >= 1.0).then(|| Rect::new(x0, y0, x0 + w, y0 + h))
|
||||
}
|
||||
|
||||
/// Whether a drag of `kind` lands on whole pixels. Align Edges is the Triangle (#13370) and
|
||||
/// Rectangle (#13346) tools' option, and only in Shape mode, where its checkbox is enabled; the
|
||||
/// other Shape tools, and a greyed checkbox, still snap.
|
||||
/// Whether a drag of `kind` lands on whole pixels. The Triangle (#13370) and Rectangle (#13346)
|
||||
/// drags keep their fractions with Align Edges off in Shape mode; the other Shape tools' drags (the
|
||||
/// framework's drag lands them on pixels), and a greyed checkbox, still snap.
|
||||
pub(super) fn snaps_to_pixels(app: &PhotocraftApp, kind: ShapeKind) -> bool {
|
||||
let o = &app.ui.tool_options;
|
||||
!(matches!(kind, ShapeKind::Triangle | ShapeKind::Rectangle) && o.shape_mode == super::VectorMode::Shape && !o.align_edges)
|
||||
@@ -226,7 +226,7 @@ fn with_tool_radius(app: &PhotocraftApp, kind: ShapeKind, mut p: Value) -> Value
|
||||
/// `shape.create` params with the options bar's fill and stroke.
|
||||
fn create_params(app: &PhotocraftApp, geometry: &ShapeGeometry, kind: ShapeKind) -> Result<Value, String> {
|
||||
let mut p = geometry_params(app, geometry, kind)?;
|
||||
p["useAlignedRendering"] = json!(app.ui.tool_options.use_aligned_rendering);
|
||||
p["useAlignedRendering"] = json!(app.ui.tool_options.align_edges);
|
||||
p["fill"] = fill_param(app);
|
||||
p["stroke"] = stroke_param(app);
|
||||
Ok(p)
|
||||
@@ -288,10 +288,9 @@ pub fn finish_drag(app: &mut PhotocraftApp, kind: ShapeKind, geometry: &ShapeGeo
|
||||
}
|
||||
};
|
||||
let path = photocraft_engine::vector_cmds::path_json(&outline);
|
||||
if let Err(e) = app.run(
|
||||
"shape.create",
|
||||
json!({"kind": "path", "path": path, "addTo": id.0, "op": op, "useAlignedRendering": app.ui.tool_options.use_aligned_rendering}),
|
||||
) {
|
||||
if let Err(e) =
|
||||
app.run("shape.create", json!({"kind": "path", "path": path, "addTo": id.0, "op": op, "useAlignedRendering": app.ui.tool_options.align_edges}))
|
||||
{
|
||||
report(app, e);
|
||||
}
|
||||
return;
|
||||
@@ -424,25 +423,9 @@ fn preview_layer(app: &PhotocraftApp, kind: ShapeKind, geometry: &ShapeGeometry,
|
||||
let o = &app.ui.tool_options;
|
||||
let path = shape_outline(app, kind, geometry, keep_angle)?;
|
||||
let paint = !draws_path(o);
|
||||
let snapped_geometry = snapped(geometry, keep_angle, snaps_to_pixels(app, kind))?;
|
||||
let live = if let ShapeGeometry::Line { from, to, weight } = snapped_geometry {
|
||||
Some(photocraft_doc::LiveShape::ArrowLine {
|
||||
from: [from.x, from.y],
|
||||
to: [to.x, to.y],
|
||||
weight,
|
||||
start: o.arrow_start,
|
||||
end: o.arrow_end,
|
||||
width: f64::from(o.arrow_width),
|
||||
length: f64::from(o.arrow_length),
|
||||
concavity: if o.arrow_concavity.is_finite() { f64::from(o.arrow_concavity.round().clamp(-50.0, 50.0)) } else { 0.0 },
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(photocraft_doc::ShapeLayer {
|
||||
path,
|
||||
use_aligned_rendering: paint && o.use_aligned_rendering,
|
||||
live,
|
||||
use_aligned_rendering: paint && o.align_edges,
|
||||
fill: (paint && o.shape_fill).then(|| tool_paint(app, false)),
|
||||
stroke: (paint && o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, tool_paint(app, true))),
|
||||
..Default::default()
|
||||
@@ -475,16 +458,12 @@ pub fn show_preview(app: &PhotocraftApp, ui: &egui::Ui, at: egui::Rect, view: &C
|
||||
let Some((kind, geometry)) = super::host::shape_preview(app) else { return };
|
||||
let shift = craft::ui::runtime::pointer::frame(ui.ctx()).mods.shift;
|
||||
let Some(mut shape) = preview_layer(app, kind, geometry, shift) else { return };
|
||||
if shape.use_aligned_rendering {
|
||||
let origin = view.to_screen(Point::new(0.0, 0.0));
|
||||
let x = view.to_screen(Point::new(1.0, 0.0));
|
||||
let y = view.to_screen(Point::new(0.0, 1.0));
|
||||
let transform = photocraft_geom::Affine { m: [x.x - origin.x, x.y - origin.y, y.x - origin.x, y.y - origin.y, origin.x, origin.y].map(f64::from) };
|
||||
if let Some(st) = app.session.active() {
|
||||
crate::shape_stroke_ui::paint_document_shape_preview(&ui.painter().with_clip_rect(at), &shape, &transform, st.doc.bounds());
|
||||
}
|
||||
return;
|
||||
// Align Edges fits the shape to document pixels, so it is applied here, in document space:
|
||||
// the preview then shows the committed layer's geometry at any zoom.
|
||||
if let Some(aligned) = photocraft_vector::align_edges::aligned_shape(&shape, photocraft_vector::DEFAULT_TOLERANCE) {
|
||||
shape = aligned;
|
||||
}
|
||||
shape.use_aligned_rendering = false;
|
||||
shape.path = path_on_screen(&shape.path, view);
|
||||
if let Some(stroke) = &mut shape.stroke {
|
||||
// `view.zoom` is screen points per document unit.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! #13370: the Triangle tool's Align Edges checkbox. On (the default) the drawn box snaps to whole
|
||||
//! pixels; off it keeps the drag's fractional coordinates. It is greyed outside Shape mode.
|
||||
//! #13370: the Triangle tool's Align Edges checkbox, every shape tool's one checkbox as in the
|
||||
//! reference application. On (the default) the drawn box snaps to whole pixels; off it keeps the
|
||||
//! drag's fractional coordinates. It is greyed outside Shape mode.
|
||||
|
||||
use craft::draw::ui::VectorMode;
|
||||
use craft::draw::ui::shape_drag::ShapeKind;
|
||||
@@ -71,20 +72,41 @@ fn a_greyed_checkbox_keeps_snapping_in_path_mode() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_bar_shows_align_edges_for_the_triangle_not_the_ellipse() {
|
||||
fn options_bar_shows_align_edges_for_the_triangle() {
|
||||
let mut h = harness(Tool::Triangle);
|
||||
let node = h.get_by_label("Snap Bounding Box");
|
||||
let node = h.get_by_label("Align Edges");
|
||||
assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode");
|
||||
assert_eq!(node.accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_label("Snap Bounding Box").click();
|
||||
h.get_by_label("Align Edges").click();
|
||||
h.run_steps(3);
|
||||
assert!(!h.state().ui.tool_options.align_edges, "clicking toggles the option");
|
||||
assert_eq!(h.get_by_label("Snap Bounding Box").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert_eq!(h.get_by_label("Align Edges").accesskit_node().toggled(), Some(Toggled::False));
|
||||
|
||||
h.state_mut().ui.tool_options.shape_mode = VectorMode::Path;
|
||||
h.run_steps(4);
|
||||
assert!(h.get_by_label("Snap Bounding Box").accesskit_node().is_disabled(), "greyed in Path mode");
|
||||
assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode");
|
||||
}
|
||||
|
||||
let h = harness(Tool::EllipseShape);
|
||||
assert!(h.query_by_label("Snap Bounding Box").is_none());
|
||||
/// The reference application has one Align Edges checkbox on every shape tool's and the Pen's
|
||||
/// options bar, on after Reset Tool: here too, exactly one, on, enabled in Shape mode.
|
||||
#[test]
|
||||
fn every_shape_tool_and_the_pen_show_one_align_edges_checkbox() {
|
||||
for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Star, Tool::Line, Tool::CustomShape, Tool::Pen] {
|
||||
let mut h = harness(tool);
|
||||
h.state_mut().ui.tool_options.vector_mode = VectorMode::Shape;
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.query_all_by_label("Align Edges").count(), 1, "{tool:?}");
|
||||
let node = h.get_by_label("Align Edges");
|
||||
assert!(!node.accesskit_node().is_disabled(), "{tool:?}: enabled in Shape mode");
|
||||
assert_eq!(node.accesskit_node().toggled(), Some(Toggled::True), "{tool:?}");
|
||||
}
|
||||
let opts = ToolOptions { align_edges: false, ..Default::default() };
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.ui.tool_options = opts;
|
||||
for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Line, Tool::Pen] {
|
||||
app.ui.tool = tool;
|
||||
app.ui.tool_options.align_edges = false;
|
||||
crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap();
|
||||
assert!(app.ui.tool_options.align_edges, "{tool:?}: Reset Tool turns Align Edges back on");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Align Edges (a shape layer's `use_aligned_rendering`): at render time the whole shape is fitted
|
||||
//! to whole document pixels, as the reference application does.
|
||||
//!
|
||||
//! The rule, measured in the reference application: take the bounds of what is painted (the fill
|
||||
//! area, or the stroke's outer edge when there is a stroke), round the left/top edge to the nearest
|
||||
//! whole pixel (a half rounds up) and the width/height to whole pixels, then translate and scale the
|
||||
//! whole path so its painted bounds fill that box. Fill and stroke use the same transform. Curves
|
||||
//! keep their antialiasing, diagonals just move with the shape, and inner edges of a shape with
|
||||
//! several subpaths are not snapped one by one. The stored path is never changed: turning the flag
|
||||
//! off renders the original coverage again.
|
||||
|
||||
use photocraft_doc::{Path, ShapeLayer, StrokeAlign};
|
||||
use photocraft_geom::Affine;
|
||||
|
||||
use crate::{flatten_path, stroke_polygons, stroke_style};
|
||||
|
||||
/// Bounds `(x0, y0, x1, y1)` of a set of points; `None` when empty or not finite.
|
||||
fn points_bounds<'a>(pts: impl Iterator<Item = &'a (f64, f64)>) -> Option<(f64, f64, f64, f64)> {
|
||||
let mut b: Option<(f64, f64, f64, f64)> = None;
|
||||
for &(x, y) in pts {
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
b = Some(match b {
|
||||
None => (x, y, x, y),
|
||||
Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x), y1.max(y)),
|
||||
});
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Bounds of the path's own geometry (`path`) and of everything the shape paints (`painted`):
|
||||
/// the fill area, grown to the stroke's outer edge when the shape has a visible stroke.
|
||||
fn painted_bounds(shape: &ShapeLayer, tol: f64) -> Option<((f64, f64, f64, f64), (f64, f64, f64, f64))> {
|
||||
let lines = flatten_path(&shape.path, tol);
|
||||
let path = points_bounds(lines.iter().flat_map(|l| l.pts.iter()))?;
|
||||
let stroke = shape.stroke.as_ref().filter(|s| s.width > 0.0 && s.opacity > 0.0);
|
||||
if shape.fill.is_none() && stroke.is_none() {
|
||||
return None;
|
||||
}
|
||||
let Some(s) = stroke else { return Some((path, path)) };
|
||||
let all_closed = shape.path.subpaths.iter().all(|sp| sp.closed);
|
||||
let mut style = stroke_style(s);
|
||||
if all_closed && s.align == StrokeAlign::Inside {
|
||||
// An inside stroke is clipped by the fill area: nothing is painted beyond the path.
|
||||
return Some((path, path));
|
||||
}
|
||||
if all_closed && s.align == StrokeAlign::Outside {
|
||||
// As the renderer does: a centred outline twice as wide, of which the outer half shows.
|
||||
style.width *= 2.0;
|
||||
}
|
||||
let outline = stroke_polygons(&lines, &style, tol);
|
||||
let outer = points_bounds(outline.iter().flatten()).map_or(path, |o| (o.0.min(path.0), o.1.min(path.1), o.2.max(path.2), o.3.max(path.3)));
|
||||
Some((path, outer))
|
||||
}
|
||||
|
||||
/// One axis: the scale and offset that map the path's `lo..hi` so the painted `plo..phi` lands on
|
||||
/// whole pixels. `None` for non-finite input.
|
||||
fn fit_axis(lo: f64, hi: f64, plo: f64, phi: f64) -> Option<(f64, f64)> {
|
||||
let size = phi - plo;
|
||||
// A half rounds up (10.5 -> 11, 20.5 -> 21), as measured.
|
||||
let start = (plo + 0.5).floor();
|
||||
let mut target = (size + 0.5).floor();
|
||||
if target < 1.0 {
|
||||
// Thinner than half a pixel: keep its size rather than collapse it to nothing.
|
||||
target = size;
|
||||
}
|
||||
// The path's own extent inside the painted box (the stroke's reach on either side stays as wide).
|
||||
let (before, after) = (lo - plo, phi - hi);
|
||||
let (span, new_span) = (hi - lo, target - before - after);
|
||||
let scale = if span > 1e-9 && new_span > 0.0 { new_span / span } else { 1.0 };
|
||||
let offset = start + before - lo * scale;
|
||||
(scale.is_finite() && offset.is_finite()).then_some((scale, offset))
|
||||
}
|
||||
|
||||
/// The path the shape renders with Align Edges on: the stored path translated and scaled so its
|
||||
/// painted bounds sit on whole pixels. `None` when the flag is off, nothing is painted, the path
|
||||
/// is inverted (it paints everywhere) or already aligned, so callers render the stored path.
|
||||
pub fn aligned_path(shape: &ShapeLayer, tol: f64) -> Option<Path> {
|
||||
if !shape.use_aligned_rendering || shape.path.inverted {
|
||||
return None;
|
||||
}
|
||||
let (path, painted) = painted_bounds(shape, tol)?;
|
||||
let (sx, tx) = fit_axis(path.0, path.2, painted.0, painted.2)?;
|
||||
let (sy, ty) = fit_axis(path.1, path.3, painted.1, painted.3)?;
|
||||
if sx == 1.0 && sy == 1.0 && tx == 0.0 && ty == 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(shape.path.transform(&Affine { m: [sx, 0.0, 0.0, sy, tx, ty] }))
|
||||
}
|
||||
|
||||
/// The shape as Align Edges renders it: [`aligned_path`] in place of the stored path, the flag
|
||||
/// cleared so the result renders as it is. `None` when nothing moves. Code that renders the fill
|
||||
/// and the stroke separately (the compositor's split for layer effects) must start from this, so
|
||||
/// both parts take the transform of the whole shape, not each their own.
|
||||
pub fn aligned_shape(shape: &ShapeLayer, tol: f64) -> Option<ShapeLayer> {
|
||||
let path = aligned_path(shape, tol)?;
|
||||
Some(ShapeLayer {
|
||||
path,
|
||||
fill: shape.fill.clone(),
|
||||
stroke: shape.stroke.clone(),
|
||||
use_aligned_rendering: false,
|
||||
live: None,
|
||||
cache: None,
|
||||
psd_raw: None,
|
||||
density: shape.density,
|
||||
feather: shape.feather,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{Color, Fill, ShapeStroke};
|
||||
|
||||
fn rect_shape(x: f64, y: f64, w: f64, h: f64) -> ShapeLayer {
|
||||
ShapeLayer { path: crate::shapes::rect(x, y, w, h), fill: Some(Fill::Solid(Color::BLACK)), use_aligned_rendering: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn bounds(p: &Path) -> (f64, f64, f64, f64) {
|
||||
p.control_bounds().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_off_renders_the_stored_path() {
|
||||
let shape = ShapeLayer { use_aligned_rendering: false, ..rect_shape(10.5, 10.5, 20.0, 20.0) };
|
||||
assert!(aligned_path(&shape, 0.01).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_rounds_up_and_the_size_rounds() {
|
||||
let b = bounds(&aligned_path(&rect_shape(10.5, 10.5, 20.0, 20.0), 0.01).unwrap());
|
||||
assert_eq!(b, (11.0, 11.0, 31.0, 31.0));
|
||||
let b = bounds(&aligned_path(&rect_shape(10.25, 10.0, 20.5, 20.0), 0.01).unwrap());
|
||||
assert!((b.0 - 10.0).abs() < 1e-9 && (b.2 - 31.0).abs() < 1e-9, "{b:?}");
|
||||
let b = bounds(&aligned_path(&rect_shape(-10.5, -3.5, 20.0, 2.0), 0.01).unwrap());
|
||||
assert_eq!((b.0, b.1), (-10.0, -3.0), "a half rounds up below zero too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_aligned_shape_is_left_alone() {
|
||||
assert!(aligned_path(&rect_shape(10.0, 10.0, 20.0, 20.0), 0.01).is_none());
|
||||
let stroked = ShapeLayer { stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }), ..rect_shape(10.5, 10.5, 20.0, 20.0) };
|
||||
assert!(aligned_path(&stroked, 0.01).is_none(), "the stroke's outer edge 10..31 is already whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_and_outside_strokes_reach_as_far_as_they_paint() {
|
||||
let with = |align, width| ShapeLayer { stroke: Some(ShapeStroke { width, align, ..Default::default() }), ..rect_shape(10.5, 10.5, 20.0, 20.0) };
|
||||
// Inside: painted bounds are the path's, 10.5 -> 11.
|
||||
assert_eq!(bounds(&aligned_path(&with(StrokeAlign::Inside, 2.0), 0.01).unwrap()).0, 11.0);
|
||||
// Outside 1 px: painted 9.5..31.5 -> 10..32, the path moves to 11..31.
|
||||
assert_eq!(bounds(&aligned_path(&with(StrokeAlign::Outside, 1.0), 0.01).unwrap()).0, 11.0);
|
||||
// Outside 2 px: painted 8.5..32.5 -> 9..33, the path moves to 11..31.
|
||||
assert_eq!(bounds(&aligned_path(&with(StrokeAlign::Outside, 2.0), 0.01).unwrap()).0, 11.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_painted_inverted_or_hostile_input_renders_unchanged() {
|
||||
let unpainted = ShapeLayer { fill: None, stroke: None, ..rect_shape(10.5, 10.5, 20.0, 20.0) };
|
||||
assert!(aligned_path(&unpainted, 0.01).is_none());
|
||||
let mut inverted = rect_shape(10.5, 10.5, 20.0, 20.0);
|
||||
inverted.path.inverted = true;
|
||||
assert!(aligned_path(&inverted, 0.01).is_none());
|
||||
assert!(aligned_path(&rect_shape(f64::NAN, 1.0, 2.0, 2.0), 0.01).is_none());
|
||||
assert!(aligned_path(&rect_shape(1.0, 1.0, f64::INFINITY, 2.0), 0.01).is_none());
|
||||
assert!(aligned_path(&ShapeLayer { use_aligned_rendering: true, fill: Some(Fill::Solid(Color::BLACK)), ..Default::default() }, 0.01).is_none());
|
||||
// Huge but finite coordinates must not panic.
|
||||
let _ = aligned_path(&rect_shape(1e300, -1e300, 1e300, 1e-300), 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliver_keeps_its_size_and_a_line_just_moves() {
|
||||
let b = bounds(&aligned_path(&rect_shape(10.6, 10.0, 0.3, 20.0), 0.01).unwrap());
|
||||
assert!((b.2 - b.0 - 0.3).abs() < 1e-9 && b.0 == 11.0, "{b:?}");
|
||||
// A zero-width path (a vertical line) with a 1 px stroke: painted 9.75..10.75 -> 10..11.
|
||||
let line = ShapeLayer {
|
||||
path: Path::new(vec![photocraft_doc::Subpath::polyline(&[(10.25, 10.0), (10.25, 30.0)])]),
|
||||
fill: None,
|
||||
stroke: Some(ShapeStroke { width: 1.0, ..Default::default() }),
|
||||
use_aligned_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
let b = bounds(&aligned_path(&line, 0.01).unwrap());
|
||||
assert_eq!((b.0, b.2), (10.5, 10.5));
|
||||
}
|
||||
}
|
||||
+16
-114
@@ -20,11 +20,11 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod align_edges;
|
||||
pub mod edit;
|
||||
pub mod feather;
|
||||
pub mod flatten;
|
||||
pub mod map;
|
||||
mod pixel_align;
|
||||
pub mod raster;
|
||||
pub mod shapes;
|
||||
pub mod stroke;
|
||||
@@ -42,14 +42,6 @@ pub use stroke::{StrokeStyle, stroke_polygons};
|
||||
/// Default flattening tolerance in pixels (curve-to-chord distance).
|
||||
pub const DEFAULT_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// Render-only fill path for an eligible aligned live Line/ArrowLine, in document pixels.
|
||||
/// Previews apply their view transform afterwards, matching committed document rendering.
|
||||
/// Returns `None` for unpainted paths or geometry that must retain legacy placement.
|
||||
pub fn pixel_aligned_line_fill_path(shape: &ShapeLayer) -> Option<Path> {
|
||||
shape.fill.as_ref()?;
|
||||
pixel_align::line_fill_path(shape)
|
||||
}
|
||||
|
||||
/// Compiles the fill area of `path`: one component per subpath (filled with the path's rule)
|
||||
/// folded with the subpath operations; open subpaths are closed implicitly.
|
||||
pub fn fill_rasterizer(path: &Path, tol: f64) -> Rasterizer {
|
||||
@@ -72,38 +64,9 @@ fn fill_rasterizer_with(path: &Path, tol: f64, ctl: &Interrupt) -> Option<Raster
|
||||
|
||||
/// Compiles the stroke outline of `path` (all subpaths, one non-zero component).
|
||||
pub fn stroke_rasterizer(path: &Path, style: &StrokeStyle, tol: f64) -> Rasterizer {
|
||||
stroke_rasterizer_with_alignment(path, style, tol, false)
|
||||
}
|
||||
|
||||
/// Align actual straight outline edges for integral widths above one pixel.
|
||||
/// Curved source paths keep their original outline antialiasing.
|
||||
fn stroke_rasterizer_with_alignment(path: &Path, style: &StrokeStyle, tol: f64, aligned: bool) -> Rasterizer {
|
||||
// Stroke outlines tolerate a coarser flattening than fills (the offset hides chord error).
|
||||
let lines = flatten_path(path, (tol * 4.0).min(style.width.max(0.01) * 0.1).max(1e-3));
|
||||
let mut polys = stroke_polygons(&lines, style, tol);
|
||||
// Rounding both edges of a fractional-width outline can collapse it to zero.
|
||||
// Keep its area coverage: a subpixel stroke cannot occupy an opaque integer row.
|
||||
if aligned
|
||||
&& style.width >= 2.0
|
||||
&& style.width.fract() == 0.0
|
||||
&& path.subpaths.iter().all(|subpath| subpath.knots.iter().all(|knot| knot.anchor == knot.in_ctrl && knot.anchor == knot.out_ctrl))
|
||||
{
|
||||
for polygon in &mut polys {
|
||||
let original = polygon.clone();
|
||||
for index in 0..original.len() {
|
||||
let next = (index + 1) % original.len();
|
||||
let (a, b) = (original[index], original[next]);
|
||||
if a.0 == b.0 {
|
||||
polygon[index].0 = pixel_align::snap_edge(a.0);
|
||||
polygon[next].0 = pixel_align::snap_edge(b.0);
|
||||
}
|
||||
if a.1 == b.1 {
|
||||
polygon[index].1 = pixel_align::snap_edge(a.1);
|
||||
polygon[next].1 = pixel_align::snap_edge(b.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let polys = stroke_polygons(&lines, style, tol);
|
||||
let mut r = Rasterizer::new(false);
|
||||
r.add_component(&polys, PathOp::Combine, FillRule::NonZero);
|
||||
r
|
||||
@@ -609,16 +572,10 @@ impl FillCoverage {
|
||||
|
||||
/// Everything needed to render a shape layer, compiled once.
|
||||
pub struct CompiledShape {
|
||||
pixel_stroke: pixel_align::PixelRuns,
|
||||
pixel_dash_caps: pixel_align::PixelRuns,
|
||||
pixel_dash_threshold: f32,
|
||||
pixel_dash_centers: bool,
|
||||
pixel_dash_bias: Option<Rasterizer>,
|
||||
pixel_rectangle: Option<(f64, f64, f64, f64)>,
|
||||
fill: Option<(FillCoverage, Paint)>,
|
||||
stroke: Option<(Rasterizer, Paint, f32)>,
|
||||
/// Fill area used to clip inside/outside strokes.
|
||||
align: Option<(Rasterizer, bool, f32)>,
|
||||
align: Option<(Rasterizer, bool)>,
|
||||
bounds: Option<Rect>,
|
||||
}
|
||||
|
||||
@@ -631,71 +588,33 @@ impl CompiledShape {
|
||||
|
||||
/// [`CompiledShape::new`] with the feather computed over `coverage` while gradients still lay
|
||||
/// out in `gradient_frame`: measuring a shape beyond the canvas it is drawn in.
|
||||
///
|
||||
/// A shape with Align Edges on (`use_aligned_rendering`) renders [`align_edges::aligned_path`]
|
||||
/// instead of its stored path: every renderer (layer caches, the compositor's fill/stroke
|
||||
/// split, previews, extents) compiles shapes here, so they all agree.
|
||||
pub fn with_frames(shape: &ShapeLayer, tol: f64, coverage: Rect, gradient_frame: Rect) -> Self {
|
||||
let aligned = align_edges::aligned_shape(shape, tol);
|
||||
let shape = aligned.as_ref().unwrap_or(shape);
|
||||
let pb = shape.path.control_bounds().unwrap_or((0.0, 0.0, 0.0, 0.0));
|
||||
// Dash arc lengths and phase belong to the stored geometry. Snap the
|
||||
// resulting outline/coverage, never the path fed to dash generation.
|
||||
let dashed_path = shape.stroke.as_ref().filter(|s| !s.dashes.is_empty()).map(|_| &shape.path);
|
||||
let aligned_shape = pixel_align::aligned_edge_path(shape).map(|path| ShapeLayer { path, live: None, ..shape.clone() });
|
||||
let shape = aligned_shape.as_ref().unwrap_or(shape);
|
||||
let g = gradient_frame;
|
||||
let cb = (f64::from(g.x0), f64::from(g.y0), f64::from(g.x1), f64::from(g.y1));
|
||||
let area = fill_rasterizer(&shape.path, tol);
|
||||
let mut bounds = None;
|
||||
let fill = shape.fill.as_ref().map(|f| {
|
||||
let aligned = pixel_align::line_fill_path(shape).map(|p| fill_rasterizer(&p, tol));
|
||||
let coverage = FillCoverage::new(shape, aligned.as_ref().unwrap_or(&area), coverage);
|
||||
let coverage = FillCoverage::new(shape, &area, coverage);
|
||||
bounds = coverage.bounds();
|
||||
(coverage, Paint::from_fill(f, pb, cb))
|
||||
});
|
||||
let all_closed = shape.path.subpaths.iter().all(|s| s.closed);
|
||||
let mut align = None;
|
||||
let coordinate_tolerance = pixel_align::coordinate_tolerance(shape, gradient_frame);
|
||||
let pixel_rectangle =
|
||||
pixel_align::rectangle_bounds(shape, coordinate_tolerance).map(|bounds| dashed_path.and_then(Path::control_bounds).unwrap_or(bounds));
|
||||
let mut pixel_stroke = pixel_align::PixelRuns::stroke(shape, tol, coordinate_tolerance);
|
||||
// The stroker's round caps preserve circular area. Their half-circle
|
||||
// outside an integer dash boundary has area pi/8 at width 1. Use that
|
||||
// tie instead of 1/2, retaining the caps' extra pixel of raster length.
|
||||
let pixel_dash_threshold =
|
||||
if shape.stroke.as_ref().is_some_and(|s| s.cap == photocraft_doc::LineCap::Round) { std::f32::consts::PI / 8.0 } else { 0.5 };
|
||||
let mut pixel_dash_caps = if shape.stroke.as_ref().is_some_and(|s| !s.dashes.is_empty()) {
|
||||
pixel_align::PixelRuns::stroke(shape, tol, coordinate_tolerance)
|
||||
} else {
|
||||
pixel_align::PixelRuns::default()
|
||||
};
|
||||
if let Some(path) = dashed_path {
|
||||
pixel_dash_caps.use_source_coordinates(path);
|
||||
}
|
||||
let mut pixel_dash_bias = None;
|
||||
let stroke = shape.stroke.as_ref().filter(|s| s.width > 0.0 && s.opacity > 0.0).map(|s| {
|
||||
let mut st = stroke_style(s);
|
||||
if all_closed && s.align != StrokeAlign::Center {
|
||||
// Inside/outside strokes: a centred stroke twice as wide, clipped by the fill area.
|
||||
st.width *= 2.0;
|
||||
align = Some((area.clone(), s.align == StrokeAlign::Inside, 1.0));
|
||||
}
|
||||
if let Some((x0, y0, x1, y1)) = pixel_rectangle {
|
||||
if dashed_path.is_some() {
|
||||
// The original stroke can sit entirely outside the selected row
|
||||
// at a half-pixel tie. Move its normal coverage before clipping.
|
||||
pixel_stroke.select_rectangle_interior((x0, y0, x1, y1));
|
||||
pixel_dash_caps.select_rectangle_interior((x0, y0, x1, y1));
|
||||
} else {
|
||||
pixel_stroke = pixel_align::PixelRuns::default();
|
||||
}
|
||||
// Preserve dash positions from the original vector path.
|
||||
// Select the interior pixel row for crisp 1px strokes.
|
||||
let (x0, y0, x1, y1) = (pixel_align::snap_edge(x0), pixel_align::snap_edge(y0), pixel_align::snap_edge(x1), pixel_align::snap_edge(y1));
|
||||
let mask = shapes::rect(x0, y0, x1 - x0, y1 - y0);
|
||||
align = Some((fill_rasterizer(&mask, tol), true, 2.0));
|
||||
}
|
||||
let r = stroke_rasterizer_with_alignment(dashed_path.unwrap_or(&shape.path), &st, tol, shape.use_aligned_rendering);
|
||||
if !pixel_dash_caps.is_empty() {
|
||||
// A tiny positive translation resolves only otherwise indistinguishable cap
|
||||
// ties. Reuse the compiled outline so dash lengths, phase and budgets agree.
|
||||
pixel_dash_bias = Some(r.translated(1.0 / 1024.0, 1.0 / 1024.0));
|
||||
align = Some((area.clone(), s.align == StrokeAlign::Inside));
|
||||
}
|
||||
let r = stroke_rasterizer(&shape.path, &st, tol);
|
||||
let sb = r.pixel_bounds();
|
||||
bounds = match (bounds, sb) {
|
||||
(Some(a), Some(b)) => Some(a.union(&b)),
|
||||
@@ -706,8 +625,7 @@ impl CompiledShape {
|
||||
if shape.path.inverted && shape.fill.is_some() {
|
||||
bounds = Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4));
|
||||
}
|
||||
let pixel_dash_centers = shape.stroke.as_ref().is_some_and(|s| s.cap == photocraft_doc::LineCap::Butt);
|
||||
CompiledShape { fill, stroke, align, bounds, pixel_stroke, pixel_dash_caps, pixel_dash_threshold, pixel_dash_centers, pixel_dash_bias, pixel_rectangle }
|
||||
CompiledShape { fill, stroke, align, bounds }
|
||||
}
|
||||
|
||||
/// Pixel bounds of the rendering (`None` = nothing visible).
|
||||
@@ -733,28 +651,12 @@ impl CompiledShape {
|
||||
}
|
||||
if let Some((r, paint, opacity)) = &self.stroke {
|
||||
let mut cov = r.render(rect);
|
||||
self.pixel_stroke.apply(rect, &mut cov, |region| r.render(region));
|
||||
if let Some((area, inside, scale)) = &self.align {
|
||||
if let Some((area, inside)) = &self.align {
|
||||
let a = area.render(rect);
|
||||
for (i, (c, f)) in cov.iter_mut().zip(&a).enumerate() {
|
||||
if *c <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let clip = if *inside { *f } else { 1.0 - *f };
|
||||
if clip <= 0.0 {
|
||||
*c = 0.0;
|
||||
continue;
|
||||
}
|
||||
let scale = self
|
||||
.pixel_rectangle
|
||||
.map_or(*scale, |bounds| pixel_align::rectangle_coverage_scale(bounds, rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32));
|
||||
*c = (*c * clip * scale).min(1.0);
|
||||
for (c, f) in cov.iter_mut().zip(&a) {
|
||||
*c *= if *inside { *f } else { 1.0 - *f };
|
||||
}
|
||||
}
|
||||
self.pixel_dash_caps.sharpen_dash_caps(rect, &mut cov, self.pixel_dash_threshold, r, self.pixel_dash_bias.as_ref(), self.pixel_dash_centers);
|
||||
if let Some(bounds) = self.pixel_rectangle.filter(|_| self.pixel_dash_bias.is_some()) {
|
||||
pixel_align::restore_rectangle_dash_corners(bounds, rect, &mut cov, r);
|
||||
}
|
||||
for (i, (o, c)) in out.iter_mut().zip(&cov).enumerate() {
|
||||
if *c <= 0.0 {
|
||||
continue;
|
||||
|
||||
@@ -1,565 +0,0 @@
|
||||
//! Render-only alignment of shape edges and straight one-pixel stroke runs. Stored
|
||||
//! geometry and dash settings remain unchanged; curved interiors retain area antialiasing.
|
||||
use photocraft_doc::{LiveShape, Path, ShapeLayer, StrokeAlign};
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
// Trigonometric live shapes and quarter-turn transforms carry tiny rounding errors.
|
||||
const ALIGN_EPSILON: f64 = 1e-7;
|
||||
/// Round an edge to the nearest pixel, choosing increasing coordinates at half ties.
|
||||
/// Comparing the fractional part avoids addition rounding just below a half pixel.
|
||||
pub(crate) fn snap_edge(coordinate: f64) -> f64 {
|
||||
let lower = coordinate.floor();
|
||||
if coordinate - lower >= 0.5 { lower + 1.0 } else { lower }
|
||||
}
|
||||
|
||||
type CleanLine = (Vec<(f64, f64)>, Vec<bool>);
|
||||
/// Compare source coordinates without treating flattened curve chords as straight segments.
|
||||
fn same(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() <= ALIGN_EPSILON
|
||||
}
|
||||
|
||||
/// A PSD path is rounded to signed 8.24 fractions of the document dimensions. Only
|
||||
/// imported PSD geometry gets its half-quantum allowance; native paths keep the strict epsilon.
|
||||
pub(crate) fn coordinate_tolerance(shape: &ShapeLayer, _canvas: Rect) -> (f64, f64) {
|
||||
let [width, height] = match shape.psd_coordinate_frame {
|
||||
Some(frame) => frame,
|
||||
// Import and native-load migration supply provenance. A render ROI cannot.
|
||||
None => return (ALIGN_EPSILON, ALIGN_EPSILON),
|
||||
};
|
||||
// Valid PSB dimensions need less than 0.009 px; cap hostile oversized frames too.
|
||||
let epsilon = |side: u32| (f64::from(side) / 33_554_432.0).clamp(ALIGN_EPSILON, 1.0 / 64.0);
|
||||
(epsilon(width), epsilon(height))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PixelRuns(Vec<Run>);
|
||||
struct Run {
|
||||
horizontal: bool,
|
||||
coordinate: i32,
|
||||
negative_side: bool,
|
||||
sample_offset: f64,
|
||||
start: f64,
|
||||
end: f64,
|
||||
}
|
||||
impl PixelRuns {
|
||||
/// Quantize only dash cap coverage on isolated axis runs. Butt caps sample the
|
||||
/// compiled outline at pixel centers; extended caps retain area selection. Sampling neighbors
|
||||
/// resolves an exact half-pixel tie consistently: round both boundaries toward
|
||||
/// increasing document coordinates. A 9px dash therefore stays 9 opaque pixels,
|
||||
/// including when its phase alternates between integer and half-integer starts.
|
||||
/// Ambiguous equal-neighbor ties probe a positively biased copy of the compiled edges;
|
||||
/// this distinguishes alternating one-pixel dashes whose area samples are all one half.
|
||||
pub(crate) fn sharpen_dash_caps(
|
||||
&self,
|
||||
rect: Rect,
|
||||
coverage: &mut [f32],
|
||||
threshold: f32,
|
||||
rasterizer: &crate::raster::Rasterizer,
|
||||
biased_rasterizer: Option<&crate::raster::Rasterizer>,
|
||||
sample_centers: bool,
|
||||
) {
|
||||
let width = rect.width() as usize;
|
||||
for run in &self.0 {
|
||||
let lo = run.start.ceil() as i32;
|
||||
let hi = run.end.floor() as i32;
|
||||
let c = run.coordinate;
|
||||
let strip = if run.horizontal { Rect::new(lo, c - 1, hi, c + 1) } else { Rect::new(c - 1, lo, c + 1, hi) };
|
||||
let visible = strip.intersect(&rect);
|
||||
if visible.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Probe the original outline at the centerline and along-axis pixel centers.
|
||||
// The small negative bias preserves the existing positive-coordinate tie policy.
|
||||
let centers_rect = if run.horizontal { Rect::new(visible.x0, c, visible.x1, c + 1) } else { Rect::new(c, visible.y0, c + 1, visible.y1) };
|
||||
let offset = if run.horizontal { (0.5 - 1e-6, run.sample_offset) } else { (run.sample_offset, 0.5 - 1e-6) };
|
||||
if sample_centers {
|
||||
let centers = rasterizer.point_samples(centers_rect, offset);
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = (y - rect.y0) as usize * width + (x - rect.x0) as usize;
|
||||
let sample = if run.horizontal { x - visible.x0 } else { y - visible.y0 } as usize;
|
||||
if let Some(out) = coverage.get_mut(index).filter(|out| **out > 0.0) {
|
||||
*out = centers.get(sample).copied().unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let source = if run.horizontal {
|
||||
Rect::new(visible.x0.saturating_sub(1), c - 1, visible.x1.saturating_add(1), c + 1)
|
||||
} else {
|
||||
Rect::new(c - 1, visible.y0.saturating_sub(1), c + 1, visible.y1.saturating_add(1))
|
||||
};
|
||||
let values = rasterizer.render(source);
|
||||
let mut biased = None;
|
||||
let sw = source.width() as usize;
|
||||
let sum = |p: i32| {
|
||||
let k = if run.horizontal { (p - source.x0) as usize } else { (p - source.y0) as usize * sw };
|
||||
let adjacent = if run.horizontal { k + sw } else { k + 1 };
|
||||
values.get(k).copied().unwrap_or(0.0) + values.get(adjacent).copied().unwrap_or(0.0)
|
||||
};
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = (y - rect.y0) as usize * width + (x - rect.x0) as usize;
|
||||
let Some(out) = coverage.get_mut(index) else {
|
||||
continue;
|
||||
};
|
||||
// The normal alignment / rectangle clip already selects the row.
|
||||
if *out <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let p = if run.horizontal { x } else { y };
|
||||
let value = sum(p);
|
||||
*out = if (value - threshold).abs() <= 1e-5 {
|
||||
let before = sum(p.saturating_sub(1));
|
||||
let after = sum(p.saturating_add(1));
|
||||
if (before - after).abs() > 1e-5 {
|
||||
f32::from(before > after)
|
||||
} else {
|
||||
let values = biased.get_or_insert_with(|| biased_rasterizer.map_or_else(Vec::new, |r| r.render(source)));
|
||||
let k = if run.horizontal { (p - source.x0) as usize } else { (p - source.y0) as usize * sw };
|
||||
let adjacent = if run.horizontal { k + sw } else { k + 1 };
|
||||
f32::from(values.get(k).copied().unwrap_or(0.0) + values.get(adjacent).copied().unwrap_or(0.0) > threshold)
|
||||
}
|
||||
} else {
|
||||
f32::from(value > threshold)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any isolated source run can use coverage alignment.
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
/// Keep centered one-pixel source runs isolated from neighboring geometry and joins.
|
||||
pub(crate) fn stroke(shape: &ShapeLayer, tol: f64, coordinate_tolerance: (f64, f64)) -> Self {
|
||||
if !shape.use_aligned_rendering || !shape.stroke.as_ref().is_some_and(|s| s.width == 1.0 && s.align == StrokeAlign::Center) {
|
||||
return Self::default();
|
||||
}
|
||||
let mut runs = Self::path(&shape.path, coordinate_tolerance);
|
||||
if runs.0.is_empty() {
|
||||
return runs;
|
||||
}
|
||||
let Some(joins) = join_bounds(shape, tol) else {
|
||||
return Self::default();
|
||||
};
|
||||
runs.0.retain(|run| {
|
||||
joins.iter().all(|(p, radius)| {
|
||||
let (along, normal) = if run.horizontal { (p.0, p.1) } else { (p.1, p.0) };
|
||||
along + radius <= run.start
|
||||
|| along - radius >= run.end
|
||||
|| normal + radius <= f64::from(run.coordinate) - 1.0
|
||||
|| normal - radius >= f64::from(run.coordinate) + 1.0
|
||||
})
|
||||
});
|
||||
runs
|
||||
}
|
||||
/// Leave endpoint guards on an integer-axis segment long enough to have a safe interior.
|
||||
fn segment(a: (f64, f64), b: (f64, f64), tolerance: (f64, f64)) -> Self {
|
||||
let horizontal = same(a.1, b.1);
|
||||
if !horizontal && !same(a.0, b.0) {
|
||||
return Self::default();
|
||||
}
|
||||
let (coordinate, start, end) = if horizontal { (a.1, a.0.min(b.0), a.0.max(b.0)) } else { (a.0, a.1.min(b.1), a.1.max(b.1)) };
|
||||
if !coordinate.is_finite()
|
||||
|| (coordinate - coordinate.round()).abs() > if horizontal { tolerance.1 } else { tolerance.0 }
|
||||
// Normal-axis sampling needs both adjacent integer rows/columns.
|
||||
|| coordinate.round() <= f64::from(i32::MIN)
|
||||
|| coordinate.round() >= f64::from(i32::MAX)
|
||||
|| !start.is_finite()
|
||||
|| !end.is_finite()
|
||||
|| end - start < 5.0
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
Self(vec![Run { horizontal, coordinate: coordinate.round() as i32, negative_side: false, sample_offset: 0.0, start: start + 2.0, end: end - 2.0 }])
|
||||
}
|
||||
/// Find straight source segments with bounded overlap checks; curves retain normal coverage.
|
||||
fn path(path: &Path, coordinate_tolerance: (f64, f64)) -> Self {
|
||||
// Alignment is optional. Complex artwork retains its normal bounded renderer;
|
||||
// do not add quadratic compilation work to arbitrary imported paths.
|
||||
if path.subpaths.iter().map(|s| s.knots.len()).sum::<usize>() > 256 {
|
||||
return Self::default();
|
||||
}
|
||||
let segments: Vec<_> = path.subpaths.iter().flat_map(|s| s.segments()).collect();
|
||||
let mut runs = Self::default();
|
||||
for (i, [a, c1, c2, b]) in segments.iter().enumerate() {
|
||||
if !((same(a.x, b.x) && same(c1.x, a.x) && same(c2.x, a.x)) || (same(a.y, b.y) && same(c1.y, a.y) && same(c2.y, a.y))) {
|
||||
continue;
|
||||
}
|
||||
let candidate = Self::segment((a.x, a.y), (b.x, b.y), coordinate_tolerance);
|
||||
for run in candidate.0 {
|
||||
// Coverage belongs to the entire stroke. Leave crossing/overlapping
|
||||
// geometry alone rather than moving another segment's antialiasing.
|
||||
let isolated = segments.iter().enumerate().all(|(j, points)| i == j || isolated(&run, points, 0.75));
|
||||
if isolated {
|
||||
runs.0.push(run);
|
||||
}
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
/// Probe dash centers on the stored segment even when its normal coordinate snapped.
|
||||
/// Run discovery already caps the source to 256 knots and excludes overlaps.
|
||||
pub(crate) fn use_source_coordinates(&mut self, path: &Path) {
|
||||
if self.is_empty() {
|
||||
return;
|
||||
}
|
||||
let segments: Vec<_> = path.subpaths.iter().flat_map(|s| s.segments()).collect();
|
||||
for run in &mut self.0 {
|
||||
for points in &segments {
|
||||
let coordinate = if run.horizontal { points[0].y } else { points[0].x };
|
||||
let on_axis = points.iter().all(|p| same(if run.horizontal { p.y } else { p.x }, coordinate));
|
||||
let (a, b) = if run.horizontal { (points[0].x, points[3].x) } else { (points[0].y, points[3].y) };
|
||||
if on_axis && snap_edge(coordinate) == f64::from(run.coordinate) && a.min(b) <= run.start && a.max(b) >= run.end {
|
||||
run.sample_offset = coordinate - f64::from(run.coordinate);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangle strokes select the interior side on the right and bottom edges.
|
||||
pub(crate) fn select_rectangle_interior(&mut self, (x0, y0, x1, y1): (f64, f64, f64, f64)) {
|
||||
for run in &mut self.0 {
|
||||
let (low, high) = if run.horizontal { (y0, y1) } else { (x0, x1) };
|
||||
run.negative_side = f64::from(run.coordinate) == snap_edge(high);
|
||||
run.sample_offset = if run.negative_side { high } else { low } - f64::from(run.coordinate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Combine normal-axis coverage in the selected pixel, sampling beyond tile boundaries.
|
||||
pub(crate) fn apply(&self, rect: Rect, coverage: &mut [f32], sample: impl Fn(Rect) -> Vec<f32>) {
|
||||
let width = rect.width() as usize;
|
||||
for run in &self.0 {
|
||||
let lo = run.start.ceil() as i32;
|
||||
let hi = run.end.floor() as i32;
|
||||
let c = run.coordinate;
|
||||
let strip = if run.horizontal { Rect::new(lo, c - 1, hi, c + 1) } else { Rect::new(c - 1, lo, c + 1, hi) };
|
||||
// Sample both rows even when the caller renders tiles/bands split at the run.
|
||||
let visible = strip.intersect(&rect);
|
||||
if visible.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let source = if run.horizontal { Rect::new(visible.x0, c - 1, visible.x1, c + 1) } else { Rect::new(c - 1, visible.y0, c + 1, visible.y1) };
|
||||
let values = sample(source);
|
||||
let sw = source.width() as usize;
|
||||
for y in visible.y0..visible.y1 {
|
||||
for x in visible.x0..visible.x1 {
|
||||
let index = (y - rect.y0) as usize * width + (x - rect.x0) as usize;
|
||||
let k = if run.horizontal { (x - source.x0) as usize } else { (y - source.y0) as usize * sw };
|
||||
let adjacent = if run.horizontal { k + sw } else { k + 1 };
|
||||
if let (Some(out), Some(a), Some(b)) = (coverage.get_mut(index), values.get(k), values.get(adjacent)) {
|
||||
*out = if (if run.horizontal { y } else { x }) == c - i32::from(run.negative_side) { (*a + *b).min(1.0) } else { 0.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Line Tool bar is a fill, so translate its render-only copy by half a pixel.
|
||||
/// Moving the whole arrow also retains antialiasing and the proportions of its heads.
|
||||
pub(crate) fn line_fill_path(shape: &ShapeLayer) -> Option<Path> {
|
||||
// A completely transparent solid outline paints nothing and must not prevent
|
||||
// alignment of the live bar. Other paints retain conservative legacy placement.
|
||||
let visible_outline = shape
|
||||
.stroke
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.width > 0.0 && s.opacity > 0.0 && !matches!(&s.paint, photocraft_doc::Fill::Solid(color) if color.alpha <= 0.0));
|
||||
if !shape.use_aligned_rendering || shape.has_soft_mask() || visible_outline {
|
||||
return None;
|
||||
}
|
||||
let live = shape.live.as_ref()?;
|
||||
let (from, to, weight) = match live {
|
||||
LiveShape::Line { from, to, weight } | LiveShape::ArrowLine { from, to, weight, .. } => (from, to, weight),
|
||||
_ => return None,
|
||||
};
|
||||
if *weight != 1.0 || !equivalent_live_path(&crate::shapes::live_path(live), &shape.path) {
|
||||
return None;
|
||||
}
|
||||
let horizontal = same(from[1], to[1]) && !same(from[0], to[0]);
|
||||
let vertical = same(from[0], to[0]) && !same(from[1], to[1]);
|
||||
let coordinate = if horizontal { from[1] } else { from[0] };
|
||||
if (!horizontal && !vertical) || !coordinate.is_finite() || !same(coordinate, coordinate.round()) {
|
||||
return None;
|
||||
}
|
||||
Some(shape.path.transform(&photocraft_geom::Affine::translate(if vertical { 0.5 } else { 0.0 }, if horizontal { 0.5 } else { 0.0 })))
|
||||
}
|
||||
|
||||
/// Reflections reverse closed outlines and can change their first knot. Compare all
|
||||
/// controls too, so stale live metadata cannot qualify a different filled shape.
|
||||
fn equivalent_live_path(expected: &Path, stored: &Path) -> bool {
|
||||
if expected == stored {
|
||||
return true;
|
||||
}
|
||||
if expected.fill_rule != stored.fill_rule || expected.inverted != stored.inverted || expected.subpaths.len() != stored.subpaths.len() {
|
||||
return false;
|
||||
}
|
||||
expected.subpaths.iter().zip(&stored.subpaths).all(|(a, b)| {
|
||||
if !a.closed || !b.closed || a.op != b.op || a.knots.len() != b.knots.len() {
|
||||
return false;
|
||||
}
|
||||
let matching = |left: &[photocraft_doc::Knot], right: &[photocraft_doc::Knot]| {
|
||||
left.iter().zip(right).all(|(l, r)| {
|
||||
l.smooth == r.smooth
|
||||
&& [l.anchor, l.in_ctrl, l.out_ctrl].into_iter().zip([r.anchor, r.in_ctrl, r.out_ctrl]).all(|(p, q)| same(p.x, q.x) && same(p.y, q.y))
|
||||
})
|
||||
};
|
||||
if matching(&a.knots, &b.knots) {
|
||||
return true;
|
||||
}
|
||||
let mut reversed = a.knots.clone();
|
||||
reversed.reverse();
|
||||
for knot in &mut reversed {
|
||||
std::mem::swap(&mut knot.in_ctrl, &mut knot.out_ctrl);
|
||||
}
|
||||
for _ in 0..reversed.len() {
|
||||
if matching(&reversed, &b.knots) {
|
||||
return true;
|
||||
}
|
||||
reversed.rotate_left(1);
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
/// Reject a run when another source segment or its control bounds enter its coverage strip.
|
||||
fn isolated(run: &Run, points: &[photocraft_geom::Point; 4], padding: f64) -> bool {
|
||||
let c = f64::from(run.coordinate);
|
||||
let [a, c1, c2, b] = points;
|
||||
if a == c1 && b == c2 {
|
||||
let (n0, n1, t0, t1) = if run.horizontal { (a.y, b.y, a.x, b.x) } else { (a.x, b.x, a.y, b.y) };
|
||||
let delta = n1 - n0;
|
||||
if delta != 0.0 {
|
||||
let u = (c - 1.0 - padding - n0) / delta;
|
||||
let v = (c + 1.0 + padding - n0) / delta;
|
||||
let lo = u.min(v).max(0.0);
|
||||
let hi = u.max(v).min(1.0);
|
||||
if lo > hi {
|
||||
return true;
|
||||
}
|
||||
let p = t0 + (t1 - t0) * lo;
|
||||
let q = t0 + (t1 - t0) * hi;
|
||||
return p.max(q) + padding <= run.start || p.min(q) - padding >= run.end;
|
||||
}
|
||||
}
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in points {
|
||||
x0 = x0.min(p.x);
|
||||
y0 = y0.min(p.y);
|
||||
x1 = x1.max(p.x);
|
||||
y1 = y1.max(p.y);
|
||||
}
|
||||
if run.horizontal {
|
||||
x1 + padding <= run.start || x0 - padding >= run.end || y1 + padding <= c - 1.0 || y0 - padding >= c + 1.0
|
||||
} else {
|
||||
y1 + padding <= run.start || y0 - padding >= run.end || x1 + padding <= c - 1.0 || x0 - padding >= c + 1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognize the same rectangle after a reversed traversal or quarter-turn transform.
|
||||
/// The stored path still determines stroke geometry and dash phase.
|
||||
pub(crate) fn integer_rectangle(path: &Path, tolerance: (f64, f64)) -> bool {
|
||||
if path.inverted || path.subpaths.len() != 1 {
|
||||
return false;
|
||||
}
|
||||
let Some(s) = path.subpaths.first() else {
|
||||
return false;
|
||||
};
|
||||
if !s.closed || s.knots.len() != 4 {
|
||||
return false;
|
||||
}
|
||||
let Some((x0, y0, x1, y1)) = path.control_bounds() else {
|
||||
return false;
|
||||
};
|
||||
let near_integer = |coordinate: f64, epsilon: f64| coordinate.is_finite() && (coordinate - coordinate.round()).abs() <= epsilon;
|
||||
if x1.round() - x0.round() < 2.0
|
||||
|| y1.round() - y0.round() < 2.0
|
||||
|| ![(x0, tolerance.0), (x1, tolerance.0), (y0, tolerance.1), (y1, tolerance.1)].iter().all(|(value, epsilon)| near_integer(*value, *epsilon))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut corners = 0u8;
|
||||
for k in &s.knots {
|
||||
corners |= 1 << (u8::from(same(k.anchor.x, x1)) + 2 * u8::from(same(k.anchor.y, y1)));
|
||||
if !(same(k.anchor.x, x0) || same(k.anchor.x, x1)) || !(same(k.anchor.y, y0) || same(k.anchor.y, y1)) || k.in_ctrl != k.anchor || k.out_ctrl != k.anchor
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
corners == 15 && s.segments().iter().all(|[a, _, _, b]| (same(a.x, b.x) && !same(a.y, b.y)) || (same(a.y, b.y) && !same(a.x, b.x)))
|
||||
}
|
||||
|
||||
/// The original bounds of an eligible rectangle; only its render-time clipping mask is rounded.
|
||||
pub(crate) fn rectangle_bounds(shape: &ShapeLayer, tolerance: (f64, f64)) -> Option<(f64, f64, f64, f64)> {
|
||||
let stroke = shape.stroke.as_ref()?;
|
||||
if !shape.use_aligned_rendering || stroke.width != 1.0 || stroke.align != StrokeAlign::Center || !integer_rectangle(&shape.path, tolerance) {
|
||||
return None;
|
||||
}
|
||||
shape.path.control_bounds()
|
||||
}
|
||||
|
||||
/// At a half-pixel tie the inward row can have no source coverage near a guarded endpoint.
|
||||
/// Sample the original dashed outline on its centerline so a dash gap still stays empty.
|
||||
pub(crate) fn restore_rectangle_dash_corners((x0, y0, x1, y1): (f64, f64, f64, f64), rect: Rect, coverage: &mut [f32], stroke: &crate::raster::Rasterizer) {
|
||||
let (left, top, right, bottom) = (snap_edge(x0) as i32, snap_edge(y0) as i32, snap_edge(x1) as i32, snap_edge(y1) as i32);
|
||||
for (x, sx, dx) in [(left, x0, 1i32), (right.saturating_sub(1), x1, -1)] {
|
||||
for (y, sy, dy) in [(top, y0, 1i32), (bottom.saturating_sub(1), y1, -1)] {
|
||||
for (px, py, horizontal) in [(x, y, true), (x, y, false), (x.saturating_add(dx), y, true), (x, y.saturating_add(dy), false)] {
|
||||
if px < left || px >= right || py < top || py >= bottom || px < rect.x0 || px >= rect.x1 || py < rect.y0 || py >= rect.y1 {
|
||||
continue;
|
||||
}
|
||||
let (edge, row, side) = if horizontal { (sy, py, dy) } else { (sx, px, dx) };
|
||||
if !same(f64::from(row) + 0.5 - edge, f64::from(side)) {
|
||||
continue;
|
||||
}
|
||||
let i = (py - rect.y0) as usize * rect.width() as usize + (px - rect.x0) as usize;
|
||||
let Some(value) = coverage.get_mut(i).filter(|v| **v == 0.0) else { continue };
|
||||
let cell = Rect::new(px, py, px + 1, py + 1);
|
||||
let probe = |pixel: i32, low: f64, high: f64| (f64::from(pixel) + 0.5).max(low).min(high) - f64::from(pixel);
|
||||
let offset = if horizontal { (probe(px, x0, x1), sy - f64::from(py)) } else { (sx - f64::from(px), probe(py, y0, y1)) };
|
||||
*value = stroke.point_samples(cell, offset).first().copied().unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize the selected interior row using its actual normal-axis coverage. This keeps
|
||||
/// quantized PSD edges opaque without rounding the path used for dash lengths and phase.
|
||||
pub(crate) fn rectangle_coverage_scale((x0, y0, x1, y1): (f64, f64, f64, f64), x: i32, y: i32) -> f32 {
|
||||
let mut normal: f64 = 1.0;
|
||||
for (pixel, edge, inside_positive) in [(x, x0, true), (x, x1, false), (y, y0, true), (y, y1, false)] {
|
||||
let rounded = snap_edge(edge);
|
||||
let row = (rounded as i32).saturating_sub(i32::from(!inside_positive));
|
||||
if pixel == row {
|
||||
normal = normal.min(0.5 + (edge - rounded) * if inside_positive { 1.0 } else { -1.0 });
|
||||
}
|
||||
}
|
||||
let scale = normal.recip() as f32;
|
||||
if scale.is_finite() { scale } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Bound actual tessellated joins, including sharp interior cusps. Source control
|
||||
/// bounds alone do not contain a long miter. Use the stroker's flattening tolerance
|
||||
/// and duplicate-point policy, without modifying its path or dash calculations.
|
||||
fn join_bounds(shape: &ShapeLayer, tol: f64) -> Option<Vec<((f64, f64), f64)>> {
|
||||
let style = crate::stroke_style(shape.stroke.as_ref()?);
|
||||
if !style.miter_limit.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let flatten_tol = if tol.is_nan() { 0.1 } else { (tol * 4.0).clamp(1e-3, 0.1) };
|
||||
let lines = crate::flatten_path(&shape.path, flatten_tol);
|
||||
if lines.iter().map(|l| l.pts.len()).sum::<usize>() > 8192 {
|
||||
return None;
|
||||
}
|
||||
let mut bounds = Vec::new();
|
||||
for line in lines {
|
||||
let (points, knots) = clean_line(&line)?;
|
||||
let n = points.len();
|
||||
if n < 3 {
|
||||
bounds.extend(points.into_iter().map(|p| (p, 0.75)));
|
||||
continue;
|
||||
}
|
||||
let closed = line.closed;
|
||||
let range = if closed { 0..n } else { 1..n - 1 };
|
||||
for i in range {
|
||||
let a = *points.get((i + n - 1) % n)?;
|
||||
let b = *points.get(i)?;
|
||||
let c = *points.get((i + 1) % n)?;
|
||||
let unit = |x: f64, y: f64| {
|
||||
let length = x.hypot(y);
|
||||
(length > 0.0 && length.is_finite()).then(|| (x / length, y / length))
|
||||
};
|
||||
let u = unit(b.0 - a.0, b.1 - a.1)?;
|
||||
let v = unit(c.0 - b.0, c.1 - b.1)?;
|
||||
let cosine = ((1.0 + u.0 * v.0 + u.1 * v.1).clamp(0.0, 2.0) * 0.5).sqrt();
|
||||
let limit = if knots.get(i).copied().unwrap_or(true) { style.miter_limit.min(500.0) } else { f64::INFINITY };
|
||||
// Bevel/round joins may be smaller; this conservative envelope also
|
||||
// bounds the miter vertices of continuous curve ribbons.
|
||||
let radius = if cosine >= 1e-9 && 1.0 / cosine <= limit { (0.5 / cosine).max(0.75) } else { 0.75 };
|
||||
bounds.push((b, radius));
|
||||
}
|
||||
}
|
||||
Some(bounds)
|
||||
}
|
||||
/// Match the stroker's duplicate-point policy while retaining source-knot join flags.
|
||||
fn clean_line(line: &crate::Polyline) -> Option<CleanLine> {
|
||||
let mut points: Vec<(f64, f64)> = Vec::new();
|
||||
let mut knots = Vec::new();
|
||||
for (i, p) in line.pts.iter().enumerate() {
|
||||
if !p.0.is_finite() || !p.1.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if points.last().is_some_and(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9) {
|
||||
continue;
|
||||
}
|
||||
points.push(*p);
|
||||
knots.push(line.knot.get(i).copied().unwrap_or(true));
|
||||
}
|
||||
if line.closed && points.len() > 1 && points.first().zip(points.last()).is_some_and(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1) < 1e-9) {
|
||||
points.pop();
|
||||
knots.pop();
|
||||
}
|
||||
Some((points, knots))
|
||||
}
|
||||
|
||||
/// Snap source axis-aligned edges on a render-only path. Moving a knot's handles
|
||||
/// with its anchor preserves the adjoining curve's tangent. Diagonals and curves
|
||||
/// are not inferred from tessellated chords.
|
||||
pub(crate) fn aligned_edge_path(shape: &ShapeLayer) -> Option<Path> {
|
||||
if !shape.use_aligned_rendering || line_fill_path(shape).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut path = shape.path.clone();
|
||||
for subpath in &mut path.subpaths {
|
||||
let source = subpath.knots.clone();
|
||||
let count = source.len();
|
||||
if count < 2 {
|
||||
continue;
|
||||
}
|
||||
let mut axes = vec![(false, false); count];
|
||||
// A vertical tangent identifies a horizontal extremum, and conversely.
|
||||
// Snap its normal coordinate, moving handles with the anchor; curve
|
||||
// interiors keep area antialiasing instead of thresholding their chords.
|
||||
for (index, knot) in source.iter().enumerate() {
|
||||
let curved = knot.in_ctrl != knot.anchor || knot.out_ctrl != knot.anchor;
|
||||
axes[index] = (
|
||||
curved && same(knot.in_ctrl.x, knot.anchor.x) && same(knot.out_ctrl.x, knot.anchor.x),
|
||||
curved && same(knot.in_ctrl.y, knot.anchor.y) && same(knot.out_ctrl.y, knot.anchor.y),
|
||||
);
|
||||
}
|
||||
let segments = if subpath.closed { count } else { count - 1 };
|
||||
for index in 0..segments {
|
||||
let next = (index + 1) % count;
|
||||
let a = source[index];
|
||||
let b = source[next];
|
||||
let points = [a.anchor, a.out_ctrl, b.in_ctrl, b.anchor];
|
||||
let vertical = points.iter().all(|point| same(point.x, a.anchor.x));
|
||||
let horizontal = points.iter().all(|point| same(point.y, a.anchor.y));
|
||||
for knot in [index, next] {
|
||||
axes[knot].0 |= vertical;
|
||||
axes[knot].1 |= horizontal;
|
||||
}
|
||||
}
|
||||
for ((target, original), (vertical, horizontal)) in subpath.knots.iter_mut().zip(source).zip(axes) {
|
||||
if vertical && original.anchor.x.is_finite() {
|
||||
let snapped = snap_edge(original.anchor.x);
|
||||
let delta = snapped - original.anchor.x;
|
||||
target.anchor.x = snapped;
|
||||
target.in_ctrl.x = original.in_ctrl.x + delta;
|
||||
target.out_ctrl.x = original.out_ctrl.x + delta;
|
||||
}
|
||||
if horizontal && original.anchor.y.is_finite() {
|
||||
let snapped = snap_edge(original.anchor.y);
|
||||
let delta = snapped - original.anchor.y;
|
||||
target.anchor.y = snapped;
|
||||
target.in_ctrl.y = original.in_ctrl.y + delta;
|
||||
target.out_ctrl.y = original.out_ctrl.y + delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
(path != shape.path).then_some(path)
|
||||
}
|
||||
@@ -152,64 +152,6 @@ impl Rasterizer {
|
||||
self.inverted
|
||||
}
|
||||
|
||||
/// Translate compiled edges by a finite render-only offset without retessellating dashes.
|
||||
pub(crate) fn translated(&self, dx: f64, dy: f64) -> Self {
|
||||
let mut shifted = self.clone();
|
||||
for edge in &mut shifted.edges {
|
||||
edge.x0 += dx;
|
||||
edge.y0 += dy;
|
||||
edge.y1 += dy;
|
||||
}
|
||||
shifted.bounds = shifted.bounds.map(|(x0, y0, x1, y1)| (x0 + dx, y0 + dy, x1 + dx, y1 + dy));
|
||||
shifted
|
||||
}
|
||||
|
||||
/// Sample the compiled outline without integrating pixel area. Used only on isolated
|
||||
/// aligned butt-dash runs, where a subpixel dash may still contain a pixel center.
|
||||
pub(crate) fn point_samples(&self, rect: Rect, offset: (f64, f64)) -> Vec<f32> {
|
||||
let mut out = vec![0.0; rect.width() as usize * rect.height() as usize];
|
||||
let mut active = Vec::new();
|
||||
let mut crossings = Vec::new();
|
||||
let mut wind = vec![0i32; self.comps.len()];
|
||||
let mut next = 0;
|
||||
for (row, y) in (rect.y0..rect.y1).enumerate() {
|
||||
let y = f64::from(y) + offset.1;
|
||||
active.retain(|&i: &usize| self.edges.get(i).is_some_and(|e| e.y1 > y));
|
||||
while let Some(e) = self.edges.get(next).filter(|e| e.y0 <= y) {
|
||||
if e.y1 > y {
|
||||
active.push(next);
|
||||
}
|
||||
next += 1;
|
||||
}
|
||||
crossings.clear();
|
||||
for &i in &active {
|
||||
if let Some(e) = self.edges.get(i) {
|
||||
crossings.push((e.x_at(y), e.comp, e.dir));
|
||||
}
|
||||
}
|
||||
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
wind.fill(0);
|
||||
let mut union_count = 0;
|
||||
let mut crossing = 0;
|
||||
for (column, x) in (rect.x0..rect.x1).enumerate() {
|
||||
let x = f64::from(x) + offset.0;
|
||||
while let Some(&(_, comp, dir)) = crossings.get(crossing).filter(|e| e.0 <= x) {
|
||||
if let Some(w) = wind.get_mut(comp as usize) {
|
||||
let was = self.comp_inside(comp as usize, *w);
|
||||
*w = w.saturating_add(dir);
|
||||
let now = self.comp_inside(comp as usize, *w);
|
||||
union_count += i32::from(now) - i32::from(was);
|
||||
}
|
||||
crossing += 1;
|
||||
}
|
||||
if let Some(value) = out.get_mut(row * rect.width() as usize + column) {
|
||||
*value = f32::from(self.inside(&wind, union_count));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the combined shape is inside given per-component winding numbers.
|
||||
#[inline]
|
||||
fn inside(&self, wind: &[i32], union_count: i32) -> bool {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,5 @@
|
||||
# Control protocol
|
||||
|
||||
`ui.set {useAlignedRendering: true}` changes the Align Edges tool preference for
|
||||
subsequent shape creation. `ui.inspect.toolOptions.useAlignedRendering` reports
|
||||
that preference, not the selected shape's setting. Shape-tool options display the
|
||||
selected shape's value. The Pen displays the target layer's value when appending
|
||||
to it, the captured value during a valid draft, or the tool preference for New Layer.
|
||||
Use
|
||||
`shape.edit {layer: id, useAlignedRendering: true}` to change an existing layer and
|
||||
`shape.info {layer: id}` to read its `useAlignedRendering` value (engine commands
|
||||
are invoked through `engine.execute` on this control channel).
|
||||
|
||||
Shape stroke defaults are drivable with `ui.set {shapeStroke: {width, align, cap, join,
|
||||
miterLimit, dashes, dashOffset, opacity}}`; partial fields merge, null disables the stroke.
|
||||
Values use the existing `shape.edit` names and units. Colour uses `tools.setColors`.
|
||||
@@ -111,6 +101,7 @@ The transport is the framework's control server (`craft::automation::server` in
|
||||
- `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state.
|
||||
- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once. Window ends with the open documents as `window.document.<index>` (tab order, the active one checked, #2991); invoking one brings that document to the front and replies `{document: index}`. Camera Raw and the full-window workspaces (Liquify, Content-Aware Fill, Filter Gallery, Adaptive Wide Angle) are modal: while one is open, `ui.menu.invoke` refuses every other menu item ("menu command is unavailable while a modal dialog is open") and accepts only that workspace's own `{"ui": {...}}` requests (`filter.liquify`, `edit.contentAwareFill`, `filter.filterGallery`, `filter.adaptiveWideAngle`, `filter.cameraRaw`; `params` must hold only the `ui` object), so finish it with `{"ui":{"commit":true}}` or `{"ui":{"cancel":true}}` first. Those requests are refused too while a dialog, an unsaved-changes prompt or a crop that blocks the command is open: resolve that first, then commit or cancel the workspace. `ui.menu.list` reports the same gate: an item the modal state refuses is listed with `enabled: false`. `engine.execute` is not a menu click and is not gated
|
||||
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.
|
||||
- `ui.set {useAlignedRendering: bool}` sets the shape tools' and the Pen's one Align Edges checkbox (on by default and after Reset Tool): a drag lands on whole pixels and the next shape layer gets Align Edges. `ui.inspect` reports it as `toolOptions.useAlignedRendering`; that is the tool option, not the selected layer's flag, which the options bar shows and edits while a shape layer is selected. A layer's own flag is read with `shape.info` and changed with `shape.edit {layer, useAlignedRendering}` (through `engine.execute`); see [Align Edges](pixel-aligned-strokes.md).
|
||||
- `ui.set` also accepts `statusInfo` (the status bar item next to the zoom field), `marqueeStyle` (`normal`, `fixedRatio`, `fixedSize`; the size stays as the options bar's Style dropdown leaves it) and `marqueeSize` (`[width, height]` within the style's range), `actionsPanel` (an object patching `buttonMode` and `collapsed`), `presetBrowsers` (`{<panel>: {view, zoom}}`, each patching that preset panel's browser), `toolbarColumns` (1 up to the number of toolbar cells: the toolbar column's width in tool columns) and `recentView` (`grid` or `list`, the Home screen's recent files). `ui.inspect` reports `statusInfo`.
|
||||
- `ui.set` also accepts `moveShowTransform` (boolean), the Move tool's Show Transform Controls checkbox (`ui.inspect` › `toolOptions.move_show_transform`). With Move active and the controls visible, a primary `ui.pointer` down on a handle or in the rotation zone starts the same Free Transform session as the canvas, framing all selected non-Background layers. `move` and `up` drive the existing preview; `ui.key {"key":"Enter"}` commits one "Free Transform" history step. A press inside the box keeps the ordinary Move behavior. Hidden or disabled controls do not start a transform. An invalid value rejects the whole `ui.set` request before any fields change.
|
||||
- `ui.set` also accepts `camTransformOnDrop` (boolean), the Content-Aware Move tool's Transform On Drop checkbox: a drop then puts a scale/rotate box on the patch (`ui.inspect` › `camTransform`: its document/revision, drag `offset` and `frame`), driven with `ui.pointer` (handles as Free Transform's; outside the box rotates), committed with `ui.key Enter` (one `paint.contentAwareMove` with `scaleX`, `scaleY`, `rotate`) or dropped with `Escape`.
|
||||
|
||||
@@ -1,43 +1,59 @@
|
||||
# Align Edges
|
||||
|
||||
Shape tools expose **Align Edges** in the options bar. The corresponding scripted
|
||||
setting is `useAlignedRendering` on `shape.create`, `shape.edit`, `shape.info`,
|
||||
`path.toShape` and `shape.presets.place`. It defaults to false for new shapes;
|
||||
appending with `addTo` preserves the target setting when omitted. Tool presets
|
||||
retain the preference; Reset Tool restores false.
|
||||
A shape layer's **Align Edges** (`ShapeLayer::use_aligned_rendering`, PSD block `sn2P`, scripting
|
||||
key `useAlignedRendering`) fits the whole shape to whole document pixels when it is rendered, as the
|
||||
reference application does. The stored path is never changed: an anchor at 10.5 stays at 10.5, and
|
||||
turning the flag off renders the original soft edges again.
|
||||
|
||||
The Triangle and Rectangle tools also expose **Snap Bounding Box**, enabled by default. That
|
||||
separate tool preference (`align_edges`) rounds the drag box before creating the
|
||||
path; it does not toggle render-time Align Edges or edit an existing layer.
|
||||
## The rule
|
||||
|
||||
Alignment affects both fill and stroke. Straight horizontal and vertical source
|
||||
edges at fractional coordinates snap to document pixel boundaries on a render-only
|
||||
copy. Curve extrema at anchors with axis-aligned handles snap too, including
|
||||
ellipse boundaries; extrema inside a Bézier segment are not detected. Handles
|
||||
move with their anchors, preserving adjoining curve tangents.
|
||||
Curves and diagonals retain antialiasing; flattened curve chords are never snapped.
|
||||
Stored paths, live parameters, stroke widths and dash settings are unchanged.
|
||||
Turning the option off restores the original coverage. Existing one-pixel stroke
|
||||
and dash-cap coverage rules remain in use after edge alignment. Straight outline
|
||||
edges of wider integer-width strokes also snap when every source knot has
|
||||
coincident handles. Paths with curved segments, including rounded rectangles,
|
||||
retain outline antialiasing on their straight sides too. Centered fractional-width strokes
|
||||
keep their area coverage so a subpixel outline cannot collapse to zero width.
|
||||
Inside/outside strokes use a doubled outline before clipping to the fill; some
|
||||
fractional requested widths therefore produce a snapped integral-width outline
|
||||
(for example, 1.5 px becomes a 3 px outline before clipping). Curved source
|
||||
outlines retain antialiasing.
|
||||
Measured in the reference application (a black shape on white):
|
||||
|
||||
Native projects retain the setting. PSD `strokeStyleStrokeAdjust` is an independent
|
||||
stroke-style property: it neither enables Align Edges on import nor changes when
|
||||
Align Edges is toggled. Existing values survive stroke appearance edits. PSD/PSB
|
||||
stores Align Edges in the layer's `sn2P` (Using Aligned Rendering) block: four
|
||||
big-endian bytes, nonzero for enabled, as specified by
|
||||
[Adobe's PSD format documentation](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/).
|
||||
An absent block defaults to false. Unchanged valid blocks stay byte-identical.
|
||||
Fill/stroke splitting retains the layer setting for ordinary fills as well as
|
||||
live lines, so layer effects and clipped content use the same aligned coverage.
|
||||
1. Take the bounds of what the shape paints: the fill area, or the stroke's outer edge when it has
|
||||
a visible stroke (a centred stroke reaches half its width beyond the path, an outside stroke its
|
||||
whole width, an inside stroke nothing).
|
||||
2. Round the left and top edge to the nearest whole pixel (a half rounds up: 10.5 becomes 11) and
|
||||
the width and height to whole pixels (20.5 becomes 21).
|
||||
3. Translate and scale the whole path so its painted bounds fill that box. The fill and the stroke
|
||||
take this one transform; the stroke keeps its width.
|
||||
|
||||
Aligned previews rasterize in document pixels before the view transform. Large
|
||||
previews use bounded work per frame and a temporary coarse fallback until native
|
||||
coverage is ready. Cache identities include the setting and geometry provenance.
|
||||
So curves stay antialiased (an ellipse moves, it is not bent), diagonals just move with the shape,
|
||||
and the inner edges of a shape with several subpaths are not snapped one by one. A few results:
|
||||
|
||||
| Shape | Reference application, Align Edges on |
|
||||
|---|---|
|
||||
| Rectangle 10.5..30.5, fill | covers columns 11..30 (off: columns 10 and 30 half covered) |
|
||||
| Rectangle 10.25..30.75 / 10.4..30.6 / 10.75..30.25 | covers 10..30 / 10..29 / 11..30 |
|
||||
| 1 px centred stroke on rectangle 10..30 | the stroke paints columns 10 and 30 |
|
||||
| 2 px stroke on rectangle 10.25..30.25 | columns 9-10 and 29-30 |
|
||||
| Fill + 1 px stroke at 10.5 | unchanged: its outer edge 10..31 is already whole |
|
||||
| Pen triangle (10.5,10.5) (30.5,10.5) (10.5,30.5) | moves by half a pixel on both axes |
|
||||
|
||||
Not measured, and chosen here: a shape thinner than half a pixel keeps its size (rounding would
|
||||
make it vanish); an inverted path (it paints everywhere) is not moved; a 1 px Line paints its band
|
||||
19.5..20.5 on row 20 (the reference's Line tool could not be driven by script).
|
||||
|
||||
The rule lives in `photocraft_vector::align_edges` and is applied in `CompiledShape`, which every
|
||||
renderer uses: layer caches, the compositor (also its fill/stroke split under layer effects, which
|
||||
starts from `align_edges::aligned_shape` so both parts move together), previews and extents.
|
||||
|
||||
## The checkbox
|
||||
|
||||
The shape tools and the Pen (in Shape mode) have one **Align Edges** checkbox at the options bar's
|
||||
right end, on by default and after Reset Tool, greyed in Path mode. It does both: the drag lands on
|
||||
whole pixels (with it off, the Rectangle's and Triangle's drags keep their fractions; the other
|
||||
tools' drags always land on whole pixels), and the new shape layer gets Align Edges. With a shape layer selected the checkbox
|
||||
shows and edits that layer's flag, as Fill and Stroke do; the Properties panel has it too. Tool
|
||||
presets store it as `useAlignedRendering` (older settings and presets as `align_edges`).
|
||||
|
||||
## Files
|
||||
|
||||
- PSD: `sn2P` is a four-byte value, nonzero for on. It is separate from the stroke's Stroke Adjust.
|
||||
The reference application writes it as 1 when on and leaves it out when off (checked by saving
|
||||
both), so a PSD shape layer without it renders without Align Edges.
|
||||
- `.pcraft`: `use_aligned_rendering`, written only when on. Files from before it existed have no
|
||||
such field and keep rendering as they did (off).
|
||||
- Scripting: `shape.create`, `shape.edit`, `path.toShape` and `shape.presets.place` take
|
||||
`useAlignedRendering`; `shape.info` reports it. Without the param a new layer is off (scripts
|
||||
keep their old results); `addTo` keeps the target layer's value. The UI always passes the
|
||||
checkbox's value.
|
||||
|
||||
Reference in New Issue
Block a user