Follow-ups to #665, #666, #734: Photoshop's mask-only Remove Background, one-step eye sweep, no-clone Show Only (#824)

* layer.showOnly: no document clone, keep layers added during a solo, more tests

- Compute the rows from a borrow instead of cloning the whole document, and set
  visibility by path (one walk) instead of an id lookup per layer.
- Restoring keeps the current visibility of layers the snapshot doesn't know
  (added while one layer was shown alone) instead of leaving them unspecified.
- Tests: enclosing groups stay visible and a group's contents keep their own
  visibility, an undo ends the solo, one history step, no snapshot shows every
  layer, bad layer ids and no document return errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers eye sweep: one history step, no skipped rows on a fast drag

- Every layer.setProps of one eye-column drag shares a coalesce key, so the
  whole sweep is one "Layer Visibility" undo step (it was one per row).
- A row counts as swept when the pointer passed it since the last frame, so
  a fast drag that jumps a row in one frame no longer skips it.
- The sweep lives in a small EyeSweep helper instead of inline in layer_row.
- layer.setProps names a visibility-only change "Layer Visibility" also when
  it carries a coalesce key.
- The harness test also checks one undo step and a single-move drag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Layers panel: hidden effects and smart filters get an empty eye box too

Matches the layer rows (and Photoshop): an effect or smart filter that is off
leaves its eye box empty instead of drawing a struck-out eye, so the whole
eye column of the Layers panel reads the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove Background: Photoshop's mask-only Quick Action, reusing Select Subject's sampler

Photoshop's Remove Background is a Properties (and contextual task bar) Quick
Action that analyses the selected layer and adds a layer mask from Select
Subject; it has no Layer menu item and no destructive variant.

- No menu path (drops the Layer › Remove Background placement); it stays
  reachable from Quick Actions, the command palette, the CLI, the control
  channel and MCP.
- Always a layer mask: drop the `output: "transparency"` bake and the `fill`
  layer (both are existing commands: Layer Mask › Apply, New Fill Layer) and
  the `radius` knob.
- Analyse the layer alone by default (`sampleAllLayers` false), as Photoshop
  does for the selected layer; true samples the composite.
- Reuse Select Subject's sampler: smartselect_cmds gains `with_doc_sampler`
  (what `with_sampler` now calls) instead of a second CompositeSampler and
  find/refine helpers.
- Promote the Background only once a subject is found.
- Tests: mask at 8/16/32-bit with untouched pixels, one history step,
  undo/redo, Background promotion, no subject, layer-alone default vs
  sampleAllLayers, disabled states and bad params, replacing a mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Korean labels for Relight's Ambient and Warmth (i18n coverage test red on main after #735)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
BFlatandClaude Opus 5.5 authored and GitHub committed 2026-10-08 04:25:22 +07:00
1 parent e1cf321183
commit 15af216bd1
9 files changed
+244 -402

No files matched your search

