From c4eef5a17d27dae4ec496c45806a363be5f1d54a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:32:59 +0000 Subject: [PATCH] refactor: one value-kind enum for every attribute table --- src/idml/attrs.rs | 679 +++++++++++---------------------------- src/idml/kind.rs | 278 ++++++++++++++++ src/idml/mod.rs | 2 + src/idml/resources.rs | 4 +- src/idml/spread.rs | 12 +- src/idml/styles.rs | 7 +- src/idml/transparency.rs | 66 +--- 7 files changed, 495 insertions(+), 553 deletions(-) create mode 100644 src/idml/kind.rs diff --git a/src/idml/attrs.rs b/src/idml/attrs.rs index fdfb7bb..d00b275 100644 --- a/src/idml/attrs.rs +++ b/src/idml/attrs.rs @@ -11,51 +11,31 @@ use super::*; use crate::model::AnchorSettings; use crate::model::attrs::{Delimiter, NestedStyle, TabStop}; -#[derive(Clone, Copy)] -pub(super) enum AttrKind { - Number, - Swatch, - Point, - Enum(&'static [(u32, &'static str)]), - /// A built-in style named by its code (reference 0), written as - /// ``. - Builtin(&'static str, &'static [(u32, &'static str)]), -} - -/// Codes of built-in stroke styles. See `docs/format/attributes.md`. /// Frame fitting attributes of page items and object styles, in the /// order IDML writes them (`docs/format/objects.md`). -pub(super) const FITTING_ATTRS: [(u32, &str); 7] = [ - (0x6E83, "AutoFit"), - (0x6E7E, "LeftCrop"), - (0x6E7F, "TopCrop"), - (0x6E80, "RightCrop"), - (0x6E81, "BottomCrop"), - (0x6E7C, "FittingOnEmptyFrame"), - (0x6E7D, "FittingAlignment"), +pub(super) const FITTING_ATTRS: [(u32, &str, Kind); 7] = [ + (0x6E83, "AutoFit", Kind::Enum(&[(0, "false")])), + (0x6E7E, "LeftCrop", Kind::Number), + (0x6E7F, "TopCrop", Kind::Number), + (0x6E80, "RightCrop", Kind::Number), + (0x6E81, "BottomCrop", Kind::Number), + ( + 0x6E7C, + "FittingOnEmptyFrame", + Kind::Enum(&[ + (0, "None"), + (1, "ContentToFrame"), + (2, "Proportionally"), + (3, "FillProportionally"), + ]), + ), + ( + 0x6E7D, + "FittingAlignment", + Kind::Enum(&[(0, "TopLeftAnchor"), (4, "CenterAnchor")]), + ), ]; -/// The IDML value of frame fitting attribute `id`; `None` for codes -/// without evidence. -pub(super) fn fitting_value(id: u32, v: &Value) -> Option { - match id { - 0x6E83 => (v.as_u32()? == 0).then(|| "false".to_string()), - 0x6E7C => match v.as_u32()? { - 0 => Some("None".into()), - 1 => Some("ContentToFrame".into()), - 2 => Some("Proportionally".into()), - 3 => Some("FillProportionally".into()), - _ => None, - }, - 0x6E7D => match v.as_u32()? { - 0 => Some("TopLeftAnchor".into()), - 4 => Some("CenterAnchor".into()), - _ => None, - }, - _ => v.as_f64().map(num), - } -} - /// IDML attributes of anchored object settings: `VerticalAlignment`, /// `AnchorYoffset`, and the combinations of the other fields observed in /// every sample. See `docs/format/objects.md`. @@ -102,14 +82,15 @@ pub(super) fn anchored_settings(a: &AnchorSettings) -> Vec<(&'static str, String } /// Frame fitting attributes of `attrs` with IDs in `ids`, in IDML order. -pub(super) fn fitting_attrs(attrs: &Attrs, ids: &[u32]) -> Vec<(&'static str, String)> { +pub(super) fn fitting_attrs(w: &Writer, attrs: &Attrs, ids: &[u32]) -> Vec<(&'static str, String)> { FITTING_ATTRS .iter() - .filter(|(id, _)| ids.contains(id)) - .filter_map(|&(id, name)| Some((name, fitting_value(id, attrs.get(id)?)?))) + .filter(|(id, ..)| ids.contains(id)) + .filter_map(|&(id, name, kind)| Some((name, w.value_text(kind, attrs.get(id)?)?))) .collect() } +/// Codes of built-in stroke styles. See `docs/format/attributes.md`. pub(super) const STROKE_TYPES: &[(u32, &str)] = &[ (0x5A29, "Solid"), (0x5A38, "Canned Dashed 3x2"), @@ -141,91 +122,44 @@ pub(super) const BUILTIN_STROKE_STYLES: &[&str] = &[ "Solid", ]; -#[derive(Clone, Copy)] -pub(super) enum TextKind { - Number, - /// Stored as a fraction, written as a percentage. - Percent, - /// Multiplied by the factor when written. - Scale(f64), - /// True when the value equals the given code. - Bool(u32), - Enum(&'static [(u32, &'static str)]), - Swatch, - /// A swatch, or 0 for "Text Color" (written in Properties). - SwatchOrText, - Font, - FontStyle, - Leading, - /// A language object, written as `$ID/`. - Language, - /// The given value is written as the enumeration value, others as - /// numbers of the given IDML type. - NumberOr(f64, &'static str, &'static str), - /// Two f64 (a point). - Point, - /// A list of tab stops (`TabList`). - TabList, - /// A list of nested styles (`AllNestedStyles`). - NestedStyles, - /// A character style reference. - CharacterStyle, - /// A font family, or 0 for none (`$ID/`). - FontOrNone, - /// A string, or the empty string for `Nothing`. - StringOrNothing, - /// u32 bullet character type and u32 character value (`BulletChar`). - BulletChar, - /// u32 length in characters, then text segments; left out when empty. - Text, - /// A number, left out when 0. - NonZero, - /// Manual kerning in ems, written in thousandths of an em; 1e8 (the - /// root style's value) is left out. - Kerning, - /// A kinsoku or mojikumi set: 0 `Nothing`, a built-in table (written - /// as its enumeration value) or a custom kinsoku table (an object). - CjkSet, -} - /// Value of the kerning attribute (0x1B13) in every root paragraph style; /// IDML writes no `KerningValue` for it. pub(super) const KERNING_NONE: f64 = 1e8; /// Text attributes: ID, IDML name, kind, written in ``. /// See `docs/format/attributes.md` for the evidence behind each entry. -pub(super) const TEXT_ATTRS: &[(u32, &str, TextKind, bool)] = &[ - (0x1B01, "FillColor", TextKind::Swatch, false), - (0x1B02, "FontStyle", TextKind::FontStyle, false), - (0x1B03, "PointSize", TextKind::Number, false), - (0x1B06, "HorizontalScale", TextKind::Percent, false), - (0x1B08, "Ligatures", TextKind::Bool(1), false), +pub(super) const TEXT_ATTRS: &[(u32, &str, Kind, bool)] = &[ + (0x1B01, "FillColor", Kind::Swatch, false), + (0x1B02, "FontStyle", Kind::String, false), + (0x1B03, "PointSize", Kind::Number, false), + (0x1B06, "HorizontalScale", Kind::Percent, false), + (0x1B08, "Ligatures", Kind::Equals(1), false), ( 0x1B07, "KerningMethod", - TextKind::Enum(&[(15972, "$ID/Metrics"), (79875, "$ID/Optical")]), + Kind::Enum(&[(15972, "$ID/Metrics"), (79875, "$ID/Optical")]), false, ), - (0x1B0A, "StrokeWeight", TextKind::Number, false), - (0x1B0B, "Tracking", TextKind::Scale(1000.0), false), - (0x1B13, "KerningValue", TextKind::Kerning, false), + (0x1B0A, "StrokeWeight", Kind::Number, false), + (0x1B0B, "Tracking", Kind::Scale(1000.0), false), + (0x1B13, "KerningValue", Kind::Kerning, false), ( 0x1B0C, "Composer", - TextKind::Enum(&[ + Kind::Enum(&[ (0x2001, "HL Single"), (0x2002, "HL Composer"), (0x2078, "HL Composer Optyca"), ]), false, ), - (0x1B0D, "DropCapCharacters", TextKind::Number, false), - (0x1B0E, "DropCapLines", TextKind::Number, false), - (0x1B10, "BaselineShift", TextKind::Number, false), + (0x1B0D, "DropCapCharacters", Kind::Number, false), + (0x1B0E, "DropCapLines", Kind::Number, false), + (0x1B10, "BaselineShift", Kind::Number, false), ( 0x1B11, "Capitalization", - TextKind::Enum(&[ + Kind::Enum(&[ (0, "Normal"), (1, "SmallCaps"), (2, "AllCaps"), @@ -233,99 +167,99 @@ pub(super) const TEXT_ATTRS: &[(u32, &str, TextKind, bool)] = &[ ]), false, ), - (0x1B12, "StrokeColor", TextKind::Swatch, false), - (0x1B15, "VerticalScale", TextKind::Percent, false), - (0x1B16, "LeftIndent", TextKind::Number, false), - (0x1B17, "RightIndent", TextKind::Number, false), - (0x1B18, "FirstLineIndent", TextKind::Number, false), - (0x1B1A, "AutoLeading", TextKind::Percent, false), - (0x1B1B, "Leading", TextKind::Leading, true), - (0x1B1D, "AppliedLanguage", TextKind::Language, false), - (0x1B1F, "Hyphenation", TextKind::Bool(3), false), - (0x1B24, "NoBreak", TextKind::Bool(1), false), - (0x1B25, "HyphenationZone", TextKind::Number, false), - (0x1B26, "SpaceBefore", TextKind::Number, false), - (0x1B27, "SpaceAfter", TextKind::Number, false), - (0x1B29, "TabList", TextKind::TabList, true), - (0x1B2A, "Underline", TextKind::Bool(1), false), - (0x1B2B, "AppliedFont", TextKind::Font, true), + (0x1B12, "StrokeColor", Kind::Swatch, false), + (0x1B15, "VerticalScale", Kind::Percent, false), + (0x1B16, "LeftIndent", Kind::Number, false), + (0x1B17, "RightIndent", Kind::Number, false), + (0x1B18, "FirstLineIndent", Kind::Number, false), + (0x1B1A, "AutoLeading", Kind::Percent, false), + (0x1B1B, "Leading", Kind::Leading, true), + (0x1B1D, "AppliedLanguage", Kind::Language, false), + (0x1B1F, "Hyphenation", Kind::Equals(3), false), + (0x1B24, "NoBreak", Kind::Equals(1), false), + (0x1B25, "HyphenationZone", Kind::Number, false), + (0x1B26, "SpaceBefore", Kind::Number, false), + (0x1B27, "SpaceAfter", Kind::Number, false), + (0x1B29, "TabList", Kind::TabList, true), + (0x1B2A, "Underline", Kind::Equals(1), false), + (0x1B2B, "AppliedFont", Kind::Font, true), ( 0x1B2C, "OTFFigureStyle", - TextKind::Enum(&[ + Kind::Enum(&[ (1, "ProportionalOldstyle"), (2, "ProportionalLining"), (4, "Default"), ]), false, ), - (0x1B2E, "MaximumWordSpacing", TextKind::Percent, false), - (0x1B2F, "MinimumWordSpacing", TextKind::Percent, false), - (0x1B31, "MaximumLetterSpacing", TextKind::Percent, false), - (0x1B32, "MinimumLetterSpacing", TextKind::Percent, false), + (0x1B2E, "MaximumWordSpacing", Kind::Percent, false), + (0x1B2F, "MinimumWordSpacing", Kind::Percent, false), + (0x1B31, "MaximumLetterSpacing", Kind::Percent, false), + (0x1B32, "MinimumLetterSpacing", Kind::Percent, false), ( 0x1B37, "StartParagraph", - TextKind::Enum(&[(0, "Anywhere"), (2, "NextPage")]), + Kind::Enum(&[(0, "Anywhere"), (2, "NextPage")]), false, ), ( 0x1B3C, "Position", - TextKind::Enum(&[(0, "Normal"), (5, "OTNumerator")]), + Kind::Enum(&[(0, "Normal"), (5, "OTNumerator")]), false, ), - (0x1B40, "KeepLinesTogether", TextKind::Bool(1), false), - (0x1B42, "FillTint", TextKind::Number, false), - (0x1B46, "GradientFillAngle", TextKind::Number, false), - (0x1B48, "GradientFillLength", TextKind::Number, false), - (0x1B4A, "GradientFillStart", TextKind::Point, false), - (0x1B4D, "RuleAboveLineWeight", TextKind::Number, false), - (0x1B4F, "RuleAboveOffset", TextKind::Number, false), - (0x1B50, "RuleAboveLeftIndent", TextKind::Number, false), - (0x1B51, "RuleAboveRightIndent", TextKind::Number, false), + (0x1B40, "KeepLinesTogether", Kind::Equals(1), false), + (0x1B42, "FillTint", Kind::Number, false), + (0x1B46, "GradientFillAngle", Kind::Number, false), + (0x1B48, "GradientFillLength", Kind::Number, false), + (0x1B4A, "GradientFillStart", Kind::Point, false), + (0x1B4D, "RuleAboveLineWeight", Kind::Number, false), + (0x1B4F, "RuleAboveOffset", Kind::Number, false), + (0x1B50, "RuleAboveLeftIndent", Kind::Number, false), + (0x1B51, "RuleAboveRightIndent", Kind::Number, false), ( 0x1B52, "RuleAboveWidth", - TextKind::Enum(&[(1, "ColumnWidth"), (2, "TextWidth")]), + Kind::Enum(&[(1, "ColumnWidth"), (2, "TextWidth")]), false, ), - (0x1B53, "RuleBelowColor", TextKind::SwatchOrText, true), - (0x1B54, "RuleBelowLineWeight", TextKind::Number, false), - (0x1B55, "RuleBelowTint", TextKind::Number, false), - (0x1B56, "RuleBelowOffset", TextKind::Number, false), - (0x1B5D, "RuleBelow", TextKind::Bool(1), false), + (0x1B53, "RuleBelowColor", Kind::SwatchOrText, true), + (0x1B54, "RuleBelowLineWeight", Kind::Number, false), + (0x1B55, "RuleBelowTint", Kind::Number, false), + (0x1B56, "RuleBelowOffset", Kind::Number, false), + (0x1B5D, "RuleBelow", Kind::Equals(1), false), ( 0x1B6A, "ParagraphBreakType", - TextKind::Enum(&[(0, "Anywhere"), (1, "NextColumn")]), + Kind::Enum(&[(0, "Anywhere"), (1, "NextColumn")]), false, ), ( 0x1B6B, "SingleWordJustification", - TextKind::Enum(&[(0, "LeftAlign"), (3, "FullyJustified")]), + Kind::Enum(&[(0, "LeftAlign"), (3, "FullyJustified")]), false, ), - (0x1B75, "AllNestedStyles", TextKind::NestedStyles, true), + (0x1B75, "AllNestedStyles", Kind::NestedStyles, true), ( 0x42C0, "TreatIdeographicSpaceAsSpace", - TextKind::Bool(1), + Kind::Equals(1), false, ), ( 0x50F18, "DiacriticPosition", - TextKind::Enum(&[(4, "OpentypePosition"), (5, "OpentypePositionFromBaseline")]), + Kind::Enum(&[(4, "OpentypePosition"), (5, "OpentypePositionFromBaseline")]), false, ), - (0x4221, "Mojikumi", TextKind::CjkSet, true), - (0x4224, "KinsokuSet", TextKind::CjkSet, true), + (0x4221, "Mojikumi", Kind::CjkSet, true), + (0x4224, "KinsokuSet", Kind::CjkSet, true), ( 0x1B7E, "Justification", - TextKind::Enum(&[ + Kind::Enum(&[ (0, "LeftAlign"), (1, "CenterAlign"), (2, "RightAlign"), @@ -334,93 +268,78 @@ pub(super) const TEXT_ATTRS: &[(u32, &str, TextKind, bool)] = &[ ]), false, ), - (0x1B80, "DropcapDetail", TextKind::Number, false), - (0x1B8C, "OTFContextualAlternate", TextKind::Bool(1), false), - (0x1B8D, "UnderlineColor", TextKind::SwatchOrText, true), - (0x1B91, "UnderlineOffset", TextKind::Number, false), - (0x1B94, "UnderlineWeight", TextKind::Number, false), - (0x1BB7, "MiterLimit", TextKind::Number, false), + (0x1B80, "DropcapDetail", Kind::Number, false), + (0x1B8C, "OTFContextualAlternate", Kind::Equals(1), false), + (0x1B8D, "UnderlineColor", Kind::SwatchOrText, true), + (0x1B91, "UnderlineOffset", Kind::Number, false), + (0x1B94, "UnderlineWeight", Kind::Number, false), + (0x1BB7, "MiterLimit", Kind::Number, false), ( 0x1BB9, "EndJoin", - TextKind::Enum(&[(0, "MiterEndJoin"), (1, "RoundEndJoin")]), + Kind::Enum(&[(0, "MiterEndJoin"), (1, "RoundEndJoin")]), false, ), ( 0x1BBD, "SpanColumnType", - TextKind::Enum(&[(0, "SingleColumn"), (1, "SpanColumns")]), + Kind::Enum(&[(0, "SingleColumn"), (1, "SpanColumns")]), false, ), ( 0x1BBE, "SpanSplitColumnCount", - TextKind::NumberOr(1.0, "All", "short"), + Kind::NumberOr(1.0, "All", "short"), true, ), - (0x1BBF, "SplitColumnInsideGutter", TextKind::Number, false), - (0x1BC4, "SpanColumnMinSpaceAfter", TextKind::Number, false), - (0x1BD2, "ParagraphShadingColor", TextKind::Swatch, true), - (0x1BD3, "ParagraphShadingTint", TextKind::Number, false), - (0x1BD6, "ParagraphShadingOn", TextKind::Bool(1), false), - (0x1BDB, "ParagraphShadingTopOffset", TextKind::Number, false), - ( - 0x1BDC, - "ParagraphShadingBottomOffset", - TextKind::Number, - false, - ), - (0x1BF6, "ParagraphBorderColor", TextKind::Swatch, true), - (0x1BF9, "ParagraphBorderOn", TextKind::Bool(1), false), - (0x1DF03, "ParagraphBorderTopOffset", TextKind::Number, false), - ( - 0x1DF04, - "ParagraphBorderBottomOffset", - TextKind::Number, - false, - ), + (0x1BBF, "SplitColumnInsideGutter", Kind::Number, false), + (0x1BC4, "SpanColumnMinSpaceAfter", Kind::Number, false), + (0x1BD2, "ParagraphShadingColor", Kind::Swatch, true), + (0x1BD3, "ParagraphShadingTint", Kind::Number, false), + (0x1BD6, "ParagraphShadingOn", Kind::Equals(1), false), + (0x1BDB, "ParagraphShadingTopOffset", Kind::Number, false), + (0x1BDC, "ParagraphShadingBottomOffset", Kind::Number, false), + (0x1BF6, "ParagraphBorderColor", Kind::Swatch, true), + (0x1BF9, "ParagraphBorderOn", Kind::Equals(1), false), + (0x1DF03, "ParagraphBorderTopOffset", Kind::Number, false), + (0x1DF04, "ParagraphBorderBottomOffset", Kind::Number, false), ( 0x1DF21, "SameParaStyleSpacing", - TextKind::NumberOr(-1.0, "SetIgnore", "unit"), + Kind::NumberOr(-1.0, "SetIgnore", "unit"), true, ), - (0x4265, "GridAlignFirstLineOnly", TextKind::Bool(1), false), - (0x425E, "Tatechuyoko", TextKind::Bool(1), false), - (0x4279, "ShataiDegreeAngle", TextKind::Scale(100.0), false), - (0x427A, "ShataiAdjustTsume", TextKind::Bool(1), false), - (0x427B, "ShataiAdjustRotation", TextKind::Bool(1), false), - (0x422D, "RubyFlag", TextKind::NonZero, false), - (0x422E, "RubyString", TextKind::Text, false), + (0x4265, "GridAlignFirstLineOnly", Kind::Equals(1), false), + (0x425E, "Tatechuyoko", Kind::Equals(1), false), + (0x4279, "ShataiDegreeAngle", Kind::Scale(100.0), false), + (0x427A, "ShataiAdjustTsume", Kind::Equals(1), false), + (0x427B, "ShataiAdjustRotation", Kind::Equals(1), false), + (0x422D, "RubyFlag", Kind::NonZero, false), + (0x422E, "RubyString", Kind::Text, false), ( 0x4266, "GridAlignment", - TextKind::Enum(&[(0, "None"), (1, "AlignBaseline")]), + Kind::Enum(&[(0, "None"), (1, "AlignBaseline")]), false, ), ( 0x1A401, "BulletsAndNumberingListType", - TextKind::Enum(&[(0, "NoList"), (1, "BulletList")]), + Kind::Enum(&[(0, "NoList"), (1, "BulletList")]), false, ), - (0x1A406, "BulletChar", TextKind::BulletChar, true), - (0x1A413, "BulletsFont", TextKind::FontOrNone, true), - (0x1A414, "BulletsFontStyle", TextKind::StringOrNothing, true), - (0x1A419, "NumberingContinue", TextKind::Bool(1), false), - ( - 0x1A41F, - "BulletsCharacterStyle", - TextKind::CharacterStyle, - true, - ), + (0x1A406, "BulletChar", Kind::BulletChar, true), + (0x1A413, "BulletsFont", Kind::FontOrNone, true), + (0x1A414, "BulletsFontStyle", Kind::StringOrNothing, true), + (0x1A419, "NumberingContinue", Kind::Equals(1), false), + (0x1A41F, "BulletsCharacterStyle", Kind::CharacterStyle, true), ( 0x1A420, "NumberingCharacterStyle", - TextKind::CharacterStyle, + Kind::CharacterStyle, true, ), - (0x1A423, "NumberingExpression", TextKind::FontStyle, false), + (0x1A423, "NumberingExpression", Kind::String, false), ]; /// An attribute written as a `` child: name, type, value. @@ -446,31 +365,31 @@ impl From for PropValue { /// Page item attributes: attribute-list ID, IDML name, value kind. /// See `docs/format/attributes.md` for the evidence behind each entry. -pub(super) const ITEM_ATTRS: &[(u32, &str, AttrKind)] = &[ - (0x6E68, "FillColor", AttrKind::Swatch), - (0x6E69, "FillTint", AttrKind::Number), - (0x6E64, "StrokeColor", AttrKind::Swatch), - (0x6E65, "StrokeWeight", AttrKind::Number), - (0x6E6D, "MiterLimit", AttrKind::Number), +pub(super) const ITEM_ATTRS: &[(u32, &str, Kind)] = &[ + (0x6E68, "FillColor", Kind::Swatch), + (0x6E69, "FillTint", Kind::Number), + (0x6E64, "StrokeColor", Kind::Swatch), + (0x6E65, "StrokeWeight", Kind::Number), + (0x6E6D, "MiterLimit", Kind::Number), ( 0x6E6F, "CornerOption", - AttrKind::Enum(&[(0x5A15, "RoundedCorner")]), + Kind::Enum(&[(0x5A15, "RoundedCorner")]), ), - (0x6E70, "CornerRadius", AttrKind::Number), - (0x551F, "GradientFillLength", AttrKind::Number), - (0x5520, "GradientFillStart", AttrKind::Point), - (0x5525, "GradientStrokeLength", AttrKind::Number), - (0x5526, "GradientStrokeStart", AttrKind::Point), + (0x6E70, "CornerRadius", Kind::Number), + (0x551F, "GradientFillLength", Kind::Number), + (0x5520, "GradientFillStart", Kind::Point), + (0x5525, "GradientStrokeLength", Kind::Number), + (0x5526, "GradientStrokeStart", Kind::Point), ( 0x6E6E, "StrokeType", - AttrKind::Builtin("StrokeStyle/$ID/", STROKE_TYPES), + Kind::Builtin("StrokeStyle/$ID/", STROKE_TYPES), ), ( 0x6E8C, "StrokeAlignment", - AttrKind::Enum(&[(0, "CenterAlignment"), (1, "InsideAlignment")]), + Kind::Enum(&[(0, "CenterAlignment"), (1, "InsideAlignment")]), ), ]; @@ -518,91 +437,65 @@ pub(super) fn join_numbers(v: &[u32]) -> String { v.iter().map(u32::to_string).collect::>().join(" ") } -/// Kinds of cell attribute values. -#[derive(Clone, Copy)] -pub(super) enum CellKind { - Number, - Integer, - Swatch, - Enum(&'static [(u32, &'static str)]), - /// A stroke style code in the first four of eight bytes; the other - /// four are 0. - StrokeType, - /// A cell style UID; 0 is written as `n`. - CellStyle, -} - /// Cell attributes of a cell attribute set: ID, IDML attributes, kind. /// See `docs/format/tables.md`. -pub(super) const CELL_ATTRS: &[(u32, &[&str], CellKind)] = &[ - (0xB62C, &["TextTopInset", "TopInset"], CellKind::Number), - (0xB62B, &["TextLeftInset", "LeftInset"], CellKind::Number), - ( - 0xB62E, - &["TextBottomInset", "BottomInset"], - CellKind::Number, - ), - (0xB62D, &["TextRightInset", "RightInset"], CellKind::Number), - (0xB63D, &["FillColor"], CellKind::Swatch), - (0xB63E, &["FillTint"], CellKind::Number), +pub(super) const CELL_ATTRS: &[(u32, &[&str], Kind)] = &[ + (0xB62C, &["TextTopInset", "TopInset"], Kind::Number), + (0xB62B, &["TextLeftInset", "LeftInset"], Kind::Number), + (0xB62E, &["TextBottomInset", "BottomInset"], Kind::Number), + (0xB62D, &["TextRightInset", "RightInset"], Kind::Number), + (0xB63D, &["FillColor"], Kind::Swatch), + (0xB63E, &["FillTint"], Kind::Number), ( 0xB677, &["VerticalJustification"], - CellKind::Enum(&[(1, "CenterAlign"), (2, "BottomAlign")]), + Kind::Enum(&[(1, "CenterAlign"), (2, "BottomAlign")]), ), - ( - 0xB6DE, - &["ClipContentToCell"], - CellKind::Enum(&[(0, "false")]), - ), - (0xB645, &["LeftEdgeStrokeWeight"], CellKind::Number), - (0xB64D, &["LeftEdgeStrokeType"], CellKind::StrokeType), - (0xB649, &["LeftEdgeStrokeColor"], CellKind::Swatch), - (0xB6A8, &["LeftEdgeStrokeTint"], CellKind::Number), - (0xB6F9, &["LeftEdgeStrokePriority"], CellKind::Integer), - (0xB647, &["TopEdgeStrokeWeight"], CellKind::Number), - (0xB64F, &["TopEdgeStrokeType"], CellKind::StrokeType), - (0xB64A, &["TopEdgeStrokeColor"], CellKind::Swatch), - (0xB6AA, &["TopEdgeStrokeTint"], CellKind::Number), - (0xB6FB, &["TopEdgeStrokePriority"], CellKind::Integer), - (0xB646, &["RightEdgeStrokeWeight"], CellKind::Number), - (0xB64E, &["RightEdgeStrokeType"], CellKind::StrokeType), - (0xB64B, &["RightEdgeStrokeColor"], CellKind::Swatch), - (0xB6A9, &["RightEdgeStrokeTint"], CellKind::Number), - (0xB6FA, &["RightEdgeStrokePriority"], CellKind::Integer), - (0xB648, &["BottomEdgeStrokeWeight"], CellKind::Number), - (0xB650, &["BottomEdgeStrokeType"], CellKind::StrokeType), - (0xB64C, &["BottomEdgeStrokeColor"], CellKind::Swatch), - (0xB6AB, &["BottomEdgeStrokeTint"], CellKind::Number), - (0xB6FC, &["BottomEdgeStrokePriority"], CellKind::Integer), + (0xB6DE, &["ClipContentToCell"], Kind::Enum(&[(0, "false")])), + (0xB645, &["LeftEdgeStrokeWeight"], Kind::Number), + (0xB64D, &["LeftEdgeStrokeType"], Kind::StrokeType), + (0xB649, &["LeftEdgeStrokeColor"], Kind::Swatch), + (0xB6A8, &["LeftEdgeStrokeTint"], Kind::Number), + (0xB6F9, &["LeftEdgeStrokePriority"], Kind::Integer), + (0xB647, &["TopEdgeStrokeWeight"], Kind::Number), + (0xB64F, &["TopEdgeStrokeType"], Kind::StrokeType), + (0xB64A, &["TopEdgeStrokeColor"], Kind::Swatch), + (0xB6AA, &["TopEdgeStrokeTint"], Kind::Number), + (0xB6FB, &["TopEdgeStrokePriority"], Kind::Integer), + (0xB646, &["RightEdgeStrokeWeight"], Kind::Number), + (0xB64E, &["RightEdgeStrokeType"], Kind::StrokeType), + (0xB64B, &["RightEdgeStrokeColor"], Kind::Swatch), + (0xB6A9, &["RightEdgeStrokeTint"], Kind::Number), + (0xB6FA, &["RightEdgeStrokePriority"], Kind::Integer), + (0xB648, &["BottomEdgeStrokeWeight"], Kind::Number), + (0xB650, &["BottomEdgeStrokeType"], Kind::StrokeType), + (0xB64C, &["BottomEdgeStrokeColor"], Kind::Swatch), + (0xB6AB, &["BottomEdgeStrokeTint"], Kind::Number), + (0xB6FC, &["BottomEdgeStrokePriority"], Kind::Integer), ]; /// Table and table style attributes: ID, IDML attribute, kind. /// See `docs/format/tables.md`. -pub(super) const TABLE_ATTRS: &[(u32, &str, CellKind)] = &[ - (0xB662, "SpaceBefore", CellKind::Number), - (0xB663, "SpaceAfter", CellKind::Number), - (0xB684, "StartRowStrokeColor", CellKind::Swatch), - (0xB690, "StartRowStrokeWeight", CellKind::Number), - (0xB688, "StartRowStrokeType", CellKind::StrokeType), - ( - 0xB683, - "ColumnFillsPriority", - CellKind::Enum(&[(0, "false")]), - ), - (0xB67B, "StartRowFillColor", CellKind::Swatch), - (0xB6B0, "StartRowFillTint", CellKind::Number), - (0xB67C, "EndRowFillColor", CellKind::Swatch), - (0xB6B1, "EndRowFillTint", CellKind::Number), +pub(super) const TABLE_ATTRS: &[(u32, &str, Kind)] = &[ + (0xB662, "SpaceBefore", Kind::Number), + (0xB663, "SpaceAfter", Kind::Number), + (0xB684, "StartRowStrokeColor", Kind::Swatch), + (0xB690, "StartRowStrokeWeight", Kind::Number), + (0xB688, "StartRowStrokeType", Kind::StrokeType), + (0xB683, "ColumnFillsPriority", Kind::Enum(&[(0, "false")])), + (0xB67B, "StartRowFillColor", Kind::Swatch), + (0xB6B0, "StartRowFillTint", Kind::Number), + (0xB67C, "EndRowFillColor", Kind::Swatch), + (0xB6B1, "EndRowFillTint", Kind::Number), ( 0x10457, "HeaderRegionSameAsBodyRegion", - CellKind::Enum(&[(0, "false"), (1, "true")]), + Kind::Enum(&[(0, "false"), (1, "true")]), ), - (0x10450, "HeaderRegionCellStyle", CellKind::CellStyle), - (0x10452, "BodyRegionCellStyle", CellKind::CellStyle), - (0x10453, "LeftColumnRegionCellStyle", CellKind::CellStyle), - (0x10454, "RightColumnRegionCellStyle", CellKind::CellStyle), + (0x10450, "HeaderRegionCellStyle", Kind::CellStyle), + (0x10452, "BodyRegionCellStyle", Kind::CellStyle), + (0x10453, "LeftColumnRegionCellStyle", Kind::CellStyle), + (0x10454, "RightColumnRegionCellStyle", Kind::CellStyle), ]; /// Paragraph style of a cell style. @@ -664,24 +557,8 @@ impl Writer<'_> { let mut props = Vec::new(); for &(id, name, kind, in_props) in TEXT_ATTRS { let Some(v) = attrs.get(id) else { continue }; - let out: Option<(&'static str, PropValue)> = match kind { - TextKind::TabList => match v { - Value::TabList(stops) => tab_list(stops).map(|l| ("list", PropValue::List(l))), - _ => None, - }, - TextKind::NestedStyles => match v { - Value::StyleList { - nested: Some(n), .. - } => Some(("list", PropValue::List(self.nested_styles(n)))), - _ => None, - }, - TextKind::BulletChar => match *v { - Value::BulletChar { kind, value } => bullet_char(kind, value).map(|a| ("", a)), - _ => None, - }, - _ => self.text_value(kind, v).map(|(t, s)| (t, s.into())), - }; - if out.is_none() && matches!(kind, TextKind::Enum(_)) { + let out = self.value(kind, v); + if out.is_none() && kind.is_code() { attrs.unknown_code(id, v); } if let Some((ty, value)) = out { @@ -695,108 +572,6 @@ impl Writer<'_> { (plain, props) } - /// IDML type and text of a single-valued text attribute. - pub(super) fn text_value(&self, kind: TextKind, v: &Value) -> Option<(&'static str, String)> { - let swatch = |u: u32| self.doc.swatches.get(&u).cloned(); - match kind { - TextKind::Number => v - .as_f64() - .or(v.as_u32().map(f64::from)) - .map(|f| ("unit", num(f))), - TextKind::Point => match *v { - Value::Point(x, y) => Some(("unit", nums(&[x, y]))), - _ => None, - }, - TextKind::Percent => v.as_f64().map(|f| ("unit", num(round(f * 100.0)))), - TextKind::Scale(k) => v.as_f64().map(|f| ("unit", num(round(f * k)))), - TextKind::Kerning => v - .as_f64() - .filter(|&f| f != KERNING_NONE) - .map(|f| ("unit", num(round(f * 1000.0)))), - TextKind::Bool(t) => v.as_u32().map(|u| ("boolean", (u == t).to_string())), - TextKind::CjkSet => { - let u = v.as_u32()?; - if u == 0 { - return Some(("enumeration", "Nothing".into())); - } - let t = self.doc.cjk_tables.iter().find(|t| t.uid == u)?; - // Built-in tables observed in the corpus (attributes.md). - const BUILTIN: [(&str, &str); 6] = [ - ("$ID/kHardKinsokuName", "HardKinsoku"), - ("$ID/kSoftKinsokuName", "SoftKinsoku"), - ("$ID/kKoreanKinsokuName", "KoreanKinsoku"), - ("$ID/kSimpChineseKinsokuName", "SimplifiedChineseKinsoku"), - ("$ID/kMojikumiDefaultName1", "LineEndAllOneHalfEmEnum"), - ("$ID/kMojikumiDefaultName16", "SimpChineseDefault"), - ]; - if let Some((_, e)) = BUILTIN.iter().find(|(k, _)| *k == t.name) { - return Some(("enumeration", e.to_string())); - } - if t.name.starts_with("$ID/") || t.mojikumi { - return None; - } - Some(("object", format!("KinsokuTable/{}", self_name(&t.name)))) - } - TextKind::Enum(map) => v - .as_u32() - .and_then(|u| map.iter().find(|(k, _)| *k == u)) - .map(|(_, n)| ("enumeration", n.to_string())), - TextKind::Swatch => v.as_u32().and_then(swatch).map(|s| ("object", s)), - TextKind::SwatchOrText => match v.as_u32() { - Some(0) => Some(("string", "Text Color".into())), - Some(u) => swatch(u).map(|s| ("object", s)), - None => None, - }, - TextKind::Font => v - .as_u32() - .and_then(|u| self.doc.fonts.get(&u)) - .map(|f| ("string", f.name.clone())), - TextKind::FontStyle => v.as_string().map(|s| ("string", s)), - TextKind::Leading => v.as_f64().map(|f| { - if f < 0.0 { - ("enumeration", "Auto".into()) - } else { - ("unit", num(f)) - } - }), - TextKind::Language => v - .as_u32() - .and_then(|u| self.doc.languages.get(&u)) - .map(|l| ("string", format!("$ID/{l}"))), - TextKind::NumberOr(code, name, ty) => v.as_f64().map(|f| { - if f == code { - ("enumeration", name.to_string()) - } else { - (ty, num(f)) - } - }), - TextKind::CharacterStyle => v - .as_u32() - .map(|u| ("object", self.style_ref(Some(u).filter(|&u| u != 0), false))), - TextKind::FontOrNone => match v.as_u32() { - Some(0) => Some(("string", "$ID/".into())), - Some(u) => self.doc.fonts.get(&u).map(|f| ("string", f.name.clone())), - None => None, - }, - TextKind::NonZero => v - .as_u32() - .filter(|&u| u != 0) - .map(|u| ("long", u.to_string())), - TextKind::Text => match v { - Value::Text(t) if !t.is_empty() => Some(("string", t.clone())), - _ => None, - }, - TextKind::StringOrNothing => v.as_string().map(|s| { - if s.is_empty() { - ("enumeration", "Nothing".into()) - } else { - ("string", s) - } - }), - TextKind::TabList | TextKind::NestedStyles | TextKind::BulletChar => None, - } - } - /// Records of an `AllNestedStyles` list. See `docs/format/attributes.md`. pub(super) fn nested_styles(&self, styles: &[NestedStyle]) -> Vec> { styles @@ -825,107 +600,33 @@ impl Writer<'_> { /// Page item attributes from an attribute list, as IDML values. pub(super) fn item_attr_values(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { - let mut out = Vec::new(); - for &(id, name, kind) in ITEM_ATTRS { - let Some(v) = attrs.get(id) else { continue }; - let text = match kind { - AttrKind::Number => v.as_f64().map(num), - AttrKind::Swatch => v.as_ref().and_then(|u| self.doc.swatches.get(&u).cloned()), - AttrKind::Point => match v { - Value::Point(x, y) => Some(nums(&[*x, *y])), - _ => None, - }, - AttrKind::Enum(map) => v - .as_u32() - .and_then(|u| map.iter().find(|(k, _)| *k == u)) - .map(|(_, n)| n.to_string()), - AttrKind::Builtin(prefix, map) => match v { - Value::RefOrCode(0, code) => map - .iter() - .find(|(k, _)| k == code) - .map(|(_, n)| format!("{prefix}{n}")), - _ => None, - }, - }; - match text { - Some(t) => out.push((name, t)), - None if matches!(kind, AttrKind::Enum(_) | AttrKind::Builtin(..)) => { - attrs.unknown_code(id, v) - } - None => {} - } - } - out + self.attr_values(attrs, ITEM_ATTRS) } /// IDML attributes of a table or table style attribute list. pub(super) fn table_attrs(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { - TABLE_ATTRS - .iter() - .filter_map(|&(id, name, kind)| { - let v = attrs.get(id)?; - let t = match kind { - CellKind::CellStyle => match v.as_u32()? { - 0 => Some("n".to_string()), - u => self - .doc - .cell_styles - .get(&u) - .map(|s| Self::table_style_ref("CellStyle", s)), - }, - _ => self.table_value(v, kind), - }; - if t.is_none() && matches!(kind, CellKind::Enum(_) | CellKind::StrokeType) { - attrs.unknown_code(id, v); - } - Some((name, t?)) - }) - .collect() + self.attr_values(attrs, TABLE_ATTRS) } - /// IDML attributes of a cell attribute set. + /// IDML attributes of a cell attribute set. Some cell attributes are + /// written as two IDML attributes. pub(super) fn cell_attrs(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { let mut out = Vec::new(); for &(id, names, kind) in CELL_ATTRS { let Some(v) = attrs.get(id) else { continue }; - match self.table_value(v, kind) { + match self.value_text(kind, v) { Some(t) => { for &name in names { out.push((name, t.clone())); } } - None if matches!(kind, CellKind::Enum(_) | CellKind::StrokeType) => { - attrs.unknown_code(id, v) - } + None if kind.is_code() => attrs.unknown_code(id, v), None => {} } } out } - pub(super) fn table_value(&self, v: &Value, kind: CellKind) -> Option { - { - match kind { - CellKind::Number => v.as_f64().map(num), - CellKind::Integer => v.as_u32().map(|u| u.to_string()), - CellKind::Swatch => v.as_ref().and_then(|u| self.doc.swatches.get(&u).cloned()), - CellKind::Enum(map) => v - .as_u32() - .and_then(|u| map.iter().find(|(k, _)| *k == u)) - .map(|(_, n)| n.to_string()), - CellKind::StrokeType => match *v { - Value::Words(CELL_NO_STROKE_TYPE, 0) => Some("n".to_string()), - Value::Words(code, 0) => STROKE_TYPES - .iter() - .find(|(k, _)| *k == code) - .map(|(_, n)| format!("StrokeStyle/$ID/{n}")), - _ => None, - }, - CellKind::CellStyle => v.as_u32().and_then(|u| self.cell_style_ref(u)), - } - } - } - /// The gradient attributes of a page item: its own, or, for a group, /// the values all its children have. See `docs/format/objects.md`. pub(super) fn gradients(item: &PageItem) -> Vec<(&'static str, String)> { diff --git a/src/idml/kind.rs b/src/idml/kind.rs new file mode 100644 index 0000000..3284610 --- /dev/null +++ b/src/idml/kind.rs @@ -0,0 +1,278 @@ +//! Value kinds: how a decoded attribute value becomes IDML text. The +//! attribute tables of text, page item, frame fitting, cell, table and +//! transparency attributes (`attrs.rs`, `transparency.rs`) all name one +//! of these kinds, and [`Writer::value`] converts every kind. +//! +//! Evidence for each table entry: `docs/format/attributes.md`, +//! `tables.md` and `transparency.md`. + +use super::*; +use crate::model::Value; + +/// How an attribute value is written in IDML. +#[derive(Clone, Copy)] +pub(super) enum Kind { + /// A number: an f64, an integer, an enumeration value or a 4-byte + /// value. + Number, + /// A number the IDML schema limits to this range (inclusive); values + /// outside it have no IDML value. + Range(f64, f64), + /// Stored as a fraction, written as a percentage. + Percent, + /// Multiplied by the factor when written. + Scale(f64), + /// Manual kerning in ems, written in thousandths of an em; 1e8 (the + /// root style's value) is left out. + Kerning, + /// An integer, written as such. + Integer, + /// A number, left out when 0. + NonZero, + /// The given value is written as the enumeration value, others as + /// numbers of the given IDML type. + NumberOr(f64, &'static str, &'static str), + /// A leading: negative for `Auto`. + Leading, + /// True when the value equals the given code. + Equals(u32), + /// 0 false, 1 true; other codes are not known. + Bool, + /// An enumeration value by code. + Enum(&'static [(u32, &'static str)]), + /// A built-in style named by its code (reference 0), written as + /// ``. + Builtin(&'static str, &'static [(u32, &'static str)]), + /// A stroke style code in the first of two words; the second is 0. + StrokeType, + /// Two f64. + Point, + /// A swatch UID. + Swatch, + /// A swatch, or 0 for "Text Color". + SwatchOrText, + /// A font family. + Font, + /// A font family, or 0 for none (`$ID/`). + FontOrNone, + /// A string. + String, + /// A string, or the empty string for `Nothing`. + StringOrNothing, + /// Text; left out when empty. + Text, + /// A language object, written as `$ID/`. + Language, + /// A character style reference. + CharacterStyle, + /// A cell style UID; 0 is written as `n`. + CellStyle, + /// A kinsoku or mojikumi set: 0 `Nothing`, a built-in table (written + /// as its enumeration value) or a custom kinsoku table (an object). + CjkSet, + /// A list of tab stops (`TabList`). + TabList, + /// A list of nested styles (`AllNestedStyles`). + NestedStyles, + /// A bullet character (`BulletChar`). + BulletChar, +} + +impl Kind { + /// Whether a value without an IDML value is reported to `indd audit` + /// as an unknown code. + pub(super) fn is_code(self) -> bool { + matches!( + self, + Kind::Enum(_) | Kind::Builtin(..) | Kind::StrokeType | Kind::Bool + ) + } +} + +/// Built-in kinsoku and mojikumi tables observed in the corpus +/// (`docs/format/attributes.md`): table name and IDML enumeration value. +const BUILTIN_CJK_TABLES: [(&str, &str); 6] = [ + ("$ID/kHardKinsokuName", "HardKinsoku"), + ("$ID/kSoftKinsokuName", "SoftKinsoku"), + ("$ID/kKoreanKinsokuName", "KoreanKinsoku"), + ("$ID/kSimpChineseKinsokuName", "SimplifiedChineseKinsoku"), + ("$ID/kMojikumiDefaultName1", "LineEndAllOneHalfEmEnum"), + ("$ID/kMojikumiDefaultName16", "SimpChineseDefault"), +]; + +fn text(ty: &'static str, s: String) -> (&'static str, PropValue) { + (ty, PropValue::Text(s)) +} + +impl Writer<'_> { + /// The IDML type and value of `v` written as `kind`; `None` if it has + /// no IDML value. + pub(super) fn value(&self, kind: Kind, v: &Value) -> Option<(&'static str, PropValue)> { + let swatch = |u: u32| self.doc.swatches.get(&u).cloned(); + let number = || v.as_f64().or(v.as_u32().map(f64::from)); + match kind { + Kind::Number => number().map(|f| text("unit", num(f))), + Kind::Range(lo, hi) => v + .as_f64() + .filter(|f| (lo..=hi).contains(f)) + .map(|f| text("unit", num(f))), + Kind::Percent => v.as_f64().map(|f| text("unit", num(round(f * 100.0)))), + Kind::Scale(k) => v.as_f64().map(|f| text("unit", num(round(f * k)))), + Kind::Kerning => v + .as_f64() + .filter(|&f| f != KERNING_NONE) + .map(|f| text("unit", num(round(f * 1000.0)))), + Kind::Integer => v.as_u32().map(|u| text("long", u.to_string())), + Kind::NonZero => v + .as_u32() + .filter(|&u| u != 0) + .map(|u| text("long", u.to_string())), + Kind::NumberOr(code, name, ty) => v.as_f64().map(|f| { + if f == code { + text("enumeration", name.to_string()) + } else { + text(ty, num(f)) + } + }), + Kind::Leading => v.as_f64().map(|f| { + if f < 0.0 { + text("enumeration", "Auto".into()) + } else { + text("unit", num(f)) + } + }), + Kind::Equals(t) => v.as_u32().map(|u| text("boolean", (u == t).to_string())), + Kind::Bool => match v.as_u32()? { + 0 => Some(text("boolean", "false".into())), + 1 => Some(text("boolean", "true".into())), + _ => None, + }, + Kind::Enum(map) => v + .as_u32() + .and_then(|u| map.iter().find(|(k, _)| *k == u)) + .map(|(_, n)| text("enumeration", n.to_string())), + Kind::Builtin(prefix, map) => match v { + Value::RefOrCode(0, code) => map + .iter() + .find(|(k, _)| k == code) + .map(|(_, n)| text("object", format!("{prefix}{n}"))), + _ => None, + }, + Kind::StrokeType => match *v { + Value::Words(CELL_NO_STROKE_TYPE, 0) => Some(text("object", "n".into())), + Value::Words(code, 0) => STROKE_TYPES + .iter() + .find(|(k, _)| *k == code) + .map(|(_, n)| text("object", format!("StrokeStyle/$ID/{n}"))), + _ => None, + }, + Kind::Point => match *v { + Value::Point(x, y) => Some(text("unit", nums(&[x, y]))), + _ => None, + }, + Kind::Swatch => v.as_u32().and_then(swatch).map(|s| text("object", s)), + Kind::SwatchOrText => match v.as_u32()? { + 0 => Some(text("string", "Text Color".into())), + u => swatch(u).map(|s| text("object", s)), + }, + Kind::Font => v + .as_u32() + .and_then(|u| self.doc.fonts.get(&u)) + .map(|f| text("string", f.name.clone())), + Kind::FontOrNone => match v.as_u32()? { + 0 => Some(text("string", "$ID/".into())), + u => self + .doc + .fonts + .get(&u) + .map(|f| text("string", f.name.clone())), + }, + Kind::String => v.as_string().map(|s| text("string", s)), + Kind::StringOrNothing => v.as_string().map(|s| { + if s.is_empty() { + text("enumeration", "Nothing".into()) + } else { + text("string", s) + } + }), + Kind::Text => match v { + Value::Text(t) if !t.is_empty() => Some(text("string", t.clone())), + _ => None, + }, + Kind::Language => v + .as_u32() + .and_then(|u| self.doc.languages.get(&u)) + .map(|l| text("string", format!("$ID/{l}"))), + Kind::CharacterStyle => v + .as_u32() + .map(|u| text("object", self.style_ref(Some(u).filter(|&u| u != 0), false))), + Kind::CellStyle => match v.as_u32()? { + 0 => Some(text("object", "n".into())), + u => self + .doc + .cell_styles + .get(&u) + .map(|s| text("object", Self::table_style_ref("CellStyle", s))), + }, + Kind::CjkSet => { + let u = v.as_u32()?; + if u == 0 { + return Some(text("enumeration", "Nothing".into())); + } + let t = self.doc.cjk_tables.iter().find(|t| t.uid == u)?; + if let Some((_, e)) = BUILTIN_CJK_TABLES.iter().find(|(k, _)| *k == t.name) { + return Some(text("enumeration", e.to_string())); + } + if t.name.starts_with("$ID/") || t.mojikumi { + return None; + } + Some(text( + "object", + format!("KinsokuTable/{}", self_name(&t.name)), + )) + } + Kind::TabList => match v { + Value::TabList(stops) => tab_list(stops).map(|l| ("list", PropValue::List(l))), + _ => None, + }, + Kind::NestedStyles => match v { + Value::StyleList { + nested: Some(n), .. + } => Some(("list", PropValue::List(self.nested_styles(n)))), + _ => None, + }, + Kind::BulletChar => match *v { + Value::BulletChar { kind, value } => bullet_char(kind, value).map(|a| ("", a)), + _ => None, + }, + } + } + + /// The IDML text of `v` written as `kind`, for a plain attribute. + pub(super) fn value_text(&self, kind: Kind, v: &Value) -> Option { + match self.value(kind, v)?.1 { + PropValue::Text(t) => Some(t), + _ => None, + } + } + + /// The IDML values of the attributes of `attrs` listed in `table` (ID, + /// IDML name, kind), in table order. Values without an IDML value are + /// left out; unknown codes are reported to `indd audit`. + pub(super) fn attr_values( + &self, + attrs: &Attrs, + table: &[(u32, &'static str, Kind)], + ) -> Vec<(&'static str, String)> { + let mut out = Vec::new(); + for &(id, name, kind) in table { + let Some(v) = attrs.get(id) else { continue }; + match self.value_text(kind, v) { + Some(t) => out.push((name, t)), + None if kind.is_code() => attrs.unknown_code(id, v), + None => {} + } + } + out + } +} diff --git a/src/idml/mod.rs b/src/idml/mod.rs index c72a934..9898d64 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -10,6 +10,7 @@ mod attrs; mod designmap; mod format; +mod kind; mod pages; mod resources; mod spread; @@ -24,6 +25,7 @@ use attrs::*; pub use format::num; pub(crate) use format::round; use format::*; +use kind::Kind; use pages::*; use styles::*; diff --git a/src/idml/resources.rs b/src/idml/resources.rs index 70f270d..81e563c 100644 --- a/src/idml/resources.rs +++ b/src/idml/resources.rs @@ -412,8 +412,8 @@ impl Writer<'_> { ours[i] .attrs .extend(values.into_iter().map(|(k, v)| (k.to_string(), v))); - let all: Vec = FITTING_ATTRS.iter().map(|(id, _)| *id).collect(); - let fitting = fitting_attrs(a, &all); + let all: Vec = FITTING_ATTRS.iter().map(|(id, ..)| *id).collect(); + let fitting = fitting_attrs(self, a, &all); if !fitting.is_empty() { let i = ours_of(&mut ours, "FrameFittingOption"); ours[i] diff --git a/src/idml/spread.rs b/src/idml/spread.rs index 8e29505..320daa2 100644 --- a/src/idml/spread.rs +++ b/src/idml/spread.rs @@ -458,9 +458,7 @@ impl Writer<'_> { ], ); } - for (effect, attr, v) in - transparency::write(x, &item.attrs, &uref(Some(item.uid)), &self.doc.swatches) - { + for (effect, attr, v) in transparency::write(self, x, &item.attrs, &uref(Some(item.uid))) { self.warnings.borrow_mut().push(format!( "item {}: {effect} {attr} {v} is outside the IDML range; left out", item.uid @@ -485,7 +483,7 @@ impl Writer<'_> { .and_then(|u| self.doc.object_styles.get(&u)); let differ: Vec = FITTING_ATTRS .iter() - .map(|(id, _)| *id) + .map(|(id, ..)| *id) .filter(|&id| { item.attrs .get(id) @@ -493,12 +491,12 @@ impl Writer<'_> { }) .collect(); let attrs = if !differ.is_empty() { - fitting_attrs(&item.attrs, &differ) + fitting_attrs(self, &item.attrs, &differ) } else { match style { Some(s) if !(s.builtin && s.name == "[None]" && s.based_on.is_none()) => { - let all: Vec = FITTING_ATTRS.iter().map(|(id, _)| *id).collect(); - fitting_attrs(&s.fitting, &all) + let all: Vec = FITTING_ATTRS.iter().map(|(id, ..)| *id).collect(); + fitting_attrs(self, &s.fitting, &all) } _ => Vec::new(), } diff --git a/src/idml/styles.rs b/src/idml/styles.rs index 68d0a89..16a429f 100644 --- a/src/idml/styles.rs +++ b/src/idml/styles.rs @@ -580,8 +580,11 @@ impl Writer<'_> { ); } } - let all: Vec = FITTING_ATTRS.iter().map(|(id, _)| *id).collect(); - node.set(&["FrameFittingOption"], fitting_attrs(&os.fitting, &all)); + let all: Vec = FITTING_ATTRS.iter().map(|(id, ..)| *id).collect(); + node.set( + &["FrameFittingOption"], + fitting_attrs(self, &os.fitting, &all), + ); if let Some(d) = &os.anchor { node.set(&["AnchoredObjectSetting"], anchored_settings(d)); } diff --git a/src/idml/transparency.rs b/src/idml/transparency.rs index 2076532..55df9df 100644 --- a/src/idml/transparency.rs +++ b/src/idml/transparency.rs @@ -1,23 +1,10 @@ //! Transparency settings of page items. See `docs/format/transparency.md`. -use std::collections::BTreeMap; - -use super::num; +use super::kind::Kind; use super::xml::Xml; +use super::{Writer, num}; use crate::model::{Attrs, Value}; -#[derive(Clone, Copy)] -enum Kind { - Number, - /// A number the IDML schema limits to this range (inclusive). - Range(f64, f64), - Bool, - Point, - Enum(&'static [(u32, &'static str)]), - /// A swatch UID, written only when the effect is applied. - Swatch, -} - /// Blend mode codes seen in the corpus. const BLEND_MODES: &[(u32, &str)] = &[ (0, "Normal"), @@ -248,48 +235,15 @@ fn stops(raw: &[[f64; 3]]) -> Option> { ) } -/// A value as IDML text; `Err` with the value when it is outside the -/// schema's range. -fn value(v: &Value, kind: Kind, swatches: &BTreeMap) -> Option> { - if let Kind::Range(lo, hi) = kind { - let f = v.as_f64()?; - return Some(if (lo..=hi).contains(&f) { - Ok(num(f)) - } else { - Err(f) - }); - } - Some(Ok(match kind { - Kind::Range(..) => unreachable!(), - Kind::Number => v.as_f64().map(num), - Kind::Bool => match v.as_u32()? { - 0 => Some("false".into()), - 1 => Some("true".into()), - _ => None, - }, - Kind::Point => match v { - Value::Point(a, b) => Some(format!("{} {}", num(*a), num(*b))), - _ => None, - }, - Kind::Enum(map) => { - let code = v.as_u32()?; - map.iter() - .find(|(k, _)| *k == code) - .map(|(_, n)| n.to_string()) - } - Kind::Swatch => v.as_ref().and_then(|u| swatches.get(&u).cloned()), - }?)) -} - /// Write the transparency settings found in a page item's attribute list. /// `item` is the item's `Self`, which names the opacity stops. Returns the /// values left out because they are outside the schema's range, as /// (effect, attribute, value). pub(super) fn write( + w: &Writer, x: &mut Xml, attrs: &Attrs, item: &str, - swatches: &BTreeMap, ) -> Vec<(&'static str, &'static str, f64)> { let mut left_out = Vec::new(); let inner_shadow_applied = attrs.get(INNER_SHADOW_APPLIED).and_then(Value::as_u32) == Some(1); @@ -305,10 +259,16 @@ pub(super) fn write( continue; } let Some(v) = attrs.get(id) else { continue }; - match value(v, kind, swatches) { - Some(Ok(t)) => values.push((name, t)), - Some(Err(f)) => left_out.push((effect, name, f)), - None if matches!(kind, Kind::Enum(_) | Kind::Bool) => attrs.unknown_code(id, v), + if let Kind::Range(lo, hi) = kind + && let Some(f) = v.as_f64() + && !(lo..=hi).contains(&f) + { + left_out.push((effect, name, f)); + continue; + } + match w.value_text(kind, v) { + Some(t) => values.push((name, t)), + None if kind.is_code() => attrs.unknown_code(id, v), None => {} } }