Merge main into #1727 (control-protocol: ui.pointer tool? plus brushPicker)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UHgFEHEsefoQoBParH47JA
This commit is contained in:
Claude committed 2026-10-09 13:29:25 +00:00
commit 9f09987ce1
39 files changed
+1461 -164

No files matched your search

+6 -3
View File
@@ -30,9 +30,10 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Which OSes the test job runs on. main, manual runs and PRs labelled `full-ci` get all three.
# Other PRs get Linux, plus macOS and Windows when they touch code whose behaviour differs by
# Which OSes the test job runs on. main, manual runs and PRs labelled `full-ci` get Linux and
# Windows. Other PRs get Linux, plus Windows when they touch code whose behaviour differs by
# platform: the app shell, UI, text and fonts, GPU, pen input, build scripts or the lockfile.
# macOS is tested only by release.yml.
platforms:
name: select platforms
runs-on: ubuntu-latest
@@ -48,7 +49,9 @@ jobs:
BASE: ${{ github.event.pull_request.base.sha }}
FULL: ${{ contains(github.event.pull_request.labels.*.name, 'full-ci') }}
run: |
all='["ubuntu-latest","macos-latest","windows-latest"]'
# No macOS on PRs or main: the org's 5 macOS slots are kept for release builds, and
# release.yml builds and tests macOS (a failing release is fixed and rebuilt).
all='["ubuntu-latest","windows-latest"]'
if [ "$EVENT" != pull_request ] || [ "$FULL" = true ]; then
echo "os=$all" >> "$GITHUB_OUTPUT"
exit 0
+49 -1
View File
@@ -21,6 +21,16 @@ const OPEN_EXTS: &[&str] = &[
"afdesign", "afphoto", "afpub",
];
/// Open dialog extensions that also match uppercase and mixed-case names (`IMG_0001.JPG`).
/// On Linux and the BSDs rfd turns each extension into a case-sensitive `*.ext` glob for the XDG
/// portal or zenity, so every letter becomes a character class, as the portal spec suggests
/// (`*.[iI][cC][oO]`). Windows and macOS take literal extensions and ignore case already.
fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
let case_sensitive_globs = cfg!(all(unix, not(target_os = "macos")));
let class = |c: char| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() };
extensions.iter().map(|ext| if case_sensitive_globs { ext.chars().map(class).collect() } else { ext.to_string() }).collect()
}
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
/// extension comes first, so a .pcraft document saves as .pcraft by default and everything else
/// keeps defaulting to Photoshop.
@@ -67,7 +77,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
}
let answer: Pin<Box<dyn Future<Output = Option<FileDialogAnswer>> + Send>> = match request {
FileDialogRequest::Open { multiple } => {
let dialog = dialog.add_filter("All Formats", OPEN_EXTS).add_filter("PhotoCraft", &["pcraft"]);
let dialog = dialog.add_filter("All Formats", &open_filter_extensions(OPEN_EXTS)).add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]));
if multiple {
let picked = dialog.pick_files();
Box::pin(async move { picked.await.map(|files| FileDialogAnswer::Paths(files.iter().map(path_of).collect())) })
@@ -383,6 +393,44 @@ mod tests {
use photocraft_ui_egui::{PhotocraftApp, prefs_ui};
use serde_json::{Value, json};
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn open_filters_cover_uppercase_and_mixed_case_extensions() {
// Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`.
fn matches(glob: &str, text: &str) -> bool {
let mut text = text.chars();
let mut glob = glob.chars();
while let Some(g) = glob.next() {
let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() };
if !text.next().is_some_and(|t| class.contains(t)) {
return false;
}
}
text.next().is_none()
}
assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]);
let globs = open_filter_extensions(OPEN_EXTS);
assert_eq!(globs.len(), OPEN_EXTS.len());
for (ext, glob) in OPEN_EXTS.iter().zip(&globs) {
// Every casing: lower, UPPER, and alternating both ways (JpG, jPg).
let alternating = |upper_first: bool| -> String {
ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect()
};
for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] {
assert!(matches(glob, &name), "{glob} should match .{name}");
}
assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}");
}
assert!(!globs.iter().any(|glob| matches(glob, "txt")));
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
#[test]
fn open_filters_keep_literal_extensions_on_windows_and_macos() {
assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS);
assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]);
}
#[test]
fn xwayland_command_matches_how_photocraft_was_installed() {
// Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do.
+3
View File
@@ -17,6 +17,9 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.AlanRockefeller]
sync_github_name = true
[people.echelon]
real_name = "Brandon Thomas"
display_name = "Brandon Thomas"
+101 -1
View File
@@ -320,7 +320,10 @@ impl LiquifyField {
let r = (s.size / 2.0).max(0.5);
let spacing = (r * 0.2).max(0.5);
let steps = (len / spacing).ceil().max(1.0) as usize;
for k in 1..=steps {
// Walk only the steps whose dab can reach a field node: the rest return from `dab` before
// touching anything, and a segment to a far-off point has trillions of them (#937).
let Some((k0, k1)) = self.reachable_steps(a, b, steps, r, s.tool.is_stationary()) else { return dirty };
for k in k0..=k1 {
let t0 = (k - 1) as f64 / steps as f64;
let t1 = k as f64 / steps as f64;
let c = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1];
@@ -333,6 +336,39 @@ impl LiquifyField {
dirty
}
/// The steps `k0..=k1` of a segment walked in `steps` whose dab can touch a field node, or
/// `None` when none can. Step `k` centres its dab at `a + (b - a)·(k - o)/steps`, with `o` = 1
/// for the dragging tools and 0 for the stationary ones (see `stroke_segment`). A dab reaches a
/// node only when its centre is within `r` plus a node of the node grid, so the window below
/// pads that by another node and a step: the dabs it leaves out would each change nothing.
fn reachable_steps(&self, a: [f64; 3], b: [f64; 3], steps: usize, r: f64, stationary: bool) -> Option<(usize, usize)> {
if self.w == 0 || self.h == 0 {
return None;
}
let pad = r + 2.0 * self.cell;
let lo = [f64::from(self.bounds.x0) + 0.5 - pad, f64::from(self.bounds.y0) + 0.5 - pad];
let hi = [lo[0] + (self.w - 1) as f64 * self.cell + 2.0 * pad, lo[1] + (self.h - 1) as f64 * self.cell + 2.0 * pad];
let (n, o) = (steps as f64, if stationary { 0.0 } else { 1.0 });
let (mut k0, mut k1) = (1.0f64, n);
for ax in 0..2 {
let d = b[ax] - a[ax];
if d == 0.0 {
if a[ax].is_nan() || a[ax] < lo[ax] || a[ax] > hi[ax] {
return None;
}
continue;
}
let (u0, u1) = ((lo[ax] - a[ax]) / d, (hi[ax] - a[ax]) / d);
k0 = k0.max((u0.min(u1) * n + o).floor() - 1.0);
k1 = k1.min((u0.max(u1) * n + o).ceil() + 1.0);
}
// NaN: a segment whose length overflowed.
if k0.is_nan() || k1.is_nan() || k0 > k1 {
return None;
}
Some((k0 as usize, k1 as usize))
}
/// One dab at `c` with brush motion `delta`. Returns the document rect it affected.
fn dab(&mut self, s: &LiquifyStroke, c: [f64; 2], delta: [f64; 2], point_pressure: f64) -> Rect {
if s.tool == LiquifyTool::LassoMask {
@@ -742,6 +778,70 @@ mod tests {
use super::*;
use photocraft_color::{ColorMode, PixelFormat, SampleType};
/// The segment walk before #937: every step, whether or not its dab can reach the field.
fn full_walk(f: &mut LiquifyField, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect {
let mut dirty = Rect::EMPTY;
let (pa, pb) = (a[2].clamp(0.0, 1.0), b[2].clamp(0.0, 1.0));
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
let r = (s.size / 2.0).max(0.5);
let steps = (len / (r * 0.2).max(0.5)).ceil().max(1.0) as usize;
for k in 1..=steps {
let (t0, t1) = ((k - 1) as f64 / steps as f64, k as f64 / steps as f64);
let c = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1];
let delta = [(b[0] - a[0]) * (t1 - t0), (b[1] - a[1]) * (t1 - t0)];
let centre = if s.tool.is_stationary() { c } else { [c[0] - delta[0], c[1] - delta[1]] };
dirty = dirty.union(&f.dab(s, centre, delta, pa + (pb - pa) * t1));
}
dirty
}
#[test]
fn a_segment_walks_only_the_dabs_that_can_reach_the_field() {
// #937: a segment to a far-off point walked one dab per spacing step along its whole
// length (~3e14 for 1e15 px). Skipping the dabs that can't reach a field node must leave
// every result bit-identical to the full walk.
use LiquifyTool::*;
let bounds = Rect::new(-7, 3, 89, 67);
let segments: [([f64; 3], [f64; 3]); 9] = [
([10.0, 20.0, 1.0], [70.0, 50.0, 0.5]), // inside
([-900.0, 30.0, 1.0], [40.0, 31.0, 1.0]), // in from far left
([40.0, 30.0, 1.0], [40.0, 4000.0, 0.2]), // out downwards
([-500.0, -500.0, 1.0], [600.0, 600.0, 1.0]), // diagonal through
([-300.0, -9.0, 1.0], [300.0, -9.0, 1.0]), // parallel, just above (the brush reaches)
([-300.0, -400.0, 1.0], [300.0, -400.0, 1.0]), // parallel, far above (reaches nothing)
([88.5, -50.0, 1.0], [88.5, 120.0, 1.0]), // vertical, along the right edge
([200.0, 200.0, 1.0], [201.0, 900.0, 1.0]), // entirely outside
([0.0, 0.0, 1.0], [0.25, 0.1, 1.0]), // shorter than one step
];
for tool in [ForwardWarp, PushLeft, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, Freeze, Thaw] {
for size in [6.0, 40.0] {
for (a, b) in segments {
let s = LiquifyStroke::new(tool, size);
let (mut fast, mut full) = (LiquifyField::new(bounds, 2.0), LiquifyField::new(bounds, 2.0));
// Some displacement first, so Reconstruct and Smooth have something to undo.
for f in [&mut fast, &mut full] {
f.stroke_segment(&LiquifyStroke::new(ForwardWarp, 30.0), [20.0, 20.0, 1.0], [60.0, 40.0, 1.0]);
}
let dirty = fast.stroke_segment(&s, a, b);
assert_eq!(dirty, full_walk(&mut full, &s, a, b), "{tool:?} {size} {a:?} {b:?}");
assert!(fast.d == full.d && fast.freeze == full.freeze, "{tool:?} {size} {a:?} {b:?}");
}
}
}
}
#[test]
fn a_segment_to_a_far_off_point_returns() {
// The issue's request: about 3.3e14 steps before the fix. Also a segment whose length
// overflows f64.
let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0);
let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0);
let dirty = f.stroke_segment(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0]);
assert!(!dirty.is_empty() && dirty.x1 <= 64, "{dirty:?}");
f.stroke_segment(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0]);
f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]);
}
fn sample(st: SampleType) -> Surface {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
for y in 0..64 {
+12
View File
@@ -288,6 +288,18 @@ impl Effect {
}
}
/// Switches this instance on or off, keeping its settings.
pub fn set_enabled(&mut self, on: bool) {
match self {
Effect::DropShadow(s) | Effect::InnerShadow(s) => s.common.enabled = on,
Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.common.enabled = on,
Effect::Stroke(s) => s.common.enabled = on,
Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => common.enabled = on,
Effect::Satin(s) => s.common.enabled = on,
Effect::BevelEmboss(b) => b.enabled = on,
}
}
/// Short label for UIs.
pub fn label(&self) -> &'static str {
match self {
+67 -28
View File
@@ -31,42 +31,77 @@ fn num(p: &Value, key: &str, default: f32) -> f32 {
p.get(key).and_then(Value::as_f64).map_or(default, |v| v as f32)
}
/// `key`'s value; a null counts as missing (as in `adjust_params`).
fn given<'a>(p: &'a Value, key: &str) -> Option<&'a Value> {
p.get(key).filter(|v| !v.is_null())
}
fn opt_str<'a>(cmd: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
match given(p, key) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s)),
Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))),
}
}
fn opt_bool(cmd: &str, p: &Value, key: &str) -> Result<Option<bool>> {
match given(p, key) {
None => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
}
}
/// A percentage in -100..100 (clamped); anything but a finite number is an error.
fn percent(cmd: &str, key: &str, v: &Value) -> Result<f32> {
let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?;
Ok((x as f32).clamp(-100.0, 100.0))
}
/// Selective Color from params. Accepts per-range arrays (`"reds":[c,m,y,k]` in percent) and the
/// dialog's single-range form (`"colors":"reds","cyan":…,"magenta":…,"yellow":…,"black":…`);
/// `"method":"relative|absolute"`. Unspecified ranges keep `base`'s values.
pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Adjustment {
/// `"method":"relative|absolute"`. Unspecified ranges keep `base`'s values; a key of the wrong
/// type is an error.
pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjustment> {
const CMD: &str = "selectiveColor";
let (mut relative, mut adj) = match base {
Some(Adjustment::SelectiveColor { relative, adjustments }) => (*relative, *adjustments),
_ => (true, [[0.0; 4]; 9]),
};
if let Some(m) = p.get("method").and_then(Value::as_str) {
relative = m != "absolute";
match opt_str(CMD, p, "method")? {
None => {}
Some("relative") => relative = true,
Some("absolute") => relative = false,
Some(m) => return Err(bad(CMD, format!("`method` must be \"relative\" or \"absolute\", not `{m}`"))),
}
if let Some(b) = p.get("relative").and_then(Value::as_bool) {
if let Some(b) = opt_bool(CMD, p, "relative")? {
relative = b;
}
for (i, key) in RANGES.iter().enumerate() {
if let Some(a) = p.get(*key).and_then(Value::as_array) {
for (k, v) in a.iter().take(4).enumerate() {
adj[i][k] = (v.as_f64().unwrap_or(0.0) as f32).clamp(-100.0, 100.0);
for (row, key) in adj.iter_mut().zip(RANGES) {
let Some(v) = given(p, key) else { continue };
let a = v.as_array().filter(|a| a.len() == 4).ok_or_else(|| bad(CMD, format!("`{key}` must be an array of 4 numbers [c, m, y, k]")))?;
for (slot, x) in row.iter_mut().zip(a) {
*slot = percent(CMD, key, x)?;
}
}
if let Some(c) = opt_str(CMD, p, "colors")? {
let Some((row, _)) = adj.iter_mut().zip(RANGES).find(|(_, r)| *r == c) else {
return Err(bad(CMD, format!("unknown range `{c}` (ranges: {})", RANGES.join(", "))));
};
for (slot, key) in row.iter_mut().zip(["cyan", "magenta", "yellow", "black"]) {
if let Some(v) = given(p, key) {
*slot = percent(CMD, key, v)?;
}
}
}
let range = p.get("colors").and_then(Value::as_str).and_then(|c| RANGES.iter().position(|r| *r == c));
if let Some(i) = range {
for (k, key) in ["cyan", "magenta", "yellow", "black"].iter().enumerate() {
if let Some(v) = p.get(*key).and_then(Value::as_f64) {
adj[i][k] = (v as f32).clamp(-100.0, 100.0);
}
}
}
Adjustment::SelectiveColor { relative, adjustments: adj }
Ok(Adjustment::SelectiveColor { relative, adjustments: adj })
}
/// Color Lookup from params: `"lut"` (a built-in look id or `"none"`), `"file"` (a .cube / .3dl /
/// .look path, native only) or `"data"` (the file's text, with `"fileName"` naming its format),
/// `"interpolation":"trilinear|tetrahedral"`, `"dither":bool`. The table is embedded in the
/// layer, as Photoshop does. Unspecified fields keep `base`'s values.
/// layer, as Photoshop does. Unspecified fields keep `base`'s values; a key of the wrong type is an
/// error.
pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjustment> {
const CMD: &str = "colorLookup";
let (mut name, mut lut, mut size, mut tetrahedral, mut dither) = match base {
@@ -74,7 +109,7 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
_ => (String::new(), None, 0, false, false),
};
let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String)> = None;
if let Some(id) = p.get("lut").and_then(Value::as_str) {
if let Some(id) = opt_str(CMD, p, "lut")? {
if id == "none" || id.is_empty() {
name.clear();
lut = None;
@@ -85,12 +120,13 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
loaded = Some((f, label));
}
}
if let Some(text) = p.get("data").and_then(Value::as_str) {
let file_name = p.get("fileName").and_then(Value::as_str).unwrap_or("lut.cube");
let file_name = opt_str(CMD, p, "fileName")?;
if let Some(text) = opt_str(CMD, p, "data")? {
let file_name = file_name.unwrap_or("lut.cube");
let f = photocraft_cms::lutfile::parse(file_name, text.as_bytes()).map_err(|e| bad(CMD, e.0))?;
loaded = Some((f, base_name(file_name)));
}
if let Some(path) = p.get("file").and_then(Value::as_str).filter(|s| !s.is_empty()) {
if let Some(path) = opt_str(CMD, p, "file")?.filter(|s| !s.is_empty()) {
let bytes = read_file(path).ok_or_else(|| bad(CMD, format!("can't read {path}")))?;
let f = photocraft_cms::lutfile::parse(path, &bytes).map_err(|e| bad(CMD, format!("{path}: {}", e.0)))?;
loaded = Some((f, base_name(path)));
@@ -109,13 +145,16 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
size = f.size as u32;
lut = Some(std::sync::Arc::new(f.data));
}
if let Some(i) = p.get("interpolation").and_then(Value::as_str) {
tetrahedral = i == "tetrahedral";
match opt_str(CMD, p, "interpolation")? {
None => {}
Some("trilinear") => tetrahedral = false,
Some("tetrahedral") => tetrahedral = true,
Some(i) => return Err(bad(CMD, format!("`interpolation` must be \"trilinear\" or \"tetrahedral\", not `{i}`"))),
}
if let Some(b) = p.get("tetrahedral").and_then(Value::as_bool) {
if let Some(b) = opt_bool(CMD, p, "tetrahedral")? {
tetrahedral = b;
}
if let Some(b) = p.get("dither").and_then(Value::as_bool) {
if let Some(b) = opt_bool(CMD, p, "dither")? {
dither = b;
}
Ok(Adjustment::ColorLookup { name, lut, size, tetrahedral, dither })
@@ -143,7 +182,7 @@ fn read_file(_: &str) -> Option<Vec<u8>> {
pub fn update_adjustment(existing: &Adjustment, p: &Value) -> Option<Result<Adjustment>> {
let empty = p.as_object().is_none_or(|o| o.keys().all(|k| matches!(k.as_str(), "layer" | "coalesce" | "__kind")));
match existing {
Adjustment::SelectiveColor { .. } => Some(Ok(selective_from_params(p, (!empty).then_some(existing)))),
Adjustment::SelectiveColor { .. } => Some(selective_from_params(p, (!empty).then_some(existing))),
Adjustment::ColorLookup { .. } => Some(lookup_from_params(p, (!empty).then_some(existing))),
_ => None,
}
+81
View File
@@ -219,6 +219,87 @@ LUT_3D_SIZE 2
assert_eq!(looks.as_array().unwrap().len(), photocraft_cms::lutfile::BUILTIN.len());
}
/// The kind's parameters, read back from the model (Color Lookup with its table name and size).
fn adjustment_of(s: &Session, id: photocraft_doc::LayerId) -> Adjustment {
match &doc(s).layer(id).unwrap().content {
LayerContent::Adjustment(a) => a.clone(),
other => panic!("{other:?}"),
}
}
#[test]
fn selective_color_and_color_lookup_reject_wrong_typed_params() {
let cube = "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
// (kind, params, the key the error must name)
let cases: Vec<(&str, Value, &str)> = vec![
("selectiveColor", json!({"method": 5}), "method"),
("selectiveColor", json!({"method": "sideways"}), "method"),
("selectiveColor", json!({"relative": "yes"}), "relative"),
("selectiveColor", json!({"reds": "not-an-array"}), "reds"),
("selectiveColor", json!({"blues": [10, 20]}), "blues"),
("selectiveColor", json!({"neutrals": [10, "20", 0, 0]}), "neutrals"),
("selectiveColor", json!({"colors": 3, "cyan": 50}), "colors"),
("selectiveColor", json!({"colors": "purples", "cyan": 50}), "purples"),
("selectiveColor", json!({"colors": "reds", "cyan": "50"}), "cyan"),
("selectiveColor", json!({"colors": "blacks", "black": [1]}), "black"),
("colorLookup", json!({"lut": 42}), "lut"),
("colorLookup", json!({"interpolation": 5}), "interpolation"),
("colorLookup", json!({"interpolation": "bicubic"}), "interpolation"),
("colorLookup", json!({"tetrahedral": 1}), "tetrahedral"),
("colorLookup", json!({"dither": "yes"}), "dither"),
("colorLookup", json!({"data": 42}), "data"),
("colorLookup", json!({"data": cube, "fileName": 7}), "fileName"),
("colorLookup", json!({"file": 42}), "file"),
];
let named = |r: Result<Value>, key: &str, what: &str| match r {
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().contains(key), "{what}: {e}"),
other => panic!("{what}: expected BadParams naming `{key}`, got {other:?}"),
};
for depth in DEPTHS {
for mode in ["rgb", "cmyk", "lab"] {
for (kind, p, key) in &cases {
let what = format!("{kind} {p} {depth} {mode}");
let mut s = session(depth, mode);
let (layers, steps, px) = (doc(&s).layers.len(), s.active().unwrap().history.past_len(), rgba(&s, 3, 3));
named(s.execute(&format!("image.adjustments.{kind}"), p.clone()), key, &what);
named(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), p.clone()), key, &what);
assert_eq!(doc(&s).layers.len(), layers, "{what}: no layer added");
assert_eq!(s.active().unwrap().history.past_len(), steps, "{what}: no history step");
assert_eq!(rgba(&s, 3, 3), px, "{what}: pixels unchanged");
}
}
}
// An update with a wrong-typed key fails and keeps every existing value.
let mut s = session(8, "rgb");
let made = [
("selectiveColor", json!({"method": "absolute", "reds": [10, -20, 30, -40], "colors": "blues", "yellow": 40})),
("colorLookup", json!({"lut": "warm", "interpolation": "tetrahedral", "dither": true})),
];
for (kind, p) in made {
let id = photocraft_doc::LayerId(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), p).unwrap()["layer"].as_u64().unwrap());
let before = adjustment_of(&s, id);
for (k, p, key) in cases.iter().filter(|c| c.0 == kind) {
let mut p = p.clone();
p["layer"] = json!(id.0);
named(s.execute("layer.setAdjustment", p.clone()), key, &format!("setAdjustment {k} {p}"));
assert_eq!(adjustment_of(&s, id), before, "{p}");
}
// Null still means "not given": the update keeps everything.
let nulls = json!({"layer": id.0, "method": null, "reds": null, "colors": null, "lut": null, "interpolation": null, "dither": null});
s.execute("layer.setAdjustment", nulls).unwrap();
assert_eq!(adjustment_of(&s, id), before, "{kind}: nulls");
}
// Well-typed values reach the model.
match adjustment_of(&s, doc(&s).layers[1].id) {
Adjustment::SelectiveColor { relative: false, adjustments } => {
assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]);
assert_eq!(adjustments[4], [0.0, 0.0, 40.0, 0.0]);
}
other => panic!("{other:?}"),
}
assert!(matches!(adjustment_of(&s, doc(&s).layers[2].id), Adjustment::ColorLookup { lut: Some(_), tetrahedral: true, dither: true, .. }));
}
#[test]
fn new_kinds_round_trip_through_psd_and_pcraft() {
let mut s = session(8, "rgb");
+7 -1
View File
@@ -203,7 +203,7 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color
};
Adjustment::GradientMap { stops, reverse: r.boolean("reverse", rev0)?, dither: r.boolean("dither", dither0)? }
}
"selectiveColor" => crate::adjust_cmds::selective_from_params(p, base.filter(|b| matches!(b, Adjustment::SelectiveColor { .. }))),
"selectiveColor" => crate::adjust_cmds::selective_from_params(p, base.filter(|b| matches!(b, Adjustment::SelectiveColor { .. })))?,
"colorLookup" => crate::adjust_cmds::lookup_from_params(p, base.filter(|b| matches!(b, Adjustment::ColorLookup { .. })))?,
other => return Err(bad("adjustment", format!("unknown adjustment kind `{other}`"))),
})
@@ -909,6 +909,12 @@ mod tests {
("channelMixer", json!({"red": [1, 2, 3]})),
("gradientMap", json!({"stops": [[0, "#000"]]})),
("gradientMap", json!({"stops": 7})),
("selectiveColor", json!({"method": 5})),
("selectiveColor", json!({"reds": "not-an-array"})),
("selectiveColor", json!({"colors": "reds", "cyan": "50"})),
("colorLookup", json!({"lut": 42})),
("colorLookup", json!({"interpolation": 5})),
("colorLookup", json!({"dither": "yes"})),
("nope", json!({})),
("levels", json!([1, 2])),
] {
+25 -4
View File
@@ -74,11 +74,17 @@ pub fn parse_points(p: &Value, cmd: &str) -> Result<Vec<StrokePoint>> {
if pts.is_empty() {
return Err(bad(cmd, "`points` is empty"));
}
// A stroke runs dab by dab along its length: an absurd coordinate would mean billions of dabs.
check_coords(&pts, cmd)?;
Ok(pts)
}
/// A stroke runs dab by dab along its length: an absurd coordinate would mean billions of dabs.
/// Shared by the painting and the retouch tools' `points` (#976).
pub(crate) fn check_coords(pts: &[StrokePoint], cmd: &str) -> Result<()> {
if pts.iter().any(|q| !(q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)) {
return Err(bad(cmd, format!("point coordinates must be finite and within ±{MAX_COORD}")));
}
Ok(pts)
Ok(())
}
/// Deep-merge `patch` into `base` (objects merge key by key; anything else replaces).
@@ -324,6 +330,7 @@ pub struct LiveStroke {
pub doc: std::sync::Arc<photocraft_doc::Document>,
/// Jitter seed to pass to `paint.stroke`.
pub seed: u64,
cmd: String,
renderer: StrokeRenderer,
mirror: Option<(crate::symmetry_cmds::SymmetryAxis, StrokeRenderer)>,
mirror_distinct: bool,
@@ -365,8 +372,20 @@ impl LiveStroke {
let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
let mirror = s.active().and_then(|st| st.symmetry_path.clone()).map(|axis| (axis, StrokeRenderer::new(&brush, Some(surf.format()), zoom)));
let pre = surf.clone();
let mut live =
Self { doc: std::sync::Arc::new(doc), seed, renderer, mirror, mirror_distinct: false, pre, sel, lock, layer, params: p.clone(), tail: Rect::EMPTY };
let mut live = Self {
doc: std::sync::Arc::new(doc),
seed,
cmd: cmd.into(),
renderer,
mirror,
mirror_distinct: false,
pre,
sel,
lock,
layer,
params: p.clone(),
tail: Rect::EMPTY,
};
live.push(&pts)?;
Ok(live)
}
@@ -381,7 +400,9 @@ impl LiveStroke {
/// committing it now would: with smoothing, the brush lags behind the pointer and catches up
/// when the stroke ends, so that catch-up tail is drawn too (and redrawn on every step), and
/// nothing new appears on release.
/// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
if let Some((axis, mirror)) = &mut self.mirror {
let reflected = axis.reflect_points(pts);
+51
View File
@@ -336,6 +336,57 @@ fn live_stroke_matches_the_committed_stroke() {
assert!(LiveStroke::begin(&Session::new(), &json!({"points": [[1, 1]]})).is_err());
}
#[test]
fn stroke_coordinate_validation_keeps_the_existing_bounds() {
let edges = [StrokePoint::new(-MAX_COORD, MAX_COORD, 1.0), StrokePoint::new(MAX_COORD, -MAX_COORD, 1.0)];
assert!(check_coords(&edges, "paint.stroke").is_ok());
assert!(check_coords(&[], "paint.stroke").is_ok(), "an empty live update is allowed");
for (x, y) in [(MAX_COORD + 1.0, 0.0), (0.0, -MAX_COORD - 1.0), (f64::NAN, 0.0), (0.0, f64::INFINITY)] {
assert!(check_coords(&[StrokePoint::new(x, y, 1.0)], "paint.stroke").is_err());
}
// The command parser still rejects empty strokes and shares the same inclusive boundary.
assert!(parse_points(&json!({"points": []}), "paint.stroke").is_err());
assert!(parse_points(&json!({"points": [[MAX_COORD, -MAX_COORD]]}), "paint.stroke").is_ok());
}
#[test]
fn live_brush_and_pencil_reject_invalid_batches_without_changing_the_preview() {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 32, "height": 32, "depth": depth, "background": "transparent"})).unwrap();
let st = s.active().unwrap();
let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.past_len());
let id = st.active_layer.unwrap();
for (cmd, erase) in [("paint.stroke", false), ("paint.stroke", true), ("paint.pencil", false)] {
let p = json!({"points": [[8, 16]], "size": 4, "erase": erase, "seed": 7});
let mut live = LiveStroke::begin_with(&s, cmd, &p).unwrap();
let mut control = LiveStroke::begin_with(&s, cmd, &p).unwrap();
// NaN first: on an unguarded renderer this fails without starting the enormous segment.
for (x, y) in [(f64::NAN, 16.0), (16.0, f64::NAN), (f64::INFINITY, 16.0), (16.0, f64::NEG_INFINITY), (1e300, 16.0), (16.0, -MAX_COORD - 1.0)] {
let shown = live.doc.clone();
let bounds = live.bounds();
let batch = [StrokePoint::new(12.0, 18.0, 1.0), StrokePoint::new(x, y, 1.0)];
let err = live.push(&batch).unwrap_err();
assert!(matches!(err, EngineError::BadParams { cmd: ref actual, ref msg }
if actual == cmd && msg.contains("point coordinates must be finite")));
assert!(std::sync::Arc::ptr_eq(&shown, &live.doc), "reject the whole batch before touching the preview");
assert_eq!(live.bounds(), bounds);
}
// A rejected batch must not advance the renderer; resuming is identical to never
// receiving it. Ordinary off-canvas points remain valid too.
let next = [StrokePoint::new(-4.0, 16.0, 1.0), StrokePoint::new(24.0, 16.0, 1.0)];
assert_eq!(live.push(&next).unwrap(), control.push(&next).unwrap());
assert_eq!(live.bounds(), control.bounds());
let (got, want) = (live.doc.layer(id).unwrap().surface().unwrap(), control.doc.layer(id).unwrap().surface().unwrap());
assert!(same_pixels(got, want, live.bounds()));
assert_eq!(got.content_bounds(), want.content_bounds());
}
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&doc, &st.doc));
assert_eq!((st.revision, st.history.past_len()), (revision, history));
}
}
#[test]
fn live_pencil_matches_the_committed_pencil_and_auto_erases() {
let mut s = session(80, 40);
+1
View File
@@ -1165,6 +1165,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::plugin_cmds::specs());
v.extend(crate::group_view_cmds::specs());
v.extend(crate::fx_view_cmds::specs());
v.extend(crate::fx_visibility_cmds::specs());
v.extend(crate::mask_view_cmds::specs());
v.extend(crate::actions_cmds::specs());
v
+14
View File
@@ -266,3 +266,17 @@ fn background_layer_is_floated_by_geometric_warps() {
assert!(l.surface().unwrap().format().alpha);
assert!(l.surface().unwrap().pixel(2, 15)[3] < 0.01, "exposed area is transparent");
}
#[test]
fn liquify_with_a_far_off_stroke_point_returns() {
// #937: the issue's request walked ~3.3e14 dab steps along a segment to (1e15, 0).
for depth in [8u64, 16, 32] {
let mut s = session(depth);
let r = s.execute(LIQUIFY, json!({"strokes": [{"tool": "forwardWarp", "size": 30, "points": [[0, 0], [1e15, 0]]}]})).unwrap();
assert_eq!(r["changed"], true, "{depth}: the start of the stroke is on the canvas");
let mut s = session(depth);
let before = active_surface(&s);
s.execute(LIQUIFY, json!({"strokes": [{"tool": "bloat", "size": 30, "points": [[5000, 5000], [1e15, 1e15]]}]})).unwrap();
assert_eq!(active_surface(&s).read_region(Rect::new(0, 0, 80, 60)), before.read_region(Rect::new(0, 0, 80, 60)), "{depth}: off-canvas only");
}
}
+85 -16
View File
@@ -61,20 +61,27 @@ fn step_key(s: &Session, what: &str) -> String {
/// Rewrite the active pixel layer's RGBA over the selection bounds (or the canvas). `f` gets the
/// area, the pixels, and the selection coverage per pixel; results are blended back by coverage,
/// and transparency stays locked when the layer locks it.
fn map_pixels(s: &mut Session, label: &str, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
/// and transparency stays locked when the layer locks it. When `p` targets an alpha channel, the
/// Quick Mask or the layer mask (`Session::execute` fills that in from the Channels panel), that
/// grayscale surface is rewritten instead, as the core filters do (#935).
fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
let id = layer_param(s, &Value::Null)?;
let channel = crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels;
s.edit(label, |doc, _| {
let canvas = doc.bounds();
let selection = doc.selection.clone();
let area = selection.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas));
let locks = doc.effective_locks(id);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
if locks.pixels || locks.all {
return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));
}
let lock_alpha = locks.transparency;
let surf = l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
let (surf, lock_alpha) = if channel {
let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, Some(id), p)? else { return Ok(()) };
(surf, false)
} else {
let locks = doc.effective_locks(id);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
if locks.pixels || locks.all {
return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));
}
(l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?, locks.transparency)
};
if area.is_empty() {
return Ok(());
}
@@ -154,8 +161,8 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
/// Histogram equalization, like Photoshop's: one CDF over the R, G and B values of
/// the selected pixels, applied to every channel.
fn equalize(s: &mut Session) -> Result<Value> {
map_pixels(s, "Equalize", |_, px, cover| {
fn equalize(s: &mut Session, p: &Value) -> Result<Value> {
map_pixels(s, "Equalize", p, |_, px, cover| {
let mut hist = [0f64; 256];
for (p, &k) in px.iter().zip(cover) {
if k > 0.0 && p[3] > 0.0 {
@@ -186,8 +193,8 @@ fn equalize(s: &mut Session) -> Result<Value> {
}
/// Filter › Blur › Average: the selection (or layer) filled with its mean colour.
fn average(s: &mut Session) -> Result<Value> {
map_pixels(s, "Average", |_, px, cover| {
fn average(s: &mut Session, p: &Value) -> Result<Value> {
map_pixels(s, "Average", p, |_, px, cover| {
let (mut sum, mut wsum, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64);
for (p, &k) in px.iter().zip(cover) {
let w = (p[3] * k) as f64;
@@ -240,7 +247,7 @@ fn clouds(s: &mut Session, p: &Value, difference: bool) -> Result<Value> {
let seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0) as u32;
let size = s.active().map_or(256.0, |d| d.doc.size.width.max(d.doc.size.height) as f32);
let base = (size / 4.0).clamp(16.0, 512.0);
map_pixels(s, if difference { "Difference Clouds" } else { "Clouds" }, |area, px, _| {
map_pixels(s, if difference { "Difference Clouds" } else { "Clouds" }, p, |area, px, _| {
let w = area.width() as usize;
for (i, p) in px.iter_mut().enumerate() {
let (x, y) = ((area.x0 + (i % w) as i32) as f32, (area.y0 + (i / w) as i32) as f32);
@@ -655,7 +662,7 @@ pub fn specs() -> Vec<CommandSpec> {
})?;
Ok(json!({"selected": true}))
}),
spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", has_pixels, |s, _| equalize(s)),
spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", has_pixels, equalize),
spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| {
let d = s.active().ok_or(EngineError::NoDocument)?;
let all = reveal_all_bounds(&d.doc);
@@ -760,7 +767,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_layer,
show_only
),
spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, |s, _| average(s)),
spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average),
spec!("filter.render.clouds", "Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, false)),
spec!("filter.render.differenceClouds", "Difference Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, true)),
]
@@ -781,6 +788,68 @@ mod tests {
&s.active().unwrap().doc
}
#[test]
fn equalize_average_and_clouds_edit_the_targeted_channel() {
// #935: these four ran through `map_pixels`, which always rewrote the active layer, so
// with an alpha channel or the Quick Mask targeted they changed the layer and left the
// channel alone.
let cmds = ["image.adjustments.equalize", "filter.blur.average", "filter.render.clouds", "filter.render.differenceClouds"];
for depth in [8, 16, 32] {
for target in ["quickMask", "alpha", "mask"] {
for cmd in cmds {
let mut s = session(depth);
s.tools.foreground = [0.0, 0.0, 0.0, 1.0];
s.tools.background = [1.0, 1.0, 1.0, 1.0];
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
let p = match target {
"quickMask" => {
s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
json!({"seed": 1})
}
"alpha" => {
s.execute("channel.new", json!({"fill": "white"})).unwrap();
s.execute("channel.target", json!({"channel": 0})).unwrap();
json!({"seed": 1})
}
_ => {
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
json!({"seed": 1, "target": "mask"})
}
};
// Two levels in the target, so Equalize and Average have something to change.
let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } });
s.edit("levels", |doc, active| {
let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &edit_target).unwrap();
surf.fill_rect(Rect::new(0, 0, 20, 30), &[0.4]);
surf.fill_rect(Rect::new(20, 0, 40, 30), &[0.5]);
Ok(())
})
.unwrap();
let full = Rect::new(0, 0, 40, 30);
let read = |s: &Session| {
let d = doc(s);
let layer = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap();
let t = match target {
"quickMask" => d.quick_mask.as_ref().unwrap().surface.read_region(full),
"alpha" => d.channels[0].surface.read_region(full),
_ => layer.mask.as_ref().unwrap().surface.read_region(full),
};
(layer.surface().unwrap().read_region(full), t)
};
let ((layer0, target0), past) = (read(&s), s.active().unwrap().history.past_len());
s.execute(cmd, p).unwrap();
let (layer1, target1) = read(&s);
let case = format!("{cmd} on {target} at {depth}");
assert_eq!(layer1, layer0, "{case}: the layer is untouched");
assert_ne!(target1, target0, "{case}: the target changed");
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}");
s.undo();
assert_eq!(read(&s).1, target0, "{case}: undo restores the target");
}
}
}
}
fn active(s: &Session) -> &Layer {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap()
+183
View File
@@ -0,0 +1,183 @@
//! Layers panel: the eyes on a layer's effects rows (#1622). The eye on the "Effects" row shows or
//! hides every effect of that layer; the eye on one effect's row shows or hides that effect. The
//! effects keep their settings either way, and each toggle is one history step.
use photocraft_doc::LayerId;
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
const ID: &str = "layer.setEffectsVisible";
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: ID.into(), msg: msg.into() }
}
fn has_effects(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
if d.doc.walk().iter().any(|(_, _, l)| !l.effects.items.is_empty()) { Ok(()) } else { Err("no layer has effects".into()) }
}
/// `{"layer":id?,"index":n?,"visible":bool?}`: show or hide a layer's effects (no `visible`:
/// toggle). Without `index` it is the whole list (the "Effects" row); with it, the effect at that
/// position in the layer's list.
fn set_visible(s: &mut Session, p: &Value) -> Result<Value> {
let want = match p.get("visible") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_bool().ok_or_else(|| bad("`visible` must be true or false"))?),
};
let index = match p.get("index") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("`index` must be an effect position (0, 1, …)"))?),
};
let st = s.active().ok_or(EngineError::NoDocument)?;
let id = match p.get("layer") {
None | Some(Value::Null) => st.active_layer.ok_or_else(|| bad("no layer given and no active layer"))?,
Some(v) => LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be a layer id"))?),
};
let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
if l.effects.items.is_empty() {
return Err(bad(format!("layer {} has no effects", id.0)));
}
let (current, name) = match index {
Some(i) => {
let e = l.effects.items.get(i).ok_or_else(|| bad(format!("layer {} has no effect at index {i}", id.0)))?;
(e.enabled(), e.label())
}
None => (l.effects.enabled, "Layer Effects"),
};
let visible = want.unwrap_or(!current);
if visible != current {
let label = format!("{} {name}", if visible { "Show" } else { "Hide" });
s.edit(&label, |doc, _| {
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
match index {
Some(i) => l.effects.items.get_mut(i).ok_or_else(|| bad(format!("layer {} has no effect at index {i}", id.0)))?.set_enabled(visible),
None => l.effects.enabled = visible,
}
Ok(())
})?;
}
Ok(json!({"layer": id.0, "index": index, "visible": visible}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: ID,
label: "Show/Hide Effects",
menu: &[],
shortcut: None,
params: r##"{"layer":id?,"index":n?,"visible":bool?} (no index: all of the layer's effects, the "Effects" row; index: the effect at that position in the layer's list; no visible: toggle)"##,
enabled: has_effects,
run: set_visible,
journal: true,
}]
}
#[cfg(test)]
mod tests {
use super::*;
/// A red layer with a drop shadow and a blue colour overlay, and the background (no effects).
fn session() -> (Session, u64, u64) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
let bg = s.active().unwrap().doc.layers[0].id.0;
let a = s.execute("layer.new.layer", json!({"name": "a"})).unwrap()["layer"].as_u64().unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
s.execute("layer.layerStyle.dropShadow", json!({"layer": a})).unwrap();
s.execute("layer.layerStyle.colorOverlay", json!({"layer": a, "color": "#0000ff"})).unwrap();
(s, a, bg)
}
/// (the whole list is on, each effect is on).
fn state(s: &Session, id: u64) -> (bool, Vec<bool>) {
let d = s.active().unwrap();
let fx = &d.doc.layer(LayerId(id)).unwrap().effects;
(fx.enabled, fx.items.iter().map(|e| e.enabled()).collect())
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn flat(s: &Session) -> photocraft_compose::Buffer {
photocraft_compose::flatten(&s.active().unwrap().doc)
}
#[test]
fn the_effects_row_eye_hides_and_shows_the_whole_list() {
let (mut s, a, _) = session();
let n = steps(&s);
assert_eq!(s.execute(ID, json!({"layer": a})).unwrap(), json!({"layer": a, "index": null, "visible": false}));
assert_eq!(state(&s, a), (false, vec![true, true]), "each effect keeps its own state");
assert_eq!(steps(&s), n + 1, "one history step");
assert_eq!(s.active().unwrap().history.undo_label(), Some("Hide Layer Effects"));
// The active layer is the default target.
assert_eq!(s.execute(ID, json!({})).unwrap()["visible"], true);
assert_eq!(state(&s, a), (true, vec![true, true]));
assert_eq!(s.active().unwrap().history.undo_label(), Some("Show Layer Effects"));
}
#[test]
fn one_effect_eye_hides_only_that_effect_and_undoes() {
let (mut s, a, _) = session();
assert_eq!(s.execute(ID, json!({"layer": a, "index": 1})).unwrap()["visible"], false);
assert_eq!(state(&s, a), (true, vec![true, false]));
assert_eq!(s.active().unwrap().history.undo_label(), Some("Hide Color Overlay"));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(state(&s, a), (true, vec![true, true]));
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(state(&s, a), (true, vec![true, false]));
s.execute(ID, json!({"layer": a, "index": 1, "visible": true})).unwrap();
assert_eq!(state(&s, a), (true, vec![true, true]));
}
#[test]
fn hiding_changes_the_composite_and_keeps_the_settings() {
let (mut s, a, _) = session();
let before = s.active().unwrap().doc.layer(LayerId(a)).unwrap().effects.items.clone();
let shown = flat(&s);
s.execute(ID, json!({"layer": a, "visible": false})).unwrap();
assert_ne!(flat(&s), shown, "hidden effects are not drawn");
s.execute(ID, json!({"layer": a, "visible": true})).unwrap();
assert_eq!(flat(&s), shown);
assert_eq!(s.active().unwrap().doc.layer(LayerId(a)).unwrap().effects.items, before);
}
#[test]
fn asking_for_the_current_state_adds_no_history_step() {
let (mut s, a, _) = session();
let n = steps(&s);
assert_eq!(s.execute(ID, json!({"layer": a, "visible": true})).unwrap()["visible"], true);
assert_eq!(s.execute(ID, json!({"layer": a, "index": 0, "visible": true})).unwrap()["visible"], true);
assert_eq!(steps(&s), n);
}
#[test]
fn bad_params_fail_gracefully() {
let (mut s, a, bg) = session();
let before = state(&s, a);
for p in [
json!({"layer": bg}),
json!({"layer": 9999}),
json!({"layer": "x"}),
json!({"layer": -1}),
json!({"layer": a, "index": 2}),
json!({"layer": a, "index": -1}),
json!({"layer": a, "index": 1.5}),
json!({"layer": a, "index": "0"}),
json!({"layer": a, "index": u64::MAX}),
json!({"layer": a, "visible": "yes"}),
json!({"layer": a, "visible": 1}),
] {
assert!(s.execute(ID, p.clone()).is_err(), "{p}");
}
assert_eq!(state(&s, a), before, "a refused call changes nothing");
let mut empty = Session::new();
assert!(empty.execute(ID, json!({})).is_err());
empty.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
assert!(empty.execute(ID, json!({})).is_err(), "no effects: disabled");
}
}
+1
View File
@@ -39,6 +39,7 @@ pub mod filters_ext;
pub mod float_cmds;
mod frame_cmds;
pub mod fx_view_cmds;
pub mod fx_visibility_cmds;
pub mod gallery_cmds;
pub mod gradient_fill_cmds;
pub mod group_view_cmds;
+23 -6
View File
@@ -81,10 +81,7 @@ fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option<Laye
if pts.is_empty() {
return Err(bad(cmd, "`points` is empty"));
}
// A stroke runs dab by dab along its length: an absurd coordinate would mean billions of dabs.
if pts.iter().any(|q| !(q.x.abs() <= crate::brush_cmds::MAX_COORD && q.y.abs() <= crate::brush_cmds::MAX_COORD)) {
return Err(bad(cmd, format!("point coordinates must be finite and within ±{}", crate::brush_cmds::MAX_COORD)));
}
crate::brush_cmds::check_coords(&pts, cmd)?;
let base = s.tools.brush.clone();
let pct = |k: &str, d: f32, lo: f32, hi: f32| num(p, k, d).clamp(lo, hi) / 100.0;
let brush = BrushSettings {
@@ -318,6 +315,7 @@ enum LivePaint {
pub struct LiveRetouch {
/// The active document with the stroke so far.
pub doc: std::sync::Arc<Document>,
cmd: String,
renderer: photocraft_paint::StrokeRenderer,
pre: std::sync::Arc<Document>,
pre_surf: Surface,
@@ -364,8 +362,21 @@ impl LiveRetouch {
LivePaint::History(src) if src.format() != pre_surf.format() => LivePaint::History(src.convert(pre_surf.format())),
other => other,
};
let mut live =
Self { doc: std::sync::Arc::new(doc), renderer, pre, pre_surf, id, params: p.clone(), paint, mode, opacity, sel, lock, tail: Rect::EMPTY };
let mut live = Self {
doc: std::sync::Arc::new(doc),
cmd: cmd.into(),
renderer,
pre,
pre_surf,
id,
params: p.clone(),
paint,
mode,
opacity,
sel,
lock,
tail: Rect::EMPTY,
};
live.push(&stroke.points)?;
Ok(live)
}
@@ -380,7 +391,9 @@ impl LiveRetouch {
/// the commit, and pixels painted earlier in the stroke are never re-cloned. What finishing
/// the stroke now would add is drawn too (a lone first dab shows on the press), and redrawn on
/// every step.
/// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
crate::brush_cmds::check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
let old = std::mem::replace(&mut self.tail, Rect::EMPTY);
let mut dmg = Rect::EMPTY;
@@ -867,6 +880,7 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
pub struct LiveDab {
/// The active document with the stroke so far.
pub doc: std::sync::Arc<Document>,
cmd: String,
renderer: photocraft_paint::StrokeRenderer,
done: usize,
effect: DabEffect,
@@ -899,6 +913,7 @@ impl LiveDab {
let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs();
let mut live = Self {
doc: std::sync::Arc::new(doc),
cmd: cmd.into(),
renderer,
done: 0,
effect,
@@ -922,7 +937,9 @@ impl LiveDab {
}
/// Render more points; returns the rectangle that changed.
/// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
crate::brush_cmds::check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
let ctx = self.renderer.ctx.clone();
let new: Vec<_> = self.renderer.dabs().get(self.done..).unwrap_or_default().to_vec();
+99
View File
@@ -1133,6 +1133,68 @@ fn live_clone_matches_the_commit() {
}
}
// Both preview implementations must reject an entire pointer batch before their renderer,
// coverage, tail or working surface changes. Compare a resumed stroke with a clean control.
macro_rules! live_coordinate_regression {
($name:ident, $live:ty, [$($cmd:literal),+]) => {
#[test]
fn $name() {
for depth in DEPTHS {
let mut s = session(32, 32, depth, "rgb");
paint_layer(&mut s, texture);
let st = s.active().unwrap();
let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.past_len());
let id = st.active_layer.unwrap();
for cmd in [$($cmd),+] {
let p = json!({"points": [[8, 16]], "source": [4, 8], "size": 4, "hardness": 100});
let mut live = <$live>::begin(&s, cmd, &p).unwrap();
let mut control = <$live>::begin(&s, cmd, &p).unwrap();
// The first regression case fails fast even without the guard, before any
// enormous coordinate reaches the path walker.
for (x, y) in [
(f64::NAN, 16.0),
(16.0, f64::NAN),
(f64::INFINITY, 16.0),
(16.0, f64::NEG_INFINITY),
(1e300, 16.0),
(16.0, -crate::brush_cmds::MAX_COORD - 1.0),
] {
let shown = live.doc.clone();
let bounds = live.bounds();
let batch = [StrokePoint::new(12.0, 18.0, 1.0), StrokePoint::new(x, y, 1.0)];
let err = live.push(&batch).unwrap_err();
assert!(matches!(err, EngineError::BadParams { cmd: ref actual, ref msg }
if actual == cmd && msg.contains("point coordinates must be finite")));
assert!(std::sync::Arc::ptr_eq(&shown, &live.doc), "{cmd}: invalid batch changed the preview");
assert_eq!(live.bounds(), bounds, "{cmd}");
}
let next = [StrokePoint::new(-4.0, 16.0, 1.0), StrokePoint::new(24.0, 16.0, 1.0)];
assert_eq!(live.push(&next).unwrap(), control.push(&next).unwrap(), "{cmd}");
assert_eq!(live.bounds(), control.bounds(), "{cmd}");
let got = live.doc.layer(id).unwrap().surface().unwrap();
let want = control.doc.layer(id).unwrap().surface().unwrap();
assert_eq!(got.read_region(live.bounds()), want.read_region(control.bounds()), "{cmd}");
assert_eq!(got.content_bounds(), want.content_bounds(), "{cmd}");
}
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&doc, &st.doc));
assert_eq!((st.revision, st.history.past_len()), (revision, history));
}
}
};
}
live_coordinate_regression!(
live_retouch_rejects_invalid_batches_without_changing_the_preview,
LiveRetouch,
["paint.cloneStamp", "paint.healingBrush", "paint.historyBrush"]
);
live_coordinate_regression!(
live_dab_rejects_invalid_batches_without_changing_the_preview,
LiveDab,
["paint.dodge", "paint.burn", "paint.sponge", "paint.blur", "paint.sharpen", "paint.smudge"]
);
/// The live Dodge shows what the commit paints, also where a stroke doubles back across the
/// cells that remember each pixel's original colour (the live stroke edits one dab at a time).
/// 32-bit, so the live working copy isn't quantised between dabs.
@@ -1164,3 +1226,40 @@ fn live_dodge_matches_the_commit_across_cells() {
assert!(changed);
assert!(worst <= 1e-4, "live and commit differ by {worst}");
}
#[test]
fn retouch_strokes_refuse_absurd_point_coordinates() {
// #976: a segment to (1e300, 0) has an infinite length and the dab walker would never stop, so
// every retouch tool's `points` must stay within ±1e6, as the painting tools' do.
let cmds = [
"paint.dodge",
"paint.burn",
"paint.sponge",
"paint.blur",
"paint.sharpen",
"paint.smudge",
"paint.cloneStamp",
"paint.healingBrush",
"paint.spotHealing",
"paint.historyBrush",
"paint.patternStamp",
];
// A single far point first: cheap even without the bound, so a regression fails fast.
let far = [json!([[1_000_001, 0]]), json!([[0, 0], [0, -2_000_000]]), json!([[0, 0], [1e300, 0]]), json!([[1e300, 1e300]])];
for depth in DEPTHS {
let mut s = session(32, 32, depth, "rgb");
paint_layer(&mut s, |x, y| [x as f32 / 32.0, y as f32 / 32.0, 0.25, 1.0]);
s.execute("cloneSource.set", json!({"source": [8, 8]})).unwrap();
let (before, past) = (rgba(&s, 16, 16), s.active().unwrap().history.past_len());
for cmd in cmds {
for points in &far {
let err = s.execute(cmd, json!({ "points": points })).unwrap_err();
assert!(err.to_string().contains("within ±"), "{cmd} {points} at {depth}: {err}");
}
}
assert_eq!((rgba(&s, 16, 16), s.active().unwrap().history.past_len()), (before, past), "{depth}: nothing changed");
// Control: a stroke on the canvas still retouches.
s.execute("paint.dodge", json!({"points": [[4, 16], [28, 16]], "size": 8})).unwrap();
assert_ne!(rgba(&s, 16, 16), before, "{depth}");
}
}
+2 -2
View File
@@ -125,8 +125,8 @@ impl Plugin {
let ctx = BandCtx { surface, extent, canvas, selection, fmt, ov, params: Value::Object(resolved) };
let run = |b: &Rect| {
let r = self.run_band(&ctx, *b, &deadline).map(|data| encode_band(surface, *b, &data));
if r.is_err() {
deadline.abort();
if let Err(error) = &r {
deadline.abort(error.clone());
}
r
};
+12 -10
View File
@@ -1,7 +1,6 @@
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use wasmi::{
Config, EnforcedLimits, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc, TypedResumableCall, WasmParams,
@@ -73,7 +72,7 @@ impl std::fmt::Debug for Plugin {
pub(crate) struct Deadline {
#[cfg(not(target_arch = "wasm32"))]
at: std::time::Instant,
abort: Arc<AtomicBool>,
abort: Arc<Mutex<Option<Error>>>,
}
impl Deadline {
@@ -83,20 +82,23 @@ impl Deadline {
Self {
#[cfg(not(target_arch = "wasm32"))]
at: std::time::Instant::now() + std::time::Duration::from_millis(limits.wall_time_ms),
abort: Arc::new(AtomicBool::new(false)),
abort: Arc::new(Mutex::new(None)),
}
}
pub(crate) fn abort(&self) {
self.abort.store(true, Ordering::Relaxed);
pub(crate) fn abort(&self, error: Error) {
// Publish the cause with the cancellation state so siblings cannot replace it with a
// generic cancellation error, even when results are collected in a different order.
self.abort.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert(error);
}
fn check(&self) -> Result<()> {
if self.abort.load(Ordering::Relaxed) {
return Err(Error::Failed("stopped because another band failed".into()));
if let Some(error) = self.abort.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() {
return Err(error);
}
#[cfg(not(target_arch = "wasm32"))]
if std::time::Instant::now() >= self.at {
self.abort();
return Err(Error::Limit("time budget".into()));
let error = Error::Limit("time budget".into());
self.abort(error.clone());
return Err(error);
}
Ok(())
}
+41
View File
@@ -227,6 +227,47 @@ fn budgets_stop_runaway_plugins() {
assert_eq!(e, Error::Limit("instruction budget".into()));
}
#[test]
fn parallel_bands_preserve_the_originating_error() {
let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap();
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 256, 256), &[0.0, 0.0, 0.0, 1.0]);
s.fill_rect(Rect::new(0, 256, 256, 512), &[1.0, 0.0, 0.0, 1.0]);
for (body, expected) in [
("(i32.const 7)", Error::Failed("pc_filter returned error code 7".into())),
("unreachable", Error::Trap("wasm `unreachable` instruction executed".into())),
] {
// The later band fails immediately while the earlier one is still running (or hasn't
// started). Collecting in band order must not turn that failure into sibling cancellation.
let filter = format!(
"(if (result i32) (f32.gt (f32.load (local.get $buf)) (f32.const 0.5)) \
(then {body}) (else (loop $spin (br $spin)) (i32.const 0)))"
);
let limits = Limits { band_bytes: 1, fuel_base: 100_000_000, fuel_per_sample: 0, ..Limits::default() };
let p = Plugin::load(&ok_module(&filter), limits).unwrap();
let before = s.clone();
let e = pool.install(|| p.apply(&s, Rect::new(0, 0, 256, 512), None, &json!({}))).unwrap_err();
assert_eq!(e, expected);
assert_eq!(s, before, "a failed run must not change the input");
}
}
#[test]
fn parallel_bands_preserve_instruction_budget() {
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
let p = Plugin::load(
&ok_module("(loop $spin (br $spin)) (i32.const 0)"),
Limits { band_bytes: 1, fuel_base: 1_000_000, fuel_per_sample: 0, ..Limits::default() },
)
.unwrap();
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 768, 512), &[0.25, 0.5, 0.75, 1.0]);
for _ in 0..8 {
let e = pool.install(|| p.apply(&s, Rect::new(0, 0, 768, 512), None, &json!({}))).unwrap_err();
assert_eq!(e, Error::Limit("instruction budget".into()));
}
}
#[test]
fn wall_clock_budget_stops_runaway_plugins() {
let spin = ok_module("(loop $l (br $l)) (i32.const 0)");
+8 -1
View File
@@ -182,7 +182,14 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
Some(id) if adjust_editors::needs_histogram(&kind) => Some(tone::histograms(app, HistSource::Layer(id), adjust_editors::space_of(&values))),
_ => None,
};
let cx = EditorCx { mem: dialog_mem(&kind), hist, gray, swatches: adjust_editors::swatches(app), dialog: true };
let cx = EditorCx {
mem: dialog_mem(&kind),
hist,
gray,
swatches: adjust_editors::swatches(app),
gradients: adjust_editors::gradient_presets(app, &kind),
dialog: true,
};
let e = adjust_editors::editor(ui, &kind, &mut values, &cx);
if e.changed
&& let Value::Object(v) = values
+36 -15
View File
@@ -14,6 +14,8 @@ use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}
use photocraft_doc::adjust::{HueRange, ToneSpace};
use photocraft_doc::{Adjustment, LayerId};
use photocraft_engine::adjust_params::{self, HUE_RANGES, PHOTO_FILTERS};
use photocraft_engine::presets::Group;
use photocraft_engine::presets::gradients::GradientPreset;
use serde_json::{Value, json};
use crate::PhotocraftApp;
@@ -79,6 +81,8 @@ pub struct EditorCx {
pub gray: bool,
/// Current foreground and background colours (Gradient Map preset).
pub swatches: [[f32; 3]; 2],
/// The session's gradient preset library (Gradient Map's picker; empty for other kinds).
pub gradients: Vec<Group<GradientPreset>>,
/// Hosted by an Image › Adjustments dialog (false: the Properties panel). Photoshop's dialog
/// sliders follow the mouse wheel; the panel's don't.
pub dialog: bool,
@@ -1109,22 +1113,34 @@ fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let t = Tokens::get(ui.ctx());
let mut e = Edit::default();
let mut stops = read_stops(v);
let presets: [(&str, Vec<Stop>); 5] = [
(tl!("Black, White"), vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]),
(tl!("Foreground to Background"), vec![(0.0, cx.swatches[0]), (1.0, cx.swatches[1])]),
(tl!("Violet, Orange"), vec![(0.0, [0.161, 0.039, 0.349]), (1.0, [1.0, 0.486, 0.0])]),
(tl!("Blue, Red, Yellow"), vec![(0.0, [0.039, 0.0, 0.698]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 0.988, 0.0])]),
(tl!("Copper"), vec![(0.0, [0.592, 0.275, 0.102]), (0.4, [0.984, 0.847, 0.773]), (0.7, [0.424, 0.180, 0.086]), (1.0, [0.937, 0.859, 0.804])]),
];
let mut preset = usize::MAX;
// Photoshop's gradient picker: the same library as the Gradient tool and Gradients panel
// (built-in groups and the user's own), Foreground/Background resolved to the current colours.
let [fg, bg] = cx.swatches.map(|c| [c[0], c[1], c[2], 1.0]);
ui.horizontal(|ui| {
label(ui, tl!("Preset:"));
let mut opts: Vec<(usize, &str)> = vec![(usize::MAX, tl!("Custom"))];
opts.extend(presets.iter().enumerate().map(|(i, p)| (i, p.0)));
if widgets::dropdown(ui, &format!("{:?}-gm-preset", cx.mem), &mut preset, &opts, 190.0)
&& let Some(p) = presets.get(preset)
{
stops = p.1.clone();
let mut picked = None;
egui::ComboBox::from_id_salt(cx.mem.with("gm-preset")).selected_text(tl!("Custom")).width(190.0).height(420.0).icon(widgets::chevron_icon).show_ui(
ui,
|ui| {
for g in &cx.gradients {
ui.label(RichText::new(&g.name).color(t.text_faint));
for p in &g.items {
ui.horizontal(|ui| {
// A map has no transparency: colour stops only, shown opaque.
let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect();
let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click());
crate::preset_panels::paint_gradient(ui, r, &rgba);
// Both, not short-circuited: the name is drawn either way.
if swatch.clicked() | ui.selectable_label(false, &p.name).clicked() {
picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::<Vec<Stop>>());
}
});
}
}
},
);
if let Some(p) = picked {
stops = p;
write_stops(v, &stops);
e.add(Edit::discrete(true));
}
@@ -1202,6 +1218,11 @@ pub fn is_gray(mode: photocraft_doc::ColorMode) -> bool {
matches!(mode, photocraft_doc::ColorMode::Grayscale | photocraft_doc::ColorMode::Duotone | photocraft_doc::ColorMode::Bitmap)
}
/// The gradient preset library for a `kind` editor's picker (Gradient Map only; empty otherwise).
pub fn gradient_presets(app: &PhotocraftApp, kind: &str) -> Vec<Group<GradientPreset>> {
if kind == "gradientMap" { app.session.presets.gradients.clone() } else { Vec::new() }
}
pub fn swatches(app: &PhotocraftApp) -> [[f32; 3]; 2] {
let c = |x: [f32; 4]| [x[0], x[1], x[2]];
[c(app.session.tools.foreground), c(app.session.tools.background)]
@@ -1313,7 +1334,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
};
let gray = app.session.active().is_some_and(|s| is_gray(s.doc.mode));
let hist = needs_histogram(kind).then(|| tone::histograms(app, HistSource::BelowLayer(id), space_of(&values)));
let cx = EditorCx { mem: layer_mem(id), hist, gray, swatches: swatches(app), dialog: false };
let cx = EditorCx { mem: layer_mem(id), hist, gray, swatches: swatches(app), gradients: gradient_presets(app, kind), dialog: false };
let e = editor(ui, kind, &mut values, &cx);
if e.changed {
app.live_adjust = Some((id, values.clone()));
@@ -396,3 +396,39 @@ fn color_balance_properties_history_and_reset_like_photoshop() {
assert_eq!(cb(&h), ([0.0; 3], [0.0; 3], [0.0; 3], false), "third Reset: still the defaults");
assert_eq!(steps(&h), before, "the edit and the Resets share one history step");
}
fn map_stops(a: &Adjustment) -> Vec<(f32, [u8; 3])> {
let q = |v: f32| (v * 255.0).round() as u8;
match a {
Adjustment::GradientMap { stops, .. } => stops.iter().map(|(t, c)| (*t, [q(c[0]), q(c[1]), q(c[2])])).collect(),
other => panic!("{other:?}"),
}
}
/// Issue #1588: the Gradient Map preset picker offers the session's gradient library (built-in
/// groups beyond Basics and the user's own saved gradients), and picking one writes its stops as
/// one history step.
#[test]
fn gradient_map_picker_offers_the_gradient_library() {
use photocraft_engine::presets::{Group, gradients};
let mut h = app_harness("gradientMap", "rgb", 8);
// A short library so every row fits the popup: Basics, Blues and a user-saved group.
let mut lib: Vec<_> = gradients::builtin().into_iter().take(2).collect();
lib.push(Group::new("Mine", vec![gradients::GradientPreset::new("My Teal", &["#008080", "#ffee00"])]));
h.state_mut().session.presets.gradients = lib;
h.run_steps(2);
let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();
for (name, want) in
[("Blue 03", vec![(0.0, [0x00, 0xb4, 0xd8]), (1.0, [0x03, 0x04, 0x5e])]), ("My Teal", vec![(0.0, [0x00, 0x80, 0x80]), (1.0, [0xff, 0xee, 0x00])])]
{
let before = steps(&h);
// The picker sits right of its "Preset:" label.
let preset = label_rect(&h, "Preset:").expect("the preset picker");
click(&mut h, Pos2::new(preset.right() + 60.0, preset.center().y));
let item = h.query_by_label(name).unwrap_or_else(|| panic!("`{name}` in the picker")).rect();
click(&mut h, item.center());
h.run_steps(4);
assert_eq!(map_stops(&layer(&h).1), want, "{name}");
assert_eq!(steps(&h), before + 1, "{name}: one history step");
}
}
+57 -2
View File
@@ -1104,6 +1104,10 @@ fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx:
/// Live preview for an open filter dialog: run the filter on the proxy and upload it.
fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64, [u32; 2])> {
// Command dialogs always edit the active document. Never show their preview in another tab.
if app.session.active_index() != Some(idx) {
return None;
}
if crate::adjust_preview::on_layer(app, idx) {
return None;
}
@@ -1129,7 +1133,10 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u6
let buf = photocraft_compose::flatten(r);
let t1 = crate::gpu_canvas::now_ms();
let (display, _) = canvas_display(app, &doc, None);
app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth);
// Headless/CPU tests can still inspect the computed preview without a GPU texture.
if let Some(gpu) = app.gpu.as_ref() {
gpu.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth);
}
app.perf.record("filter-preview", r.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1);
}
app.filter_preview = Some(crate::filter_dialog::FilterPreview { doc: doc_id, revision, hash, k, result });
@@ -2171,7 +2178,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if !fresh {
let t0 = crate::gpu_canvas::now_ms();
let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis);
let segs = crate::outline::outline_scaled(sel, b, step);
// Filters can occupy every worker in Rayon's global pool. A parallel scan here would
// block the UI thread waiting for those workers, preventing job cancellation (#1554).
let segs = if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) };
app.perf.span("outline", crate::gpu_canvas::now_ms() - t0);
app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs)));
}
@@ -4579,3 +4588,49 @@ mod transform_controls_tests {
assert!(!transform_controls_hit(r, pos2(60.0, 4.0)));
}
}
#[cfg(test)]
mod rotation_preview_isolation_tests {
use super::*;
use serde_json::json;
/// A CPU-only app must be able to generate the actual rotation preview without a
/// GPU adapter; checking the result also verifies Preview off and document integrity.
#[test]
fn rotation_preview_is_computed_headlessly_without_mutating_document() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 96, "height": 48})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
assert!(app.gpu.is_none());
crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap();
let dialog = app.ui.dialogs.last_mut().unwrap();
dialog.fields.insert("angle".into(), json!(90.0));
dialog.fields.insert("direction".into(), json!("cw"));
let (factor, _, size) = ensure_filter_preview(&mut app, 0).expect("CPU preview computed");
assert_eq!(factor, 1);
assert_eq!(size, [48, 96]);
let original = &app.session.active().unwrap().doc;
assert_eq!([original.size.width, original.size.height], [96, 48]);
app.ui.dialogs.last_mut().unwrap().fields.insert("__preview".into(), json!(false));
assert!(ensure_filter_preview(&mut app, 0).is_none(), "disabling Preview must hide the preview");
assert_eq!([app.session.active().unwrap().doc.size.width, app.session.active().unwrap().doc.size.height], [96, 48]);
}
/// A dialog operates on the active document and cannot render a preview into a
/// background tab, even if that tab has a valid canvas index.
#[test]
fn filter_preview_is_not_returned_for_inactive_document() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 96, "height": 48})).unwrap();
let mut app = PhotocraftApp::new(session, crate::Services::default());
crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap();
app.ui.dialogs.last_mut().unwrap().fields.insert("angle".into(), json!(90.0));
assert!(ensure_filter_preview(&mut app, 0).is_some());
app.session.execute("file.new", json!({"width": 40, "height": 20})).unwrap();
assert_eq!(app.session.active_index(), Some(1));
assert!(ensure_filter_preview(&mut app, 0).is_none(), "an inactive tab must never inherit the command preview");
}
}
+4 -3
View File
@@ -291,10 +291,11 @@ fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) {
}
/// Paths with their anchors (selected ones filled), the shown handles, the drag's preview in
/// place of its path, and the marquee.
pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) {
/// place of its path, and the marquee. `paths` false (View › Show › Target Path off) leaves only
/// the marquee.
pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32, paths: bool) {
let ds = &app.ui.direct_selection;
for (r, path) in candidates(app) {
for (r, path) in if paths { candidates(app) } else { Vec::new() } {
let path = match &ds.drag {
Some(Drag::Edit { target, preview: Some(p), .. }) if *target == r => p.clone(),
_ => path,
+30 -5
View File
@@ -562,15 +562,22 @@ pub fn paint_thumbnail(ui: &egui::Ui, layer: LayerId, f: &Fill, rect: Rect) -> b
true
}
/// Options-bar swatch of the current gradient. Both modes paint the selected preset (classic
/// drags no longer replace it with opaque foreground/background colours), so both show it.
pub fn preset_swatch(app: &PhotocraftApp, ui: &mut egui::Ui) {
/// Options-bar swatch of the current gradient. Both live and classic modes use the same
/// engine-owned preset, so its popup reuses the Gradients browser instead of keeping an
/// independent copy of the chosen gradient in the UI (#1651).
pub fn preset_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let stops = app.session.presets.gradient.resolve(app.session.tools.foreground, app.session.tools.background);
let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::hover());
let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::click());
paint_ramp(ui.painter(), r, |u| photocraft_algo::paint::sample_stops(&stops, u));
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
let _ = resp.on_hover_text(tl!("The current gradient (pick one in Window › Gradients)"));
let resp = resp.on_hover_text(tl!("The current gradient (pick one in Window › Gradients)"));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Gradients")));
egui::Popup::menu(&resp).show(|ui| {
ui.set_min_width(260.0);
ui.set_max_width(330.0);
crate::preset_panels::gradients_panel(app, ui);
});
}
/// Live mode: style, reverse, dither and blend mode changes in the options bar also edit the selected
@@ -898,6 +905,24 @@ mod tests {
assert!(thumbnail_image(&Fill::Solid(Color::WHITE)).is_none());
}
#[test]
fn options_bar_swatch_opens_the_real_preset_browser_and_selects_presets() {
use egui_kittest::{Harness, kittest::Queryable};
let app = app_with_gradient("linear");
let mut h = Harness::builder().with_size(vec2(440.0, 560.0)).build_ui_state(|ui, app: &mut PhotocraftApp| preset_swatch(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro);
h.run_steps(2);
let original = h.state().session.presets.gradient.name.clone();
h.get_by_label("Gradients").click();
h.run_steps(2);
// The popup uses the existing presets UI, not a detached swatch or an editor-only copy.
h.get_by_label("Foreground to Transparent").click();
h.run_steps(2);
assert_eq!(h.state().session.presets.gradient.name, "Foreground to Transparent");
assert_ne!(h.state().session.presets.gradient.name, original);
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 1, "choosing a tool preset does not edit document layers");
}
#[test]
fn live_drag_creates_a_fill_layer_and_handles_edit_it() {
let mut app = app_with_gradient("linear");
+30 -30
View File
@@ -372,10 +372,10 @@
Add Layer Below to Selection Ebene darunter zur Auswahl hinzufügen
Stamp Down Nach unten stempeln
Flatten Image Bild auf eine Ebene reduzieren
Matting Mattierung
Matting Randbereinigung
Color Decontaminate… Farbreinigung…
Remove Black Matte Schwarze Mattierung entfernen
Remove White Matte Weiße Mattierung entfernen
Remove Black Matte Schwarzen Farbsaum entfernen
Remove White Matte Weißen Farbsaum entfernen
Defringe… Randstörungen entfernen…
Group Layers Ebenen gruppieren
Ungroup Layers Ebenengruppe auflösen
@@ -436,7 +436,7 @@
Contextual Alternates Kontextuelle Alternativen
Discretionary Ligatures Optionale Ligaturen
Swash Swash
Oldstyle Mediäval
Oldstyle Mediävalziffern
Stylistic Alternates Stilistische Alternativen
Titling Alternates Titel-Alternativen
Ornaments Ornamente
@@ -649,8 +649,8 @@
4-up 4-fach
6-up 6-fach
Consolidate All to Tabs Alle in Registerkarten zusammenfassen
Float in Window Im Fenster schweben
Float All in Windows Alle in Fenstern schweben
Float in Window In Fenster schweben lassen
Float All in Windows Alle in Fenstern schweben lassen
New Window for Document Neues Fenster für Dokument
Workspace Arbeitsbereich
Essentials Essentials
@@ -712,13 +712,13 @@
Other… Weitere…
Remove Warp Split Verkrümmungsteilung entfernen
Shape Form
Split Warp Crosswise Verkrümmung quer teilen
Split Warp Crosswise Verkrümmung kreuzweise teilen
Split Warp Horizontally Verkrümmung horizontal teilen
Split Warp Vertically Verkrümmung vertikal teilen
Statistics… Statistiken…
@plural {n} item|{n} items {n} Element|{n} Elemente
Auto Automatisch
(print to the printer) (auf den Drucker drucken)
(print to the printer) (an den Drucker senden)
+ Add variable + Variable hinzufügen
30 frames @ 30 fps 30 Frames @ 30 fps
3D LUT File 3D-LUT-Datei
@@ -729,7 +729,7 @@
Adaptive Wide Angle isn't open Adaptiver Weitwinkel ist nicht geöffnet
Add Hinzufügen
Add Layer Mask Ebenenmaske hinzufügen
Add Stop Stopp hinzufügen
Add Stop Farbstopp hinzufügen
Add a layer style Ebenenstil hinzufügen
Add a mask (from the selection; {key} inverts) Maske hinzufügen (aus der Auswahl; {key} kehrt um)
Add an adjustment Anpassung hinzufügen
@@ -791,10 +791,10 @@
Bilinear Bilinear
Black Schwarz
Black & White Schwarzweiß
Black Point Compensation Tiefpunktkompensation
Black Point Compensation Tiefenkompensierung
Black, White Schwarz, Weiß
Blacks Schwarz
Blending Fusionieren
Blending Überblenden
Blending Options Fusionsoptionen
Blue Blau
Blue, Red, Yellow Blau, Rot, Gelb
@@ -821,7 +821,7 @@
Canvas extension color: Farbe der Zeichenflächenerweiterung:
Capture Erfassen
Capture the visibility, position and style of every layer with + below, then switch between versions. Erfasse Sichtbarkeit, Position und Stil jeder Ebene mit + unten, und wechsle dann zwischen Versionen.
Catch-up on Stroke End Auf Strichende aufholen
Catch-up on Stroke End Am Strichende nachführen
Center Mitte
Center Crop Marks Mittige Beschnittmarken
Center text Text zentrieren
@@ -846,11 +846,11 @@
Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Klicken vergrößert · {key}-Klick verkleinert · nach rechts/links ziehen zoomt rein/raus
Click with the Note tool to add a note. Klicke mit dem Notiz-Werkzeug, um eine Notiz hinzuzufügen.
Click: corner · Drag: smooth · Click first point: close · {key} finish · Esc cancel Klick: Ecke · Ziehen: weich · Ersten Punkt klicken: schließen · {key} fertig · Esc abbrechen
Clip to layer below Auf die Ebene darunter beschneiden
Clip to layer below Auf darunterliegende Ebene begrenzen
Clipped Beschnitten
Close Style Options Stiloptionen schließen
Cmd Cmd
Coated CMYK Gestrichenes CMYK
Coated CMYK CMYK für gestrichenes Papier
Color & Swatches Farbe & Farbfelder
Color Balance Farbbalance
Color Detail Farbdetails
@@ -1091,7 +1091,7 @@
Invert All Alle invertieren
Invert has no settings. Invertieren hat keine Einstellungen.
Italic Kursiv
Join us on Discord Tritt uns auf Discord bei
Join us on Discord Tritt unserem Discord bei
Justify all Alles im Blocksatz
Justify last centered Letzte Zeile zentriert
Justify last left Letzte Zeile links
@@ -1147,7 +1147,7 @@
Mask Options Maskenoptionen
Masking Maskieren
Master Gesamt
Matte Mattierung
Matte Hintergrundfarbe
Median: Median:
Menus Menüs
Mesh Size Gitternetzgröße
@@ -1223,7 +1223,7 @@
Pattern Size Mustergröße
Pause Pause
Percent Prozent
Perceptual Wahrnehmung
Perceptual Perzeptiv
Perspective Warp is not active Perspektivische Verkrümmung ist nicht aktiv
Perspective Warp: draw planes along the image's perspective, then switch to Warp Perspektivische Verkrümmung: zeichne Flächen entlang der Bildperspektive, wechsle dann zu Verkrümmen
Photo Filter Foto-Filter
@@ -1251,7 +1251,7 @@
Pressure Druck
Pressure for Opacity Druck für Deckkraft
Pressure for Size Druck für Größe
Prevent auto-nesting in and out of Artboards and Frames Automatisches Einbetten in und aus Zeichenbereichen und Rahmen verhindern
Prevent auto-nesting in and out of Artboards and Frames Automatisches Verschieben in oder aus Zeichenbereichen und Rahmen verhindern
Preview Vorschau
Previous frame Vorheriger Frame
Previous note Vorherige Notiz
@@ -1264,7 +1264,7 @@
Promote Hochstufen
Protect Detail Details schützen
Protect Foreground Color Vordergrundfarbe schützen
Protect Tones Farbtöne schützen
Protect Tones Tonwerte schützen
Proximity Match Umgebungsabgleich
Pulled String Mode Fadenmodus
Puppet Warp is not active Marionetten-Verkrümmung ist nicht aktiv
@@ -1279,7 +1279,7 @@
Rate Rate
Recently Used Zuletzt verwendet
Reconstruct Rekonstruieren
Record ● a sequence of edits, then play ▶ it on any document. Zeichne ● eine Folge von Bearbeitungen auf und gebe sie ▶ auf jedem Dokument wieder.
Record ● a sequence of edits, then play ▶ it on any document. Zeichne ● eine Folge von Bearbeitungen auf und gib sie ▶ auf jedem Dokument wieder.
Red Rot
Redefine style by current selection Stil anhand der aktuellen Auswahl neu definieren
Reflected Gradient Reflektierter Verlauf
@@ -1291,7 +1291,7 @@
Remove All Pins Alle Pins entfernen
Remove Background Hintergrund entfernen
Remove Planes Flächen entfernen
Remove stop Stopp entfernen
Remove stop Farbstopp entfernen
Remove variable Variable entfernen
Rename Umbenennen
Rename Group… Gruppe umbenennen…
@@ -1389,7 +1389,7 @@
Strength: Stärke:
Strikethrough Durchgestrichen
Stroke Kontur
Stroke Catch-up Strich-Aufholen
Stroke Catch-up Strich nachführen
Stroke: Kontur:
Style Stil
Style Options Stiloptionen
@@ -1695,7 +1695,7 @@
Do you want to save the changes you made to “{name}” before closing? Möchtest du die an „{name}“ vorgenommenen Änderungen vor dem Schließen speichern?
Doc: {flat}/{layered} Dok: {flat}/{layered}
Scratch: {size} Auslagerung: {size}
Untagged {mode} Nicht getaggtes {mode}-Profil
Untagged {mode} {mode} ohne Farbprofil
Invalid {mode} profile Ungültiges {mode}-Profil
Unnamed {mode} profile Unbenanntes {mode}-Profil
{w} px x {h} px ({ppi} ppi) {w} px x {h} px ({ppi} ppi)
@@ -1836,7 +1836,7 @@
Same folder Gleicher Ordner
Save in background Im Hintergrund speichern
Scratch Disks Auslagerungsfestplatten
Screen Bildschirm
Screen Negativ multiplizieren
Screen resolution Bildschirmauflösung
Scrubby slider acceleration Ziehregler-Beschleunigung
Sessions only Nur Sitzungen
@@ -1901,7 +1901,7 @@
Adjustment Preview Anpassungsvorschau
Airbrush: keeps depositing paint while the pointer rests. Airbrush: legt weiter Farbe ab, solange der Zeiger ruht.
Angle: Winkel:
Blend If Fusionieren wenn
Blend If Farbbereich
Close Tab Group Registerkartengruppe schließen
Collapse Einklappen
Collapse All Groups Alle Gruppen einklappen
@@ -2224,7 +2224,7 @@
Show/Hide All Panels Alle Bedienfelder ein-/ausblenden
Show/Hide Panels Bedienfelder ein-/ausblenden
Could not open Öffnen nicht möglich
{path}: the path is not valid Unicode; rename the file and open it again. {path}: Der Pfad ist kein gültiges Unicode; benennen Sie die Datei um und öffnen Sie sie erneut.
{path}: the path is not valid Unicode; rename the file and open it again. {path}: Der Dateipfad enthält ungültige Zeichen. Benenne die Datei um und öffne sie erneut.
# Fill dialog, layer style contours and Image Size
Contents: Inhalt:
@@ -2243,7 +2243,7 @@
Red Eye Rote Augen
Pupil Size Pupillengröße
Darken Amount Abdunklungsgrad
Click a red pupil to neutralize it Klicken Sie auf eine rote Pupille
Click a red pupil to neutralize it Klick auf die Pupille, um die Rotfärbung zu entfernen.
open source Open Source
…and {n} more …und {n} weitere
@@ -2276,7 +2276,7 @@ fontWeight Medium Medium
fontWeight SemiBold Halbfett
fontWeight Bold Fett
fontWeight ExtraBold Extrafett
fontWeight Black Schwarz
fontWeight Black Sehr fett (Black)
fontWeight Italic Kursiv
# Pattern Stamp tool
@@ -2284,6 +2284,6 @@ fontWeight Italic Kursiv
Pattern Stamp Musterstempel
Impressionist Impressionistisch
Rotate View Ansicht drehen
Rotate View Tool Ansicht drehen-Werkzeug
Rotate View Tool Ansicht-drehen-Werkzeug
Reset View Ansicht zurücksetzen
Drag around the centre to rotate the view · Shift constrains to 15° Ziehen Sie um die Mitte, um die Ansicht zu drehen · Umschalt rastet auf 15° ein
Drag around the centre to rotate the view · Shift constrains to 15° Ansicht drehen: im Bogen ziehen · Umschalt: 15°-Schritte
Can't render this file because it contains an unexpected character in line 6 and column 47.
+18
View File
@@ -500,3 +500,21 @@ fn eyedropper_and_alt_sampling_show_a_pipette() {
h.state_mut().ui.tool = crate::state::Tool::Eyedropper;
assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, windows));
}
/// Esc while drawing with the Pen ends the path where it is, left open, and keeps it as the work
/// path, as ↩ does; it used to throw the path away (#1769).
#[test]
fn esc_ends_a_pen_path_and_keeps_it() {
let mut h = harness();
h.state_mut().ui.tool = crate::state::Tool::Pen;
h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], ..Default::default() });
h.key_press(Key::Escape);
h.run_steps(2);
assert!(h.state().ui.pen.is_none(), "the Pen leaves drawing state");
let doc = &h.state().session.active().unwrap().doc;
let path = doc.work_path.as_ref().expect("the path is kept as the work path");
assert_eq!(path.subpaths.len(), 1);
assert!(!path.subpaths[0].closed, "left open");
assert_eq!(path.subpaths[0].knots.len(), 3);
assert_eq!(h.state().ui.selected_path.as_deref(), Some("work"));
}
+47
View File
@@ -152,6 +152,53 @@ fn a_configured_but_disabled_effect_stays_discoverable_in_the_panel() {
assert!(effect_row.is_positive(), "a configured disabled effect remains visible for discovery");
}
/// #1622: the eyes on the effects rows work. The "Effects" eye hides and shows the whole list, an
/// effect's eye only that effect; each click is one history step, keeps the effect's settings and
/// never opens the Layer Style dialog.
#[test]
fn the_eyes_on_the_effects_rows_hide_and_show_effects() {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
let id = s.execute("layer.new.layer", json!({"name": "Styled"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.layerStyle.dropShadow", json!({"layer": id})).unwrap();
s.execute("layer.layerStyle.colorOverlay", json!({"layer": id})).unwrap();
let mut h = harness(s, 1.0, "promedium", 290.0);
// (the whole list is on, each effect is on).
let fx = |h: &Harness<'_, PhotocraftApp>| {
let fx = &h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects;
(fx.enabled, fx.items.iter().map(Effect::enabled).collect::<Vec<_>>())
};
let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();
let eye = |h: &Harness<'_, PhotocraftApp>, row: &str| {
let r = h.get_by_label(row).rect();
pos2(r.left() + 15.0, r.center().y)
};
let (settings, n) = (h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects.items.clone(), steps(&h));
assert_eq!(fx(&h), (true, vec![true, true]));
let p = eye(&h, "Color Overlay");
click(&mut h, p);
assert_eq!(fx(&h), (true, vec![true, false]), "only the clicked effect is hidden");
assert_eq!(steps(&h), n + 1, "one history step");
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Hide Color Overlay"));
// The row stays (its eye box empty), and a click there shows the effect again.
let p = eye(&h, "Color Overlay");
click(&mut h, p);
assert_eq!(fx(&h), (true, vec![true, true]));
let p = eye(&h, "Effects");
click(&mut h, p);
assert_eq!(fx(&h), (false, vec![true, true]), "the Effects eye hides the list; each effect keeps its own eye");
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Hide Layer Effects"));
let p = eye(&h, "Effects");
click(&mut h, p);
assert_eq!(fx(&h), (true, vec![true, true]));
assert_eq!(h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().effects.items, settings, "settings survive");
assert_eq!(steps(&h), n + 4);
assert!(h.state().ui.dialogs.is_empty(), "an eye click never opens the Layer Style dialog");
}
fn groups_open(s: &photocraft_engine::Session) -> Vec<bool> {
s.active().unwrap().doc.walk().into_iter().filter_map(|(_, _, l)| if let LayerContent::Group(g) = &l.content { Some(g.expanded) } else { None }).collect()
}
+44
View File
@@ -935,6 +935,50 @@ mod tests {
assert!(open(&mut app, &ctx).is_ok());
}
/// Follow-up to #1494 / #1484: Alt is captured at stroke-down and stays recorded
/// through undo, redo and deterministic Liquify field reconstruction.
#[test]
fn alt_reversed_twirl_survives_replay_undo_and_redo() {
let ctx = egui::Context::default();
let mut app = app_with_layer();
open(&mut app, &ctx).unwrap();
control(&mut app, &json!({"tool": "twirlCw", "size": 36, "rate": 80})).unwrap();
// Releasing Alt while dragging must not change the tool recorded at pointer-down.
pointer(&mut app, ToolEvent::Down { x: 53.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::ALT);
pointer(&mut app, ToolEvent::Move { x: 58.0, y: 41.0, pressure: 1.0 }, egui::Modifiers::NONE);
pointer(&mut app, ToolEvent::Up { x: 58.0, y: 41.0 }, egui::Modifiers::NONE);
let d = app.distort.liquify.as_ref().unwrap();
assert_eq!(d.opts.tool, LiquifyTool::TwirlCw, "Alt must not change the selected tool");
assert_eq!(d.strokes.len(), 1);
assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw);
assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field);
// A following stroke without Alt records the original tool.
pointer(&mut app, ToolEvent::Down { x: 70.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE);
pointer(&mut app, ToolEvent::Move { x: 75.0, y: 42.0, pressure: 1.0 }, egui::Modifiers::ALT);
pointer(&mut app, ToolEvent::Up { x: 75.0, y: 42.0 }, egui::Modifiers::ALT);
let d = app.distort.liquify.as_ref().unwrap();
assert_eq!(d.strokes.len(), 2);
assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw);
assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field);
control(&mut app, &json!({"undo": true})).unwrap();
let d = app.distort.liquify.as_ref().unwrap();
assert_eq!(d.strokes.len(), 1);
assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw);
assert_eq!(d.redo[0].tool, LiquifyTool::TwirlCw);
assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field);
control(&mut app, &json!({"redo": true})).unwrap();
let d = app.distort.liquify.as_ref().unwrap();
assert_eq!(d.strokes.len(), 2);
assert!(d.redo.is_empty());
assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw);
assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw);
assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field);
}
#[test]
fn dialog_strokes_match_the_engine_and_commit_once() {
let ctx = egui::Context::default();
+32 -2
View File
@@ -17,6 +17,16 @@ pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {
/// Like [`outline`], sampling one pixel per `step`×`step` block (segments stay in document space).
pub fn outline_scaled(mask: &Surface, bounds: Rect, step: u32) -> Vec<Segment> {
outline_scaled_impl(mask, bounds, step, true)
}
/// Trace without waiting for Rayon's shared worker pool. The UI uses this while background jobs
/// are active, because a long-running filter can occupy all the workers (#1554).
pub fn outline_scaled_serial(mask: &Surface, bounds: Rect, step: u32) -> Vec<Segment> {
outline_scaled_impl(mask, bounds, step, false)
}
fn outline_scaled_impl(mask: &Surface, bounds: Rect, step: u32, parallel: bool) -> Vec<Segment> {
if bounds.is_empty() {
return Vec::new();
}
@@ -42,12 +52,17 @@ pub fn outline_scaled(mask: &Surface, bounds: Rect, step: u32) -> Vec<Segment> {
}
};
#[cfg(not(target_arch = "wasm32"))]
{
if parallel {
use rayon::prelude::*;
grid.par_chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));
} else {
grid.chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));
}
#[cfg(target_arch = "wasm32")]
grid.chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));
{
let _ = parallel;
grid.chunks_mut(w).enumerate().for_each(|(gy, row)| sample_row(gy, row));
}
let inside = |x: usize, y: usize| grid[y * w + x];
// Grid → document coordinates, clamped so coarse cells never draw outside the selection bounds.
let r = Rect::new(gx0 * step, gy0 * step, gx1 * step, gy1 * step);
@@ -131,6 +146,21 @@ mod tests {
}
}
#[test]
fn serial_outline_matches_parallel_for_scales_and_clipped_bounds() {
let mut mask = Surface::new(PixelFormat::GRAY8);
mask.fill_rect(Rect::new(3, 5, 110, 90), &[1.0]);
mask.fill_rect(Rect::new(17, 21, 45, 65), &[0.0]);
mask.fill_rect(Rect::new(73, 9, 88, 42), &[0.0]);
for step in [1, 2, 4, 8, 16] {
for bounds in [mask.content_bounds(), Rect::new(13, 19, 91, 77), Rect::new(200, 200, 240, 240)] {
let parallel = outline_scaled(&mask, bounds, step);
let serial = outline_scaled_serial(&mask, bounds, step);
assert_eq!(serial, parallel, "outline differs at step {step}, bounds {bounds:?}");
}
}
}
#[test]
fn empty_mask_has_no_outline() {
let m = Surface::new(PixelFormat::GRAY8);
+85 -6
View File
@@ -1560,7 +1560,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::layer_reveal::scroll_to_row(ui, top);
}
if !l.effects.items.is_empty() && fx_collapsed.iter().all(|id| *id != l.id) {
effect_rows(app, ui, l, depth);
effect_rows(app, ui, l, depth, &mut actions);
}
crate::smart_ui::filter_rows(app, ui, l, depth, &mut actions);
}
@@ -1606,8 +1606,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
actions.push(("layer.new.group".into(), json!({})));
}
actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers"));
let adj = icons::button(ui, "contrast", 26.0, false, tl!("Create new fill or adjustment layer"));
egui::Popup::menu(&adj).show(|ui| {
let adj = footer_menu_button(ui, "contrast", 26.0, tl!("Create new fill or adjustment layer"));
egui::Popup::menu(&adj).open_memory(footer_menu_right_click(&adj)).show(|ui| {
ui.set_min_width(190.0);
for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("layer.newAdjustmentLayer.")) {
if ui.button(tl!(c.label).trim_end_matches('…')).clicked() {
@@ -1638,7 +1638,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
actions.push((crate::layer_menu_ui::add_mask_command(doc.selection.is_some(), alt).into(), json!({})));
}
let fx = fx_button(ui, 26.0, tl!("Add a layer style"));
egui::Popup::menu(&fx).show(|ui| {
egui::Popup::menu(&fx).open_memory(footer_menu_right_click(&fx)).show(|ui| {
ui.set_min_width(180.0);
if ui.button(tl!("Blending Options…")).clicked() {
crate::layer_style::open(app, None);
@@ -1711,6 +1711,31 @@ fn footer_label(command: &str) -> &'static str {
}
}
/// A secondary click opens a Layers footer popup, as in Photoshop; a primary click still toggles
/// it (the `Popup::menu` default this replaces).
fn footer_menu_right_click(response: &egui::Response) -> Option<egui::SetOpenCommand> {
if response.secondary_clicked() {
Some(egui::SetOpenCommand::Bool(true))
} else if response.clicked() {
Some(egui::SetOpenCommand::Toggle)
} else {
None
}
}
/// The small down-arrow makes it clear that the footer icon expands into a menu.
fn footer_menu_arrow(ui: &egui::Ui, rect: Rect) {
let t = Tokens::get(ui.ctx());
let arrow = Rect::from_min_size(rect.right_bottom() - vec2(11.0, 10.0), vec2(9.0, 9.0));
icons::paint(ui, arrow, "chevron-down", 8.0, t.text_dim);
}
fn footer_menu_button(ui: &mut egui::Ui, icon: &str, size: f32, tip: &str) -> egui::Response {
let response = icons::button(ui, icon, size, false, tip);
footer_menu_arrow(ui, response.rect);
response
}
/// Photoshop's italic "fx" footer button (no icon-font equivalent).
fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response {
let t = Tokens::get(ui.ctx());
@@ -1722,6 +1747,7 @@ fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response {
job.append("fx", 0.0, egui::TextFormat { font_id: egui::FontId::proportional(15.0), color: t.icon, italics: true, ..Default::default() });
let g = ui.painter().layout_job(job);
ui.painter().galley(r.center() - g.size() / 2.0, g, t.icon);
footer_menu_arrow(ui, r);
resp.on_hover_text(tip)
}
@@ -2746,8 +2772,9 @@ fn layer_drag_and_drop(
}
}
/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect).
fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize) {
/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye
/// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622).
fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) {
let t = Tokens::get(ui.ctx());
let indent = 30.0 + depth as f32 * 14.0 + 34.0;
let mut rows: Vec<(String, bool, Option<&'static str>)> = vec![("Effects".into(), l.effects.enabled, None)];
@@ -2767,9 +2794,19 @@ fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usi
ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator));
}
let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 9.0), vec2(18.0, 18.0));
// A hidden effect's eye box is left empty (still clickable), like a hidden layer's.
if on {
icons::paint(ui, eye, "eye", 12.0, t.icon);
}
// The whole eye column of the row takes the click, so it never opens the Layer Style dialog.
let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom()));
if ui.interact(eye_cell, ui.id().with(("fx-eye", l.id.0, i)), Sense::click()).clicked() {
let mut params = json!({"layer": l.id.0, "visible": !on});
if let (Some(index), Some(o)) = (i.checked_sub(1), params.as_object_mut()) {
o.insert("index".into(), json!(index));
}
actions.push(("layer.setEffectsVisible".into(), params));
}
let x = rect.left() + indent + if i == 0 { 0.0 } else { 16.0 };
if i == 0 {
icons::paint(ui, Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 14.0)), "sparkles", 11.0, t.text_dim);
@@ -3433,6 +3470,48 @@ mod layer_drag_edge_scroll_tests {
}
}
#[cfg(test)]
mod footer_menu_tests {
use super::*;
// Exercise the actual egui pointer path, not just a mocked click flag.
#[test]
fn right_click_opens_footer_menu_and_primary_click_still_works() {
let ctx = egui::Context::default();
let rect = Rect::from_min_size(Pos2::ZERO, vec2(300.0, 100.0));
let pos = pos2(35.0, 20.0);
let frame = |events: Vec<egui::Event>| {
let mut opened = false;
let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }, |ui| {
let response = ui.add_sized([100.0, 28.0], egui::Button::new("Footer menu"));
egui::Popup::menu(&response).open_memory(footer_menu_right_click(&response)).show(|ui| {
opened = true;
ui.label("Menu entry");
});
});
output.textures_delta.clear();
opened
};
frame(Vec::new());
frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE },
]);
assert!(
frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: egui::Modifiers::NONE }]),
"secondary release opens the popup"
);
// A primary click also remains supported by egui::Popup::menu.
frame(vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]);
frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }]);
assert!(
frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }]),
"primary release still opens the popup"
);
}
}
#[cfg(test)]
mod group_drag_selection_tests {
use super::*;
+64 -1
View File
@@ -1022,7 +1022,14 @@ fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>
Value::Bool(b) => {
ui.label("");
let mut b = *b;
crate::widgets::checkbox(ui, &mut b, &label);
if path == "interface.systemTitleBar" && cfg!(all(not(target_arch = "wasm32"), not(target_os = "macos"))) {
ui.vertical(|ui| {
crate::widgets::checkbox(ui, &mut b, &label);
ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim));
});
} else {
crate::widgets::checkbox(ui, &mut b, &label);
}
obj.insert(k, json!(b));
}
Value::String(s) if path == "interface.language" => {
@@ -1993,6 +2000,62 @@ mod tests {
assert_eq!(restarted.session.prefs().interface.ui_font_size, prefs::UiFontSize::Large);
}
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))]
#[test]
fn system_title_bar_explains_next_launch_and_preserves_apply_and_cancel() {
use egui_kittest::{Harness, kittest::Queryable};
let (mut app, store) = app_with_store();
app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap();
app.custom_titlebar = true;
let id = open_preferences(&mut app, "interface");
let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
app
});
h.run_steps(4);
h.get_by_label("System title bar").scroll_to_me();
h.run_steps(4);
h.get_by_label("Applies at next launch.");
for desired in [true, false] {
h.get_by_label("System title bar").click();
h.run_steps(4);
assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"]["interface"]["systemTitleBar"], desired);
assert_eq!(h.state().session.prefs().interface.system_title_bar, !desired, "the draft is not applied yet");
h.get_by_label("Applies at next launch.");
h.get_by_label("Apply").click();
h.run_steps(4);
assert_eq!(h.state().session.prefs().interface.system_title_bar, desired);
assert_eq!(stored(&store)["interface"]["systemTitleBar"], desired);
assert!(h.state().custom_titlebar, "do not change the current window or restart it");
let (reloaded, _) = app_with_saved(store.lock().unwrap().clone());
assert_eq!(reloaded.session.prefs().interface.system_title_bar, desired);
h.get_by_label("Applies at next launch.");
}
h.get_by_label("System title bar").click();
h.run_steps(4);
h.get_by_label("Cancel").click();
h.run_steps(4);
assert!(h.state().ui.dialogs.iter().all(|d| d.id != id));
assert!(!h.state().session.prefs().interface.system_title_bar);
assert_eq!(stored(&store)["interface"]["systemTitleBar"], false);
assert!(h.state().custom_titlebar);
}
#[test]
fn next_launch_notice_does_not_mark_unrelated_interface_preferences() {
use egui_kittest::{Harness, kittest::Queryable};
let obj = json!({"showTooltips": true}).as_object().unwrap().clone();
let mut h =
Harness::new_ui_state(|ui, obj: &mut Map<String, Value>| section_fields(ui, "interface", obj, &[], crate::i18n::Lang::from_pref("en")), obj);
h.run_steps(4);
assert!(h.query_by_label("Applies at next launch.").is_none());
h.get_by_label("Show tooltips").click();
h.run_steps(4);
assert_eq!(h.state()["showTooltips"], false);
assert!(h.query_by_label("Applies at next launch.").is_none());
}
#[test]
fn preferences_confirm_after_apply_commits_later_edits() {
let (mut app, _) = app_with_store();
+4 -10
View File
@@ -291,16 +291,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
return;
}
// Pen path in progress: ↩ finishes (open path), Esc cancels.
if app.ui.pen.is_some() {
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
crate::vector_ui::pen_commit(app, false);
return;
}
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
app.ui.pen = None;
return;
}
// Pen path in progress: ↩ and Esc both end it as an open path and keep it, as in Photoshop (#1769).
if app.ui.pen.is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Escape)) {
crate::vector_ui::pen_commit(app, false);
return;
}
// Magnetic Lasso: ↩ closes, Esc cancels, ⌫ removes a fastening point (not Edit › Clear),
// [ ] change the detection width (not the brush size).
+53 -2
View File
@@ -407,10 +407,12 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
}
}
};
// View › Show › Target Path (under Extras) hides the paths; the Pen's path in progress stays.
let paths = app.ui.view.shows(app.ui.view.show.target_path);
if crate::direct_select::shows(app, painter.ctx().input(|i| i.modifiers)) {
// Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790).
crate::direct_select::draw_overlay(app, painter, &to_scr, accent);
} else {
crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths);
} else if paths {
if vector_tool {
if let Some(wp) = &doc.work_path {
draw_path(wp, tool == Tool::PathSelection);
@@ -1025,6 +1027,55 @@ mod tests {
assert!(!entries.iter().any(|(_, id, _)| *id == "path.delete"));
}
/// How many shapes the path overlay paints for `app` this frame.
fn overlay_shapes(app: &PhotocraftApp, ctx: &egui::Context) -> usize {
let doc = app.session.active().unwrap().doc.clone();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0));
let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect);
let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0 };
draw_overlay(app, &painter, &xf, &doc);
});
out.textures_delta.clear();
out.shapes.len()
}
#[test]
fn show_target_path_and_extras_hide_the_path_outlines() {
// #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the
// work path and the active shape's path.
let ctx = egui::Context::default();
let mut app = app();
let path = json!({"subpaths": [{"closed": true, "knots": [
{"anchor": [10, 10], "in": [10, 10], "out": [10, 10]},
{"anchor": [80, 10], "in": [80, 10], "out": [80, 10]},
{"anchor": [80, 80], "in": [80, 80], "out": [80, 80]}
]}]});
app.run("path.set", json!({"path": path})).unwrap();
assert!(app.session.active().unwrap().doc.work_path.is_some());
finish_shape(&mut app, Tool::Rectangle, [100.0, 100.0], [160.0, 150.0], egui::Modifiers::NONE);
let toggle = |app: &mut PhotocraftApp, id: &str| crate::menus::invoke(app, &ctx, id, Value::Null).unwrap();
for tool in [Tool::Pen, Tool::PathSelection, Tool::DirectSelection, Tool::Rectangle] {
app.ui.tool = tool;
assert!(app.ui.view.show.target_path && app.ui.view.extras);
assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the paths are drawn by default");
toggle(&mut app, "view.show.targetPath");
assert!(!app.ui.view.show.target_path);
assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Target Path off");
toggle(&mut app, "view.show.targetPath");
toggle(&mut app, "view.extras");
assert!(!app.ui.view.extras);
assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Extras off");
toggle(&mut app, "view.extras");
assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: shown again");
}
// The Pen's path in progress is a gesture, not the target path: it stays visible.
app.ui.tool = Tool::Pen;
app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[60.0, 40.0]; 3]], ..Default::default() });
toggle(&mut app, "view.show.targetPath");
assert!(overlay_shapes(&app, &ctx) > 0, "the pen path in progress is still drawn");
}
#[test]
fn shape_drag_creates_layers_with_modifiers() {
let mut app = app();
+11 -9
View File
@@ -37,20 +37,19 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given. `params` must be a JSON object (omit it or pass `null` for none); an array, string, number or boolean is an error naming the command, in every transport (control channel, `serve`, MCP and the CLI)
- `engine.commands`: list commands with enablement
- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`)
- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?}`: change UI state; any other field is an error, checked before anything changes (`theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` and `brushPickerView` are `list` or `grid` for the Brushes panel and the Brush Preset picker; `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour)
- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, gradientBlendMode?, gradientClassic?}`: change UI state; any other field is an error, checked before anything changes (`theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` and `brushPickerView` are `list` or `grid` for the Brushes panel and the Brush Preset picker; `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour)
- `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state.
- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?}`: change UI state; any other field is an error, checked before anything changes (`theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour)
- `ui.menu.invoke {id, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.
- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.
Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them.
- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once
- Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor`
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) edits the sections in its `values` field. `ui.dialog.apply {dialog}` saves those values through `prefs.set` and keeps the same dialog and section open. `ui.dialog.confirm` saves and closes; `ui.dialog.cancel` discards only edits made since the last successful Apply. Invalid values return an error without closing the Apply dialog or changing the saved preferences. Settings marked for the next launch still require a restart.
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart.
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker (`brushPicker` in `ui.inspect` reports its screen position `[x, y]`, or `null` when closed), or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven.
- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker (`brushPicker` in `ui.inspect` reports its screen position `[x, y]`, or `null` when closed), or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven.
- Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape.
- `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
@@ -61,7 +60,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
base64 PNG data; a path is relative to the automation write root. Raises the window first
(default) because occluded macOS windows stop rendering
- `ui.focus`: bring the main window to the front
- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))
- `app.open {path}` / `app.save {path?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))
- `app.quit`
## Engine commands
@@ -249,8 +248,11 @@ lines are visible. The protocol is unencrypted and must remain on loopback; do n
it to an untrusted host.
Filesystem access fails closed unless launch-time read and/or write roots are granted with
`--automation-read-root` and `--automation-write-root` (or
`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`). Request paths must be
`--automation-read-root` and `--automation-write-root`. The environment-variable equivalents
(`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`) are supported by
the desktop `photocraft` process, but not by headless `photocraft-cli mcp` or `serve`;
for those CLI modes, supply the flags explicitly. In MCP bridge mode, configure roots on the
desktop process rather than on the bridging CLI. Request paths must be
non-empty, forward-slash relative paths beneath the applicable root. Absolute paths, parent
traversal, alternate separators, drive/device/stream prefixes, malformed components, and link
escapes are rejected before file effects. Read and write authority are independent; the parent of
@@ -276,7 +278,7 @@ no MCP framing, no app start-up per command. Configure its file access with the
| `engine.commands` | `{filter?}`: registry with params docs and enablement |
| `session.list` | open documents and the active index |
| `doc.open` / `doc.new` | `{path}` / `file.new` params |
| `doc.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
| `doc.inspect` | `{index?}`: same JSON as `document.inspect` |
| `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` |
| `doc.select` / `doc.close` | `{index}` / `{index?}` |
+33 -5
View File
@@ -5,6 +5,29 @@
- Rust stable (1.95+). Add the web target with `rustup target add wasm32-unknown-unknown`.
- macOS, Windows or Linux. Linux needs `libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev`.
### Windows source builds
Use the Rust MSVC toolchain and install Visual Studio or Microsoft C++ Build Tools with the
**Desktop development with C++** workload. Follow Microsoft's
[Rust setup guide](https://learn.microsoft.com/en-us/windows/dev-environment/rust/setup),
then open a new terminal and check `cargo --version` and `rustc --version`.
On Windows 11, Smart App Control can block Cargo, rustc or executables generated during a build.
If a build reports `An Application Control policy has blocked this file. (os error 4551)`
([#1585](https://github.com/storytold/photocraft/issues/1585)), check:
- **Windows Security → App & browser control → Smart App Control settings** for its status.
- **Event Viewer → Applications and Services Logs → Microsoft → Windows → CodeIntegrity →
Operational** for the blocked executable and policy, especially on managed machines.
This error indicates an application-control restriction; moving `CARGO_TARGET_DIR` or
reinstalling Rust does not establish that the blocked executable is trusted. See Microsoft's
[Smart App Control FAQ](https://support.microsoft.com/en-us/windows/security/threat-malware-protection/smart-app-control-frequently-asked-questions)
for the available controls; there is no per-app exception. On a managed device, ask your
administrator about an approved development environment. If you only want to run PhotoCraft,
use the [packaged Windows release](https://github.com/storytold/photocraft/releases) to avoid
building locally; the downloaded app is still subject to Windows application-control checks.
## Build and run
```sh
@@ -65,8 +88,8 @@ By default PhotoCraft's own crates log at `info` and everything else at `warn`.
| `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) |
| `PHOTOCRAFT_CONTROL_TOKEN` | 64-hex bearer token for control TCP (avoid on shared systems where environment inspection is possible) |
| `PHOTOCRAFT_CONTROL_TOKEN_FILE` | Read, or create for a server, the control bearer-token file |
| `PHOTOCRAFT_AUTOMATION_READ_ROOT` | Directory capability for automation reads; requests use relative paths |
| `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` | Separate directory capability for automation writes; requests use relative paths |
| `PHOTOCRAFT_AUTOMATION_READ_ROOT` | Desktop app only: automation read root. Headless CLI modes require the `--automation-read-root` flag |
| `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` | Desktop app only: automation write root. Headless CLI modes require the `--automation-write-root` flag |
| `PHOTOCRAFT_CPU_CANVAS=1` | Force the CPU canvas path instead of the wgpu shader canvas |
| `PHOTOCRAFT_NATIVE_WAYLAND=1` | Linux: stay on native Wayland when a pen is attached (by default the window then opens through Xwayland, because Wayland gives the app no pen input; #639) |
| `WGPU_BACKEND=dx12` | Pick the wgpu backend(s) (`vulkan`, `dx12`, `metal`, `gl`); overrides `performance.gpuBackend` and the startup fallback |
@@ -138,6 +161,8 @@ Keep one `PcraftWriter` per open document: re-saving then only compresses and wr
- **Headless:** `photocraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>`. It drives an in-process engine session and has no file authority when a root is omitted.
- **Live app:** start `photocraft --control 7878 --control-token-file <private-path> --automation-read-root <dir> --automation-write-root <dir>`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <private-path>`. The desktop process owns the roots. See `docs/control-protocol.md#mcp-bridge`.
For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access.
Tools:
- `session_list`
@@ -153,7 +178,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`):
"mcpServers": {
"photocraft": {
"command": "/path/to/photocraft/target/release/photocraft-cli",
"args": ["mcp"]
"args": ["mcp", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-write-root", "/absolute/path/to/trusted/workspace"]
},
"photocraft-live": {
"command": "/path/to/photocraft/target/release/photocraft-cli",
@@ -165,7 +190,10 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`):
```sh
cargo build --release -p photocraft-cli
claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp
mkdir -p "$PWD/photocraft-work"
claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp \
--automation-read-root "$PWD/photocraft-work" \
--automation-write-root "$PWD/photocraft-work"
```
`doc_inspect` (and the engine command `document.inspect`) reports the layer tree with kinds,
@@ -178,7 +206,7 @@ capability-scoped export, resize/crop, CMYK + native save) driven purely over MC
Without MCP, `photocraft-cli serve [--port N]` keeps a headless session open and answers JSON lines
(see `docs/control-protocol.md#headless-server`).
A typical agent loop:
A typical agent loop (place inputs under the configured read root and outputs under the write root):
1. `doc_open {path}`
2. `command_list {filter:"blur"}`
+3 -1
View File
@@ -49,7 +49,9 @@ build. Limits (`photocraft_plugins::Limits`, defaults):
Every band runs in a **fresh instance**, so no state survives between calls, and parallel bands
never share memory. Traps, exhausted budgets, malformed modules, bad manifests, out-of-range
pointers and non-zero return codes all become errors; the document is left untouched (the edit is
transactional). Output samples that are NaN or infinite keep their original value; integer-depth
transactional). When a failure stops sibling bands, those bands retain the originating error
instead of replacing it with a generic cancellation message. Output samples that are NaN or
infinite keep their original value; integer-depth
documents and alpha are clamped to 0–1.
wasmi is built with its *portable* (loop) dispatcher: the default tail-call dispatcher relies on LLVM
+3
View File
@@ -88,6 +88,9 @@ Preferences has **Apply**, **OK** and **Cancel**. Apply saves the edited section
dialog open; it is disabled when the values match the saved preferences. OK saves and closes.
Cancel discards only changes made since the last successful Apply. A failed Apply leaves the
draft open for correction. Settings marked for the next launch still require a restart.
On Windows and Linux, System Title Bar displays “Applies at next launch.” beneath its checkbox,
including before editing and after Apply. Saving this preference does not restart the app or
change the current window's decorations; the next launch reads the saved choice.
## High DPI and 4K displays