+3 -1
View File
@@ -464,7 +464,9 @@ fn build() -> Vec<CommandSpec> {
has_layer,
|s, p| {
let id = layer_param(s, p)?;
let label = if p.get("visible").is_some() && p.as_object().is_some_and(|o| o.len() <= 2) { "Layer Visibility" } else { "Layer Properties" };
let only_visibility =
p.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "visible" | "coalesce")));
let label = if only_visibility { "Layer Visibility" } else { "Layer Properties" };
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
// Clipping and channel changes reach the layers around it: recomposite everything.
let local = p.get("clipped").is_none() && p.get("channels").is_none();
+75 -293
View File
@@ -1,228 +1,82 @@
//! Layer › Remove Background: isolate the subject of a pixel layer in one history step.
//!
//! The subject is found with the same classical saliency + GrabCut path as Select › Subject, then
//! optionally refined. The default result is a layer mask (original pixels stay recoverable);
//! `"output":"transparency"` bakes coverage into pixel alpha. An optional `"fill"` colour inserts a
//! solid Color Fill layer immediately below the subject in that same step.
//! Remove Background, Photoshop's Quick Action for a pixel layer (Properties › Quick Actions):
//! Select Subject with a light edge refinement, turned into a layer mask, in one history step.
//! Like Photoshop it is non-destructive (the pixels stay; the mask hides the background), turns
//! the Background layer into a normal layer first and has no menu item.
use photocraft_algo::matting::{self, RefineParams};
use photocraft_algo::segment::{Sampler, SurfaceSampler, subject};
use photocraft_color::Color;
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, LayerMask};
use photocraft_geom::Rect;
use photocraft_algo::segment::subject;
use photocraft_doc::{Layer, LayerContent, LayerMask};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, layer_param};
use crate::smartselect_cmds::with_doc_sampler;
use crate::{EngineError, Result, Session};
const CMD: &str = "layer.removeBackground";
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
}
/// Edge refinement after Select Subject: a narrow smart radius and a little smoothing, so soft
/// edges and hair get partial coverage instead of a hard cut.
const REFINE: RefineParams = RefineParams { radius: 2.0, smart_radius: true, smooth: 10.0, feather: 0.5, contrast: 10.0, shift_edge: 0.0 };
/// Composite of all visible layers (same split as `select.subject`).
struct CompositeSampler<'a>(&'a Document);
impl Sampler for CompositeSampler<'_> {
fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
photocraft_compose::render(self.0, r).px
/// Remove Background needs an unlocked pixel layer.
fn check(l: &Layer) -> std::result::Result<(), String> {
if !matches!(l.content, LayerContent::Raster(_)) {
return Err(format!("the layer is a {} layer, not a pixel layer", l.content.kind_name()));
}
if l.locks.pixels || l.locks.all {
return Err(format!("Could not complete your request because the layer \"{}\" is locked", l.name));
}
Ok(())
}
fn enabled(s: &Session) -> std::result::Result<(), String> {
let l = crate::active_layer_of(s)?;
if !matches!(l.content, LayerContent::Raster(_)) {
return Err(format!("active layer is a {} layer, not a pixel layer", l.content.kind_name()));
}
if l.locks.pixels || l.locks.all {
return Err(format!("the layer \"{}\" is locked", l.name));
}
Ok(())
}
#[derive(Clone, Copy)]
enum Output {
Mask,
Transparency,
}
impl Output {
fn as_str(self) -> &'static str {
match self {
Output::Mask => "mask",
Output::Transparency => "transparency",
}
}
}
fn output_param(p: &Value) -> Result<Output> {
match p.get("output") {
None => Ok(Output::Mask),
Some(Value::String(s)) => match s.as_str() {
"mask" => Ok(Output::Mask),
"transparency" => Ok(Output::Transparency),
_ => Err(bad("output must be mask|transparency")),
},
Some(_) => Err(bad("output must be mask|transparency")),
}
}
fn radius_param(p: &Value) -> Result<f32> {
match p.get("radius") {
None => Ok(2.0),
Some(v) => {
let Some(x) = v.as_f64() else {
return Err(bad("radius must be a finite number in 0..=64"));
};
if !x.is_finite() || x < 0.0 {
return Err(bad("radius must be a finite number in 0..=64"));
}
Ok((x as f32).clamp(0.0, 64.0))
}
}
}
fn fill_param(p: &Value) -> Result<Option<Color>> {
match p.get("fill") {
None => Ok(None),
Some(Value::String(s)) => {
let [r, g, b] = crate::prefs::parse_hex(s).ok_or_else(|| bad("fill must be #rrggbb"))?;
Ok(Some(Color::rgb(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0)))
}
Some(_) => Err(bad("fill must be #rrggbb")),
}
}
fn bool_or(p: &Value, key: &str, default: bool) -> bool {
p.get(key).and_then(Value::as_bool).unwrap_or(default)
}
fn target_layer(s: &Session, p: &Value) -> Result<LayerId> {
let _ = s.active().ok_or(EngineError::NoDocument)?;
let id = layer_param(s, p)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
if !matches!(l.content, LayerContent::Raster(_)) {
return Err(EngineError::Other(format!("the layer is a {} layer, not a pixel layer", l.content.kind_name())));
}
if l.locks.pixels || l.locks.all {
return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name)));
}
Ok(id)
}
fn find_subject(doc: &Document, id: LayerId, sample_all: bool) -> Result<Option<photocraft_algo::selection::Region>> {
let canvas = doc.bounds();
if sample_all {
return Ok(subject::select_subject(&CompositeSampler(doc), canvas));
}
let surf = doc.layer(id).and_then(photocraft_doc::Layer::surface).ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
Ok(subject::select_subject(&SurfaceSampler(surf), canvas))
}
fn refine_subject(
doc: &Document,
id: LayerId,
sample_all: bool,
region: photocraft_algo::selection::Region,
radius: f32,
) -> Result<photocraft_algo::selection::Region> {
let canvas = doc.bounds();
let params = RefineParams { radius, smart_radius: true, smooth: 10.0, feather: 0.5, contrast: 10.0, shift_edge: 0.0 };
let refined = if sample_all {
matting::refine_mask(&CompositeSampler(doc), &matting::region_reader(&region), region.bbox, canvas, &params)
} else {
let surf = doc.layer(id).and_then(photocraft_doc::Layer::surface).ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
matting::refine_mask(&SurfaceSampler(surf), &matting::region_reader(&region), region.bbox, canvas, &params)
};
Ok(refined.unwrap_or(region))
}
fn apply_cutout(doc: &mut Document, id: LayerId, region: &photocraft_algo::selection::Region, output: Output) -> Result<()> {
match output {
Output::Transparency => {
let src = doc.layer(id).and_then(photocraft_doc::Layer::surface).cloned().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?;
let pixels = matting::masked_copy(&src, region);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.content = LayerContent::Raster(pixels);
l.mask = None;
}
Output::Mask => {
let surface = matting::region_surface(region);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.mask = Some(LayerMask { surface, ..LayerMask::reveal_all() });
}
}
doc.selection = None;
Ok(())
}
fn insert_fill_below(doc: &mut Document, subject: LayerId, color: Color) -> LayerId {
let layer = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(Fill::Solid(color)));
let fid = doc.insert_above(Some(subject), layer);
let _ = doc.shift(fid, -1);
fid
}
struct CutoutOut {
layer: u64,
output: &'static str,
fill_layer: Option<u64>,
bounds: [i32; 4],
check(crate::active_layer_of(s)?)
}
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let output = output_param(p)?;
let radius = radius_param(p)?;
let fill = fill_param(p)?;
let sample_all = bool_or(p, "sampleAllLayers", true);
let refine = bool_or(p, "refine", true);
let id = target_layer(s, p)?;
let id = layer_param(s, p)?;
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
check(doc.layer(id).ok_or(EngineError::NoLayer(id))?).map_err(EngineError::Other)?;
let sample_all = p.get("sampleAllLayers").and_then(Value::as_bool).unwrap_or(false);
let refine = p.get("refine").and_then(Value::as_bool).unwrap_or(true);
crate::jobs::edit_job(
s,
"Remove Background",
move |doc, _active, ctx| {
crate::extra_cmds::background_to_layer_for_mask(doc, id);
if ctx.cancelled() {
return Err(EngineError::Cancelled);
}
ctx.progress(0.15, "Finding subject");
let mut region = find_subject(doc, id, sample_all)?.ok_or_else(|| EngineError::Other("no subject found".into()))?;
move |doc, _, ctx| {
ctx.progress(0.1, "Finding subject");
let found = with_doc_sampler(doc, Some(id), sample_all, |smp, d| subject::select_subject(smp, d.bounds()));
let mut region = found.ok_or_else(|| EngineError::Other("no subject found".into()))?;
if ctx.cancelled() {
return Err(EngineError::Cancelled);
}
if refine {
ctx.progress(0.55, "Refining edge");
region = refine_subject(doc, id, sample_all, region, radius)?;
ctx.progress(0.6, "Refining edge");
let refined = with_doc_sampler(doc, Some(id), sample_all, |smp, d| {
matting::refine_mask(smp, &matting::region_reader(&region), region.bbox, d.bounds(), &REFINE)
});
region = refined.unwrap_or(region);
if ctx.cancelled() {
return Err(EngineError::Cancelled);
}
}
ctx.progress(0.85, "Applying");
apply_cutout(doc, id, &region, output)?;
let fill_layer = fill.map(|color| insert_fill_below(doc, id, color).0);
crate::extra_cmds::background_to_layer_for_mask(doc, id);
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface: matting::region_surface(&region), ..LayerMask::reveal_all() });
doc.selection = None;
let b = region.bbox;
Ok(CutoutOut { layer: id.0, output: output.as_str(), fill_layer, bounds: [b.x0, b.y0, b.width() as i32, b.height() as i32] })
},
|r| {
let mut v = json!({ "layer": r.layer, "output": r.output, "bounds": r.bounds });
if let Some(fid) = r.fill_layer {
v["fillLayer"] = json!(fid);
}
v
Ok([b.x0, b.y0, b.width() as i32, b.height() as i32])
},
move |bounds| json!({ "layer": id.0, "bounds": bounds }),
)
}
/// Remove Background command spec.
/// Remove Background command spec (no menu path: a Properties Quick Action in Photoshop).
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: CMD,
label: "Remove Background",
menu: &["Layer"],
menu: &[],
shortcut: None,
params: r##"{"layer":id?,"sampleAllLayers":bool=true,"output":"mask|transparency"="mask","refine":bool=true,"radius":px=2,"fill":"#rrggbb?"}"##,
params: r##"{"layer":id?,"sampleAllLayers":bool=false,"refine":bool=true} → {layer,bounds} (adds a layer mask from Select Subject; the Background becomes a normal layer)"##,
enabled,
run,
journal: true,
@@ -233,6 +87,8 @@ pub fn specs() -> Vec<CommandSpec> {
mod tests {
use super::*;
use photocraft_algo::segment::Rng;
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session {
let mut s = Session::new();
@@ -257,14 +113,10 @@ mod tests {
s
}
fn noise_field(w: u32, h: u32, seed: u64) -> Vec<f32> {
let mut rng = Rng::new(seed);
(0..w * h).map(|_| rng.normal()).collect()
}
/// Textured disc (centre (100, 80), radius 45) on a noisy background.
fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) {
let nz = noise_field(200, 160, 2);
let mut rng = Rng::new(2);
let nz: Vec<f32> = (0..200 * 160).map(|_| rng.normal()).collect();
let inside = |x: i32, y: i32| {
let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0);
dx * dx + dy * dy <= 45.0 * 45.0
@@ -286,13 +138,12 @@ mod tests {
s.active().unwrap().active_layer.unwrap()
}
fn layer(s: &Session, id: LayerId) -> &photocraft_doc::Layer {
fn layer(s: &Session, id: LayerId) -> &Layer {
s.active().unwrap().doc.layer(id).unwrap()
}
fn mask_cov(s: &Session, x: i32, y: i32) -> f32 {
let id = active_id(s);
layer(s, id).mask.as_ref().map_or(0.0, |m| m.value(x, y))
layer(s, active_id(s)).mask.as_ref().map_or(0.0, |m| m.value(x, y))
}
fn mask_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 {
@@ -307,35 +158,27 @@ mod tests {
i as f32 / u.max(1) as f32
}
fn corner_alpha(s: &Session) -> f32 {
let doc = &s.active().unwrap().doc;
photocraft_compose::render(doc, Rect::new(0, 0, 1, 1)).px.first().map(|p| p[3]).unwrap_or(0.0)
}
fn corner_rgb(s: &Session) -> [f32; 3] {
let doc = &s.active().unwrap().doc;
let p = photocraft_compose::render(doc, Rect::new(0, 0, 1, 1)).px.first().copied().unwrap_or([0.0; 4]);
[p[0], p[1], p[2]]
}
#[test]
fn remove_background_mask_depths_and_undo() {
fn remove_background_masks_the_subject_at_every_depth_and_undoes() {
for depth in [8, 16, 32] {
let (mut s, inside) = disc(depth);
assert!(s.is_enabled(CMD));
let before_rev = s.active().unwrap().revision;
let r = s.execute(CMD, json!({})).unwrap();
assert_eq!(r["output"], "mask");
assert_eq!(r["layer"], active_id(&s).0);
let id = active_id(&s);
let pixels = layer(&s, id).surface().unwrap().read_region(Rect::new(0, 0, 200, 160));
let steps = s.active().unwrap().history.past_len();
let r = s.execute(CMD, json!({})).unwrap();
assert_eq!(r["layer"], id.0);
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "depth {depth}: one history step");
assert!(layer(&s, id).mask.is_some(), "depth {depth}: expected a layer mask");
let v = mask_iou(&s, 200, 160, &inside);
assert!(v >= 0.75, "depth {depth}: IoU {v}");
assert!(mask_cov(&s, 0, 0) < 0.2, "depth {depth}: background corner still revealed");
assert!(mask_cov(&s, 100, 80) >= 0.8, "depth {depth}: disc centre hidden");
assert!(corner_alpha(&s) < 0.2, "depth {depth}: composite corner alpha {}", corner_alpha(&s));
// Non-destructive: the pixels are untouched, only masked.
assert_eq!(layer(&s, id).surface().unwrap().read_region(Rect::new(0, 0, 200, 160)), pixels, "depth {depth}");
let corner = photocraft_compose::render(&s.active().unwrap().doc, Rect::new(0, 0, 1, 1)).px[0][3];
assert!(corner < 0.2, "depth {depth}: composite corner alpha {corner}");
assert!(s.active().unwrap().doc.selection.is_none());
assert!(s.active().unwrap().revision > before_rev);
s.execute("edit.undo", json!({})).unwrap();
assert!(layer(&s, id).mask.is_none(), "depth {depth}: mask remained after undo");
s.execute("edit.redo", json!({})).unwrap();
@@ -344,66 +187,19 @@ mod tests {
}
#[test]
fn remove_background_transparency_and_fill() {
let (mut s, _) = disc(8);
let subject = active_id(&s);
let layers_before = s.active().unwrap().doc.layer_count();
let r = s.execute(CMD, json!({"output": "transparency", "fill": "#00aa44"})).unwrap();
assert_eq!(r["output"], "transparency");
assert_eq!(r["layer"], subject.0);
let fill_id = LayerId(r["fillLayer"].as_u64().unwrap());
assert_eq!(s.active().unwrap().doc.layer_count(), layers_before + 1);
assert_eq!(active_id(&s), subject);
let l = layer(&s, subject);
assert!(l.mask.is_none(), "transparency output should drop the mask");
let surf = l.surface().unwrap();
assert!(surf.format().alpha);
let a = |x: i32, y: i32| {
let p = surf.pixel(x, y);
*p.last().unwrap_or(&0.0)
};
assert!(a(0, 0) < 0.2, "corner alpha {}", a(0, 0));
assert!(a(100, 80) >= 0.8, "centre alpha {}", a(100, 80));
let fl = layer(&s, fill_id);
assert!(matches!(&fl.content, LayerContent::Fill(Fill::Solid(c)) if (c.c[1] - 170.0 / 255.0).abs() < 0.02));
let walk: Vec<LayerId> = s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
let fi = walk.iter().position(|x| *x == fill_id).unwrap();
let si = walk.iter().position(|x| *x == subject).unwrap();
assert!(fi < si, "fill layer should sit below the subject");
let rgb = corner_rgb(&s);
assert!((rgb[0] - 0.0).abs() < 0.08 && (rgb[1] - 170.0 / 255.0).abs() < 0.08 && (rgb[2] - 68.0 / 255.0).abs() < 0.08, "fill colour at corner {rgb:?}");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.layer_count(), layers_before);
assert!(s.active().unwrap().doc.layer(fill_id).is_none());
assert!(layer(&s, subject).mask.is_none());
let orig = layer(&s, subject).surface().unwrap().pixel(0, 0);
let oa = if orig.len() >= 4 { orig[3] } else { 1.0 };
assert!(oa > 0.9, "undo should restore opaque pixels, alpha {oa}");
}
#[test]
fn remove_background_promotes_background() {
fn remove_background_turns_the_background_into_a_layer() {
let (mut s, _) = disc(8);
let id = active_id(&s);
let l = layer(&s, id);
assert_eq!(l.name, "Background");
assert!(l.locks.transparency && l.locks.position);
assert_eq!(layer(&s, id).name, "Background");
s.execute(CMD, json!({})).unwrap();
let l = layer(&s, id);
assert!(
l.name != "Background" || !l.locks.transparency || !l.locks.position,
"still the Background: {} locks t={} p={}",
l.name,
l.locks.transparency,
l.locks.position
);
assert_eq!(l.name, "Layer 0");
assert!(!l.locks.transparency && !l.locks.position);
assert!(l.mask.is_some());
}
#[test]
fn remove_background_no_subject_leaves_document() {
fn remove_background_without_a_subject_leaves_the_document() {
let mut s = session_with(32, 32, 8, |_, _| [0.5, 0.5, 0.5]);
let before = s.active().unwrap().revision;
let id = active_id(&s);
@@ -413,7 +209,7 @@ mod tests {
}
#[test]
fn remove_background_disabled_and_bad_params() {
fn remove_background_disabled_states_and_bad_params() {
assert!(!Session::new().is_enabled(CMD));
assert!(Session::new().execute(CMD, json!({})).is_err());
@@ -428,53 +224,39 @@ mod tests {
assert!(s.execute(CMD, json!({})).is_err());
let (mut s, _) = disc(8);
let id = active_id(&s);
s.edit("lock", |doc, _| {
doc.layer_mut(id).unwrap().locks.pixels = true;
Ok(())
})
.unwrap();
s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
assert!(!s.is_enabled(CMD));
assert!(s.execute(CMD, json!({})).is_err());
let (mut s, _) = disc(8);
assert!(s.execute(CMD, json!({"output": "bogus"})).is_err());
assert!(s.execute(CMD, json!({"fill": "nope"})).is_err());
assert!(s.execute(CMD, json!({"radius": -1})).is_err());
assert!(s.execute(CMD, json!({"radius": f64::NAN})).is_err());
assert!(s.execute(CMD, json!({"radius": f64::INFINITY})).is_err());
assert!(s.execute(CMD, json!({"layer": 999999})).is_err());
let before = s.active().unwrap().revision;
assert!(s.execute(CMD, json!({"fill": "nope"})).is_err());
assert_eq!(s.active().unwrap().revision, before, "bad fill must not edit");
assert!(s.execute(CMD, json!({"layer": 999_999})).is_err());
// Wrong types fall back to the defaults (the active layer, layer-only sampling, refined).
assert!(s.execute(CMD, json!({"layer": "x", "sampleAllLayers": 3, "refine": "no"})).is_ok());
assert!(s.active().unwrap().revision > before);
}
#[test]
fn remove_background_ignores_hidden_lower_layer_when_not_sampling_all() {
fn remove_background_looks_at_the_layer_alone_by_default() {
let (mut s, _) = disc(8);
let bottom = active_id(&s);
s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap();
let top = active_id(&s);
s.edit("hide", |doc, _| {
doc.layer_mut(bottom).unwrap().visible = false;
Ok(())
})
.unwrap();
s.execute("layer.select", json!({"layer": top.0})).unwrap();
let before = s.active().unwrap().revision;
assert!(s.execute(CMD, json!({"sampleAllLayers": false})).is_err());
// The empty layer has no subject of its own, though the photo shows through it.
assert!(s.execute(CMD, json!({})).is_err());
assert_eq!(s.active().unwrap().revision, before);
assert!(layer(&s, top).mask.is_none());
assert!(layer(&s, bottom).mask.is_none());
assert!(layer(&s, top).mask.is_none() && layer(&s, bottom).mask.is_none());
// Sampling all layers finds the subject in the composite.
s.execute(CMD, json!({"sampleAllLayers": true})).unwrap();
assert!(layer(&s, top).mask.is_some() && layer(&s, bottom).mask.is_none());
}
#[test]
fn remove_background_twice_keeps_one_mask() {
fn remove_background_twice_replaces_the_mask() {
let (mut s, _) = disc(8);
s.execute(CMD, json!({})).unwrap();
s.execute(CMD, json!({})).unwrap();
let id = active_id(&s);
assert!(layer(&s, id).mask.is_some());
s.execute(CMD, json!({"refine": false})).unwrap();
let masks = s.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| l.mask.is_some()).count();
assert_eq!(masks, 1);
}
+67 -42
View File
@@ -1,7 +1,8 @@
//! Everyday Photoshop commands that build on the core ones: Edit › Stroke, the fixed Transform
//! presets (Rotate 180°/90°, Flip), Paste Into, Reselect, Equalize, Reveal All, Layer from
//! Background, Copy/Paste Layer Style, Hide All Effects, layer-mask toggles, Rasterize variants,
//! Delete Hidden / Empty Layers, Ungroup, Hide/Show Layers, Average and Clouds.
//! Delete Hidden / Empty Layers, Ungroup, Hide/Show Layers, Show Only This Layer (⌥-click an eye),
//! Average and Clouds.
use photocraft_algo::selection as sel;
use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask};
@@ -454,61 +455,48 @@ fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result<Value> {
Ok(Value::Null)
}
/// Is `id` shown alone: it and its enclosing groups visible, every layer outside it hidden?
fn shown_alone(doc: &Document, id: LayerId) -> bool {
let Some(path) = doc.path_of(id) else { return false };
doc.walk().iter().all(|(p, _, l)| match () {
_ if path.starts_with(p) => l.visible,
_ if p.starts_with(&path) => true,
_ => !l.visible,
})
/// Is the layer at `path` shown alone: it and its enclosing groups visible, every layer outside
/// it hidden (the layers inside a group keep their own visibility)?
fn shown_alone(doc: &Document, path: &[usize]) -> bool {
doc.walk().iter().all(|(p, _, l)| if path.starts_with(p) { l.visible } else { p.starts_with(path) || !l.visible })
}
/// ⌥-click on a layer's eye: show only that layer, or, when it already is shown
/// alone, restore every layer's visibility from before (all layers shown if that was lost).
/// ⌥-clicking another eye while one layer is shown alone moves the solo and keeps the snapshot.
/// ⌥-click on a layer's eye: show only that layer (and its enclosing groups), or, when it already
/// is shown alone, restore every layer's visibility from before (every layer shown when there is
/// no snapshot). ⌥-clicking another eye while one layer is shown alone moves the solo and keeps
/// the snapshot. One history step either way; the snapshot is view state.
fn show_only(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, p)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = st.doc.clone();
let doc = &st.doc;
let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
let saved = st.show_only.clone().filter(|(prev, _)| shown_alone(&doc, *prev));
if shown_alone(&doc, id) {
let before: Vec<(LayerId, bool)> = match saved {
Some((_, v)) => v,
None => doc.walk().iter().map(|(_, _, l)| (l.id, true)).collect(),
};
s.edit("Show Layers", |doc, _| {
for (lid, visible) in &before {
if let Some(l) = doc.layer_mut(*lid) {
l.visible = *visible;
}
}
Ok(())
})?;
if let Some(st) = s.active_mut() {
st.show_only = None;
}
return Ok(json!({"shownAlone": false}));
}
let snapshot = match saved {
Some((_, v)) => v,
None => doc.walk().iter().map(|(_, _, l)| (l.id, l.visible)).collect(),
// The snapshot only counts while its solo is still in effect (an undo or a plain eye click ends it).
let saved = st.show_only.as_ref().filter(|(prev, _)| doc.path_of(*prev).is_some_and(|pp| shown_alone(doc, &pp)));
let walk = doc.walk();
let solo = !shown_alone(doc, &path);
let (label, rows, next): (_, Vec<(Vec<usize>, bool)>, _) = if solo {
let snapshot = saved.map_or_else(|| walk.iter().map(|(_, _, l)| (l.id, l.visible)).collect(), |(_, v)| v.clone());
// Layers inside the shown layer keep their visibility.
let rows = walk.iter().filter(|(p, _, _)| p.len() <= path.len() || !p.starts_with(&path)).map(|(p, _, _)| (p.clone(), path.starts_with(p))).collect();
("Show Only This Layer", rows, Some((id, snapshot)))
} else {
let before: Option<std::collections::HashMap<LayerId, bool>> = saved.map(|(_, v)| v.iter().copied().collect());
// Layers added since the snapshot keep their current visibility.
let rows = walk.iter().map(|(p, _, l)| (p.clone(), before.as_ref().is_none_or(|b| b.get(&l.id).copied().unwrap_or(l.visible)))).collect();
("Show Layers", rows, None)
};
let rows: Vec<(LayerId, bool)> =
doc.walk().iter().filter(|(p, _, _)| !(p.starts_with(&path) && p.len() > path.len())).map(|(p, _, l)| (l.id, path.starts_with(p))).collect();
s.edit("Show Only This Layer", |doc, _| {
for (lid, visible) in &rows {
if let Some(l) = doc.layer_mut(*lid) {
s.edit(label, |doc, _| {
for (p, visible) in &rows {
if let Some(l) = doc.layer_at_mut(p) {
l.visible = *visible;
}
}
Ok(())
})?;
if let Some(st) = s.active_mut() {
st.show_only = Some((id, snapshot));
st.show_only = next;
}
Ok(json!({"shownAlone": true}))
Ok(json!({ "shownAlone": solo }))
}
/// Pixels of a fill or smart-object layer's content alone (no mask, effects or opacity).
@@ -911,6 +899,43 @@ mod tests {
assert_eq!(vis(&s), [false, false, true]);
assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap()["shownAlone"], false);
assert_eq!(vis(&s), [true, false, true], "restored, with Layer 1 still hidden");
// One history step each way.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(vis(&s), [false, false, true]);
}
#[test]
fn show_only_keeps_groups_and_their_contents() {
let mut s = session(8);
s.execute("layer.new.layer", json!({})).unwrap();
let inner = active(&s).id;
let group = s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap();
let shown = |s: &Session| doc(s).walk().iter().map(|(_, _, l)| l.visible).collect::<Vec<_>>();
// Background, Layer 1, Group 1, Layer 2 (inside the group).
s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap();
assert_eq!(shown(&s), [false, false, true, true], "the enclosing group stays visible");
// An undo ends the solo, so the next ⌥-click solos again from the current state.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap()["shownAlone"], true);
s.execute("edit.undo", json!({})).unwrap();
// Showing a group alone leaves its contents as they are.
s.execute("layer.setProps", json!({"layer": inner.0, "visible": false})).unwrap();
s.execute("layer.showOnly", json!({"layer": group.0})).unwrap();
assert_eq!(shown(&s), [false, false, true, false]);
s.execute("layer.showOnly", json!({"layer": group.0})).unwrap();
assert_eq!(shown(&s), [true, true, true, false]);
}
#[test]
fn show_only_without_a_snapshot_shows_every_layer() {
let mut s = session(16);
let bg = doc(&s).layers[0].id;
s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap();
// Layer 1 is already the only visible layer: ⌥-clicking it shows everything.
assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false);
assert!(doc(&s).layers.iter().all(|l| l.visible));
assert!(s.execute("layer.showOnly", json!({"layer": 9999})).is_err());
assert!(Session::new().execute("layer.showOnly", json!({})).is_err());
}
#[test]
+11 -7
View File
@@ -6,7 +6,7 @@
use photocraft_algo::matting::{self, RefineParams};
use photocraft_algo::segment::{Sampler, SurfaceSampler, focus, grabcut, quick, subject};
use photocraft_algo::selection::{Region, SelectionMode, combine_region};
use photocraft_doc::{Document, Layer, LayerContent, LayerMask};
use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask};
use photocraft_geom::Rect;
use serde_json::{Value, json};
@@ -47,12 +47,16 @@ impl Sampler for CompositeSampler<'_> {
/// active layer has no pixels).
fn with_sampler<R>(s: &Session, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> Result<R> {
let d = s.active().ok_or(EngineError::NoDocument)?;
let doc = d.doc.clone();
let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| l.surface());
Ok(match (all_layers, layer) {
(false, Some(surf)) => f(&SurfaceSampler(surf), &doc),
_ => f(&CompositeSampler(&doc), &doc),
})
Ok(with_doc_sampler(&d.doc, d.active_layer, all_layers, f))
}
/// Runs `f` with a sampler over `layer`'s pixels in `doc` (or the composite with `all_layers`, or
/// when the layer has no pixels).
pub(crate) fn with_doc_sampler<R>(doc: &Document, layer: Option<LayerId>, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> R {
match (all_layers, layer.and_then(|id| doc.layer(id)).and_then(Layer::surface)) {
(false, Some(surf)) => f(&SurfaceSampler(surf), doc),
_ => f(&CompositeSampler(doc), doc),
}
}
/// Stores `region` combined with the current selection by `m` as one history step.
+2
View File
@@ -2111,6 +2111,8 @@ cameraRaw Color 색상
Gloss 광택
Metallic 금속성
Ambience 주변광
Ambient 주변광 비율
Warmth 따뜻함
White Is High 흰색이 높음
Reduce Color Noise 색상 노이즈 감소
Sharpen Details 세부 묘사 선명하게
1 # Korean (ko) catalog. UTF-8: context<TAB>English source<TAB>translation.
2111
2112
2113
2114
2115
2116
2117
2118
+38 -32
View File
@@ -179,40 +179,46 @@ fn collapse_all_groups_from_the_panel_menu_and_it_is_saved() {
}
}
/// Dragging down the eye column hides (or shows) every layer swept over and never reorders the
/// layers; a hidden layer's eye box is empty and a click shows it again.
/// Dragging down the eye column hides (or shows) every layer swept over, in one history step, and
/// never reorders the layers, even when one pointer move jumps several rows; a hidden layer's eye
/// box is empty and a click shows it again.
#[test]
fn dragging_down_the_eyes_sweeps_visibility_without_reordering() {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
for i in 0..4 {
s.execute("layer.new.layer", json!({"name": format!("L{i}")})).unwrap();
}
let mut h = harness(s, 1.0, "promedium", 290.0);
let order = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let visible = |h: &Harness<'_, PhotocraftApp>, id: u64| h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().visible;
let before = order(&h);
// Rows top to bottom: L3, L2, L1, L0, Background.
let rows = recorded(&h.ctx);
let eye = |r: &RowRects| pos2(r.row.left() + 17.0, r.row.center().y);
let (first, last) = (eye(&rows[0]), eye(&rows[2]));
h.event(egui::Event::PointerMoved(first));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: first, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
for k in 1..=10 {
h.event(egui::Event::PointerMoved(first + (last - first) * (k as f32 / 10.0)));
for moves in [10, 1] {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
for i in 0..4 {
s.execute("layer.new.layer", json!({"name": format!("L{i}")})).unwrap();
}
let mut h = harness(s, 1.0, "promedium", 290.0);
let order = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let visible = |h: &Harness<'_, PhotocraftApp>, id: u64| h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().visible;
let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();
let (before, steps_before) = (order(&h), steps(&h));
// Rows top to bottom: L3, L2, L1, L0, Background.
let rows = recorded(&h.ctx);
let eye = |r: &RowRects| pos2(r.row.left() + 17.0, r.row.center().y);
let (first, last) = (eye(&rows[0]), eye(&rows[2]));
h.event(egui::Event::PointerMoved(first));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: first, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
for k in 1..=moves {
h.event(egui::Event::PointerMoved(first + (last - first) * (k as f32 / moves as f32)));
h.run_steps(1);
}
h.event(egui::Event::PointerButton { pos: last, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
for r in &rows[..3] {
assert!(!visible(&h, r.layer), "{moves} moves: layer {} swept hidden", r.layer);
}
assert!(visible(&h, rows[3].layer), "{moves} moves: rows past the sweep are untouched");
assert_eq!(order(&h), before, "{moves} moves: an eye drag never reorders the layers");
assert_eq!(steps(&h), steps_before + 1, "{moves} moves: the whole sweep is one history step");
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Layer Visibility"));
// A click on the (empty) eye box of a hidden layer shows it again.
let p = eye(&recorded(&h.ctx)[1]);
click(&mut h, p);
assert!(visible(&h, rows[1].layer));
}
h.event(egui::Event::PointerButton { pos: last, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
for r in &rows[..3] {
assert!(!visible(&h, r.layer), "layer {} swept hidden", r.layer);
}
assert!(visible(&h, rows[3].layer), "rows past the sweep are untouched");
assert_eq!(order(&h), before, "an eye drag never reorders the layers");
// A click on the (empty) eye box of a hidden layer shows it again.
let p = eye(&recorded(&h.ctx)[1]);
click(&mut h, p);
assert!(visible(&h, rows[1].layer));
}
+1 -5
View File
@@ -625,11 +625,7 @@ pub fn is_live(id: &str) -> bool {
}
/// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`.
const PLACE_AFTER: &[(&str, &str)] = &[
("file.newFromClipboard", "file.new"),
("layer.removeBackground", "layer.layerMask.fromTransparency"),
("filter.render.relight", "filter.render.lightingEffects"),
];
const PLACE_AFTER: &[(&str, &str)] = &[("file.newFromClipboard", "file.new"), ("filter.render.relight", "filter.render.lightingEffects")];
pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
// 1) Photoshop's full menu tree, in Photoshop order; live where we implement the command.
+44 -21
View File
@@ -1572,6 +1572,46 @@ fn select_mode(m: egui::Modifiers) -> &'static str {
}
}
/// A drag down the Layers panel's eye column (Photoshop): the first eye toggles and every row
/// swept over gets the same visibility, once per row, all in one history step.
#[derive(Clone)]
struct EyeSweep {
visible: bool,
/// The `coalesce` key shared by the drag's `layer.setProps` calls.
key: u64,
swept: Vec<u64>,
}
/// Starts an eye-column sweep from `eye`, or applies a running one to the row `row` of `l`.
fn eye_sweep(ctx: &egui::Context, l: &Layer, row: Rect, eye: &egui::Response, actions: &mut Vec<(String, Value)>) {
let id = egui::Id::new("layer-eye-sweep");
let set =
|visible: bool, key: u64| ("layer.setProps".to_string(), json!({"layer": l.id.0, "visible": visible, "coalesce": format!("layer-eye-sweep:{key}")}));
if eye.drag_started() {
let sweep = EyeSweep { visible: !l.visible, key: ctx.cumulative_pass_nr(), swept: vec![l.id.0] };
actions.push(set(sweep.visible, sweep.key));
ctx.data_mut(|d| d.insert_temp(id, sweep));
return;
}
let Some(mut sweep) = ctx.data(|d| d.get_temp::<EyeSweep>(id)) else { return };
let (down, pos, delta) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.interact_pos(), i.pointer.delta()));
if !down {
ctx.data_mut(|d| d.remove::<EyeSweep>(id));
return;
}
// Everything the pointer passed since the last frame, so a fast drag skips no row.
let Some(p) = pos else { return };
let (y0, y1) = ((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y));
if y1 < row.top() || y0 >= row.bottom() || sweep.swept.contains(&l.id.0) {
return;
}
if l.visible != sweep.visible {
actions.push(set(sweep.visible, sweep.key));
}
sweep.swept.push(l.id.0);
ctx.data_mut(|d| d.insert_temp(id, sweep));
}
#[allow(clippy::too_many_arguments)]
fn layer_row(
app: &mut PhotocraftApp,
@@ -1622,26 +1662,7 @@ fn layer_row(
if l.visible {
icons::paint(ui, eye, "eye", 15.0, t.icon);
}
let sweep_id = egui::Id::new("layer-eye-sweep");
if eye_resp.drag_started() {
let visible = !l.visible;
ctx.data_mut(|d| d.insert_temp(sweep_id, (visible, vec![l.id.0])));
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": visible})));
} else if let Some((visible, mut swept)) = ctx.data(|d| d.get_temp::<(bool, Vec<u64>)>(sweep_id)) {
if !ctx.input(|i| i.pointer.primary_down()) {
ctx.data_mut(|d| d.remove::<(bool, Vec<u64>)>(sweep_id));
} else if let Some(p) = ctx.input(|i| i.pointer.interact_pos())
&& p.y >= rect.top()
&& p.y < rect.bottom()
&& !swept.contains(&l.id.0)
{
if l.visible != visible {
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": visible})));
}
swept.push(l.id.0);
ctx.data_mut(|d| d.insert_temp(sweep_id, (visible, swept)));
}
}
eye_sweep(ctx, l, rect, &eye_resp, actions);
if eye_resp.clicked() {
// ⌥-click shows only this layer; ⌥-click it again to restore the others.
if ui.input(|i| i.modifiers.alt) {
@@ -2406,7 +2427,9 @@ 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));
icons::paint(ui, eye, if on { "eye" } else { "eye-off" }, 12.0, if on { t.icon } else { t.text_faint });
if on {
icons::paint(ui, eye, "eye", 12.0, t.icon);
}
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);
+3 -1
View File
@@ -60,7 +60,9 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth:
None => sm.filters_enabled,
Some(i) => sm.smart_filters[i].visible,
};
icons::paint(ui, eye, if shown { "eye" } else { "eye-off" }, 12.0, if shown { t.icon } else { t.text_faint });
if shown {
icons::paint(ui, eye, "eye", 12.0, t.icon);
}
if eye_resp.clicked() {
actions.push(match index {
None => ("layer.smartFilter.disableSmartFilters".into(), json!({"layer": l.id.0})),