Merge origin/main into feat/smart-sharpen-canvas-preview (#9981)

Conflict only in the docs/ui-parity.md status line: kept both entries.

Co-Authored-By: ljkx <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
committed 2026-11-08 01:22:40 +01:00
commit e812bfcbae
175 files changed
+13916 -494

No files matched your search

+1
View File
@@ -38,6 +38,7 @@ next to them.
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/th.tsv` | Thai UI translations | @Thanawatttt and PhotoCraft contributors, with opencode (DeepSeek) as an AI contributor | Machine-assisted first draft from PhotoCraft's English labels, reviewed for UI terminology | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ta.tsv` | Tamil UI translations | @newsbaba24x7 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `crates/ui-egui/src/i18n/ka.tsv` | Georgian UI translations | @devius with Claude Code, AI-assisted | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
+88
View File
@@ -1117,6 +1117,50 @@ pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp)
puppet_warp_with_mask(src, bounds, w, interp, None).map(|(out, _)| out)
}
/// How many times over a stored mesh's triangles may cover its deformed box, counting each
/// triangle's bounding box: a real mesh tiles the box about twice (a fold adds a layer), a
/// crafted one stacks large triangles to multiply the drawing work.
const MAX_MESH_COVERAGE: f64 = 16.0;
/// Draws `src` (content inside `bounds`) through a mesh solved elsewhere, as a Photoshop file
/// stores its Puppet Warp: `mesh.verts` move to `deformed`, the triangles drawn in their stored
/// order. `None` for a malformed mesh (sizes that don't match, an index out of range, a vertex
/// that isn't finite), one whose deformed box spans more than [`MAX_WARP_PIXELS`] or whose
/// triangles cover that box more than [`MAX_MESH_COVERAGE`] times.
pub fn warp_with_mesh(src: &Surface, bounds: Rect, mesh: &PuppetMesh, deformed: &[[f64; 2]], interp: Interp) -> Option<Surface> {
let n = mesh.verts.len();
if mesh.tris.is_empty() || deformed.len() != n || mesh.tris.iter().flatten().any(|&i| i >= n) {
return None;
}
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
for p in mesh.verts.iter().chain(deformed) {
if !(p[0].is_finite() && p[1].is_finite()) {
return None;
}
}
for p in deformed {
(x0, y0, x1, y1) = (x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1]));
}
let area = (x1 - x0 + 1.0) * (y1 - y0 + 1.0);
if area > MAX_WARP_PIXELS {
return None;
}
let covered: f64 = mesh
.tris
.iter()
.map(|t| {
let (xs, ys) = (t.map(|i| deformed[i][0]), t.map(|i| deformed[i][1]));
let span = |v: [f64; 3]| v.iter().fold(f64::MIN, |m, &a| m.max(a)) - v.iter().fold(f64::MAX, |m, &a| m.min(a)) + 1.0;
span(xs) * span(ys)
})
.sum();
if covered > MAX_MESH_COVERAGE * area {
return None;
}
let order: Vec<usize> = (0..mesh.tris.len()).collect();
Some(render(src, bounds, mesh, deformed, &order, interp))
}
/// [`puppet_warp`], also moving `mask` (a one-channel layer mask linked to `src`) with the same
/// mesh, as Photoshop moves a linked mask with its layer (#4910). The mask is `None` in the
/// result when none was given.
@@ -1267,6 +1311,50 @@ mod tests {
assert!(!in_mesh(&m, [40.0, 50.0]) && !in_mesh(&m, [60.0, 20.0]));
}
#[test]
fn a_stored_mesh_is_drawn_as_it_is() {
// A Photoshop file's Puppet Warp keeps its solved mesh: two triangles over a 40 × 40 box,
// sheared and moved. A dot lands where the mesh's affine map puts it; pixels outside the
// mesh are dropped.
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true));
for y in 0..48 {
for x in 0..48 {
let dot = (f64::from(x) + 0.5 - 12.0).hypot(f64::from(y) + 0.5 - 20.0) <= 2.0;
s.write_pixel(x, y, &if dot { [1.0, 1.0, 1.0, 1.0] } else { [0.0, 0.0, 0.0, 1.0] });
}
}
let mesh = PuppetMesh { verts: vec![[0.0, 0.0], [40.0, 0.0], [40.0, 40.0], [0.0, 40.0]], tris: vec![[0, 1, 2], [0, 2, 3]], spacing: 20.0 };
let map = |p: [f64; 2]| [p[0] + 0.25 * p[1] + 3.0, p[1] + 5.0];
let deformed: Vec<[f64; 2]> = mesh.verts.iter().map(|v| map(*v)).collect();
let b = s.content_bounds();
let out = warp_with_mesh(&s, b, &mesh, &deformed, Interp::Bilinear).expect("a valid mesh draws");
let ob = out.content_bounds();
let (mut sw, mut sx, mut sy) = (0.0, 0.0, 0.0);
for (i, px) in out.read_region(ob).as_chunks::<4>().0.iter().enumerate() {
let w = f64::from(px[0] * px[3]);
let (x, y) = (f64::from(ob.x0) + (i % ob.width() as usize) as f64 + 0.5, f64::from(ob.y0) + (i / ob.width() as usize) as f64 + 0.5);
(sw, sx, sy) = (sw + w, sx + w * x, sy + w * y);
}
let want = map([12.0, 20.0]);
assert!((sx / sw - want[0]).abs() < 0.05 && (sy / sw - want[1]).abs() < 0.05, "dot at {:?}, want {want:?}", [sx / sw, sy / sw]);
// The source column x = 44 is outside the mesh: nothing lands right of the sheared box.
assert!(ob.x1 <= 54 && ob.y1 <= 45, "{ob:?}");
// Malformed meshes are refused rather than drawn.
assert!(warp_with_mesh(&s, b, &mesh, &deformed[..3], Interp::Bilinear).is_none());
let bad = PuppetMesh { tris: vec![[0, 1, 4]], ..mesh.clone() };
assert!(warp_with_mesh(&s, b, &bad, &deformed, Interp::Bilinear).is_none());
let mut far = deformed.clone();
far[2] = [f64::NAN, 0.0];
assert!(warp_with_mesh(&s, b, &mesh, &far, Interp::Bilinear).is_none());
far[2] = [1.0e6, 1.0e6];
assert!(warp_with_mesh(&s, b, &mesh, &far, Interp::Bilinear).is_none());
// The same two triangles stacked 40 times: far more drawing than the box needs.
let stacked = PuppetMesh { tris: mesh.tris.repeat(40), ..mesh.clone() };
assert!(warp_with_mesh(&s, b, &stacked, &deformed, Interp::Bilinear).is_none());
let none = PuppetMesh { tris: Vec::new(), ..mesh };
assert!(warp_with_mesh(&s, b, &none, &deformed, Interp::Bilinear).is_none());
}
#[test]
fn no_pins_or_unmoved_pins_are_identity() {
for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
+2
View File
@@ -732,7 +732,9 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool {
| "path.info"
| "path.addToSelection"
| "path.subtractFromSelection"
| "path.intersectWithSelection"
| "path.set"
| "actions.insertPath"
| "path.transform"
| "path.moveAnchors"
| "path.moveHandle"
+6
View File
@@ -564,6 +564,12 @@ impl SmartObject {
perspective: None,
}
}
/// Where the placed source lands (transform, perspective and warp), as JSON: the placement a
/// smart filter stored in document pixels (an imported Puppet Warp mesh) was made for.
pub fn placement_json(&self) -> serde_json::Value {
serde_json::json!({"transform": self.transform.m, "perspective": self.perspective, "warp": self.warp})
}
}
#[derive(Clone, Debug, PartialEq)]
+89 -40
View File
@@ -94,6 +94,9 @@ pub const MAX_PLAYBACK_STEPS: u64 = 100_000;
#[serde(default)]
pub struct ActionState {
pub list: Vec<Action>,
/// Painting-tool strokes are recorded only when the user enables them for this session.
#[serde(skip)]
pub record_tools: bool,
/// Journal length when recording started, and the action index being recorded into.
#[serde(skip)]
pub recording: Option<(usize, usize)>,
@@ -165,7 +168,7 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result<Value> {
}
}
}
if id.starts_with("filter.gallery.")
if (id.starts_with("filter.gallery.") || id == crate::atn_cmds::MENU_ITEM)
&& let Some(object) = p.as_object_mut()
{
object.remove(crate::atn_cmds::RECORDED_EVENT);
@@ -276,6 +279,63 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> {
Ok((action, from))
}
/// Visit calls in the current namespace, leaving embedded inline Batch scopes untouched.
fn visit_calls(steps: &mut [(String, Value)], f: &mut impl FnMut(&str, &mut Value, bool)) {
let mut pending: Vec<_> = steps.iter_mut().rev().map(|(id, params)| (id.clone(), params)).collect();
while let Some((id, params)) = pending.pop() {
let scoped = id == "file.automate.batch" && params.get("calledActions").is_some_and(|v| !v.is_null());
if id == "file.automate.batch" {
let inline = if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") };
if let Some(key) = inline {
if scoped {
continue;
}
// A present invalid `steps` still wins over `action`, just as at runtime.
let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue };
for step in steps.iter_mut().rev() {
let call = match step {
Value::Array(a) => {
let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue };
a.get_mut(1).map(|params| (id, params))
}
Value::Object(o) => {
let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { continue };
o.get_mut("params").map(|params| (id, params))
}
// String steps and omitted params use `{}`, with no action target.
_ => None,
};
if let Some(call) = call {
pending.push(call);
}
}
continue;
}
}
f(&id, params, scoped);
}
}
/// Shift numeric selectors in the session list, including calls in unscoped inline Batch steps.
pub(crate) fn shift_action_calls(list: &mut [Action], at: usize, count: usize) {
for action in list {
visit_calls(&mut action.steps, &mut |id, params, _| {
if !matches!(id, "actions.play" | "file.automate.batch") {
return;
}
let Some(value) = params.get("action") else { return };
let Some(index) = num(value).and_then(|i| usize::try_from(i).ok()) else { return };
if index >= at {
params["action"] = if let Some(fractional) = value.as_f64().filter(|_| value.is_f64()) {
json!(fractional + count as f64)
} else {
json!(index.saturating_add(count))
};
}
});
}
}
/// Capture transitive Play Action, Conditional and Batch dependencies for a standalone droplet
/// (#2794, #6804). Ordinary references become names; normalized copies keep source-list order.
/// A named Batch with its own action list selects an untouched source copy at an exported index,
@@ -286,42 +346,6 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
fn target(list: &[Action], params: &Value, id: &str) -> Result<usize> {
if id == "file.automate.batch" { crate::file_cmds::batch_action(list, params) } else { resolve(list, params, id) }
}
/// Visit calls in the current namespace, leaving embedded inline Batch scopes untouched.
fn visit_calls(steps: &mut [(String, Value)], f: &mut impl FnMut(&str, &mut Value, bool)) {
let mut pending: Vec<_> = steps.iter_mut().rev().map(|(id, params)| (id.clone(), params)).collect();
while let Some((id, params)) = pending.pop() {
let scoped = id == "file.automate.batch" && params.get("calledActions").is_some_and(|v| !v.is_null());
if id == "file.automate.batch" {
let inline = if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") };
if let Some(key) = inline {
if scoped {
continue;
}
// A present invalid `steps` still wins over `action`, just as at runtime.
let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue };
for step in steps.iter_mut().rev() {
let call = match step {
Value::Array(a) => {
let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue };
a.get_mut(1).map(|params| (id, params))
}
Value::Object(o) => {
let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { continue };
o.get_mut("params").map(|params| (id, params))
}
// String steps and omitted params use `{}`, with no action target.
_ => None,
};
if let Some(call) = call {
pending.push(call);
}
}
continue;
}
}
f(&id, params, scoped);
}
}
/// Capture ordinary calls transitively, but retain an untouched source for scoped named Batch.
fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut VecDeque<(usize, usize)>, scoped: &mut BTreeSet<usize>) {
if depth > 16 {
@@ -482,7 +506,7 @@ fn from_step(p: &Value, len: usize) -> Result<usize> {
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
let actions: Vec<Value> = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect();
let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone()));
Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording}))
Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.actions.record_tools}))
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
@@ -545,7 +569,32 @@ const RECORDED_WITH_DIALOG: &[&str] = &["edit.checkSpelling"];
/// Replayable journal entries not yet committed to this action while recording.
pub fn pending_steps(s: &Session, action: usize) -> impl Iterator<Item = &(String, Value)> {
let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from);
s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p))
s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.actions.record_tools || !tool_stroke(id)))
}
/// The point-based painting tools committed by the canvas; fills and gradients remain commands.
pub(crate) fn tool_stroke(id: &str) -> bool {
matches!(
id,
"paint.stroke"
| "paint.pencil"
| "paint.mixerBrush"
| "paint.colorReplacement"
| "paint.blur"
| "paint.sharpen"
| "paint.smudge"
| "paint.dodge"
| "paint.burn"
| "paint.sponge"
| "paint.cloneStamp"
| "paint.healingBrush"
| "paint.historyBrush"
| "paint.artHistoryBrush"
| "paint.patternStamp"
| "paint.backgroundEraser"
| "paint.spotHealing"
| "paint.remove"
)
}
pub(crate) fn flush_recording(s: &mut Session) -> Result<()> {
@@ -1094,7 +1143,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "List Actions",
menu: &[],
shortcut: None,
params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null}",
params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null, toolRecording:bool}",
enabled: always,
run: list,
journal: false,
+185 -6
View File
@@ -13,6 +13,11 @@ use crate::actions_cmds::{flush_recording, not_playing, pending_steps, resolve};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
mod insert_path;
mod record_again;
pub use insert_path::selected_path as selected_recording_path;
pub use record_again::{RecordAgainTarget, target as record_again_target};
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
@@ -21,6 +26,35 @@ fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
/// Flush under the old mode so changing the toggle never retroactively records or loses a stroke.
fn allow_tool_recording(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.allowToolRecording";
not_playing(s, cmd)?;
let enabled = match p.get("enabled") {
None | Some(Value::Null) => !s.actions.record_tools,
Some(Value::Bool(enabled)) => *enabled,
Some(_) => return Err(bad(cmd, "`enabled` must be true or false")),
};
if enabled != s.actions.record_tools {
if s.actions.recording.is_some() && s.tool_stroke_job_running() {
return Err(bad(cmd, "wait for the current tool stroke before changing recording"));
}
flush_recording(s)?;
s.actions.record_tools = enabled;
}
Ok(json!({"enabled": enabled}))
}
/// Insert a menu event with absent settings, reusing the ordinary validated step insertion.
fn insert_menu_item(s: &mut Session, p: &Value) -> Result<Value> {
if p.as_object().is_some_and(|o| o.keys().any(|k| !matches!(k.as_str(), "action" | "at" | "id" | "eventKind"))) {
return Err(bad("actions.insertMenuItem", "menu items accept no recorded settings"));
}
let params = json!({"id":p.get("id"),"eventKind":p.get("eventKind").cloned().unwrap_or(json!("name"))});
crate::atn_cmds::menu_item_command(&params)?;
s.execute("actions.insert", json!({"action":p.get("action"),"at":p.get("at"),"id":crate::atn_cmds::MENU_ITEM,"params":params}))
}
fn index(p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
@@ -66,18 +100,113 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
let action = &mut s.actions.list[idx];
action.steps.insert(at, (id.clone(), params));
action.remap_steps(|i| Some(if i >= at { i + 1 } else { i }));
// An inserted Stop has its dialog toggle on, so it shows its message in the app.
if id == crate::atn_cmds::STOP_MESSAGE {
action.dialogs.insert(at);
let is_stop = id == crate::atn_cmds::STOP_MESSAGE;
let result = insert_step(s, idx, at, (id, params));
// A newly inserted Stop shows its message in the app. Duplicates keep their own flags.
if is_stop {
s.actions.list[idx].dialogs.insert(at);
}
Ok(result)
}
/// Insert an already validated step without normalizing a copied step's payload.
fn insert_step(s: &mut Session, idx: usize, at: usize, step: (String, Value)) -> Value {
let action = &mut s.actions.list[idx];
let id = step.0.clone();
action.steps.insert(at, step);
action.remap_steps(|i| Some(if i >= at { i + 1 } else { i }));
let result = json!({"action": action.name, "step": at, "id": id, "steps": action.steps.len()});
s.actions.touch();
result
}
/// Duplicate a step or action below its source, preserving settings and per-step flags.
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.duplicate";
not_playing(s, cmd)?;
if let Some(set) = p.get("set") {
if p.get("action").is_some() || p.get("step").is_some() {
return Err(bad(cmd, "select a set or an action step, not both"));
}
return duplicate_set(s, set.as_str().ok_or_else(|| bad(cmd, "set must be a name"))?);
}
let idx = resolve(&s.actions.list, p, cmd)?;
if let Some(step) = index(p, "step", cmd)? {
let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count());
if step >= len {
return Err(bad(cmd, "step is out of range"));
}
if s.actions.recording.is_some_and(|(_, i)| i == idx) {
flush_recording(s)?;
}
let action = &s.actions.list[idx];
let copied = action.steps.get(step).cloned().ok_or_else(|| bad(cmd, "step is out of range"))?;
let (disabled, dialog) = (action.disabled.contains(&step), action.dialogs.contains(&step));
let at = step + 1;
let mut result = insert_step(s, idx, at, copied);
let action = &mut s.actions.list[idx];
if disabled {
action.disabled.insert(at);
}
if dialog {
action.dialogs.insert(at);
}
result["index"] = json!(idx);
return Ok(result);
}
if s.actions.recording.is_some() {
return Err(bad(cmd, "stop recording before duplicating an action"));
}
let mut copied = s.actions.list[idx].clone();
let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone()));
copied.name = names.claim(&format!("{} copy", copied.name));
let at = idx + 1;
let result = json!({"action": copied.name, "index": at, "steps": copied.steps.len()});
s.actions.list.insert(at, copied);
crate::actions_cmds::shift_action_calls(&mut s.actions.list, at, 1);
s.actions.touch();
Ok(result)
}
/// Copy the named group represented by main, including a session-only empty New Set.
fn duplicate_set(s: &mut Session, source: &str) -> Result<Value> {
let cmd = "actions.duplicate";
if s.actions.recording.is_some() {
return Err(bad(cmd, "stop recording before duplicating a set"));
}
let sets = set_names(s);
if !sets.iter().any(|name| name == source) {
return Err(bad(cmd, "the selected set no longer exists"));
}
let name = crate::atn_cmds::UniqueNames::new(sets).claim(&format!("{source} copy"));
if let Some(first) = s.actions.list.iter().position(|action| action.set.as_deref() == Some(source)) {
let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|action| action.name.clone()));
let copies: Vec<_> = s
.actions
.list
.iter()
.filter(|action| action.set.as_deref() == Some(source))
.cloned()
.map(|mut action| {
action.name = names.claim(&format!("{} copy", action.name));
action.set = Some(name.clone());
action
})
.collect();
// Classic groups rows by name even when a set's actions are interleaved.
let at = first + s.actions.list[first..].iter().take_while(|action| action.set.as_deref() == Some(source)).count();
let count = copies.len();
s.actions.list.splice(at..at, copies);
crate::actions_cmds::shift_action_calls(&mut s.actions.list, at, count);
s.actions.touch();
return Ok(json!({"set": name, "index": at, "actions": count}));
}
let at = s.actions.sets.iter().position(|set| set == source).ok_or_else(|| bad(cmd, "the selected set no longer exists"))? + 1;
s.actions.sets.insert(at, name.clone());
s.actions.touch();
Ok(json!({"set": name, "actions": 0}))
}
/// The panel's dialog toggle column. With `step`, switch one step's dialog on or off; without
/// it, every step (all on unless all already are, like clicking the action's own toggle).
fn dialog(s: &mut Session, p: &Value) -> Result<Value> {
@@ -277,6 +406,56 @@ fn conditional(s: &mut Session, p: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: "actions.insertMenuItem",
label: "Insert Menu Item…",
menu: &[],
shortcut: None,
params: r##"{"action":name|index,"id":menu command,"at":index?,"eventKind":"name"|"code"="name"} → {action,step,id,steps}. Records an unambiguous supported menu event without settings. Image Size and mapped filter menu events are supported. Desktop playback opens the existing editor when settings are needed; no-settings items run immediately."##,
enabled: always,
run: insert_menu_item,
journal: false,
},
CommandSpec {
id: "actions.insertPath",
label: "Insert Path",
menu: &[],
shortcut: None,
params: r##"{"action":name|index,"name":"work"|"layer"|saved path name,"at":index?} → {action,step,id,steps}. Snapshot exactly the selected path as a path.set work-path step, preserving cubic handles and path options. No fallback from a missing Work Path to a layer path. The measured Work Path ATN descriptor supports absolute coordinates, cubic handles, even-odd subpaths and Add/Subtract/XOR. Paths outside that measured form still play natively and are reported as unsupported by ATN export."##,
enabled: always,
run: insert_path::run,
journal: false,
},
CommandSpec {
id: "actions.allowToolRecording",
label: "Allow Tool Recording",
menu: &[],
shortcut: None,
params: r##"{"enabled":bool?=toggle} → {enabled:bool}. Opt in to recording painting-tool strokes (off initially). Existing pending steps are committed under the previous mode. Painting, history and the journal are unchanged. actions.list reports toolRecording."##,
enabled: always,
run: allow_tool_recording,
journal: false,
},
CommandSpec {
id: "actions.recordAgain",
label: "Record Again",
menu: &[],
shortcut: None,
params: r##"{"action":name|index,"step":index,"params":{new settings},"revision":u64?} → {action,step,id,result}. Replays the selected command and stores its new settings only after success, preserving its enabled/dialog flags. The panel opens the command's editor at the recorded settings. Stop recording or playback first; revision optionally rejects stale library state."##,
enabled: always,
run: record_again::run,
journal: false,
},
CommandSpec {
id: "actions.duplicate",
label: "Duplicate Action",
menu: &[],
shortcut: None,
params: r##"{"action":name|index,"step":index?} or {"set":name} → {action?,index?,step?,steps?,set?,actions?}. Copy an action, step or named set below the source. Copies retain settings and flags, and leave shortcuts with the originals."##,
enabled: always,
run: duplicate,
journal: false,
},
CommandSpec {
id: "actions.insert",
label: "Insert Step",
@@ -0,0 +1,26 @@
//! Capture full native geometry without substituting another path for a stale selection.
use super::{Result, Session, Value, bad, json};
use photocraft_doc::{LayerContent, Path};
/// Borrow exactly the path the panel selected, without Work Path's ordinary layer fallback.
pub fn selected_path<'a>(s: &'a Session, name: &str) -> Result<&'a Path> {
let st = s.active().ok_or(crate::EngineError::NoDocument)?;
let path = match name {
"work" => st.doc.work_path.as_ref(),
"layer" => st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| match &l.content {
LayerContent::Shape(shape) => Some(&shape.path),
_ => l.vector_mask.as_ref().map(|v| &v.path),
}),
name => st.doc.paths.iter().find(|p| p.name == name).map(|p| &p.path),
};
path.ok_or_else(|| bad("actions.insertPath", "the selected path no longer exists"))
}
/// The native path step is also the source for a future independently verified ATN wire mapping.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("actions.insertPath", "select a path"))?;
let path = selected_path(s, name)?;
photocraft_vector::flatten::validate_path(path).map_err(|e| bad("actions.insertPath", e))?;
let path = crate::vector_cmds::path_json(path);
s.execute("actions.insert", json!({"action":p.get("action"),"at":p.get("at"),"id":"path.set","params":{"name":"work","path":path}}))
}
@@ -0,0 +1,55 @@
//! Record Again executes the selected command before replacing its stored settings.
use super::{Result, Session, Value, bad, index, json, not_playing, resolve};
const COMMAND: &str = "actions.recordAgain";
/// A validated selection shared by the engine and the panel's seeded editor.
pub struct RecordAgainTarget {
pub action: usize,
pub step: usize,
pub command: String,
pub params: Value,
}
/// Resolve only executable steps, without flushing recording or editing the library.
pub fn target(s: &Session, p: &Value) -> Result<RecordAgainTarget> {
not_playing(s, COMMAND)?;
if s.actions.recording.is_some() {
return Err(bad(COMMAND, "stop recording before recording a step again"));
}
if let Some(revision) = p.get("revision") {
let revision = revision.as_u64().ok_or_else(|| bad(COMMAND, "`revision` must be an unsigned integer"))?;
if revision != s.actions.rev {
return Err(bad(COMMAND, "the actions changed; select the step again"));
}
}
let action = resolve(&s.actions.list, p, COMMAND)?;
let step = index(p, "step", COMMAND)?.ok_or_else(|| bad(COMMAND, "select a step"))?;
let (id, params) = s.actions.list.get(action).and_then(|a| a.steps.get(step)).ok_or_else(|| bad(COMMAND, "step is out of range"))?;
let (command, params) =
if id == crate::atn_cmds::MENU_ITEM { (crate::atn_cmds::menu_item_command(params)?.to_string(), json!({})) } else { (id.clone(), params.clone()) };
if command.starts_with("actions.") || !crate::commands::find(&command).is_some_and(|c| c.journal) {
return Err(bad(COMMAND, "the selected step has no editable engine command"));
}
Ok(RecordAgainTarget { action, step, command, params })
}
/// Keep the original definition on invalid settings, denied execution or changed ownership.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let selected = target(s, p)?;
let params = p.get("params").filter(|p| p.is_object()).cloned().ok_or_else(|| bad(COMMAND, "supply the step's new settings in `params`"))?;
let original = s.actions.list.get(selected.action).and_then(|a| a.steps.get(selected.step)).cloned().ok_or_else(|| bad(COMMAND, "step is out of range"))?;
let revision = s.actions.rev;
// Resolve portable recorded targets for execution; keep their portable form in the step.
let resolved = crate::actions_cmds::playback_params(s, &selected.command, &params)?;
let result = s.execute(&selected.command, resolved)?;
if s.actions.rev != revision || s.actions.list.get(selected.action).and_then(|a| a.steps.get(selected.step)) != Some(&original) {
return Err(bad(COMMAND, "the action changed during execution; its step was not overwritten"));
}
let action = s.actions.list.get_mut(selected.action).ok_or_else(|| bad(COMMAND, "the action no longer exists"))?;
let step = action.steps.get_mut(selected.step).ok_or_else(|| bad(COMMAND, "the step no longer exists"))?;
*step = (selected.command.clone(), params);
let name = action.name.clone();
s.actions.touch();
Ok(json!({"action": name, "step": selected.step, "id": selected.command, "result": result}))
}
+18
View File
@@ -32,6 +32,7 @@ mod descriptors;
mod events;
mod fields;
mod files;
mod menu_item;
mod steps_artboard;
mod steps_batch;
@@ -41,6 +42,7 @@ mod steps_content_aware;
mod steps_direct_adjustments;
mod steps_distort;
mod steps_doc;
mod steps_droplet;
mod steps_gallery;
mod steps_gradient;
mod steps_image;
@@ -48,6 +50,7 @@ mod steps_layer;
mod steps_layer_style;
mod steps_lookup;
mod steps_make;
mod steps_path;
mod steps_perspective_warp;
mod steps_type_path;
@@ -62,6 +65,7 @@ mod tables;
#[cfg(test)]
use adjustments::{levels_from, selective_from};
pub(crate) use convert::UniqueNames;
pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, import_with_encoding, parse_function_key};
#[cfg(test)]
use convert::{MAX_NAME_CHARS, export_item, normalise};
@@ -76,6 +80,7 @@ use events::{EVENTS, event_and_descriptor, event_for};
#[cfg(test)]
use fields::Mapped;
use files::{load, save};
pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings};
#[cfg(test)]
use steps_doc::crop_from;
pub(crate) use steps_gallery::RECORDED_EVENT;
@@ -150,6 +155,16 @@ pub fn specs() -> Vec<CommandSpec> {
run: stop_message,
journal: true,
},
CommandSpec {
id: MENU_ITEM,
label: "Menu Item",
menu: &[],
shortcut: None,
params: r##"{"id":menu command,"eventKind":"name"|"code"="name"} (a descriptor-free Image Size or unambiguous mapped filter menu event; desktop playback asks for settings when needed, headless playback only runs stateless menu items)"##,
enabled: always,
run: menu_item::run,
journal: true,
},
CommandSpec {
id: PHOTOSHOP_STEP,
label: "Photoshop Step",
@@ -177,3 +192,6 @@ mod selection_tests;
#[cfg(test)]
mod render_tests;
#[cfg(test)]
mod recorded_tools_tests;
+13 -8
View File
@@ -69,10 +69,12 @@ fn convert_action(file: &AtnFile, a: &AtnAction, set: &str, unsupported: &mut Ve
let mut action = Action::new(name.clone(), Vec::new());
action.set = Some(clip_name(set));
for (i, item) in a.items.iter().enumerate() {
let mapped = match (event_for(&item.event), &item.descriptor) {
(Some(e), Some(d)) => (e.from)(d),
(Some(e), None) => (e.from)(&Descriptor::default()),
(None, _) => Mapped::Unsupported { harmless: false },
let menu = item.descriptor.is_none().then(|| super::menu_item::from_event(&item.event)).flatten();
let mapped = match (menu, event_for(&item.event), &item.descriptor) {
(Some(params), _, _) => Mapped::Steps(vec![(super::MENU_ITEM.into(), params)]),
(_, Some(e), Some(d)) => (e.from)(d),
(_, Some(e), None) => (e.from)(&Descriptor::default()),
_ => Mapped::Unsupported { harmless: false },
};
let (new_steps, enabled) = match mapped {
Mapped::Steps(mut s) => {
@@ -136,6 +138,9 @@ pub struct Skipped {
}
pub(super) fn export_item(id: &str, params: &Value, set: &str) -> Option<AtnItem> {
if id == super::MENU_ITEM {
return super::menu_item::export(params);
}
if id == PHOTOSHOP_STEP {
let event = jstr(params, "event")?;
let event = match params.get("eventKind") {
@@ -166,7 +171,7 @@ pub(super) fn export_item(id: &str, params: &Value, set: &str) -> Option<AtnItem
{
return Some(AtnItem { event, dictionary: name, descriptor: Some(descriptor), ..Default::default() });
}
let event = if e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) };
let event = if id == "path.set" || e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) };
let omit_descriptor = super::steps_stack::without_descriptor(id, &params) || super::steps_video::omitted(id, &params);
let descriptor = (!omit_descriptor).then_some(descriptor);
Some(AtnItem { event, dictionary: e.label.as_bytes().to_vec(), descriptor, ..Default::default() })
@@ -268,18 +273,18 @@ pub fn export(
/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the
/// taken list per candidate is cubic when an action file repeats one base name many times, so
/// membership uses a set and the next suffix to try is cached per base name.
pub(super) struct UniqueNames {
pub(crate) struct UniqueNames {
taken: std::collections::HashSet<String>,
next_suffix: std::collections::HashMap<String, u32>,
}
impl UniqueNames {
pub(super) fn new<I: IntoIterator<Item = String>>(existing: I) -> Self {
pub(crate) fn new<I: IntoIterator<Item = String>>(existing: I) -> Self {
UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() }
}
/// Reserves and returns a unique name derived from `name`, recording it as taken.
pub(super) fn claim(&mut self, name: &str) -> String {
pub(crate) fn claim(&mut self, name: &str) -> String {
if self.taken.insert(name.to_string()) {
return name.to_string();
}
+10
View File
@@ -910,6 +910,7 @@ pub(super) const EVENTS: &[Event] = &[
"layer.new.layerFromBackground",
"layer.layerStyle.blendingOptions",
"layer.smartFilter.blendingOptions",
"path.set",
],
from: set_from,
to: set_to,
@@ -1199,6 +1200,15 @@ pub(super) const EVENTS: &[Event] = &[
from: super::steps_batch::batch_from,
to: super::steps_batch::batch_to,
},
// Create Droplet (#10710): Photoshop has no string ID for it.
Event {
code: "CrtD",
name: "CrtD",
label: "Create Droplet",
ids: &["file.automate.createDroplet"],
from: super::steps_droplet::droplet_from,
to: super::steps_droplet::droplet_to,
},
Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to },
Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to },
];
+8 -7
View File
@@ -51,21 +51,22 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
names.push(name);
added.push(a);
}
// Play, Conditional and Batch steps call actions by name: follow the renames in the actions just
// loaded, each target looked up once by the name the file gave it.
// Play, Conditional, Batch and Create Droplet steps call actions by name: follow the renames in
// the actions just loaded, each target looked up once by the name the file gave it.
for a in &mut added {
for (id, params) in &mut a.steps {
// A qualified Batch reference belongs to the file's original set, not to a
// foreign set which happens to have the destination override's name.
if id == "file.automate.batch" && params.get("set").and_then(Value::as_str) == Some(original_set.as_str()) {
// A qualified Batch or Create Droplet reference belongs to the file's original set, not
// to a foreign set which happens to have the destination override's name.
let by_set = matches!(id.as_str(), "file.automate.batch" | "file.automate.createDroplet");
if by_set && params.get("set").and_then(Value::as_str) == Some(original_set.as_str()) {
params["set"] = json!(imp.set);
} else if id == "file.automate.batch" && params.get("set").is_some_and(|set| !set.is_null()) {
} else if by_set && params.get("set").is_some_and(|set| !set.is_null()) {
continue;
}
let keys: &[&str] = match id.as_str() {
"actions.play" => &["action"],
"actions.conditional" => &["then", "else"],
"file.automate.batch" => &["action"],
"file.automate.batch" | "file.automate.createDroplet" => &["action"],
_ => &[],
};
for key in keys {
@@ -0,0 +1,90 @@
//! Descriptor-free menu intent is distinct from a command with recorded settings.
//! Image Size and unambiguous mapped filter events keep absent settings distinct from empty ones.
use super::events::{EVENTS, Event, event_for};
use super::{AtnEvent, AtnItem, EngineError, Result, Session, Value, bad, json};
/// Find a supported, unambiguous event for a menu step with no settings.
fn menu_event(id: &str) -> Option<&'static Event> {
// Camera Raw's ATN mapping requires a verified settings descriptor (#8714).
if id == crate::lens_cmds::RAW || (id != "image.imageSize" && !id.starts_with("filter.")) {
return None;
}
EVENTS.iter().find(|e| {
e.ids == [id]
&& !e.name.is_empty()
&& event_for(&AtnEvent::name(e.name)).is_some_and(|mapped| mapped.code == e.code && mapped.ids == e.ids)
&& crate::commands::find(id).is_some()
})
}
/// Menu choices use existing event mappings rather than inventing event names from command ids.
pub fn menu_item_commands() -> Vec<&'static str> {
let mut seen = std::collections::HashSet::new();
EVENTS.iter().flat_map(|e| e.ids.iter().copied()).filter(|id| menu_event(id).is_some() && seen.insert(*id)).collect()
}
/// Stateless filter menu items execute immediately; settings-bearing ones require the editor.
pub fn menu_item_needs_settings(id: &str) -> bool {
crate::commands::find(id).is_none_or(|c| !c.params.trim_start().starts_with("{}"))
}
/// An Insert Menu Item step with no recorded command descriptor.
pub const MENU_ITEM: &str = "actions.menuItem";
/// Validate menu identity before the shell gates and opens its actual command.
pub fn menu_item_command(p: &Value) -> Result<&str> {
let object = p.as_object().ok_or_else(|| bad(MENU_ITEM, "parameters must be an object"))?;
if object.keys().any(|key| !matches!(key.as_str(), "id" | "eventKind" | super::RECORDED_EVENT)) {
return Err(bad(MENU_ITEM, "only `id` and `eventKind` are supported; a menu item has no recorded settings"));
}
if object.get("eventKind").is_some_and(|kind| !matches!(kind.as_str(), Some("code" | "name"))) {
return Err(bad(MENU_ITEM, "`eventKind` must be name or code"));
}
let id = p.get("id").and_then(Value::as_str).ok_or_else(|| bad(MENU_ITEM, "select a menu command"))?;
let event = menu_event(id).ok_or_else(|| bad(MENU_ITEM, "the command has no unambiguous supported menu event"))?;
if p.get("eventKind").and_then(Value::as_str) == Some("code") {
let code = event.code.as_bytes().try_into().ok().map(AtnEvent::Code);
if !code.as_ref().and_then(event_for).is_some_and(|mapped| mapped.name == event.name && mapped.ids == event.ids) {
return Err(bad(MENU_ITEM, "this menu event has no unambiguous four-character code"));
}
}
Ok(id)
}
/// Preserve the exact code/name kind only for the supported descriptor-free event.
pub(super) fn from_event(event: &AtnEvent) -> Option<Value> {
let mapped = event_for(event)?;
let id = *mapped.ids.first()?;
let canonical = menu_event(id)?;
if canonical.name != mapped.name || canonical.code != mapped.code {
return None;
}
let kind = match event {
AtnEvent::Code(code) if mapped.code.as_bytes() == code => "code",
AtnEvent::Name(name) if mapped.name.as_bytes() == name => "name",
_ => return None,
};
Some(json!({"id":id,"eventKind":kind}))
}
/// Write absent settings as `None`, never as an empty or current-target descriptor.
pub(super) fn export(p: &Value) -> Option<AtnItem> {
let mapped = menu_event(menu_item_command(p).ok()?)?;
let event = if p.get("eventKind").and_then(Value::as_str) == Some("code") {
AtnEvent::Code(mapped.code.as_bytes().try_into().ok()?)
} else {
AtnEvent::name(mapped.name)
};
let (event, dictionary) = super::steps_gallery::recorded_event(super::MENU_ITEM, p).unwrap_or_else(|| (event, mapped.label.as_bytes().to_vec()));
Some(AtnItem { event, dictionary, descriptor: None, ..Default::default() })
}
/// Headless execution runs stateless items and refuses settings deliberately left for a dialog.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let id = menu_item_command(p)?;
if !menu_item_needs_settings(id) {
return s.execute(id, json!({}));
}
Err(EngineError::Other(format!("interactive-required: `{id}` needs its menu item dialog; no recorded settings were supplied")))
}
@@ -0,0 +1,227 @@
use super::super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem, UnicodeString, atn};
use super::*;
/// Construct a pixel point directly from the measured #10706 wire format.
fn wire_point(x: f64, y: f64) -> D {
D::Descriptor(Descriptor::new("Pnt ").with("Hrzn", D::UnitFloat { unit: *b"#Pxl", value: x }).with("Vrtc", D::UnitFloat { unit: *b"#Pxl", value: y }))
}
/// Encode a fixture corner without cubic handles.
fn corner(x: f64, y: f64) -> D {
D::Descriptor(Descriptor::new("Pthp").with("Anch", wire_point(x, y)))
}
/// Build the measured outer and inner contours independently of the exporter.
fn fixture(operation: &str, joined: bool, reversed: bool) -> Descriptor {
let mut outer = vec![corner(50.0, 250.0), corner(50.0, 100.0), corner(350.0, 100.0), corner(350.0, 250.0)];
if !joined {
outer[1] = D::Descriptor(
Descriptor::new("Pthp")
.with("Anch", wire_point(50.0, 100.0))
.with("Fwd ", wire_point(50.0, 100.0))
.with("Bwd ", wire_point(100.0, 20.0))
.with("Smoo", D::Boolean(false)),
);
outer[2] = D::Descriptor(
Descriptor::new("Pthp")
.with("Anch", wire_point(350.0, 100.0))
.with("Fwd ", wire_point(300.0, 20.0))
.with("Bwd ", wire_point(350.0, 100.0))
.with("Smoo", D::Boolean(false)),
);
}
let mut inner = vec![corner(150.0, 150.0), corner(250.0, 150.0), corner(250.0, 220.0), corner(150.0, 220.0)];
if reversed {
inner.reverse();
}
let sub = |points| D::Descriptor(Descriptor::new("Sbpl").with("Clsp", D::Boolean(true)).with("Pts ", D::List(points)));
let component = |op, subs| {
D::Descriptor(
Descriptor::new("PaCm")
.with("shapeOperation", D::Enumerated { type_id: Id::new("shapeOperation"), value: Id::new(op) })
.with("SbpL", D::List(subs)),
)
};
let components = if joined {
vec![component("Add ", vec![sub(outer), sub(inner)])]
} else {
vec![component("Add ", vec![sub(outer)]), component(operation, vec![sub(inner)])]
};
Descriptor::new(if joined { "null" } else { "setd" })
.with("null", D::Reference(vec![ReferenceItem::Property { class: class("Path"), key: Id::new("WrPt") }]))
.with("T ", D::List(components))
}
/// Extract the single executable Work Path assignment from a measured descriptor.
fn params(d: &Descriptor) -> Value {
let Mapped::Steps(steps) = from(d) else { panic!("measured path must map") };
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].0, "path.set");
steps[0].1.clone()
}
/// Sample the filled contour, its hole and the untouched exterior independently.
fn check_area(path: &Path) {
let pixels = photocraft_vector::fill_rasterizer(path, photocraft_vector::DEFAULT_TOLERANCE).render(photocraft_geom::Rect::new(0, 0, 400, 300));
for (x, y, expected) in [(100, 185, 1.0), (200, 185, 0.0), (10, 20, 0.0)] {
assert_eq!(pixels[y * 400 + x], expected, "sample {x},{y}");
}
}
#[test]
fn measured_curves_and_component_operations_round_trip_and_cut_holes() {
for (operation, expected) in [("Sbtr", PathOp::Subtract), ("xor", PathOp::Exclude)] {
let d = fixture(operation, false, false);
let p = params(&d);
let path = crate::vector_cmds::parse_path(&p["path"]).unwrap();
assert_eq!(path.fill_rule, FillRule::EvenOdd);
assert_eq!(path.subpaths[1].op, expected);
let knots = &path.subpaths[0].knots;
assert_eq!(knots[1].out_ctrl, Point::new(50.0, 100.0));
assert_eq!(knots[1].in_ctrl, Point::new(100.0, 20.0));
assert_eq!(knots[2].out_ctrl, Point::new(300.0, 20.0));
assert_eq!(knots[2].in_ctrl, Point::new(350.0, 100.0));
assert_eq!(to(&p), Some(d));
check_area(&path);
}
}
#[test]
fn one_component_has_even_odd_holes_with_either_inner_winding() {
for reversed in [false, true] {
let d = fixture("Add ", true, reversed);
let p = params(&d);
let path = crate::vector_cmds::parse_path(&p["path"]).unwrap();
assert_eq!(path.components(), vec![0..2]);
assert_eq!(path.subpaths[1].op, PathOp::Join);
check_area(&path);
assert_eq!(to(&p), Some(d));
}
}
#[test]
fn whole_atn_and_native_insert_path_replay_keep_geometry() {
let original = fixture("Sbtr", false, false);
let file = AtnFile {
actions: vec![AtnAction {
items: vec![AtnItem { event: AtnEvent::name("set"), descriptor: Some(original.clone()), ..Default::default() }],
..Default::default()
}],
..Default::default()
};
let imported = super::super::import(&atn::write(&file).unwrap()).unwrap();
assert!(imported.unsupported.is_empty());
let (bytes, skipped) = super::super::export("S", &[&imported.actions[0]], &[], false).unwrap();
assert!(skipped.is_empty());
assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor, Some(original.clone()));
let expected = path_from(&original).unwrap();
let mut s = crate::Session::new();
s.execute("file.new", json!({"width":400,"height":300})).unwrap();
s.execute("path.set", json!({"name":"Source","path":crate::vector_cmds::path_json(&expected)})).unwrap();
s.actions.list.push(Action::new("Captured", Vec::new()));
let revision = s.active().unwrap().revision;
s.execute("actions.insertPath", json!({"action":0,"name":"Source"})).unwrap();
assert_eq!(s.active().unwrap().revision, revision);
let (bytes, skipped) = super::super::export("S", &[&s.actions.list[0]], &[], false).unwrap();
assert!(skipped.is_empty());
let imported = super::super::import(&bytes).unwrap();
assert!(imported.unsupported.is_empty());
s.actions.list = imported.actions;
s.execute("path.set", json!({"name":"Source","path":{"subpaths":[]}})).unwrap();
let played = s.execute("actions.play", json!({"action":0})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(s.active().unwrap().doc.work_path.as_ref(), Some(&expected));
check_area(s.active().unwrap().doc.work_path.as_ref().unwrap());
}
#[test]
fn source_wire_identity_is_retained_only_for_unchanged_geometry() {
let mut d = fixture("xor", false, false);
d.name = UnicodeString::new_nul("Set");
d.items.reverse();
let mut p = params(&d);
assert_eq!(to(&p).unwrap().to_bytes(), d.to_bytes());
p["path"]["subpaths"][0]["knots"][0]["anchor"][0] = json!(51.0);
assert!(to(&p).is_none());
}
#[test]
fn unknown_and_unrepresented_settings_are_not_silently_lost() {
let base = fixture("Sbtr", false, false);
let mut empty_components = base.clone();
let (_, components) = empty_components.items.iter_mut().find(|(key, _)| key.is("T ")).unwrap();
*components = D::List(Vec::new());
for d in [base.clone().with("extra", D::Boolean(true)), empty_components, fixture("Intr", false, false)] {
assert!(matches!(from(&d), Mapped::Unsupported { harmless: false }));
}
let p = params(&base);
let mut empty = p.clone();
empty["path"]["subpaths"] = json!([]);
empty.as_object_mut().unwrap().remove(SOURCE);
assert!(to(&empty).is_none());
for key in ["inverted", "fillRule"] {
let mut changed = p.clone();
changed["path"][key] = if key == "inverted" { json!(true) } else { json!("nonzero") };
changed.as_object_mut().unwrap().remove(SOURCE);
assert!(to(&changed).is_none());
}
let mut changed = p.clone();
changed["path"]["unrepresented"] = json!(1);
assert!(to(&changed).is_none());
let mut changed = p;
changed[SOURCE] = json!("not base64");
assert!(to(&changed).is_none());
}
#[test]
fn malformed_coordinates_and_oversized_paths_stay_unsupported() {
fn list(value: &mut D) -> &mut Vec<D> {
match value {
D::List(v) => v,
_ => panic!("fixture list"),
}
}
fn object(value: &mut D) -> &mut Descriptor {
match value {
D::Descriptor(v) => v,
_ => panic!("fixture object"),
}
}
for bad in [D::UnitFloat { unit: *b"#Prc", value: 50.0 }, D::UnitFloat { unit: *b"#Pxl", value: f64::NAN }, D::Double(50.0)] {
let mut d = fixture("Sbtr", false, false);
let components = list(&mut d.items[1].1);
let subs = list(&mut object(&mut components[0]).items[1].1);
let points = list(&mut object(&mut subs[0]).items[1].1);
let anchor = object(&mut points[0]);
let coordinates = object(&mut anchor.items[0].1);
coordinates.items[0].1 = bad;
assert!(matches!(from(&d), Mapped::Unsupported { harmless: false }));
}
let mut p = params(&fixture("Sbtr", false, false));
p.as_object_mut().unwrap().remove(SOURCE);
let knot = p["path"]["subpaths"][0]["knots"][0].clone();
p["path"]["subpaths"][0]["knots"] = json!(vec![knot.clone(); MAX_PARTS - 4]);
assert!(to(&p).is_some(), "the existing 4096-knot ceiling remains representable");
p["path"]["subpaths"][0]["knots"] = json!(vec![knot; MAX_PARTS + 1]);
assert!(to(&p).is_none());
}
#[test]
fn oversized_descriptor_names_are_rejected_before_retained_wire_serialization() {
// Each name meets the local limit, but their aggregate exceeds the carrier.
// Keep this typed input independent of the serializer under test.
let mut point =
Descriptor::new("Pnt ").with("Hrzn", D::UnitFloat { unit: *b"#Pxl", value: 50.0 }).with("Vrtc", D::UnitFloat { unit: *b"#Pxl", value: 50.0 });
point.name = UnicodeString(vec![b'x' as u16; 4096]);
let mut knot = Descriptor::new("Pthp").with("Anch", D::Descriptor(point));
knot.name = UnicodeString(vec![b'x' as u16; 4096]);
let sub = Descriptor::new("Sbpl").with("Clsp", D::Boolean(true)).with("Pts ", D::List(vec![D::Descriptor(knot); 300]));
let component = Descriptor::new("PaCm")
.with("shapeOperation", D::Enumerated { type_id: Id::new("shapeOperation"), value: Id::new("Add ") })
.with("SbpL", D::List(vec![D::Descriptor(sub)]));
let d = Descriptor::new("setd")
.with("null", D::Reference(vec![ReferenceItem::Property { class: class("Path"), key: Id::new("WrPt") }]))
.with("T ", D::List(vec![D::Descriptor(component)]));
assert!(path_from(&d).is_none(), "recognition must reject before from() serializes the retained descriptor");
assert!(matches!(from(&d), Mapped::Unsupported { harmless: false }));
}
@@ -0,0 +1,214 @@
//! #10710: Actions steps recorded with the Gradient tool and Create Droplet, as the issue's table
//! gives them (measured in `docs/atn.md` › "Measured through dialogs and recordings"; once mapped,
//! the events are listed with the supported events instead).
use super::*;
fn action(items: Vec<AtnItem>) -> Vec<u8> {
atn::write(&AtnFile {
name: UnicodeString::new_nul("Recorded"),
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
..Default::default()
})
.unwrap()
}
fn step(event: &[u8; 4], label: &str, d: Descriptor) -> AtnItem {
AtnItem { event: AtnEvent::Code(*event), dictionary: label.as_bytes().to_vec(), descriptor: Some(d), ..Default::default() }
}
fn saved(s: &mut Session) -> Vec<AtnItem> {
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
assert_eq!(r["skipped"], json!([]), "{r}");
atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items
}
/// The gradient object the Gradient tool records: dither, classic interpolation, angle, type,
/// scale and offset in percent, then the two-stop gradient.
fn tool_gradient(angle: f64, scale: f64, offset: (f64, f64)) -> Descriptor {
let stop = |hex: &str, at: i32| {
D::Descriptor(
desc("Clrt")
.with("Clr ", D::Descriptor(color_desc(hex).unwrap()))
.with("Type", enm("Clry", "UsrS"))
.with("Lctn", D::Integer(at))
.with("Mdpn", D::Integer(50)),
)
};
let trn = |at: i32| D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", D::Integer(at)).with("Mdpn", D::Integer(50)));
let grad = desc("Grdn")
.with("Nm ", text("Custom"))
.with("GrdF", enm("GrdF", "CstS"))
.with("Intr", D::Double(4096.0))
.with("Clrs", D::List(vec![stop("#102030", 0), stop("#f0e0d0", 4096)]))
.with("Trns", D::List(vec![trn(0), trn(4096)]));
desc("gradientLayer")
.with("Dthr", D::Boolean(true))
.with("gradientsInterpolationMethod", enm("gradientInterpolationMethodType", "Gcls"))
.with("Angl", ang(angle))
.with("Type", enm("GrdT", "Lnr "))
.with("Scl ", pct(scale))
.with("Ofst", D::Descriptor(desc("Pnt ").with("Hrzn", pct(offset.0)).with("Vrtc", pct(offset.1))))
.with("Grad", D::Descriptor(grad))
}
/// The Gradient tool (default mode) records a Make of a gradient fill layer at the first click and
/// a Set with the finished drag (`Algn` false). Both load as their commands, play, and save back
/// as recorded.
#[test]
fn gradient_tool_steps_load_play_and_save_back() {
let make = desc("null")
.with("null", class_ref("contentLayer"))
.with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(tool_gradient(90.0, 100.0, (0.0, 0.0))))));
let set = desc("null")
.with("null", target_ref("contentLayer"))
.with("T ", D::Descriptor(tool_gradient(-35.0, 140.0, (12.5, -8.0)).with("Algn", D::Boolean(false))));
let items = vec![step(b"Mk ", "Make", make.clone()), step(b"setd", "Set", set.clone())];
let mut s = Session::new();
let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&action(items))})).unwrap();
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
let ids: Vec<&str> = s.actions.list[0].steps.iter().map(|(id, _)| id.as_str()).collect();
assert_eq!(ids, ["layer.newFillLayer.gradient", "gradient.fill.set"]);
let set_params = &s.actions.list[0].steps[1].1;
assert_eq!(
(set_params["angle"].as_f64(), set_params["scale"].as_f64(), set_params["align"].as_bool()),
(Some(-35.0), Some(140.0), Some(false)),
"{set_params}"
);
s.execute("file.new", json!({"width": 20, "height": 12})).unwrap();
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(played["ran"], 2, "{played}");
let back = saved(&mut s);
assert_eq!(back.len(), 2);
assert_eq!((back[0].event.id(), back[0].descriptor.as_ref()), ("Mk ".to_string(), Some(&make)));
assert_eq!((back[1].event.id(), back[1].descriptor.as_ref()), ("setd".to_string(), Some(&set)));
}
/// A Create Droplet step as the reference application records it with a Folder destination and
/// Override Action "Save As" on.
fn droplet(file: &str, output: &str, extra: &[(&str, D)]) -> Descriptor {
let reference = D::Reference(vec![
ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul("Sharpen") },
ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul("Tools") },
]);
let mut d = desc("null").with("In ", path_value(file)).with("Fldr", D::Boolean(false)).with("Usng", reference);
for (k, v) in extra.iter().take_while(|(k, _)| *k == "OvrO") {
d = d.with(k, v.clone());
}
d = d.with("T ", path_value(output)).with("Ovrd", D::Boolean(true));
for (k, v) in extra.iter().filter(|(k, _)| *k != "OvrO") {
d = d.with(k, v.clone());
}
d
}
/// Create Droplet loads as `file.automate.createDroplet`, plays (writes the droplet with the
/// action's steps) and saves back as recorded.
#[test]
fn create_droplet_step_loads_plays_and_saves_back() {
let dir = std::env::temp_dir().join(format!("pc-10710-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Sharpen.pcdroplet").to_string_lossy().into_owned();
let out = dir.join("out").to_string_lossy().into_owned();
let recorded = droplet(&file, &out, &[("OvrO", D::Boolean(true))]);
let mut s = Session::new();
// The action the droplet runs.
s.actions.list.push(crate::actions_cmds::Action::new("Sharpen", vec![("filter.sharpen.sharpen".into(), json!({}))]));
s.actions.list[0].set = Some("Tools".into());
let loaded = s
.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&action(vec![step(b"CrtD", "Create Droplet", recorded.clone())]))}))
.unwrap();
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
let a = s.actions.list.iter().find(|a| a.name == "A").unwrap();
assert_eq!(
a.steps,
[("file.automate.createDroplet".to_string(), json!({"path": file, "action": "Sharpen", "set": "Tools", "output": out, "overrideOpen": true}))]
);
let r = s.execute("file.automate.createDroplet", a.steps[0].1.clone()).unwrap();
assert_eq!(r["path"], json!(file));
let written: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
assert_eq!(written["action"]["steps"], json!([["filter.sharpen.sharpen", {}]]));
assert_eq!((written["options"]["output"].as_str(), written["options"]["overrideOpen"].as_bool()), (Some(out.as_str()), Some(true)));
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
let back = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
let item = back.actions.iter().find(|a| a.name.to_string_lossy() == "A").unwrap().items[0].clone();
assert_eq!((item.event.id(), item.descriptor), ("CrtD".to_string(), Some(recorded)));
let _ = std::fs::remove_dir_all(&dir);
}
/// What the droplet cannot do keeps the Photoshop step: Include All Subfolders, Save and Close,
/// no destination, Save As steps left to save where recorded, suppressed dialogs, custom naming
/// and an error log.
#[test]
fn create_droplet_steps_the_droplet_cannot_play_are_kept() {
let kept = |d: Descriptor| matches!(steps_droplet::droplet_from(&d), Mapped::Unsupported { harmless: false });
let base = || droplet("/d/S.pcdroplet", "/d/out", &[]);
let replaced = |key: &str, v: D| {
let mut d = base();
d.items.retain(|(k, _)| !k.is(key));
d.with(key, v)
};
assert!(!kept(base()), "the plain form maps");
assert!(kept(replaced("Fldr", D::Boolean(true))));
assert!(kept(replaced("Ovrd", D::Boolean(false))));
let mut no_destination = base();
no_destination.items.retain(|(k, _)| !k.is("T "));
assert!(kept(no_destination.clone()));
assert!(kept(no_destination.with("SvAn", D::Boolean(true))));
assert!(kept(base().with("suppressOpenOptions", D::Boolean(true))));
assert!(kept(base().with("fileNamingRules", D::Descriptor(desc("fileNamingRules")))));
assert!(kept(base().with("Log ", path_value("/d/logs"))));
}
/// Settings the event has no key for refuse the step on save rather than replay differently.
#[test]
fn create_droplet_steps_that_cannot_be_written_are_refused() {
let p = json!({"path": "/d/S.pcdroplet", "action": "Sharpen", "output": "/d/out"});
assert!(export_item("file.automate.createDroplet", &p, "S").is_some());
for extra in [json!({"format": "png"}), json!({"quality": 8}), json!({"steps": [["filter.sharpen.sharpen", {}]]}), json!({"name": "Other"})] {
let mut q = p.clone();
q.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
assert!(export_item("file.automate.createDroplet", &q, "S").is_none(), "{q}");
}
let mut no_output = p.clone();
no_output.as_object_mut().unwrap().remove("output");
assert!(export_item("file.automate.createDroplet", &no_output, "S").is_none());
}
/// Loading a set whose action clashes with one already in the panel renames the loaded copy; its
/// Create Droplet steps follow the rename, as Batch steps do, whether the reference names the
/// action alone or the action in the file's own set (CodeRabbit review on steps_droplet.rs:59).
#[test]
fn create_droplet_steps_follow_a_renamed_loaded_action() {
let with_ref = |items: Vec<ReferenceItem>| {
let mut d = droplet("/d/S.pcdroplet", "/d/out", &[]);
d.items.retain(|(k, _)| !k.is("Usng"));
d.with("Usng", D::Reference(items))
};
let actn = || ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul("Sharpen") };
let own_set = ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul("Recorded") };
let file = atn::write(&AtnFile {
name: UnicodeString::new_nul("Recorded"),
actions: vec![
AtnAction { name: UnicodeString::new_nul("Sharpen"), ..Default::default() },
AtnAction {
name: UnicodeString::new_nul("A"),
items: vec![step(b"CrtD", "Create Droplet", with_ref(vec![actn()])), step(b"CrtD", "Create Droplet", with_ref(vec![actn(), own_set]))],
..Default::default()
},
],
..Default::default()
})
.unwrap();
let mut s = Session::new();
s.actions.list.push(crate::actions_cmds::Action::new("Sharpen", vec![]));
s.actions.list[0].set = Some("Tools".into());
let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&file), "set": "Loaded"})).unwrap();
assert_eq!(r["actions"], json!(["Sharpen 2", "A"]), "{r}");
let a = s.actions.list.iter().find(|a| a.name == "A").unwrap();
assert_eq!(a.steps[0].1["action"], "Sharpen 2", "{:?}", a.steps[0]);
assert_eq!((&a.steps[1].1["action"], &a.steps[1].1["set"]), (&json!("Sharpen 2"), &json!("Loaded")), "{:?}", a.steps[1]);
}
@@ -0,0 +1,85 @@
//! File › Automate › Create Droplet (`CrtD`, #10710): the droplet file (`In `), the action
//! (`Usng`) and the Batch keys, as #10710 lists them from the reference application. Only the form
//! `file.automate.createDroplet` plays the same way maps; any other stays a Photoshop step.
use super::descriptors::{class, desc, jstr, path_text, path_value};
use super::fields::{Mapped, step};
use super::{D, Descriptor, Map, ReferenceItem, UnicodeString, Value, json};
/// The keys a recorded Create Droplet step can carry (the Batch keys, with `In ` for the source).
const KEYS: &[&str] = &["In ", "Fldr", "Usng", "OvrO", "suppressWarnings", "suppressOpenOptions", "T ", "SvAn", "Ovrd", "fileNamingRules", "Log ", "Nm "];
fn flag(d: &Descriptor, key: &str) -> Option<bool> {
match d.get(key) {
None => Some(false),
Some(D::Boolean(b)) => Some(*b),
Some(_) => None,
}
}
/// A droplet that saves each file into a folder and overrides the action's Save As steps maps:
/// that is what `file.automate.createDroplet` writes (its output folder replaces recorded saves).
/// Include All Subfolders (the droplet lists a folder's own images only), Save and Close or no
/// destination, Save As steps left to save where they were recorded, suppressed warnings or open
/// options, custom file naming and an error log have no field in the droplet, so they keep the
/// Photoshop step.
pub(super) fn droplet_from(d: &Descriptor) -> Mapped {
read(d).map_or(Mapped::Unsupported { harmless: false }, |p| step("file.automate.createDroplet", Value::Object(p)))
}
fn read(d: &Descriptor) -> Option<Map<String, Value>> {
if !d.items.iter().all(|(k, _)| KEYS.iter().any(|s| k.is(s))) {
return None;
}
let off = |k: &str| flag(d, k) == Some(false);
if !off("Fldr") || !off("SvAn") || !off("suppressWarnings") || !off("suppressOpenOptions") || flag(d, "Ovrd") != Some(true) {
return None;
}
if ["fileNamingRules", "Log ", "Nm "].iter().any(|k| d.get(k).is_some()) {
return None;
}
let mut p = Map::new();
p.insert("path".into(), json!(path_text(d.get("In ")?)?));
let D::Reference(items) = d.get("Usng")? else { return None };
match items.as_slice() {
[ReferenceItem::Name { class: action, name }, ReferenceItem::Name { class: set, name: set_name }]
if action.class_id.is("Actn") && set.class_id.is("ASet") =>
{
p.insert("action".into(), json!(name.to_string_lossy()));
p.insert("set".into(), json!(set_name.to_string_lossy()));
}
[ReferenceItem::Name { class: action, name }] if action.class_id.is("Actn") => {
p.insert("action".into(), json!(name.to_string_lossy()));
}
_ => return None,
}
p.insert("output".into(), json!(path_text(d.get("T ")?)?));
if flag(d, "OvrO")? {
p.insert("overrideOpen".into(), json!(true));
}
Some(p)
}
/// Written as `read` reads it: the droplet file, Include All Subfolders off, the action by name
/// (in its set when the step names one), Override Action "Open" only when on, the destination
/// folder and Override Action "Save As" on. Any other setting refuses the step.
pub(super) fn droplet_to(_: &str, p: &Value) -> Option<Descriptor> {
let allowed = ["path", "action", "set", "output", "overrideOpen"];
if p.as_object()?.iter().any(|(k, v)| !v.is_null() && !allowed.contains(&k.as_str())) {
return None;
}
let path = jstr(p, "path").filter(|s| !s.is_empty())?;
let action = jstr(p, "action").filter(|s| !s.is_empty())?;
let output = jstr(p, "output").filter(|s| !s.is_empty())?;
let mut reference = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(action) }];
if let Some(set) = p.get("set").filter(|v| !v.is_null()) {
reference.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set.as_str()?) });
}
let mut d = desc("null").with("In ", path_value(path)).with("Fldr", D::Boolean(false)).with("Usng", D::Reference(reference));
match p.get("overrideOpen") {
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) => d = d.with("OvrO", D::Boolean(true)),
Some(_) => return None,
}
Some(d.with("T ", path_value(output)).with("Ovrd", D::Boolean(true)))
}
@@ -600,11 +600,12 @@ pub(crate) const RECORDED_EVENT: &str = "_atnEvent";
/// Remember the event of a step loaded from an effect's own event (`AccE`, `accentedEdges`).
/// A `GEfc` step carries nothing and saves as `GEfc`, as does a step made in PhotoCraft.
pub(super) fn remember_event(item: &AtnItem, steps: &mut [(String, Value)]) {
if !is_effect(&item.event) {
return;
}
let [(id, Value::Object(p))] = steps else { return };
if effect_command(&item.event) != Some(id.as_str()) {
let menu = id == super::MENU_ITEM
&& item.descriptor.is_none()
&& super::menu_item::from_event(&item.event)
.is_some_and(|expected| p.get("id") == expected.get("id") && p.get("eventKind") == expected.get("eventKind"));
if !menu && effect_command(&item.event) != Some(id.as_str()) {
return;
}
let kind = match item.event {
@@ -617,8 +618,8 @@ pub(super) fn remember_event(item: &AtnItem, steps: &mut [(String, Value)]) {
p.insert(RECORDED_EVENT.into(), json!({"event": item.event.id(), "eventKind": kind, "name": item.dictionary(), "dictionary": dictionary}));
}
/// The event and panel name bytes a step of command `id` remembered by [`remember_event`] saves
/// as; `None` (save as `GEfc`) when it has none or it is not the own event of `id`'s effect.
/// Return remembered event/name bytes only while they still match the current command and kind.
/// Otherwise the exporter uses that command's canonical event and name.
pub(super) fn recorded_event(id: &str, params: &Value) -> Option<(AtnEvent, Vec<u8>)> {
let r = params.get(RECORDED_EVENT)?;
let event = jstr(r, "event")?;
@@ -631,7 +632,13 @@ pub(super) fn recorded_event(id: &str, params: &Value) -> Option<(AtnEvent, Vec<
Some(bytes) => bytes,
None => jstr(r, "name").unwrap_or("").as_bytes().to_vec(),
};
(effect_command(&event) == Some(id)).then_some((event, name))
let matches = if id == super::MENU_ITEM {
super::menu_item::from_event(&event)
.is_some_and(|expected| params.get("id") == expected.get("id") && params.get("eventKind") == expected.get("eventKind"))
} else {
effect_command(&event) == Some(id)
};
matches.then_some((event, name))
}
/// A Filter Gallery step: the effect `GEfk` names, every key clamped or looked up, Photoshop's
@@ -1164,6 +1164,7 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped {
let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } };
let unsupported = Mapped::Unsupported { harmless: false };
match (ref_class(r).as_deref(), target(r)) {
(Some("Path"), Target::Property(p)) if p == "WrPt" => super::steps_path::from(d),
(Some("Chnl"), Target::Property(p)) if p == "fsel" => selection_from(d),
// Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off.
(Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})),
@@ -1270,6 +1271,7 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]);
let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t);
Some(match id {
"path.set" => return super::steps_path::to(p),
"select.all" => sel(enm("Ordn", "Al ")),
"select.deselect" => sel(enm("Ordn", "None")),
"select.reselect" => sel(enm("Ordn", "Prvs")),
@@ -0,0 +1,212 @@
//! Measured Insert Path: per-component operations, with even-odd subpaths in each component.
use super::descriptors::{PX, class, desc, enm, get_list, get_ref, jstr, px};
use super::fields::{Mapped, step};
use super::{D, Descriptor, Id, ReferenceItem, Value, json};
use photocraft_doc::{FillRule, Knot, Path, PathOp, Subpath};
use photocraft_geom::Point;
pub(super) const SOURCE: &str = "_atnInsertPathDescriptor";
// The native path validator admits at most 4096 knots/subpaths. Larger wire
// records remain complete kept steps rather than secondary geometry allocations.
const MAX_PARTS: usize = 4096;
const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024;
#[cfg(test)]
#[path = "path_tests.rs"]
mod tests;
/// Bound the retained wire form before serializing it into a second allocation.
/// Names use UTF-16; 64 bytes per measured field conservatively covers its fixed
/// key/type/scalar or list header. Nested descriptors charge their own fields.
fn keys(d: &Descriptor, required: &[&str], optional: &[&str], budget: &mut usize) -> bool {
let size = d.name.0.len().checked_mul(2).and_then(|names| d.items.len().checked_mul(64)?.checked_add(names)?.checked_add(32));
let Some(remaining) = size.and_then(|size| budget.checked_sub(size)) else { return false };
*budget = remaining;
d.name.0.len() <= 4096
&& d.items.iter().all(|(k, _)| required.iter().chain(optional).any(|key| k.is(key)))
&& required.iter().all(|key| d.items.iter().filter(|(k, _)| k.is(key)).count() == 1)
&& optional.iter().all(|key| d.items.iter().filter(|(k, _)| k.is(key)).count() <= 1)
}
/// Require the recorded object class before interpreting its fields as geometry.
fn object<'a>(value: &'a D, class_id: &str) -> Option<&'a Descriptor> {
match value {
D::Descriptor(d) if d.class_id.is(class_id) => Some(d),
_ => None,
}
}
/// Read a pixel point within the native coordinate range and charge its fields to the wire budget.
fn point(value: &D, budget: &mut usize) -> Option<Point> {
let d = object(value, "Pnt ")?;
if !keys(d, &["Hrzn", "Vrtc"], &[], budget) {
return None;
}
let coordinate = |key| match d.get(key)? {
D::UnitFloat { unit, value } if *unit == PX && value.is_finite() && value.abs() <= f64::from(f32::MAX) => Some(*value),
_ => None,
};
Some(Point::new(coordinate("Hrzn")?, coordinate("Vrtc")?))
}
/// A corner stores only its anchor. A cubic knot must supply both handles and its smooth flag.
fn knot(value: &D, budget: &mut usize) -> Option<Knot> {
let d = object(value, "Pthp")?;
if !keys(d, &["Anch"], &["Fwd ", "Bwd ", "Smoo"], budget) {
return None;
}
let anchor = point(d.get("Anch")?, budget)?;
match (d.get("Fwd "), d.get("Bwd "), d.get("Smoo")) {
(None, None, None) => Some(Knot::corner(anchor.x, anchor.y)),
(Some(out), Some(input), Some(D::Boolean(smooth))) => {
Some(Knot { anchor, out_ctrl: point(out, budget)?, in_ctrl: point(input, budget)?, smooth: *smooth })
}
_ => None,
}
}
/// Decode a Work Path property assignment, preserving the grouping and operation of each component.
fn path_from(d: &Descriptor) -> Option<Path> {
let mut budget = MAX_SOURCE_BYTES;
if !(d.class_id.is("null") || d.class_id.is("setd")) || !keys(d, &["null", "T "], &[], &mut budget) {
return None;
}
let Some([ReferenceItem::Property { class, key }]) = get_ref(d, "null") else { return None };
if !class.class_id.is("Path") || class.name.0.len() > 4096 || !key.is("WrPt") {
return None;
}
budget = budget.checked_sub(class.name.0.len().checked_mul(2)?.checked_add(64)?)?;
let components = get_list(d, "T ")?;
if components.is_empty() || components.len() > MAX_PARTS {
return None;
}
let mut path = Path { fill_rule: FillRule::EvenOdd, ..Default::default() };
let mut count = 0usize;
for value in components {
let component = object(value, "PaCm")?;
if !keys(component, &["shapeOperation", "SbpL"], &[], &mut budget) {
return None;
}
let op = match component.get("shapeOperation")? {
D::Enumerated { type_id, value } if type_id.is("shapeOperation") => {
if value.is("Add ") {
PathOp::Combine
} else if value.is("Sbtr") {
PathOp::Subtract
} else if value.is("xor") {
PathOp::Exclude
} else {
return None;
}
}
_ => return None,
};
if path.subpaths.is_empty() && op != PathOp::Combine {
return None;
}
let subpaths = get_list(component, "SbpL")?;
if subpaths.is_empty() || path.subpaths.len().checked_add(subpaths.len())? > MAX_PARTS {
return None;
}
for (i, value) in subpaths.iter().enumerate() {
let sub = object(value, "Sbpl")?;
if !keys(sub, &["Clsp", "Pts "], &[], &mut budget) {
return None;
}
let D::Boolean(closed) = sub.get("Clsp")? else { return None };
let points = get_list(sub, "Pts ")?;
count = count.checked_add(points.len())?;
if count > MAX_PARTS {
return None;
}
let knots = points.iter().map(|value| knot(value, &mut budget)).collect::<Option<Vec<_>>>()?;
path.subpaths.push(Subpath { closed: *closed, knots, op: if i == 0 { op } else { PathOp::Join } });
}
}
photocraft_vector::flatten::validate_path(&path).ok()?;
Some(path)
}
/// Decode only the measured Work Path form; unsupported data stays a complete kept step.
pub(super) fn from(d: &Descriptor) -> Mapped {
let Some(path) = path_from(d) else { return Mapped::Unsupported { harmless: false } };
let raw = d.to_bytes();
if raw.len() > MAX_SOURCE_BYTES {
return Mapped::Unsupported { harmless: false };
}
step("path.set", json!({"name":"work", "path":crate::vector_cmds::path_json(&path), SOURCE:photocraft_paint::tile::b64_encode(&raw)}))
}
/// Write a point using pixel units for both coordinates.
fn point_to(p: Point) -> D {
D::Descriptor(desc("Pnt ").with("Hrzn", px(p.x)).with("Vrtc", px(p.y)))
}
/// Emit the compact corner form only when the handles coincide and the knot has no smooth flag.
fn knot_to(k: &Knot) -> D {
let mut d = desc("Pthp").with("Anch", point_to(k.anchor));
if k.in_ctrl != k.anchor || k.out_ctrl != k.anchor || k.smooth {
d = d.with("Fwd ", point_to(k.out_ctrl)).with("Bwd ", point_to(k.in_ctrl)).with("Smoo", D::Boolean(k.smooth));
}
D::Descriptor(d)
}
/// Export representable native geometry or an unchanged validated source descriptor.
/// Nonzero winding, inversion and unmeasured operations cannot silently become even-odd.
pub(super) fn to(p: &Value) -> Option<Descriptor> {
if jstr(p, "name") != Some("work") || p.as_object()?.keys().any(|k| !matches!(k.as_str(), "name" | "path" | SOURCE)) {
return None;
}
let value = p.get("path")?;
let subpaths = value.get("subpaths")?.as_array()?;
if subpaths.is_empty()
|| subpaths.len() > MAX_PARTS
|| subpaths.iter().try_fold(0usize, |n, s| n.checked_add(s.get("knots")?.as_array()?.len()))? > MAX_PARTS
{
return None;
}
let path = crate::vector_cmds::parse_path(value).ok()?;
photocraft_vector::flatten::validate_path(&path).ok()?;
let mut canonical = crate::vector_cmds::path_json(&path);
let mut supplied = value.clone();
super::convert::normalise(&mut canonical);
super::convert::normalise(&mut supplied);
if path.inverted || path.fill_rule != FillRule::EvenOdd || canonical != supplied {
return None;
}
if let Some(source) = p.get(SOURCE) {
let text = source.as_str()?;
if text.len() > MAX_SOURCE_BYTES.div_ceil(3) * 4 {
return None;
}
let raw = photocraft_paint::tile::b64_decode(text)?;
if raw.len() > MAX_SOURCE_BYTES {
return None;
}
let original = Descriptor::from_bytes(&raw).ok()?;
return (path_from(&original)? == path).then_some(original);
}
let mut components = Vec::new();
for range in path.components() {
let first = path.subpaths.get(range.start)?;
let op = match first.op {
PathOp::Combine => "Add ",
PathOp::Subtract => "Sbtr",
PathOp::Exclude => "xor",
_ => return None,
};
if components.is_empty() && first.op != PathOp::Combine {
return None;
}
let subs = path
.subpaths
.get(range)?
.iter()
.map(|s| D::Descriptor(desc("Sbpl").with("Clsp", D::Boolean(s.closed)).with("Pts ", D::List(s.knots.iter().map(knot_to).collect()))))
.collect();
components.push(D::Descriptor(desc("PaCm").with("shapeOperation", enm("shapeOperation", op)).with("SbpL", D::List(subs))));
}
Some(
desc("setd").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Path"), key: Id::new("WrPt") }])).with("T ", D::List(components)),
)
}
+18 -2
View File
@@ -741,6 +741,7 @@ fn every_mapped_command_exports_and_imports_back() {
("filter.blur.smartBlur", json!({"radius": 2.5, "threshold": 40, "quality": "medium", "mode": "overlayEdge"})),
("filter.other.offset", json!({"horizontal": 10, "vertical": -5, "undefinedAreas": "wrap"})),
("filter.blur.blur", json!({})),
("file.automate.createDroplet", json!({"path": "/d/Sharpen.pcdroplet", "action": "Sharpen", "set": "Tools", "output": "/d/out", "overrideOpen": true})),
("filter.distort.shear", json!({"points": [[0,0], [0.5,0.25], [1,0]], "undefinedAreas": "repeat"})),
("filter.distort.pinch", json!({"amount": -30})),
("filter.distort.polarCoordinates", json!({"mode": "polarToRectangular"})),
@@ -834,6 +835,13 @@ fn every_mapped_command_exports_and_imports_back() {
("layer.new.layer", json!({"name": "Ink", "opacity": 0.5, "mode": "Multiply"})),
("type.convertToShape", json!({})),
("type.createWorkPath", json!({})),
(
"path.set",
json!({"name":"work","path":{"fillRule":"evenodd","inverted":false,"subpaths":[{"closed":false,"op":"combine","knots":[
{"anchor":[1,2],"in":[1,2],"out":[3,4],"smooth":false},
{"anchor":[8,9],"in":[6,7],"out":[8,9],"smooth":false}
]}]}}),
),
("filter.blur.shapeBlur", json!({})),
("filter.blur.shapeBlur", json!({"radius": 10})),
("layer.new.group", json!({"name": "G"})),
@@ -1114,6 +1122,10 @@ fn every_mapped_command_exports_and_imports_back() {
// Executable values match; independent public tests verify the source carrier.
back.as_object_mut().unwrap().remove("__atnClassicGradient");
}
if *id == "path.set" {
// The imported step retains the original descriptor alongside its playable path.
back.as_object_mut().unwrap().remove(super::steps_path::SOURCE).unwrap();
}
if *id == "edit.perspectiveWarp" {
back.as_object_mut().unwrap().remove("__atnPerspectiveWarp");
}
@@ -1407,6 +1419,7 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() {
Some(desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(desc("GdMp")))))),
),
item("GsnB", "Gaussian Blur", None),
item("GsnB", "Gaussian Blur", Some(desc("null"))),
// Duplicate into another open document: the `T` reference means nothing at
// replay, so the step is kept verbatim instead of misplayed as a same-doc copy.
item(
@@ -1428,8 +1441,11 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() {
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
let ids: Vec<&str> = imp.actions[0].steps.iter().map(|(id, _)| id.as_str()).collect();
assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, "filter.blur.gaussianBlur", PHOTOSHOP_STEP]);
assert_eq!(imp.unsupported.len(), 5);
assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, MENU_ITEM, "filter.blur.gaussianBlur", PHOTOSHOP_STEP]);
assert_eq!(imp.actions[0].steps[4].1["id"], "filter.blur.gaussianBlur");
assert_eq!(imp.actions[0].steps[4].1["eventKind"], "code");
assert_eq!(imp.actions[0].steps[5].1, json!({}));
assert_eq!(imp.unsupported.iter().map(|step| step.step).collect::<Vec<_>>(), [0, 1, 2, 3, 6]);
assert!(imp.actions[0].disabled.is_empty(), "steps with a document effect stay on so playback reports them");
}
+57 -2
View File
@@ -14,7 +14,7 @@ use std::cell::RefCell;
use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, apply_liquify, auto_cell};
use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, straighten};
use photocraft_algo::puppet::{PuppetDensity, PuppetMode, PuppetPin, PuppetWarp, puppet_warp, puppet_warp_with_mask};
use photocraft_algo::puppet::{PuppetDensity, PuppetMesh, PuppetMode, PuppetPin, PuppetWarp, puppet_warp, puppet_warp_with_mask, warp_with_mesh};
use photocraft_algo::transform::Interp;
use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};
use photocraft_color::PixelFormat;
@@ -86,6 +86,51 @@ pub fn puppet_params(cmd: &str, p: &Value) -> Result<PuppetWarp> {
Ok(PuppetWarp { pins, mode, density, expansion })
}
/// The most vertices a stored Puppet Warp mesh may have (Photoshop's meshes have hundreds); the
/// PSD importer reads no more.
const MAX_STORED_VERTS: usize = 1 << 16;
/// A Puppet Warp's stored mesh, as a Photoshop file keeps it (`mesh`: `{"pins", "verts",
/// "deformed", "tris"}`, document pixels): the mesh solved for `pins`, drawn as it is instead of
/// solving again. `None` when there is none, it is malformed, or the filter was edited since: its
/// pins are no longer the ones it was solved for, or a solver setting is set (imported params
/// set none).
pub fn stored_puppet_mesh(p: &Value) -> Option<(PuppetMesh, Vec<[f64; 2]>)> {
let m = p.get("mesh")?;
if m.get("pins") != p.get("pins") || ["mode", "density", "expansion"].iter().any(|k| p.get(*k).is_some()) {
return None;
}
let points = |k: &str| -> Option<Vec<[f64; 2]>> {
let v = m.get(k)?.as_array()?;
if v.len() > MAX_STORED_VERTS {
return None;
}
v.iter().map(|q| serde_json::from_value::<[f64; 2]>(q.clone()).ok()).collect()
};
let (verts, deformed) = (points("verts")?, points("deformed")?);
let tris = m.get("tris")?.as_array()?;
if tris.len() > 2 * MAX_STORED_VERTS {
return None;
}
let tris: Vec<[usize; 3]> = tris.iter().map(|t| serde_json::from_value(t.clone()).ok()).collect::<Option<_>>()?;
Some((PuppetMesh { verts, tris, spacing: 0.0 }, deformed))
}
/// `params` of smart filter `command` on `sm`, without a stored Puppet Warp mesh made for another
/// placement than `sm`'s (`mesh.placement`, recorded on import): a mesh in document pixels doesn't
/// fit a smart object moved, transformed or warped since, so its pins are solved instead.
pub fn placed_puppet_params<'a>(command: &str, params: &'a Value, sm: &photocraft_doc::SmartObject) -> std::borrow::Cow<'a, Value> {
let stale = command == PUPPET_SMART && params.get("mesh").is_some_and(|m| m.get("placement") != Some(&sm.placement_json()));
if !stale {
return std::borrow::Cow::Borrowed(params);
}
let mut p = params.clone();
if let Some(o) = p.as_object_mut() {
o.remove("mesh");
}
std::borrow::Cow::Owned(p)
}
/// Perspective Warp params (planes, after the optional straighten).
pub fn perspective_params(cmd: &str, p: &Value) -> Result<Vec<Plane>> {
let mut planes: Vec<Plane> = match p.get("planes") {
@@ -182,7 +227,17 @@ pub fn apply_to_surface(id: &str, params: &Value, surf: &Surface, canvas: Rect)
Some(liquify_surface(surf, &strokes, cell, canvas))
}
// A stored warp too far to render leaves the smart object as it is (#1019).
PUPPET | PUPPET_SMART => Some(puppet_surface(surf, &puppet_params(id, params).ok()?, interp(params)).unwrap_or_else(|| surf.clone())),
PUPPET | PUPPET_SMART => {
// A mesh stored with the filter (from a Photoshop file) is drawn as it is; one that
// can't be drawn leaves the pins to solve.
let b = surf.content_bounds();
if let Some((mesh, deformed)) = stored_puppet_mesh(params).filter(|_| !b.is_empty())
&& let Some(out) = warp_with_mesh(surf, b, &mesh, &deformed, interp(params))
{
return Some(out);
}
Some(puppet_surface(surf, &puppet_params(id, params).ok()?, interp(params)).unwrap_or_else(|| surf.clone()))
}
PERSPECTIVE | PERSPECTIVE_SMART => Some(perspective_surface(surf, &perspective_params(id, params).ok()?, interp(params))),
_ => None,
}
@@ -473,3 +473,71 @@ fn unlocked_or_position_locked_smart_objects_take_distortions() {
}
}
}
#[test]
fn a_stored_puppet_mesh_is_drawn_while_its_pins_hold() {
// A Photoshop file's Puppet Warp carries its solved mesh: it is drawn as it is (here a whole
// move by (2, 1), although one pin alone would move the block by (6, 4)), until the pins
// change; then the pins are solved.
let surf = active_surface(&session(8));
let canvas = Rect::new(0, 0, 80, 60);
let pins = json!([{"src": [30, 25], "dst": [36, 29]}]);
let verts = [[8.0, 8.0], [62.0, 8.0], [62.0, 42.0], [8.0, 42.0]];
let moved: Vec<[f64; 2]> = verts.iter().map(|v| [v[0] + 2.0, v[1] + 1.0]).collect();
let mesh = json!({"pins": pins, "verts": verts, "deformed": moved, "tris": [[0, 1, 2], [0, 2, 3]]});
let shifted = |dx, dy| photocraft_algo::resample::translate_surface(&surf, dx, dy);
let p = json!({"pins": pins, "interpolation": "bilinear", "mesh": mesh});
let out = apply_to_surface(PUPPET_SMART, &p, &surf, canvas).unwrap();
assert_eq!(out.content_bounds(), Rect::new(12, 11, 62, 41));
assert!(worst(&out, &shifted(2, 1), Rect::new(12, 11, 62, 41)) <= 1.0 / 255.0);
// Pins edited after import: the stored mesh no longer applies.
let mut edited = p.clone();
edited["mesh"]["pins"][0]["dst"] = json!([40, 29]);
let out = apply_to_surface(PUPPET_SMART, &edited, &surf, canvas).unwrap();
assert_eq!(out.content_bounds(), Rect::new(16, 14, 66, 44));
// So does a solver setting set after import (imported params set none).
for (k, v) in [("mode", json!("rigid")), ("density", json!("more")), ("expansion", json!(2.0))] {
let mut q = p.clone();
q[k] = v;
let out = apply_to_surface(PUPPET_SMART, &q, &surf, canvas).unwrap();
assert_eq!(out.content_bounds(), Rect::new(16, 14, 66, 44), "{k}");
}
// A malformed mesh is ignored the same way.
for bad in [
json!({"pins": pins, "verts": verts, "deformed": [[0, 0]], "tris": [[0, 1, 2]]}),
json!({"pins": pins, "verts": verts, "deformed": moved, "tris": [[0, 1, 9]]}),
] {
let mut q = p.clone();
q["mesh"] = bad;
let out = apply_to_surface(PUPPET_SMART, &q, &surf, canvas).unwrap();
assert_eq!(out.content_bounds(), Rect::new(16, 14, 66, 44));
}
}
#[test]
fn a_stored_puppet_mesh_is_drawn_only_on_the_placement_it_was_made_for() {
// The mesh sits in document pixels where the layer was on import (`mesh.placement`); once the
// smart object is moved, transformed or warped, its pins are solved instead.
let surf = active_surface(&session(8));
let canvas = Rect::new(0, 0, 80, 60);
let pins = json!([{"src": [30, 25], "dst": [36, 29]}]);
let verts = [[8.0, 8.0], [62.0, 8.0], [62.0, 42.0], [8.0, 42.0]];
let moved: Vec<[f64; 2]> = verts.iter().map(|v| [v[0] + 2.0, v[1] + 1.0]).collect();
let src = photocraft_doc::SmartSource::Linked { path: "x.png".into() };
let mut sm = photocraft_doc::SmartObject::new(src, photocraft_geom::Affine::IDENTITY, None);
let mesh = json!({"pins": pins, "verts": verts, "deformed": moved, "tris": [[0, 1, 2], [0, 2, 3]], "placement": sm.placement_json()});
let params = json!({"pins": pins, "interpolation": "bilinear", "mesh": mesh});
sm.smart_filters.push(SmartFilter { command: PUPPET_SMART.into(), params, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true });
let render = |sm: &photocraft_doc::SmartObject| crate::smart_cmds::apply_smart_filters(&surf, sm, canvas).unwrap().content_bounds();
assert_eq!(render(&sm), Rect::new(12, 11, 62, 41), "the stored mesh");
let mut placed = sm.clone();
placed.transform = photocraft_geom::Affine { m: [1.0, 0.0, 0.0, 1.0, 4.0, 0.0] };
assert_eq!(render(&placed), Rect::new(16, 14, 66, 44), "moved: solved");
let mut warped = sm.clone();
warped.warp = Some(photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Arc, 10.0, [0.0, 0.0, 50.0, 30.0]));
assert_eq!(render(&warped), Rect::new(16, 14, 66, 44), "warped: solved");
// A mesh with no placement recorded is treated the same way.
let mut bare = sm.clone();
bare.smart_filters[0].params["mesh"].as_object_mut().unwrap().remove("placement");
assert_eq!(render(&bare), Rect::new(16, 14, 66, 44), "no placement: solved");
}
+8 -4
View File
@@ -989,12 +989,16 @@ fn guide_position(s: &Session, p: &Value, vertical: bool) -> Result<Option<f64>>
let px = match (v.as_f64(), v.as_str()) {
(Some(n), _) => n,
(None, Some(text)) => {
let (n, unit) = crate::prefs::Unit::parse_length(text).ok_or_else(|| {
EngineError::Other(format!("`position` {text:?} is not a length: give a number of pixels, or a number with px, in, cm, mm, pt, pc or %"))
})?;
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let extent = if vertical { doc.size.width } else { doc.size.height };
unit.unwrap_or(crate::prefs::Unit::Pixels).to_px(n, doc.resolution_dpi as f64, extent as f64, s.prefs().units_and_rulers.point_size.per_inch())
let per_inch = s.prefs().units_and_rulers.point_size.per_inch();
// A length, or arithmetic on lengths as Photoshop's field takes ("100% / 3", #10440).
let to_px = |n: f64, unit: crate::prefs::Unit| unit.to_px(n, doc.resolution_dpi as f64, extent as f64, per_inch);
crate::prefs::Unit::eval_length(text, crate::prefs::Unit::Pixels, to_px).ok_or_else(|| {
EngineError::Other(format!(
"`position` {text:?} is not a length: give a number of pixels, a number with px, in, cm, mm, pt, pc or %, or arithmetic on them (+ - * /)"
))
})?
}
_ => return Err(EngineError::Other("`position` must be a number of pixels or text with a unit".into())),
};
+70
View File
@@ -1292,6 +1292,56 @@ fn guide_positions_take_photoshop_units() {
assert_eq!(s.active().unwrap().doc.guides.horizontal[0], 50.0);
}
/// #10440: the position takes arithmetic as Photoshop's New Guide field does. Measured in
/// Photoshop 2025 on a 600 × 400, 72 ppi document: "100% / 3" → 200, "100% - 50px" → 550,
/// "300 / 2" → 150 (pixels), "1in + 10" → 792 (the bare 10 is in the first operand's unit).
#[test]
fn guide_positions_take_arithmetic() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400, "resolution": 72})).unwrap();
for (text, px) in [
("100% / 3", 200.0),
("100% - 50px", 550.0),
("300 / 2", 150.0),
("1in + 10", 792.0),
("2 * 50 px", 100.0),
("10 + 2 * 3", 16.0),
("-50px + 100", 50.0),
] {
assert!((new_guide(&mut s, "vertical", json!(text)) - px).abs() < 1e-6, "{text}");
}
// Horizontal guides take percent of the height.
assert!((new_guide(&mut s, "horizontal", json!("50% + 10px")) - 210.0).abs() < 1e-6);
for bad in ["100% /", "1in * 2in", "10 / 0", "10 / 2px", "5 ^ 2", "+", "50% 3"] {
let err = s.execute("view.newGuide", json!({"orientation": "vertical", "position": bad})).unwrap_err();
assert!(err.to_string().contains("not a length"), "{bad}: {err}");
}
}
/// The Unicode minus (U+2212, what some keyboards and pasted text give) is a minus, as in the
/// numeric fields' own evaluator.
#[test]
fn guide_position_arithmetic_takes_the_unicode_minus() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400, "resolution": 72})).unwrap();
for (text, px) in [("100% − 50px", 550.0), ("−50px + 100", 50.0), ("1in − −10", 792.0), ("−100", -100.0)] {
assert!((new_guide(&mut s, "vertical", json!(text)) - px).abs() < 1e-6, "{text}");
}
}
/// Text longer than the numeric fields' 1024-byte cap is refused before it is tokenised.
#[test]
fn guide_position_arithmetic_is_capped_at_1024_bytes() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400, "resolution": 72})).unwrap();
let fits = format!("{}100", "0 + ".repeat(255));
assert_eq!(fits.len(), 1023);
assert_eq!(new_guide(&mut s, "vertical", json!(fits)), 100.0);
let long = format!("{}100", "0 + ".repeat(256));
let err = s.execute("view.newGuide", json!({"orientation": "vertical", "position": long})).unwrap_err();
assert!(err.to_string().contains("not a length"), "{err}");
}
#[test]
fn new_guides_keep_their_own_colour_through_moves_deletes_and_undo() {
let mut s = Session::new();
@@ -1381,6 +1431,26 @@ fn editing_a_guide_changes_what_is_given_in_one_undoable_step() {
assert_eq!(g.color(true, 200.0), Some([0xff, 0x00, 0xff]));
}
/// #10440: Edit Selected Guides reads its position as New Guide does, arithmetic included; % is of
/// the new orientation's extent.
#[test]
fn editing_a_guide_takes_arithmetic_in_its_position() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap();
s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap();
s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20})).unwrap();
s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "position": "100% / 4"})).unwrap();
s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "position": "1in + 1"})).unwrap();
assert_eq!(s.active().unwrap().doc.guides.vertical, vec![100.0, 200.0]);
s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "newOrientation": "horizontal", "position": "50% − 10px"})).unwrap();
let g = &s.active().unwrap().doc.guides;
assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![200.0], vec![90.0]));
let before = g.clone();
let err = s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "position": "1in * 2in"})).unwrap_err();
assert!(err.to_string().contains("not a length"), "{err}");
assert_eq!(s.active().unwrap().doc.guides, before);
}
#[test]
fn bad_guide_edits_are_refused_without_a_history_step() {
let mut s = Session::new();
+1 -1
View File
@@ -313,7 +313,7 @@ pub use content_aware::{CafPlan, FillEdit, MAX_CAF_EDITS, MAX_CAF_POINTS, SelOp,
use content_aware::{can_caf, content_aware_fill, delete_and_fill};
pub use content_aware_scale::ContentAwareScalePreview;
use content_aware_scale::content_aware_scale;
pub use fade::fade_surface;
pub use fade::{FadePreview, fade_preview, fade_surface};
use fade::{can_fade, fade};
pub use find_replace::find_matches;
use find_replace::{find_replace, has_type_layer};
+54 -10
View File
@@ -1,5 +1,5 @@
use super::{
BlendMode, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of,
BlendMode, Document, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of,
surface_of_mut, to_rgba,
};
@@ -67,7 +67,18 @@ pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: Ble
Ok(())
}
pub(super) fn fade(s: &mut Session, p: &Value) -> Result<Value> {
/// What Edit › Fade with `p` blends: the layer, mask or channel of the last step, its pixels
/// before it, the area to blend, the mode and the opacity.
struct FadeJob {
target: FadeTarget,
label: String,
before: Surface,
area: Rect,
mode: BlendMode,
opacity: f32,
}
fn fade_job(s: &Session, p: &Value) -> Result<FadeJob> {
let cmd = "edit.fade";
let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?;
let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0;
@@ -82,12 +93,45 @@ pub(super) fn fade(s: &mut Session, p: &Value) -> Result<Value> {
// A uniform mask can change every pixel without storing a single tile. In that case
// the content bounds are empty, but Fade must still blend across the canvas.
let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) };
let label = format!("Fade {}", src.label);
s.edit(&label, |doc, _| {
let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?;
fade_surface(&before, surf, area, mode, opacity)?;
surf.prune();
Ok(())
})?;
Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()}))
Ok(FadeJob { target: src.target, label: src.label, before, area, mode, opacity })
}
fn apply_fade(doc: &mut Document, j: &FadeJob) -> Result<()> {
let surf = surface_of_mut(doc, j.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?;
fade_surface(&j.before, surf, j.area, j.mode, j.opacity)?;
surf.prune();
Ok(())
}
pub(super) fn fade(s: &mut Session, p: &Value) -> Result<Value> {
let j = fade_job(s, p)?;
let label = format!("Fade {}", j.label);
s.edit(&label, |doc, _| apply_fade(doc, &j))?;
Ok(json!({"faded": j.label, "opacity": j.opacity * 100.0, "mode": j.mode.label()}))
}
/// Edit › Fade with given params, captured from the session without a history step: the Fade
/// dialog's live preview (#8230). [`FadePreview::render`] does the blend and can run off the
/// session (the preview worker). The document copy shares its tiles with the session's, and
/// only the tiles in the faded area are blended and rewritten.
pub struct FadePreview {
doc: Document,
job: FadeJob,
}
impl FadePreview {
/// The active document as Edit › Fade would leave it.
pub fn render(mut self) -> Result<Document> {
apply_fade(&mut self.doc, &self.job)?;
Ok(self.doc)
}
}
/// What Edit › Fade with `p` would do to the active document. `Err` when Fade isn't available
/// or `p` is invalid.
pub fn fade_preview(s: &Session, p: &Value) -> Result<FadePreview> {
can_fade(s).map_err(|e| bad("edit.fade", e))?;
let job = fade_job(s, p)?;
let doc = Document::clone(&s.active().ok_or(EngineError::NoDocument)?.doc);
Ok(FadePreview { doc, job })
}
@@ -23,6 +23,33 @@ fn active(s: &Session) -> &Layer {
st.doc.layer(st.active_layer.unwrap()).unwrap()
}
/// #8230: the Fade dialog's preview is the document Fade would leave, at every depth and in a
/// blend mode, with no history step and nothing changed until OK; with nothing to fade or a bad
/// mode it is an error, not a panic.
#[test]
fn fade_preview_matches_fade_without_a_step() {
for depth in [8, 16, 32] {
assert!(fade_preview(&session(depth), &json!({"opacity": 50})).is_err(), "nothing to fade yet");
for p in [json!({"opacity": 25}), json!({"opacity": 60, "mode": "difference"}), json!({})] {
let mut s = session(depth);
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
let (steps, revision) = (s.active().unwrap().history.past_len(), s.active().unwrap().revision);
let preview = fade_preview(&s, &p).and_then(FadePreview::render).unwrap();
assert_eq!((s.active().unwrap().history.past_len(), s.active().unwrap().revision), (steps, revision), "depth {depth} {p}: no step");
assert_eq!(px(&s, 5, 5)[0], 0.0, "depth {depth} {p}: the layer is untouched");
let id = s.active().unwrap().active_layer.unwrap();
let shown = preview.layer(id).unwrap().surface().unwrap().pixel(5, 5);
s.execute("edit.fade", p.clone()).unwrap();
assert_eq!(shown, px(&s, 5, 5), "depth {depth} {p}: the preview is what OK applies");
}
let mut s = session(depth);
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
assert!(fade_preview(&s, &json!({"mode": "nonsense"})).is_err());
s.execute("layer.new.layer", json!({})).unwrap();
assert!(fade_preview(&s, &json!({})).is_err(), "not right after the step");
}
}
#[test]
fn fade_blends_last_step_at_all_depths() {
for depth in [8, 16, 32] {
@@ -119,7 +146,11 @@ fn fade_an_alpha_channel_or_the_quick_mask_at_all_depths() {
assert!((channel(&s, 5, 5) - (1.0 - was)).abs() < 0.01, "depth {depth}, quick mask {quick_mask}: inverted");
let expected = was + (1.0 - 2.0 * was) * k;
let steps = s.active().unwrap().history.past_len();
// The Fade dialog's preview (#8230) shows the channel as OK leaves it.
let preview = fade_preview(&s, &json!({"opacity": opacity})).and_then(FadePreview::render).unwrap();
let shown = if quick_mask { preview.quick_mask.as_ref() } else { preview.channels.first() }.unwrap().surface.pixel(5, 5)[0];
s.execute("edit.fade", json!({"opacity": opacity})).unwrap();
assert_eq!(shown, channel(&s, 5, 5), "depth {depth}, quick mask {quick_mask}, {opacity} %: the preview is what OK applies");
for (x, y) in [(0, 0), (5, 5), (63, 47)] {
let v = channel(&s, x, y);
assert!((v - expected).abs() < 0.02, "depth {depth}, quick mask {quick_mask}, {opacity} %, ({x}, {y}): {v}");
+9 -1
View File
@@ -101,7 +101,15 @@ pub fn specs() -> Vec<CommandSpec> {
}
Ok(Value::Null)
}),
spec!("select.findLayers", "Find Layers", &["Select"], Some("Cmd+Alt+Shift+F"), r##"{"name":str (case-insensitive substring)}"##, has_doc, find_layers),
spec!(
"select.findLayers",
"Find Layers",
&["Select"],
Some("Cmd+Alt+Shift+F"),
r##"{"name":str?} (filters the Layers panel by Name, a case-insensitive substring, selecting none of the matches; without `name` the panel's Name text is kept; replies with the matching layers)"##,
has_doc,
find_layers
),
spec!("layer.selectLinkedLayers", "Select Linked Layers", &["Layer"], None, "{}", has_linked, |s, _| select_linked(s)),
spec!("layer.align.topEdges", "Top Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "topEdges")),
spec!("layer.align.verticalCenters", "Vertical Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "verticalCenters")),
@@ -336,16 +336,27 @@ pub(super) fn select_all_layers(s: &mut Session) -> Result<Value> {
Ok(json!({"selected": n}))
}
/// Select › Find Layers (#10884): as in Photoshop it filters the Layers panel by Name and leaves the
/// layer selection alone. The reply's `layerFilter` is the Name filter the app applies (`name` only
/// when one is given) and `selected` lists the layers it matches: part of the name, trimmed and
/// ignoring case, as the panel matches: every layer for a blank name, which the panel doesn't filter
/// by (none without a name).
pub(super) fn find_layers(s: &mut Session, p: &Value) -> Result<Value> {
let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase();
let name = match p.get("name") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_str().ok_or_else(|| bad("select.findLayers", "`name` must be a string"))?),
};
let d = s.active().ok_or(EngineError::NoDocument)?;
let ids: Vec<LayerId> = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect();
if ids.is_empty() {
return Err(EngineError::Other(format!("no layer name contains \"{needle}\"")));
let needle = name.map(|n| n.trim().to_lowercase());
let ids: Vec<u64> = match &needle {
Some(n) => d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(n.as_str())).map(|(_, _, l)| l.id.0).collect(),
None => Vec::new(),
};
let mut filter = json!({"by": "name"});
if let Some(n) = name {
filter["name"] = json!(n);
}
let out = ids.iter().map(|l| l.0).collect::<Vec<_>>();
set_selection(s, ids, None, None)?;
Ok(json!({"selected": out}))
Ok(json!({"selected": ids, "layerFilter": filter}))
}
pub(super) fn select_linked(s: &mut Session) -> Result<Value> {
@@ -586,9 +586,23 @@ fn find_layers_by_name() {
s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap();
s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap();
assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo");
let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap();
assert_eq!(r["selected"], json!([a.0, b.0]));
assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err());
// #10884: Find Layers filters the Layers panel by Name and leaves the selection alone.
s.execute("layer.select", json!({"layer": a.0})).unwrap();
let r = s.execute("select.findLayers", json!({"name": " PHOTO "})).unwrap();
assert_eq!(r["selected"], json!([a.0, b.0]), "the matching layers, trimmed and ignoring case");
assert_eq!(r["layerFilter"], json!({"by": "name", "name": " PHOTO "}), "the app sets the Name text as given");
assert_eq!(s.active().unwrap().selected_layers(), [a], "the selection is unchanged");
let r = s.execute("select.findLayers", json!({"name": "nothing"})).unwrap();
assert_eq!(r["selected"], json!([]), "no match lists nothing and is no error");
let all: Vec<u64> = doc(&s).walk().into_iter().map(|(_, _, l)| l.id.0).collect();
for blank in ["", " "] {
let r = s.execute("select.findLayers", json!({"name": blank})).unwrap();
assert_eq!(r["selected"], json!(all), "a blank name filters nothing, as in the panel: {blank:?}");
}
let r = s.execute("select.findLayers", json!({})).unwrap();
assert_eq!((&r["selected"], &r["layerFilter"]), (&json!([]), &json!({"by": "name"})), "without a name it only switches to Name");
assert_eq!(s.active().unwrap().selected_layers(), [a]);
assert!(s.execute("select.findLayers", json!({"name": 3})).is_err());
assert!(s.execute("layer.renameLayer", json!({})).is_err());
}
@@ -129,7 +129,7 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) ->
// Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.
let extent = canvas.union(&placed.content_bounds());
for f in sm.smart_filters.iter().filter(|f| f.visible) {
cur = apply_smart_filter(f, &cur, filter_bounds(f, placed, canvas), extent, &JobCtx::new())?;
cur = apply_smart_filter(f, sm, &cur, filter_bounds(f, placed, canvas), extent, &JobCtx::new())?;
}
Ok(match sm.filter_mask.as_ref().filter(|m| m.enabled) {
Some(m) => photocraft_compose::filter_mask::mix(placed, &cur, m),
@@ -155,8 +155,9 @@ fn renders_in_object(f: &SmartFilter) -> bool {
/// One visible smart filter over `cur`, blended with its blend mode and opacity. `Err` when the
/// requesting session's authority denies the filter's params: callers surface the error instead of
/// rendering (and caching) unfiltered pixels.
fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect, ctx: &JobCtx) -> Result<Surface> {
let out = match crate::filters::apply_filter_to_surface_in(&f.command, &f.params, cur, canvas, None, extent, ctx)? {
fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas: Rect, extent: Rect, ctx: &JobCtx) -> Result<Surface> {
let params = crate::distort_cmds::placed_puppet_params(&f.command, &f.params, sm);
let out = match crate::filters::apply_filter_to_surface_in(&f.command, &params, cur, canvas, None, extent, ctx)? {
// Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone.
Some(out) => out,
None => cur.clone(),
@@ -367,7 +368,7 @@ pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Resul
Some(b) => b,
None => *object_bounds.insert(filter_bounds(f, &placed()?.surface, canvas)),
};
cur = Stage { surface: apply_smart_filter(f, &cur.surface, bounds, cur.extent, ctx)?, extent: cur.extent };
cur = Stage { surface: apply_smart_filter(f, sm, &cur.surface, bounds, cur.extent, ctx)?, extent: cur.extent };
stack_cache::put(*key, &cur);
}
ctx.progress(1.0, "");
+11
View File
@@ -230,6 +230,17 @@ pub fn specs() -> Vec<CommandSpec> {
run: |s, p| path_to_selection_with_mode(s, p, "subtract"),
journal: true,
},
// ⇧⌥⌘↩ / Ctrl+Alt+Shift+Enter intersects the path with the selection (#7726).
CommandSpec {
id: "path.intersectWithSelection",
label: "Intersect Path with Selection",
menu: &[],
shortcut: Some("Cmd+Alt+Shift+Enter"),
params: r##"{"name":str|"work"|"layer"="work","feather":px=0,"antiAlias":bool=true} (path.toSelection with mode "intersect")"##,
enabled: has_doc,
run: |s, p| path_to_selection_with_mode(s, p, "intersect"),
journal: true,
},
spec!(
"path.toShape",
"Make Shape from Path",
+2 -1
View File
@@ -371,7 +371,8 @@ pub(super) fn path_to_selection(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "selected": selected }))
}
/// `path.toSelection` with the combine mode fixed by the command (⌘⇧↩ adds, ⌘⌥↩ subtracts);
/// `path.toSelection` with the combine mode fixed by the command (⌘⇧↩ adds, ⌘⌥↩ subtracts,
/// ⇧⌥⌘↩ intersects);
/// a `mode` in the params is overridden, the rest is forwarded and validated as usual.
pub(super) fn path_to_selection_with_mode(s: &mut Session, p: &Value, mode: &str) -> Result<Value> {
let mut q = match p {
@@ -568,6 +568,26 @@ fn open_pen_paths_make_the_same_selection_as_closed_paths() {
}
}
/// ⇧⌘↩, ⌥⌘↩ and ⇧⌥⌘↩'s commands are Make Selection from Path with their mode (#7726), whatever
/// `mode` the params ask for.
#[test]
fn the_fixed_mode_path_commands_combine_as_their_mode() {
let mut s = session(80, 80, 8);
let square = |x: f64| path_json(&vector::shapes::rect(x, 20.0, 30.0, 30.0));
s.execute("path.set", json!({"name": "Sq", "path": square(30.0)})).unwrap();
for (id, mode) in [("path.addToSelection", "add"), ("path.subtractFromSelection", "subtract"), ("path.intersectWithSelection", "intersect")] {
s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 30, "antiAlias": false})).unwrap();
s.execute("path.toSelection", json!({"name": "Sq", "mode": mode, "antiAlias": false})).unwrap();
let want = selection_mask(&s);
s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 30, "antiAlias": false})).unwrap();
s.execute(id, json!({"name": "Sq", "mode": "replace", "antiAlias": false})).unwrap();
assert_eq!(selection_mask(&s), want, "{id} is mode {mode}");
}
// Intersecting keeps only the 10 px both squares cover.
let mask = selection_mask(&s);
assert_eq!(mask.iter().filter(|v| **v > 0.5).count(), 10 * 30);
}
#[test]
fn selection_to_work_path_roundtrip_iou() {
let mut s = session(240, 180, 8);
+1 -1
View File
@@ -200,7 +200,7 @@ pub struct ToolState {
impl ToolState {
/// How many CMYK picks are remembered.
const CMYK_PICKS: usize = 8;
pub const CMYK_PICKS: usize = 8;
/// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1).
pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) {
+11 -4
View File
@@ -507,9 +507,9 @@ struct Running {
label: String,
params: Value,
journal: bool,
/// The recording (`ActionState::take`) running when the job started, if any (set by
/// `dispatch`, once recording resumes). Only that recording gets the job's step: one started
/// later must not pick up an edit made before it.
/// The take active at dispatch, including strokes started with tool recording off.
started_in_take: Option<u64>,
/// The take eligible to receive this job's step under the mode at dispatch.
recorded_by: Option<u64>,
pre_selected: Option<Vec<LayerId>>,
before: crate::actions_record::Before,
@@ -863,6 +863,7 @@ fn new_job<T: Send + 'static>(
label: label.to_string(),
params: Value::Null,
journal: true,
started_in_take: None,
recorded_by: None,
pre_selected: None,
before: crate::actions_record::Before::capture(s),
@@ -1031,6 +1032,11 @@ pub struct PendingPsdPreflight {
}
impl Session {
/// A recording mode change must not reclassify an in-flight stroke from this take.
pub(crate) fn tool_stroke_job_running(&self) -> bool {
self.jobs.running.iter().any(|job| job.started_in_take == Some(self.actions.take) && crate::actions_cmds::tool_stroke(&job.command))
}
/// Run the heavy part of inline (not background) job commands under `ctx`, so another thread
/// can cancel them: a live preview whose parameters changed stops its stale computation
/// (`Err(Cancelled)`, the document unchanged) instead of finishing it. `None` restores the
@@ -1814,7 +1820,8 @@ impl Session {
job.command = id.to_string();
job.params = params;
job.journal = spec.journal;
job.recorded_by = self.actions.recording.map(|_| self.actions.take);
job.started_in_take = self.actions.recording.map(|_| self.actions.take);
job.recorded_by = job.started_in_take.filter(|_| self.actions.record_tools || !crate::actions_cmds::tool_stroke(id));
job.pre_selected = pre_selected.clone();
job.before = std::mem::take(&mut record_before);
let jid = job.id;
+75
View File
@@ -188,6 +188,78 @@ impl Unit {
let unit = if suffix.is_empty() { None } else { Some(Unit::from_suffix(suffix)?) };
Some((v, unit))
}
/// A length typed as Photoshop's numeric fields take arithmetic (#10440): lengths and numbers
/// joined by `+`, `-`, `*` and `/`, e.g. "100% / 3", "100% - 50px", "1in + 10", "2 * 50 px".
/// `*` and `/` bind tighter, and `−` (U+2212) is a minus. A number without a unit added or
/// subtracted takes the first operand's unit (Photoshop: "1in + 10" is 11 in), or `default`
/// when the first has none; one multiplied or divided is a plain number. `to_px` converts a
/// value in a unit. `None` when the text is over 1024 bytes (the numeric fields' cap) or isn't
/// such an expression, multiplies two lengths, divides by a length or by zero, or the result
/// isn't finite.
pub fn eval_length(text: &str, default: Unit, to_px: impl Fn(f64, Unit) -> f64) -> Option<f64> {
if text.len() > 1024 {
return None;
}
let text = text.replace('−', "-");
// Tokens: operators, and operands (a number with an optional unit suffix).
let mut ops = Vec::new();
let mut operands: Vec<(f64, Option<Unit>)> = Vec::new();
let mut rest = text.trim();
let mut want_operand = true;
while !rest.is_empty() {
if want_operand {
let num_end = rest
.char_indices()
.find(|&(i, c)| !(c.is_ascii_digit() || matches!(c, '.' | ',') || (i == 0 && matches!(c, '-' | '+'))))
.map_or(rest.len(), |(i, _)| i);
let after = &rest[num_end..];
let unit_end = after.find(['+', '-', '*', '/']).unwrap_or(after.len());
let (v, unit) = Unit::parse_length(&rest[..num_end + unit_end])?;
operands.push((v, unit));
rest = after[unit_end..].trim_start();
want_operand = false;
} else {
let op = rest.chars().next()?;
if !matches!(op, '+' | '-' | '*' | '/') {
return None;
}
ops.push(op);
rest = rest[1..].trim_start();
want_operand = true;
}
}
if want_operand || operands.is_empty() {
return None;
}
let first_unit = operands[0].1.unwrap_or(default);
// Fold the products and quotients into terms: (sum of px for unit factors, scalar, has a unit).
let mut terms: Vec<(char, f64, Option<Unit>)> = Vec::new();
let (mut sign, mut value, mut unit) = ('+', operands[0].0, operands[0].1);
for (op, (v, u)) in ops.iter().zip(operands.iter().skip(1)) {
match op {
'*' => {
if unit.is_some() && u.is_some() {
return None;
}
value *= v;
unit = unit.or(*u);
}
'/' => {
if u.is_some() || *v == 0.0 {
return None;
}
value /= v;
}
_ => {
terms.push((sign, value, unit));
(sign, value, unit) = (*op, *v, *u);
}
}
}
terms.push((sign, value, unit));
let px: f64 = terms.iter().map(|&(s, v, u)| if s == '-' { -1.0 } else { 1.0 } * to_px(v, u.unwrap_or(first_unit))).sum();
px.is_finite().then_some(px)
}
/// The unit a typed suffix names, in any case: `px`, `in` or `"`, `cm`, `mm`, `pt`, `pc` or
/// `pica`, `%`, and their long forms (`pixels`, `inches`, `centimetres`…). The one table every
/// length field reads.
@@ -1301,6 +1373,9 @@ pub struct Preferences {
/// Last selected tool, restored at launch. A tool-name string owned and validated by the
/// shell; null in older files. Kept separate from tool options so neither overwrites the other.
pub selected_tool: Value,
/// Foreground/background swatches for pixels and masks and exact CMYK picks, restored by the shell at launch.
/// Null in older files, which retain the default black/white pixel colours.
pub tool_colors: Value,
/// The tools used last, most recent first, restored at launch so each toolbar slot shows the
/// tool it was left on and each tool key brings it back, as in Photoshop (#3569). Tool-name
/// strings owned and validated by the shell; null in older files.
+55
View File
@@ -612,6 +612,61 @@ fn tool_presets_save_filter_select() {
assert!(s.execute("tool.presets.new", json!({"name": "x"})).is_err());
}
#[test]
fn tool_presets_reject_invalid_colors_before_applying_the_brush() {
let mut invalid = vec![
json!(null),
json!(true),
json!(7),
json!("red"),
json!({}),
json!([]),
json!([1]),
json!([1, 0]),
json!([1, 0, 0, 1, 0]),
json!([null, 0.4, 0.6]),
];
for channel in 0..4 {
for bad_channel in [json!(1e100), json!(-1e100), json!(null), json!("red"), json!(true), json!({}), json!([])] {
let mut values = json!([0.2, 0.4, 0.6, 0.8]);
values[channel] = bad_channel;
invalid.push(values);
}
}
for values in invalid {
let mut s = Session::new();
s.execute("tools.setColors", json!({"foreground": [0.2, 0.4, 0.6, 0.8]})).unwrap();
let color = s.tools.foreground;
let brush = s.tools.brush.clone();
let brush_rev = s.tools.brush_rev;
s.execute(
"tool.presets.new",
json!({
"name": "Invalid", "tool": "brush", "options": {"brush": {"size": 77}, "foreground": values}
}),
)
.unwrap();
assert!(s.execute("tool.presets.select", json!({"preset": "Invalid"})).is_err(), "{values}");
assert_eq!(s.tools.foreground, color, "{values}");
assert_eq!(s.tools.brush, brush, "{values}");
assert_eq!(s.tools.brush_rev, brush_rev, "{values}");
}
}
#[test]
fn tool_presets_keep_finite_hdr_colors_and_leave_absent_colors_unchanged() {
let mut s = Session::new();
for (options, expected) in [
(json!({"foreground": [1.5, -0.1, 0.6, 0.8]}), [1.5, -0.1, 0.6, 0.8]),
(json!({"foreground": [0.2, 0.4, 0.6]}), [0.2, 0.4, 0.6, 1.0]),
(json!({}), [0.2, 0.4, 0.6, 1.0]),
] {
let preset = s.execute("tool.presets.new", json!({"tool": "move", "options": options})).unwrap();
s.execute("tool.presets.select", json!({"preset": preset["name"]})).unwrap();
assert_eq!(s.tools.foreground, expected);
}
}
/// An Art History Brush preset captures the brush's opacity and selecting it restores it.
#[test]
fn art_history_brush_preset_carries_the_opacity() {
+12 -4
View File
@@ -158,13 +158,21 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
.find(|t| t.name == name)
.cloned()
.ok_or_else(|| bad(CMD, format!("no tool preset \"{name}\" (see tool.presets.list)")))?;
// Validate before applying the brush too: an invalid colour must leave the preset unapplied.
let foreground = match t.options.get("foreground") {
None => s.tools.foreground,
Some(value) => {
let valid = value.as_array().is_some_and(|channels| matches!(channels.len(), 3 | 4) && channels.iter().all(Value::is_number));
if !valid {
return Err(bad(CMD, "`foreground` must be [r, g, b] or [r, g, b, a] numbers"));
}
crate::commands::color_param(CMD, &t.options, "foreground", s.tools.foreground)?
}
};
if let Some(b) = t.options.get("brush").filter(|b| b.is_object()) {
super::call(s, "tools.setBrush", json!({"brush": b}))?;
}
if let Some(c) = t.options.get("foreground").and_then(Value::as_array).filter(|a| a.len() >= 3) {
let v: Vec<f32> = c.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
s.tools.foreground = [v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)];
}
s.tools.foreground = foreground;
Ok(json!({"name": t.name, "tool": t.tool, "options": t.options}))
}
@@ -125,7 +125,7 @@ fn native_default_is_written_explicitly_and_keeps_its_behavior() {
}
}
/// Unsupported flags and empty steps remain complete descriptors instead of becoming resizes.
/// Only an absent descriptor is menu intent. Empty or invalid descriptors remain kept steps.
#[test]
fn malformed_or_empty_steps_are_kept_without_becoming_resizes() {
for event in ["ImgS", "imageSize"] {
@@ -143,12 +143,20 @@ fn malformed_or_empty_steps_are_kept_without_becoming_resizes() {
let original = atn::parse(&source).unwrap();
let mut s = Session::new();
let loaded = load(&mut s, &source);
assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1);
assert_eq!(s.actions.list[0].steps.len(), 1);
assert_eq!(s.actions.list[0].steps[0].0, atn_cmds::PHOTOSHOP_STEP);
let (step, params) = &s.actions.list[0].steps[0];
if original.actions[0].items[0].descriptor.is_none() {
assert_eq!(loaded["unsupported"], json!([]));
assert_eq!(step, atn_cmds::MENU_ITEM);
assert_eq!(params["id"], "image.imageSize");
assert_eq!(params["eventKind"], if event == "ImgS" { "code" } else { "name" });
} else {
assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1);
assert_eq!(step, atn_cmds::PHOTOSHOP_STEP);
}
let saved = atn::parse(&save(&mut s)).unwrap();
assert_eq!(saved.actions[0].items[0].descriptor, original.actions[0].items[0].descriptor);
assert_eq!(saved.actions[0].items[0].event, original.actions[0].items[0].event);
assert_eq!(saved.actions[0].items[0].dictionary, original.actions[0].items[0].dictionary);
}
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Duplicate keeps action identities, complete settings and per-step flags stable.
use photocraft_engine::{Session, actions_cmds::Action};
use serde_json::{Value, json};
/// A tiny document to distinguish definition edits from document mutations and playback.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
s
}
#[test]
fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() {
let mut s = session();
let mut source = Action::new("Source", vec![("actions.play".into(), json!({"action": 1})), ("layer.select".into(), json!({"layer": "Photo"}))]);
source.disabled.insert(1);
source.dialogs.insert(0);
source.set = Some("Retouch".into());
source.color = "red".into();
let foreign = json!({"actions": [{"name": "Foreign", "steps": [["actions.play", {"action": 1}]]}]});
s.actions.list = vec![
source.clone(),
Action::new("Target", vec![("select.all".into(), json!({}))]),
Action::new(
"Caller",
vec![
("actions.play".into(), json!({"action": 1})),
("actions.play".into(), json!({"action": 3})), // Unresolved before and after insertion.
("actions.play".into(), json!({"action": 1.0})),
("file.automate.batch".into(), foreign.clone()),
("actions.conditional".into(), json!({"if": "always", "then": "Target", "else": "Source"})),
],
),
];
s.prefs.edit(|p| {
p.shortcuts.insert("actions.play:Source".into(), "F6".into());
});
let revision = s.active().unwrap().revision;
let result = s.execute("actions.duplicate", json!({"action": "Source"})).unwrap();
assert_eq!(result["index"], 1);
assert_eq!(s.actions.list.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Source", "Source copy", "Target", "Caller"]);
let mut expected = source;
expected.name = "Source copy".into();
expected.steps[0].1["action"] = json!(2);
assert_eq!(s.actions.list[1], expected);
assert_eq!(s.actions.list[0].steps[0].1["action"], 2);
let caller = &s.actions.list[3];
assert_eq!(caller.steps[0].1["action"], 2);
assert_eq!(caller.steps[1].1["action"], 4);
assert_eq!(caller.steps[2].1["action"], 2.0);
assert_eq!(caller.steps[3].1, foreign, "embedded libraries keep their own indices");
assert_eq!(caller.steps[4].1, json!({"if": "always", "then": "Target", "else": "Source"}));
assert_eq!(s.prefs().shortcuts.get("actions.play:Source").map(String::as_str), Some("F6"));
assert!(!s.prefs().shortcuts.contains_key("actions.play:Source copy"));
assert_eq!(s.active().unwrap().revision, revision);
let played = s.execute("actions.play", json!({"action": "Source copy"})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert!(s.active().unwrap().doc.selection.is_some(), "the copied call still plays Target rather than itself");
s.execute("actions.duplicate", json!({"action": 0})).unwrap();
assert_eq!(s.actions.list[1].name, "Source copy 2");
assert_eq!(s.actions.list[2].name, "Source copy");
assert_eq!(s.actions.list[1].steps[0].1["action"], 3);
}
#[test]
fn step_copies_preserve_payloads_and_shift_both_flag_columns() {
let mut s = session();
let payload = json!({"layer": "Photo", "_actionLayer": {"name": "Photo", "ordinal": 2}});
let mut a = Action::new("Steps", vec![("layer.select".into(), payload.clone()), ("select.all".into(), Value::Null), ("select.deselect".into(), json!({}))]);
a.disabled.extend([0, 2]);
a.dialogs.extend([0, 1]);
s.actions.list.push(a);
let revision = s.active().unwrap().revision;
let result = s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap();
assert_eq!(result["step"], 1);
assert_eq!(result["index"], 0);
let a = &s.actions.list[0];
assert_eq!(a.name, "Steps");
assert_eq!(a.steps[0], a.steps[1]);
assert_eq!(a.disabled.iter().copied().collect::<Vec<_>>(), [0, 1, 3]);
assert_eq!(a.dialogs.iter().copied().collect::<Vec<_>>(), [0, 1, 2]);
s.execute("actions.duplicate", json!({"action": 0, "step": 2})).unwrap();
assert!(s.actions.list[0].steps[2].1.is_null());
assert!(s.actions.list[0].steps[3].1.is_null(), "copying does not normalize null settings to an empty object");
s.actions.list[0].steps[1].1["layer"] = json!(99);
assert_eq!(s.actions.list[0].steps[0].1, payload, "the copy owns its settings");
assert_eq!(s.active().unwrap().revision, revision);
}
#[test]
fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() {
let mut s = session();
s.execute("actions.record", json!({"name": "Recording"})).unwrap();
s.execute("select.all", json!({})).unwrap();
let before = s.actions.list.clone();
let recording = s.actions.recording;
let revision = s.active().unwrap().revision;
for params in [
json!({}),
json!({"action": 9}),
json!({"action": 0}),
json!({"action": 0, "step": -1}),
json!({"action": 0, "step": 5}),
json!({"action": 0, "step": "x"}),
] {
assert!(s.execute("actions.duplicate", params.clone()).is_err(), "{params}");
assert_eq!(s.actions.list, before);
assert_eq!(s.actions.recording, recording);
assert_eq!(s.active().unwrap().revision, revision);
}
s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap();
assert_eq!(s.actions.list[0].steps, vec![("select.all".into(), json!({})); 2]);
assert!(s.actions.recording.is_some());
s.execute("select.deselect", json!({})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
assert_eq!(s.actions.list[0].steps.len(), 3);
s.actions.list.push(Action::new("Edit during playback", vec![("actions.duplicate".into(), json!({"action": 0}))]));
let before = s.actions.list.clone();
let played = s.execute("actions.play", json!({"action": "Edit during playback"})).unwrap();
assert!(played["failed"]["error"].as_str().is_some_and(|e| e.contains("playback")), "{played}");
assert_eq!(s.actions.list, before);
}
@@ -0,0 +1,200 @@
//! The remaining panel commands compose with the same definitions, journal and ATN boundary.
use photocraft_engine::{Session, actions_cmds::Action, actions_edit_cmds, atn_cmds, jobs::Started};
use serde_json::json;
/// Tiny real document with one empty action keeps recording and background jobs observable.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width":40,"height":30})).unwrap();
s.actions.list.push(Action::new("A", vec![]));
s
}
/// A painted stripe gives both the remove tool and blur a real input before recording starts.
fn stroke(s: &mut Session, color: &str) {
s.execute("paint.stroke", json!({"points":[[8,15],[32,15]],"size":3,"color":color})).unwrap();
}
/// Mode changes flush under the previous mode without altering painting or ordinary recording.
#[test]
fn tool_recording_is_opt_in_and_toggles_do_not_reclassify_pending_steps() {
let mut s = session();
s.execute("actions.record", json!({"action":"A"})).unwrap();
stroke(&mut s, "#ff0000");
s.execute("select.all", json!({})).unwrap();
let original = s.actions.clone();
assert!(s.execute("actions.allowToolRecording", json!({"enabled":"yes"})).is_err());
assert_eq!(s.actions, original, "invalid mode must not flush pending work");
s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap();
stroke(&mut s, "#00ff00");
s.execute("actions.allowToolRecording", json!({"enabled":false})).unwrap();
stroke(&mut s, "#0000ff");
s.execute("select.deselect", json!({})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
assert_eq!(s.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["select.all", "paint.stroke", "select.deselect"]);
assert_eq!(s.actions.list[0].steps[1].1["color"], "#00ff00");
assert_eq!(s.journal.iter().filter(|s| s.0 == "paint.stroke").count(), 3, "all actual painting remains journaled");
assert_eq!(s.execute("actions.list", json!({})).unwrap()["toolRecording"], false);
}
/// A stroke started while off never joins a later enabled recording; ordinary jobs keep their owner.
#[test]
fn background_stroke_ownership_does_not_suppress_ordinary_filter_jobs() {
for command in ["paint.remove", "filter.blur.gaussianBlur"] {
let mut s = session();
stroke(&mut s, "#bb3300");
s.execute("actions.record", json!({"action":"A"})).unwrap();
let params = if command == "paint.remove" { json!({"points":[[20,15],[21,15]],"size":3}) } else { json!({"radius":1}) };
let Started::Job(job) = s.start(command, params).unwrap() else { panic!("expected the real background job: {command}") };
let changed = s.execute("actions.allowToolRecording", json!({"enabled":true}));
if command == "paint.remove" {
assert!(changed.is_err(), "the in-flight stroke retains the mode it started under");
assert!(!s.actions.record_tools);
} else {
changed.unwrap();
}
s.wait_job(job).unwrap();
if command == "paint.remove" {
s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap();
}
s.execute("actions.stop", json!({})).unwrap();
let ids = s.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::<Vec<_>>();
if command == "paint.remove" {
assert!(ids.is_empty());
} else {
assert_eq!(ids, [command]);
}
}
}
/// A Remove job started outside the current take neither blocks its toggle nor joins its steps.
#[test]
fn background_strokes_from_outside_the_current_take_do_not_block_the_toggle() {
for previous_take in [false, true] {
let mut s = session();
stroke(&mut s, "#bb3300");
if previous_take {
s.execute("actions.record", json!({"action":"A"})).unwrap();
s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap();
}
let Started::Job(job) = s.start("paint.remove", json!({"points":[[20,15],[21,15]],"size":3})).unwrap() else {
panic!("expected the real Remove job");
};
if previous_take {
s.execute("actions.stop", json!({})).unwrap();
s.execute("actions.allowToolRecording", json!({"enabled":false})).unwrap();
}
s.execute("actions.record", json!({"action":"A"})).unwrap();
assert_eq!(s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap()["enabled"], true);
s.wait_job(job).unwrap();
s.execute("actions.stop", json!({})).unwrap();
assert!(s.actions.list[0].steps.is_empty());
assert_eq!(s.journal.iter().filter(|step| step.0 == "paint.remove").count(), 1);
}
}
/// Interleaved membership and numeric calls expose incorrect folder placement or target rewriting.
#[test]
fn set_duplication_preserves_metadata_call_targets_and_empty_folder_order() {
let mut s = session();
s.actions.list.clear();
for (name, set) in [("A", "S"), ("Other", "T"), ("B", "S")] {
let mut a = Action::new(name, vec![("actions.play".into(), json!({"action":2}))]);
a.set = Some(set.into());
a.color = "red".into();
a.disabled.insert(0);
a.dialogs.insert(0);
s.actions.list.push(a);
}
s.prefs.edit(|p| {
p.shortcuts.insert("actions.play:A".into(), "F5".into());
});
let result = s.execute("actions.duplicate", json!({"set":"S"})).unwrap();
assert_eq!(result["set"], "S copy");
assert_eq!(actions_edit_cmds::set_names(&s), ["S", "S copy", "T"]);
assert_eq!(s.actions.list.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["A", "A copy", "B copy", "Other", "B"]);
for a in &s.actions.list {
assert_eq!(a.steps[0].1["action"], 4);
assert_eq!(a.color, "red");
assert!(a.disabled.contains(&0));
assert!(a.dialogs.contains(&0));
}
assert!(!s.prefs().shortcuts.contains_key("actions.play:A copy"));
let mut empty = Session::new();
for name in ["E", "F"] {
empty.execute("actions.newSet", json!({"name":name})).unwrap();
}
empty.execute("actions.duplicate", json!({"set":"E"})).unwrap();
assert_eq!(actions_edit_cmds::set_names(&empty), ["E", "E copy", "F"]);
let original = empty.actions.clone();
for params in [json!({"set":"Missing"}), json!({"set":"E","action":0}), json!({"set":false})] {
assert!(empty.execute("actions.duplicate", params).is_err());
assert_eq!(empty.actions, original);
}
}
/// Menu insertion keeps descriptor absence and kind; empty descriptors and ambiguous commands differ.
#[test]
fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() {
assert!(!atn_cmds::menu_item_needs_settings("filter.noise.despeckle"));
assert!(atn_cmds::menu_item_needs_settings("filter.blur.gaussianBlur"));
for id in ["image.imageSize", "filter.blur.gaussianBlur", "filter.noise.despeckle"] {
for kind in ["name", "code"] {
let mut s = session();
s.execute("actions.insertMenuItem", json!({"action":"A","id":id,"eventKind":kind})).unwrap();
let bytes = atn_cmds::export("S", &[&s.actions.list[0]], &[], false).unwrap().0;
let raw = photocraft_psd::atn::parse(&bytes).unwrap();
assert!(raw.actions[0].items[0].descriptor.is_none());
let imported = atn_cmds::import(&bytes).unwrap();
let (step, params) = &imported.actions[0].steps[0];
assert_eq!(step, atn_cmds::MENU_ITEM);
assert_eq!(params["id"], id);
assert_eq!(params["eventKind"], kind);
let (saved, skipped) = atn_cmds::export("S", &[&imported.actions[0]], &[], false).unwrap();
assert!(skipped.is_empty());
let saved = photocraft_psd::atn::parse(&saved).unwrap();
assert_eq!(saved.actions[0].items[0], raw.actions[0].items[0]);
let played = s.execute("actions.play", json!({"action":"A"})).unwrap();
assert_eq!(played.get("failed").is_none(), !atn_cmds::menu_item_needs_settings(id), "{id}: {played}");
}
}
let mut s = session();
let original = s.actions.clone();
for params in
[json!({"action":"A","id":"layer.setProps"}), json!({"action":"A","id":"file.open"}), json!({"action":"A","id":"image.imageSize","params":{"width":4}})]
{
assert!(s.execute("actions.insertMenuItem", params).is_err());
assert_eq!(s.actions, original);
}
let mut raw = photocraft_psd::atn::AtnFile::default();
raw.actions.push(photocraft_psd::atn::AtnAction {
items: vec![photocraft_psd::atn::AtnItem {
event: photocraft_psd::atn::AtnEvent::name("gaussianBlur"),
descriptor: Some(photocraft_psd::descriptor::Descriptor::new("null")),
..Default::default()
}],
..Default::default()
});
let loaded = atn_cmds::import(&photocraft_psd::atn::write(&raw).unwrap()).unwrap();
assert_eq!(loaded.actions[0].steps[0].0, "filter.blur.gaussianBlur");
}
/// A full curve is snapshotted independently of later source edits and replays as the work path.
#[test]
fn insert_path_captures_cubic_geometry_without_editing_the_document() {
let mut s = session();
let path = json!({"fillRule":"evenodd","inverted":true,"subpaths":[{"closed":false,"op":"combine","knots":[{"anchor":[1.5,2.25],"in":[-1.0,3.0],"out":[5.0,8.0],"smooth":true},{"anchor":[20.0,18.0],"in":[12.0,5.0],"out":[21.0,19.0]}]}]});
s.execute("path.set", json!({"name":"Curve","path":path})).unwrap();
let expected = s.execute("path.info", json!({"name":"Curve"})).unwrap()["path"].clone();
let revision = s.active().unwrap().revision;
assert!(s.execute("actions.insertPath", json!({"action":"A","name":"work"})).is_err());
assert!(s.actions.list[0].steps.is_empty());
s.execute("actions.insertPath", json!({"action":"A","name":"Curve"})).unwrap();
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(s.actions.list[0].steps[0].1["path"], expected);
s.execute("path.set", json!({"name":"Curve","path":{"subpaths":[]}})).unwrap();
let played = s.execute("actions.play", json!({"action":"A"})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(s.execute("path.info", json!({"name":"work"})).unwrap()["path"], expected);
assert!(atn_cmds::export("S", &[&s.actions.list[0]], &[], false).is_err(), "the measured ATN descriptor cannot represent inversion");
}
@@ -0,0 +1,77 @@
//! Record Again edits one definition only after its concrete command succeeds.
use photocraft_engine::{EngineError, Session, actions_cmds::Action, atn_cmds};
use serde_json::{Value, json};
/// A disabled, dialog-enabled resize followed by another step exposes flag and ordering loss.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
let mut a = Action::new("A", vec![("image.imageSize".into(), json!({"width": 4, "height": 3, "resample": "nearest"})), ("select.all".into(), json!({}))]);
a.disabled.insert(0);
a.dialogs.insert(0);
s.actions.list.push(a);
s
}
/// Only the selected step runs, retains its flags, and exports its new settings to ATN.
#[test]
fn successful_rerecording_updates_one_step_and_roundtrips_new_settings() {
for menu in [false, true] {
let mut s = session();
if menu {
s.actions.list[0].steps[0] = (atn_cmds::MENU_ITEM.into(), json!({"id": "image.imageSize"}));
}
let revision = s.actions.rev;
s.execute("actions.recordAgain", json!({"action": "A", "step": 0, "revision": revision, "params": {"width": 6, "height": 5, "resample": "nearest"}}))
.unwrap();
assert_eq!(s.active().unwrap().doc.size, photocraft_engine::doc::Size::new(6, 5));
assert!(s.active().unwrap().doc.selection.is_none(), "the following step did not play");
let a = &s.actions.list[0];
assert_eq!(a.steps.len(), 2);
assert_eq!(a.steps[0].0, "image.imageSize");
assert_eq!(a.steps[0].1["width"], 6);
assert!(a.disabled.contains(&0));
assert!(a.dialogs.contains(&0));
assert_eq!(s.actions.rev, revision + 1);
assert_eq!(s.journal.last().unwrap().0, "image.imageSize");
let bytes = atn_cmds::export("Set", &[a], &[], false).unwrap().0;
let loaded = atn_cmds::import(&bytes).unwrap();
assert_eq!(loaded.actions[0].steps[0].1["width"].as_f64(), Some(6.0));
assert!(loaded.actions[0].disabled.contains(&0));
assert!(loaded.actions[0].dialogs.contains(&0));
}
}
/// Permit the wrapper while denying its concrete edit, proving nested authorization remains active.
fn deny_resize(id: &str, _: &Value) -> photocraft_engine::Result<()> {
if id == "image.imageSize" { Err(EngineError::Other("resize denied".into())) } else { Ok(()) }
}
/// Invalid settings, stale selections, denied execution and recording preserve the original step.
#[test]
fn failed_or_stale_rerecording_never_replaces_the_original_step() {
let mut s = session();
let original = s.actions.list.clone();
let revision = s.active().unwrap().revision;
for request in [
json!({"action":"A","step":0}),
json!({"action":"A","step":0,"params":[]}),
json!({"action":"A","step":0,"params":{"percent":-1}}),
json!({"action":"A","step":99,"params":{}}),
json!({"action":"Missing","step":0,"params":{}}),
json!({"action":"A","step":0,"revision":1,"params":{}}),
] {
assert!(s.execute("actions.recordAgain", request.clone()).is_err(), "{request}");
assert_eq!(s.actions.list, original);
assert_eq!(s.actions.rev, 0);
assert_eq!(s.active().unwrap().revision, revision);
}
s.authorize = Some(deny_resize);
assert!(s.execute("actions.recordAgain", json!({"action":"A","step":0,"params":{"width":6,"height":5}})).is_err());
assert_eq!(s.actions.list, original);
s.authorize = None;
s.execute("actions.record", json!({"action":"A"})).unwrap();
s.execute("select.all", json!({})).unwrap();
assert!(s.execute("actions.recordAgain", json!({"action":"A","step":0,"params":{}})).is_err());
assert_eq!(s.actions.list, original, "recording was not flushed by a refused edit");
}
+3
View File
@@ -1,5 +1,8 @@
//! The crate's integration tests, linked into one test binary.
mod actions_duplicate;
mod actions_panel_menu;
mod actions_record_again;
mod actions_single_history;
mod affinity;
mod artboard_export_names;
+109 -7
View File
@@ -13,13 +13,14 @@
//! (`pixelLength`, `logicalLength`, `logicalUnits`) follow Photoshop's scripting names for the
//! measurement scale; no sample file was available, so parsing is lenient and the raw resource
//! is kept byte-exact while the scale is unchanged.
//! * Count information: image resource 1080 is kept verbatim (its layout is not public) unless
//! the document has its own count markers, which only `.pcraft` stores.
//! * Count information: image resource 1080 (a version-16 `Cnt ` descriptor) maps to the
//! document's ordered Count groups. Unreadable resources are kept while there are no groups.
use std::sync::Arc;
use photocraft_doc::{Color, Document, MeasurementScale, Note};
use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor};
use photocraft_doc::{Color, CountGroup, Document, MeasurementScale, Note};
use photocraft_psd::ImageResource;
use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor};
pub const MEASUREMENT_SCALE: u16 = 1074;
pub const COUNT_INFO: u16 = 1080;
@@ -341,17 +342,118 @@ pub fn fresh_scale_resource(doc: &Document) -> Option<Vec<u8>> {
(!doc.measurement.scale.is_default()).then(|| write_scale_resource(&doc.measurement.scale))
}
/// Decode the measured resource as a whole so unknown or damaged groups stay opaque.
fn count_groups_from_resource(data: &[u8]) -> Option<Vec<CountGroup>> {
let d = VersionedDescriptor::from_bytes(data).ok()?.descriptor;
if !d.class_id.is("Cnt ") || d.items.len() != 2 || d.get("Vrsn") != Some(&Value::Integer(1)) {
return None;
}
let Value::List(groups) = d.get("countGroupList")? else { return None };
groups.iter().map(count_group_from_descriptor).collect()
}
/// Decode the fields the Count tool can use without coercing unrecognized data.
fn count_group_from_descriptor(value: &Value) -> Option<CountGroup> {
let Value::Descriptor(d) = value else { return None };
if !d.class_id.is("countGroup") || d.items.len() != 8 {
return None;
}
let integer = |key| match d.get(key)? {
Value::Integer(n) => u32::try_from(*n).ok(),
_ => None,
};
let channel = |key| u8::try_from(integer(key)?).ok().map(|n| f32::from(n) / 255.0);
let color = Color::rgb(channel("Rd ")?, channel("Grn ")?, channel("Bl ")?);
let Value::Text(name) = d.get("Nm ")? else { return None };
let Value::Boolean(visible) = d.get("Vsbl")? else { return None };
let Value::List(objects) = d.get("countObjectList")? else { return None };
let marker_size = integer("Rds ")?;
let label_size = integer("fontSize")?;
// Keep out-of-range sizes opaque instead of passing them to the marker and text renderers.
if !(1..=10).contains(&marker_size) || !(8..=72).contains(&label_size) {
return None;
}
let name = String::from_utf16(name.0.strip_suffix(&[0]).unwrap_or(&name.0)).ok()?;
let points = objects.iter().map(count_point_from_descriptor).collect::<Option<_>>()?;
Some(CountGroup { name, color, marker_size, label_size, visible: *visible, points })
}
/// Keep document coordinates as doubles and reject nonfinite values.
fn count_point_from_descriptor(value: &Value) -> Option<[f64; 2]> {
let Value::Descriptor(d) = value else { return None };
if !d.class_id.is("countObject") || d.items.len() != 2 {
return None;
}
let (Value::Double(x), Value::Double(y)) = (d.get("X ")?, d.get("Y ")?) else { return None };
(x.is_finite() && y.is_finite()).then_some([*x, *y])
}
/// Consume readable Count data. Keep only opaque bytes when no resource can be read.
pub(crate) fn import_count_resource(doc: &mut Document) {
if let Some(groups) = doc.metadata.psd_resources.iter().filter(|(id, _, _)| *id == COUNT_INFO).find_map(|(_, _, data)| count_groups_from_resource(data)) {
doc.measurement.count_groups = groups;
doc.metadata.psd_resources.retain(|(id, _, _)| *id != COUNT_INFO);
}
}
/// Resource 1080 from the current groups, warning when PSD changes sizes or omits points.
pub(crate) fn fresh_count_resource(doc: &Document, warnings: &mut Vec<String>) -> Option<ImageResource> {
if doc.measurement.count_groups.is_empty() {
return None;
}
let groups = doc.measurement.count_groups.iter().map(|group| count_group_descriptor(group, warnings)).collect();
let d = Descriptor::new("Cnt ").with("Vrsn", Value::Integer(1)).with("countGroupList", Value::List(groups));
Some(ImageResource::new(COUNT_INFO, VersionedDescriptor::new(d).to_bytes()))
}
/// Write the measured group layout and preserve marker order.
fn count_group_descriptor(group: &CountGroup, warnings: &mut Vec<String>) -> Value {
let marker_size = group.marker_size.clamp(1, 10);
let label_size = group.label_size.clamp(8, 72);
if marker_size != group.marker_size || label_size != group.label_size {
warnings.push(format!(
"Count group {:?} sizes adjusted for PSD (marker {} to {marker_size}, label {} to {label_size})",
group.name, group.marker_size, group.label_size
));
}
let [r, g, b, _] = group.color.to_rgba8();
let objects: Vec<_> = group
.points
.iter()
.filter(|[x, y]| x.is_finite() && y.is_finite())
.map(|&[x, y]| Value::Descriptor(Descriptor::new("countObject").with("X ", Value::Double(x)).with("Y ", Value::Double(y))))
.collect();
let omitted = group.points.len() - objects.len();
if omitted != 0 {
warnings.push(format!("Count group {:?} had nonfinite points omitted from PSD export ({omitted} total)", group.name));
}
Value::Descriptor(
Descriptor::new("countGroup")
.with("Rd ", Value::Integer(i32::from(r)))
.with("Grn ", Value::Integer(i32::from(g)))
.with("Bl ", Value::Integer(i32::from(b)))
.with("Nm ", Value::Text(UnicodeString::new_nul(&group.name)))
.with("Rds ", Value::Integer(marker_size as i32))
.with("fontSize", Value::Integer(label_size as i32))
.with("Vsbl", Value::Boolean(group.visible))
.with("countObjectList", Value::List(objects)),
)
}
/// Whether to keep a preserved resource with this id on export.
pub fn keep_resource(doc: &Document, id: u16) -> bool {
match id {
MEASUREMENT_SCALE => keep_raw_scale(doc),
// Our count markers can't be written into Photoshop's (unpublished) layout; a stale copy
// would contradict them, so it is dropped once the document has markers of its own.
COUNT_INFO => doc.measurement.count_total() == 0,
// An opaque copy is only used when there are no document groups to write.
COUNT_INFO => doc.measurement.count_groups.is_empty(),
_ => true,
}
}
#[cfg(test)]
#[path = "count_resource_tests.rs"]
mod count_resource_tests;
#[cfg(test)]
mod tests {
use super::*;
+213
View File
@@ -0,0 +1,213 @@
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Color, ColorTable, CountGroup, Document};
use photocraft_geom::Size;
use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor};
use photocraft_psd::{ColorMode as PsdMode, ImageResource, PsdFile};
use super::{COUNT_INFO, count_groups_from_resource};
fn measured_resource(second_y: f64) -> Vec<u8> {
let point = |x, y| Value::Descriptor(Descriptor::new("countObject").with("X ", Value::Double(x)).with("Y ", Value::Double(y)));
let first = Descriptor::new("countGroup")
.with("Rd ", Value::Integer(51))
.with("Grn ", Value::Integer(102))
.with("Bl ", Value::Integer(204))
.with("Nm ", Value::Text(UnicodeString::new_nul("Cells")))
.with("Rds ", Value::Integer(3))
.with("fontSize", Value::Integer(12))
.with("Vsbl", Value::Boolean(true))
.with("countObjectList", Value::List(vec![point(9.5, 10.5), point(1.125, second_y), point(3.5, 4.5)]));
let second = Descriptor::new("countGroup")
.with("Rd ", Value::Integer(255))
.with("Grn ", Value::Integer(0))
.with("Bl ", Value::Integer(0))
.with("Nm ", Value::Text(UnicodeString::new_nul("Café")))
.with("Rds ", Value::Integer(10))
.with("fontSize", Value::Integer(72))
.with("Vsbl", Value::Boolean(false))
.with("countObjectList", Value::List(vec![point(7.5, 8.5), point(5.5, 6.5)]));
VersionedDescriptor::new(
Descriptor::new("Cnt ").with("Vrsn", Value::Integer(1)).with("countGroupList", Value::List(vec![Value::Descriptor(first), Value::Descriptor(second)])),
)
.to_bytes()
}
fn groups() -> Vec<CountGroup> {
vec![
CountGroup {
name: "Cells".into(),
color: Color::rgb(51.0 / 255.0, 102.0 / 255.0, 204.0 / 255.0),
marker_size: 3,
label_size: 12,
visible: true,
points: vec![[9.5, 10.5], [1.125, 2.75], [3.5, 4.5]],
},
CountGroup {
name: "Café".into(),
color: Color::rgb(1.0, 0.0, 0.0),
marker_size: 10,
label_size: 72,
visible: false,
points: vec![[7.5, 8.5], [5.5, 6.5]],
},
]
}
fn document(mode: ColorMode) -> Document {
Document::new("Counts", Size::new(16, 16), mode, SampleType::U8)
}
fn to_psd(doc: &Document) -> Vec<u8> {
crate::export(doc, "counts.psd", &crate::ExportOptions::default()).unwrap().bytes
}
fn import_counts(data: Vec<u8>) -> Document {
let mut file = PsdFile::from_bytes(&to_psd(&document(ColorMode::Rgb))).unwrap();
file.resources.push(ImageResource::new(COUNT_INFO, data));
crate::import("counts.psd", &file.to_bytes().unwrap()).unwrap().document
}
/// Two independently constructed groups preserve every option and the order of all five points.
#[test]
fn parses_hand_built_count_descriptor() {
assert_eq!(count_groups_from_resource(&measured_resource(2.75)), Some(groups()));
assert!(count_groups_from_resource(&measured_resource(f64::INFINITY)).is_none());
let mut trailing = measured_resource(2.75);
trailing.push(1);
assert!(count_groups_from_resource(&trailing).is_none());
}
/// Count groups round-trip through the real PSD reader and both export routes.
#[test]
fn count_groups_round_trip_through_psd() {
for (mode, wire_mode) in [(ColorMode::Rgb, PsdMode::Rgb), (ColorMode::Bitmap, PsdMode::Bitmap), (ColorMode::Multichannel, PsdMode::Multichannel)] {
let mut doc = document(mode);
doc.measurement.count_groups = groups();
let exported = crate::export(&doc, "counts.psd", &crate::ExportOptions::default()).unwrap();
assert!(!exported.warnings.iter().any(|warning| warning.starts_with("Count group ")));
let bytes = exported.bytes;
let file = PsdFile::from_bytes(&bytes).unwrap();
assert_eq!(file.header.color_mode, wire_mode);
let resources: Vec<_> = file.resources.iter().filter(|r| r.id == COUNT_INFO).collect();
assert_eq!(resources.len(), 1);
assert_eq!(resources[0].data, measured_resource(2.75));
let reopened = crate::import("counts.psd", &bytes).unwrap().document;
assert_eq!(reopened.measurement.count_groups, doc.measurement.count_groups);
assert!(!reopened.metadata.psd_resources.iter().any(|(id, _, _)| *id == COUNT_INFO));
}
}
/// Both export routes report clamped sizes and preserve the original Count groups.
#[test]
fn count_size_clamps_warn_without_changing_source_groups() {
for mode in [ColorMode::Rgb, ColorMode::Bitmap] {
let mut doc = document(mode);
let mut original = groups();
original[0].marker_size = 0;
original[0].label_size = 73;
original[1].marker_size = 11;
original[1].label_size = 7;
doc.measurement.count_groups = original.clone();
let exported = crate::export(&doc, "counts.psd", &crate::ExportOptions::default()).unwrap();
let warnings: Vec<_> = exported.warnings.iter().filter(|warning| warning.starts_with("Count group ")).map(String::as_str).collect();
assert_eq!(
warnings,
[
"Count group \"Cells\" sizes adjusted for PSD (marker 0 to 1, label 73 to 72)",
"Count group \"Café\" sizes adjusted for PSD (marker 11 to 10, label 7 to 8)",
]
);
assert_eq!(doc.measurement.count_groups, original);
let reopened = crate::import("counts.psd", &exported.bytes).unwrap().document;
let mut expected = original;
expected[0].marker_size = 1;
expected[0].label_size = 72;
expected[1].marker_size = 10;
expected[1].label_size = 8;
assert_eq!(reopened.measurement.count_groups, expected);
}
}
/// Opaque data survives an untouched save and an add-then-delete, but current groups win.
#[test]
fn unreadable_count_resource_is_preserved_without_groups() {
let raw = vec![0, 0, 0, 16, 0];
let mut doc = import_counts(raw.clone());
assert!(doc.measurement.count_groups.is_empty());
let check_raw = |doc: &Document| {
let file = PsdFile::from_bytes(&to_psd(doc)).unwrap();
assert_eq!(file.resource(COUNT_INFO).unwrap().data, raw);
};
check_raw(&doc);
doc.measurement.count_groups.push(CountGroup::default());
let file = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
let mut resources = file.resources.iter().filter(|r| r.id == COUNT_INFO);
assert_eq!(count_groups_from_resource(&resources.next().unwrap().data), Some(doc.measurement.count_groups.clone()));
assert!(resources.next().is_none());
doc.measurement.count_groups.clear();
check_raw(&doc);
}
/// Deleting the imported groups cannot bring back the readable resource.
#[test]
fn deleting_all_readable_count_groups_writes_no_resource() {
let mut doc = import_counts(measured_resource(2.75));
assert_eq!(doc.measurement.count_groups, groups());
assert!(!doc.metadata.psd_resources.iter().any(|(id, _, _)| *id == COUNT_INFO));
doc.measurement.count_groups.clear();
let file = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
assert!(file.resource(COUNT_INFO).is_none());
}
/// Indexed export uses the shared layerless writer and keeps exactly one Count resource.
#[test]
fn indexed_count_groups_round_trip_through_psd() {
let mut doc = document(ColorMode::Indexed);
doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: None });
let opaque = vec![0, 0, 0, 16, 0];
doc.metadata.psd_resources.push((COUNT_INFO, String::new(), std::sync::Arc::new(opaque.clone())));
let file = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
assert_eq!(file.header.color_mode, PsdMode::Indexed);
assert_eq!(file.resource(COUNT_INFO).unwrap().data, opaque);
doc.measurement.count_groups = groups();
let bytes = to_psd(&doc);
let file = PsdFile::from_bytes(&bytes).unwrap();
assert_eq!(file.header.color_mode, PsdMode::Indexed);
assert!(file.layer_info.is_none());
let resources: Vec<_> = file.resources.iter().filter(|r| r.id == COUNT_INFO).collect();
assert_eq!(resources.len(), 1);
assert_eq!(resources[0].data, measured_resource(2.75));
let reopened = crate::import("counts.psd", &bytes).unwrap().document;
assert_eq!(reopened.color_table, doc.color_table);
assert_eq!(reopened.measurement.count_groups, doc.measurement.count_groups);
}
/// Both PSD routes report omitted points, keeping the finite points in order.
#[test]
fn nonfinite_count_points_warn_on_psd_export() {
for (mode, wire_mode) in [(ColorMode::Rgb, PsdMode::Rgb), (ColorMode::Bitmap, PsdMode::Bitmap)] {
let mut doc = document(mode);
doc.measurement.count_groups = groups();
let options = crate::ExportOptions::default();
let clean = crate::export(&doc, "counts.psd", &options).unwrap();
assert!(!clean.warnings.iter().any(|warning| warning.starts_with("Count group ")));
let reopened = crate::import("counts.psd", &clean.bytes).unwrap().document;
assert_eq!(reopened.measurement.count_groups, doc.measurement.count_groups);
let mut expected = groups();
expected[0].points.remove(1);
doc.measurement.count_groups[0].points[1][1] = f64::INFINITY;
let original = doc.measurement.count_groups.clone();
let exported = crate::export(&doc, "counts.psd", &options).unwrap();
let warnings: Vec<_> = exported.warnings.iter().filter(|warning| warning.starts_with("Count group ")).map(String::as_str).collect();
assert_eq!(warnings, ["Count group \"Cells\" had nonfinite points omitted from PSD export (1 total)"]);
assert_eq!(doc.measurement.count_groups, original);
let file = PsdFile::from_bytes(&exported.bytes).unwrap();
assert_eq!(file.header.color_mode, wire_mode);
let reopened = crate::import("counts.psd", &exported.bytes).unwrap().document;
assert_eq!(reopened.measurement.count_groups, expected);
}
}
+1
View File
@@ -196,6 +196,7 @@ pub(crate) fn layerless_file(
if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) {
resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data));
}
resources.extend(crate::annotations_map::fresh_count_resource(doc, warnings));
resources.push(version_info_resource(true));
// Document-level tagged blocks (patterns, notes, ...) are valid without a layer section; a
// kept layer block would describe layers the document doesn't have. Their signatures follow
+1
View File
@@ -235,6 +235,7 @@ fn export_supported_document(
if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) {
resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data));
}
resources.extend(crate::annotations_map::fresh_count_resource(doc, &mut ex.warnings));
if let Some(Some(data)) = comps_resource {
resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data));
}
+5 -2
View File
@@ -710,7 +710,7 @@ impl Ctx<'_> {
crate::linked::embedded_payload_in_blocks(global.iter().map(|(_, key, data)| (key, data.as_slice())), &id).map(|(_, source)| source)
})
});
LayerContent::Smart(SmartObject {
let mut sm = SmartObject {
contents_id,
source: SmartSource::Linked { path: id },
vector_preview,
@@ -723,7 +723,9 @@ impl Ctx<'_> {
warp,
stack_mode: None,
perspective,
})
};
crate::smart_map::pin_puppet_meshes(&mut sm);
LayerContent::Smart(sm)
}
/// Typed vector mask from `vsms`/`vmsk` (non-shape layers). A user mask that Photoshop
@@ -1238,6 +1240,7 @@ fn read_initial_metadata(
if let Some(scale) = crate::annotations_map::raw_scale(doc) {
doc.measurement.scale = scale;
}
crate::annotations_map::import_count_resource(doc);
let _ = layered;
(damaged, alloc_error)
}
+308
View File
@@ -0,0 +1,308 @@
//! Puppet Warp smart filters (`Fltr` class `rigidTransform`) as observed in Photoshop-authored
//! mockup PSDs.
//!
//! The filter holds a `puppetShapeList` with one `puppetShape` per mesh. Each shape stores its
//! pins (`PinP` where they were placed, `posFinalPins` where they are now, x, y pairs in document
//! pixels) and the mesh Photoshop solved for them, as raw data:
//!
//! ```text
//! originalVertexArray, deformedVertexArray: f32 LE x, y per vertex (document pixels)
//! indexArray: i32 LE, three per triangle
//! ```
//!
//! and the corners of the layer the mesh was built on (`PuX0..3`, `PuY0..3` on the filter).
//! Replace Contents keeps the mesh: Photoshop redraws the new contents through the stored
//! triangles (measured on a dot grid: 0.1 px mean). So the mesh is imported as the
//! `layer.smartObjects.puppetWarp` filter's `mesh`, which is drawn as it is while the pins are
//! unchanged, and the whole item is kept as a template ([`TEMPLATE_KEY`]) to write back. Pins
//! alone feed PhotoCraft's own solver once they are edited; the mode, density and rotation
//! settings aren't mapped (their stored values aren't identified), so those stay at defaults.
use photocraft_doc::SmartFilter;
use photocraft_psd::descriptor::{Descriptor, Value};
use serde_json::{Value as J, json};
use super::{blend_options, from_hex, get_desc, set, to_hex};
use crate::blocks::num;
pub(super) const CLASS: &str = "rigidTransform";
pub(super) const COMMAND: &str = "layer.smartObjects.puppetWarp";
pub(super) const TEMPLATE_KEY: &str = "__puppetPsd";
/// Far beyond the few hundred vertices Photoshop's meshes have, yet small enough that the
/// copies a hostile mesh makes (arrays, JSON params, cloned filters) stay bounded.
const MAX_VERTS: usize = 1 << 16;
fn raw<'a>(d: &'a Descriptor, key: &str) -> Option<&'a [u8]> {
match d.get(key)? {
Value::RawData(b) => Some(b),
_ => None,
}
}
fn floats(d: &Descriptor, key: &str) -> Option<Vec<f64>> {
let Value::List(v) = d.get(key)? else { return None };
v.iter().map(|x| num(Some(x)).filter(|f| f.is_finite())).collect()
}
/// `f32` LE x, y pairs; `None` unless whole, finite and at most [`MAX_VERTS`].
fn vertices(b: &[u8]) -> Option<Vec<[f64; 2]>> {
if !b.len().is_multiple_of(8) || b.len() / 8 > MAX_VERTS {
return None;
}
let f = |c: &[u8]| c.try_into().ok().map(f32::from_le_bytes).filter(|v| v.is_finite()).map(f64::from);
b.as_chunks::<8>().0.iter().map(|c| Some([f(&c[..4])?, f(&c[4..])?])).collect()
}
/// `i32` LE triples, each index below `n`.
fn triangles(b: &[u8], n: usize) -> Option<Vec<[usize; 3]>> {
if !b.len().is_multiple_of(12) || b.len() / 12 > 2 * MAX_VERTS {
return None;
}
let i = |c: &[u8]| c.try_into().ok().map(i32::from_le_bytes).and_then(|v| usize::try_from(v).ok()).filter(|&v| v < n);
b.as_chunks::<12>().0.iter().map(|c| Some([i(&c[..4])?, i(&c[4..8])?, i(&c[8..])?])).collect()
}
/// One shape's pins (as params), vertices, deformed vertices and triangles.
type Shape = (Vec<J>, Vec<[f64; 2]>, Vec<[f64; 2]>, Vec<[usize; 3]>);
/// Pins and mesh of one `puppetShape`, with vertex indices offset by `base`.
fn shape(s: &Descriptor, base: usize) -> Option<Shape> {
let (from, to) = (floats(s, "PinP")?, floats(s, "posFinalPins")?);
if from.len() != to.len() || !from.len().is_multiple_of(2) {
return None;
}
let pins = from.as_chunks::<2>().0.iter().zip(to.as_chunks::<2>().0).map(|(a, b)| json!({"src": a, "dst": b})).collect();
let verts = vertices(raw(s, "originalVertexArray")?)?;
let deformed = vertices(raw(s, "deformedVertexArray")?)?;
if verts.len() != deformed.len() {
return None;
}
let tris = triangles(raw(s, "indexArray")?, verts.len())?;
Some((pins, verts, deformed, tris.into_iter().map(|t| t.map(|i| i + base)).collect()))
}
/// Pins and mesh of a `rigidTransform` descriptor (shapes joined into one mesh), as
/// `{"pins", "mesh"}`.
fn settings(f: &Descriptor) -> Option<J> {
let Some(Value::List(shapes)) = f.get("puppetShapeList") else { return None };
let (mut pins, mut verts, mut deformed, mut tris) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
for s in shapes {
let Value::Descriptor(s) = s else { return None };
let (p, v, d, t) = shape(s, verts.len())?;
pins.extend(p);
verts.extend(v);
deformed.extend(d);
tris.extend(t);
}
if tris.is_empty() || verts.len() > MAX_VERTS {
return None;
}
let pins = J::Array(pins);
Some(json!({"pins": pins, "mesh": {"pins": pins, "verts": verts, "deformed": deformed, "tris": tris}}))
}
/// The corners of the layer the mesh was built on (`PuX0`, `PuY0` … `PuX3`, `PuY3`), as x, y
/// pairs.
pub(super) fn built_on(params: &J) -> Option<[f64; 8]> {
let item = template(params).ok()?;
let f = get_desc(&item, "Fltr")?;
let mut q = [0.0; 8];
for i in 0..4 {
q[2 * i] = num(f.get(&format!("PuX{i}"))).filter(|v| v.is_finite())?;
q[2 * i + 1] = num(f.get(&format!("PuY{i}"))).filter(|v| v.is_finite())?;
}
Some(q)
}
/// `layer.smartObjects.puppetWarp` params for a Puppet Warp item with a readable mesh.
pub(super) fn import_params(item: &Descriptor) -> Option<J> {
let f = get_desc(item, "Fltr")?;
if !f.class_id.is(CLASS) {
return None;
}
let mut params = settings(f)?;
// Neutral blending in the template: the model's own fields replace it on export.
let mut template = item.clone();
let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
set(&mut template, "blendOptions", blend_options(&neutral));
set(&mut template, "enab", Value::Boolean(true));
params.as_object_mut()?.insert(TEMPLATE_KEY.into(), json!(to_hex(&template.to_bytes())));
Some(params)
}
/// The template item of `params`, checked to be a Puppet Warp filter.
fn template(params: &J) -> Result<Descriptor, String> {
let raw = params.get(TEMPLATE_KEY).and_then(J::as_str).ok_or("a Puppet Warp made in PhotoCraft is not written to PSD")?;
let bytes = from_hex(raw).ok_or("the Puppet Warp PSD data is not valid hex")?;
let item = Descriptor::from_bytes(&bytes).map_err(|e| format!("the Puppet Warp PSD data is unreadable ({e})"))?;
if !item.class_id.is("filterFX") || !get_desc(&item, "Fltr").is_some_and(|f| f.class_id.is(CLASS)) {
return Err("the Puppet Warp PSD data is not a Puppet Warp filter".into());
}
Ok(item)
}
/// The `filterFXList` item: the template, while the pins are still the imported ones.
pub(super) fn export_item(params: &J) -> Result<Descriptor, String> {
let item = template(params)?;
let imported = get_desc(&item, "Fltr").and_then(settings).ok_or("the Puppet Warp PSD data has no readable mesh")?;
if params.get("pins") != imported.get("pins") {
return Err("Puppet Warp pins moved in PhotoCraft are not written to PSD".into());
}
// Imported params set no solver settings, so a set one is an edit the template doesn't hold.
if let Some(k) = ["mode", "density", "expansion"].into_iter().find(|k| params.get(*k).is_some()) {
return Err(format!("the Puppet Warp `{k}` set in PhotoCraft is not written to PSD"));
}
Ok(item)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter, parse_sold};
use photocraft_psd::descriptor::{UnicodeString, VersionedDescriptor};
const QUAD: [f64; 8] = [10.0, 20.0, 110.0, 22.0, 108.0, 220.0, 12.0, 218.0];
fn list(v: &[f64]) -> Value {
Value::List(v.iter().map(|x| Value::Double(*x)).collect())
}
fn f32s(v: &[[f32; 2]]) -> Value {
Value::RawData(v.iter().flatten().flat_map(|x| x.to_le_bytes()).collect())
}
fn i32s(v: &[i32]) -> Value {
Value::RawData(v.iter().flat_map(|x| x.to_le_bytes()).collect())
}
/// A Puppet Warp shape as Photoshop writes it: a box of two triangles with one pin.
fn shape(dx: f32) -> Descriptor {
let verts = [[10.0, 20.0], [110.0, 22.0], [108.0, 220.0], [12.0, 218.0]];
let moved: Vec<[f32; 2]> = verts.iter().map(|v| [v[0] + dx, v[1]]).collect();
Descriptor::new("puppetShape")
.with("rigidType", Value::Boolean(true))
.with("originalVertexArray", f32s(&verts))
.with("deformedVertexArray", f32s(&moved))
.with("indexArray", i32s(&[0, 1, 2, 0, 2, 3]))
.with("pinOffsets", list(&[0.0, 0.0]))
.with("posFinalPins", list(&[60.0 + f64::from(dx), 120.0]))
.with("pinVertexIndices", list(&[0.0]))
.with("PinP", list(&[60.0, 120.0]))
.with("meshExpansion", Value::Integer(2))
}
fn item(shapes: Vec<Descriptor>) -> Descriptor {
let mut f = Descriptor::new(CLASS)
.with("rigidType", Value::Boolean(true))
.with("puppetShapeList", Value::List(shapes.into_iter().map(Value::Descriptor).collect()));
for i in 0..4 {
f = f.with(&format!("PuX{i}"), Value::Double(QUAD[2 * i])).with(&format!("PuY{i}"), Value::Double(QUAD[2 * i + 1]));
}
let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
Descriptor::new("filterFX")
.with("Nm ", Value::Text(UnicodeString::new_nul("Puppet Warp")))
.with("blendOptions", blend_options(&neutral))
.with("enab", Value::Boolean(true))
.with("hasoptions", Value::Boolean(true))
.with("Fltr", Value::Descriptor(f))
.with("filterID", Value::Integer(973))
}
#[test]
fn puppet_items_map_to_the_command_with_their_mesh() {
let src = item(vec![shape(4.0), shape(-2.0)]);
let f = filter_from_item(&src);
assert_eq!(f.command, COMMAND);
assert_eq!(f.params["pins"], json!([{"src": [60.0, 120.0], "dst": [64.0, 120.0]}, {"src": [60.0, 120.0], "dst": [58.0, 120.0]}]));
let mesh = &f.params["mesh"];
assert_eq!(mesh["pins"], f.params["pins"]);
assert_eq!(mesh["verts"].as_array().unwrap().len(), 8);
assert_eq!(mesh["verts"][2], json!([108.0, 220.0]));
assert_eq!(mesh["deformed"][2], json!([112.0, 220.0]));
// The second shape's triangles index its own vertices.
assert_eq!(mesh["tris"], json!([[0, 1, 2], [0, 2, 3], [4, 5, 6], [4, 6, 7]]));
assert_eq!(built_on(&f.params), Some(QUAD));
// Unchanged pins write the original item back; blending is the model's.
assert_eq!(item_for_filter(&f).unwrap(), src);
let mut faded = f.clone();
faded.opacity = 0.5;
assert_eq!(filter_from_item(&item_for_filter(&faded).unwrap()).opacity, 0.5);
// Moved pins aren't written (the stored mesh would no longer match them).
let mut moved = f.clone();
moved.params["pins"][0]["dst"] = json!([70.0, 120.0]);
assert!(item_for_filter(&moved).is_err());
// Nor are solver settings set after import (the template holds the imported ones).
for (k, v) in [("mode", json!("rigid")), ("density", json!("more")), ("expansion", json!(2.0))] {
let mut edited = f.clone();
edited.params[k] = v;
assert!(item_for_filter(&edited).is_err(), "{k}");
}
// The import records the placement the mesh was solved for; the item written back is
// unchanged by it.
let mut sm = photocraft_doc::SmartObject::new(
photocraft_doc::SmartSource::Linked { path: String::new() },
photocraft_geom::Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] },
None,
);
sm.smart_filters.push(f.clone());
crate::smart_map::pin_puppet_meshes(&mut sm);
assert_eq!(sm.smart_filters[0].params["mesh"]["placement"], sm.placement_json());
assert_eq!(item_for_filter(&sm.smart_filters[0]).unwrap(), src);
// A Puppet Warp made in PhotoCraft has no template: not written, as before.
let own = SmartFilter { params: json!({"pins": f.params["pins"]}), ..f };
assert!(item_for_filter(&own).is_err());
}
#[test]
fn unreadable_puppet_filters_stay_opaque() {
let with = |key: &str, v: Value| {
let mut s = shape(4.0);
set(&mut s, key, v);
item(vec![s])
};
for src in [
with("originalVertexArray", Value::RawData(vec![0; 31])),
with("originalVertexArray", f32s(&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])),
with("deformedVertexArray", f32s(&[[f32::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])),
with("indexArray", i32s(&[0, 1, 4])),
with("indexArray", i32s(&[0, 1, -1])),
with("indexArray", Value::RawData(vec![0; 10])),
with("indexArray", i32s(&[])),
with("posFinalPins", list(&[60.0])),
with("PinP", Value::Integer(3)),
item(vec![]),
] {
let f = filter_from_item(&src);
assert_eq!(f.command, UNSUPPORTED_FILTER);
assert_eq!(item_for_filter(&f).unwrap(), src);
}
}
#[test]
fn a_mesh_built_on_other_corners_is_dropped() {
// The mesh is in document pixels where the layer was when it was built: a layer whose
// corners differ from the stored ones keeps the pins but not the mesh.
let sold = |quad: [f64; 8]| {
let fx = Descriptor::new("filterFXStyle")
.with("enab", Value::Boolean(true))
.with("filterFXList", Value::List(vec![Value::Descriptor(item(vec![shape(4.0)]))]));
let d = Descriptor::new("null").with("Trnf", list(&quad)).with("nonAffineTransform", list(&quad)).with("filterFX", Value::Descriptor(fx));
let mut v = b"soLD".to_vec();
v.extend_from_slice(&4u32.to_be_bytes());
v.extend(VersionedDescriptor::new(d).to_bytes());
v
};
let filter = |quad| parse_sold(&sold(quad)).and_then(|p| p.stack).map(|s| s.filters[0].clone()).expect("a stack");
let kept = filter(QUAD);
assert_eq!(kept.command, COMMAND);
assert!(kept.params.get("mesh").is_some());
let mut moved = QUAD;
moved[0] += 5.0;
let f = filter(moved);
assert_eq!(f.command, COMMAND);
assert!(f.params.get("mesh").is_none());
assert_eq!(f.params["pins"], kept.params["pins"]);
// Still written back as it was.
assert_eq!(item_for_filter(&f).unwrap(), item(vec![shape(4.0)]));
}
}
+38 -2
View File
@@ -25,7 +25,7 @@
//! (`HStr`) maps to its adjustment command in `hue_sat_filter_map.rs`.
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{LayerMask, SmartFilter};
use photocraft_doc::{LayerMask, SmartFilter, SmartObject};
use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
use photocraft_geom::{Affine, Rect as GeomRect};
use photocraft_psd::Compression;
@@ -49,6 +49,8 @@ mod displace;
mod hue_sat;
#[path = "perspective_warp_map.rs"]
mod perspective_warp;
#[path = "puppet_map.rs"]
mod puppet;
pub use displace::{embed_map as displace_embed_map, embedded_map as displace_embedded_map, without_map as displace_without_map};
pub use perspective_warp::{
@@ -133,10 +135,44 @@ pub fn parse_sold(data: &[u8]) -> Option<Placed> {
let d = sold_descriptor(data)?;
let (idnt, transform) = crate::blocks::parse_smart(b"SoLd", data);
let placed = text_of(&d, "placed").unwrap_or_default();
let stack = get_desc(&d, "filterFX").map(filter_stack);
let mut stack = get_desc(&d, "filterFX").map(filter_stack);
if let Some(stack) = &mut stack {
drop_moved_puppet_meshes(stack, &d);
}
Some(Placed { descriptor: d, idnt, placed, transform, stack })
}
/// A Puppet Warp's stored mesh sits where the layer was when it was built (document pixels); one
/// built on other corners than the layer's own doesn't fit it, so its pins are solved instead.
fn drop_moved_puppet_meshes(stack: &mut FilterStack, d: &Descriptor) {
let corners = |k: &str| match d.get(k) {
Some(Value::List(v)) if v.len() == 8 => v.iter().map(|x| num(Some(x))).collect::<Option<Vec<f64>>>(),
_ => None,
};
let quad = corners("nonAffineTransform").or_else(|| corners("Trnf"));
for f in stack.filters.iter_mut().filter(|f| f.command == puppet::COMMAND) {
let fits = match (&quad, puppet::built_on(&f.params)) {
(Some(q), Some(b)) => q.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.01),
_ => false,
};
if !fits && let Some(p) = f.params.as_object_mut() {
p.remove("mesh");
}
}
}
/// Records on each imported Puppet Warp mesh the placement it was solved for (`mesh.placement`,
/// [`SmartObject::placement_json`]): once the smart object is moved, transformed or warped, the
/// mesh no longer fits it and the pins are solved instead.
pub(crate) fn pin_puppet_meshes(sm: &mut SmartObject) {
let placement = sm.placement_json();
for f in sm.smart_filters.iter_mut().filter(|f| f.command == puppet::COMMAND) {
if let Some(m) = f.params.get_mut("mesh").and_then(J::as_object_mut) {
m.insert("placement".into(), placement.clone());
}
}
}
/// Reads a `filterFX` object.
pub fn filter_stack(fx: &Descriptor) -> FilterStack {
let filters = match fx.get("filterFXList") {
+7 -1
View File
@@ -7,7 +7,7 @@ use super::import::{
use super::placed::enumv;
use super::{
Class, Descriptor, FilterStack, Id, J, ReferenceItem, SmartFilter, UNSUPPORTED_FILTER, UnicodeString, Value, camera_raw, displace, hue_sat,
perspective_warp,
perspective_warp, puppet,
};
// ---------- writing ----------
@@ -309,6 +309,12 @@ pub fn item_for_filter(f: &SmartFilter) -> Result<Descriptor, String> {
if perspective_warp::handles(&f.command) {
return perspective_warp::export_item(f);
}
if f.command == puppet::COMMAND && f.params.get(puppet::TEMPLATE_KEY).is_some() {
let mut d = puppet::export_item(&f.params)?;
set(&mut d, "blendOptions", blend_options(f));
set(&mut d, "enab", Value::Boolean(f.visible));
return Ok(d);
}
if f.command == UNSUPPORTED_FILTER {
let raw = f.params.get("psd").and_then(J::as_str).and_then(from_hex).ok_or("its filter data is missing")?;
let mut d = Descriptor::from_bytes(&raw).map_err(|e| format!("its filter data is unreadable ({e})"))?;
+2 -1
View File
@@ -2,7 +2,7 @@ use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc, whole};
use super::placed::enumv;
use super::{
BlendMode, Descriptor, Id, J, Map, ReferenceItem, SmartFilter, UNSUPPORTED_FILTER, UnicodeString, Value, bool_or, camera_raw, displace, enum_of, get_desc,
hue_sat, json, num, perspective_warp, text_of,
hue_sat, json, num, perspective_warp, puppet, text_of,
};
// ---------- the filters we model ----------
@@ -867,6 +867,7 @@ pub fn filter_from_item(item: &Descriptor) -> SmartFilter {
Some(displace::CLASS) => displace::import_params(item).map(|p| (displace::COMMAND, p)),
Some(hue_sat::CLASS) => fltr.and_then(hue_sat::import_params).map(|p| (hue_sat::COMMAND, p)),
Some(perspective_warp::CLASS) => perspective_warp::import_params(item).map(|p| (perspective_warp::COMMAND, p)),
Some(puppet::CLASS) => puppet::import_params(item).map(|p| (puppet::COMMAND, p)),
Some(GALLERY_CLASS) => fltr.and_then(|f| gallery_params(item, f)).map(|p| (GALLERY_COMMAND, p)),
Some(c @ ("Fbrs" | "Clds" | "DfrC")) => fltr.and_then(|f| coloured_params(c, item, f)),
// A `Fltr` that is there but not a descriptor is settings we can't read: kept verbatim
+130
View File
@@ -0,0 +1,130 @@
//! Hasselblad 3FR / FFF: a TIFF whose IFD0 holds the camera's JPEG preview and
//! whose CFA image sits in a SubIFD with DNG-style tags (BlackLevel, WhiteLevel,
//! DefaultCropOrigin / DefaultCropSize, AsShotNeutral, ColorMatrix1) but no
//! DNGVersion and no CFA-pattern tag — neither the TIFF/EP 33421/33422 pair nor
//! the EXIF one — so the Bayer phase comes from measurements of each body.
//!
//! Decoded today: the X2D II 100C's 16-bit uncompressed samples (Compression 1,
//! one strip covering the whole sensor, masked borders included; the crop to the
//! usable area comes from the file's DefaultCrop tags). Bodies that store
//! lossless-JPEG strips (Compression 7, the earlier X and H generations) are
//! recognised but not decoded yet.
//!
//! Clean-room: derived from the TIFF 6.0 and DNG specifications, observation of
//! sample files, and the camera's own embedded JPEG — the oracle the
//! camera-profile measurements in [`crate::cameras`] use. No code or tables
//! from dcraw, LibRaw, rawspeed, rawler or darktable.
use crate::cr2::clip_level;
use crate::error::{RawError, Result};
use crate::sensor::{BlackLevels, Cfa, JpegLayout, Rect, Sensor, read_plane};
use crate::tiff::{Ifd, Tiff, tag};
use crate::tiffep;
use crate::{Limits, RawFormat};
/// The Bayer colours at the data origin, row-major (0 red, 1 green, 2 blue).
/// Hasselblad records no CFA tag, so a body's phase is measured against its own
/// embedded JPEG: on an X2D II 100C dusk landscape the blue sky reads red at the
/// origin site at about half the green rate while the blue site holds three
/// quarters of it, the reverse of the warm ground.
fn cfa_for(model: Option<&str>) -> (Cfa, bool) {
let measured = model.is_some_and(|m| m.eq_ignore_ascii_case("X2D II 100C"));
(Cfa { width: 2, height: 2, colors: vec![0, 1, 1, 2], origin_x: 0, origin_y: 0 }, measured)
}
pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
let ifds = t.all_ifds();
let Some(raw) = tiffep::raw_ifd(t, &ifds) else {
return Err(RawError::unsupported("Hasselblad 3FR/FFF: no CFA image found"));
};
match t.tag_uint(&raw, tag::COMPRESSION).unwrap_or(1) {
1 => {}
7 => return Err(RawError::unsupported("lossless-JPEG (compressed 3FR/FFF)")),
c => return Err(RawError::unsupported(format!("raw compression scheme {c}"))),
}
let plane = read_plane(t, &raw, limits, JpegLayout::Flat)?;
if plane.samples != 1 {
return Err(RawError::unsupported(format!("CFA data with {} samples per pixel", plane.samples)));
}
let make = ifds.iter().find_map(|i| t.tag_ascii(i, tag::MAKE));
let model = ifds.iter().find_map(|i| t.tag_ascii(i, tag::MODEL));
let (cfa, measured) = cfa_for(model.as_deref());
let mut warnings = Vec::new();
if !measured {
warnings.push(format!(
"{}: this body's Bayer phase is not measured yet; assumed the X2D II 100C's (red at the data origin)",
model.as_deref().unwrap_or("Hasselblad")
));
}
let full = Rect::new(0, 0, plane.width, plane.height);
// DNG-style ActiveArea (top, left, bottom, right) in the raw IFD; an absent,
// inverted or out-of-plane one leaves the whole plane active.
let active = match t.tag_uints(&raw, tag::ACTIVE_AREA).as_slice() {
[top, left, bottom, right] if bottom > top && right > left => {
Rect::new(*left as usize, *top as usize, (*right - *left) as usize, (*bottom - *top) as usize).intersect(&full)
}
_ => full,
};
let active = if active.is_empty() { full } else { active };
// DNG-style DefaultCropOrigin / DefaultCropSize in the raw IFD, relative to
// the active area as in DNG.
let mut crop = active;
if let ([ox, oy], [cw, ch]) = (t.tag_floats(&raw, tag::DEFAULT_CROP_ORIGIN).as_slice(), t.tag_floats(&raw, tag::DEFAULT_CROP_SIZE).as_slice()) {
let f = |v: f64| if v.is_finite() && v >= 0.0 { v.round() as usize } else { 0 };
let r = Rect::new(active.x.saturating_add(f(*ox)), active.y.saturating_add(f(*oy)), f(*cw), f(*ch)).intersect(&active);
if !r.is_empty() {
crop = r;
}
}
let bl = t.tag_floats(&raw, tag::BLACK_LEVEL);
let black = match bl.as_slice() {
[b] if b.is_finite() && *b >= 0.0 => BlackLevels::uniform(*b as f32),
// A 2×2 repeat is in the CFA's own row-major order.
[r, g1, g2, b] if [*r, *g1, *g2, *b].iter().all(|v| v.is_finite() && *v >= 0.0) => {
BlackLevels { rows: 2, cols: 2, values: [r, g1, g2, b].map(|v| *v as f32).to_vec(), delta_h: Vec::new(), delta_v: Vec::new() }
}
_ => {
warnings.push("Hasselblad 3FR/FFF: black level not recorded; assumed 0".into());
BlackLevels::uniform(0.0)
}
};
let white =
t.tag_floats(&raw, tag::WHITE_LEVEL).first().copied().filter(|w| *w > 0.0).map(|w| w as f32).unwrap_or_else(|| clip_level(&plane.data, plane.bits));
// AsShotNeutral (IFD0) is the camera-space colour of a neutral patch: the
// green-normalised multipliers are the other channels over green.
let camera_wb = ifds
.iter()
.find_map(|i: &Ifd| t.tag_floats(i, tag::AS_SHOT_NEUTRAL).try_into().ok())
.and_then(|n: [f64; 3]| match n {
[r, g, b] if g > 0.0 && r > 0.0 && b > 0.0 => Some([g / r, 1.0, g / b]),
_ => None,
})
.filter(|m| m.iter().all(|v| (0.25..8.0).contains(v)));
let ifd0 = t.ifd_at(t.first_ifd, 0);
let baseline_exposure = ifd0.as_ref().map(|i| t.tag_floats(i, tag::BASELINE_EXPOSURE).first().copied().unwrap_or(0.0)).unwrap_or(0.0);
let mut sensor = Sensor {
format: RawFormat::Fff,
make,
model,
width: plane.width,
height: plane.height,
samples: 1,
data: plane.data,
cfa: Some(cfa),
linearization: None,
black,
white: [white; 3],
active,
crop,
color: Default::default(),
camera_wb,
orientation: crate::tiff::orientation(ifd0.as_ref().and_then(|i| t.tag_uint(i, tag::ORIENTATION))),
baseline_exposure: if baseline_exposure.is_finite() { baseline_exposure.clamp(-10.0, 10.0) } else { 0.0 },
gain_maps: Vec::new(),
tone_curve: Vec::new(),
black_point: 0.0,
warnings,
};
crate::cameras::apply(&mut sensor, plane.bits);
Ok(sensor)
}
+11 -3
View File
@@ -33,8 +33,9 @@
//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),
//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),
//! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed),
//! uncompressed Olympus ORF and uncompressed Fujifilm RAF (Bayer and
//! X-Trans). Everything else reports [`RawError::Unsupported`].
//! uncompressed Olympus ORF, uncompressed Fujifilm RAF (Bayer and
//! X-Trans), and Hasselblad 3FR/FFF (the X2D II 100C's uncompressed 16-bit CFA;
//! see [`crate::hasselblad`]). Everything else reports [`RawError::Unsupported`].
//!
//! The crate is standalone (no workspace dependencies), does no I/O, builds for
//! `wasm32-unknown-unknown` and never panics on hostile input: sizes are
@@ -51,6 +52,7 @@ mod demosaic;
mod develop;
mod dng;
mod error;
mod hasselblad;
mod jxl;
mod ljpeg;
mod look;
@@ -119,6 +121,8 @@ pub enum RawFormat {
Rw2,
/// Fujifilm RAF.
Raf,
/// Hasselblad 3FR / FFF.
Fff,
/// Another TIFF/EP raw.
TiffEp,
}
@@ -135,13 +139,14 @@ impl RawFormat {
RawFormat::Orf => "ORF",
RawFormat::Rw2 => "RW2",
RawFormat::Raf => "RAF",
RawFormat::Fff => "3FR/FFF",
RawFormat::TiffEp => "TIFF/EP raw",
}
}
}
/// File extensions of the raw formats this crate recognises.
pub const EXTENSIONS: &[&str] = &["dng", "cr2", "cr3", "nef", "nrw", "arw", "srf", "sr2", "pef", "orf", "rw2", "raf"];
pub const EXTENSIONS: &[&str] = &["dng", "cr2", "cr3", "nef", "nrw", "arw", "srf", "sr2", "pef", "orf", "rw2", "raf", "3fr", "fff"];
/// Decompression-bomb guards, checked on header values before allocating
/// (the same shape and defaults as `photocraft-codecs`' limits).
@@ -195,6 +200,8 @@ fn make_format(make: Option<&str>) -> RawFormat {
RawFormat::Pef
} else if m.starts_with("OLYMPUS") || m.starts_with("OM DIGITAL") {
RawFormat::Orf
} else if m.starts_with("HASSELBLAD") {
RawFormat::Fff
} else {
RawFormat::TiffEp
}
@@ -249,6 +256,7 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result<Sensor, RawError> {
RawFormat::Cr2 => cr2::decode(&t, limits),
RawFormat::Rw2 => rw2::decode(&t, limits),
RawFormat::Orf => orf::decode(&t, limits),
RawFormat::Fff => hasselblad::decode(&t, limits),
f => tiffep::decode(&t, f, limits),
}
}
+2
View File
@@ -9,6 +9,7 @@
mod canon;
mod dng;
mod hasselblad;
mod lj92;
mod orf;
mod raf;
@@ -17,6 +18,7 @@ mod tiff;
pub use canon::{Cr2Spec, Cr2SrawSpec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep};
pub use dng::{DngSpec, DngStorage, baseline_jpeg, gain_map_opcode_list, map_polynomial_opcode_list};
pub use hasselblad::Hasselblad3frSpec;
pub use lj92::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables};
pub use orf::orf;
pub use raf::{RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, scene};
+106
View File
@@ -0,0 +1,106 @@
use super::tiff::{TiffBuilder, Val, urat};
// ---------------------------------------------------------------- Hasselblad 3FR
/// A synthetic Hasselblad 3FR, as the X2D II 100C writes it: IFD0 with Make,
/// Model and DNG-style AsShotNeutral, and the CFA image in a SubIFD —
/// `bits`-bit uncompressed samples with BlackLevel, WhiteLevel and DefaultCrop
/// tags and no CFA-pattern tags. `compression` and the optional tags exist for
/// the unsupported and hostile variants.
#[derive(Debug, Clone)]
pub struct Hasselblad3frSpec {
pub width: usize,
pub height: usize,
/// Row-major sensor samples.
pub data: Vec<u16>,
pub bits: u16,
pub compression: u16,
/// The BlackLevel RATIONAL; `None` leaves the tag out.
pub black: Option<(u32, u32)>,
/// The WhiteLevel; `None` leaves the tag out.
pub white: Option<u16>,
/// AsShotNeutral; `None` leaves the tag out.
pub as_shot_neutral: Option<[f64; 3]>,
/// DefaultCropOrigin (x, y) and DefaultCropSize (w, h); `None` leaves both out.
pub crop: Option<([u16; 2], [u16; 2])>,
/// ActiveArea (top, left, bottom, right); `None` leaves the tag out.
pub active_area: Option<[u32; 4]>,
pub make: String,
pub model: String,
}
impl Hasselblad3frSpec {
/// An X2D II 100C-shaped file: 16-bit uncompressed, black 4096, white
/// 64763, the sample file's as-shot neutral, no crop.
pub fn new(width: usize, height: usize, data: Vec<u16>) -> Self {
Hasselblad3frSpec {
width,
height,
data,
bits: 16,
compression: 1,
black: Some((4096, 1)),
white: Some(64763),
as_shot_neutral: Some([0.375, 1.0, 0.617]),
crop: None,
active_area: None,
make: "Hasselblad".into(),
model: "X2D II 100C".into(),
}
}
pub fn build(&self) -> Vec<u8> {
let mut t = TiffBuilder::default();
let len = self.data.len() * 2;
let strip = t.blob(self.data.iter().flat_map(|&v| v.to_le_bytes()).collect());
let mut raw = vec![
(254, Val::Long(vec![0])),
(256, Val::Long(vec![self.width as u32])),
(257, Val::Long(vec![self.height as u32])),
(258, Val::Short(vec![self.bits])),
(259, Val::Short(vec![self.compression])),
(262, Val::Short(vec![32803])),
(273, Val::Blobs(vec![strip])),
(277, Val::Short(vec![1])),
(278, Val::Long(vec![self.height as u32])),
(279, Val::Long(vec![len as u32])),
];
if let Some((n, d)) = self.black {
raw.push((50714, Val::Rational(vec![(n, d)])));
}
if let Some(w) = self.white {
raw.push((50717, Val::Short(vec![w])));
}
if let Some((origin, size)) = &self.crop {
raw.push((50719, Val::Short(origin.to_vec())));
raw.push((50720, Val::Short(size.to_vec())));
}
if let Some(area) = self.active_area {
raw.push((50829, Val::Long(area.to_vec())));
}
let raw_ifd = t.ifd(raw);
let thumb = t.blob(vec![128; 12]);
let mut ifd0 = vec![
(254, Val::Long(vec![1])),
(256, Val::Long(vec![2])),
(257, Val::Long(vec![2])),
(258, Val::Short(vec![8, 8, 8])),
(259, Val::Short(vec![7])),
(262, Val::Short(vec![6])),
(271, Val::Ascii(self.make.clone())),
(272, Val::Ascii(self.model.clone())),
(273, Val::Blobs(vec![thumb])),
(277, Val::Short(vec![3])),
(278, Val::Long(vec![2])),
(279, Val::Long(vec![12])),
(330, Val::Ifds(vec![raw_ifd])),
(50708, Val::Ascii(format!("{} {}", self.make, self.model))),
];
if let Some(n) = self.as_shot_neutral {
ifd0.push((50728, Val::Rational(n.iter().map(|&v| urat(v)).collect())));
}
let i0 = t.ifd(ifd0);
t.chain = vec![i0];
t.build()
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ const NIKON_BLACK_LEVEL: u16 = 0x003D;
const SONY_BLACK_LEVEL: u16 = 0x7310;
const SONY_WB_RGGB_LEVELS: u16 = 0x7313;
fn raw_ifd(t: &Tiff, ifds: &[Ifd]) -> Option<Ifd> {
pub(crate) fn raw_ifd(t: &Tiff, ifds: &[Ifd]) -> Option<Ifd> {
ifds.iter()
.filter(|i| t.tag_uint(i, tag::PHOTOMETRIC) == Some(PHOTOMETRIC_CFA))
.max_by_key(|i| u64::from(t.tag_uint(i, tag::IMAGE_WIDTH).unwrap_or(0)) * u64::from(t.tag_uint(i, tag::IMAGE_LENGTH).unwrap_or(0)))
+143
View File
@@ -0,0 +1,143 @@
//! Synthetic Hasselblad 3FR files (the X2D II 100C layout): identification,
//! exact samples, metadata, the DefaultCrop area, and the unsupported and
//! hostile variants.
use photocraft_raw::testgen::{Hasselblad3frSpec, mosaic, scene};
use photocraft_raw::*;
const RGGB: [u8; 4] = [0, 1, 1, 2];
fn spec() -> Hasselblad3frSpec {
let (w, h) = (16, 12);
Hasselblad3frSpec::new(w, h, mosaic(&scene(w, h), w, RGGB, 4096, 64763))
}
#[test]
fn identifies_as_fff() {
let b = spec().build();
assert_eq!(identify(&b), Some(RawFormat::Fff));
assert!(is_raw(&b));
assert!(EXTENSIONS.contains(&"3fr") && EXTENSIONS.contains(&"fff"));
}
#[test]
fn decodes_exactly() {
let s = spec();
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!((sensor.width, sensor.height), (16, 12));
assert_eq!(sensor.samples, 1);
assert_eq!(sensor.data, s.data, "the samples are the stored strip");
let cfa = sensor.cfa.as_ref().unwrap();
assert_eq!((cfa.width, cfa.height), (2, 2));
for (i, &c) in RGGB.iter().enumerate() {
assert_eq!(cfa.color(i % 2, i / 2), c, "position {i}");
}
assert!(cfa.is_bayer());
assert_eq!(sensor.format, RawFormat::Fff);
}
#[test]
fn metadata() {
let mut s = spec();
s.crop = Some(([2, 2], [12, 8]));
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!(sensor.crop, Rect::new(2, 2, 12, 8));
assert_eq!(sensor.active, Rect::new(0, 0, 16, 12));
assert_eq!(sensor.black, BlackLevels::uniform(4096.0));
assert_eq!(sensor.white, [64763.0; 3]);
let wb = sensor.camera_wb.unwrap();
assert!((wb[0] - 1.0 / 0.375).abs() < 1e-9, "{wb:?}");
assert!((wb[2] - 1.0 / 0.617).abs() < 1e-9, "{wb:?}");
assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("X2D II 100C")));
assert_eq!(sensor.orientation, 1);
assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings);
}
#[test]
fn develops() {
let mut s = spec();
s.crop = Some(([2, 2], [12, 8]));
let b = s.build();
for m in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] {
let d = develop(&b, &DevelopOptions { demosaic: m, ..Default::default() }).unwrap_or_else(|e| panic!("{m:?}: {e}"));
assert_eq!((d.width, d.height), (12, 8), "{m:?}");
}
}
#[test]
fn unknown_body_warns_about_the_assumed_phase() {
let mut s = spec();
s.model = "X2D 100C".into();
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert!(sensor.warnings.iter().any(|w| w.contains("Bayer phase")), "{:?}", sensor.warnings);
}
#[test]
fn compressed_3fr_is_reported_unsupported() {
let mut s = spec();
s.compression = 7;
let e = decode(&s.build(), &Limits::default()).unwrap_err();
assert!(matches!(&e, RawError::Unsupported(reason) if reason.contains("lossless-JPEG")), "{e:?}");
}
#[test]
fn missing_levels_fall_back() {
let mut s = spec();
// Clipped highlights, so the clipping point stands in for the missing WhiteLevel.
for v in s.data.iter_mut().step_by(8) {
*v = u16::MAX;
}
s.black = None;
s.white = None;
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!(sensor.black, BlackLevels::uniform(0.0));
assert!(sensor.warnings.iter().any(|w| w.contains("black level")), "{:?}", sensor.warnings);
// clip_level backs the clipped plateau off slightly.
assert!((sensor.white[0] - f32::from(u16::MAX) * 0.995).abs() < 1.0, "{:?}", sensor.white);
}
#[test]
fn a_crop_outside_the_plane_is_dropped() {
let mut s = spec();
s.crop = Some(([100, 100], [4, 4]));
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!(sensor.crop, Rect::new(0, 0, 16, 12));
}
#[test]
fn active_area_bounds_the_image_and_the_crop() {
let mut s = spec();
s.active_area = Some([1, 2, 11, 14]);
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!(sensor.active, Rect::new(2, 1, 12, 10));
assert_eq!(sensor.crop, Rect::new(2, 1, 12, 10), "no default crop: the active area");
let d = develop(&s.build(), &DevelopOptions::default()).unwrap();
assert_eq!((d.width, d.height), (12, 10));
// The default crop is relative to the active area, as in DNG.
s.crop = Some(([1, 1], [8, 6]));
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!(sensor.crop, Rect::new(3, 2, 8, 6));
}
#[test]
fn an_active_area_outside_the_plane_is_ignored() {
let mut s = spec();
s.active_area = Some([100, 100, 200, 200]);
let sensor = decode(&s.build(), &Limits::default()).unwrap();
assert_eq!((sensor.active, sensor.crop), (Rect::new(0, 0, 16, 12), Rect::new(0, 0, 16, 12)));
}
#[test]
fn truncated_strip_is_malformed() {
let mut b = spec().build();
// The preview blob sits past the strip; cutting 60 bytes eats into the strip.
b.truncate(b.len() - 60);
assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Malformed(_))));
}
#[test]
fn zero_dimensions_are_malformed() {
let mut s = spec();
s.width = 0;
assert!(matches!(decode(&s.build(), &Limits::default()), Err(RawError::Malformed(_))));
}
+1
View File
@@ -3,6 +3,7 @@
mod cr3;
mod development_limits;
mod dng;
mod hasselblad;
mod hostile;
mod nef_packed;
mod nikon_d4_depth;
+5 -2
View File
@@ -133,6 +133,7 @@ impl PhotocraftApp {
synthetic_reinject: false,
synthetic_snapshot: None,
automation_input: false,
programmatic_playback: false,
run_depth: 0,
paused_playbacks: Default::default(),
channel_thumbs: None,
@@ -169,7 +170,7 @@ impl PhotocraftApp {
distort: Default::default(),
gradient: Default::default(),
camera_raw: None,
pending_raw_open: None,
raw_shelf: Vec::new(),
raw_redevelop: Vec::new(),
wide_angle: None,
dialog_edits: Default::default(),
@@ -208,6 +209,8 @@ impl PhotocraftApp {
held_memory_prompts: Default::default(),
prompt_order: Default::default(),
held_preset_import: None,
held_record_again: None,
held_insert_menu: None,
allow_close: false,
stylus: Default::default(),
control_click: Default::default(),
@@ -234,7 +237,7 @@ impl PhotocraftApp {
impl eframe::App for PhotocraftApp {
fn on_exit(&mut self) {
if let Err(err) = tool_memory::save_on_exit(self) {
log::warn!("Preferences: could not save the final tool selection: {err}");
log::warn!("Preferences: could not save the final tool state: {err}");
}
// Release a pending screenshot's image budget and answer its control request; the
// callback is inert afterwards (it holds only a weak slot).
+9
View File
@@ -6,6 +6,7 @@ use super::{
impl PhotocraftApp {
/// Run an engine command, reporting errors in the status bar.
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
let params = if id == "select.findLayers" { crate::layer_filter_ui::find::params_for_run(self, params) } else { params };
if let Some(result) = delete_layer_prompt::intercept(self, id, &params) {
return result;
}
@@ -31,6 +32,13 @@ impl PhotocraftApp {
}
self.sync_mask_targets();
}
// Find Layers sets the Layers panel's Name filter however it runs: the menu, the shortcut,
// `engine.execute` or an action step (#10884).
if id == "select.findLayers"
&& let Ok(reply) = &result
{
crate::layer_filter_ui::find::apply(self, reply);
}
result
}
@@ -264,6 +272,7 @@ impl PhotocraftApp {
| "path.toSelection"
| "path.addToSelection"
| "path.subtractFromSelection"
| "path.intersectWithSelection"
)
&& self.session.active().is_some_and(|st| st.doc.selection.is_some())
{
@@ -0,0 +1,207 @@
//! ⌥ (Alt) with the Background Eraser is the Eyedropper, as with the Brush (#11906): a click or
//! drag sets the foreground colour, adds no history state and changes no pixel, and the cursor
//! is the pipette while ⌥ is held. Control+⌥ stays the brush-resize gesture.
use egui::{Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::ViewXform;
use crate::state::Tool;
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
crate::shortcuts::handle(app, &ctx);
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(4);
let v = &mut h.state_mut().ui.views[0];
v.zoom = 1.0;
v.center = [100.0, 50.0];
v.fit_pending = false;
h.run_steps(2);
h
}
fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 {
let app = h.state();
let v = &app.ui.views[0];
let xf = ViewXform {
rect: crate::rulers::content_rect(app, app.last_canvas_rect),
zoom: v.zoom,
center: v.center,
flip: app.ui.view.flip_horizontal,
rotation: v.rotation,
aspect: app.ui.view.display_aspect(),
};
xf.to_screen(x, y)
}
fn mods(h: &mut Harness<'static, PhotocraftApp>, m: Modifiers) {
h.event(egui::Event::ModifiersChanged(m));
h.run_steps(1);
}
fn button(h: &mut Harness<'static, PhotocraftApp>, b: PointerButton, p: Pos2, down: bool, m: Modifiers) {
h.event(egui::Event::PointerButton { pos: p, button: b, pressed: down, modifiers: m });
h.run_steps(1);
}
/// Press `b` at document point `from` with `m` held from before the press, and move to `to`;
/// the button stays down.
fn press_and_move(h: &mut Harness<'static, PhotocraftApp>, b: PointerButton, from: [f32; 2], to: [f32; 2], m: Modifiers) {
let p = screen(h, from[0], from[1]);
mods(h, m);
h.event(egui::Event::PointerMoved(p));
h.run_steps(1);
button(h, b, p, true, m);
if from != to {
for i in 1..=8 {
let t = i as f32 / 8.0;
let q = screen(h, from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t);
h.event(egui::Event::PointerMoved(q));
h.run_steps(1);
}
}
}
/// Release `b` at document point `at`, then let go of the modifiers.
fn release(h: &mut Harness<'static, PhotocraftApp>, b: PointerButton, at: [f32; 2], m: Modifiers) {
button(h, b, screen(h, at[0], at[1]), false, m);
h.run_steps(2);
mods(h, Modifiers::NONE);
}
/// A drag between document points with `m` held from before the press until after the
/// release; `from == to` is a click.
fn drag(h: &mut Harness<'static, PhotocraftApp>, from: [f32; 2], to: [f32; 2], m: Modifiers) {
press_and_move(h, PointerButton::Primary, from, to, m);
release(h, PointerButton::Primary, to, m);
}
/// Red on the left, green on the right of an unlocked layer, Background Eraser active, blue
/// foreground and white background colour.
fn background_eraser() -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
app.run("edit.fill", json!({"color": "#00ff00"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
app.run("tools.setColors", json!({"foreground": BLUE, "background": [1.0, 1.0, 1.0, 1.0]})).unwrap();
app.sync_views();
let mut h = harness(app);
h.state_mut().ui.tool = Tool::BackgroundEraser;
h.run_steps(1);
h
}
/// The document and the number of history states, to show nothing changed.
fn snapshot(h: &Harness<'static, PhotocraftApp>) -> (std::sync::Arc<photocraft_doc::Document>, usize) {
let st = h.state().session.active().unwrap();
(st.doc.clone(), st.history.past_len())
}
fn unchanged(h: &Harness<'static, PhotocraftApp>, before: &(std::sync::Arc<photocraft_doc::Document>, usize), what: &str) {
let (doc, steps) = snapshot(h);
assert!(std::sync::Arc::ptr_eq(&doc, &before.0), "{what}: no pixel changed");
assert_eq!(steps, before.1, "{what}: no history state");
}
#[test]
fn alt_click_sets_the_foreground_without_erasing() {
let mut h = background_eraser();
let before = snapshot(&h);
drag(&mut h, [150.0, 50.0], [150.0, 50.0], Modifiers::ALT);
assert_eq!(h.state().session.tools.foreground, GREEN, "⌥-click picked green");
assert_eq!(h.state().session.tools.background, [1.0, 1.0, 1.0, 1.0], "the background colour stays");
unchanged(&h, &before, "⌥-click");
assert!(!h.state().alt_sampling, "the release ends the sampling");
}
#[test]
fn alt_drag_follows_the_pointer_without_erasing() {
let mut h = background_eraser();
let before = snapshot(&h);
press_and_move(&mut h, PointerButton::Primary, [150.0, 50.0], [40.0, 50.0], Modifiers::ALT);
assert_eq!(h.state().session.tools.foreground, RED, "⌥-drag samples while the button is held");
release(&mut h, PointerButton::Primary, [40.0, 50.0], Modifiers::ALT);
assert_eq!(h.state().session.tools.foreground, RED, "⌥-drag ends on red");
unchanged(&h, &before, "⌥-drag");
}
/// The same press without ⌥ still erases: the harness drives the real tool.
#[test]
fn a_click_without_alt_still_erases() {
let mut h = background_eraser();
let (_, steps) = snapshot(&h);
drag(&mut h, [150.0, 50.0], [150.0, 50.0], Modifiers::NONE);
assert_eq!(h.state().session.tools.foreground, BLUE);
assert_eq!(snapshot(&h).1, steps + 1, "the stroke added a history state");
let st = h.state().session.active().unwrap();
let layer = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
assert_eq!(layer.rgba(150, 50)[3], 0.0, "the clicked pixel was erased");
}
/// While ⌥ is held the cursor is the Eyedropper's pipette (`pipette_cursor`), where the
/// Background Eraser otherwise shows its own tip; Control+⌥ keeps the tip.
#[test]
fn alt_shows_the_eyedropper_cursor() {
let mut h = background_eraser();
let p = screen(&h, 150.0, 50.0);
let pipette = |h: &mut Harness<'static, PhotocraftApp>, m: Modifiers| {
mods(h, m);
h.hover_at(p);
h.run_steps(2);
let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-icon-cursor"));
let shown = h.ctx.memory(|memory| memory.areas().visible_layer_ids().contains(&layer));
(shown, h.output().platform_output.cursor_icon)
};
assert_eq!(pipette(&mut h, Modifiers::ALT), (true, egui::CursorIcon::None), "⌥: the pipette replaces the pointer");
assert!(!pipette(&mut h, Modifiers::NONE).0, "without ⌥: the eraser's own tip");
assert!(!pipette(&mut h, Modifiers::ALT | Modifiers::CTRL).0, "Control+⌥ is not the Eyedropper");
assert!(pipette(&mut h, Modifiers::ALT).0, "⌥ again: the pipette again");
}
/// Control+⌥-drag stays the brush-resize gesture: it samples nothing and erases nothing.
#[test]
fn ctrl_alt_drag_resizes_instead_of_sampling() {
assert!(crate::canvas::alt_samples(Tool::BackgroundEraser, Modifiers::ALT));
assert!(!crate::canvas::alt_samples(Tool::BackgroundEraser, Modifiers::ALT | Modifiers::CTRL));
let mut h = background_eraser();
h.state_mut().run("tools.setBrush", json!({"brush": {"size": 40}})).unwrap();
let before = snapshot(&h);
drag(&mut h, [150.0, 50.0], [40.0, 50.0], Modifiers::ALT | Modifiers::CTRL);
assert_eq!(h.state().session.tools.foreground, BLUE, "Control+⌥ sampled nothing");
unchanged(&h, &before, "Control+⌥-drag");
assert_ne!(h.state().session.tools.brush.size, 40.0, "Control+⌥-drag resized the brush");
}
/// ⌥+right-drag (not measured in the reference application) keeps today's meaning, the brush
/// resize: it samples nothing and erases nothing.
#[test]
fn alt_right_drag_resizes_instead_of_sampling() {
let mut h = background_eraser();
h.state_mut().run("tools.setBrush", json!({"brush": {"size": 40}})).unwrap();
let before = snapshot(&h);
press_and_move(&mut h, PointerButton::Secondary, [150.0, 50.0], [40.0, 50.0], Modifiers::ALT);
release(&mut h, PointerButton::Secondary, [40.0, 50.0], Modifiers::ALT);
assert_eq!(h.state().session.tools.foreground, BLUE, "⌥+right-drag sampled nothing");
unchanged(&h, &before, "⌥+right-drag");
assert_ne!(h.state().session.tools.brush.size, 40.0, "⌥+right-drag resized the brush");
}
@@ -0,0 +1,134 @@
//! Shift+Alt+Q selects Behind for Brush and Pencil (#11894).
use egui::{Context, Event, Key, Modifiers, RawInput};
use photocraft_color::BlendMode;
use photocraft_engine::Session;
use serde_json::json;
use crate::PhotocraftApp;
use crate::brush_mode_menu::{self, Item};
use crate::state::Tool;
/// Create a test document for the selected tool, optionally with a transparent layer.
fn app(tool: Tool, transparent_layer: bool) -> PhotocraftApp {
let mut app = PhotocraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
if transparent_layer {
app.run("layer.new.layer", json!({})).unwrap();
}
app.ui.tool = tool;
app
}
/// Send Shift+Alt+Q through the shortcut handler and assert that it consumes the key.
fn press_behind(app: &mut PhotocraftApp, ctx: &Context) {
let modifiers = Modifiers::SHIFT | Modifiers::ALT;
let events = vec![Event::ModifiersChanged(modifiers), Event::Key { key: Key::Q, physical_key: Some(Key::Q), pressed: true, repeat: false, modifiers }];
ctx.begin_pass(RawInput { events, ..Default::default() });
crate::shortcuts::handle(app, ctx);
assert!(!ctx.input(|i| i.events.iter().any(|e| matches!(e, Event::Key { key: Key::Q, .. }))));
ctx.end_pass().textures_delta.clear();
}
/// Check whether the rendered options bar displays the Behind label.
fn options_show_behind(app: &mut PhotocraftApp, ctx: &Context) -> bool {
/// Find the Behind text label in a shape or its descendants.
fn has_behind(shape: &egui::Shape) -> bool {
match shape {
egui::Shape::Text(text) => text.galley.text() == "Behind",
egui::Shape::Vec(shapes) => shapes.iter().any(has_behind),
_ => false,
}
}
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 300.0)));
let mut out = ctx.run_ui(RawInput { screen_rect, ..Default::default() }, |ui| crate::panels::options_bar(app, ui));
out.textures_delta.clear();
out.shapes.iter().any(|shape| has_behind(&shape.shape))
}
/// The key leaves Clear, uses one menu-equivalent command, and changes the displayed Mode.
#[test]
fn brush_and_pencil_select_behind_in_one_command() {
for tool in [Tool::Brush, Tool::Pencil] {
let mut app = app(tool, true);
app.ui.tool_options.brush_clear = true;
app.ui.tool_options.pencil_clear = true;
app.session.tools.brush.mode = BlendMode::Multiply;
let ctx = Context::default();
PhotocraftApp::setup_context(&ctx, Default::default());
assert!(brush_mode_menu::enabled(&app, Item::Behind));
let (id, params) = brush_mode_menu::engine_call(&app, tool, Item::Behind).unwrap();
assert_eq!((id, &params), ("tools.setBrush", &json!({"brush": {"mode": "Normal", "behind": true}})));
let before = app.session.journal.len();
press_behind(&mut app, &ctx);
assert_eq!(&app.session.journal[before..], &[(id.to_owned(), params)]);
assert_eq!(app.ui.brush_tool, tool);
assert_eq!(app.ui.tool_options.brush_clear, tool != Tool::Brush);
assert_eq!(app.ui.tool_options.pencil_clear, tool != Tool::Pencil);
let brush = app.session.execute("brush.get", json!({})).unwrap();
assert_eq!(brush["behind"], true);
assert_eq!(brush["mode"], "Normal");
assert!(options_show_behind(&mut app, &ctx), "{tool:?}");
}
}
/// A shortcut on the start screen must leave both the live brush and its owning tool alone.
#[test]
fn brush_and_pencil_do_not_select_behind_without_a_document() {
for (tool, brush_tool) in [(Tool::Brush, Tool::Pencil), (Tool::Pencil, Tool::Brush)] {
let mut app = PhotocraftApp::new(Session::new(), Default::default());
assert!(app.session.active().is_none());
app.ui.tool = tool;
app.ui.brush_tool = brush_tool;
app.ui.tool_options.brush_clear = true;
app.ui.tool_options.pencil_clear = true;
app.session.tools.brush.mode = BlendMode::Multiply;
let brush = app.session.execute("brush.get", json!({})).unwrap();
let before = app.session.journal.len();
press_behind(&mut app, &Context::default());
assert_eq!(app.session.journal.len(), before);
assert_eq!(app.session.execute("brush.get", json!({})).unwrap(), brush);
assert_eq!(app.ui.brush_tool, brush_tool);
assert!(app.ui.tool_options.brush_clear && app.ui.tool_options.pencil_clear);
}
}
/// The same Background restriction used by the menu applies before the shortcut changes settings.
#[test]
fn background_does_not_accept_behind() {
for tool in [Tool::Brush, Tool::Pencil] {
let mut app = app(tool, false);
app.ui.tool_options.brush_clear = true;
app.ui.tool_options.pencil_clear = true;
let ctx = Context::default();
assert!(!brush_mode_menu::enabled(&app, Item::Behind));
let before = app.session.journal.len();
let brush_tool = app.ui.brush_tool;
let brush = app.session.execute("brush.get", json!({})).unwrap();
press_behind(&mut app, &ctx);
assert_eq!(app.session.journal.len(), before);
assert_eq!(app.session.execute("brush.get", json!({})).unwrap(), brush);
assert_eq!(app.ui.brush_tool, brush_tool);
assert!(app.ui.tool_options.brush_clear && app.ui.tool_options.pencil_clear);
}
}
/// The consumed key stays a no-op for layers and for tools outside the measured scope.
#[test]
fn other_tools_keep_the_behind_key_as_a_no_op() {
for tool in [Tool::Move, Tool::CloneStamp, Tool::PatternStamp, Tool::HistoryBrush, Tool::Gradient, Tool::PaintBucket] {
let mut app = app(tool, true);
let ctx = Context::default();
let before = app.session.journal.len();
let brush_tool = app.ui.brush_tool;
let active = app.session.active().unwrap();
let layer = active.active_layer.unwrap();
let blend = active.doc.layer(layer).unwrap().blend;
press_behind(&mut app, &ctx);
assert_eq!(app.session.journal.len(), before, "{tool:?}");
assert_eq!(app.ui.tool, tool);
assert_eq!(app.ui.brush_tool, brush_tool);
assert_eq!(app.session.active().unwrap().doc.layer(layer).unwrap().blend, blend);
assert!(!app.session.tools.brush.behind);
}
}
+15 -6
View File
@@ -2002,9 +2002,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
None => paint_dots(ui, rect, app.session.prefs().interface.show_canvas_dots),
}
let border = app.session.prefs().interface.canvas_border;
// Default-mode Crop changes its camera during input. Defer its image until the new camera
// is known; other tools keep their existing paint order and texture/outline snapshots.
// Default-mode Crop changes its camera during input. Live painting must also process the
// current pointer samples before preparing the image, or every dab appears a frame late.
// Under a dialog the image keeps its place below the dialog's own overlays (Refine Edge).
let crop_camera = primary && crate::crop_mode::moves_image(app);
let paint_after_input = crop_camera || (primary && app.ui.dialogs.is_empty() && strokes_live(app.ui.tool));
let paint_input = CanvasPaintInput {
ctx: &ctx,
rect,
@@ -2022,7 +2024,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
target_xf,
pixel_grid,
};
let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &display_view, xf, &paint_input)) };
let painted = if paint_after_input { None } else { Some(paint_canvas(app, ui, &display_view, xf, &paint_input)) };
let img_rect = xf.doc_rect(doc.bounds());
// Under an open dialog the canvas widget is inert, but the image still pans and zooms.
@@ -2043,7 +2045,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
app.stylus.update_for_frame(ui.ctx().cumulative_frame_nr(), &ui.input(|i| i.events.clone()));
crate::stylus::Stylus::sync_eraser_tool(app);
// A Magnetic Lasso border left behind by a tool or document switch is dropped.
crate::magnetic_lasso_ui::frame(app);
crate::magnetic_lasso_ui::frame(app, ui.input(|i| i.pointer.primary_down()), primary);
// A Properties Levels/Curves eyedropper left behind by a tool or layer switch is dropped.
crate::layer_picker::prune(app);
// Held keys (hold_keys.rs): Space repositions a crop frame, marquee, lasso or shape being
@@ -2190,12 +2192,16 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
ctx.request_repaint();
}
}
let xf = if crop_camera {
let xf = if paint_after_input {
// This frame's navigation input (wheel pan, pinch zoom) shows in this frame too.
if view.zoom != render_zoom {
display_view.zoom = view.zoom;
}
if view.center != target_xf.center {
display_view.center = view.center;
}
display_view.rotation = view.rotation;
ViewXform { center: display_view.center, rotation: display_view.rotation, ..xf }.pixel_aligned_for(app, ppp)
ViewXform { zoom: display_view.zoom / ppp, center: display_view.center, rotation: display_view.rotation, ..xf }.pixel_aligned_for(app, ppp)
} else {
xf
};
@@ -2293,6 +2299,9 @@ mod layer_edges_tests;
#[cfg(test)]
mod guide_ants_tests;
#[cfg(test)]
mod live_frame_tests;
#[cfg(test)]
mod rotation_preview_isolation_tests {
use super::*;
+6 -2
View File
@@ -112,10 +112,10 @@ pub(super) fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter,
const RING_GREY: Color32 = Color32::from_gray(127);
/// Tools on which holding ⌥ (Alt) switches to the Eyedropper: a click or drag sets the
/// foreground colour, as with the Eyedropper itself (#417).
/// foreground colour, as with the Eyedropper itself (#417, the Background Eraser #11906).
pub(crate) fn alt_samples(tool: Tool, mods: egui::Modifiers) -> bool {
// Control+Alt is the brush-resize drag (`brush_resize`), not sampling.
mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket)
mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket | Tool::BackgroundEraser)
}
/// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the
@@ -303,3 +303,7 @@ pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool {
#[cfg(test)]
#[path = "../eyedropper_mask_sample_tests.rs"]
mod eyedropper_mask_sample_tests;
#[cfg(test)]
#[path = "../background_eraser_alt_click_tests.rs"]
mod background_eraser_alt_click_tests;
+6
View File
@@ -86,6 +86,12 @@ impl Drag {
}
}
/// The document and target a vector drag was pressed on are still the current ones
/// ([`VectorGestureOwner`]); false for a drag that captured none.
pub(crate) fn vector_owner_valid(&self, app: &PhotocraftApp) -> bool {
self.vector_owner.as_ref().is_some_and(|owner| owner.valid(app))
}
/// Reposition: move the start and every point so the last one lands on `to` (same size).
pub fn shift_to(&mut self, to: [f64; 2]) {
let last = self.points.last().map_or(self.start, |p| [p[0], p[1]]);
+41 -23
View File
@@ -58,8 +58,10 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
}
params = crate::select_mask_view::request_params(&d.fields, params);
}
crate::actions::authorize_panel_preview(app, d.id, &d.fields, &cmd, &params).ok()?;
let st = app.session.documents().get(idx)?;
let k = filter_preview_factor(app, &st.doc, &cmd, &params);
// Fade previews at full size: it blends one area, like OK does, and has no proxy (#8230).
let k = if cmd == FADE { 1 } else { filter_preview_factor(app, &st.doc, &cmd, &params) };
let request = crate::filter_dialog::FilterPreviewKey {
doc: st.doc.id,
revision: st.revision,
@@ -111,19 +113,23 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
let color = app.session.color.settings.clone();
let task = request.clone();
let fade = fade_job(app, &task);
if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| {
let t0 = crate::gpu_canvas::now_ms();
let result = crate::filter_dialog::preview_document_for_target(
&doc,
task.active,
&task.command,
&task.params,
task.k,
Some(cancel),
task.target,
&documents,
&color,
)
let result = match fade {
Some(fade) => fade.and_then(|f| f.render().ok()),
None => crate::filter_dialog::preview_document_for_target(
&doc,
task.active,
&task.command,
&task.params,
task.k,
Some(cancel),
task.target,
&documents,
&color,
),
}
.map(|doc| {
let buffer = photocraft_compose::flatten(&doc);
(std::sync::Arc::new(doc), buffer)
@@ -154,17 +160,20 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
let doc = app.session.documents().get(idx)?.doc.clone();
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
let t0 = crate::gpu_canvas::now_ms();
let computed = crate::filter_dialog::preview_document_for_target(
&doc,
request.active,
&request.command,
&request.params,
request.k,
None,
request.target,
&documents,
&app.session.color.settings,
)
let computed = match fade_job(app, &request) {
Some(fade) => fade.and_then(|f| f.render().ok()),
None => crate::filter_dialog::preview_document_for_target(
&doc,
request.active,
&request.command,
&request.params,
request.k,
None,
request.target,
&documents,
&app.session.color.settings,
),
}
.map(|doc| {
let buffer = photocraft_compose::flatten(&doc);
(std::sync::Arc::new(doc), buffer)
@@ -176,6 +185,15 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
Some((preview.key.k, key, [result.size.width, result.size.height]))
}
const FADE: &str = "edit.fade";
/// Edit › Fade blends back towards the pixels before the last step, which only the session's
/// history holds, so its preview is captured from the session here (cheap: the copy shares its
/// tiles) and blended where filter previews compute (#8230). `None` for every other command.
fn fade_job(app: &PhotocraftApp, request: &crate::filter_dialog::FilterPreviewKey) -> Option<Option<photocraft_engine::edit_menu_cmds::FadePreview>> {
(request.command == FADE).then(|| photocraft_engine::edit_menu_cmds::fade_preview(&app.session, &request.params).ok())
}
/// Channel overlays must use the filter's current proxy too, including on the CPU canvas.
/// The cache key changes with the completed request; unchanged frames reuse the overlay texture.
pub(crate) fn filter_channel_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(std::sync::Arc<Document>, u64)> {
@@ -230,6 +230,31 @@ fn edit_selected_guides_opens_new_guide_on_the_guide_and_applies_the_edit() {
assert_eq!(selected(&app), Some((true, 1)), "the edited guide stays selected");
}
/// #10440: Edit Selected Guides' position takes arithmetic as New Guide's does, a leading bare
/// number in the ruler unit.
#[test]
fn edit_selected_guides_takes_arithmetic_in_the_position() {
let mut app = app();
app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap();
click(&mut app, 50.0, 70.0);
let id = crate::new_guide_ui::open_edit(&mut app).unwrap();
let mut edited = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
// "30 + 10" with percent rulers is 40 % of the 200 px width.
edited.insert("position".into(), json!("30 + 10"));
assert_eq!(crate::new_guide_ui::params(&app, &edited)["position"], "30 % + 10");
app.ui.dialogs.retain(|d| d.id != id);
crate::new_guide_ui::confirm(&mut app, &edited).unwrap();
assert_eq!(guides(&app), (vec![80.0], vec![30.0]));
assert_eq!(selected(&app), Some((true, 0)), "the edited guide stays selected");
// A unit on the first operand wins: 100 % of the width less 50 px.
let id = crate::new_guide_ui::open_edit(&mut app).unwrap();
let mut edited = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
edited.insert("position".into(), json!("100% - 50px"));
app.ui.dialogs.retain(|d| d.id != id);
crate::new_guide_ui::confirm(&mut app, &edited).unwrap();
assert_eq!(guides(&app), (vec![150.0], vec![30.0]));
}
#[test]
fn editing_an_uncoloured_guide_keeps_the_preference_colour_unless_one_is_chosen() {
let mut app = app();
@@ -0,0 +1,96 @@
//! Live painting tools show this frame's pointer input in this frame (no extra frame of delay),
//! and the deferred image follows the animated camera.
use super::*;
use serde_json::json;
#[test]
fn live_brush_texture_includes_this_frames_press_and_moves() {
for tool in [Tool::Brush, Tool::MixerBrush] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 128, "height": 64, "background": "white"})).unwrap();
app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap();
app.ui.tool = tool;
app.sync_views();
let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 640.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
egui::CentralPanel::default().show(ui, |ui| document_area(app, ui));
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(3);
let p = h.state().last_canvas_rect.center();
h.input_mut().events.push(egui::Event::PointerMoved(p));
h.input_mut().events.push(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
let shown = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| {
let app = h.state_mut();
let live = app.live_stroke.as_ref().expect("painting starts on press");
let key = live.display_key();
let doc = live.stroke.doc().clone();
let (_, display) = canvas_display(app, &doc, None);
assert_eq!(app.canvases.values().next().unwrap().tex_preview_key, key ^ display, "{tool:?}: texture includes this frame's input");
};
shown(&mut h);
h.input_mut().events.push(egui::Event::PointerMoved(p + vec2(25.0, 0.0)));
h.run_steps(1);
shown(&mut h);
let end = p + vec2(25.0, 0.0);
h.input_mut().events.push(egui::Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
assert!(h.state().live_stroke.is_none());
// The Brush keeps the shown pixels as its committed stroke; the Mixer Brush commits the
// pixels its live preview rendered (`gesture.rs`).
if tool == Tool::Brush {
assert!(h.state().committed_stroke.is_some(), "release reuses the shown pixels");
}
let label = h.state().session.active().and_then(|st| st.history.undo_label()).map(str::to_owned);
assert_eq!(label.as_deref(), Some(if tool == Tool::MixerBrush { "Mixer Brush" } else { "Brush Tool" }));
assert!(!h.state().ui.status_error, "{}", h.state().ui.status);
}
}
#[test]
fn live_tools_paint_the_interpolated_camera_during_zoom_animation() {
for tool in [Tool::Brush, Tool::MixerBrush] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
app.run("prefs.set", json!({"values": {"general.animatedZoom": true}})).unwrap();
app.sync_views();
app.ui.tool = tool;
let v = &mut app.ui.views[0];
v.fit_pending = false;
v.zoom = 2.0;
v.center = [32.0, 32.0];
v.doc_size = [64, 64];
v.zoom_animating = true;
v.display_camera = Some((1.0, [32.0, 32.0]));
v.zoom_transition = Some(crate::state::ZoomTransition { from: (1.0, [32.0, 32.0]), target: (2.0, [32.0, 32.0]), started: 0.0 });
let view = v.clone();
let ctx = egui::Context::default();
let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0;
let rect = Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), time: Some(0.1), ..Default::default() }, |ui| {
canvas_view(&mut app, ui, 0, rect, view.clone(), true);
});
out.textures_delta.clear();
let mesh = out
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Mesh(mesh) if mesh.texture_id == tex => Some(mesh),
_ => None,
})
.unwrap();
let min = mesh.vertices.iter().map(|v| v.pos.x).fold(f32::INFINITY, f32::min);
let max = mesh.vertices.iter().map(|v| v.pos.x).fold(f32::NEG_INFINITY, f32::max);
let shown = app.ui.views[0].display_camera.unwrap().0;
assert!(shown > 1.0 && shown < 2.0, "{tool:?}: animation is between endpoints");
assert!(((max - min) - 64.0 * shown).abs() < 0.01, "{tool:?}: image must use the animated camera, width {} at zoom {shown}", max - min);
}
}
+13 -4
View File
@@ -67,10 +67,19 @@ fn session_fields(current: &BrushSettings, brush: &BrushSettings) -> BrushSettin
BrushSettings { color: current.color, background: current.background, erase: current.erase, seed: current.seed, ..brush.clone() }
}
/// A tool's brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's
/// smoothing, with the session's own fields of `current`.
pub(crate) fn fresh_brush(current: &BrushSettings) -> BrushSettings {
session_fields(current, &BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() })
/// The Brush tool's tip after Reset Tool, as the reference measures it (#11810): size, hardness
/// and spacing of a 13 px soft round at 25 % spacing.
const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25);
/// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's
/// smoothing, with the session's own fields of `current`. The Brush tool's tip is
/// [`BRUSH_TOOL_TIP`]; the other tools keep the default tip.
pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings {
let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() };
if tool == Tool::Brush {
(brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP;
}
session_fields(current, &brush)
}
/// Photoshop's 10 % stroke smoothing, what a tool's brush starts at.
+41 -2
View File
@@ -18,13 +18,17 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::brush_mode_menu::show(app, ui.ctx());
}
/// Where each docked document is drawn under Window › Arrange: its index and the cell it gets,
/// at the border positions the user has dragged them to. `None` with no docked document, or when
/// the arrangement is the plain single canvas. With more documents than the layout has cells, the
/// shown run starts at [`PhotocraftApp::arrange_start`] and always includes the active one.
pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option<Vec<(usize, Rect)>> {
let documents = docked_document_indices(app);
let n = documents.len();
if n == 0 {
return None;
}
let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n)?;
let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n, &app.ui.view.arrange_splits)?;
// Keep stable tiles, expressing the remembered document index in the filtered docked list.
let start = documents.partition_point(|&d| d < app.arrange_start).min(n.saturating_sub(cells.len()));
let idx = app.session.active_index().and_then(|d| documents.iter().position(|&p| p == d));
@@ -109,19 +113,27 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if let Some(shown) = arranged_cells(app, rect) {
app.arrange_start = shown.first().map_or(0, |(d, _)| *d);
let t = crate::theme::Tokens::get(ui.ctx());
// A press on a border grip drags the border (`drag_borders`); it activates no document.
// The grips are laid out after the canvases, so egui gives them the press (#10101).
let grips: Vec<Rect> = border_grips(app, rect).into_iter().map(|(_, grip)| grip).collect();
for (d, cell) in shown {
let cell = cell.shrink(1.0);
let view = app.ui.views[d].clone();
let v = canvas_view(app, ui, d, cell, view, d == active_doc);
if d != active_doc {
app.ui.views[d] = v;
if main_focused && ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) {
if main_focused
&& ui.input(|i| {
i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p) && !grips.iter().any(|g| g.contains(p)))
})
{
app.session.set_active(d);
}
}
let stroke = if d == active_doc { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) };
ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside);
}
drag_borders(app, ui, rect);
return;
}
if idx != active_doc && main_focused && ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| rect.contains(p))) {
@@ -131,6 +143,33 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
canvas_view(app, ui, idx, rect, view, app.session.active_index() == Some(idx));
}
/// Window › Arrange: the borders between the documents are dragged to give one more room, as in
/// Photoshop (#10101). Laid out after the canvases, so a grip over a cell's edge takes the press.
fn drag_borders(app: &mut PhotocraftApp, ui: &egui::Ui, rect: Rect) {
let n = docked_document_indices(app).len();
let layout = app.ui.view.arrange.clone();
for (border, grip) in border_grips(app, rect) {
let response = ui.interact(grip, ui.scope_id().with(("arrange-border", border.split)), Sense::drag());
if response.hovered() || response.dragged() {
ui.ctx().set_cursor_icon(if border.vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
}
if response.dragged()
&& let Some(p) = response.interact_pointer_pos()
{
crate::view_cmds::drag_border(&layout, rect, n, &mut app.ui.view.arrange_splits, border.split, p);
}
}
}
/// The arrangement's borders, each with the strip either side of it that grabs it.
fn border_grips(app: &PhotocraftApp, rect: Rect) -> Vec<(crate::view_cmds::Border, Rect)> {
let n = docked_document_indices(app).len();
crate::view_cmds::borders(&app.ui.view.arrange, rect, n, &app.ui.view.arrange_splits)
.into_iter()
.map(|b| (b, b.line.expand2(if b.vertical { egui::vec2(3.0, 0.0) } else { egui::vec2(0.0, 3.0) })))
.collect()
}
/// The tab strip; returns where its document tabs are.
pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {
let t = crate::theme::Tokens::get(ui.ctx());
+50
View File
@@ -3072,3 +3072,53 @@ fn torn_off_document_is_not_drawn_again_in_the_main_window() {
assert_eq!(tabs, Some(vec![1]), "{kind:?}: only the docked document stays on the main tab strip");
}
}
/// #8230: Edit › Fade opens with a Preview checkbox, and the canvas shows the layer faded with the
/// dialog's opacity, at full size, on the background worker and the inline path alike. Cancel
/// leaves the document, its history and Fade itself as they were; OK applies what was shown.
#[test]
fn fade_dialog_previews_the_faded_layer_and_cancel_keeps_the_document() {
for background in [false, true] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap();
app.run("edit.fill", json!({"color": "#000000"})).unwrap();
app.background_jobs = background;
let ctx = egui::Context::default();
let st = app.session.active().unwrap();
let (layer, steps, revision) = (st.active_layer.unwrap(), st.history.past_len(), st.revision);
let id = crate::filter_dialog::open(&mut app, "edit.fade").expect("Fade has a dialog");
let d = app.ui.dialog_mut(id).expect("the dialog");
assert_eq!(d.fields.get("__preview"), Some(&json!(true)), "a Preview checkbox, on");
d.fields.insert("opacity".into(), json!(25));
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let (k, size) = loop {
if let Some((k, _, size)) = ensure_filter_preview(&mut app, 0, &ctx)
&& app.filter_preview.as_ref().is_some_and(|p| p.key.params.get("opacity") == Some(&json!(25)))
{
break (k, size);
}
assert!(std::time::Instant::now() < deadline, "background jobs {background}: no preview");
std::thread::sleep(std::time::Duration::from_millis(1));
};
assert_eq!((k, size), (1, [40, 30]), "background jobs {background}: full size");
let shown = app.filter_preview.as_ref().and_then(|p| p.result.as_ref()).expect("a result").layer(layer).unwrap().surface().unwrap().pixel(3, 3);
assert!((shown[0] - 0.75).abs() < 0.01, "background jobs {background}: {shown:?}");
// Cancel: nothing changed, nothing previewed, and Fade is still there to use.
app.ui.close_dialog(id);
assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "background jobs {background}: no preview after Cancel");
let st = app.session.active().unwrap();
assert_eq!(st.doc.layer(layer).unwrap().surface().unwrap().pixel(3, 3)[0], 0.0, "background jobs {background}: the layer is untouched");
assert_eq!((st.history.past_len(), st.revision), (steps, revision), "background jobs {background}: no history step");
assert!(app.session.is_enabled("edit.fade"), "background jobs {background}: Fade is still available");
// OK applies the faded layer as one step.
let id = crate::filter_dialog::open(&mut app, "edit.fade").unwrap();
app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(25));
crate::dialogs::confirm(&mut app, id).unwrap();
let st = app.session.active().unwrap();
let faded = st.doc.layer(layer).unwrap().surface().unwrap().pixel(3, 3)[0];
assert!((faded - shown[0]).abs() < 1e-6, "background jobs {background}: OK applies the preview ({faded})");
assert_eq!(st.history.past_len(), steps + 1);
}
}
+6 -1
View File
@@ -116,7 +116,12 @@ fn execute_command(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRe
// params and never open a dialog (an agent would otherwise get a modal instead of a
// result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog.
if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() {
return run_waiting(app, wait, |app| app.run(id, params));
return run_waiting(app, wait, |app| {
let previous = std::mem::replace(&mut app.programmatic_playback, true);
let result = app.run(id, params);
app.programmatic_playback = previous;
result
});
}
run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params))
}
+20 -3
View File
@@ -311,6 +311,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields:
_ if crate::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields),
_ if crate::actions::owns_stop_message(fields) => crate::actions::stop_message_body(ui, fields),
_ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_body(ui, fields),
_ if crate::actions::menu_item::owns(fields) => crate::actions::menu_item::body(ui, fields),
_ if crate::actions::owns_new_set(fields) => crate::actions::new_set_body(ui, fields),
_ if crate::actions::playback::owns(fields) => crate::actions::playback::body(ui, fields),
_ if crate::new_layer_ui::owns(fields) => crate::new_layer_ui::body(ui, fields),
@@ -320,7 +321,6 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields:
_ if crate::stack_dialog::owns(fields) => crate::stack_dialog::body(app, ui, fields, d.id),
_ if crate::tool_reset::owns(fields) => crate::tool_reset::body(ui),
_ if crate::crop_presets::owns(fields) => crate::crop_presets::body(app, ui, fields),
_ if crate::variables_ui::owns(fields) => crate::variables_ui::body(app, ui, fields),
_ => return command_body_more(app, ui, d, fields, id),
}
outcome
@@ -330,6 +330,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields:
fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id) -> Option<bool> {
let mut outcome: Option<bool> = None;
match d.kind {
_ if crate::variables_ui::owns(fields) => crate::variables_ui::body(app, ui, fields),
_ if merge_channels_ui::owns(fields) => merge_channels_ui::body(ui, fields),
_ if crate::file_ui::owns(fields) => crate::file_ui::body(app, ui, fields, d.id),
_ if crate::color_picker_ui::owns(fields) => {
@@ -886,6 +887,8 @@ const ROUTES: &[fn(&Fields) -> bool] = &[
crate::disk_change_prompt::owns,
crate::actions::owns_stop_message,
crate::actions::owns_insert_stop,
crate::actions::menu_item::owns,
crate::actions::record_again::owns,
crate::actions::owns_new_set,
crate::actions::playback::owns,
crate::new_layer_ui::owns,
@@ -963,7 +966,13 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value,
crate::actions::abandoned(app, &d.fields);
return Err("dialog has no command".into());
};
if crate::filter_dialog::needs_displace_map(&cmd, &crate::filter_dialog::params_of(&d.fields)) {
let params = crate::filter_dialog::params_of(&d.fields);
if let Err(error) = crate::actions::authorize_panel_preview(app, d.id, &d.fields, &cmd, &params) {
app.filter_preview = None;
crate::actions::abandoned(app, &d.fields);
return Err(error);
}
if crate::filter_dialog::needs_displace_map(&cmd, &params) {
app.filter_preview = None;
let result = crate::filter_dialog::ask_displace_map(app, cmd, d.fields.clone());
if result.is_err() {
@@ -980,7 +989,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value,
}
return result;
}
let (cmd, params) = match crate::smart_ui::confirm_command(app, &d.fields, cmd, crate::filter_dialog::params_of(&d.fields)) {
let (cmd, params) = match crate::smart_ui::confirm_command(app, &d.fields, cmd, params) {
Ok(edit) => edit,
Err(e) => {
app.filter_preview = None;
@@ -1066,6 +1075,12 @@ pub(crate) fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(),
/// Confirm a command dialog through the first handler whose marker its fields carry; the prompts
/// and small editors are here, the rest in `confirm_command_more`.
fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, String> {
if crate::actions::record_again::owns(&d.fields) || crate::actions::record_again::owns_dialog(app, d.id) {
return crate::actions::record_again::confirm(app, d.id, &d.fields);
}
if crate::actions::menu_item::owns(&d.fields) || crate::actions::menu_item::owns_dialog(app, d.id) {
return crate::actions::menu_item::confirm(app, d.id, &d.fields);
}
match d.kind {
_ if crate::open_prompt::owns_memory(&d.fields) => crate::open_prompt::answer_memory(app, true),
_ if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true),
@@ -1162,6 +1177,8 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
crate::color_picker_ui::live_preview::end(app, *picker);
}
app.ui.dialogs.retain(|d| !pickers.contains(&d.id));
crate::actions::record_again::cancel(app, id);
crate::actions::menu_item::cancel(app, id);
crate::actions::stopped(app, &closed.fields);
if crate::guide_layout_ui::owns(&closed.fields) {
app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id));
+4 -1
View File
@@ -191,7 +191,10 @@ fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> {
}
let kind = d.fields.get("__adjust")?.as_str()?.to_string();
let preview = d.fields.get("__preview").and_then(Value::as_bool).unwrap_or(true);
Some((kind, crate::filter_dialog::params_of(&d.fields), preview))
let params = crate::filter_dialog::params_of(&d.fields);
let command = format!("image.adjustments.{kind}");
crate::actions::authorize_panel_preview(app, d.id, &d.fields, &command, &params).ok()?;
Some((kind, params, preview))
}
/// Whether Image › Adjustments `kind` on document `idx` would edit a channel (the Channels panel's
@@ -30,6 +30,7 @@ use crate::widgets;
mod controls;
mod convert;
mod filmstrip;
mod menu;
mod open;
mod proxy;
@@ -38,6 +39,7 @@ mod sidecar;
pub use controls::show;
#[cfg(test)]
use convert::open_pixels;
pub use filmstrip::HeldRaw;
pub use menu::menu;
#[cfg(test)]
use open::{Coverage, commit_open_raw, document_index, finish_redevelop, open_raw, replace_raw_document};
@@ -1,4 +1,4 @@
use super::open::{Target, cancel, commit_open_raw, open_raw, raw_stage};
use super::open::{Target, cancel, raw_stage};
use super::sidecar::{load_settings, report_file_error, save_settings};
use super::{
Align2, BANDS, CameraRaw, CameraRawDialog, Color32, ERect, FontId, PANEL_W, PhotocraftApp, Pos2, Sense, Stroke, Tokens, ToneZone, Value, Wheel, curve_lut,
@@ -69,7 +69,7 @@ pub(super) fn commit(app: &mut PhotocraftApp) -> Result<Value, String> {
Target::OpenRaw => {
let raw = d.raw_open.clone().ok_or("no raw file is being opened")?;
let (params, original) = (d.params.clone(), d.original.clone());
commit_open_raw(app, &params, &raw, Some(&original))?
super::filmstrip::open_all(app, &params, &raw, &original)?
}
};
app.camera_raw = None;
@@ -188,10 +188,11 @@ fn curve_editor(ui: &mut egui::Ui, p: &mut CameraRaw, dirty: &mut bool, state: &
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
if app.camera_raw.is_none()
&& let Some(raw) = app.pending_raw_open.take()
&& let Err(e) = open_raw(app, ctx, raw)
&& !app.raw_shelf.is_empty()
&& let Err(e) = super::filmstrip::open_held(app, ctx, 0)
{
// The document stays open, developed with the defaults.
app.raw_shelf.remove(0);
app.ui.status = e;
app.ui.status_error = true;
}
@@ -241,6 +242,7 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) {
let screen = ctx.content_rect();
let current_display = app.session.active().and_then(|st| app.session.color.canvas_display(&st.doc).ok());
let mut action: Option<&str> = None;
let mut show_held: Option<usize> = None;
egui::Area::new(egui::Id::unique("camera-raw-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
let Some(d) = app.camera_raw.as_mut() else { return };
history_keys(d, ctx);
@@ -278,7 +280,16 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) {
let animated_zoom = app.session.prefs().general.animated_zoom;
let scope = &mut app.ui.camera_raw_scope;
// Clip both pixels and scope overlays before painting the settings dock/footer.
let preview_body = ERect::from_min_max(body.min, pos2((body.right() - PANEL_W).max(body.left() + 1.0), body.bottom()));
// Several raws being opened: the filmstrip on the left.
let film_w = if d.target == Target::OpenRaw && app.raw_shelf.len() > 1 { super::filmstrip::FILM_W } else { 0.0 };
if film_w > 0.0 {
let film = ERect::from_min_max(body.min, pos2(body.left() + film_w - 1.0, body.bottom()));
painter.rect_filled(film, 0.0, t.dock);
painter.line_segment([film.right_top(), film.right_bottom()], Stroke::new(1.0, t.separator));
show_held = super::filmstrip::filmstrip(ui, film, &mut app.raw_shelf, d.raw_open.as_ref().map(|r| r.document), &t);
}
let preview_body =
ERect::from_min_max(pos2(body.left() + film_w, body.top()), pos2((body.right() - PANEL_W).max(body.left() + film_w + 1.0), body.bottom()));
let view = ERect::from_min_max(
preview_body.min + vec2(16.0, 16.0),
pos2((preview_body.right() - 16.0).max(preview_body.left() + 17.0), (preview_body.bottom() - 48.0).max(preview_body.top() + 17.0)),
@@ -476,6 +487,15 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) {
) {
action = Some(if role == widgets::ButtonRole::Default { "ok" } else { "cancel" });
}
// Done (open-time dialog): keep the settings in the raws' sidecars, open nothing.
if d.target == Target::OpenRaw
&& fu
.add_sized([90.0, 28.0], egui::Button::new(tl!("Done")))
.on_hover_text(tl!("Save the settings to each raw's sidecar without opening it"))
.clicked()
{
action = Some("done");
}
fu.add_space(12.0);
widgets::checkbox(&mut fu, &mut d.show_before, tl!("Before (Y)"));
fu.label(egui::RichText::new(format!("{:.0} ms", d.render_ms)).color(t.text_faint));
@@ -496,6 +516,12 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) {
}
});
crate::camera_raw_scope_ui::persist(app, ctx);
if let Some(i) = show_held
&& let Err(e) = super::filmstrip::show_raw(app, ctx, i)
{
app.ui.status = e;
app.ui.status_error = true;
}
if ctx.input(|i| i.key_pressed(egui::Key::Y))
&& let Some(d) = app.camera_raw.as_mut()
{
@@ -511,6 +537,9 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) {
}
}
Some("cancel") => cancel(app),
Some("done") => {
super::filmstrip::done(app);
}
Some("save") => {
let r = save_settings(app);
report_file_error(app, r);
@@ -48,24 +48,10 @@ pub(super) fn apply_raw_conversions(app: &mut PhotocraftApp, index: usize, d: &p
Ok(())
}
pub(super) fn open_pixels(
app: &mut PhotocraftApp,
ctx: &egui::Context,
layer: LayerId,
surf: photocraft_raster::Surface,
params: CameraRaw,
coverage: Coverage,
target: Target,
) -> Result<(), String> {
let st = app.session.active().ok_or("no document")?;
let canvas = st.doc.bounds();
let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
let mut params = params;
if params.encoding_gamma == 0.0 {
params.encoding_gamma = photocraft_engine::lens_cmds::encoding_gamma(&st.doc);
}
// Use the engine filter domain, including pixels outside the canvas: spatial Camera Raw
// stages (vignette, grain, local contrast) must agree with the committed result.
/// What the preview develops, and its size: the engine filter domain, including pixels outside the
/// canvas, since spatial Camera Raw stages (vignette, grain, local contrast) must agree with the
/// committed result.
pub(super) fn preview_area(canvas: Rect, surf: &photocraft_raster::Surface) -> Result<(Rect, usize, usize), String> {
let area = canvas.union(&surf.content_bounds());
let width = area.x1.checked_sub(area.x0).filter(|n| (1..=1_048_576).contains(n));
let height = area.y1.checked_sub(area.y0).filter(|n| (1..=1_048_576).contains(n));
@@ -76,6 +62,12 @@ pub(super) fn open_pixels(
if w.checked_mul(h).is_none_or(|pixels| pixels > 512_000_000) {
return Err("Camera Raw preview bounds are too large".into());
}
Ok((area, w, h))
}
/// `area` of `surf` (`w`×`h`) box-averaged down to at most [`PROXY_SIDE`] pixels on its long side:
/// the proxy, its size, and the side of the blocks averaged.
pub(super) fn box_proxy(surf: &photocraft_raster::Surface, area: Rect, w: usize, h: usize) -> (Vec<[f32; 4]>, usize, usize, usize) {
let k = w.max(h).div_ceil(PROXY_SIDE).max(1);
let (pw, ph) = (w.div_ceil(k), h.div_ceil(k));
let mut proxy = vec![[0.0f32; 4]; pw * ph];
@@ -98,6 +90,27 @@ pub(super) fn open_pixels(
proxy[py * pw + x] = [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]];
}
}
(proxy, pw, ph, k)
}
pub(super) fn open_pixels(
app: &mut PhotocraftApp,
ctx: &egui::Context,
layer: LayerId,
surf: photocraft_raster::Surface,
params: CameraRaw,
coverage: Coverage,
target: Target,
) -> Result<(), String> {
let st = app.session.active().ok_or("no document")?;
let canvas = st.doc.bounds();
let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
let mut params = params;
if params.encoding_gamma == 0.0 {
params.encoding_gamma = photocraft_engine::lens_cmds::encoding_gamma(&st.doc);
}
let (area, w, h) = preview_area(canvas, &surf)?;
let (proxy, pw, ph, k) = box_proxy(&surf, area, w, h);
// Coverage at the centre of each proxy block.
let sample = |value: &dyn Fn(i32, i32) -> f32| {
(0..ph)
@@ -0,0 +1,290 @@
//! The open-time dialog's filmstrip: raws opened together wait side by side in one Camera Raw
//! dialog, as in Photoshop's. Each keeps its own settings and demosaic choice when another is
//! shown, Open develops every one and Cancel closes every one.
use super::open::{Target, commit_open_raw, open_raw_with, return_on_failure};
use super::sidecar::read_sidecar;
use super::{
Align2, CameraRaw, CameraRawDialog, Color32, ERect, FontId, PhotocraftApp, RawOpen, Rect, Sense, Stroke, Tokens, Value, json, pos2, vec2, widgets,
};
/// The filmstrip column, shown when more than one raw is being opened.
pub(super) const FILM_W: f32 = 150.0;
/// Long side of a filmstrip thumbnail, in pixels.
const THUMB_SIDE: usize = 240;
/// A raw waiting in the open-time dialog: opened (developed with the defaults) and reviewed
/// before Open keeps it.
pub struct HeldRaw {
pub raw: RawOpen,
/// Its settings and the settings it started from (its sidecar's, or the defaults) once it
/// has been shown and left for another (`None`: not edited yet).
pub(super) kept: Option<(CameraRaw, CameraRaw)>,
/// The filmstrip thumbnail until it is first drawn, then its texture.
pub(super) thumb: Option<egui::ColorImage>,
tex: Option<egui::TextureHandle>,
}
impl HeldRaw {
pub(super) fn new(app: &PhotocraftApp, raw: RawOpen) -> Self {
let thumb = super::open::document_index(app, raw.document).and_then(|i| thumbnail(app, i));
HeldRaw { raw, kept: None, thumb, tex: None }
}
}
/// A filmstrip thumbnail of document `index` (a just-developed raw: its first pixel layer).
fn thumbnail(app: &PhotocraftApp, index: usize) -> Option<egui::ColorImage> {
let doc = &app.session.documents().get(index)?.doc;
let surf = doc.layers.iter().find_map(|l| l.surface())?;
let area = doc.bounds();
let (w, h) = (area.width() as usize, area.height() as usize);
if w == 0 || h == 0 {
return None;
}
let k = w.max(h).div_ceil(THUMB_SIDE).max(1);
let (tw, th) = (w.div_ceil(k), h.div_ceil(k));
let mut acc = vec![[0.0f32; 5]; tw * th];
let mut row = vec![[0.0f32; 4]; w];
for y in (0..h).step_by(k.div_ceil(2).max(1)) {
surf.read_rgba_into(Rect::new(area.x0, area.y0 + y as i32, area.x1, area.y0 + y as i32 + 1), &mut row);
for (x, q) in row.iter().enumerate().step_by(k.div_ceil(2).max(1)) {
let a = &mut acc[(y / k) * tw + x / k];
for c in 0..4 {
a[c] += q[c];
}
a[4] += 1.0;
}
}
let px: Vec<[f32; 4]> = acc.iter().map(|a| if a[4] > 0.0 { [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]] } else { [0.0; 4] }).collect();
let display = app.session.color.canvas_display(doc).ok()?;
Some(CameraRawDialog::image(&px, tw, th, &display))
}
/// `px` (`w`×`h`) box-averaged down to at most [`THUMB_SIDE`] pixels on its long side.
fn shrink(px: &[[f32; 4]], w: usize, h: usize) -> (Vec<[f32; 4]>, usize, usize) {
let k = w.max(h).div_ceil(THUMB_SIDE).max(1);
let (tw, th) = (w.div_ceil(k), h.div_ceil(k));
let mut acc = vec![[0.0f32; 5]; tw * th];
for (i, q) in px.iter().enumerate().take(w * h) {
if let Some(a) = acc.get_mut((i / w / k) * tw + (i % w) / k) {
for c in 0..4 {
a[c] += q[c];
}
a[4] += 1.0;
}
}
(acc.iter().map(|a| if a[4] > 0.0 { [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]] } else { [0.0; 4] }).collect(), tw, th)
}
/// Shows raw `i` of the filmstrip, with the settings it was left with (its sidecar's, the
/// Camera Raw Defaults' Auto, or the defaults the first time).
pub(super) fn open_held(app: &mut PhotocraftApp, ctx: &egui::Context, i: usize) -> Result<(), String> {
let held = app.raw_shelf.get(i).ok_or("no raw file at that place in the filmstrip")?;
let (raw, kept) = (held.raw.clone(), held.kept.clone());
open_raw_with(app, ctx, raw, kept)
}
/// Shows raw `to` of the filmstrip; the one being left keeps its settings, and its thumbnail
/// shows them.
pub(super) fn show_raw(app: &mut PhotocraftApp, ctx: &egui::Context, to: usize) -> Result<(), String> {
let Some(d) = app.camera_raw.as_ref() else { return Ok(()) };
let current = d.raw_open.as_ref().map(|r| r.document);
if d.target != Target::OpenRaw || app.raw_shelf.get(to).is_none_or(|h| Some(h.raw.document) == current) {
return Ok(());
}
keep_settings(app);
// On success this replaces the dialog. On failure the dialog stays on the raw being left, and
// the other keeps its place in the filmstrip.
let active = app.session.active_index();
let shown = open_held(app, ctx, to);
if shown.is_err()
&& let Some(i) = active
{
app.session.set_active(i);
}
shown
}
/// Stores the dialog's settings (and demosaic choice) on its filmstrip raw, and refreshes the
/// raw's thumbnail from the preview.
pub(super) fn keep_settings(app: &mut PhotocraftApp) {
let Some(d) = app.camera_raw.as_ref() else { return };
let Some(raw) = &d.raw_open else { return };
let Some(held) = app.raw_shelf.iter_mut().find(|h| h.raw.document == raw.document) else { return };
held.kept = Some((d.params.clone(), d.original.clone()));
held.raw.demosaic = raw.demosaic;
// The preview may not have caught up with the last edit: the thumbnail shows what was kept.
let frame = (d.dirty || d.render_pending()).then(|| d.proxy_job().run().px);
let developed = frame.as_deref().unwrap_or(&d.processed);
if !developed.is_empty() {
let (px, w, h) = shrink(developed, d.pw, d.ph);
held.thumb = Some(CameraRawDialog::image(&px, w, h, &d.display));
held.tex = None;
}
}
/// The settings Open develops a never-shown filmstrip raw with, and what they started from:
/// its sidecar's, else the Camera Raw Defaults' Auto when that is on, else the defaults.
pub(super) fn first_settings(app: &PhotocraftApp, raw: &RawOpen) -> (CameraRaw, Option<CameraRaw>) {
if let Some((loaded, _, _)) = raw.path.as_deref().and_then(read_sidecar) {
return (loaded.clone(), Some(loaded));
}
let mut p = CameraRaw::default();
// From the proxy the dialog would use, so showing a raw doesn't change what Auto gives it.
if app.session.prefs().raw_defaults.apply_auto_tone
&& let Some(st) = super::open::document_index(app, raw.document).and_then(|i| app.session.documents().get(i))
&& let Some(surf) = st.doc.layers.iter().find_map(|l| l.surface())
&& let Ok((area, w, h)) = super::convert::preview_area(st.doc.bounds(), surf)
{
let (proxy, ..) = super::convert::box_proxy(surf, area, w, h);
photocraft_algo::camera_raw::auto_tone(&proxy, &mut p);
}
(p, None)
}
/// Open with raws in the filmstrip: the shown one as the dialog has it, then every other with
/// its own settings. One reply for one raw, `{"opened": [...]}` for several. A raw leaves the
/// filmstrip once it has opened or its background develop has started: one that fails stays or
/// comes back there with its settings, so the dialog returns for it (or Cancel still closes it).
pub(super) fn open_all(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, original: &CameraRaw) -> Result<Value, String> {
keep_settings(app);
let others: Vec<photocraft_doc::DocId> = app.raw_shelf.iter().map(|h| h.raw.document).filter(|id| *id != raw.document).collect();
let first = commit_open_raw(app, params, raw, Some(original));
if let Ok(v) = &first {
return_on_failure(app, v, original);
app.raw_shelf.retain(|h| h.raw.document != raw.document);
}
if others.is_empty() {
return first;
}
let mut opened = Vec::new();
let mut failed = Vec::new();
match first {
Ok(v) => opened.push(v),
Err(e) => failed.push(format!("{}: {e}", raw.name)),
}
for id in others {
let Some(held) = app.raw_shelf.iter().find(|h| h.raw.document == id) else { continue };
let (held_raw, kept) = (held.raw.clone(), held.kept.clone());
let (p, loaded) = match kept {
Some((p, original)) => (p, Some(original)),
None => first_settings(app, &held_raw),
};
match commit_open_raw(app, &p, &held_raw, loaded.as_ref()) {
Ok(v) => {
return_on_failure(app, &v, loaded.as_ref().unwrap_or(&CameraRaw::default()));
opened.push(v);
app.raw_shelf.retain(|h| h.raw.document != id);
}
Err(e) => failed.push(format!("{}: {e}", held_raw.name)),
}
}
if !failed.is_empty() {
let e = failed.join("; ");
if opened.is_empty() {
return Err(e);
}
crate::notices::error(app, e);
}
Ok(json!({"opened": opened}))
}
/// Done: saves each raw's settings to its sidecar, as Camera Raw's Done does, and opens none of
/// them (they close again).
pub(super) fn done(app: &mut PhotocraftApp) -> Value {
use super::sidecar::Stored;
keep_settings(app);
let Some(d) = app.camera_raw.as_ref() else { return Value::Null };
let Some(raw) = d.raw_open.clone() else { return Value::Null };
let mut raws = vec![(raw.clone(), d.params.clone())];
for held in app.raw_shelf.iter().filter(|h| h.raw.document != raw.document) {
let p = match &held.kept {
Some((p, _)) => p.clone(),
None => first_settings(app, &held.raw).0,
};
raws.push((held.raw.clone(), p));
}
let stored: Vec<Stored> = raws.iter().map(|(raw, p)| super::sidecar::store_sidecar(app, raw, p)).collect();
let saved: Vec<&String> = stored.iter().filter_map(|s| if let Stored::Written(name) = s { Some(name) } else { None }).collect();
// A failed write (already in a notice) keeps the dialog and every raw open, so no edit is lost.
if stored.contains(&Stored::Failed) {
app.ui.status = tl!("Some settings could not be saved; the raws stay open").to_string();
app.ui.status_error = true;
return json!({"done": false, "saved": saved});
}
app.ui.status = if !saved.is_empty() {
crate::i18n::fmt(tl!("Saved Camera Raw settings to {file}"), &[("file", &saved.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))])
} else if stored.iter().all(|s| *s == Stored::Defaults) {
tl!("Nothing to save: these raws are at their default settings").to_string()
} else {
tl!("No settings saved: these raws can't keep a sidecar here").to_string()
};
app.ui.status_error = saved.is_empty() && stored.contains(&Stored::Skipped);
let saved = json!(saved);
app.camera_raw = None;
app.raw_shelf.clear();
for (raw, _) in &raws {
if let Some(index) = super::open::document_index(app, raw.document) {
app.session.close(index);
}
}
app.sync_views();
json!({"done": true, "saved": saved})
}
/// The filmstrip of raws being opened: a thumbnail and name each, the shown one outlined, a dot
/// on edited ones. Returns the one clicked.
pub(super) fn filmstrip(ui: &mut egui::Ui, rect: ERect, shelf: &mut [HeldRaw], current: Option<photocraft_doc::DocId>, t: &Tokens) -> Option<usize> {
let mut clicked = None;
let mut film = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(6.0, 6.0))));
film.set_clip_rect(rect.intersect(ui.clip_rect()));
egui::ScrollArea::vertical().id_salt("camera-raw-filmstrip").auto_shrink([false, false]).show(&mut film, |ui| {
ui.spacing_mut().item_spacing.y = 6.0;
let w = ui.available_width();
for (i, held) in shelf.iter_mut().enumerate() {
if held.tex.is_none()
&& let Some(img) = held.thumb.take()
{
held.tex = Some(ui.ctx().load_texture(format!("camera-raw-thumb-{}", held.raw.document.0), img, egui::TextureOptions::LINEAR));
}
let (tile, response) = ui.allocate_exact_size(vec2(w, w * 0.75 + 18.0), Sense::click());
let frame = ERect::from_min_size(tile.min, vec2(w, w * 0.75));
let p = ui.painter();
p.rect_filled(frame, 2.0, if response.hovered() { t.hover } else { t.canvas });
if let Some(tex) = &held.tex {
let size = tex.size_vec2();
let fit = ((frame.width() - 8.0) / size.x.max(1.0)).min((frame.height() - 8.0) / size.y.max(1.0));
let r = ERect::from_center_size(frame.center(), size * fit);
widgets::checker(p, r, 6.0);
p.image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
if Some(held.raw.document) == current {
p.rect_stroke(frame, 2.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
}
if held.kept.as_ref().is_some_and(|(p, _)| !p.is_identity()) {
p.circle_filled(frame.right_top() + vec2(-7.0, 7.0), 3.0, t.text);
}
let name = ERect::from_min_max(pos2(tile.left(), frame.bottom()), tile.max);
let font = FontId::proportional(10.5);
let label = tail_fitting(p, &held.raw.name, font.clone(), name.width());
p.with_clip_rect(name).text(name.center(), Align2::CENTER_CENTER, label, font, t.text_dim);
let response = response.on_hover_text(&held.raw.name);
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, Some(held.raw.document) == current, &held.raw.name));
if response.clicked() {
clicked = Some(i);
}
}
});
clicked
}
/// `name`, or "…" and as much of its end as fits in `width`: raws from one shoot differ at the
/// end of their names (the frame number).
fn tail_fitting(p: &egui::Painter, name: &str, font: FontId, width: f32) -> String {
let fits = |s: &str| p.layout_no_wrap(s.to_owned(), font.clone(), Color32::WHITE).size().x <= width;
if fits(name) {
return name.to_owned();
}
let chars: Vec<char> = name.chars().collect();
(1..chars.len()).map(|start| format!("…{}", chars[start..].iter().collect::<String>())).find(|s| fits(s)).unwrap_or_default()
}
@@ -149,7 +149,7 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document()
app.session.set_active(0);
assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap();
let queued = app.pending_raw_open.as_ref().expect("the explicitly named RAW was queued");
let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the explicitly named RAW was queued");
assert_eq!(queued.document, raw.document);
assert_eq!((&queued.name, &queued.path, &queued.bytes), (&raw.name, &raw.path, &raw.bytes));
assert_eq!(app.session.active().unwrap().doc.id, control.doc.id, "queueing does not activate the target");
@@ -160,12 +160,12 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document()
fn queue_identity_rejects_a_missing_document_without_replacing_the_pending_review() {
let (mut app, raw, control) = identity_app();
queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap();
let pending = app.pending_raw_open.as_ref().unwrap().clone();
let pending = app.raw_shelf.first().map(|h| &h.raw).unwrap().clone();
app.session.set_active(0);
let missing = photocraft_doc::DocId::fresh();
assert!(!app.session.documents().iter().any(|state| state.doc.id == missing));
assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&[1, 2, 3]), &[]).is_err());
let queued = app.pending_raw_open.as_ref().expect("the existing review is preserved");
let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the existing review is preserved");
assert_eq!(queued.document, pending.document);
assert_eq!((&queued.name, &queued.path, &queued.bytes), (&pending.name, &pending.path, &pending.bytes));
assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
@@ -35,15 +35,16 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val
for (key, value) in fields {
match key.as_str() {
"set" | "scope" | "view" | "demosaic" => {}
"before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {}
"before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => {
"before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {}
"before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => {
return Some(Err(format!("Camera Raw {key} must be a boolean")));
}
_ => return Some(Err(format!("unknown Camera Raw ui property {key}"))),
}
}
if ui.get("commit").and_then(Value::as_bool) == Some(true) && ui.get("cancel").and_then(Value::as_bool) == Some(true) {
return Some(Err("Camera Raw cannot commit and cancel together".into()));
let ends = ["commit", "cancel", "done"].into_iter().filter(|k| ui.get(*k).and_then(Value::as_bool) == Some(true)).count();
if ends > 1 {
return Some(Err("Camera Raw takes one of commit, cancel and done".into()));
}
for (key, run) in [("saveSettings", save_settings as fn(&mut PhotocraftApp) -> Result<Value, String>), ("loadSettings", load_settings)] {
if ui.get(key).and_then(Value::as_bool) == Some(true) {
@@ -72,6 +73,9 @@ fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Opti
// Stage both filter and presentation updates. No texture, preference or dialog mutation
// occurs until every part of the request has passed validation.
let d = app.camera_raw.as_ref()?;
if ui.get("done").and_then(Value::as_bool) == Some(true) && d.target != super::open::Target::OpenRaw {
return Some(Err("Done is for raws being opened".into()));
}
let mut next_params = d.params.clone();
// Auto (the Light panel's button): the tone sliders from the image's histogram.
if ui.get("auto").and_then(Value::as_bool) == Some(true) {
@@ -165,5 +169,8 @@ fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Opti
if ui.get("commit").and_then(Value::as_bool) == Some(true) {
return Some(commit(app));
}
if ui.get("done").and_then(Value::as_bool) == Some(true) {
return Some(Ok(super::filmstrip::done(app)));
}
Some(Ok(app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null)))
}
@@ -45,7 +45,8 @@ pub fn without_develop_note(warnings: &[String]) -> Vec<String> {
}
/// Queues the open-time dialog for the document whose import completed, independent of the
/// active tab. A delayed completion for a closed document must not review another photograph.
/// active tab: the dialog shows on the next frame, or adds it to its filmstrip when it is already
/// open. A delayed completion for a closed document must not review another photograph.
/// `warnings` are the import's: its note says which demosaic method the open developed with.
pub fn queue_open_dialog(
app: &mut PhotocraftApp,
@@ -61,22 +62,42 @@ pub fn queue_open_dialog(
// The method the open actually used (`jobs::import_options` at the job's start), from its
// note: the preference may have changed while a background open ran.
let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method());
app.pending_raw_open = Some(RawOpen {
if app.raw_shelf.iter().any(|h| h.raw.document == document) {
return Ok(());
}
let raw = RawOpen {
document,
name: name.to_string(),
path: path.map(str::to_string),
bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())),
developed_with: method,
demosaic: method,
});
};
let held = super::filmstrip::HeldRaw::new(app, raw);
app.raw_shelf.push(held);
Ok(())
}
/// Opens the queued open-time dialog on its document's (only) layer.
/// Opens the open-time dialog on a queued raw's (only) layer.
#[cfg(test)]
pub(super) fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen) -> Result<(), String> {
open_raw_with(app, ctx, raw, None)
}
/// [`open_raw`], or with `kept` settings and the settings they started from (a filmstrip raw
/// shown again).
pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen, kept: Option<(CameraRaw, CameraRaw)>) -> Result<(), String> {
let index = document_index(app, raw.document).ok_or("the raw document was closed")?;
app.session.set_active(index);
let (layer, surf, _) = crate::distort_ui::active_pixels(app)?;
if let Some((params, original)) = kept {
open_pixels(app, ctx, layer, surf, params, Coverage::None, Target::OpenRaw)?;
if let Some(d) = app.camera_raw.as_mut() {
d.original = original;
}
attach_raw(app, raw);
return Ok(());
}
// The file's sidecar (`IMG_0001.xmp` beside it) fills the dialog, as Camera Raw's does; the
// status bar names what it could not apply.
let mut params = CameraRaw::default();
@@ -103,6 +124,12 @@ pub(super) fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpe
photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut d.params);
d.dirty = true;
}
attach_raw(app, raw);
Ok(())
}
/// Gives the open dialog its raw: the file name, and the camera tone curve it was developed with.
fn attach_raw(app: &mut PhotocraftApp, raw: RawOpen) {
let curve = match (&raw.bytes, &raw.path) {
(Some(b), _) => Some(photocraft_io::raw::tone_curve(b)),
#[cfg(not(target_arch = "wasm32"))]
@@ -117,7 +144,6 @@ pub(super) fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpe
d.raw_curve = curve;
d.raw_open = Some(raw);
}
Ok(())
}
pub(super) fn document_index(app: &PhotocraftApp, id: photocraft_doc::DocId) -> Option<usize> {
@@ -153,6 +179,9 @@ pub struct Redevelop {
filter_step: bool,
/// The Camera Raw Defaults the open started with, for the conversions after the filter step.
defaults: photocraft_engine::prefs::RawDefaults,
/// The dialog's Open started this, from these settings: if the re-develop fails, the raw goes
/// back to the filmstrip to be tried again or cancelled.
back_to_filmstrip: Option<CameraRaw>,
}
/// The sliders a raw open applies while developing, before the tone curve (as Camera Raw does).
@@ -225,7 +254,7 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw:
}
photocraft_engine::jobs::Started::Job(job) => {
let defaults = app.session.prefs().raw_defaults.clone();
app.raw_redevelop.push(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false, defaults });
app.raw_redevelop.push(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false, defaults, back_to_filmstrip: None });
app.ui.status = label;
app.ui.status_error = false;
Ok(json!({"job": job.0, "pending": true}))
@@ -233,6 +262,15 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw:
}
}
/// `reply` is [`commit_open_raw`]'s from the dialog's Open: if it started a background re-develop
/// and that fails, the raw comes back to the filmstrip, its settings having started from `original`.
pub(super) fn return_on_failure(app: &mut PhotocraftApp, reply: &Value, original: &CameraRaw) {
let job = reply.get("job").and_then(Value::as_u64);
if let Some(pending) = app.raw_redevelop.iter_mut().find(|r| Some(r.job.0) == job && !r.filter_step) {
pending.back_to_filmstrip = Some(original.clone());
}
}
/// Swap the default-developed document `doc_id` for the re-developed one, at the same tab
/// position and with the same path. Returns `{document, docId, previous, warnings, wb}`:
/// `document` is the tab index at apply time, `docId` is the replacement's stable identity.
@@ -324,7 +362,7 @@ fn finish_open_raw(
&& let Some(job) = r.get("job").and_then(Value::as_u64)
{
let job = photocraft_engine::jobs::JobId(job);
app.raw_redevelop.push(Redevelop { job, params: rest.clone(), raw: raw.clone(), filter_step: true, defaults: d.clone() });
app.raw_redevelop.push(Redevelop { job, params: rest.clone(), raw: raw.clone(), filter_step: true, defaults: d.clone(), back_to_filmstrip: None });
result["filter"] = r;
mark_unmodified(app, index);
return Ok(result);
@@ -373,7 +411,7 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str,
/// Every k-th pixel of a surface's content, k chosen so the longer side has about `max_side`
/// samples: enough for a histogram (Auto tone) without reading a whole raw.
fn sample_pixels(surf: &photocraft_raster::Surface, max_side: usize) -> Vec<[f32; 4]> {
pub(super) fn sample_pixels(surf: &photocraft_raster::Surface, max_side: usize) -> Vec<[f32; 4]> {
let area = surf.content_bounds();
let (w, h) = (area.x1.saturating_sub(area.x0).max(0) as usize, area.y1.saturating_sub(area.y0).max(0) as usize);
if w == 0 || h == 0 {
@@ -435,7 +473,15 @@ pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::
Err(err) => crate::notices::error(app, format!("{}: {err}", e.label)),
},
photocraft_engine::jobs::JobOutcome::Failed(err) => {
// The document stays open, developed with the defaults.
// The document stays open, developed with the defaults; from the dialog, it goes back
// to the filmstrip with its settings, which may have no sidecar to keep them.
if let Some(original) = pending.back_to_filmstrip
&& document_index(app, pending.raw.document).is_some()
{
let mut held = super::filmstrip::HeldRaw::new(app, pending.raw);
held.kept = Some((pending.params, original));
app.raw_shelf.push(held);
}
app.sync_views();
crate::notices::error(app, format!("{}: {err}", e.label));
}
@@ -447,13 +493,18 @@ pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::
true
}
/// Cancel: closes the dialog; for the open-time dialog also the document it was opening.
/// Cancel: closes the dialog; for the open-time dialog also the documents it was opening (every
/// raw in its filmstrip).
pub(super) fn cancel(app: &mut PhotocraftApp) {
let Some(d) = app.camera_raw.take() else { return };
if let (Target::OpenRaw, Some(raw)) = (d.target, &d.raw_open)
&& let Some(index) = document_index(app, raw.document)
{
app.session.close(index);
if let (Target::OpenRaw, Some(raw)) = (d.target, &d.raw_open) {
let mut opening: Vec<_> = std::mem::take(&mut app.raw_shelf).into_iter().map(|h| h.raw.document).collect();
opening.push(raw.document);
for id in opening {
if let Some(index) = document_index(app, id) {
app.session.close(index);
}
}
app.sync_views();
app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &raw.name)]);
app.ui.status_error = false;
@@ -52,27 +52,49 @@ pub(super) fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &Cam
if !app.session.prefs().raw_defaults.write_xmp_sidecars || loaded == Some(params) {
return;
}
store_sidecar(app, raw, params);
}
/// What [`store_sidecar`] did.
#[derive(Debug, PartialEq)]
pub(super) enum Stored {
/// Written: the sidecar's name.
Written(String),
/// Nothing to keep: default settings and no sidecar of ours to update.
Defaults,
/// This raw can't keep a sidecar here: an automation request, a DNG or a raw without a path,
/// another application's sidecar, or no file writer.
Skipped,
/// The write failed (already reported in a notice).
Failed,
}
/// Writes `params` to `raw`'s sidecar under [`write_sidecar`]'s rules, whatever the preference
/// (Done asks for it).
pub(super) fn store_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw) -> Stored {
if app.automation_input || app.session.authorize.is_some() {
log::info!("{}: sidecar not written for an automation request", raw.name);
return;
return Stored::Skipped;
}
let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return };
let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return Stored::Skipped };
let sidecar = sidecar_path(path);
let name = crate::file_open::display_name(&sidecar);
match existing_sidecar_is_ours(&sidecar) {
Some(false) => {
let kept = crate::i18n::fmt(tl!("Kept {name}: written by another application"), &[("name", &name)]);
crate::notices::post(app, kept, Vec::new(), false, None);
return;
return Stored::Skipped;
}
None if params.is_identity() => return,
None if params.is_identity() => return Stored::Defaults,
_ => {}
}
let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes();
let Some(write) = app.services.write.as_mut() else { return };
let Some(write) = app.services.write.as_mut() else { return Stored::Skipped };
if let Err(e) = write(&sidecar, &bytes) {
crate::notices::error(app, crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &name), ("error", &e)]));
return Stored::Failed;
}
Stored::Written(name)
}
/// `None` when there is no sidecar at `sidecar`, else whether PhotoCraft wrote it. One that
+268 -24
View File
@@ -1,5 +1,10 @@
use super::*;
/// The first raw waiting for the open-time dialog, taken off its filmstrip.
fn take_queued(app: &mut PhotocraftApp) -> Option<RawOpen> {
(!app.raw_shelf.is_empty()).then(|| app.raw_shelf.remove(0).raw)
}
/// #9550: a Color Mixer Hue track runs through the neighbouring bands' hues (Reds: magenta to
/// orange, wrapping round), not from grey; Saturation and Luminance keep grey to the colour.
#[test]
@@ -358,7 +363,7 @@ fn raw_opens_in_camera_raw_and_open_redevelops() {
// A raw has no embedded profile (ProPhoto RGB is the space it is developed into), so Ask
// When Opening (on by default) has nothing to ask about.
assert!(app.ui.dialogs.is_empty(), "no profile prompt for a raw");
let raw = app.pending_raw_open.take().expect("a raw open queues the dialog");
let raw = take_queued(&mut app).expect("a raw open queues the dialog");
open_raw(&mut app, &ctx, raw).unwrap();
let d = app.camera_raw.as_ref().unwrap();
assert_eq!(d.target, Target::OpenRaw);
@@ -388,7 +393,7 @@ fn the_demosaic_method_is_chosen_at_open() {
let ctx = egui::Context::default();
app.open_bytes("IMG_0002.dng", &dng).unwrap();
let ahd = pixels(&app);
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let d = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "bilinear"}})).unwrap().unwrap();
assert_eq!(d["openingRaw"]["demosaic"], "bilinear");
@@ -405,7 +410,7 @@ fn the_demosaic_method_is_chosen_at_open() {
app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "bilinear"})).unwrap();
app.open_bytes("IMG_0003.dng", &dng).unwrap();
assert_eq!(pixels(&app), bilinear, "developed with the preference's method");
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let d = app.camera_raw.as_ref().unwrap().describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview);
assert_eq!(d["openingRaw"]["demosaic"], "bilinear");
@@ -419,11 +424,11 @@ fn the_demosaic_method_is_chosen_at_open() {
// The preference may change while a background open runs: the dialog starts from the
// method the open developed with (its note), not from the newer preference.
let warnings = app.open_bytes("IMG_0004.dng", &dng).unwrap();
app.pending_raw_open.take();
take_queued(&mut app);
app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap();
let document = app.session.active().unwrap().doc.id;
queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
use photocraft_io::raw::Demosaic;
assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear));
}
@@ -433,7 +438,7 @@ fn shadows_of_a_raw_open_act_on_the_raw_data_and_the_preview_shows_it() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("IMG_0002.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
assert!(app.camera_raw.as_ref().unwrap().raw_curve.is_some(), "the preview knows how the raw was developed");
let mean = |px: &[[f32; 4]]| px.iter().map(|p| p[0] + p[1] + p[2]).sum::<f32>() / px.len() as f32;
@@ -454,7 +459,7 @@ fn clarity_texture_and_dehaze_of_a_raw_open_act_on_the_raw_data() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("IMG_0003.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let before = mean_red(&app);
let preview_before = app.camera_raw.as_ref().unwrap().processed.clone();
@@ -476,7 +481,7 @@ fn background_redevelop_keeps_the_tab_position_and_view() {
app.open_bytes("mid.dng", &dng).unwrap();
app.run("file.new", json!({"width": 12, "height": 12})).unwrap();
app.sync_views();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
let old_id = raw.document;
assert_eq!(document_index(&app, old_id), Some(1));
app.ui.views[1].zoom = 3.0;
@@ -516,7 +521,7 @@ fn a_raw_opens_and_redevelops_at_the_raw_defaults_resolution() {
app.run("prefs.set", json!({"path": "rawDefaults.resolution", "value": 240})).unwrap();
app.open_bytes("IMG_0004.dng", &dng).unwrap();
assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0);
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
@@ -526,19 +531,201 @@ fn a_raw_opens_and_redevelops_at_the_raw_defaults_resolution() {
assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0, "automation open");
}
/// Raws opened together share the dialog in a filmstrip, each with its own settings; Open
/// develops them all, Cancel closes them all.
#[test]
fn several_raws_share_the_dialog_and_keep_their_own_settings() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("one.dng", &dng).unwrap();
app.open_bytes("two.dng", &dng).unwrap();
app.open_bytes("three.dng", &dng).unwrap();
assert_eq!(app.raw_shelf.len(), 3);
assert!(app.raw_shelf.iter().all(|h| h.thumb.is_some()), "each has a thumbnail");
let ids: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap();
app.camera_raw.as_mut().unwrap().render(&ctx);
filmstrip::show_raw(&mut app, &ctx, 1).unwrap();
let d = app.camera_raw.as_ref().unwrap();
assert_eq!((d.raw_open.as_ref().unwrap().document, d.layer_name.as_str(), d.params.exposure), (ids[1], "two.dng", 0.0));
assert_eq!(app.raw_shelf[0].kept.as_ref().map(|(p, _)| p.exposure), Some(1.0), "the first keeps its settings");
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 30}}})).unwrap().unwrap();
filmstrip::show_raw(&mut app, &ctx, 0).unwrap();
assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 1.0, "back to the first, as it was left");
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["opened"].as_array().map(Vec::len), Some(3), "{r}");
assert!(app.raw_shelf.is_empty() && app.camera_raw.is_none());
assert_eq!(app.session.documents().len(), 3, "the never-shown third opens too");
assert!(app.session.documents().iter().all(|st| st.saved_revision == st.revision), "Open leaves them unmodified");
// Cancel closes every raw in the filmstrip.
app.open_bytes("four.dng", &dng).unwrap();
app.open_bytes("five.dng", &dng).unwrap();
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap();
assert!(app.raw_shelf.is_empty());
assert_eq!(app.session.documents().len(), 3);
}
/// A raw whose Open fails stays in the filmstrip with its settings, and the dialog comes back
/// for it; the raws that opened leave it.
#[test]
fn a_raw_that_fails_to_open_stays_in_the_filmstrip_with_its_settings() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("one.dng", &dng).unwrap();
app.open_bytes("two.dng", &dng).unwrap();
app.open_bytes("three.dng", &dng).unwrap();
let ids: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
// Two's file can no longer be developed, and it was left with its own settings.
let mut kept = CameraRaw { exposure: 0.5, ..Default::default() };
kept.contrast = 20.0;
app.raw_shelf[1].raw.bytes = Some(std::sync::Arc::new(b"not a raw file".to_vec()));
app.raw_shelf[1].kept = Some((kept.clone(), CameraRaw::default()));
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["opened"].as_array().map(Vec::len), Some(2), "one and three open: {r}");
let left: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
assert_eq!(left, vec![ids[1]], "only the failed raw stays in the filmstrip");
assert_eq!(app.raw_shelf[0].kept.as_ref().map(|(p, _)| p), Some(&kept), "with its settings");
// The dialog comes back for it with them; when every raw fails, the dialog and its
// filmstrip stay.
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
let shown = &app.camera_raw.as_ref().unwrap().params;
assert_eq!((shown.exposure, shown.contrast), (0.5, 20.0));
app.open_bytes("four.dng", &dng).unwrap();
app.raw_shelf[1].raw.bytes = Some(std::sync::Arc::new(b"not a raw file either".to_vec()));
app.raw_shelf[1].kept = Some((kept.clone(), CameraRaw::default()));
assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().is_err());
assert_eq!(app.raw_shelf.len(), 2, "both raws stay in the filmstrip");
assert!(app.camera_raw.is_some(), "and the dialog stays open");
// Cancel still closes every raw in it.
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap();
assert!(app.raw_shelf.is_empty());
assert_eq!(app.session.documents().len(), 2, "one and three stay open");
}
/// A raw that can't be shown leaves things as they were: the dialog stays on the raw being left,
/// and the other keeps its place in the filmstrip with its settings.
#[test]
fn a_raw_that_cannot_be_shown_keeps_the_dialog_and_the_filmstrip() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("one.dng", &dng).unwrap();
app.open_bytes("two.dng", &dng).unwrap();
let ids: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
let kept = CameraRaw { exposure: 0.5, ..Default::default() };
app.raw_shelf[1].kept = Some((kept.clone(), CameraRaw::default()));
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap();
let two = document_index(&app, ids[1]).unwrap();
app.session.close(two);
assert!(filmstrip::show_raw(&mut app, &ctx, 1).is_err());
let d = app.camera_raw.as_ref().expect("the dialog stays");
assert_eq!((d.raw_open.as_ref().unwrap().document, d.params.exposure), (ids[0], 1.0));
assert_eq!(app.raw_shelf.len(), 2);
assert_eq!(app.raw_shelf[1].kept.as_ref().map(|(p, _)| p), Some(&kept));
}
/// Leaving a raw before its preview has caught up: its thumbnail shows the settings it keeps, not
/// the frame before them.
#[test]
fn a_raw_left_before_its_preview_lands_gets_a_thumbnail_of_its_settings() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("one.dng", &dng).unwrap();
app.open_bytes("two.dng", &dng).unwrap();
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
let d = app.camera_raw.as_mut().unwrap();
d.params.exposure = 2.0;
d.dirty = true;
filmstrip::keep_settings(&mut app);
let thumb = app.raw_shelf[0].thumb.clone().expect("a thumbnail");
app.camera_raw.as_mut().unwrap().render(&ctx);
filmstrip::keep_settings(&mut app);
assert!(thumb == app.raw_shelf[0].thumb.clone().unwrap(), "the thumbnail matches a finished develop of the same settings");
}
/// Open returns once a background develop has started; if that develop then fails, the raw comes
/// back to the filmstrip with its settings, as one that failed at once stays there.
#[test]
fn a_raw_whose_background_develop_fails_comes_back_to_the_filmstrip() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("one.dng", &dng).unwrap();
app.open_bytes("two.dng", &dng).unwrap();
let ids: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
let (kept, from) = (CameraRaw { exposure: 0.5, contrast: 20.0, ..Default::default() }, CameraRaw { contrast: 5.0, ..Default::default() });
app.raw_shelf[1].raw.bytes = Some(std::sync::Arc::new(b"not a raw file".to_vec()));
app.raw_shelf[1].kept = Some((kept.clone(), from.clone()));
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap();
app.background_jobs = true;
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["opened"].as_array().map(Vec::len), Some(2), "both started: {r}");
assert!(app.raw_shelf.is_empty());
for _ in 0..3000 {
crate::jobs_ui::tick(&mut app, &ctx);
if app.raw_redevelop.is_empty() && !app.session.has_jobs() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished");
let left: Vec<_> = app.raw_shelf.iter().map(|h| h.raw.document).collect();
assert_eq!(left, vec![ids[1]], "only the failed raw comes back");
assert_eq!(app.raw_shelf[0].kept, Some((kept, from)), "with its settings");
app.background_jobs = false;
filmstrip::open_held(&mut app, &ctx, 0).unwrap();
assert_eq!(app.camera_raw.as_ref().unwrap().params.contrast, 20.0);
}
/// Camera Raw Defaults' Auto reads the same pixels whether a raw was shown or not, so Open gives
/// it the same settings either way: a fine pattern that a sparse sample misreads shows it.
#[test]
fn auto_tone_of_a_never_shown_raw_matches_the_dialogs() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
app.run("prefs.set", json!({"path": "rawDefaults.applyAutoTone", "value": true})).unwrap();
app.run("file.new", json!({"width": 1800, "height": 1200})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
let st = app.session.active_mut().unwrap();
let id = st.doc.layers.iter().find(|l| l.surface().is_some()).unwrap().id;
st.active_layer = Some(id);
let document = st.doc.id;
let Some(photocraft_doc::LayerContent::Raster(s)) = std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).map(|l| &mut l.content) else {
panic!("a pixel layer")
};
let format = s.format();
let (dark, light) = (photocraft_raster::from_rgba(&format, [0.1, 0.1, 0.1, 1.0]), photocraft_raster::from_rgba(&format, [0.9, 0.9, 0.9, 1.0]));
for y in 0..1200 {
for x in 0..1800 {
s.write_pixel(x, y, if (x + y) % 2 == 0 { &dark } else { &light });
}
}
let method = photocraft_io::raw::Demosaic::Ahd;
let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method };
let (unshown, _) = filmstrip::first_settings(&app, &raw);
open_raw(&mut app, &ctx, raw).unwrap();
let shown = &app.camera_raw.as_ref().unwrap().params;
let tone = |p: &CameraRaw| [p.exposure, p.contrast, p.highlights, p.shadows, p.whites, p.blacks];
assert_eq!(tone(&unshown), tone(shown));
}
#[test]
fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("a.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap();
assert_eq!(r["cancelled"], true);
assert!(app.session.documents().is_empty(), "Cancel closes the raw being opened");
// Unchanged settings: Open keeps the default develop and adds no step.
app.open_bytes("b.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!((r["document"].as_u64(), r["redeveloped"].as_bool(), r.get("filter")), (Some(0), Some(false), None), "{r}");
@@ -546,7 +733,7 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() {
// Preference off: raws open straight away.
app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap();
app.open_bytes("c.dng", &dng).unwrap();
assert!(app.pending_raw_open.is_none());
assert!(app.raw_shelf.is_empty());
// A non-raw never queues the dialog; a closed document is an error, not a panic.
assert!(
open_raw(
@@ -570,7 +757,7 @@ fn calibration_changes_the_preview_and_round_trips_through_xmp() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("IMG_0005.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let before = app.camera_raw.as_ref().unwrap().processed.clone();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadowTint": 100, "calibrationHue": [100, 0, 0], "calibrationSat": [0, 0, -100]}}}))
@@ -595,7 +782,7 @@ fn auto_sets_the_light_sliders_from_the_image() {
let (mut app, dng) = raw_app();
let ctx = egui::Context::default();
app.open_bytes("IMG_0006.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
assert!(app.camera_raw.as_ref().unwrap().params.is_identity());
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": true}})).unwrap().unwrap();
@@ -605,7 +792,7 @@ fn auto_sets_the_light_sliders_from_the_image() {
// The preference does the same when a raw opens without a sidecar.
app.run("prefs.set", json!({"path": "rawDefaults.applyAutoTone", "value": true})).unwrap();
app.open_bytes("IMG_0007.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
assert_eq!(app.camera_raw.as_ref().unwrap().params, p, "Apply auto tone opens the dialog with Auto's settings");
}
@@ -635,7 +822,7 @@ fn a_sidecar_fills_the_dialog_and_open_writes_it_back() {
}));
let ctx = egui::Context::default();
app.open_bytes("IMG_0008.cr2", &dng).unwrap();
let mut raw = app.pending_raw_open.take().unwrap();
let mut raw = take_queued(&mut app).unwrap();
raw.path = Some(raw_path.clone());
open_raw(&mut app, &ctx, raw).unwrap();
let d = app.camera_raw.as_ref().unwrap();
@@ -657,14 +844,14 @@ fn a_sidecar_fills_the_dialog_and_open_writes_it_back() {
let dng_path = dir.join("IMG_0009.dng").to_string_lossy().into_owned();
std::fs::write(&dng_path, &dng).unwrap();
app.open_bytes("IMG_0009.dng", &dng).unwrap();
let mut raw = app.pending_raw_open.take().unwrap();
let mut raw = take_queued(&mut app).unwrap();
raw.path = Some(dng_path);
open_raw(&mut app, &ctx, raw).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap();
assert!(written.lock().unwrap().is_empty(), "no sidecar for a DNG");
app.run("prefs.set", json!({"path": "rawDefaults.writeXmpSidecars", "value": false})).unwrap();
app.open_bytes("IMG_0008.cr2", &dng).unwrap();
let mut raw = app.pending_raw_open.take().unwrap();
let mut raw = take_queued(&mut app).unwrap();
raw.path = Some(raw_path.clone());
open_raw(&mut app, &ctx, raw).unwrap();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 30}, "commit": true}})).unwrap().unwrap();
@@ -673,7 +860,7 @@ fn a_sidecar_fills_the_dialog_and_open_writes_it_back() {
app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap();
let before = app.session.documents().len();
app.open_file(&raw_path, &dng).unwrap();
assert!(app.pending_raw_open.is_none());
assert!(app.raw_shelf.is_empty());
assert_eq!(app.session.documents().len(), before + 1);
let st = app.session.active().unwrap();
assert_eq!(st.saved_revision, st.revision, "opening with a sidecar leaves the document unmodified");
@@ -686,7 +873,7 @@ fn camera_raw_defaults_apply_when_a_raw_opens() {
let (mut app, dng) = raw_app();
app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": false, "rawDefaults.colorSpace": "srgb", "rawDefaults.bitDepth": "8", "rawDefaults.resolution": 240.0, "rawDefaults.sharpenFor": "screen", "rawDefaults.openAsSmartObject": true}})).unwrap();
app.open_bytes("IMG_0010.dng", &dng).unwrap();
assert!(app.pending_raw_open.is_none());
assert!(app.raw_shelf.is_empty());
let st = app.session.active().unwrap();
assert_eq!(st.doc.depth, photocraft_color::SampleType::U8, "Bit depth 8");
assert_eq!(st.doc.resolution_dpi, 240.0, "Resolution");
@@ -700,7 +887,7 @@ fn camera_raw_defaults_apply_when_a_raw_opens() {
.unwrap();
let ctx = egui::Context::default();
app.open_bytes("IMG_0011.dng", &dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(&mut app).unwrap();
open_raw(&mut app, &ctx, raw).unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["defaults"], json!(["sharpenFor", "colorSpace"]), "{r}");
@@ -756,7 +943,7 @@ fn raw_with_sidecar(tag: &str, sidecar: Option<&str>) -> (PhotocraftApp, Vec<u8>
/// Opens the raw at `raw_path` in the open-time dialog, as File › Open does.
fn open_dialog_at(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], raw_path: &str) {
app.open_bytes("IMG_0100.cr2", dng).unwrap();
let mut raw = app.pending_raw_open.take().unwrap();
let mut raw = take_queued(app).unwrap();
raw.path = Some(raw_path.to_string());
open_raw(app, ctx, raw).unwrap();
}
@@ -808,7 +995,7 @@ fn opening_without_the_dialog_does_not_rewrite_the_sidecar() {
let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("nodialog", Some(LIGHTROOM_SIDECAR));
app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap();
app.open_file(&raw_path, &dng).unwrap();
assert!(app.pending_raw_open.is_none());
assert!(app.raw_shelf.is_empty());
assert_eq!(app.session.documents().len(), 1);
assert!(written.lock().unwrap().is_empty(), "just opening never writes the sidecar");
assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR);
@@ -855,7 +1042,7 @@ fn a_sidecar_write_error_stays_reported() {
fn open_with_settings(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], name: &str) {
app.open_bytes(name, dng).unwrap();
let raw = app.pending_raw_open.take().unwrap();
let raw = take_queued(app).unwrap();
open_raw(app, ctx, raw).unwrap();
menu(app, ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 60, "saturation": 40, "vibrance": 30}}})).unwrap().unwrap();
}
@@ -1022,3 +1209,60 @@ fn save_and_load_settings_round_trip_through_xmp_files() {
frame(&mut app);
assert_eq!(app.camera_raw.as_ref().unwrap().params.clarity, 25.0);
}
/// Done keeps the settings in the raw's sidecar and opens nothing,
/// even with the preference that writes sidecars on Open turned off.
#[test]
fn done_saves_the_sidecar_and_opens_nothing() {
let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("done", None);
let ctx = egui::Context::default();
app.run("prefs.set", json!({"path": "rawDefaults.writeXmpSidecars", "value": false})).unwrap();
let before = app.session.documents().len();
open_dialog_at(&mut app, &ctx, &dng, &raw_path);
let set = json!({"contrast": 20, "clarity": 15});
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": set}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"done": true}})).unwrap().unwrap();
assert_eq!(r["saved"], json!(["IMG_0100.xmp"]), "{r}");
assert!(app.camera_raw.is_none() && app.raw_shelf.is_empty());
assert_eq!(app.session.documents().len(), before, "Done opens nothing");
let w = written.lock().unwrap().clone();
assert_eq!(w.len(), 1);
let mut back = CameraRaw::default();
photocraft_io::camera_raw_xmp::load(&mut back, &w[0].1).unwrap();
assert_eq!((back.contrast, back.clarity), (20.0, 15.0));
// Done is only for raws being opened, and checked before anything else in the request
// changes the dialog.
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"done": true}})).unwrap().is_err());
menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap();
let before = app.camera_raw.as_ref().unwrap().params.clone();
assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 40}, "done": true}})).unwrap().is_err());
assert_eq!(app.camera_raw.as_ref().unwrap().params, before, "a refused Done changes nothing");
for other in ["commit", "cancel"] {
assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"done": true, other: true}})).unwrap().is_err(), "{other}");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A sidecar that can't be written keeps the dialog and the raw open with their settings;
/// default settings are nothing to save, not an error.
#[test]
fn done_keeps_the_raws_open_when_a_sidecar_write_fails() {
let (mut app, dng, dir, raw_path, _) = raw_with_sidecar("done-fails", None);
let ctx = egui::Context::default();
app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("read-only volume".to_string())));
open_dialog_at(&mut app, &ctx, &dng, &raw_path);
let docs = app.session.documents().len();
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 20}}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"done": true}})).unwrap().unwrap();
assert_eq!(r["done"], false, "{r}");
assert_eq!(app.camera_raw.as_ref().map(|d| d.params.contrast), Some(20.0), "the edit is still there");
assert_eq!(app.session.documents().len(), docs, "the raw stays open");
assert!(app.ui.status_error);
// At the defaults there is nothing to write: Done closes, without an error.
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 0}}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"done": true}})).unwrap().unwrap();
assert_eq!((r["done"].clone(), r["saved"].clone()), (json!(true), json!([])), "{r}");
assert!(app.camera_raw.is_none() && !app.ui.status_error, "{}", app.ui.status);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -322,6 +322,8 @@ pub const PREVIEWED: &[&str] = &[
// The preview shows the image through the chosen profile, as Photoshop's Preview does.
"edit.assignProfile",
"edit.convertToProfile",
// Previewed from the session's history (`canvas::filter_preview`), at full size (#8230).
"edit.fade",
];
pub fn has_dialog(command: &str) -> bool {
+62 -4
View File
@@ -82,6 +82,34 @@ fn with_unit(value: &str, unit: Unit) -> String {
format!("{value} {}", unit.suffix())
}
/// `typed` with `unit` after its first number when that number has none ("300 / 2" with pixel
/// rulers → "300 px / 2"); anything else as typed. Nor when a length later in its term makes it
/// a plain factor ("2 / 2 * 50 px": the term is in px already).
fn unit_on_first_number(typed: &str, unit: Unit) -> String {
let end = typed
.char_indices()
.find(|&(i, c)| !(c.is_ascii_digit() || matches!(c, '.' | ',') || (i == 0 && matches!(c, '-' | '+'))))
.map_or(typed.len(), |(i, _)| i);
let (number, rest) = typed.split_at(end);
let bare = !number.is_empty() && rest.trim_start().starts_with(['+', '-', '*', '/']) && !factor_has_unit(rest);
if bare { format!("{} {}{rest}", number, unit.suffix()) } else { typed.to_string() }
}
/// Whether an operand multiplied or divided in at the start of `rest` (up to the first `+` or `-`
/// between operands) carries a unit, as the engine splits operands.
fn factor_has_unit(mut rest: &str) -> bool {
while let Some(operand) = rest.trim_start().strip_prefix(['*', '/']).map(str::trim_start) {
// The operand runs to the next operator; a sign at its start is its own.
let end = operand.char_indices().find(|&(i, c)| i > 0 && matches!(c, '+' | '-' | '*' | '/')).map_or(operand.len(), |(i, _)| i);
let (operand, after) = operand.split_at(end);
if Unit::parse_length(operand).is_some_and(|(_, u)| u.is_some()) {
return true;
}
rest = after;
}
false
}
/// `px` (document pixels) in the ruler unit, as the field shows it: "14.11 cm". Percent is of the
/// active document's width for a vertical guide and its height for a horizontal one.
fn in_ruler_unit(app: &PhotocraftApp, px: f64, vertical: bool) -> String {
@@ -212,10 +240,14 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
/// the engine to read (or refuse, keeping the dialog open). Custom… sends its "#rrggbb".
pub fn params(app: &PhotocraftApp, f: &Map<String, Value>) -> Value {
let orientation = f.get("orientation").and_then(Value::as_str).unwrap_or("horizontal");
let typed = f.get("position").and_then(Value::as_str).unwrap_or_default().trim();
let position = match Unit::parse_length(typed) {
Some((_, None)) => with_unit(typed, ruler_unit(app)),
_ => typed.to_string(),
// A Unicode minus (U+2212) is a minus, as the engine reads it.
let typed = f.get("position").and_then(Value::as_str).unwrap_or_default().trim().replace('−', "-");
let position = match Unit::parse_length(&typed) {
Some((_, None)) => with_unit(&typed, ruler_unit(app)),
Some(_) => typed,
// Arithmetic (#10440): a first number without a unit is in the ruler unit, as in
// Photoshop ("300 / 2" is 150 px with pixel rulers); the engine evaluates the rest.
None => unit_on_first_number(&typed, ruler_unit(app)),
};
let color = f.get("color").and_then(Value::as_str).filter(|c| is_color_name(c)).unwrap_or(DEFAULT_COLOR);
let color = if color == CUSTOM { custom_color(f) } else { color.to_string() };
@@ -301,3 +333,29 @@ pub fn edit_preview<'a>(app: &'a PhotocraftApp, doc: &photocraft_doc::Document)
#[cfg(test)]
mod tests;
#[cfg(test)]
mod arithmetic_tests {
use super::{Unit, unit_on_first_number};
/// #10440: a first number without a unit is in the ruler unit, the rest goes to the engine.
#[test]
fn a_leading_bare_number_gets_the_ruler_unit() {
assert_eq!(unit_on_first_number("300 / 2", Unit::Pixels), "300 px / 2");
assert_eq!(unit_on_first_number("3+1in", Unit::Centimeters), "3 cm+1in");
assert_eq!(unit_on_first_number("100% / 3", Unit::Pixels), "100% / 3");
assert_eq!(unit_on_first_number("abc", Unit::Pixels), "abc");
}
/// A bare number multiplied or divided within a term that has a length is a plain factor:
/// the length is the term's unit, so the ruler unit isn't added (it would make a length
/// times a length). A term of bare numbers still gets it.
#[test]
fn a_leading_factor_of_a_length_gets_no_ruler_unit() {
for typed in ["2 * 50 px", "2 / 2 * 50 px", "2*50px+10", "4 / 2 * 1in - 3", "2 * -1cm"] {
assert_eq!(unit_on_first_number(typed, Unit::Centimeters), typed);
}
assert_eq!(unit_on_first_number("2 * 3 + 1in", Unit::Centimeters), "2 cm * 3 + 1in");
assert_eq!(unit_on_first_number("6 / 2 / 3 - 1", Unit::Centimeters), "6 cm / 2 / 3 - 1");
}
}
@@ -435,3 +435,29 @@ fn refused_edit_shows_the_error_and_typed_fields_in_the_dialog() {
assert!(h.query_by_label("guide edits are denied").is_none());
assert_eq!(guides(h.state()).1, vec![10.0, 20.0]);
}
/// #10440: a leading bare number gets the ruler unit after a Unicode minus (U+2212) as after "-",
/// so "5.08 − 2.54" with centimetre rulers is 2.54 cm, not 2.54 px.
#[test]
fn the_ruler_unit_goes_on_a_bare_number_before_a_unicode_minus() {
let (mut app, ctx) = app("cm");
let d = open(&mut app, &ctx);
set(&mut app, d, "vertical", "5.08 − 2.54");
crate::dialogs::confirm(&mut app, d).unwrap();
let (_, vertical) = guides(&app);
assert!(vertical.len() == 1 && (vertical[0] - 100.0).abs() < 1e-6, "{vertical:?}");
}
/// #10440: a leading bare number that multiplies or divides a length is a plain factor, so it
/// doesn't take the ruler unit (CodeRabbit: "2 / 2 * 50 px" became "2 cm / 2 * 50 px").
#[test]
fn a_leading_factor_of_a_length_is_a_plain_number() {
let (mut app, ctx) = app("cm");
for (typed, px) in [("2 * 50 px", 100.0), ("2 / 2 * 1in", 100.0), ("2 * 2.54 - 2.54", 100.0)] {
let d = open(&mut app, &ctx);
set(&mut app, d, "vertical", typed);
crate::dialogs::confirm(&mut app, d).unwrap_or_else(|e| panic!("{typed}: {e}"));
let landed = *guides(&app).1.last().unwrap();
assert!((landed - px).abs() < 1e-6, "{typed}: {landed}");
}
}
+3 -1
View File
@@ -216,7 +216,7 @@ fn expand(packed: &str, keys: &[&str]) -> Result<String, String> {
}
/// The registry. English first: it is the fallback and the source language.
pub static LANGUAGES: [LangInfo; 34] = [
pub static LANGUAGES: [LangInfo; 35] = [
LangInfo { code: "en", name: "English", source: b"", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
LangInfo { code: "ja", name: "日本語", source: catalog!("ja"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
LangInfo { code: "zh-hans", name: "简体中文", source: catalog!("zh-hans"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
@@ -284,6 +284,8 @@ pub static LANGUAGES: [LangInfo; 34] = [
LangInfo { code: "ro", name: "Română", source: catalog!("ro"), plural: plural_romanian, complete_menus: true, catalog: OnceLock::new() },
// Tamil; `ta-IN`, `ta-LK` and `ta_IN.UTF-8` resolve here. CLDR plural: one|other.
LangInfo { code: "ta", name: "தமிழ்", source: catalog!("ta"), plural: plural_one_other, complete_menus: true, catalog: OnceLock::new() },
// Georgian: nouns stay singular after a numeral (`შრე: 5`, `5 შრე`), so one form serves every count.
LangInfo { code: "ka", name: "ქართული", source: catalog!("ka"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
];
impl LangInfo {
+5
View File
@@ -4356,6 +4356,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Zobrazit hranice vrstvy při najetí
Expand layer group on click Rozbalit skupinu vrstev kliknutím
Show hover bounds from Layers Zobrazit hranice při najetí z panelu Vrstvy
Saved Camera Raw settings to {file} Nastavení Camera Raw uložena do {file}
Save the settings to each raw's sidecar without opening it Uložit nastavení do souboru sidecar každého snímku raw bez jeho otevření
No settings saved: these raws can't keep a sidecar here Nic neuloženo: tyto snímky raw zde nemohou mít soubor sidecar
Some settings could not be saved; the raws stay open Některá nastavení nelze uložit; snímky raw zůstávají otevřené
Nothing to save: these raws are at their default settings Není co ukládat: tyto snímky raw mají výchozí nastavení
# Artboard tool options bar (#11385)
Distribute Widths Rozmístit šířky
Distribute Heights Rozmístit výšky
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -3651,6 +3651,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Ebenenbegrenzung beim Darüberfahren anzeigen
Expand layer group on click Ebenengruppe per Klick erweitern
Show hover bounds from Layers Begrenzung beim Darüberfahren aus Ebenen anzeigen
Saved Camera Raw settings to {file} Camera-Raw-Einstellungen in {file} gespeichert
Save the settings to each raw's sidecar without opening it Die Einstellungen in der Filialdatei jeder Raw-Datei speichern, ohne sie zu öffnen
No settings saved: these raws can't keep a sidecar here Nichts gespeichert: Diese Raw-Dateien können hier keine Filialdatei haben
Some settings could not be saved; the raws stay open Einige Einstellungen konnten nicht gespeichert werden; die Raw-Dateien bleiben geöffnet
Nothing to save: these raws are at their default settings Nichts zu speichern: Diese Raw-Dateien haben ihre Standardeinstellungen
# Artboard tool options bar (#11385)
Distribute Widths Breiten verteilen
Distribute Heights Höhen verteilen
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -4315,6 +4315,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Εμφάνιση ορίων στρώσης στο πέρασμα του δείκτη
Expand layer group on click Ανάπτυξη ομάδας στρώσεων με κλικ
Show hover bounds from Layers Εμφάνιση ορίων στο πέρασμα από τις Στρώσεις
Saved Camera Raw settings to {file} Οι ρυθμίσεις Camera Raw αποθηκεύτηκαν στο {file}
Save the settings to each raw's sidecar without opening it Αποθήκευση των ρυθμίσεων στο συνοδευτικό αρχείο κάθε raw χωρίς άνοιγμα
No settings saved: these raws can't keep a sidecar here Δεν αποθηκεύτηκε τίποτα: αυτά τα raw δεν μπορούν να έχουν συνοδευτικό αρχείο εδώ
Some settings could not be saved; the raws stay open Ορισμένες ρυθμίσεις δεν ήταν δυνατό να αποθηκευτούν· τα raw παραμένουν ανοιχτά
Nothing to save: these raws are at their default settings Τίποτα για αποθήκευση: αυτά τα raw έχουν τις προεπιλεγμένες ρυθμίσεις
# Artboard tool options bar (#11385)
Distribute Widths Κατανομή πλατών
Distribute Heights Κατανομή υψών
Can't render this file because it contains an unexpected character in line 47 and column 53.
+5
View File
@@ -4515,6 +4515,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Mostrar límites de capa al pasar el puntero
Expand layer group on click Expandir grupo de capas al hacer clic
Show hover bounds from Layers Mostrar límites al pasar el puntero desde Capas
Saved Camera Raw settings to {file} Ajustes de Camera Raw guardados en {file}
Save the settings to each raw's sidecar without opening it Guardar los ajustes en el archivo sidecar de cada raw sin abrirlo
No settings saved: these raws can't keep a sidecar here No se guardó nada: estos raw no pueden tener un archivo sidecar aquí
Some settings could not be saved; the raws stay open No se pudieron guardar algunos ajustes; los raw siguen abiertos
Nothing to save: these raws are at their default settings Nada que guardar: estos raw tienen los ajustes predeterminados
# Artboard tool options bar (#11385)
Distribute Widths Distribuir anchos
Distribute Heights Distribuir alturas
Can't render this file because it contains an unexpected character in line 4 and column 47.
+5
View File
@@ -4638,6 +4638,11 @@ shape Appearance Apparence
Show layer bounds on hover Afficher les limites du calque au survol
Expand layer group on click Développer le groupe de calques au clic
Show hover bounds from Layers Afficher les limites au survol depuis Calques
Saved Camera Raw settings to {file} Réglages Camera Raw enregistrés dans {file}
Save the settings to each raw's sidecar without opening it Enregistrer les réglages dans le fichier annexe de chaque raw sans l’ouvrir
No settings saved: these raws can't keep a sidecar here Rien n’a été enregistré : ces raw ne peuvent pas avoir de fichier annexe ici
Some settings could not be saved; the raws stay open Certains réglages n’ont pas pu être enregistrés ; les raw restent ouverts
Nothing to save: these raws are at their default settings Rien à enregistrer : ces raw ont leurs réglages par défaut
# Artboard tool options bar (#11385)
Distribute Widths Répartir les largeurs
Distribute Heights Répartir les hauteurs
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -4522,6 +4522,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Réteghatárok megjelenítése rámutatáskor
Expand layer group on click Rétegcsoport kibontása kattintásra
Show hover bounds from Layers Határok megjelenítése a Rétegek panelről rámutatáskor
Saved Camera Raw settings to {file} Camera Raw-beállítások mentve ide: {file}
Save the settings to each raw's sidecar without opening it A beállítások mentése minden raw kísérőfájljába megnyitás nélkül
No settings saved: these raws can't keep a sidecar here Nincs mentve semmi: ezek a raw fájlok itt nem kaphatnak kísérőfájlt
Some settings could not be saved; the raws stay open Néhány beállítást nem sikerült menteni; a raw fájlok nyitva maradnak
Nothing to save: these raws are at their default settings Nincs mit menteni: ezek a raw fájlok alapértelmezett beállításokon vannak
# Artboard tool options bar (#11385)
Distribute Widths Szélességek elosztása
Distribute Heights Magasságok elosztása
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -3638,6 +3638,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Tampilkan batas layer saat kursor di atasnya
Expand layer group on click Perluas grup layer saat diklik
Show hover bounds from Layers Tampilkan batas saat kursor di atas dari Layer
Saved Camera Raw settings to {file} Pengaturan Camera Raw disimpan ke {file}
Save the settings to each raw's sidecar without opening it Simpan pengaturan ke file sidecar setiap raw tanpa membukanya
No settings saved: these raws can't keep a sidecar here Tidak ada yang disimpan: raw ini tidak dapat memiliki file sidecar di sini
Some settings could not be saved; the raws stay open Beberapa pengaturan tidak dapat disimpan; raw tetap terbuka
Nothing to save: these raws are at their default settings Tidak ada yang perlu disimpan: raw ini memakai pengaturan default
# Artboard tool options bar (#11385)
Distribute Widths Distribusi lebar
Distribute Heights Distribusi tinggi
Can't render this file because it contains an unexpected character in line 4 and column 47.
+5
View File
@@ -4714,6 +4714,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover Mostra i limiti del livello al passaggio del mouse
Expand layer group on click Espandi il gruppo di livelli al clic
Show hover bounds from Layers Mostra i limiti al passaggio dal pannello Livelli
Saved Camera Raw settings to {file} Impostazioni Camera Raw salvate in {file}
Save the settings to each raw's sidecar without opening it Salva le impostazioni nel file sidecar di ogni raw senza aprirlo
No settings saved: these raws can't keep a sidecar here Nulla salvato: questi raw non possono avere un file sidecar qui
Some settings could not be saved; the raws stay open Alcune impostazioni non sono state salvate; i raw restano aperti
Nothing to save: these raws are at their default settings Niente da salvare: questi raw hanno le impostazioni predefinite
# Artboard tool options bar (#11385)
Distribute Widths Distribuisci larghezze
Distribute Heights Distribuisci altezze
Can't render this file because it contains an unexpected character in line 79 and column 53.
+5
View File
@@ -4286,6 +4286,11 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded
Show layer bounds on hover ホバー時にレイヤーの境界を表示
Expand layer group on click クリックでレイヤーグループを展開
Show hover bounds from Layers レイヤーパネルからのホバー境界を表示
Saved Camera Raw settings to {file} Camera Raw の設定を {file} に保存しました
Save the settings to each raw's sidecar without opening it 各 Raw のサイドカーファイルに設定を保存し、開かずに閉じます
No settings saved: these raws can't keep a sidecar here 保存されませんでした:これらの Raw にはここでサイドカーファイルを作成できません
Some settings could not be saved; the raws stay open 一部の設定を保存できませんでした。Raw は開いたままです
Nothing to save: these raws are at their default settings 保存するものはありません:これらの Raw は初期設定のままです
# Artboard tool options bar (#11385)
Distribute Widths 幅を分布
Distribute Heights 高さを分布
Can't render this file because it contains an unexpected character in line 6 and column 47.
File diff suppressed because it is too large. Load diff
+5
View File
@@ -4188,6 +4188,11 @@ shape Appearance 화면 모양
Show layer bounds on hover 마우스를 올리면 레이어 경계 표시
Expand layer group on click 클릭하면 레이어 그룹 펼치기
Show hover bounds from Layers 레이어 패널에서 마우스를 올릴 때 경계 표시
Saved Camera Raw settings to {file} Camera Raw 설정을 {file}에 저장했습니다
Save the settings to each raw's sidecar without opening it 각 Raw의 사이드카 파일에 설정을 저장하고 열지 않습니다
No settings saved: these raws can't keep a sidecar here 저장된 항목 없음: 이 Raw 파일은 여기에 사이드카 파일을 둘 수 없습니다
Some settings could not be saved; the raws stay open 일부 설정을 저장할 수 없습니다. Raw 파일은 열린 상태로 유지됩니다
Nothing to save: these raws are at their default settings 저장할 항목 없음: 이 Raw 파일은 기본 설정입니다
# Artboard tool options bar (#11385)
Distribute Widths 너비 분포
Distribute Heights 높이 분포
Can't render this file because it contains an unexpected character in line 63 and column 53.
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more