Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Fix document run and ID overflow (#684, #685) (#749)

Alex Gorevski3ad26e3b51a8
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 2d3cbf656..5d038b1c4 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -310,7 +310,7 @@ fn normalize_runs<S: Clone>(text: &str, runs: Vec<(usize, S)>, base: S) -> Vec<(
if at >= total {
break;
}
- let mut end = (at + len).min(total);
+ let mut end = at.saturating_add(len).min(total);
while !text.is_char_boundary(end) {
end += 1;
}
@@ -877,6 +877,34 @@ mod tests {
assert_eq!(b.pixel_format().mode, ColorMode::Grayscale);
}
+ #[test]
+ fn text_runs_with_maximal_lengths_normalize_to_text_length() {
+ let t = TextLayer {
+ text: "ab".into(),
+ runs: vec![
+ text::TextRun { len: 1, style: text::CharStyle::default() },
+ text::TextRun { len: usize::MAX, style: text::CharStyle { size_pt: 24.0, ..Default::default() } },
+ ],
+ paragraphs: vec![
+ text::ParagraphRun { len: 1, style: text::ParagraphStyle::default() },
+ text::ParagraphRun { len: usize::MAX, style: text::ParagraphStyle { align: text::TextAlign::Center, ..Default::default() } },
+ ],
+ ..Default::default()
+ };
+
+ let chars = t.char_runs();
+ assert_eq!(chars.iter().map(|r| r.len).sum::<usize>(), t.text.len());
+ assert_eq!(chars.len(), 2);
+ assert_eq!(chars[1].len, 1);
+ assert_eq!(chars[1].style.size_pt, 24.0);
+
+ let paragraphs = t.paragraph_runs();
+ assert_eq!(paragraphs.iter().map(|r| r.len).sum::<usize>(), t.text.len());
+ assert_eq!(paragraphs.len(), 2);
+ assert_eq!(paragraphs[1].len, 1);
+ assert_eq!(paragraphs[1].style.align, text::TextAlign::Center);
+ }
+
#[test]
fn insert_remove_shift() {
let mut d = doc();
diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs
index 5890dbc3a..2705bdf5f 100644
--- a/crates/doc/src/slices.rs
+++ b/crates/doc/src/slices.rs
@@ -140,8 +140,9 @@ impl Slices {
self.list.is_empty()
}
/// A fresh slice id (Photoshop counts from 1; auto slices use ids too, so leave room).
- pub fn next_id(&self) -> u32 {
- self.list.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ /// Returns `None` when the stored ids have exhausted the `u32` id space.
+ pub fn next_id(&self) -> Option<u32> {
+ self.list.iter().map(|s| s.id).max().unwrap_or(0).checked_add(1)
}
pub fn get(&self, id: u32) -> Option<&Slice> {
self.list.iter().find(|s| s.id == id)
@@ -301,4 +302,12 @@ mod tests {
d.slices.list[0].name = "logo".into();
assert!(resolve(&d).iter().any(|s| s.name == "logo"));
}
+
+ #[test]
+ fn exhausted_slice_id_survives_serialization() {
+ let slices = Slices { list: vec![Slice { id: u32::MAX, ..Default::default() }], ..Default::default() };
+ let value = serde_json::to_value(&slices).unwrap();
+ let loaded: Slices = serde_json::from_value(value).unwrap();
+ assert_eq!(loaded.next_id(), None);
+ }
}
diff --git a/crates/doc/src/text_styles.rs b/crates/doc/src/text_styles.rs
index debfdeb20..bb85ef2f2 100644
--- a/crates/doc/src/text_styles.rs
+++ b/crates/doc/src/text_styles.rs
@@ -155,14 +155,14 @@ impl TextStyles {
if id == 0 { Some(&mut self.basic) } else { self.paragraph.iter_mut().find(|s| s.id == id) }
}
- /// A fresh character style id.
- pub fn next_char_id(&self) -> u32 {
- self.character.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ /// A fresh character style id, or `None` when the stored ids exhaust the `u32` id space.
+ pub fn next_char_id(&self) -> Option<u32> {
+ self.character.iter().map(|s| s.id).max().unwrap_or(0).checked_add(1)
}
- /// A fresh paragraph style id.
- pub fn next_para_id(&self) -> u32 {
- self.paragraph.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ /// A fresh paragraph style id, or `None` when the stored ids exhaust the `u32` id space.
+ pub fn next_para_id(&self) -> Option<u32> {
+ self.paragraph.iter().map(|s| s.id).max().unwrap_or(0).checked_add(1)
}
/// "Character Style N" / "Paragraph Style N" with the first unused N.
@@ -312,7 +312,7 @@ mod tests {
fn names_and_ids() {
let s = styles();
assert_eq!(s.unique_name(false, "Character Style"), "Character Style 1");
- assert_eq!((s.next_char_id(), s.next_para_id()), (2, 2));
+ assert_eq!((s.next_char_id(), s.next_para_id()), (Some(2), Some(2)));
assert_eq!(s.para_style(0).unwrap().name, BASIC_PARAGRAPH);
let v = serde_json::to_value(&s).unwrap();
let back: TextStyles = serde_json::from_value(v).unwrap();
@@ -320,4 +320,15 @@ mod tests {
let empty: TextStyles = serde_json::from_str("{}").unwrap();
assert_eq!(empty.basic.name, BASIC_PARAGRAPH);
}
+
+ #[test]
+ fn exhausted_style_ids_survive_serialization() {
+ let mut s = TextStyles::default();
+ s.character.push(CharacterStyleDef { id: u32::MAX, ..Default::default() });
+ s.paragraph.push(ParagraphStyleDef { id: u32::MAX, ..Default::default() });
+ let value = serde_json::to_value(&s).unwrap();
+ let loaded: TextStyles = serde_json::from_value(value).unwrap();
+ assert_eq!(loaded.next_char_id(), None);
+ assert_eq!(loaded.next_para_id(), None);
+ }
}
diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/slice_cmds.rs
index 67e2e5358..68011b347 100644
--- a/crates/engine/src/slice_cmds.rs
+++ b/crates/engine/src/slice_cmds.rs
@@ -22,6 +22,10 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
+fn exhausted_id() -> EngineError {
+ EngineError::Other("slice id space exhausted".into())
+}
+
// ---------- predicates ----------
fn has_doc(s: &Session) -> std::result::Result<(), String> {
@@ -200,7 +204,7 @@ fn target(s: &mut Session, p: &Value, cmd: &str, promote: bool) -> Result<u32> {
None if promote => {
let rect = r.rect;
s.edit("Promote to User Slice", |doc, _| {
- let id = doc.slices.next_id();
+ let id = doc.slices.next_id().ok_or_else(exhausted_id)?;
doc.slices.list.push(Slice { id, rect, ..Default::default() });
Ok(id)
})
@@ -238,7 +242,7 @@ fn new_slice(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "the slice is outside the canvas"));
}
let id = s.edit("Slice", |doc, _| {
- let id = doc.slices.next_id();
+ let id = doc.slices.next_id().ok_or_else(exhausted_id)?;
let mut sl = Slice { id, rect, ..Default::default() };
apply_options(&mut sl, p, cmd)?;
sl.rect = rect;
@@ -275,7 +279,7 @@ fn from_guides(s: &mut Session) -> Result<Value> {
// Photoshop replaces every existing slice.
doc.slices.list.clear();
for r in rects {
- let id = doc.slices.next_id();
+ let id = doc.slices.next_id().ok_or_else(exhausted_id)?;
doc.slices.list.push(Slice { id, rect: r, ..Default::default() });
}
Ok(())
@@ -369,13 +373,23 @@ fn divide(s: &mut Session, p: &Value) -> Result<Value> {
doc.slices.list.retain(|sl| sl.id != id);
let mut ids = Vec::new();
let mut parts = Vec::new();
+ let mut next_id = doc.slices.next_id();
for j in 0..down {
for i in 0..across {
let x0 = r.x0 + (r.width() as i32 * i) / across;
let x1 = r.x0 + (r.width() as i32 * (i + 1)) / across;
let y0 = r.y0 + (r.height() as i32 * j) / down;
let y1 = r.y0 + (r.height() as i32 * (j + 1)) / down;
- let nid = if ids.is_empty() { id } else { doc.slices.next_id().max(ids.iter().copied().max().unwrap_or(0) + 1) };
+ let nid = if ids.is_empty() {
+ id
+ } else {
+ let mut candidate = next_id.ok_or_else(exhausted_id)?;
+ if candidate == id {
+ candidate = candidate.checked_add(1).ok_or_else(exhausted_id)?;
+ }
+ next_id = candidate.checked_add(1);
+ candidate
+ };
ids.push(nid);
// The first part keeps the original's options; the others start fresh.
let base = if parts.is_empty() { Slice { origin: SliceOrigin::User, layer: None, ..src.clone() } } else { Slice::default() };
@@ -409,7 +423,7 @@ fn layer_based(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("Could not create a layer based slice because the layer is empty".into()));
}
let id = s.edit("New Layer Based Slice", |doc, _| {
- let id = doc.slices.next_id();
+ let id = doc.slices.next_id().ok_or_else(exhausted_id)?;
let text = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
doc.slices.list.push(Slice {
id,
diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/slice_cmds/tests.rs
index 7e6c80326..9b6a1bd12 100644
--- a/crates/engine/src/slice_cmds/tests.rs
+++ b/crates/engine/src/slice_cmds/tests.rs
@@ -158,3 +158,28 @@ fn slices_round_trip_through_psd_and_pcraft() {
assert_eq!(ls.rect, Rect::new(50, 40, 70, 60));
}
}
+
+#[test]
+fn exhausted_slice_ids_fail_without_mutating_document_or_history() {
+ let mut s = session(8);
+ s.edit("loaded max slice", |doc, _| {
+ doc.slices.list.push(Slice { id: 1, rect: Rect::new(10, 10, 20, 20), ..Default::default() });
+ doc.slices.list.push(Slice { id: u32::MAX, rect: Rect::new(10, 10, 20, 20), ..Default::default() });
+ Ok(())
+ })
+ .unwrap();
+ let past = s.active().unwrap().history.past_len();
+ let revision = s.active().unwrap().revision;
+
+ for (command, params) in [
+ ("slice.new", json!({"rect": [30, 30, 10, 10]})),
+ ("slice.divide", json!({"slice": 1, "horizontal": 1, "vertical": 2})),
+ ("slice.promote", json!({"number": 1})),
+ ] {
+ assert!(s.execute(command, params).unwrap_err().to_string().contains("slice id space exhausted"), "{command}");
+ assert_eq!(doc(&s).slices.list.len(), 2, "{command}");
+ assert!(doc(&s).slices.get(u32::MAX).is_some(), "{command}");
+ assert_eq!(s.active().unwrap().history.past_len(), past, "{command}");
+ assert_eq!(s.active().unwrap().revision, revision, "{command}");
+ }
+}
diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/type_styles_cmds.rs
index f54116c99..64ba6d87a 100644
--- a/crates/engine/src/type_styles_cmds.rs
+++ b/crates/engine/src/type_styles_cmds.rs
@@ -26,6 +26,10 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
+fn exhausted_id(paragraph: bool) -> EngineError {
+ EngineError::Other(format!("{} style id space exhausted", if paragraph { "paragraph" } else { "character" }))
+}
+
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
}
@@ -443,11 +447,11 @@ fn new_style(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
.map(str::to_string)
.unwrap_or_else(|| st.unique_name(paragraph, if paragraph { "Paragraph Style" } else { "Character Style" }));
let id = if paragraph {
- let id = st.next_para_id();
+ let id = st.next_para_id().ok_or_else(|| exhausted_id(true))?;
st.paragraph.push(ParagraphStyleDef { id, name: name.clone(), para_attrs: pa, char_attrs: ca });
id
} else {
- let id = st.next_char_id();
+ let id = st.next_char_id().ok_or_else(|| exhausted_id(false))?;
st.character.push(CharacterStyleDef { id, name: name.clone(), attrs: ca });
id
};
@@ -481,14 +485,14 @@ fn duplicate(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
let (new_id, name) = if paragraph {
let src = st.para_style(id).cloned().unwrap_or_default();
let name = format!("{} copy", src.name);
- let nid = st.next_para_id();
+ let nid = st.next_para_id().ok_or_else(|| exhausted_id(true))?;
let pos = st.paragraph.iter().position(|d| d.id == id).map_or(0, |i| i + 1);
st.paragraph.insert(pos, ParagraphStyleDef { id: nid, name: name.clone(), ..src });
(nid, name)
} else {
let src = st.char_style(id).cloned().unwrap_or_default();
let name = format!("{} copy", src.name);
- let nid = st.next_char_id();
+ let nid = st.next_char_id().ok_or_else(|| exhausted_id(false))?;
let pos = st.character.iter().position(|d| d.id == id).map_or(0, |i| i + 1);
st.character.insert(pos, CharacterStyleDef { id: nid, name: name.clone(), ..src });
(nid, name)
diff --git a/crates/engine/src/type_styles_cmds/tests.rs b/crates/engine/src/type_styles_cmds/tests.rs
index 216458049..cbb2ddbe1 100644
--- a/crates/engine/src/type_styles_cmds/tests.rs
+++ b/crates/engine/src/type_styles_cmds/tests.rs
@@ -169,3 +169,23 @@ fn shared_attribute_names_accept_both_spellings() {
let p = s.active().unwrap().doc.text_styles.resolve_para(Some(r["id"].as_u64().unwrap() as u32));
assert_eq!((p.align, p.direction), (photocraft_doc::text::TextAlign::Center, photocraft_doc::text::TextDirection::Rtl));
}
+
+#[test]
+fn exhausted_style_ids_return_errors_without_history_changes() {
+ let (mut s, _) = session("x");
+ let mut doc = (*s.active().unwrap().doc).clone();
+ doc.text_styles.character.push(CharacterStyleDef { id: u32::MAX, name: "Max".into(), ..Default::default() });
+ doc.text_styles.paragraph.push(ParagraphStyleDef { id: u32::MAX, name: "Max".into(), ..Default::default() });
+ s.active_mut().unwrap().doc = std::sync::Arc::new(doc);
+ let past = s.active().unwrap().history.past_len();
+ let revision = s.active().unwrap().revision;
+
+ assert!(s.execute("type.characterStyle.new", json!({"fromSelection": false})).unwrap_err().to_string().contains("character style id space exhausted"));
+ assert!(s.execute("type.characterStyle.duplicate", json!({"id": u32::MAX})).unwrap_err().to_string().contains("character style id space exhausted"));
+ assert!(s.execute("type.paragraphStyle.new", json!({"fromSelection": false})).unwrap_err().to_string().contains("paragraph style id space exhausted"));
+ assert!(s.execute("type.paragraphStyle.duplicate", json!({"id": u32::MAX})).unwrap_err().to_string().contains("paragraph style id space exhausted"));
+ assert_eq!(s.active().unwrap().history.past_len(), past);
+ assert_eq!(s.active().unwrap().revision, revision);
+ assert_eq!(s.active().unwrap().doc.text_styles.next_char_id(), None);
+ assert_eq!(s.active().unwrap().doc.text_styles.next_para_id(), None);
+}
diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs
index 4a19ab3fa..dd70fe320 100644
--- a/crates/format/tests/roundtrip.rs
+++ b/crates/format/tests/roundtrip.rs
@@ -3,7 +3,9 @@
mod common;
use common::*;
use photocraft_color::{ColorMode, SampleType};
-use photocraft_doc::{Document, Layer, LayerId};
+use photocraft_doc::text::{CharStyle, ParagraphStyle, TextRun};
+use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId, Slice, TextLayer};
use photocraft_format::*;
use photocraft_raster::Rgba8Image;
@@ -102,6 +104,37 @@ fn empty_document_roundtrips() {
assert_eq!(load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap(), doc);
}
+#[test]
+fn exhausted_document_ids_and_maximal_text_runs_roundtrip() {
+ let mut doc = Document::new("exhausted", photocraft_doc::Size::new(2, 1), ColorMode::Rgb, SampleType::U8);
+ doc.slices.list.push(Slice { id: u32::MAX, ..Default::default() });
+ doc.text_styles.character.push(CharacterStyleDef { id: u32::MAX, ..Default::default() });
+ doc.text_styles.paragraph.push(ParagraphStyleDef { id: u32::MAX, ..Default::default() });
+ doc.layers.push(Layer::new(
+ "Text",
+ LayerContent::Text(TextLayer {
+ text: "ab".into(),
+ runs: vec![TextRun { len: 1, style: CharStyle::default() }, TextRun { len: usize::MAX, style: CharStyle { size_pt: 24.0, ..Default::default() } }],
+ paragraphs: vec![
+ photocraft_doc::text::ParagraphRun { len: 1, style: ParagraphStyle::default() },
+ photocraft_doc::text::ParagraphRun { len: usize::MAX, style: ParagraphStyle::default() },
+ ],
+ ..Default::default()
+ }),
+ ));
+
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let loaded = load_from_bytes(&bytes).unwrap();
+ assert_eq!(loaded.slices.next_id(), None);
+ assert_eq!(loaded.text_styles.next_char_id(), None);
+ assert_eq!(loaded.text_styles.next_para_id(), None);
+ let LayerContent::Text(text) = &loaded.layers.last().unwrap().content else { panic!("text layer must roundtrip") };
+ assert_eq!(text.char_runs().iter().map(|r| r.len).sum::<usize>(), text.text.len());
+ assert_eq!(text.char_runs()[1].len, 1);
+ assert_eq!(text.char_runs()[1].style.size_pt, 24.0);
+ assert_eq!(text.paragraph_runs().iter().map(|r| r.len).sum::<usize>(), text.text.len());
+}
+
#[test]
fn zip_incremental_only_new_tiles() {
let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16);
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index 6074a5f9e..09291ece9 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -1257,7 +1257,10 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -
global_blocks.push(tb);
}
let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc));
- let slices_resource = crate::slices_map::export_resource(doc, &ex.layer_ids);
+ let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids);
+ if let Some(warning) = slices_warning {
+ ex.warnings.push(warning);
+ }
for (id, name, data) in &doc.metadata.psd_resources {
// Layer comps: the preserved list while unchanged, else regenerated (or dropped) below.
if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() {
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 45ec96251..3307cd3cb 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -721,7 +721,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
// Slices (resource 1050), after layer ids are known; the raw data stays for verbatim export.
crate::slices_map::import(&mut doc);
// Character and paragraph styles from the type layers' engine data.
- crate::text_styles_map::import(&mut doc);
+ cx.warnings.extend(crate::text_styles_map::import(&mut doc));
if ctl.cancelled() {
return None;
diff --git a/crates/io/src/slices_map.rs b/crates/io/src/slices_map.rs
index 06bfd9155..8069c63e5 100644
--- a/crates/io/src/slices_map.rs
+++ b/crates/io/src/slices_map.rs
@@ -65,12 +65,12 @@ pub fn unchanged(doc: &Document) -> bool {
/// The resource to write: `None` keeps the preserved one, `Some(None)` drops it, `Some(Some)` is
/// a fresh resource. `layer_ids` maps document layers to the PSD layer ids being written.
-pub fn export_resource(doc: &Document, layer_ids: &HashMap<LayerId, u32>) -> Option<Option<Vec<u8>>> {
+pub fn export_resource(doc: &Document, layer_ids: &HashMap<LayerId, u32>) -> (Option<Option<Vec<u8>>>, Option<String>) {
if unchanged(doc) {
- return None;
+ return (None, None);
}
if doc.slices.is_empty() {
- return Some(None);
+ return (Some(None), None);
}
let mut records: Vec<SliceRecord> = doc
.slices
@@ -104,12 +104,34 @@ pub fn export_resource(doc: &Document, layer_ids: &HashMap<LayerId, u32>) -> Opt
})
.collect();
let taken: Vec<Rect> = doc.slices.list.iter().map(|s| s.rect).collect();
- for (id, r) in (doc.slices.next_id()..).zip(slices::auto_slices(doc.bounds(), &taken)) {
+ let mut used: std::collections::HashSet<u32> = doc.slices.list.iter().map(|s| s.id).collect();
+ // Keep the usual above-max numbering when possible; if stored ids include u32::MAX, use the
+ // first available id instead of wrapping or colliding with a reserved one.
+ let mut next_id = doc.slices.next_id().or(Some(1));
+ let mut omitted_auto_slices = false;
+ for r in slices::auto_slices(doc.bounds(), &taken) {
+ let Some(mut id) = next_id else {
+ omitted_auto_slices = true;
+ break;
+ };
+ while used.contains(&id) {
+ let Some(next) = id.checked_add(1) else {
+ omitted_auto_slices = true;
+ break;
+ };
+ id = next;
+ }
+ if omitted_auto_slices {
+ break;
+ }
+ used.insert(id);
+ next_id = id.checked_add(1);
records.push(SliceRecord { id, origin: 0, kind: 1, rect: [r.x0, r.y0, r.x1, r.y1], ..Default::default() });
}
let group_name = if doc.slices.group_name.is_empty() { slices::base_name(doc) } else { doc.slices.group_name.clone() };
let res = SlicesResource { version: 6, bounds: [0, 0, doc.size.height as i32, doc.size.width as i32], group_name, slices: records };
- Some(Some(res.to_bytes()))
+ let warning = omitted_auto_slices.then(|| "auto slices omitted because the slice id space is exhausted".to_string());
+ (Some(Some(res.to_bytes())), warning)
}
#[cfg(test)]
@@ -142,7 +164,9 @@ mod tests {
..Default::default()
});
let ids: HashMap<LayerId, u32> = [(lid, 5)].into_iter().collect();
- let data = export_resource(&d, &ids).unwrap().unwrap();
+ let (data, warning) = export_resource(&d, &ids);
+ assert!(warning.is_none());
+ let data = data.unwrap().unwrap();
// Read back into a copy of the document without slices.
let mut back = d.clone();
back.slices = Slices::default();
@@ -150,6 +174,20 @@ mod tests {
import(&mut back);
assert_eq!(back.slices.list, d.slices.list);
assert!(unchanged(&back));
- assert!(export_resource(&back, &ids).is_none(), "unchanged → keep the raw resource");
+ assert_eq!(export_resource(&back, &ids), (None, None), "unchanged → keep the raw resource");
+ }
+
+ #[test]
+ fn auto_slice_ids_do_not_collide_with_maximal_stored_id() {
+ let mut d = Document::new("site.psd", Size::new(120, 90), ColorMode::Rgb, SampleType::U8);
+ d.slices.list.push(Slice { id: u32::MAX, rect: Rect::new(10, 10, 20, 20), ..Default::default() });
+ let (resource, warning) = export_resource(&d, &HashMap::new());
+ assert!(warning.is_none());
+ let data = resource.flatten().expect("a changed document writes a resource");
+ let decoded = SlicesResource::from_bytes(&data).expect("resource is valid");
+ let ids: Vec<u32> = decoded.slices.iter().map(|s| s.id).collect();
+ assert!(ids.contains(&u32::MAX));
+ assert!(ids.contains(&1));
+ assert_eq!(ids.iter().collect::<std::collections::HashSet<_>>().len(), ids.len());
}
}
diff --git a/crates/io/src/text_styles_map.rs b/crates/io/src/text_styles_map.rs
index 8919114ab..26e251b82 100644
--- a/crates/io/src/text_styles_map.rs
+++ b/crates/io/src/text_styles_map.rs
@@ -10,7 +10,8 @@ use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef, diff_att
use photocraft_doc::{Document, LayerContent, LayerId, TextLayer, TextStyles};
/// Builds `doc.text_styles` from the type layers' engine data and links the runs.
-pub fn import(doc: &mut Document) {
+pub fn import(doc: &mut Document) -> Vec<String> {
+ let mut warnings = Vec::new();
let dpi = doc.resolution_dpi;
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();
@@ -25,29 +26,42 @@ pub fn import(doc: &mut Document) {
let Some(sh) = photocraft_text::psd_styles::read_style_sheets(&raw, dpi) else { continue };
let mut cmap: HashMap<usize, u32> = HashMap::new();
for (ix, name, st) in &sh.char_sheets {
- let id = *char_ids.entry(name.clone()).or_insert_with(|| {
- let id = styles.next_char_id();
+ let id = if let Some(id) = char_ids.get(name).copied() {
+ id
+ } else {
+ let Some(id) = styles.next_char_id() else {
+ warnings.push(format!("character style {:?} was not imported: style id space exhausted", name));
+ continue;
+ };
let mut attrs = diff_attrs(st, &sh.normal_char);
attrs.remove("postscript_name");
styles.character.push(CharacterStyleDef { id, name: name.clone(), attrs });
+ char_ids.insert(name.clone(), id);
id
- });
+ };
cmap.insert(*ix, id);
}
let mut pmap: HashMap<usize, u32> = HashMap::new();
for (ix, name, p, cs) in &sh.para_sheets {
- let id = *para_ids.entry(name.clone()).or_insert_with(|| {
- let id = styles.next_para_id();
+ let id = if let Some(id) = para_ids.get(name).copied() {
+ id
+ } else {
+ let Some(id) = styles.next_para_id() else {
+ warnings.push(format!("paragraph style {:?} was not imported: style id space exhausted", name));
+ continue;
+ };
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 });
+ para_ids.insert(name.clone(), id);
id
- });
+ };
pmap.insert(*ix, id);
}
link(t, &sh.run_char, &sh.run_char_lens, &cmap, &sh.run_para, &pmap);
}
doc.text_styles = styles;
+ warnings
}
fn link(