Address review: pass-through folders, read budget, unique ids, picker

- Folders are sent as pass-through groups. TextureCraft folders blend
  their children with the layers below and mix the result in by their
  opacity whatever their mode, so an isolated Normal group rendered
  Multiply children differently. A new or changed group blend mode on
  the way back only gets a note; opacity is still applied.
- The PSD reader charges a pixel record's interleaved image against the
  decode budget, so a record with a huge rectangle and no channels is
  refused instead of allocating gigabytes.
- Undo and redo keep the project's next layer id at its highest value,
  so a layer made after undoing a PhotoCraft update can't take an id
  the hand-off record still names.
- The layer row offers the channel picker for a paint layer with no
  channel on even when the displayed channel is the one holding its
  pixels.
This commit is contained in:
Rafael Mendes committed 2026-11-10 16:30:16 -03:00
1 parent 4d98621c9d
commit 22e3df4b40
7 files changed
+146 -50

No files matched your search

+44 -1
View File
@@ -788,6 +788,10 @@ mod tests {
execute(&mut s, "layer.rename", &json!({"layer": fill.0, "name": "Red"})).unwrap();
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap();
// TextureCraft folders blend their children with what is below them whatever their mode,
// so even a Normal folder is a pass-through group in the PSD.
let folder = s.doc.project.locate(fill).unwrap().1.unwrap();
execute(&mut s, "layer.blend", &json!({"layer": folder.0, "channel": "all", "mode": "Normal", "opacity": 0.5})).unwrap();
let r = execute(&mut s, SEND, &json!({"dir": dir.path().display().to_string(), "channels": ["baseColor", "roughness"], "open": false})).unwrap();
let files = r["files"].as_array().unwrap();
assert_eq!(files.len(), 1, "{r}");
@@ -799,6 +803,8 @@ mod tests {
// Top-first: the folder holding "Red", then the project's first paint layer.
assert_eq!(doc.layers.len(), 2, "{:?}", doc.layers.iter().map(|l| &l.name).collect::<Vec<_>>());
assert!(find(children(&doc.layers[0]), "Red").is_some());
assert_eq!(&doc.layers[0].blend, b"pass");
assert!((doc.layers[0].opacity - 0.5).abs() < 0.01);
assert_eq!(doc.layers[1].name, "Layer 1");
// A paint layer without a mask hides nothing, so its group has no mask (also where it
// holds no paint).
@@ -1012,6 +1018,40 @@ mod tests {
assert!(execute(&mut s, "layer.assignChannel", &json!({"layer": folder.0, "channel": "roughness"})).is_err());
}
#[test]
fn a_layer_made_after_undoing_an_update_is_not_taken_for_the_undone_one() {
let dir = tempdir("psd_undo");
let mut s = session();
let (path, doc) = send_psd(&mut s, &dir);
let (w, h) = s.caches[0].size;
let with = |px: [u16; 4]| {
let mut layers = vec![psd::Layer { id: 1, ..new_layer("Base Color", (w, h), px, true) }];
layers.extend(doc.layers.iter().map(|n| rewrite(n, (w, h))));
layers
};
save(&path, with([0, 65535, 0, 65535]), (w, h), 1);
assert_eq!(s.sync_photocraft().len(), 1);
let imported = by_name(&s, "Base Color");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
// A layer made now must not get the undone layer's id...
execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap();
let fill = s.selected_layer().unwrap();
assert_ne!(fill, imported);
// ...so the next save, which still names that id, leaves the fill alone.
save(&path, with([65535, 0, 0, 65535]), (w, h), 2);
assert_eq!(s.sync_photocraft().len(), 1);
let l = s.doc.project.layer(fill).unwrap();
assert!(matches!(l.kind, LayerKind::Fill(_)));
assert!(l.channels.contains_key(&Channel::Roughness) && l.channels.contains_key(&Channel::BaseColor), "{:?}", l.channels);
let again = by_name(&s, "Base Color");
assert!(s.doc.pixels.layer(again, Channel::BaseColor).is_some());
// Redo after an undo hands out no id twice either.
execute(&mut s, "edit.undo", &Value::Null).unwrap();
execute(&mut s, "edit.redo", &Value::Null).unwrap();
let next = s.doc.project.next_id;
assert!(s.doc.project.layers.keys().all(|id| id.0 < next));
}
#[test]
fn edits_to_sent_layers_change_those_layers_and_removals_remove_them() {
let dir = tempdir("psd_edit");
@@ -1054,7 +1094,10 @@ mod tests {
assert!(s.log.iter().any(|l| l.contains("now a paint layer")), "{:?}", s.log);
// One undo brings it all back.
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.doc.project, before.project);
let mut restored = s.doc.project.clone();
restored.next_id = before.project.next_id;
assert_eq!(restored, before.project);
assert!(s.doc.project.next_id >= before.project.next_id, "ids are not handed out twice");
}
#[test]
+10 -11
View File
@@ -209,19 +209,18 @@ impl Tree<'_> {
}
let node = match &layer.kind {
LayerKind::Group { children, .. } => {
// A folder has one blend mode and opacity in the PSD; TextureCraft has one per channel.
let first = enabled.first().map(|(_, b)| *b).unwrap_or_default();
let uniform = enabled.iter().all(|(_, b)| b.mode == first.mode && (b.opacity - first.opacity).abs() < 1e-4);
let (blend, opacity) = if uniform {
let (key, note) = psd_key(first.mode);
if let Some(note) = note {
self.warn(&layer.name, note);
}
(key, first.opacity)
// A TextureCraft folder blends its children with the layers below it and then mixes
// the result in by its opacity, whatever its mode: a pass-through group. An
// isolated PSD group would render a Multiply child differently. The PSD has one
// opacity per group; TextureCraft has one per channel.
let first = enabled.first().map(|(_, b)| b.opacity).unwrap_or(1.0);
let opacity = if enabled.iter().all(|(_, b)| (b.opacity - first).abs() < 1e-4) {
first
} else {
self.warn(&layer.name, "the folder blends its channels differently; it is sent as a pass-through group at 100%");
(*b"pass", 1.0)
self.warn(&layer.name, "the folder's channels have different opacities; it is sent at 100%");
1.0
};
let blend = *b"pass";
let id_ = self.id(Role::Folder(id));
let children = self.nodes(children, depth + 1)?;
psd::Layer {
+14 -10
View File
@@ -182,10 +182,10 @@ impl Apply<'_> {
let id = self.s.doc.project.alloc_id();
let mut layer = Layer::new(id, node.name.clone(), LayerKind::Group { children: Vec::new(), collapsed: false }, &self.channels);
layer.visible = node.visible;
let mode = if &node.blend == b"pass" { BlendMode::Passthrough } else { mode_of(&node.blend) };
for b in layer.channels.values_mut() {
*b = ChannelBlend { mode, opacity: node.opacity };
*b = ChannelBlend { mode: BlendMode::Passthrough, opacity: node.opacity };
}
self.isolated_note(node);
self.s.doc.project.layers.insert(id, layer);
self.placed.insert(id);
let grid = self.grid(node.mask.as_ref(), inherit);
@@ -225,23 +225,27 @@ impl Apply<'_> {
(rec.is_some_and(|r| r.blend != node.blend), rec.is_some_and(|r| r.opacity != opacity))
}
/// A folder's opacity, when PhotoCraft changed it. Folders always pass through in
/// TextureCraft, so another blend mode on the group only gets a note.
fn folder_blend(&mut self, f: LayerId, node: &ReadLayer) -> Result<()> {
let (blend, opacity) = self.changed_blend(node);
if !blend && !opacity {
return Ok(());
if blend {
self.isolated_note(node);
}
let mode = if &node.blend == b"pass" { BlendMode::Passthrough } else { mode_of(&node.blend) };
for b in self.layer_mut(f)?.channels.values_mut().filter(|b| b.mode != BlendMode::Disable) {
if blend {
b.mode = mode;
}
if opacity {
if opacity {
for b in self.layer_mut(f)?.channels.values_mut().filter(|b| b.mode != BlendMode::Disable) {
b.opacity = node.opacity;
}
}
Ok(())
}
fn isolated_note(&mut self, node: &ReadLayer) {
if &node.blend != b"pass" {
self.note(format!("\"{}\": folders in TextureCraft pass through, so the group's blend mode is not kept", node.name));
}
}
/// The mask of `node`, when PhotoCraft changed it.
fn mask(&mut self, id: LayerId, node: &ReadLayer) -> Result<()> {
if self.sent_of(node).is_some_and(|r| r.mask == record(node, Role::Folder(id)).mask) {
+3
View File
@@ -672,6 +672,9 @@ impl Session {
}
fn after_history(&mut self, other: &Document) {
// Ids are never handed out twice, even after an undo: links outside the document (such as
// a PhotoCraft hand-off's record) name layers by id, and must not find a later layer.
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
+48 -5
View File
@@ -901,11 +901,14 @@ pub fn read_psd(bytes: &[u8]) -> Result<ReadDocument> {
_ => {}
}
}
let pixels = (rec.section.is_none() || rec.section == Some(0)).then(|| ReadKind::Pixels {
x: rec.rect.1,
y: rec.rect.0,
image: interleave(&planes, (rw, rh)),
});
let pixels = if rec.section.is_none() || rec.section == Some(0) {
// The interleaved image is allocated whatever channels the record has.
let need = (rw as u64).saturating_mul(rh as u64).saturating_mul(8);
budget = budget.checked_sub(need).ok_or_else(|| FormatError::TooLarge("the document's layers are too large to read back".into()))?;
Some(ReadKind::Pixels { x: rec.rect.1, y: rec.rect.0, image: interleave(&planes, (rw, rh)) })
} else {
None
};
let mask = match rec.mask {
Some((mrect, default, true)) => {
let (mw, mh) = rect_size(mrect)?;
@@ -1117,6 +1120,46 @@ mod tests {
assert_eq!(&image.data[4..8], &[10 * 257, 20 * 257, 30 * 257, 65535]);
}
#[test]
fn a_huge_layer_without_channels_is_refused_before_it_is_allocated() {
// One pixel layer claiming 30000×30000 texels but storing no channels: nothing to decode,
// yet its image would take 7 GB.
let mut rec = Vec::new();
for v in [0, 0, 30000, 30000] {
rec.i32(v);
}
rec.u16(0);
rec.bytes(b"8BIMnorm");
rec.bytes(&[255, 0, 8, 0]);
rec.u32(12);
rec.u32(0); // no mask
rec.u32(0); // no blending ranges
rec.bytes(&[0, 0, 0, 0]); // empty name, padded
let mut info = Vec::new();
info.i16(1);
info.bytes(&rec);
let mut section = Vec::new();
section.u32(info.len() as u32);
section.bytes(&info);
section.u32(0);
let mut f = Vec::new();
f.bytes(b"8BPS");
f.u16(1);
f.bytes(&[0; 6]);
f.u16(4);
f.u32(1);
f.u32(1);
f.u16(16);
f.u16(3);
f.u32(0);
f.u32(0);
f.u32(section.len() as u32);
f.bytes(&section);
f.u16(0);
f.bytes(&[0; 8]);
assert!(matches!(read_psd(&f), Err(FormatError::TooLarge(_))), "{:?}", read_psd(&f).map(|d| d.layers.len()));
}
#[test]
fn hostile_input_is_an_error() {
assert!(read_psd(b"").is_err());
+19 -18
View File
@@ -448,7 +448,25 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let ch = app.ui.layer_channel;
let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0));
let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0));
if let Some(b) = blend {
// A paint layer with no channel on (its name named none) offers the picker even when the
// displayed channel is the one holding its pixels.
if let Some(choices) = channel_choices(app, layer) {
let r = ui
.interact(blend_rect.union(op_rect), ui.scope_id().with(("assign", layer.id.0)), Sense::click())
.on_hover_text(tr("This layer has no channel on: choose the channel its painting is for"));
p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, ic::WARNING, egui::FontId::proportional(12.0), tk.warning);
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim);
egui::Popup::menu(&r).show(|ui| {
ui.set_min_width(160.0);
ui.label(RichText::new(tr("Choose channel")).strong());
for c in choices {
if ui.button(tr(c.label())).clicked() {
app.run("layer.assignChannel", json!({"layer": layer.id.0, "channel": c.id()}));
ui.close();
}
}
});
} else if let Some(b) = blend {
let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel"));
p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text);
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim);
@@ -478,23 +496,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
if r.changed() {
app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0}));
}
} else if let Some(choices) = channel_choices(app, layer) {
// A paint layer brought in with no channel on (its name named none): pick one here.
let r = ui
.interact(blend_rect.union(op_rect), ui.scope_id().with(("assign", layer.id.0)), Sense::click())
.on_hover_text(tr("This layer has no channel on: choose the channel its painting is for"));
p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, ic::WARNING, egui::FontId::proportional(12.0), tk.warning);
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim);
egui::Popup::menu(&r).show(|ui| {
ui.set_min_width(160.0);
ui.label(RichText::new(tr("Choose channel")).strong());
for c in choices {
if ui.button(tr(c.label())).clicked() {
app.run("layer.assignChannel", json!({"layer": layer.id.0, "channel": c.id()}));
ui.close();
}
}
});
} else {
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim);
}
+8 -5
View File
@@ -346,8 +346,10 @@ else on `PATH`). The menu item sends every texture set.
written from the public file format specification), holding every channel so that a mask edited
once shapes all of them:
- Every folder is a group, with the folder's mask and, when all its channels blend alike, their
blend mode and opacity (otherwise a pass-through group at 100%, with a warning).
- Every folder is a pass-through group with the folder's mask and, when all its channels share one,
its opacity (otherwise 100%, with a warning). A TextureCraft folder blends its children with the
layers below it and mixes the result in by its opacity, whatever its mode, which is what a
pass-through group does; an isolated group would render a Multiply child differently.
- Every layer is a pass-through group of the same name. The layer's mask (painted, generators,
filters, geometry and height masks included) is the group's own editable layer mask; it is left
out when it hides nothing.
@@ -373,13 +375,14 @@ stack** in one undo step:
- A group sent as a folder stays that folder, and a group sent as a layer stays that layer; their
names, visibility, order and masks follow the document. An edited mask becomes a painted mask
(generators and filters it had are replaced by the result). A folder's changed blend mode or
opacity applies to all its channels; a layer group's changed opacity scales its channels'.
(generators and filters it had are replaced by the result). A folder's changed opacity
applies to all its channels (a blend mode other than pass-through only gets a note, since
folders always pass through); a layer group's changed opacity scales its channels'.
- A channel pixel layer whose pixels changed becomes that channel's paint. A fill, instance or
other procedural layer becomes a paint layer first, keeping its other channels as they rendered
(its content effects are baked in). A changed blend mode or opacity applies to that channel. A
removed channel layer turns the channel off.
- A new group becomes a folder (pass-through stays pass-through). A new pixel layer becomes a paint
- A new group becomes a pass-through folder with its opacity and mask. A new pixel layer becomes a paint
layer of the same name, painted in the channel its name says: an id or label in any case and
spacing (`Base Color`, `base_color 2`, `rough copy`) or a common name (`Albedo`, `Diffuse`,
`Bump`, `Metalness`, `Gloss`, ...). Its transparency and own mask become its coverage. When the