refactor: split complex functions in styles, affinity text and warp

- style.presets.apply: resolve effects and patterns in one helper, and write each layer in another
- affinity text read: move the per-block character collection into block_chars
- Warp::is_identity: check a mesh and a row of its samples in helpers, with the same tolerance test

No behaviour change.
This commit is contained in:
Dylan M. Taylor committed 2026-10-25 21:30:16 -04:00
1 parent dc213b1f8a
commit eda25468df
3 files changed
+114 -81

No files matched your search

+28 -21
View File
@@ -4,7 +4,7 @@
use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect};
use crate::paint::{self, Paint};
use crate::stream::{ObjId, Value};
use crate::stream::{ObjId, Stream, Value};
/// Characters read per text node (stories are split into blocks; this caps hostile ones).
const MAX_CHARS: usize = 1 << 20;
@@ -21,26 +21,7 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
let mut placeholders = false;
for block in s.objs(story, b"Blok") {
let glyphs = s.obj(block, b"Glyp")?;
let chars: Vec<char> = match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let mut v = Vec::new();
// One past the allowance is enough to trip the check below; shared segments
// repeated by reference must not expand beyond it first.
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
for seg in s.objs(glyphs, b"Mixd") {
if v.len() >= room {
break;
}
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len())));
placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len())));
}
v
}
};
let chars = block_chars(s, glyphs, total, &mut placeholders);
total = total.checked_add(chars.len())?;
if total > MAX_CHARS {
r.warn("text longer than a million characters (truncated)");
@@ -84,6 +65,32 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
}
/// The characters of one text block. A block without a UTF-8 string is a list of segments: each
/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once
/// `total` plus these characters would pass the cap.
fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec<char> {
match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let mut v = Vec::new();
// One past the allowance is enough to trip the check below; shared segments
// repeated by reference must not expand beyond it first.
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
for seg in s.objs(glyphs, b"Mixd") {
if v.len() >= room {
break;
}
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len())));
*placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len())));
}
v
}
}
}
fn slot<T: Copy>(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option<T>) -> Option<T> {
match v? {
Value::Array(a) => a.get(i).and_then(f),
+46 -35
View File
@@ -6,7 +6,7 @@
//! `layer.layerStyle.*`.
use photocraft_color::{BlendMode, ColorMode, SampleType};
use photocraft_doc::{Document, Effect, Layer, Size};
use photocraft_doc::{Document, Effect, Layer, Pattern, Size};
use photocraft_geom::Rect;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -170,19 +170,12 @@ fn targets(s: &Session, p: &Value) -> Vec<photocraft_doc::LayerId> {
crate::layer_multi_cmds::selected(s)
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "style.presets.apply";
let style = find_style(s, p, CMD)?.clone();
let add = p.get("add").and_then(Value::as_bool).unwrap_or(false);
let ids = targets(s, p);
if ids.is_empty() {
return Err(bad(CMD, "no target layers"));
}
// Pattern overlays name their pattern; resolve to library patterns copied into the document.
/// Resolves each effect's pattern, plus the patterns that strokes and bevels name, copied from the library.
fn resolve_style_effects(s: &Session, fx_list: &[Effect]) -> Result<(Vec<Effect>, Vec<Pattern>)> {
let mut effects = Vec::new();
let mut pats = Vec::new();
for fx in style.effects {
let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?;
for fx in fx_list {
let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx.clone())?;
effects.push(fx);
pats.extend(pat);
}
@@ -192,6 +185,46 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
pats.push(pat);
}
}
Ok((effects, pats))
}
/// Writes a preset onto one layer: replaces its effects, or appends to them when `add`.
fn apply_to_layer(l: &mut Layer, style: &StylePreset, effects: &[Effect], add: bool) {
if add {
l.effects.items.extend(effects.iter().cloned());
} else {
l.effects.items = effects.to_vec();
l.effects.psd_raw = None;
}
l.effects.psd_raw = None;
l.effects.enabled = true;
// Adding keeps the layer's blending unless the preset carries some: a blend mode, or
// an Opacity saved on its own (`style.presets.new` with `includeBlending: false`).
if !add || style.blend.is_some() || style.opacity.is_some() {
if let Some(b) = style.blend {
l.blend = b;
}
if let Some(f) = style.fill_opacity {
l.fill_opacity = f;
} else if !add {
l.fill_opacity = 1.0;
}
if let Some(o) = style.opacity {
l.opacity = o;
}
}
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "style.presets.apply";
let style = find_style(s, p, CMD)?.clone();
let add = p.get("add").and_then(Value::as_bool).unwrap_or(false);
let ids = targets(s, p);
if ids.is_empty() {
return Err(bad(CMD, "no target layers"));
}
// Pattern overlays name their pattern; resolve to library patterns copied into the document.
let (effects, pats) = resolve_style_effects(s, &style.effects)?;
let label = format!("Apply Style: {}", style.name);
s.edit(&label, |doc, _| {
for pat in &pats {
@@ -204,29 +237,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
// Styles can't sit on the Background: Photoshop turns it into a normal layer first.
crate::extra_cmds::background_to_layer(doc, *id);
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
if add {
l.effects.items.extend(effects.iter().cloned());
} else {
l.effects.items = effects.clone();
l.effects.psd_raw = None;
}
l.effects.psd_raw = None;
l.effects.enabled = true;
// Adding keeps the layer's blending unless the preset carries some: a blend mode, or
// an Opacity saved on its own (`style.presets.new` with `includeBlending: false`).
if !add || style.blend.is_some() || style.opacity.is_some() {
if let Some(b) = style.blend {
l.blend = b;
}
if let Some(f) = style.fill_opacity {
l.fill_opacity = f;
} else if !add {
l.fill_opacity = 1.0;
}
if let Some(o) = style.opacity {
l.opacity = o;
}
}
apply_to_layer(l, &style, &effects, add);
}
Ok(())
})?;
+40 -25
View File
@@ -1047,6 +1047,12 @@ pub struct Warp {
pub values: Vec<f64>,
}
/// Relative to the magnitude so the fit's rounding at large origins isn't rejected.
fn point_fits(expected: [f64; 2], actual: [f64; 2]) -> bool {
let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6);
!((actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1]))
}
impl Warp {
/// No warp over `bounds`.
pub fn none(bounds: [f64; 4]) -> Warp {
@@ -1080,36 +1086,45 @@ impl Warp {
WarpStyle::None => true,
WarpStyle::Custom | WarpStyle::Cylinder => match &self.mesh {
None => true,
Some(m) => {
if !m.is_valid() {
return false;
}
let nx = m.nx();
let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1);
for pj in 0..pr {
for j in 0..4 {
let v = m.vs[pj] + (m.vs[pj + 1] - m.vs[pj]) * j as f64 / 3.0;
for pi in 0..pc {
for i in 0..4 {
let u = m.us[pi] + (m.us[pi + 1] - m.us[pi]) * i as f64 / 3.0;
let expected = self.box_point(u, v);
let actual = m.points[(3 * pj + j) * nx + 3 * pi + i];
// Relative to the magnitude so the fit's rounding at large origins isn't rejected.
let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6);
if (actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1]) {
return false;
}
}
}
}
}
true
}
Some(m) => self.mesh_is_box_fit(m),
},
_ => self.style_warp().is_none(),
}
}
/// True when every control point of `m` sits where the box's own grid puts it.
fn mesh_is_box_fit(&self, m: &BezierMesh) -> bool {
if !m.is_valid() {
return false;
}
let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1);
for pj in 0..pr {
for j in 0..4 {
if !self.mesh_row_is_box_fit(m, pj, j, pc) {
return false;
}
}
}
true
}
/// One sample row (`j` within patch row `pj`) of [`Self::mesh_is_box_fit`].
fn mesh_row_is_box_fit(&self, m: &BezierMesh, pj: usize, j: usize, pc: usize) -> bool {
let nx = m.nx();
let v = m.vs[pj] + (m.vs[pj + 1] - m.vs[pj]) * j as f64 / 3.0;
for pi in 0..pc {
for i in 0..4 {
let u = m.us[pi] + (m.us[pi + 1] - m.us[pi]) * i as f64 / 3.0;
let expected = self.box_point(u, v);
let actual = m.points[(3 * pj + j) * nx + 3 * pi + i];
if !point_fits(expected, actual) {
return false;
}
}
}
true
}
fn box_point(&self, s: f64, t: f64) -> [f64; 2] {
let b = self.bounds;
[b[0] + s * (b[2] - b[0]), b[1] + t * (b[3] - b[1])]