Merge storytold main into engine-split-step7

This commit is contained in:
aiongg committed 2026-11-23 20:51:19 +00:00
commit ff2588c2ca
29 files changed
+1629 -40

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
nightly: ${{ github.event_name == 'schedule' }}
dry-run: ${{ github.event_name == 'schedule' }}
app-name: photocraft
app-title: PhotoCraft
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
@@ -126,7 +126,7 @@ pub(super) const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "re
pub(super) const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")];
pub(super) const EXTENSION: &[(&str, &str)] =
&[("Bckg", "background"), ("FrgC", "foreground"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")];
&[("Bckg", "background"), ("FrgC", "foreground"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Gry ", "gray"), ("Trns", "transparent")];
pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[
("FrgC", "foreground"),
+5 -1
View File
@@ -343,7 +343,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Embedded…",
&["File"],
None,
r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##,
r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"centerOnSelection":bool=false (as File > Place Embedded: centre on a hard-edged rectangular selection, over center, and remove the selection in the same step),"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##,
native_doc,
|s, p| place(s, p, false)
),
@@ -456,6 +456,10 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
#[path = "file_cmds/place_selection_centre_tests.rs"]
mod place_selection_centre_tests;
#[cfg(test)]
#[path = "file_cmds/tests.rs"]
mod tests;
+28 -1
View File
@@ -364,6 +364,9 @@ pub(crate) struct PlaceInput {
pub(super) linked: Option<String>,
pub(super) params: Value,
pub(super) canvas: (f64, f64),
/// File › Place Embedded's centre on the selection (`"centerOnSelection"`, #14102): the
/// placed image is centred there and the selection removed in the place's own step.
pub(super) on_selection: Option<(f64, f64)>,
/// The document's resolution (ppi): a placed file keeps its physical size in it.
pub(super) ppi: f64,
pub(super) fmt: PixelFormat,
@@ -410,6 +413,8 @@ impl PlaceInput {
let [a, b, c, d, _, _] = f.transform.m;
(a.hypot(b), c.hypot(d))
});
// Not into a frame, whose image fills the frame.
let on_selection = if frame.is_none() && p.get("centerOnSelection").and_then(Value::as_bool) == Some(true) { selection_centre(&d.doc) } else { None };
let approve = match p.get("approveHighMemory") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
@@ -423,6 +428,7 @@ impl PlaceInput {
Ok(Self {
name: name.to_string(),
canvas,
on_selection,
ppi: f64::from(d.doc.resolution_dpi),
fmt: d.doc.pixel_format(),
opts,
@@ -453,6 +459,22 @@ impl PlaceInput {
}
}
/// The centre of the selection a File › Place Embedded centres the placed image on (#14102):
/// the bounds of a hard-edged rectangle on the canvas, the selection measured. Any other
/// selection (feathered, not rectangular, or reaching past the canvas) leaves the place centred
/// as before, and kept.
fn selection_centre(doc: &Document) -> Option<(f64, f64)> {
let sel = doc.selection.as_ref()?;
let b = sel.content_bounds();
if b.is_empty() || b.intersect(&doc.bounds()) != b || sel.default_pixel().first().is_some_and(|v| *v > 0.0) {
return None;
}
// Row by row, so a large selection is never read at once.
let n = sel.channels().max(1);
let hard = (b.y0..b.y1).all(|y| sel.read_region(photocraft_geom::Rect::new(b.x0, y, b.x1, y + 1)).chunks_exact(n).all(|px| px[0] >= 1.0));
hard.then(|| (f64::from(b.x0 + b.x1) / 2.0, f64::from(b.y0 + b.y1) / 2.0))
}
/// A place decoded, flattened and fitted, ready to be inserted by [`apply_place`].
pub(crate) struct Prepared {
pub(super) warnings: Vec<String>,
@@ -465,11 +487,13 @@ pub(crate) struct Prepared {
pub(super) smart: bool,
/// The frame the layer fills, if any (it becomes the frame's content instead of a new layer).
pub(super) frame: Option<LayerId>,
/// The place was centred on the selection, which it removes in the same step.
pub(super) deselect: bool,
}
/// Insert the prepared layer as one undo step and report the place. Runs on the session's thread.
pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result<Value> {
let Prepared { warnings, content, layer_name, label, scale, bounds, smart, frame } = p;
let Prepared { warnings, content, layer_name, label, scale, bounds, smart, frame, deselect } = p;
let layer = Layer::new(layer_name, content);
let id = layer.id;
s.edit(label, move |doc, active| {
@@ -480,6 +504,9 @@ pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result<Value> {
crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
*active = Some(id);
}
if deselect {
doc.selection = None;
}
Ok(())
})?;
Ok(json!({"layer": id.0, "frame": frame.map(|f| f.0), "scale": scale * 100.0, "bounds": bounds, "smartObject": smart, "warnings": warnings}))
@@ -0,0 +1,128 @@
//! File › Place Embedded with a selection (#14102): the placed image is centred on the
//! selection's bounds and the selection removed, in the place's one history step, as measured in
//! the reference application (400 × 300 document, selection 300,200 to 380,280).
use super::*;
/// A 400 × 300 document with the selection 300,200 to 380,280 (`extra` adds to `select.rect`'s
/// params: an ellipse, a feather), or none.
fn session(selection: Option<Value>) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "depth": 8})).unwrap();
if let Some(extra) = selection {
let mut p = json!({"x": 300, "y": 200, "width": 80, "height": 80});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
s.execute("select.rect", p).unwrap();
}
s
}
/// A gray `w` × `h` PNG.
fn png(w: u32, h: u32) -> Vec<u8> {
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![128; (w * h * 3) as usize]).unwrap();
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()
}
/// Places a `w` × `h` file with `params`; its box.
fn place(s: &mut Session, w: u32, h: u32, params: Value) -> [f64; 4] {
let r = place_bytes(s, "src.png", png(w, h), None, &params).unwrap();
let b: Vec<f64> = r["bounds"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
[b[0], b[1], b[2], b[3]]
}
/// File › Place Embedded's params: centre on the selection.
fn menu() -> Value {
json!({"centerOnSelection": true})
}
fn selection_bounds(s: &Session) -> Option<photocraft_geom::Rect> {
s.active().unwrap().doc.selection.as_ref().map(photocraft_raster::Surface::content_bounds)
}
/// The measured case: a 120 × 90 file lands at 280,195 to 400,285 (centre 340,240) and a 100 × 60
/// one at 290,210 to 390,270; the selection is gone.
#[test]
fn a_place_centres_on_the_selection_and_removes_it() {
for (w, h, want) in [(120, 90, [280.0, 195.0, 400.0, 285.0]), (100, 60, [290.0, 210.0, 390.0, 270.0])] {
let mut s = session(Some(json!({})));
assert_eq!(place(&mut s, w, h, menu()), want, "{w}×{h}");
assert_eq!(selection_bounds(&s), None, "{w}×{h}: the selection is removed");
}
}
/// One history step: Undo takes the layer away and brings the selection back; Redo places it
/// again without the selection.
#[test]
fn the_place_and_the_deselect_are_one_step() {
let mut s = session(Some(json!({})));
let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len());
place(&mut s, 100, 60, menu());
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
assert!(s.undo());
assert_eq!(s.active().unwrap().doc.layer_count(), layers);
assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280)), "Undo brings the selection back");
assert!(s.redo());
assert_eq!(s.active().unwrap().doc.layer_count(), layers + 1);
assert_eq!(selection_bounds(&s), None);
}
/// The same place as a background job lands in the same place and removes the selection too.
#[test]
fn a_place_job_centres_on_the_selection_too() {
let mut s = session(Some(json!({})));
let started = s.start_place_bytes("src.png", png(100, 60), None, menu()).unwrap();
let r = match started {
crate::jobs::Started::Done(v) => v,
crate::jobs::Started::Job(id) => {
let t = std::time::Instant::now();
loop {
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
match e.outcome {
crate::jobs::JobOutcome::Done(v) => break v,
other => panic!("the place failed: {other:?}"),
}
}
assert!(t.elapsed() < std::time::Duration::from_secs(60), "the place did not finish");
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
};
assert_eq!(r["bounds"], json!([290.0, 210.0, 390.0, 270.0]));
assert_eq!(selection_bounds(&s), None);
}
/// Without a selection the place centres on the canvas, as before: 100 × 60 at 150,120.
#[test]
fn without_a_selection_the_place_centres_on_the_canvas() {
let mut s = session(None);
assert_eq!(place(&mut s, 100, 60, menu()), [150.0, 120.0, 250.0, 180.0]);
}
/// The selection wins over an explicit `center` when asked to centre on it; without
/// `centerOnSelection` (a drop on the canvas, a script) `center` and the canvas centre are used as
/// before and the selection stays.
#[test]
fn an_explicit_center_or_no_request_keeps_the_selection() {
let mut s = session(Some(json!({})));
assert_eq!(place(&mut s, 100, 60, json!({"centerOnSelection": true, "center": [100, 100]})), [290.0, 210.0, 390.0, 270.0]);
let mut s = session(Some(json!({})));
assert_eq!(place(&mut s, 100, 60, json!({"center": [100, 100]})), [50.0, 70.0, 150.0, 130.0]);
assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280)));
let mut s = session(Some(json!({})));
assert_eq!(place(&mut s, 100, 60, json!({})), [150.0, 120.0, 250.0, 180.0]);
assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280)));
}
/// A selection that isn't a hard-edged rectangle (not measured) leaves the place as it was:
/// centred on the canvas, the selection kept.
#[test]
fn an_elliptical_or_feathered_selection_keeps_todays_place() {
for extra in [json!({"ellipse": true}), json!({"feather": 4})] {
let mut s = session(Some(extra.clone()));
let before = selection_bounds(&s);
assert_eq!(place(&mut s, 100, 60, menu()), [150.0, 120.0, 250.0, 180.0], "{extra}");
assert_eq!(selection_bounds(&s), before, "{extra}: the selection stays");
}
}
@@ -173,8 +173,9 @@ impl PlaceSteps {
None if self.input.fit && (w * base > cw || h * base > ch) => (cw / w).min(ch / h),
None => base,
};
let center = match p.get("center").and_then(Value::as_array) {
Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
let center = match (self.input.on_selection, p.get("center").and_then(Value::as_array)) {
(Some(c), _) => c,
(None, Some(c)) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
_ => (cw / 2.0, ch / 2.0),
};
// `scale` is the caller's: bound the resampled size before allocating it (a frame's image
@@ -285,6 +286,7 @@ impl PlaceSteps {
bounds,
smart,
frame: input.frame.as_ref().map(|(id, _)| *id),
deselect: input.on_selection.is_some(),
})
}
}
+20 -1
View File
@@ -684,6 +684,22 @@ fn extension_color(s: &Session, p: &Value) -> [f32; 4] {
"foreground" => s.tools.foreground,
"white" => [1.0; 4],
"black" => [0.0, 0.0, 0.0, 1.0],
// The reference application's Gray: 128,128,128 (#14543). A 32-bit document holds linear
// light, so there it is grey 128 decoded as `change_depth` decodes it (0.2159).
"gray" => {
// An Indexed document was not measured (#14543) and keeps today's background colour.
if s.active().is_some_and(|d| d.doc.mode == ColorMode::Indexed) {
return s.tools.background;
}
let v = 128.0 / 255.0;
let v = match s.active().map(|d| (d.doc.mode, d.doc.depth)) {
Some((mode @ (ColorMode::Rgb | ColorMode::Grayscale), SampleType::F32)) => {
photocraft_compose::adjust::Transfer::for_document(mode, SampleType::U8).decode(v)
}
_ => v,
};
[v, v, v, 1.0]
}
"transparent" => [0.0; 4],
hex if hex.starts_with('#') => {
let h = hex.trim_start_matches('#');
@@ -1252,7 +1268,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.canvasSize",
"Canvas Size…",
["Image"],
r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; absolute sizes only),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|transparent|#rrggbb"="background"}"##,
r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; absolute sizes only),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|gray|transparent|#rrggbb"="background"}"##,
has_doc,
canvas_size
),
@@ -1327,3 +1343,6 @@ mod image_size_drops_selection_tests;
#[cfg(test)]
mod canvas_size_noop_history_tests;
#[cfg(test)]
mod canvas_size_gray_tests;
@@ -0,0 +1,153 @@
//! #14543: Canvas Size takes Gray as its extension colour, the reference application's 128,128,128,
//! from the command and from recorded `.atn` steps (`canvasExtensionColorType` `Gry `), and a
//! `gray` step is written back as Gray.
use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem};
use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D};
use serde_json::{Value, json};
use crate::Session;
use crate::actions_cmds::{Action, ActionStep};
/// A 400 x 300 document at `depth` with a white Background and an empty layer "Top" above it.
fn doc(depth: u32) -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s
}
/// The 8-bit RGB the document shows at pixel (x, y), as the Eyedropper reads it.
fn read(s: &mut Session, x: i32, y: i32) -> [i64; 3] {
let v = s.execute("document.sampleColor", json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5})).unwrap();
let c = |i: usize| (v[i].as_f64().unwrap() * 255.0).round() as i64;
[c(0), c(1), c(2)]
}
/// The alpha of the layer "Top" at pixel (x, y).
fn top_alpha(s: &Session, x: i32, y: i32) -> f32 {
let doc = &s.active().unwrap().doc;
let top = doc.layers.iter().find(|l| l.name == "Top").unwrap();
top.surface().unwrap().rgba(x, y)[3]
}
const GROW: fn(&str) -> Value = |color| json!({"width": 500, "height": 400, "anchor": "topLeft", "extensionColor": color});
#[test]
fn gray_extends_the_background_with_128_gray_at_8_and_16_bits() {
for depth in [8, 16] {
let mut s = doc(depth);
s.execute("image.canvasSize", GROW("gray")).unwrap();
assert_eq!(read(&mut s, 450, 350), [128, 128, 128], "depth {depth}: the new area");
assert_eq!(read(&mut s, 10, 10), [255, 255, 255], "depth {depth}: the old Background keeps its pixels");
assert_eq!(top_alpha(&s, 450, 350), 0.0, "depth {depth}: only the Background is filled");
}
}
/// The Background's stored colour at pixel (x, y).
fn background_value(s: &Session, x: i32, y: i32) -> [f32; 4] {
s.active().unwrap().doc.background().unwrap().surface().unwrap().rgba(x, y)
}
/// A 32-bit document holds linear light: its Gray is the value an 8-bit grey 128 becomes when the
/// document is converted to 32 bits (0.2159), not 128/255.
#[test]
fn gray_in_a_32_bit_document_is_linear_grey_128() {
let mut converted = crate::session();
converted.execute("file.new", json!({"width": 4, "height": 4, "depth": 8, "background": "white"})).unwrap();
converted.execute("edit.fill", json!({"color": "#808080"})).unwrap();
converted.execute("image.mode.bits32", json!({})).unwrap();
let want = background_value(&converted, 1, 1);
assert!((want[0] - 0.2159).abs() < 0.002, "converted grey 128: {want:?}");
let mut s = doc(32);
s.execute("image.canvasSize", GROW("gray")).unwrap();
let got = background_value(&s, 450, 350);
for i in 0..3 {
assert!((got[i] - want[i]).abs() < 1e-4, "channel {i}: {got:?} vs {want:?}");
}
assert_eq!(got[3], 1.0);
assert_eq!(background_value(&s, 10, 10)[..3], [1.0, 1.0, 1.0], "the old Background keeps its pixels");
}
/// An Indexed Color document was not measured and keeps today's behaviour: Gray takes the
/// background colour there, as an unknown value does.
#[test]
fn gray_in_an_indexed_document_keeps_the_background_colour() {
let grown = |color: &str| {
let mut s = crate::session();
s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();
s.execute("image.mode.indexedColor", json!({})).unwrap();
s.tools.background = [0.0, 0.0, 1.0, 1.0];
s.execute("image.canvasSize", GROW(color)).unwrap();
background_value(&s, 450, 350)
};
assert_eq!(grown("gray"), grown("background"), "Gray fills with the background colour");
assert_ne!(grown("gray"), grown("white"), "the test tells the two apart");
}
#[test]
fn an_unknown_extension_colour_still_takes_the_background_colour() {
let mut s = doc(8);
s.execute("image.canvasSize", GROW("grey-ish")).unwrap();
assert_eq!(read(&mut s, 450, 350), [255, 255, 255]);
}
#[test]
fn the_params_doc_lists_gray() {
// The registry lists the commands once a session has installed them.
let _ = crate::session();
let spec = crate::registry::find("image.canvasSize").unwrap();
assert!(spec.params.contains("|gray|"), "{}", spec.params);
}
/// A recorded Canvas Size step: +100 / +100 px, relative, from the top left, extension colour type `ty`.
fn recorded_step(ty: &str) -> Vec<u8> {
let px = |v: f64| D::UnitFloat { unit: *b"#Pxl", value: v };
let enm = |t: &str, v: &str| D::Enumerated { type_id: Id::new(t), value: Id::new(v) };
let descriptor = Descriptor::new("null")
.with("Wdth", px(100.0))
.with("Hght", px(100.0))
.with("Rltv", D::Boolean(true))
.with("Hrzn", enm("HrzL", "Left"))
.with("Vrtc", enm("VrtL", "Top "))
.with("canvasExtensionColorType", enm("canvasExtensionColorType", ty));
atn::write(&AtnFile {
name: UnicodeString::new_nul("Canvas"),
actions: vec![AtnAction {
name: UnicodeString::new_nul("Step"),
items: vec![AtnItem { event: AtnEvent::Code(*b"CnvS"), dictionary: b"CnvS".to_vec(), descriptor: Some(descriptor), ..Default::default() }],
..Default::default()
}],
..Default::default()
})
.unwrap()
}
#[test]
fn a_recorded_gray_step_imports_as_gray_and_plays_back_128_gray() {
let bytes = recorded_step("Gry ");
let imported = crate::atn_cmds::import(&bytes).unwrap();
assert!(imported.unsupported.is_empty(), "the Gray step is supported: {:?}", imported.unsupported);
assert_eq!(imported.actions[0].steps[0].params["extensionColor"], json!("gray"));
let mut s = doc(8);
let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap();
assert_eq!(loaded["unsupported"], json!([]));
let played = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(read(&mut s, 450, 350), [128, 128, 128]);
}
#[test]
fn a_gray_step_is_written_back_as_gray() {
let action = Action::new("Step", vec![ActionStep::new("image.canvasSize", GROW("gray"))]);
let (bytes, skipped) = crate::atn_cmds::export("Canvas", &[&action], &[], false).unwrap();
assert!(skipped.is_empty(), "{} skipped", skipped.len());
let file = atn::parse(&bytes).unwrap();
let d = file.actions[0].items[0].descriptor.as_ref().unwrap();
assert!(
matches!(d.get("canvasExtensionColorType"), Some(D::Enumerated { value, .. }) if *value == Id::new("Gry ")),
"{:?}",
d.get("canvasExtensionColorType")
);
assert!(d.get("canvasExtensionColor").is_none(), "not a custom colour");
}
+5
View File
@@ -103,6 +103,11 @@ pub(crate) mod params {
cancel: Some(filter_dialog::cancel),
..ParamFamily::new(|key| key == image_processor_ui::COMMAND, filter_dialog::run)
},
ParamFamily {
check: Some(crate::view_cmds::dialogs::batch_check),
cancel: Some(filter_dialog::cancel),
..ParamFamily::new(|key| key == "file.automate.batch", filter_dialog::run)
},
ParamFamily { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(crate::view_cmds::dialogs::is_form, filter_dialog::run) },
crate::prefs_ui::PRESETS_FAMILY,
ParamFamily { check: Some(crate::crop_presets::check), ..ParamFamily::new(crate::crop_presets::owns, crate::crop_presets::run) },
+4 -3
View File
@@ -157,8 +157,7 @@ pub(crate) fn open_with(app: &mut PhotocraftApp, command: &str, params: &Value)
let d = &app.session.active()?.doc;
let size = PixelSize::new(d.size.width, d.size.height);
let dpi = f64::from(d.resolution_dpi);
let bytes_per_pixel = d.layers.first().and_then(|l| l.surface()).map_or(4, |s| s.format().bytes_per_pixel()) as f64;
let image_bytes_per_pixel = flat_bytes_per_pixel(d);
let bytes_per_pixel = flat_bytes_per_pixel(d);
let id = if command == IMAGE_COMMAND {
// Indexed Color resamples with Nearest Neighbor only, as the command does (#6019).
let indexed = d.mode == photocraft_color::ColorMode::Indexed;
@@ -169,7 +168,7 @@ pub(crate) fn open_with(app: &mut PhotocraftApp, command: &str, params: &Value)
let methods = if indexed { vec![Resample::Automatic, Resample::NearestNeighbor] } else { Vec::new() };
let values = ImageSizeValues::new(size).pixels_per_inch(dpi).points_per_inch(points).unit(unit).method(method).column_size(columns);
app.framework.dialogs.open(HostedImageSize::new(values, move |values: Bind<'_, ImageSizeValues>| {
ImageSize::new(values).methods(methods.clone()).bytes_per_pixel(image_bytes_per_pixel)
ImageSize::new(values).methods(methods.clone()).bytes_per_pixel(bytes_per_pixel)
}))
} else {
let values =
@@ -304,5 +303,7 @@ fn finish(app: &mut PhotocraftApp, id: DialogId, command: &str, params: Option<V
}
}
#[cfg(test)]
mod canvas_size_readout_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,37 @@
//! #14582: Canvas Size uses flat image bytes, not the first layer's storage with alpha.
use egui_kittest::{Harness, kittest::Queryable};
use serde_json::json;
use super::*;
#[test]
fn canvas_size_readouts_count_flat_image_bytes_and_update_with_new_dimensions() {
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_max_steps(8).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default());
app.run("prefs.set", json!({"path": "interface.language", "value": "en"})).unwrap();
app.session.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72})).unwrap();
app
});
h.run_steps(4);
let id = open(h.state_mut(), CANVAS_COMMAND).expect("a document is open");
h.run_steps(6);
// The fixture pins English unit words. The host still uses the regional number format,
// so render the independently measured quantities with that format before querying the UI.
let format = crate::i18n::framework_i18n().format();
let initial = format.number_ungrouped(351.6, 1);
assert_eq!(h.query_all_by_label_contains(&initial).count(), 2, "Current and New Size both count three RGB channels");
for (width, height, value, decimals) in [(1, 300, 900.0, 0), (133, 300, 116.9, 1), (500, 400, 585.9, 1), (567, 300, 498.3, 1)] {
let app = h.state_mut();
let ctx = app.ctx().clone();
app.framework.dialogs.set_json_field(&ctx, id, "width", json!(width)).unwrap();
app.framework.dialogs.set_json_field(&ctx, id, "height", json!(height)).unwrap();
h.run_steps(4);
let number = format.number_ungrouped(value, decimals);
let want = if decimals == 0 { format!("{number} bytes") } else { number };
assert_eq!(h.query_all_by_label_contains(&initial).count(), 1, "the original size is unchanged");
assert_eq!(h.query_all_by_label_contains(&want).count(), 1, "{width}×{height} shows the new flat size");
}
}
+55 -5
View File
@@ -300,6 +300,21 @@ impl PhotocraftApp {
})
}
/// [`Self::pick_file_bytes`] letting the user choose several files (File › Place Embedded):
/// `then` gets every chosen file, in the order the dialog returns them. A desktop file is
/// handed over by path and read only when [`PickedFile::read`] is called, so files waiting
/// their turn hold no contents; the web hands over each file's contents.
pub(crate) fn pick_files_bytes(&mut self, then: impl FnOnce(&mut Self, Vec<PickedFile>) -> Result<Value, String> + 'static) -> Result<Value, String> {
let mut request = open_filters(PickRequest::open_many("file"), &[]);
if let Some(dir) = last_used_dir(&self.ui.recent_files) {
request = request.directory(dir);
}
self.ask_file(request, move |app, picked| {
let files = picked_files(picked)?;
then(app, files)
})
}
/// File › Open: opens every chosen file in the order the dialog returns them, reporting each
/// failure (see [`Self::open_paths_in_order`]).
pub fn open_dialog_file(&mut self) -> Result<Value, String> {
@@ -495,15 +510,50 @@ pub(crate) fn last_used_dir(recent: &[String]) -> Option<String> {
fn read_picked(picked: Picked) -> Result<(String, Vec<u8>), String> {
match picked {
Picked::Contents(files) => files.into_iter().next().ok_or_else(|| CANCELLED.into()),
Picked::Paths(paths) => {
let path = path_string(paths.first().ok_or(CANCELLED)?);
let bytes = photocraft_format::read_file(Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?;
Ok((path, bytes))
}
Picked::Paths(paths) => read_path(path_string(paths.first().ok_or(CANCELLED)?)),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => Err(UNEXPECTED.into()),
}
}
/// The file at `path` with its contents; one that can't be read fails with "<file name>: <why>".
fn read_path(path: String) -> Result<(String, Vec<u8>), String> {
let bytes = photocraft_format::read_file(Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?;
Ok((path, bytes))
}
/// One file chosen in the several-file picker ([`PhotocraftApp::pick_files_bytes`]).
#[derive(Debug)]
pub(crate) enum PickedFile {
/// A file on disk (desktop), by its full path: read when its turn comes.
Path(String),
/// A file's name and contents (the web, where the page gets contents rather than paths).
Contents(String, Vec<u8>),
}
impl PickedFile {
/// Its name (the full path on the desktop) and contents, reading a desktop file now; one that
/// can't be read fails with "<file name>: <why>", as in [`PhotocraftApp::pick_file_bytes`].
pub(crate) fn read(self) -> Result<(String, Vec<u8>), String> {
match self {
Self::Path(path) => read_path(path),
Self::Contents(name, bytes) => Ok((name, bytes)),
}
}
}
/// The files chosen in a several-file picker, in the order the dialog returns them (none: Cancel).
fn picked_files(picked: Picked) -> Result<Vec<PickedFile>, String> {
let files: Vec<PickedFile> = match picked {
Picked::Paths(paths) => paths.iter().map(|p| PickedFile::Path(path_string(p))).collect(),
Picked::Contents(files) => files.into_iter().map(|(name, bytes)| PickedFile::Contents(name, bytes)).collect(),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(UNEXPECTED.into()),
};
if files.is_empty() {
return Err(CANCELLED.into());
}
Ok(files)
}
#[cfg(test)]
#[path = "file_dialog/tests.rs"]
mod tests;
+1 -1
View File
@@ -776,7 +776,7 @@ fn place_embedded_uses_the_single_file_picker_and_accepts_contents() {
// Cancel leaves the document alone and does not report an error.
menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap();
assert_eq!(last_request(&files).kind, PickKind::Open);
assert_eq!(last_request(&files).kind, PickKind::OpenMany);
cancel(&files);
app.poll_file_dialog();
assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before);
+76 -2
View File
@@ -100,7 +100,8 @@ pub(crate) fn log_drag_over(ctx: &egui::Context, hovering: usize) {
}
/// A file dropped on the canvas, waiting its turn to be placed in the document it was dropped on
/// (queued with its [`DocId`] in `drop_places`).
/// (queued with its [`DocId`] in `drop_places`), or one of several files chosen at once in File ›
/// Place Embedded's dialog, waiting its turn in the document the command was given in.
pub(crate) enum DropPlace {
/// Destination captured when the file is dropped, before a later pointer move.
At { source: Box<DropPlace>, frame: Option<photocraft_doc::LayerId> },
@@ -109,6 +110,10 @@ pub(crate) enum DropPlace {
/// Read by the shell itself (the browser reads dropped files asynchronously): its name and
/// contents, delivered through [`Services::place_inbox`](crate::Services::place_inbox).
Bytes(String, Vec<u8>),
/// Chosen in File › Place Embedded's dialog (desktop), by its full path: read when its turn
/// comes and placed as that dialog places a single file. The web's picks carry their contents
/// and wait as [`Self::Bytes`].
Path(String),
}
impl DropPlace {
@@ -117,6 +122,7 @@ impl DropPlace {
match self {
Self::At { source, .. } => source.queued_bytes(),
Self::File(f) => f.bytes.as_ref().map_or(0, |b| b.len()),
Self::Path(_) => 0,
Self::Bytes(_, bytes) => bytes.len(),
}
}
@@ -127,6 +133,7 @@ impl DropPlace {
match self {
Self::At { source, .. } => source.holds_bytes(),
Self::File(f) => f.bytes.is_some(),
Self::Path(_) => false,
Self::Bytes(..) => true,
}
}
@@ -557,6 +564,12 @@ impl PhotocraftApp {
let placed = self.place_bytes_with(&name, bytes, None, &params);
(name, placed)
}
DropPlace::Path(path) => {
let placed = photocraft_format::read_file(std::path::Path::new(&path))
.map_err(|e| e.to_string())
.and_then(|bytes| self.place_bytes_with(&path, bytes, None, &params));
(display_name(&path), placed)
}
};
match placed {
// Running in the background: Free Transform starts when the layer has landed.
@@ -575,6 +588,32 @@ impl PhotocraftApp {
}
}
/// File › Place Embedded with several files chosen (#14107): as in the reference application,
/// each is placed in `doc` in turn, in the order the dialog returned them, with its own Free
/// Transform and its own history state. They wait in the queue of files dropped on the canvas,
/// so the next one is placed once the previous one's transform is committed or cancelled (Esc
/// takes back only that file), and with Skip Transform when Placing all of them are placed at
/// once. A file that can't be read or placed is reported and the next one placed.
///
/// Every chosen file is queued: the drop queue's admission limits ([`queue_takes_drop`]) are
/// not applied to them. A desktop pick waits as its path, and a web pick's contents were
/// already read by the browser when the dialog answered, so refusing it would free nothing
/// and only lose a file the user chose. Each is released as soon as it is placed, and while
/// they wait they count against the limit for later drops.
///
/// None of them fills a selected Frame layer (`"frame": false`), as a single file would: each
/// would replace the previous one's image there, without a box or a layer of its own.
pub(crate) fn place_picked(&mut self, ctx: &egui::Context, doc: DocId, files: Vec<crate::file_dialog::PickedFile>) {
for file in files {
let place = match file {
crate::file_dialog::PickedFile::Path(path) => DropPlace::Path(path),
crate::file_dialog::PickedFile::Contents(name, bytes) => DropPlace::Bytes(name, bytes),
};
self.drop_places.push_back((doc, DropPlace::At { source: Box::new(place), frame: None }));
}
self.place_next_dropped(ctx);
}
/// Queue the web drops onto the canvas that the shell has read since the last frame
/// ([`Services::place_inbox`](crate::Services::place_inbox)), for the document they were
/// dropped on.
@@ -620,8 +659,15 @@ impl PhotocraftApp {
/// Place a file's bytes as a smart object layer (File › Place; `linked`: Place Linked, to that
/// path), for files that weren't read from a path the command can read. With background jobs
/// on it starts a job (`{"job", "pending": true}`; see [`crate::jobs_ui::track_place`]).
///
/// As in the reference application, Place Embedded centres the file on a selection, removing
/// it (#14102); otherwise a place centres it on the part of the canvas in view (#14103).
pub(crate) fn place_bytes(&mut self, name: &str, bytes: Vec<u8>, linked: Option<String>) -> Result<serde_json::Value, String> {
self.place_bytes_with(name, bytes, linked, &serde_json::json!({}))
let mut params = serde_json::json!({"centerOnSelection": linked.is_none()});
if let Some(centre) = visible_canvas_centre(self) {
params["center"] = serde_json::json!(centre);
}
self.place_bytes_with(name, bytes, linked, &params)
}
/// [`PhotocraftApp::place_bytes`] with the command's `params` (a frame to fill): a job where
@@ -655,6 +701,31 @@ impl PhotocraftApp {
}
}
/// Where a place lands when only part of the canvas is in view (#14103): the centre of the part
/// of the canvas the active view shows, in document pixels. `None` (the canvas centre) when the
/// whole canvas is in view, and in the cases not measured in the reference application: a
/// rotated view, or one that shows the canvas whole on one axis. `None` too when the place fills
/// the active layer's frame, whose `center` is in the frame's own space.
fn visible_canvas_centre(app: &PhotocraftApp) -> Option<[f64; 2]> {
let view = crate::canvas::document_display::active_view(app)?;
if view.rotation.abs() > 1e-6 {
return None;
}
let st = app.session.active()?;
if st.active_layer.is_some_and(|id| photocraft_engine::frame_cmds::frame_of(&st.doc, id).is_some()) {
return None;
}
let size = st.doc.size;
let shown = view.visible();
// The shown span of the canvas on one axis, if the view cuts it there.
let cut = |(lo, hi): (f64, f64), len: u32| {
let len = f64::from(len);
let (lo, hi) = (lo.max(0.0), hi.min(len));
(lo < hi && (lo > 0.0 || hi < len)).then_some((lo + hi) / 2.0)
};
Some([cut((shown.x0, shown.x1), size.width)?, cut((shown.y0, shown.y1), size.height)?])
}
/// Order names like a file browser does: runs of digits by their value (`File_2` before
/// `File_10`), everything else case-insensitively; names equal that way fall back to the exact
/// text so the order is total.
@@ -729,4 +800,7 @@ fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool {
#[cfg(test)]
mod dialog_order_tests;
#[cfg(test)]
#[path = "place_multiple_files_tests.rs"]
mod place_multiple_files_tests;
#[cfg(test)]
mod tests;
+3
View File
@@ -1093,3 +1093,6 @@ mod red_eye_context_menu_tests;
#[cfg(test)]
mod clone_stamp_indexed_bar_tests;
#[cfg(test)]
mod place_visible_centre_tests;
@@ -0,0 +1,160 @@
//! File › Automate › Batch: OK checks for a missing source folder, then a missing destination
//! folder, as the reference does (#13669). The first that fails refuses OK with the reference's
//! message in a one-button alert titled "Batch"; the dialog stays open with every value, and
//! nothing runs. The same holds for a
//! confirm through the control channel.
use craft::automation::actions::{Action, ActionStep};
use craft::automation::ui::actions::ActionSelection;
use craft::ui::dialog::DialogId;
use photocraft_engine::actions_cmds::ActionsExt;
use serde_json::{Value, json};
use super::{NO_DESTINATION_FOLDER, NO_SOURCE_FOLDER};
use crate::PhotocraftApp;
use crate::control::{ControlRequest, Reply, handle};
const BATCH: &str = "file.automate.batch";
/// The Batch dialog, opened from its menu over a 2 × 1 document with the action Invert selected
/// in the Actions panel, after the frame that loads its defaults; `input` and `output` set to the
/// given paths.
fn batch(input: &str, output: &str) -> (Box<PhotocraftApp>, egui::Context, DialogId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 2, "height": 1})).unwrap();
app.session.actions_mut().list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap();
app.ui.actions.panel.selected = Some(ActionSelection::Action(0));
let ctx = app.ctx().clone();
let reply = crate::menus::invoke(&mut app, &ctx, BATCH, json!({})).expect("the Batch dialog opens");
let want = reply["dialog"].as_str().expect("the reply names a dialog").to_owned();
let id = app.framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|id| id.value().to_string() == want).expect("the dialog is open");
let mut output_frame = ctx.run_ui(Default::default(), |ui| {
let mut frame = eframe::Frame::_new_kittest();
app.logic_frame(ui.ctx(), &mut frame);
app.ui_frame(ui, &mut frame);
});
output_frame.textures_delta.clear();
set(&mut app, &ctx, id, "input", json!(input));
set(&mut app, &ctx, id, "output", json!(output));
(app, ctx, id)
}
/// Sets the dialog's field `key` as automation does.
fn set(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId, key: &str, value: Value) {
app.framework.dialogs.set_json_field(ctx, id, key, value).unwrap_or_else(|e| panic!("{key}: {e}"));
}
/// The values the open dialog `id` lists; `None` once it closed.
fn fields(app: &PhotocraftApp, id: DialogId) -> Option<Value> {
app.framework.dialogs.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields)
}
/// The messages of the alerts the host has open (`HostedAlert`'s key is "alert").
fn alerts(app: &PhotocraftApp) -> Vec<String> {
let open = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert"));
open.filter_map(|d| Some(d.fields.as_ref()?["message"].as_str()?.to_string())).collect()
}
/// A folder holding one 2 × 1 PNG, `in/a.png`, and the path of an output folder `out` beside it.
fn image_folder() -> (tempfile::TempDir, String, String) {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("in")).unwrap();
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 2, "height": 1})).unwrap();
session.execute("file.saveACopy", json!({"path": dir.path().join("in/a.png").to_string_lossy()})).unwrap();
let input = dir.path().join("in").to_string_lossy().into_owned();
let output = dir.path().join("out").to_string_lossy().into_owned();
(dir, input, output)
}
#[test]
fn ok_without_a_source_folder_is_refused_and_keeps_the_dialog_open() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let (dir, _, output) = image_folder();
let (mut app, ctx, id) = batch("", &output);
let before = fields(&app, id).expect("the dialog is open");
assert_eq!(crate::dialogs::confirm(&mut app, &ctx, id), Err(NO_SOURCE_FOLDER.to_string()));
assert_eq!(NO_SOURCE_FOLDER, "You must choose a source folder.");
assert_eq!(alerts(&app), [NO_SOURCE_FOLDER], "the refusal shows in an alert");
assert_eq!(fields(&app, id), Some(before), "the dialog stays open with every value");
assert!(!dir.path().join("out").exists(), "nothing was written");
assert_eq!(app.session.documents().len(), 1, "nothing was opened");
});
}
#[test]
fn ok_without_a_destination_folder_is_refused_and_writes_nothing() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let (dir, input, _) = image_folder();
let (mut app, ctx, id) = batch(&input, "");
let before = fields(&app, id).expect("the dialog is open");
assert_eq!(crate::dialogs::confirm(&mut app, &ctx, id), Err(NO_DESTINATION_FOLDER.to_string()));
assert_eq!(NO_DESTINATION_FOLDER, "You must choose a destination folder.");
assert_eq!(alerts(&app), [NO_DESTINATION_FOLDER], "the refusal shows in an alert");
assert_eq!(fields(&app, id), Some(before));
let files: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(files, ["in"], "nothing was written");
});
}
/// The checks run in the reference's order: with both folders missing, the source one is named.
/// A path of blanks names no folder either.
#[test]
fn the_source_folder_is_checked_before_the_destination() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
for (input, output, message) in [("", "", NO_SOURCE_FOLDER), (" ", "", NO_SOURCE_FOLDER), ("in", " ", NO_DESTINATION_FOLDER)] {
let (mut app, ctx, id) = batch(input, output);
assert_eq!(crate::dialogs::confirm(&mut app, &ctx, id), Err(message.to_string()), "input {input:?}, output {output:?}");
assert!(fields(&app, id).is_some(), "the dialog stays open");
}
});
}
#[test]
fn a_confirm_over_the_control_channel_gets_the_same_check() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let (mut app, ctx, id) = batch("", "");
let before = fields(&app, id).expect("the dialog is open");
let dialog = id.value().to_string();
// Repeated confirms answer the same refusal.
for _ in 0..2 {
let (confirm, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": dialog}));
let Reply::Done(reply) = handle(&mut app, &ctx, &confirm) else { panic!("ui.dialog.confirm replies at once") };
assert_eq!(reply["ok"], false, "{reply}");
assert!(reply.to_string().contains(NO_SOURCE_FOLDER), "{reply}");
}
assert_eq!(fields(&app, id), Some(before));
// With the source set, the destination is checked next.
set(&mut app, &ctx, id, "input", json!("in"));
let (confirm, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": dialog}));
let Reply::Done(reply) = handle(&mut app, &ctx, &confirm) else { panic!("ui.dialog.confirm replies at once") };
assert!(reply.to_string().contains(NO_DESTINATION_FOLDER), "{reply}");
});
}
/// With both folders chosen OK runs the batch and closes the dialog.
#[test]
fn ok_with_both_folders_runs_the_batch() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let (dir, input, output) = image_folder();
let (mut app, ctx, id) = batch(&input, &output);
crate::dialogs::confirm(&mut app, &ctx, id).expect("OK is accepted");
assert!(fields(&app, id).is_none(), "OK closes the dialog");
assert!(alerts(&app).is_empty(), "an accepted OK shows no alert");
assert!(dir.path().join("out/a.png").is_file(), "the batch wrote a.png");
});
}
/// Opened Files reads no folder, and without an output folder it leaves the documents open and
/// changed: no check applies.
#[test]
fn opened_files_without_folders_is_not_refused() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
let (mut app, ctx, id) = batch("", "");
set(&mut app, &ctx, id, "source", json!("open"));
crate::dialogs::confirm(&mut app, &ctx, id).expect("OK is accepted");
assert!(fields(&app, id).is_none(), "OK closes the dialog");
assert_eq!(app.session.documents().len(), 1, "the document stays open");
});
}
+64 -3
View File
@@ -4,7 +4,7 @@ use crate::dialogs::image_processor_ui;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _};
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::requests::PathKind;
@@ -667,6 +667,48 @@ fn channel_form(app: &PhotocraftApp, id: &str) -> Option<(Vec<Param>, DialogFiel
Some((rows, DialogFields::new()))
}
/// Batch's OK with Source: Folder and no source folder chosen (#13669).
pub(crate) const NO_SOURCE_FOLDER: &str = "You must choose a source folder.";
/// Batch's OK with a folder destination and no destination folder chosen (#13669).
pub(crate) const NO_DESTINATION_FOLDER: &str = "You must choose a destination folder.";
/// Does a Batch folder field name a folder? No value and an empty or blank path count as nothing chosen.
fn batch_folder_chosen(path: Option<&str>) -> bool {
path.is_some_and(|path| !path.trim().is_empty())
}
/// The first of the reference's OK checks the Batch dialog's values fail, in its order: the source folder, then the
/// destination folder. Only a folder source has either: Opened Files reads no folder, and without an output it leaves
/// the documents open.
fn batch_missing_choice(fields: &DialogFields) -> Option<&'static str> {
if fields.text("source").is_some_and(|source| source != "folder") {
return None;
}
if !batch_folder_chosen(fields.text("input")) {
return Some(NO_SOURCE_FOLDER);
}
let folder_destination = fields.text("destination").is_none_or(|destination| destination == "folder");
(folder_destination && !batch_folder_chosen(fields.text("output"))).then_some(NO_DESTINATION_FOLDER)
}
/// The `ParamFamily::check` of the Batch dialog (#13669): OK, from the button or a confirm through the control channel,
/// is refused while a folder source or its destination names no folder. As in the reference, a one-button alert
/// titled "Batch" shows the message; the dialog stays open with its values (the refusal also shows under its rows and
/// answers a control-channel confirm), and nothing runs.
pub(crate) fn batch_check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), Label> {
let message = match batch_missing_choice(&result.fields) {
Some(NO_SOURCE_FOLDER) => tl!("You must choose a source folder."),
Some(_) => tl!("You must choose a destination folder."),
None => return Ok(()),
};
crate::dialogs::alerts::show(app, craft::ui::dialog::Alert::new(tl!("Batch"), message));
Err(Label::from(message))
}
#[cfg(test)]
#[path = "batch_ok_validation_tests.rs"]
mod batch_ok_validation_tests;
/// Handle menu commands that need a shell action or a parameter dialog before execution.
pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
if id == "file.closeAll" || id == "file.closeOthers" {
@@ -716,8 +758,8 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
Err(e) => return Some(Err(e)),
};
let linked = id == "file.placeLinked";
let ctx = ctx.clone();
Some(app.pick_file_bytes(move |app, name, bytes| {
let (ctx, queue_ctx) = (ctx.clone(), ctx.clone());
let place = move |app: &mut PhotocraftApp, name: String, bytes: Vec<u8>| {
if app.ui.transform.is_some() {
return Err("Commit or cancel the transform first".into());
}
@@ -729,6 +771,25 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
crate::transform_tool::begin_placed(app, &ctx)?;
}
Ok(result)
};
if linked {
return Some(app.pick_file_bytes(place));
}
// Place Embedded takes several files (#14107); one file is placed as before.
Some(app.pick_files_bytes(move |app, files| match <[crate::file_dialog::PickedFile; 1]>::try_from(files) {
Ok([file]) => {
let (name, bytes) = file.read()?;
place(app, name, bytes)
}
Err(files) => {
if app.ui.transform.is_some() {
return Err("Commit or cancel the transform first".into());
}
app.refocus(doc)?;
let count = files.len();
app.place_picked(&queue_ctx, doc, files);
Ok(json!({ "files": count }))
}
}))
}
"layer.smartObjects.replaceContents" => {
@@ -0,0 +1,266 @@
//! #14107: File › Place Embedded with several files chosen at once places them one after another,
//! each with its own Free Transform box, its own layer above the previous one and its own history
//! state, as the reference application does.
use super::*;
use crate::menus;
use craft::host::{PickKind, Picked, ScriptedFiles};
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
/// An app with one 40×30 document whose file dialogs answer `answers` in order (then Cancel), and
/// its file service.
fn app_answering(answers: impl IntoIterator<Item = Picked>) -> (Box<PhotocraftApp>, Arc<ScriptedFiles>) {
let files = Arc::new(ScriptedFiles::answering(answers));
let services = crate::Services { files: Some(files.clone()), ..Default::default() };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.run("file.new", json!({"width": 40, "height": 30})).unwrap();
(app, files)
}
/// An app with one 40×30 document whose File › Place Embedded dialog will answer `picked`.
fn app_picking(picked: Picked) -> (Box<PhotocraftApp>, Arc<ScriptedFiles>) {
app_answering([picked])
}
/// File › Place Embedded from the menu, its dialog shown and answered at the end of the frame.
fn place_embedded(app: &mut PhotocraftApp, ctx: &egui::Context) {
menus::invoke(app, ctx, "file.placeEmbedded", json!({})).unwrap();
app.poll_file_dialog();
}
/// PNG bytes of a white `w`×`h` image.
fn png(w: u32, h: u32) -> Vec<u8> {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
photocraft_io::export(&s.active().unwrap().doc, "p.png", &Default::default()).unwrap().bytes
}
/// The active document's layer names, bottom to top.
fn names(app: &PhotocraftApp) -> Vec<String> {
app.session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect()
}
/// The active layer's name.
fn active_name(app: &PhotocraftApp) -> String {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone()
}
/// How many history states the active document has behind it.
fn history_steps(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
/// The open Free Transform box of a placed layer, as (left, top, right, bottom) in document pixels.
fn place_box(app: &PhotocraftApp) -> [f64; 4] {
let t = app.ui.transform.as_ref().expect("a placed file is in Free Transform");
assert_eq!(t.made, Some(crate::state::MadeLayer::Place));
let quad = t.session.quad();
let xs = quad.map(|c| c.x);
let ys = quad.map(|c| c.y);
let fold = |v: [f64; 4], f: fn(f64, f64) -> f64| v.into_iter().reduce(f).unwrap();
[fold(xs, f64::min), fold(ys, f64::min), fold(xs, f64::max), fold(ys, f64::max)]
}
/// Three files (20×10, 8×6 and 12×4), as the web picker hands them over: each with its contents.
fn three_contents() -> Picked {
Picked::Contents(vec![("first.png".into(), png(20, 10)), ("second.png".into(), png(8, 6)), ("third.png".into(), png(12, 4))])
}
#[test]
fn place_embedded_asks_for_several_files_and_place_linked_for_one() {
let ctx = egui::Context::default();
let (mut app, files) = app_answering([Picked::Contents(vec![("one.png".into(), png(4, 4))]), Picked::Cancelled]);
place_embedded(&mut app, &ctx);
assert_eq!(files.requests().iter().map(|r| r.kind).collect::<Vec<_>>(), [PickKind::OpenMany]);
// Place Linked keeps its single-file dialog (several files there were not measured).
crate::transform_tool::commit(&mut app);
menus::invoke(&mut app, &ctx, "file.placeLinked", json!({})).unwrap();
app.poll_file_dialog();
assert_eq!(files.requests().iter().map(|r| r.kind).collect::<Vec<_>>(), [PickKind::OpenMany, PickKind::Open]);
}
/// The measured sequence: the first file appears with its box, ↩ commits it as its own history
/// state, the second then appears with its own box as its own layer above the first, and Esc on it
/// removes only that file. The third still follows.
#[test]
fn several_files_are_placed_one_after_another_each_in_its_own_transform() {
let ctx = egui::Context::default();
let (mut app, _) = app_picking(three_contents());
let steps = history_steps(&app);
place_embedded(&mut app, &ctx);
assert!(!app.ui.status_error, "{}", app.ui.status);
// Only the first file is placed: its box is its own size, centred on the 40×30 canvas.
assert_eq!(names(&app), ["Background", "first"]);
assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]);
assert_eq!(app.drop_places.len(), 2, "the other two wait their turn");
// Frames go by while the box is open: nothing else is placed.
app.place_next_dropped(&ctx);
assert_eq!(names(&app), ["Background", "first"]);
assert_eq!(app.drop_places.len(), 2);
// ↩ commits the first file: one history state.
crate::transform_tool::commit(&mut app);
assert_eq!(history_steps(&app), steps + 1);
// The next frame places the second one above it, with its own box.
app.place_next_dropped(&ctx);
assert_eq!(names(&app), ["Background", "first", "second"]);
assert_eq!(active_name(&app), "second");
assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]);
// Esc removes only the second file; the first stays placed and committed.
crate::transform_tool::cancel(&mut app);
assert_eq!(names(&app), ["Background", "first"]);
assert_eq!(history_steps(&app), steps + 1);
assert!(!app.session.active().unwrap().history.can_redo());
// And the third is placed next, above the first.
app.place_next_dropped(&ctx);
assert_eq!(names(&app), ["Background", "first", "third"]);
assert_eq!(place_box(&app), [14.0, 13.0, 26.0, 17.0]);
crate::transform_tool::commit(&mut app);
assert_eq!(history_steps(&app), steps + 2);
app.place_next_dropped(&ctx);
assert!(app.ui.transform.is_none() && app.drop_places.is_empty());
// Each file is its own history state: one Undo takes back only the third.
app.run("edit.undo", json!({})).unwrap();
assert_eq!(names(&app), ["Background", "first"]);
}
/// On the desktop the dialog answers paths: each file is read when its turn comes and placed as
/// the dialog's single file is (named after the file, an embedded smart object), in the order the
/// dialog returned them. A file that can't be read is reported and the next one placed.
#[test]
fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let (b, a) = (dir.join("b.png"), dir.join("a.png"));
std::fs::write(&b, png(20, 10)).unwrap();
std::fs::write(&a, png(8, 6)).unwrap();
let missing = dir.join("gone.png");
let paths: Vec<PathBuf> = [&b, &missing, &a].map(|p| p.to_path_buf()).to_vec();
let ctx = egui::Context::default();
let (mut app, _) = app_picking(Picked::Paths(paths));
place_embedded(&mut app, &ctx);
// The dialog's order, not name order: b first.
assert_eq!(names(&app), ["Background", "b"]);
assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]);
// Waiting files hold their paths, not their contents, and won't fill a selected frame.
assert!(app.drop_places.iter().all(|(_, p)| matches!(p, DropPlace::At { source, frame: None } if matches!(**source, DropPlace::Path(_)))));
crate::transform_tool::commit(&mut app);
app.place_next_dropped(&ctx);
assert_eq!(app.ui.notices.iter().filter(|n| n.tone == crate::notices::Tone::Bad && n.title.contains("gone.png")).count(), 1);
assert_eq!(names(&app), ["Background", "b", "a"]);
assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]);
let st = app.session.active().unwrap();
assert!(matches!(
&st.doc.layer(st.active_layer.unwrap()).unwrap().content,
photocraft_doc::LayerContent::Smart(sm) if matches!(&sm.source, photocraft_doc::SmartSource::Embedded { .. })
));
crate::transform_tool::commit(&mut app);
assert!(app.drop_places.is_empty());
}
/// With a Frame layer selected, the chosen files don't fill it one over another: each is placed
/// as its own layer with its own box, and the frame stays empty.
#[test]
fn several_files_with_a_frame_selected_are_each_placed_as_their_own_layer() {
let ctx = egui::Context::default();
let (mut app, _) = app_picking(three_contents());
let frame = app.run("layer.new.frame", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap()["layer"].as_u64().unwrap();
let frame = photocraft_doc::LayerId(frame);
assert_eq!(app.session.active().unwrap().active_layer, Some(frame), "the frame is selected");
let steps = history_steps(&app);
place_embedded(&mut app, &ctx);
for (i, name) in ["first", "second", "third"].into_iter().enumerate() {
assert_eq!(active_name(&app), name);
place_box(&app);
crate::transform_tool::commit(&mut app);
assert_eq!(history_steps(&app), steps + i + 1);
app.place_next_dropped(&ctx);
}
assert!(app.ui.transform.is_none() && app.drop_places.is_empty());
assert!(names(&app).ends_with(&["first".to_string(), "second".to_string(), "third".to_string()]), "{:?}", names(&app));
let doc = &app.session.active().unwrap().doc;
assert!(doc.layer(frame).unwrap().children().is_none_or(<[_]>::is_empty), "nothing filled the frame");
}
/// With Skip Transform when Placing on, all the chosen files are placed and committed at once, one
/// history state each, without Free Transform.
#[test]
fn skip_transform_when_placing_commits_every_file_at_once() {
let ctx = egui::Context::default();
let (mut app, _) = app_picking(three_contents());
app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap();
let steps = history_steps(&app);
place_embedded(&mut app, &ctx);
assert!(app.ui.transform.is_none() && app.drop_places.is_empty());
assert_eq!(names(&app), ["Background", "first", "second", "third"]);
assert_eq!(history_steps(&app), steps + 3);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(names(&app), ["Background", "first", "second"]);
}
/// With background jobs on, each file is decoded on a worker: the next one starts only once the
/// previous one has landed and its box has been committed.
#[test]
fn background_places_follow_one_another() {
let ctx = egui::Context::default();
let (mut app, _) = app_picking(Picked::Contents(vec![("first.png".into(), png(20, 10)), ("second.png".into(), png(8, 6))]));
app.background_jobs = true;
place_embedded(&mut app, &ctx);
let wait = |app: &mut PhotocraftApp, done: &dyn Fn(&PhotocraftApp) -> bool| {
let t = std::time::Instant::now();
while !done(app) {
assert!(t.elapsed() < std::time::Duration::from_secs(30), "not placed after 30 s");
crate::jobs_ui::tick(app, &ctx);
app.place_next_dropped(&ctx);
std::thread::sleep(std::time::Duration::from_millis(2));
}
};
wait(&mut app, &|app| app.ui.transform.is_some());
assert_eq!(names(&app), ["Background", "first"]);
assert_eq!(app.drop_places.len(), 1);
crate::transform_tool::commit(&mut app);
wait(&mut app, &|app| app.ui.transform.is_some());
assert_eq!(names(&app), ["Background", "first", "second"]);
assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]);
}
/// One file chosen is placed as before: at once, in Free Transform, with
/// nothing queued, and a file that can't be read is the command's error.
#[test]
fn a_single_chosen_file_is_placed_as_before() {
let ctx = egui::Context::default();
let (mut app, _) = app_picking(Picked::Contents(vec![("one.png".into(), png(20, 10))]));
place_embedded(&mut app, &ctx);
assert_eq!(names(&app), ["Background", "one"]);
assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]);
assert!(app.drop_places.is_empty());
let missing = std::env::temp_dir().join(format!("photocraft-place-missing-{}.png", std::process::id()));
let (mut app, _) = app_picking(Picked::Paths(vec![missing]));
place_embedded(&mut app, &ctx);
assert!(app.ui.status_error);
assert!(app.ui.status.contains("photocraft-place-missing-"), "{}", app.ui.status);
assert_eq!(names(&app), ["Background"]);
assert!(app.ui.transform.is_none() && app.drop_places.is_empty());
}
/// Every chosen file is placed, even past the limits that bound drops waiting for their document
/// (32 browser drops): the web's picks are already read when the dialog answers, so none is lost.
#[test]
fn every_chosen_file_is_placed_past_the_drop_queue_limit() {
let ctx = egui::Context::default();
let files: Vec<(String, Vec<u8>)> = (0..MAX_QUEUED_DROPS + 2).map(|i| (format!("f{i}.png"), png(2, 2))).collect();
let (mut app, _) = app_picking(Picked::Contents(files));
app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap();
let steps = history_steps(&app);
place_embedded(&mut app, &ctx);
assert!(!app.ui.status_error, "{}", app.ui.status);
assert!(app.drop_places.is_empty());
let expected: Vec<String> = std::iter::once("Background".to_string()).chain((0..MAX_QUEUED_DROPS + 2).map(|i| format!("f{i}"))).collect();
assert_eq!(names(&app), expected);
assert_eq!(history_steps(&app), steps + MAX_QUEUED_DROPS + 2);
}
@@ -0,0 +1,143 @@
//! File › Place Embedded / Place Linked centre the placed file on the part of the canvas in view
//! (#14103), and Place Embedded on a selection, which wins over the view (#14102). Measured in the
//! reference application on a 400 × 300 document: at 500 % with the view centred on 147.5,82 a
//! 100 × 60 file lands at 97.5,52 to 197.5,112, and a 1000 × 800 file is still fitted to the
//! canvas (375 × 300) but centred there, -40,-68 to 335,232.
use crate::canvas::testing;
use crate::{PhotocraftApp, Services, menus};
use craft::host::{Picked, ScriptedFiles};
use serde_json::json;
use std::sync::Arc;
/// A 400 × 300 document without rulers, its view at `zoom` (device pixels per document pixel)
/// centred on `center` and turned by `rotation`, shown on the canvas; the file dialog answers
/// (see [`place`]) with a gray `w` × `h` PNG on disk named `name` (a path, so Place Linked can
/// link to it).
fn placing_app(zoom: f32, center: [f32; 2], rotation: f32, name: &str, (w, h): (u32, u32)) -> (Box<PhotocraftApp>, Arc<ScriptedFiles>, std::path::PathBuf) {
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![128; (w * h * 3) as usize]).unwrap();
let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("photocraft-place-visible-centre-{}-{unique}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
let files = Arc::new(ScriptedFiles::held());
let services = Services { files: Some(files.clone()), ..Default::default() };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.run("file.new", json!({"width": 400, "height": 300, "depth": 8})).unwrap();
app.ui.extras.rulers = false;
show(&mut app, zoom, center, rotation);
(app, files, path)
}
/// Shows the view at `zoom`, centred on `center` and turned by `rotation`, on the canvas.
fn show(app: &mut PhotocraftApp, zoom: f32, center: [f32; 2], rotation: f32) {
testing::shown(app);
let v = &mut app.ui.views[0];
(v.zoom, v.center, v.rotation) = (zoom, center, rotation);
v.clear_pending();
testing::shown(app);
let shown = testing::view(app).expect("the canvas shows the view");
// The canvas aligns the view to device pixels, so its centre may move by up to half of one.
let near = |a: f64, b: f32| (a - f64::from(b)).abs() <= 0.5 / f64::from(zoom) + 1e-3;
assert!(near(shown.center.x, center[0]) && near(shown.center.y, center[1]), "the canvas shows the view asked for: {:?}", shown.center);
}
/// The part of the canvas the view shows: `[x0, y0, x1, y1]` in document pixels.
fn visible(app: &PhotocraftApp) -> [f64; 4] {
let r = testing::view(app).expect("the canvas shows a view").visible();
[r.x0, r.y0, r.x1, r.y1]
}
/// Runs `command` from the menu and answers its file dialog with `path`; the placed layer's box.
fn place(app: &mut PhotocraftApp, files: &ScriptedFiles, path: &std::path::Path, command: &str) -> [i32; 4] {
let ctx = app.ctx().clone();
menus::invoke(app, &ctx, command, json!({})).unwrap();
files.answer(Picked::Paths(vec![path.to_path_buf()])).expect("a file dialog is open");
app.poll_file_dialog();
let st = app.session.active().unwrap();
let layer = st.doc.layer(st.active_layer.unwrap()).unwrap();
assert!(matches!(layer.content, photocraft_doc::LayerContent::Smart(_)), "{command} placed the file");
let b = photocraft_engine::transform_cmds::transform_bounds(&st.doc, layer);
[b.x0, b.y0, b.x1, b.y1]
}
/// The measured view: 500 %, centred on 147.5,82 (160 × 120 document pixels in sight).
const ZOOMED: (f32, [f32; 2]) = (5.0, [147.5, 82.0]);
/// The whole canvas in view: centred on the canvas, as before (100 × 60 at 150,120).
#[test]
fn with_the_whole_canvas_in_view_a_place_centres_on_the_canvas() {
for command in ["file.placeEmbedded", "file.placeLinked"] {
let (mut app, files, path) = placing_app(1.0, [200.0, 150.0], 0.0, "src.png", (100, 60));
let [x0, y0, x1, y1] = visible(&app);
assert!(x0 <= 0.0 && y0 <= 0.0 && x1 >= 400.0 && y1 >= 300.0, "the whole canvas is in view: {x0},{y0} to {x1},{y1}");
assert_eq!(place(&mut app, &files, &path, command), [150, 120, 250, 180], "{command}");
}
}
/// Part of the canvas in view: the box is centred there. The measured box is 97.5,52 to
/// 197.5,112; a placed image starts on a whole pixel, so it is 98 to 198 across (half a pixel
/// right, as the canvas centring of an odd-sized file already is) and exactly 52 to 112 down.
#[test]
fn with_part_of_the_canvas_in_view_a_place_centres_on_that_part() {
for command in ["file.placeEmbedded", "file.placeLinked"] {
let (mut app, files, path) = placing_app(ZOOMED.0, ZOOMED.1, 0.0, "src.png", (100, 60));
let [x0, y0, x1, y1] = place(&mut app, &files, &path, command);
assert_eq!((x1 - x0, y1 - y0), (100, 60), "{command}: the size is unchanged");
assert_eq!((y0, y1), (52, 112), "{command}");
assert!((f64::from(x0 + x1) / 2.0 - 147.5).abs() <= 0.5, "{command}: centred on 147.5 across: {x0}..{x1}");
}
}
/// Resize Image During Place still fits a larger file to the canvas; only the centre moves, and
/// the box may reach past the canvas edge.
#[test]
fn a_fitted_place_keeps_its_size_and_moves_its_centre() {
let (mut app, files, path) = placing_app(ZOOMED.0, ZOOMED.1, 0.0, "big.png", (1000, 800));
assert_eq!(place(&mut app, &files, &path, "file.placeEmbedded"), [-40, -68, 335, 232]);
}
/// A selection wins over the view (#14102): Place Embedded centres on it and removes it.
#[test]
fn a_selection_wins_over_the_view() {
let (mut app, files, path) = placing_app(ZOOMED.0, ZOOMED.1, 0.0, "src.png", (100, 60));
app.run("select.rect", json!({"x": 300, "y": 200, "width": 80, "height": 80})).unwrap();
assert_eq!(place(&mut app, &files, &path, "file.placeEmbedded"), [290, 210, 390, 270]);
assert!(app.session.active().unwrap().doc.selection.is_none(), "the place removes the selection");
}
/// The views not measured keep the canvas centre: one showing the whole canvas on one axis, and
/// a rotated one.
#[test]
fn a_view_cut_on_one_axis_or_rotated_keeps_the_canvas_centre() {
// At 100 % moved right so the canvas's left 100 pixels are cut off; the whole 300 down shows.
let (mut app, files, path) = placing_app(1.0, [200.0, 150.0], 0.0, "src.png", (100, 60));
let [x0, _, x1, _] = visible(&app);
show(&mut app, 1.0, [(100.0 + (x1 - x0) / 2.0) as f32, 150.0], 0.0);
let [x0, y0, _, y1] = visible(&app);
assert!(x0 > 0.0 && y0 <= 0.0 && y1 >= 300.0, "the view cuts the canvas across only: {x0},{y0} to {y1} down");
assert_eq!(place(&mut app, &files, &path, "file.placeEmbedded"), [150, 120, 250, 180], "cut across only");
let (mut app, files, path) = placing_app(ZOOMED.0, ZOOMED.1, 15.0, "src.png", (100, 60));
assert_eq!(place(&mut app, &files, &path, "file.placeEmbedded"), [150, 120, 250, 180], "rotated");
}
/// Into a selected frame the image fills the frame wherever the view is: the view's centre is
/// not passed, since a frame place's `center` is in the frame's own space.
#[test]
fn a_place_into_a_frame_ignores_the_view() {
let (mut app, files, path) = placing_app(ZOOMED.0, ZOOMED.1, 0.0, "src.png", (100, 100));
let frame = app.run("layer.new.frame", json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["layer"].as_u64().unwrap();
let ctx = app.ctx().clone();
menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap();
files.answer(Picked::Paths(vec![path])).expect("a file dialog is open");
app.poll_file_dialog();
let doc = &app.session.active().unwrap().doc;
let image = &doc.layer(photocraft_doc::LayerId(frame)).unwrap().children().unwrap()[0];
let photocraft_doc::LayerContent::Smart(so) = &image.content else { panic!("the frame holds the placed image") };
let [a, _, _, d, e, f] = so.transform.m;
let placed = [e, f, e + 100.0 * a, f + 100.0 * d].map(|v| (v * 1000.0).round() / 1000.0);
assert_eq!(placed, [10.0, 10.0, 90.0, 90.0], "the image fills the frame");
}
+6 -1
View File
@@ -154,9 +154,13 @@ pub struct ToolOptions {
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 tool shows it, enabled in Shape mode only (#13370); the other shape tools always snap.
/// Triangle (#13370) and Rectangle (#13346) tools show it, enabled in Shape mode only; the other
/// shape tools always snap.
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
/// Rectangle's [`Self::corner_radius`]. 0 draws sharp corners.
pub polygon_corner_radius: f32,
pub line_weight: f32,
/// Line arrowheads.
pub arrow_start: bool,
@@ -500,6 +504,7 @@ impl Default for ToolOptions {
corner_radius: 0.0,
align_edges: true,
polygon_sides: 5,
polygon_corner_radius: 0.0,
line_weight: 1.0,
arrow_start: false,
arrow_end: false,
+1
View File
@@ -565,6 +565,7 @@ pub(crate) fn sanitize(o: &mut ToolOptions) {
fit(&mut o.red_eye_pupil_size, 1.0, 100.0, d.red_eye_pupil_size);
fit(&mut o.red_eye_darken, 0.0, 100.0, d.red_eye_darken);
o.polygon_sides = o.polygon_sides.clamp(3, 100);
fit(&mut o.polygon_corner_radius, *RADIUS_RANGE.start() as f32, *RADIUS_RANGE.end() as f32, d.polygon_corner_radius);
if o.crop.guide_orientation >= o.crop.guide.orientations() {
o.crop.guide_orientation = 0;
}
@@ -0,0 +1,260 @@
//! #13302: the Polygon tool's options bar has its own corner radius after Sides, in px (0 to
//! start, and after Reset Tool), in Shape and Path mode. It rounds the next polygon drawn, never
//! the active one, and shares the Rectangle Radius's 0..150000 range and its "closest value"
//! alert. Text that is not a number keeps the previous value, as the framework's number fields do.
use craft::draw::ui::VectorMode;
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::vector::Knot;
use photocraft_doc::{LayerContent, LiveShape};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
/// An 800 × 600 document with the Polygon tool current.
fn new_app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.ui.tool = Tool::Polygon;
app
}
/// The options bar drawn for `app`.
fn bar_with(app: Box<PhotocraftApp>) -> Harness<'static, Box<PhotocraftApp>> {
let mut h =
Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
h.run_steps(4);
h
}
/// The options-bar number field named `label`.
fn field_rect(h: &Harness<'static, Box<PhotocraftApp>>, label: &str) -> Option<egui::Rect> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).map(|n| n.rect())
}
/// Clicks into Radius, selects its text and types `text`, then Tabs out of it.
fn enter_radius(h: &mut Harness<'static, Box<PhotocraftApp>>, text: &str) {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius")).expect("the Radius field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
/// How many alerts are open.
fn alerts(h: &Harness<'static, Box<PhotocraftApp>>) -> usize {
crate::dialogs::alerts::alerts(h.state()).len()
}
/// The Polygon tool's radius, and the Rectangle tool's, which it must leave alone.
fn radii(h: &Harness<'static, Box<PhotocraftApp>>) -> (f32, f32) {
let o = &h.state().ui.tool_options;
(o.polygon_corner_radius, o.corner_radius)
}
/// The active layer's live shape and outline knots.
fn active_shape(app: &PhotocraftApp) -> (LiveShape, Vec<Knot>) {
let st = app.session.active().unwrap();
let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("not a shape layer") };
(sh.live.clone().unwrap(), sh.path.subpaths[0].knots.clone())
}
/// A Polygon tool drag from `from` to `to`, released there.
fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) {
let mods = egui::Modifiers::NONE;
tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods);
}
/// The issue's measured drag, 400,300 to 600,400, with the Polygon tool's radius at `radius`:
/// the new layer's live shape and outline knots.
fn drawn_with(radius: f32) -> (LiveShape, Vec<Knot>) {
let mut app = new_app();
app.ui.tool_options.polygon_corner_radius = radius;
drag(&mut app, [400.0, 300.0], [600.0, 400.0]);
assert!(!app.ui.status_error, "{}", app.ui.status);
active_shape(&app)
}
/// Where each vertex of the sharp polygon `v` is rounded by an arc of radius `r` tangent to both
/// its edges: the points `r / tan(half the vertex angle)` from it along the edge it comes from and
/// the edge it goes to, at most half the shorter edge (a radius the shape cannot take is capped).
fn tangent_points(v: &[[f64; 2]], r: f64) -> Vec<[f64; 2]> {
let n = v.len();
let along = |from: [f64; 2], to: [f64; 2], t: f64| {
let l = (to[0] - from[0]).hypot(to[1] - from[1]);
[from[0] + (to[0] - from[0]) / l * t, from[1] + (to[1] - from[1]) / l * t]
};
(0..n)
.flat_map(|i| {
let (p, c, q) = (v[(i + n - 1) % n], v[i], v[(i + 1) % n]);
let (a, b) = ([p[0] - c[0], p[1] - c[1]], [q[0] - c[0], q[1] - c[1]]);
let (la, lb) = (a[0].hypot(a[1]), b[0].hypot(b[1]));
let half = ((a[0] * b[0] + a[1] * b[1]) / (la * lb)).acos() / 2.0;
let t = (r / half.tan()).min(la.min(lb) / 2.0);
[along(c, p, t), along(c, q, t)]
})
.collect()
}
/// `a` and `b` within a thousandth of a pixel.
fn near(a: [f64; 2], b: [f64; 2]) -> bool {
(a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3
}
/// Checks `knots` round every vertex of the sharp polygon `sharp` with radius `r`: two anchors a
/// corner, on its edges, each with its handle along that edge towards the vertex (the arc is
/// tangent to the edges), all inside the 400,300 to 600,400 drag box.
fn assert_rounds(knots: &[Knot], sharp: &[Knot], r: f64) {
let v: Vec<[f64; 2]> = sharp.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();
let want = tangent_points(&v, r);
assert_eq!(knots.len(), 2 * v.len(), "two anchors a corner");
for (i, (k, w)) in knots.iter().zip(&want).enumerate() {
let a = [k.anchor.x, k.anchor.y];
assert!(near(a, *w), "anchor {i}: {a:?}, want {w:?}");
let corner = v[i / 2];
// The handle that bends towards the corner: the out handle at the arc's start, the in
// handle at its end. It lies on the edge, between the anchor and the vertex.
let h = if i % 2 == 0 { k.out_ctrl } else { k.in_ctrl };
let cross = (corner[0] - a[0]) * (h.y - a[1]) - (corner[1] - a[1]) * (h.x - a[0]);
let dot = (corner[0] - a[0]) * (h.x - a[0]) + (corner[1] - a[1]) * (h.y - a[1]);
assert!(cross.abs() < 1e-6 && dot > 0.0, "knot {i}: the arc is tangent to the edge");
for p in [k.anchor, k.in_ctrl, k.out_ctrl] {
assert!((400.0..=600.0).contains(&p.x) && (300.0..=400.0).contains(&p.y), "knot {i} is inside the drag box: {p:?}");
}
}
}
#[test]
fn the_radius_field_follows_sides_and_starts_at_zero_in_shape_and_path_mode() {
for mode in [VectorMode::Shape, VectorMode::Path] {
let mut app = new_app();
app.ui.tool_options.shape_mode = mode;
let h = bar_with(app);
let sides = field_rect(&h, "Sides").expect("the Sides field");
let radius = field_rect(&h, "Radius").unwrap_or_else(|| panic!("{mode:?}: the Radius field"));
assert!(radius.left() > sides.right() && (radius.center().y - sides.center().y).abs() < 1.0, "{mode:?}: Radius right after Sides");
assert_eq!(radii(&h), (0.0, 0.0), "{mode:?}: 0 px to start");
}
let h = bar_with({
let mut app = new_app();
app.ui.tool = Tool::Star;
app
});
assert!(field_rect(&h, "Radius").is_none(), "the Star tool has no polygon radius");
}
#[test]
fn a_radius_in_range_is_taken_without_an_alert_and_leaves_the_rectangles_alone() {
for (typed, want) in [("20", 20.0), ("0.5", 0.5), ("150000", 150_000.0), ("0", 0.0)] {
let mut h = bar_with(new_app());
enter_radius(&mut h, typed);
assert_eq!(radii(&h), (want, 0.0), "{typed}");
assert_eq!(alerts(&h), 0, "{typed} is in range");
}
}
#[test]
fn a_radius_past_the_range_takes_the_closest_value_with_one_alert() {
for (typed, want) in [("-5", 0.0), ("99999999", 150_000.0)] {
let mut h = bar_with(new_app());
enter_radius(&mut h, "12");
enter_radius(&mut h, typed);
assert_eq!(radii(&h), (want, 0.0), "{typed}");
assert_eq!(alerts(&h), 1, "{typed}: one alert");
}
}
#[test]
fn text_that_is_no_number_keeps_the_previous_radius() {
let mut h = bar_with(new_app());
enter_radius(&mut h, "12");
enter_radius(&mut h, "abc");
assert_eq!(radii(&h), (12.0, 0.0), "the last valid value stays");
}
#[test]
fn the_radius_field_leaves_the_active_polygon_and_the_history_alone() {
let mut app = new_app();
drag(&mut app, [400.0, 300.0], [600.0, 400.0]);
let before = (active_shape(&app), app.session.active().unwrap().history.past_len());
let mut h = bar_with(app);
enter_radius(&mut h, "30");
assert_eq!(radii(&h), (30.0, 0.0));
let after = (active_shape(h.state()), h.state().session.active().unwrap().history.past_len());
assert_eq!(after, before, "the active polygon keeps its corners and no History state is added");
}
#[test]
fn radius_20_rounds_every_corner_of_the_next_polygon_with_two_tangent_anchors() {
let (_, sharp) = drawn_with(0.0);
let (live, knots) = drawn_with(20.0);
assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 20.0 });
assert_rounds(&knots, &sharp, 20.0);
// 20 px fits every corner, so no arc is capped: a larger radius would move every anchor.
let v: Vec<[f64; 2]> = sharp.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();
assert!(tangent_points(&v, 20.0).iter().zip(tangent_points(&v, 21.0)).all(|(a, b)| !near(*a, b)));
}
#[test]
fn radius_1000_is_capped_by_the_shape_without_an_error() {
let (_, sharp) = drawn_with(0.0);
let (live, knots) = drawn_with(1000.0);
assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 1000.0 });
assert_rounds(&knots, &sharp, 1000.0);
}
#[test]
fn radius_0_draws_the_sharp_polygon() {
let (live, knots) = drawn_with(0.0);
assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 0.0 });
assert_eq!(knots.len(), 5, "one anchor a corner");
assert!(knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor), "no curves");
}
#[test]
fn the_rectangle_radius_does_not_round_the_polygon() {
let mut app = new_app();
app.ui.tool_options.corner_radius = 20.0;
drag(&mut app, [400.0, 300.0], [600.0, 400.0]);
let (live, _) = active_shape(&app);
assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 0.0 });
}
#[test]
fn path_mode_rounds_the_next_outline_too() {
let mut app = new_app();
app.ui.tool_options.shape_mode = VectorMode::Path;
app.ui.tool_options.polygon_corner_radius = 20.0;
drag(&mut app, [400.0, 300.0], [600.0, 400.0]);
let work = app.session.active().unwrap().doc.work_path.clone().expect("a work path");
assert_eq!(work.subpaths.len(), 1);
let (_, sharp) = drawn_with(0.0);
assert_rounds(&work.subpaths[0].knots, &sharp, 20.0);
}
#[test]
fn the_radius_is_saved_with_the_tool_options_and_reset_tool_sets_it_back_to_zero() {
let o = crate::state::ToolOptions { polygon_corner_radius: 33.0, ..Default::default() };
let back: crate::state::ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap();
assert_eq!(back.polygon_corner_radius, 33.0, "saved and read back");
assert!(crate::tools::tool_reset::option_keys(Tool::Polygon).contains(&"polygon_corner_radius"), "a Polygon tool preset stores it");
let mut reset = o.clone();
crate::tools::tool_reset::reset_options(&mut reset, Tool::Polygon);
assert_eq!(reset.polygon_corner_radius, 0.0, "Reset Tool");
// Remembered values the field could never hold come back in its range.
for (saved, want) in [(-3.0, 0.0), (1.0e9, 150_000.0), (f32::NAN, 0.0), (40.0, 40.0)] {
let mut o = crate::state::ToolOptions { polygon_corner_radius: saved, ..Default::default() };
crate::tool_memory::sanitize(&mut o);
assert_eq!(o.polygon_corner_radius, want, "{saved}");
}
}
+29 -9
View File
@@ -2,6 +2,7 @@
use craft::behavior::{EditEvent, Mixed};
use craft::draw::stroke::StrokeStyle;
use craft::draw::ui::RADIUS_RANGE;
use craft::draw::ui::shape::{ShapeAppearance, ShapeBar, ShapeChange, ShapePaint, ShapeToolSettings, VectorMode};
use craft::draw::ui::shape_drag::ShapeKind;
use craft::ui::choice::Checkbox;
@@ -157,6 +158,29 @@ 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.
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!("Align Edges").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.
Divider::vertical().show(ui);
let out = crate::option_cells::number(tl!("Radius"), &mut app.ui.tool_options.polygon_corner_radius, RADIUS_RANGE).unit("px").show(ui);
if let Some(alert) = out.out_of_range {
crate::option_cells::range_alert(app, ui, &alert);
}
}
}
/// The title of the alert for a number typed outside its range.
fn range_title(kind: ShapeKind) -> String {
match kind {
@@ -225,15 +249,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
.chips(|which, chip, chip_ui| decorate_chip(chip, which, &mut library, chip_ui))
.show(ui);
let (fill_gradient, stroke_gradient) = (library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke));
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!("Align Edges").to_owned()).enabled(shape_mode).show(ui);
if let Some(next) = on.value().copied() {
app.ui.tool_options.align_edges = next;
}
}
tool_extras(app, ui, tool);
let mut recent: Option<[f32; 3]> = None;
let mut remembered: Vec<Fill> = Vec::new();
@@ -384,3 +400,7 @@ mod rectangle_radius_target_tests;
#[cfg(test)]
#[path = "polygon_sides_alert_tests.rs"]
mod polygon_sides_alert_tests;
#[cfg(test)]
#[path = "polygon_corner_radius_field_tests.rs"]
mod polygon_corner_radius_field_tests;
+1
View File
@@ -289,6 +289,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
corner_radius,
align_edges,
polygon_sides,
polygon_corner_radius,
line_weight
)
}
+3
View File
@@ -220,6 +220,9 @@ mod line_shift_snap_tests;
#[cfg(test)]
mod ellipse_shift_circle_tests;
#[cfg(test)]
mod rectangle_align_edges_tests;
#[cfg(test)]
mod triangle_align_edges_tests;
@@ -156,6 +156,16 @@ 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 {
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!("Align Edges").to_owned()).enabled(shape_mode).show(ui);
if let Some(next) = on.value().copied() {
app.ui.tool_options.align_edges = next;
}
}
}
/// The Pen, Freeform Pen and Curvature Pen bar.
@@ -0,0 +1,146 @@
//! #13346: the Rectangle tool's Align Edges checkbox, at the options bar's right end after the
//! gear. On (the default) a drag's box snaps to whole pixels; off a rectangle keeps the drag's
//! fractional coordinates. It is greyed outside Shape mode, where the box still snaps.
use craft::draw::geometry::ShapeGeometry;
use craft::draw::ui::VectorMode;
use craft::draw::ui::shape_drag::ShapeKind;
use craft::keymap::Mods;
use egui::accesskit::Toggled;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::test_input::harness;
use crate::PhotocraftApp;
use crate::state::{Tool, ToolOptions};
const START: [f64; 2] = [10.3, 10.6];
const END: [f64; 2] = [40.7, 30.2];
const GEAR: &str = "Set additional shape and path options";
/// A 200 × 100 document with the Rectangle tool and its options set by `set`.
fn app(set: impl FnOnce(&mut ToolOptions)) -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.ui.tool = Tool::Rectangle;
set(&mut app.ui.tool_options);
app
}
/// A Rectangle drag the framework tool committed as the box from `from` to `to` with corner radius
/// `radius`: the exact fractions go to `finish_drag` as the tool hands them over.
fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], radius: f64) {
let rect = craft::behavior::kurbo::Rect::new(from[0], from[1], to[0], to[1]);
super::shapes::finish_drag(app, ShapeKind::Rectangle, &ShapeGeometry::Rect { rect, radii: [radius; 4] }, Mods::default());
}
fn layer_count(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().doc.layers.len()
}
/// The active shape layer's live rectangle `[x, y, w, h]`, its kind and its path's `[x0, y0, x1, y1]`.
fn drawn_layer(app: &mut PhotocraftApp) -> ([f64; 4], String, [f64; 4]) {
let st = app.session.active().unwrap();
let id = st.active_layer.unwrap();
let path = match &st.doc.layer(id).unwrap().content {
photocraft_doc::LayerContent::Shape(sh) => sh.path.clone(),
other => panic!("not a shape layer: {other:?}"),
};
let (x0, y0, x1, y1) = path.control_bounds().unwrap();
let info = app.session.execute("shape.info", json!({"layer": id.0})).unwrap();
let live = serde_json::from_value(info["live"]["rect"].clone()).unwrap_or_else(|_| panic!("a live rectangle: {}", info["live"]));
(live, info["live"]["kind"].as_str().unwrap_or_default().to_owned(), [x0, y0, x1, y1])
}
fn assert_close(got: [f64; 4], want: [f64; 4]) {
for (g, w) in got.iter().zip(want) {
assert!((g - w).abs() < 1e-9, "{got:?} vs {want:?}");
}
}
#[test]
fn the_drawn_shape_layer_follows_the_checkbox() {
assert!(ToolOptions::default().align_edges, "on by default");
for (align, live, bounds) in [(true, [10.0, 11.0, 30.0, 20.0], [10.0, 11.0, 40.0, 31.0]), (false, [10.3, 10.6, 30.4, 19.6], [10.3, 10.6, 40.7, 30.2])] {
let mut app = app(|o| o.align_edges = align);
let layers = layer_count(&app);
drag(&mut app, START, END, 0.0);
assert_eq!(layer_count(&app), layers + 1, "one new shape layer");
let (got_live, kind, got_bounds) = drawn_layer(&mut app);
assert_eq!(kind, "rect");
assert_close(got_live, live);
assert_close(got_bounds, bounds);
}
}
#[test]
fn a_rounded_rectangle_follows_the_checkbox_too() {
for (align, want) in [(true, [10.0, 11.0, 30.0, 20.0]), (false, [10.3, 10.6, 30.4, 19.6])] {
let mut app = app(|o| o.align_edges = align);
drag(&mut app, START, END, 4.0);
let (live, _, _) = drawn_layer(&mut app);
assert_close(live, want);
let st = app.session.active().unwrap();
let radii = match &st.doc.layer(st.active_layer.unwrap()).unwrap().content {
photocraft_doc::LayerContent::Shape(sh) => match sh.live {
Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii,
ref other => panic!("a live rectangle, got {other:?}"),
},
_ => panic!("a shape layer"),
};
assert_eq!(radii, [4.0; 4], "the corners stay rounded");
}
}
#[test]
fn a_greyed_checkbox_keeps_snapping_in_path_and_pixels_mode() {
let mut app = app(|o| o.align_edges = false);
for mode in [VectorMode::Path, VectorMode::Pixels] {
app.ui.tool_options.shape_mode = mode;
assert!(super::shapes::snaps_to_pixels(&app, ShapeKind::Rectangle), "{mode:?}");
}
app.ui.tool_options.shape_mode = VectorMode::Path;
drag(&mut app, START, END, 0.0);
let (x0, y0, x1, y1) = app.session.active().unwrap().doc.work_path.as_ref().unwrap().control_bounds().unwrap();
assert_close([x0, y0, x1, y1], [10.0, 11.0, 40.0, 31.0]);
app.ui.tool_options.shape_mode = VectorMode::Shape;
assert!(!super::shapes::snaps_to_pixels(&app, ShapeKind::Rectangle), "Shape mode with Align Edges off keeps fractions");
}
#[test]
fn a_sub_pixel_drag_still_draws_nothing() {
let mut app = app(|o| o.align_edges = false);
for end in [[10.9, 40.0], [40.0, 10.5]] {
let layers = layer_count(&app);
drag(&mut app, [10.0, 10.0], end, 0.0);
assert_eq!(layer_count(&app), layers, "{end:?}");
}
}
#[test]
fn reset_tool_turns_it_back_on() {
let mut app = app(|o| o.align_edges = false);
crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap();
assert!(app.ui.tool_options.align_edges);
}
#[test]
fn options_bar_shows_align_edges_at_its_right_end() {
let mut h = harness(Tool::Rectangle);
// 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("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("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("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("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode");
}
+16 -6
View File
@@ -123,12 +123,12 @@ 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 (#13370) is the Triangle tool's
/// 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. 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.
pub(super) fn snaps_to_pixels(app: &PhotocraftApp, kind: ShapeKind) -> bool {
let o = &app.ui.tool_options;
!(kind == ShapeKind::Triangle && o.shape_mode == super::VectorMode::Shape && !o.align_edges)
!(matches!(kind, ShapeKind::Triangle | ShapeKind::Rectangle) && o.shape_mode == super::VectorMode::Shape && !o.align_edges)
}
/// `geometry` as a drag commits it: boxes on whole pixels, a line aligned to pixel edges
@@ -213,6 +213,16 @@ fn geometry_params(app: &PhotocraftApp, geometry: &ShapeGeometry, kind: ShapeKin
})
}
/// `p` (a drag's `shape.create` geometry of `kind`) with the Polygon tool's own corner radius, which
/// rounds every vertex of the next polygon it drags (#13302). The Create Polygon dialog keeps its own.
fn with_tool_radius(app: &PhotocraftApp, kind: ShapeKind, mut p: Value) -> Value {
let r = app.ui.tool_options.polygon_corner_radius;
if kind == ShapeKind::Polygon && r > 0.0 {
p["cornerRadius"] = json!(r);
}
p
}
/// `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)?;
@@ -289,7 +299,7 @@ pub fn finish_drag(app: &mut PhotocraftApp, kind: ShapeKind, geometry: &ShapeGeo
return;
}
let mut p = match create_params(app, &geometry, kind) {
Ok(p) => p,
Ok(p) => with_tool_radius(app, kind, p),
Err(e) => return report(app, e),
};
p["historyName"] = json!(tool_history_name(kind));
@@ -395,7 +405,7 @@ fn outline_of(app: &PhotocraftApp, kind: ShapeKind, geometry: &ShapeGeometry) ->
let shape = groups.iter().flat_map(|g| &g.items).find(|s| s.name == app.ui.presets_ui.shape())?;
Some(photocraft_engine::presets::shapes::fit(&shape.path, box_of(rect), *keep_proportions))
} else {
photocraft_engine::vector_cmds::shape_path(&geometry_params(app, geometry, kind).ok()?).ok()
photocraft_engine::vector_cmds::shape_path(&with_tool_radius(app, kind, geometry_params(app, geometry, kind).ok()?)).ok()
}
}
@@ -53,7 +53,7 @@ fn align_edges_is_on_by_default_and_saved() {
#[test]
fn other_shape_tools_always_snap() {
for tool in [Tool::Polygon, Tool::EllipseShape, Tool::Rectangle, Tool::Star] {
for tool in [Tool::Polygon, Tool::EllipseShape, Tool::Star] {
let r = rect(|o| o.align_edges = false, tool, START, END).unwrap();
assert!(r.iter().all(|v| v.fract() == 0.0), "{tool:?}: {r:?}");
}
@@ -71,7 +71,7 @@ fn a_greyed_checkbox_keeps_snapping_in_path_mode() {
}
#[test]
fn options_bar_shows_align_edges_for_the_triangle_only() {
fn options_bar_shows_align_edges_for_the_triangle_not_the_ellipse() {
let mut h = harness(Tool::Triangle);
let node = h.get_by_label("Align Edges");
assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode");
@@ -85,6 +85,6 @@ fn options_bar_shows_align_edges_for_the_triangle_only() {
h.run_steps(4);
assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode");
let h = harness(Tool::Rectangle);
let h = harness(Tool::EllipseShape);
assert!(h.query_by_label("Align Edges").is_none());
}