feat: write unnamed colours and gradients only when something refers to them

IDML writes a colour or gradient without a name only if a value in the
package refers to it, a gradient stop or tint uses the colour, or the
page item defaults name it in one of the two entry tables of chunk
0x6E07 (objects.md, colours; preferences.md). The graphic part is now
written last, from the references in the other parts; the second table
of chunk 0x6E07 is read.

compare.py, trustworthy pairs: extra values 155,956 -> 33,181 (unnamed
Color -114,734, Gradient -3,498, GradientStop -4,543). 463 values are
no longer reproduced: 10 unnamed colours and 22 unnamed gradients with
their stops that IDML writes though nothing refers to them (open, see
objects.md). Value coverage 92.46 % -> 92.45 %. No conversion or schema
failures; story text 18,509/18,610.

The previous commit (09e87fa), measured alone: extra values 635,511 ->
155,956, value coverage 92.41 % -> 92.46 %; 39 values lost (7 opacity
stops and 8 drop shadows IDML writes with values equal to the style,
5 StrokeWeight, 1 TextColumnFixedWidth).
This commit is contained in:
aiongg committed 2026-10-07 22:33:58 +00:00
1 parent 09e87fadea
commit 8b0f46837b
6 files changed
+155 -16

No files matched your search

+23
View File
@@ -1778,6 +1778,29 @@ Unnamed colours are referenced by UID (`Color/u93`). All 1,296 colours in
the pairs match on `Model`, `Space`, `ColorValue`, `ColorOverride`,
`Name` and the three flags.
**Which unnamed colours IDML writes.** A colour without a name is in the
IDML only if a value written in the package refers to it (an attribute
or element text `Color/u…`; a tint counts), if a stop of any gradient
refers to it, even of an unnamed gradient that IDML leaves out (below),
or if an entry of class 0x1F05 in one of the two tables of the
page item defaults (`preferences.md`) names it with either UID. Over the
489 trustworthy pairs, of the unnamed colours the converter wrote:
| | In the IDML | Not in the IDML |
|---|---:|---:|
| Referenced by the output | 2,309 | 0 |
| Not referenced, named in a page item defaults table | 564 | 0 |
| Neither | 10 | 8,684 |
All colours, written or not, are in the swatch list of the preferences
object (class 0x2202, chunk 0x1F02), and the colour objects of the two
groups have the same chunks and flags, so neither decides it. Named
colours are always written. Unnamed gradients follow the same rule with
class 0x5503: 457 unnamed gradients are referenced nowhere and named in
no table, and none is in the IDML; 526 of the 548 unnamed gradients
IDML writes meet the rule (the other 22 are open). Their stops go with
them.
**Model codes.** The 250 distinct little-endian files hold 13,067
colours with chunk 0x1F09: 12,814 with code 0, 250 with code 2 (one
`Registration` colour per file) and 3 with code 1. Two of the three are
+6 -1
View File
@@ -217,7 +217,12 @@ The 601 files without it have `true`.
The object of class 0x6E07 has a chunk 0x6E07: u32, u32, u32 *n*, *n*
12-byte entries, then a page item attribute list (u32 count, records;
`attributes.md`) and more data. The list has the attribute IDs of page
`attributes.md`), then u32, u32, u32 *m* and *m* entries of the same
layout. An entry is u32 class, u32 UID, u32 UID. In every sample the
first table has entries for classes 0x1F05 (colour), 0x5503 (gradient),
0x5533, 0x6E0B (`None`) and 0x6E11. The entries name the unnamed colours
and gradients that IDML writes though nothing refers to them
(`objects.md`, colours). The list has the attribute IDs of page
items. Written with the page item attribute table, it gives
`PageItemDefault` `StrokeWeight` in 628 of 628 files in which an
analysis script found the list; over all pairs the converter reproduces
+40 -1
View File
@@ -132,7 +132,6 @@ pub fn write(doc: &Document, name: &str, out: impl std::io::Write) -> std::io::R
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n\t<rootfiles>\n\t\t<rootfile full-path=\"designmap.xml\" media-type=\"text/xml\">\n\t\t</rootfile>\n\t</rootfiles>\n</container>".into(),
);
files.insert("designmap.xml".into(), w.designmap(name));
files.insert("Resources/Graphic.xml".into(), w.graphic());
files.insert("Resources/Fonts.xml".into(), w.fonts());
files.insert("Resources/Styles.xml".into(), w.styles());
files.insert("Resources/Preferences.xml".into(), w.preferences());
@@ -156,6 +155,11 @@ pub fn write(doc: &Document, name: &str, out: impl std::io::Write) -> std::io::R
for s in &doc.stories {
files.insert(format!("Stories/Story_u{:x}.xml", s.uid), w.story(s));
}
// Unnamed colours and gradients are written only where the other
// parts refer to them (objects.md, colours), so the graphic part is
// written last.
let refs = swatch_refs(files.values().map(String::as_str));
files.insert("Resources/Graphic.xml".into(), w.graphic(&refs));
let mut z = zip::ZipWriter::new(out);
z.add("mimetype", MIMETYPE.as_bytes())?;
for (path, content) in &files {
@@ -165,6 +169,27 @@ pub fn write(doc: &Document, name: &str, out: impl std::io::Write) -> std::io::R
Ok(w.warnings.into_inner())
}
/// The `Color/u…` and `Gradient/u…` references in the package parts: an
/// attribute value or element text that is such a reference.
fn swatch_refs<'a>(parts: impl Iterator<Item = &'a str>) -> std::collections::HashSet<String> {
let mut out = std::collections::HashSet::new();
for part in parts {
for prefix in ["Color/u", "Gradient/u"] {
for (i, _) in part.match_indices(prefix) {
if i == 0 || !matches!(part.as_bytes()[i - 1], b'"' | b'>') {
continue;
}
let rest = &part[i + prefix.len()..];
let hex = rest.bytes().take_while(u8::is_ascii_hexdigit).count();
if hex > 0 && matches!(rest.as_bytes().get(hex), Some(b'"' | b'<')) {
out.insert(part[i..i + prefix.len() + hex].to_string());
}
}
}
}
out
}
#[cfg(test)]
impl<'a> Writer<'a> {
/// A writer for `doc` with no derived state, for unit tests.
@@ -182,3 +207,17 @@ impl<'a> Writer<'a> {
}
}
}
#[cfg(test)]
mod tests {
use super::swatch_refs;
#[test]
fn finds_unnamed_swatch_references() {
let part = r#"<A FillColor="Color/u1f" B="Color/u2x" C="Gradient/uab"><P>Color/u9</P><Q>xColor/u8</Q></A>"#;
let refs = swatch_refs([part].into_iter());
let mut v: Vec<_> = refs.into_iter().collect();
v.sort();
assert_eq!(v, ["Color/u1f", "Color/u9", "Gradient/uab"]);
}
}
+41 -3
View File
@@ -39,10 +39,48 @@ impl Writer<'_> {
out
}
pub(super) fn graphic(&self) -> String {
/// `Resources/Graphic.xml`. `refs` are the references to unnamed
/// colours and gradients in the other parts of the package: IDML
/// writes an unnamed colour or gradient only when something refers to
/// it or the page item defaults name it (`docs/format/objects.md`,
/// colours).
pub(super) fn graphic(&self, refs: &std::collections::HashSet<String>) -> String {
use crate::model::color::class;
let mut x = Xml::new();
self.package_root(&mut x, "Graphic");
let groups = self.group_swatches();
let named = |class_id: u32| -> std::collections::HashSet<u32> {
self.doc
.prefs
.item_default_entries
.iter()
.filter(|e| e.0 == class_id)
.flat_map(|e| [e.1, e.2])
.collect()
};
let gradients: Vec<_> = {
let named = named(class::GRADIENT);
self.doc
.gradients
.iter()
.filter(|g| {
!g.name.is_empty() || named.contains(&g.uid) || refs.contains(&g.reference())
})
.collect()
};
// Colours that the stops of any gradient, written or not, and the
// tints refer to.
let mut used: std::collections::HashSet<u32> = named(class::COLOR);
used.extend(
self.doc
.gradients
.iter()
.flat_map(|g| g.stops.iter().map(|s| s.color)),
);
used.extend(self.doc.tints.iter().map(|(t, ..)| t.base));
let colors = self.doc.colors.iter().filter(|c| {
!c.name.is_empty() || used.contains(&c.uid) || refs.contains(&c.reference())
});
// IDML names the colour group swatch of every swatch from DOM 12
// on (`n` for none).
let group_ref = |x: &mut Xml, reference: &str| {
@@ -53,7 +91,7 @@ impl Writer<'_> {
);
}
};
for c in &self.doc.colors {
for c in colors {
let name = c.idml_name();
let mut attrs = vec![("Self", c.reference())];
if let Some(model) = c.model_name() {
@@ -160,7 +198,7 @@ impl Writer<'_> {
x.attrs_missing(self.observed("Swatch").iter());
x.end();
// The schema requires gradients after the swatches.
for g in &self.doc.gradients {
for g in gradients {
x.start("Gradient")
.attr("Self", g.reference())
.attr("Type", if g.kind == 2 { "Radial" } else { "Linear" })
+11
View File
@@ -210,6 +210,17 @@ impl Attrs {
Attrs::records(&mut c, n, decode, list, recorder)
}
/// A page item attribute list (u32 count, records) at the cursor,
/// which is left after the list.
pub fn parse_at(
c: &mut Cursor,
list: List,
recorder: Option<&Recorder>,
) -> Result<Attrs, Error> {
let n = c.u32()? as usize;
Attrs::records(c, n, decode, list, recorder)
}
/// A page item attribute list with a u16 count, as object styles hold.
pub fn parse_short(
enc: Encoding,
+34 -11
View File
@@ -31,6 +31,9 @@ pub struct Prefs {
pub anchor: Option<super::AnchorSettings>,
/// Page item defaults (class 0x6E07), a page item attribute list.
pub item_defaults: Option<Attrs>,
/// The entries of the two tables around that list: class, UID, UID
/// (`objects.md`, page item defaults).
pub item_default_entries: Vec<(u32, u32, u32)>,
/// `Properties` children: element, name, value.
pub props: Vec<(&'static str, &'static str, PrefProp)>,
/// Print records (element, bytes), written in base64 as `PrintRecord`.
@@ -577,8 +580,10 @@ impl Reader<'_> {
}
}
}
// Page item defaults: u32, u32, u32 n, n 12-byte entries, then a
// page item attribute list.
// Page item defaults: a table (u32, u32, u32 n, n 12-byte
// entries), a page item attribute list, and a second table of the
// same layout (objects.md, page item defaults).
let mut item_default_entries = Vec::new();
let item_defaults = match self
.db
.classes()
@@ -586,16 +591,33 @@ impl Reader<'_> {
.find(|(_, c)| *c == class::ITEM_DEFAULTS)
{
Some(&(u, _)) => match self.chunk(u, id::ITEM_DEFAULTS)? {
Some(d) if d.len() >= 12 => {
let n = self.cursor(&d[8..]).u32()? as usize;
d.get(12 + 12 * n..).and_then(|rest| {
self.attrs_or_warn(
|| format!("page item defaults {u}"),
Attrs::parse(self.enc(), rest, List::Item, self.db.recorder()),
)
})
Some(d) => {
let mut c = self.cursor(&d);
let mut table = |c: &mut crate::object::Cursor| -> Result<(), Error> {
c.skip(8)?;
let n = c.u32()? as usize;
for _ in 0..n {
item_default_entries.push((c.u32()?, c.u32()?, c.u32()?));
}
Ok(())
};
match table(&mut c) {
Ok(()) => {
let attrs = self.attrs_or_warn(
|| format!("page item defaults {u}"),
Attrs::parse_at(&mut c, List::Item, self.db.recorder()),
);
if attrs.is_some() && c.remaining() > 0 && table(&mut c).is_err() {
self.warn(format!(
"page item defaults {u}: the second table is not complete"
));
}
attrs
}
Err(_) => None,
}
}
_ => None,
None => None,
},
None => None,
};
@@ -687,6 +709,7 @@ impl Reader<'_> {
.as_deref()
.map(|d| super::AnchorSettings::read(self.enc(), d)),
item_defaults,
item_default_entries,
props,
print_records,
})