fix: index records instead of rescanning growing vectors in imports, exports and commands

This commit is contained in:
Dylan M. Taylor committed 2026-11-03 11:26:15 +00:00
1 parent 327c4cc82e
commit fe65d6067f
18 files changed
+164 -62

No files matched your search

+2
View File
@@ -357,6 +357,8 @@ fn remove_entries(b: &mut [u8], ifd: &Ifd0, removed: &[usize]) {
let Some(old) = b.get(ifd.first..table_end.saturating_add(next_bytes)).map(<[u8]>::to_vec) else { return };
let mut table = Vec::with_capacity(old.len());
let mut kept = 0usize;
// Many malformed entries make both lists long: a scan of `removed` per entry was quadratic.
let removed: std::collections::HashSet<usize> = removed.iter().copied().collect();
for (i, entry) in old.chunks_exact(eb).take(ifd.count).enumerate() {
if !removed.contains(&(ifd.first + i * eb)) {
table.extend_from_slice(entry);
+23 -13
View File
@@ -167,24 +167,30 @@ impl TextStyles {
/// "Character Style N" / "Paragraph Style N" with the first unused N.
pub fn unique_name(&self, paragraph: bool, base: &str) -> String {
let taken = |n: &str| {
if paragraph {
n == BASIC_PARAGRAPH || self.paragraph.iter().any(|s| s.name == n)
} else {
n == NO_CHARACTER_STYLE || self.character.iter().any(|s| s.name == n)
}
// Collected once: with N occupied names the search tries up to N + 1 candidates, and
// scanning the styles for each was quadratic.
let names: std::collections::HashSet<&str> = if paragraph {
self.paragraph.iter().map(|s| s.name.as_str()).chain([BASIC_PARAGRAPH]).collect()
} else {
self.character.iter().map(|s| s.name.as_str()).chain([NO_CHARACTER_STYLE]).collect()
};
(1..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default()
(1..).map(|i| format!("{base} {i}")).find(|n| !names.contains(n.as_str())).unwrap_or_default()
}
/// Paragraph attributes from Basic Paragraph and `para` (a missing id falls back to Basic
/// Paragraph). The result references `para`.
pub fn resolve_para(&self, para: Option<u32>) -> ParagraphStyle {
self.resolve_para_def(para.and_then(|id| self.para_style(id)))
}
/// [`resolve_para`](Self::resolve_para) given the definition itself (a listing has it in
/// hand, and looking each up by id again is a scan of the styles per style).
pub fn resolve_para_def(&self, para: Option<&ParagraphStyleDef>) -> ParagraphStyle {
let mut s = apply_attrs(&ParagraphStyle::default(), &self.basic.para_attrs).unwrap_or_default();
if let Some(def) = para.and_then(|id| self.para_style(id)) {
if let Some(def) = para {
s = apply_attrs(&s, &def.para_attrs).unwrap_or(s);
}
s.style_sheet = para.filter(|id| *id != 0 && self.para_style(*id).is_some());
s.style_sheet = para.map(|d| d.id).filter(|id| *id != 0);
s
}
@@ -192,16 +198,20 @@ impl TextStyles {
/// for an unset family) ← Basic Paragraph ← paragraph style ← character style. The result
/// references `chr`.
pub fn resolve_char(&self, para: Option<u32>, chr: Option<u32>, default_family: &str) -> CharStyle {
self.resolve_char_def(para.and_then(|id| self.para_style(id)), chr.and_then(|id| self.char_style(id)), default_family)
}
/// [`resolve_char`](Self::resolve_char) given the definitions themselves.
pub fn resolve_char_def(&self, para: Option<&ParagraphStyleDef>, chr: Option<&CharacterStyleDef>, default_family: &str) -> CharStyle {
let base = CharStyle { font_family: default_family.to_string(), ..Default::default() };
let mut s = apply_attrs(&base, &self.basic.char_attrs).unwrap_or(base);
if let Some(def) = para.and_then(|id| self.para_style(id)).filter(|d| d.id != 0) {
if let Some(def) = para.filter(|d| d.id != 0) {
s = apply_attrs(&s, &def.char_attrs).unwrap_or(s);
}
let chr = chr.filter(|id| self.char_style(*id).is_some());
if let Some(def) = chr.and_then(|id| self.char_style(id)) {
if let Some(def) = chr {
s = apply_attrs(&s, &def.attrs).unwrap_or(s);
}
s.style_sheet = chr;
s.style_sheet = chr.map(|d| d.id);
s
}
+4 -3
View File
@@ -1026,14 +1026,15 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
}
s.analysis.next_measurement += 1;
let keep = s.analysis.data_points.of(source).to_vec();
let mut ids = Vec::new();
// The new rows are the appended suffix: a fragmented selection makes many rows, and
// matching each against the whole log by id was quadratic.
let first_new = s.analysis.log.len();
for mut m in rows {
m.retain(|k, _| keep.iter().any(|x| x == k));
s.analysis.next_row += 1;
ids.push(s.analysis.next_row);
s.analysis.log.push(LogRow { id: s.analysis.next_row, values: m });
}
let new: Vec<&LogRow> = s.analysis.log.iter().filter(|r| ids.contains(&r.id)).collect();
let new = &s.analysis.log[first_new..];
Ok(json!({"source": source, "rows": new}))
}
+8 -4
View File
@@ -463,16 +463,20 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result<
let patterns: Vec<_> = copies.patterns.iter().filter(|pat| !d.doc.patterns.iter().any(|q| q.id == pat.id)).cloned().collect();
// A copied smart object may name a PSD-embedded linked file; land its `lnk` block too (#3584).
let mut linked = Vec::new();
// The destination's records by block key, collected once: a copy keeps duplicate records,
// and checking each against every destination record was quadratic in their number.
let mut present: std::collections::HashMap<[u8; 4], std::collections::HashSet<&[u8]>> = std::collections::HashMap::new();
for (_, dk, dd) in d.doc.metadata.psd_global_blocks.iter().filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE")) {
present.entry(*dk).or_default().extend(photocraft_io::linked::records(dd));
}
for (signature, key, data) in copies.metadata.psd_global_blocks.iter().filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE")) {
if d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && std::sync::Arc::ptr_eq(dd, data)) {
continue;
}
// The clipboard may contain a subset of a destination block. Compare complete records,
// so copying one layer in the same document does not duplicate large embedded files.
let missing = photocraft_io::linked::select_items(data, &|_, raw| {
!d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && photocraft_io::linked::contains_item(dd, raw))
})
.map_err(|e| EngineError::Other(format!("Could not paste smart-object contents: {e}; the document was not changed")))?;
let missing = photocraft_io::linked::select_items(data, &|_, raw| !present.get(key).is_some_and(|set| set.contains(raw)))
.map_err(|e| EngineError::Other(format!("Could not paste smart-object contents: {e}; the document was not changed")))?;
let missing = missing.map(std::sync::Arc::new).unwrap_or_else(|| data.clone());
if !missing.is_empty() {
linked.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to paste smart-object source records".into()))?;
+17 -6
View File
@@ -260,25 +260,36 @@ fn export_import(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let (mut nb, mut ns) = (0, 0);
// Merge by name through an index built once: a file of many distinct names must not
// rescan the growing library for each (quadratic, on the command thread).
if want("brushes") {
let mut by_name: std::collections::HashMap<String, usize> = s.tools.presets.iter().enumerate().map(|(i, x)| (x.name.clone(), i)).collect();
for mut b in file.brushes {
// Nested folders as the commands bound them (a hand-edited file can't build an
// absurd tree).
b.folder.retain(|f| !f.trim().is_empty());
b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH);
match s.tools.presets.iter_mut().find(|x| x.name == b.name) {
Some(x) => *x = b,
None => s.tools.presets.push(b),
match by_name.get(&b.name) {
Some(&i) => s.tools.presets[i] = b,
None => {
by_name.insert(b.name.clone(), s.tools.presets.len());
s.tools.presets.push(b);
}
}
nb += 1;
}
s.brush_presets_changed();
}
if want("customShapes") {
let mut by_name: std::collections::HashMap<String, usize> =
s.edit_state.custom_shapes.iter().enumerate().map(|(i, x)| (x.name.clone(), i)).collect();
for c in file.custom_shapes {
match s.edit_state.custom_shapes.iter_mut().find(|x| x.name == c.name) {
Some(x) => *x = c,
None => s.edit_state.custom_shapes.push(c),
match by_name.get(&c.name) {
Some(&i) => s.edit_state.custom_shapes[i] = c,
None => {
by_name.insert(c.name.clone(), s.edit_state.custom_shapes.len());
s.edit_state.custom_shapes.push(c);
}
}
ns += 1;
}
+3 -1
View File
@@ -10,8 +10,10 @@ use crate::{EngineError, Result, Session};
/// Append incoming groups whose name the library doesn't already have; returns how many were added.
fn merge_groups<T>(cur: &mut Vec<Group<T>>, incoming: Vec<Group<T>>) -> usize {
let mut added = 0;
// Names seen so far: a file of many distinct groups must not rescan the growing library.
let mut names: std::collections::HashSet<String> = cur.iter().map(|e| e.name.clone()).collect();
for g in incoming {
if !cur.iter().any(|e| e.name == g.name) {
if names.insert(g.name.clone()) {
cur.push(g);
added += 1;
}
+21 -6
View File
@@ -48,6 +48,25 @@ impl PatternLibrary {
None => self.items.push(pat),
}
}
/// [`upsert`](Self::upsert) each of `pats`, finding the ids through one index rather than a
/// scan of the library per pattern (a `.pat` of many patterns made the import quadratic).
pub fn upsert_all(&mut self, pats: impl IntoIterator<Item = Pattern>) {
let mut by_id: std::collections::HashMap<String, usize> = self.items.iter().enumerate().map(|(i, q)| (q.id.clone(), i)).collect();
for pat in pats {
self.stored.remove(&pat.id);
match by_id.get(&pat.id) {
Some(&i) => {
self.items[i] = pat;
self.pixels_rev += 1;
}
None => {
by_id.insert(pat.id.clone(), self.items.len());
self.items.push(pat);
}
}
}
}
}
/// Whether `p` is a built-in pattern as shipped (same id, name, size and pixels): those are never
@@ -409,12 +428,8 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) => return Err(bad(cmd, "missing `path` (.pat file) or `data`")),
};
let pats = photocraft_io::pattern_map::read_pat(&bytes).map_err(EngineError::Other)?;
let mut ids = Vec::new();
for pat in pats {
ids.push(pat.id.clone());
s.patterns.stored.remove(&pat.id);
s.patterns.upsert(pat);
}
let ids: Vec<String> = pats.iter().map(|pat| pat.id.clone()).collect();
s.patterns.upsert_all(pats);
Ok(json!({"imported": ids, "count": ids.len()}))
}
+14 -4
View File
@@ -18,6 +18,7 @@
//! PostScript file (`m`/`L`/`C` path construction, `n`/`N` unpainted closed/open paths, `*u`/`*U`
//! compound paths), following the public PostScript Language Reference and the AI3 format notes.
use std::collections::{HashMap, HashSet};
use std::io::Write as _;
mod windows_marks;
@@ -1392,23 +1393,28 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
let links_dir = join(&folder, "Links");
// Copy every linked file once; relink the copy of the document to the copies.
let mut copied: Vec<(String, String)> = Vec::new();
// Indexes of `copied` and `missing`: a document names many links, and scanning the lists for
// every layer made packaging quadratic in their number.
let mut copied_by_source: HashMap<String, String> = HashMap::new();
let mut copied_names: HashSet<String> = HashSet::new();
let mut relinks: Vec<(photocraft_doc::LayerId, String)> = Vec::new();
let mut missing = Vec::new();
let mut missing_set: HashSet<String> = HashSet::new();
for (_, _, l) in doc.walk() {
let LayerContent::Smart(so) = &l.content else { continue };
let SmartSource::Linked { path } = &so.source else { continue };
if missing.contains(path) {
if missing_set.contains(path) {
continue;
}
let target = match copied.iter().find(|(src, _)| src == path) {
Some((_, t)) => t.clone(),
let target = match copied_by_source.get(path) {
Some(t) => t.clone(),
None => {
// A name no earlier copy has, ignoring case (macOS and Windows folders do): a
// renamed copy can't take the name of another link either. A file already in
// Links (an earlier package into the same folder) is never overwritten.
let base = file_name(path);
let taken = |n: &str| {
copied.iter().any(|(_, t)| file_name(t).to_lowercase() == n.to_lowercase())
copied_names.contains(&n.to_lowercase())
|| std::path::Path::new(&join(&links_dir, n)).exists()
|| std::fs::read_dir(&links_dir)
.ok()
@@ -1427,6 +1433,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
// A path that is not followed is packaged as missing, like a file that is gone.
let Ok(file) = crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)) else {
missing.push(path.clone());
missing_set.insert(path.clone());
continue;
};
// Only a file PhotoCraft can place is copied; anything else is packaged as missing.
@@ -1434,10 +1441,13 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
Some(bytes) => {
write_file(&t, &bytes)?;
copied.push((path.clone(), t.clone()));
copied_by_source.insert(path.clone(), t.clone());
copied_names.insert(fname.to_lowercase());
t
}
None => {
missing.push(path.clone());
missing_set.insert(path.clone());
continue;
}
}
+2 -5
View File
@@ -52,11 +52,8 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(IMPORT, "the file holds no styles"));
}
// Everything is checked: change the library.
let mut pattern_ids = Vec::new();
for pat in imp.patterns {
pattern_ids.push(pat.id.clone());
s.patterns.upsert(pat);
}
let pattern_ids: Vec<String> = imp.patterns.iter().map(|pat| pat.id.clone()).collect();
s.patterns.upsert_all(imp.patterns);
let styles = &mut s.presets.styles;
if replace {
styles.retain(|g| g.name != group);
+6 -2
View File
@@ -621,9 +621,12 @@ pub fn missing_fonts(doc: &Document) -> Vec<String> {
}
let mut engine = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());
let mut out: Vec<String> = Vec::new();
// Families listed so far, so a document of many distinct missing families does not rescan
// the list per run while holding the shared engine.
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for t in layers {
for r in t.char_runs() {
if style_font_missing(&mut engine.fonts, &r.style) && !out.contains(&r.style.font_family) {
if style_font_missing(&mut engine.fonts, &r.style) && seen.insert(r.style.font_family.clone()) {
out.push(r.style.font_family);
}
}
@@ -635,8 +638,9 @@ pub fn missing_fonts(doc: &Document) -> Vec<String> {
pub fn missing_fonts_in_layer(t: &TextLayer) -> Vec<String> {
let mut engine = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());
let mut out: Vec<String> = Vec::new();
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
for r in t.char_runs() {
if style_font_missing(&mut engine.fonts, &r.style) && !out.contains(&r.style.font_family) {
if style_font_missing(&mut engine.fonts, &r.style) && seen.insert(r.style.font_family.clone()) {
out.push(r.style.font_family);
}
}
+2 -2
View File
@@ -403,11 +403,11 @@ fn styles(s: &Session) -> Result<TextStyles> {
}
fn char_json(d: &CharacterStyleDef, styles: &TextStyles) -> Value {
json!({ "id": d.id, "name": d.name, "attrs": d.attrs, "resolved": styles.resolve_char(None, Some(d.id), FAMILY) })
json!({ "id": d.id, "name": d.name, "attrs": d.attrs, "resolved": styles.resolve_char_def(None, Some(d), FAMILY) })
}
fn para_json(d: &ParagraphStyleDef, styles: &TextStyles) -> Value {
json!({ "id": d.id, "name": d.name, "paragraphAttrs": d.para_attrs, "characterAttrs": d.char_attrs, "resolved": { "paragraph": styles.resolve_para(Some(d.id)), "character": styles.resolve_char(Some(d.id), None, FAMILY) } })
json!({ "id": d.id, "name": d.name, "paragraphAttrs": d.para_attrs, "characterAttrs": d.char_attrs, "resolved": { "paragraph": styles.resolve_para_def(Some(d)), "character": styles.resolve_char_def(Some(d), None, FAMILY) } })
}
fn list(s: &Session, p: &Value, paragraph: bool) -> Result<Value> {
+5 -1
View File
@@ -48,8 +48,12 @@ pub struct AslImport {
/// Patterns an effect list refers to: `(name, id)` in first-use order, without repeats.
pub fn referenced_patterns(effects: &[Effect]) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
// Seen ids and (for references without an id) names: a style of many pattern strokes must
// not rescan the list per reference.
let (mut ids, mut names): (HashSet<String>, HashSet<String>) = (HashSet::new(), HashSet::new());
let mut push = |name: &str, id: &str| {
if !out.iter().any(|(n, i)| if id.is_empty() { n == name } else { i == id }) {
let new = if id.is_empty() { names.insert(name.to_string()) } else { ids.insert(id.to_string()) };
if new {
out.push((name.to_string(), id.to_string()));
}
};
+10 -3
View File
@@ -71,15 +71,22 @@ fn groups(bytes: &[u8]) -> Result<Vec<Group>, IoError> {
continue;
}
let mut found: Vec<Group> = Vec::new();
// Prefix → slot in `found`, so a file of many prefixes is grouped in one pass.
let mut slots: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for c in &part.channels {
let Some((prefix, base)) = channel_base_split(&c.name) else { continue };
if prefix.chars().last().is_some_and(|ch| ch.is_ascii_digit()) {
continue;
}
if found.iter_mut().all(|g| g.prefix != prefix) {
found.push(Group { prefix: prefix.to_string(), part: part.index, channels: Vec::new(), alpha: None });
// Only RGB(A) channels make or join a group; other suffixes never add an entry.
if !matches!(base, "R" | "G" | "B" | "A") {
continue;
}
let Some(group) = found.iter_mut().find(|g| g.prefix == prefix) else { continue };
let slot = *slots.entry(prefix).or_insert_with(|| {
found.push(Group { prefix: prefix.to_string(), part: part.index, channels: Vec::new(), alpha: None });
found.len() - 1
});
let group = &mut found[slot];
match base {
"R" | "G" | "B" => group.channels.push(c.name.clone()),
"A" => group.alpha = Some(c.name.clone()),
+19 -1
View File
@@ -140,7 +140,10 @@ pub fn embedded_payload_in_blocks<'a>(blocks: impl IntoIterator<Item = (&'a [u8;
let mut r = Rd { d: data, p: 0 };
while let Some(len) = r.u64().and_then(|n| usize::try_from(n).ok()) {
let Some(item) = r.take(len) else { break };
if let Some((id, name, bytes)) = item_data(item)
// The uuid comes first in the record: compare it before decoding the file name and
// descriptor, which a lookup per layer would otherwise repeat for every record.
if item_uuid(item).as_deref() == Some(uuid)
&& let Some((id, name, bytes)) = item_data(item)
&& id == uuid
{
return Some((name, bytes));
@@ -172,6 +175,10 @@ fn find_slice_in_blocks<'a>(blocks: impl IntoIterator<Item = (&'a [u8; 4], &'a [
while let Some(len) = r.u64() {
let Ok(len) = usize::try_from(len) else { return None };
let item = r.take(len)?;
if item_uuid(item).as_deref() != Some(uuid) {
r.p = r.p.next_multiple_of(4);
continue;
}
let found = item_header(item).filter(|h| h.0 == uuid).and_then(|(id, name, start, n)| Some((id, name, item.get(start..start.checked_add(n)?)?)));
if found.is_some() {
return found;
@@ -413,6 +420,17 @@ fn selection_uuid<'a>(item: &'a [u8], raw: &[u8], keep: &dyn Fn(&str, &[u8]) ->
}
}
/// Every complete raw record of a block (length prefix and padding included), without decoding
/// their file bytes: what [`contains_item`] compares against, for a caller with many lookups.
pub fn records(data: &[u8]) -> impl Iterator<Item = &[u8]> {
let mut remaining = data;
std::iter::from_fn(move || {
let (_, raw) = framed_item(remaining)?;
remaining = remaining.get(raw.len()..).unwrap_or_default();
Some(raw)
})
}
/// Whether a complete raw record already occurs in a block, without decoding its file bytes.
pub fn contains_item(data: &[u8], record: &[u8]) -> bool {
let mut remaining = data;
+9 -2
View File
@@ -51,6 +51,9 @@ pub(super) struct Class {
name: String,
names: Vec<String>,
primitives: Vec<Option<u8>>,
/// Member name → first position: a layer array can look fields up in one object of many
/// members thousands of times, and a scan of `names` per lookup was quadratic.
index: HashMap<String, usize>,
}
#[derive(Debug)]
@@ -100,7 +103,7 @@ impl Graph {
pub fn optional_field<'a>(&'a self, value: &'a Value, name: &str) -> Result<Option<&'a Value>> {
match self.resolve(value)? {
Value::Object { class, members } => Ok(class.names.iter().position(|n| n == name).and_then(|i| members.get(i))),
Value::Object { class, members } => Ok(class.index.get(name).and_then(|&i| members.get(i))),
_ => Err(invalid("expected a serialized object")),
}
}
@@ -362,7 +365,11 @@ impl Parser<'_, '_> {
if matches!(tag, 3 | 5) {
self.reader.le_i32()?;
}
let class = Arc::new(Class { name, names, primitives });
let mut index = HashMap::with_capacity(names.len());
for (i, n) in names.iter().enumerate() {
index.entry(n.clone()).or_insert(i);
}
let class = Arc::new(Class { name, names, primitives, index });
if self.classes.insert(id, class.clone()).is_some() {
return Err(invalid("duplicate class metadata"));
}
+11 -6
View File
@@ -62,8 +62,9 @@ pub(crate) struct Ctx<'a> {
pub dpi: f32,
/// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning).
pub txt2: Option<photocraft_text::engine_data::Value>,
/// Smart-filter caches from the global `FEid`/`FXid` blocks (filter masks, by placed id).
pub filter_effects: Vec<photocraft_psd::filter_effects::FilterEffectsItem>,
/// Smart-filter caches from the global `FEid`/`FXid` blocks (filter masks, by placed id;
/// the first item of an id wins).
pub filter_effects: std::collections::HashMap<String, photocraft_psd::filter_effects::FilterEffectsItem>,
/// Filter masks already decoded, by placed id: every layer of a source reads the same item, and
/// a surface clones by sharing its tiles.
pub filter_masks: std::collections::HashMap<String, Option<LayerMask>>,
@@ -408,7 +409,7 @@ impl Ctx<'_> {
if let Some(done) = self.filter_masks.get(placed) {
return done.clone();
}
let item = self.filter_effects.iter().find(|i| i.id == placed)?;
let item = self.filter_effects.get(placed)?;
let mask = match crate::smart_map::mask_from_item(item, self.mask_fmt.sample, stack) {
Ok(m) => m,
Err(e) => {
@@ -672,7 +673,7 @@ impl Ctx<'_> {
None => {
// Every distinct source is kept until the import ends, so what they add up to is
// bounded: past the limit the layer keeps its stored pixels, unmixed.
let item = self.filter_effects.iter().find(|i| i.id == p.placed);
let item = self.filter_effects.get(&p.placed);
let cost = item
.and_then(|i| i.rect.size().ok())
.map_or(0, |(w, h)| (w as u64).saturating_mul(h as u64).saturating_mul(self.fmt.bytes_per_pixel() as u64));
@@ -1266,7 +1267,7 @@ fn psd_to_document_global(
fatal_error: None,
dpi: doc.resolution_dpi,
txt2: global.iter().find(|(_, k, _)| k == b"Txt2").and_then(|(_, _, d)| photocraft_text::psd::parse_txt2(d)),
filter_effects: Vec::new(),
filter_effects: Default::default(),
filter_masks: Default::default(),
unfiltered: Default::default(),
unfiltered_bytes: 0,
@@ -1287,7 +1288,11 @@ fn psd_to_document_global(
return None;
}
match photocraft_psd::filter_effects::FilterEffects::parse(data) {
Ok(fx) => cx.filter_effects.extend(fx.items),
Ok(fx) => {
for item in fx.items {
cx.filter_effects.entry(item.id.clone()).or_insert(item);
}
}
Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", String::from_utf8_lossy(key))),
}
}
+1 -1
View File
@@ -580,7 +580,7 @@ fn only_allocation_failures_are_fatal_to_a_layer_channel() {
fatal_error: None,
dpi: 72.0,
txt2: None,
filter_effects: Vec::new(),
filter_effects: Default::default(),
filter_masks: Default::default(),
unfiltered: Default::default(),
unfiltered_bytes: 0,
+7 -2
View File
@@ -16,6 +16,9 @@ pub fn import(doc: &mut Document) -> Vec<String> {
let mut styles = std::mem::take(&mut doc.text_styles);
let mut char_ids: HashMap<String, u32> = styles.character.iter().map(|d| (d.name.clone(), d.id)).collect();
let mut para_ids: HashMap<String, u32> = styles.paragraph.iter().map(|d| (d.name.clone(), d.id)).collect();
// The next free ids, found once: asking the styles for each new sheet scanned every style
// added so far (quadratic in the number of named sheets a file brings).
let (mut next_char, mut next_para) = (styles.next_char_id(), styles.next_para_id());
let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
for id in ids {
let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) else { continue };
@@ -29,10 +32,11 @@ pub fn import(doc: &mut Document) -> Vec<String> {
let id = if let Some(id) = char_ids.get(name).copied() {
id
} else {
let Some(id) = styles.next_char_id() else {
let Some(id) = next_char else {
warnings.push(format!("character style {:?} was not imported: style id space exhausted", name));
continue;
};
next_char = id.checked_add(1);
let mut attrs = diff_attrs(st, &sh.normal_char);
attrs.remove("postscript_name");
styles.character.push(CharacterStyleDef { id, name: name.clone(), attrs });
@@ -46,10 +50,11 @@ pub fn import(doc: &mut Document) -> Vec<String> {
let id = if let Some(id) = para_ids.get(name).copied() {
id
} else {
let Some(id) = styles.next_para_id() else {
let Some(id) = next_para else {
warnings.push(format!("paragraph style {:?} was not imported: style id space exhausted", name));
continue;
};
next_para = id.checked_add(1);
let mut char_attrs = cs.as_ref().map(|c| diff_attrs(c, &sh.normal_char)).unwrap_or_default();
char_attrs.remove("postscript_name");
styles.paragraph.push(ParagraphStyleDef { id, name: name.clone(), para_attrs: diff_attrs(p, &sh.normal_para), char_attrs });