feat: write preference values that every exported IDML has

This commit is contained in:
aiongg committed 2026-10-07 00:35:38 +00:00
1 parent c976451c2f
commit 0dc40563ab
5 files changed
+519 -27

No files matched your search

+41 -7
View File
@@ -1,7 +1,8 @@
# Values written from IDML observation
Some values the converter writes do not come from the INDD file. They are
values that every IDML exported by InDesign in the corpus has. They are
values that every IDML exported by InDesign in the corpus has, on the
root styles and in the preferences. They are
facts about InDesign's IDML output, not about the INDD format, and the
evidence is the corpus IDML files alone.
@@ -100,10 +101,43 @@ element in the package.
`PlatformName` is `$ID/` in all 4,464 `Font` elements of the corpus IDML
files (`fonts.md`). The converter writes that value on every font.
## Not yet written
## Preferences
`Resources/Preferences.xml` has more elements that every corpus IDML has
(`TextDefault`, `TextPreference`, `PageItemDefault`, `StoryPreference`,
`FootnoteOption` and others). Many of their attributes are the same in
all 88 files (for example 196 of the 276 attributes of `TextDefault`),
but others vary and may be stored in the INDD. They are not written yet.
`Resources/Preferences.xml` of every corpus IDML has the same 41
top-level elements (`TextDefault`, `TextPreference`,
`TextFramePreference`, `PageItemDefault`, `StoryPreference`,
`FootnoteOption`, `TransparencyDefaultContainerObject` and others; the
DOM 7 file lacks `EPubFixedLayoutExportPreference`). `tools/root_values.py`
collects each attribute, `Properties` child and child element attribute
of these elements with the same rule as for the root styles, and writes
the kept values to `src/idml/preference_values.xml`. The converter writes
those elements in the order the IDML files list them.
| Values | Same in | Written for version |
|---|---|---|
| 1,041 | 88 of 88 files | all |
| 66 | 87 of 87 files with DOM 12 or later | 12 and later |
| 46 | 80 of 80 files with DOM 15 or later | 15 and later |
For example `TextDefault` keeps 264 of its 317 values,
`TransparencyDefaultContainerObject` all 352 and `TextFramePreference`
32 of 34.
**Left out:**
- 230 values that vary between files, for example the page size,
margins and grid settings, 53 values of `TextDefault` (among them the
font and point size) and 12 of `TextPreference`.
- The document setup the converter reads from the INDD (`objects.md`):
`PageHeight`, `PageWidth`, `FacingPages`, `Intent` and the four bleed
offsets of `DocumentPreference`. The converter writes its own values
for these and adds the observed values for the rest of the element.
`ViewPreference` gets `RulerOrigin="SpreadOrigin"`, as before.
- 3 values that name a style other than a root style, which the package
need not contain: `AppliedTextObjectStyle` and `AppliedGridObjectStyle`
of `PageItemDefault`, `FootnoteTextStyle` of `FootnoteOption`.
- 20 values that only the 2 files with DOM 20 have. A value first seen
in a later version is kept only when at least 10 files show it.
Some of these values are probably stored in the INDD and may differ in a
document outside the corpus; none of them is read from the INDD yet.
+39 -11
View File
@@ -1676,25 +1676,53 @@ impl Writer<'_> {
fn preferences(&self) -> String {
let mut x = Xml::new();
self.package_root(&mut x, "Preferences");
// Values every exported IDML has (docs/format/idml-values.md);
// values read from the INDD take precedence.
let mut nodes = values::preferences(self.doc.version.major);
let mut set = |tag: &str, ours: Vec<(&str, String)>| {
let i = match nodes.iter().position(|n| n.tag == tag) {
Some(i) => i,
None => {
nodes.push(Node {
tag: tag.to_string(),
..Node::default()
});
nodes.len() - 1
}
};
let node = &mut nodes[i];
node.attrs
.retain(|(k, _)| !ours.iter().any(|(o, _)| o == k));
let rest = std::mem::take(&mut node.attrs);
node.attrs = ours.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
node.attrs.extend(rest);
};
if let Some(p) = &self.doc.preferences {
const INTENT: [&str; 3] = ["PrintIntent", "WebIntent", "MobileIntent"];
let [top, bottom, inside, outside] = p.bleed;
x.start("DocumentPreference")
.attr("PageHeight", num(p.page_height))
.attr("PageWidth", num(p.page_width))
.attr("FacingPages", p.facing_pages.to_string())
.attr("DocumentBleedTopOffset", num(top))
.attr("DocumentBleedBottomOffset", num(bottom))
.attr("DocumentBleedInsideOrLeftOffset", num(inside))
.attr("DocumentBleedOutsideOrRightOffset", num(outside));
let mut ours = vec![
("PageHeight", num(p.page_height)),
("PageWidth", num(p.page_width)),
("FacingPages", p.facing_pages.to_string()),
("DocumentBleedTopOffset", num(top)),
("DocumentBleedBottomOffset", num(bottom)),
("DocumentBleedInsideOrLeftOffset", num(inside)),
("DocumentBleedOutsideOrRightOffset", num(outside)),
];
if let Some(i) = INTENT.get(p.intent as usize) {
x.attr("Intent", *i);
ours.push(("Intent", i.to_string()));
}
x.end();
set("DocumentPreference", ours);
}
// Guide locations are written measured from the spread (see
// `guide`), so the ruler origin is stated rather than read.
x.empty("ViewPreference", &[("RulerOrigin", "SpreadOrigin".into())]);
set(
"ViewPreference",
vec![("RulerOrigin", "SpreadOrigin".into())],
);
for n in &nodes {
n.write(&mut x);
}
x.end();
x.finish()
}
+254
View File
@@ -0,0 +1,254 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Values that every IDML exported by InDesign in the corpus has in
Resources/Preferences.xml. The converter writes them; values it reads
from the INDD take precedence. Values in a block with MinimumVersion are
written only for documents of that InDesign version or later. Generated
by tools/root_values.py; evidence in docs/format/idml-values.md.
-->
<PreferenceValues>
<Values>
<ButtonPreference Name="" />
<PrintPreference PrintFile="" Copies="1" Collating="false" ReverseOrder="false" Sequence="All" PrintSpreads="false" PrintMasterPages="false" PrintNonprinting="false" PrintBlankPages="false" PrintGuidesGrids="false" PaperOffset="0" PaperGap="0" PaperTransverse="false" ScaleMode="ScaleWidthHeight" ScaleWidth="100" ScaleHeight="100" ScaleProportional="true" Thumbnails="false" Tile="false" TilingType="Auto" TilingOverlap="108" AllPrinterMarks="false" BleedMarks="false" ColorBars="false" MarkLineWeight="P25pt" BleedTop="0" BleedBottom="0" BleedInside="0" BleedOutside="0" IncludeSlugToPrint="false" TextAsBlack="false" Trapping="Off" Flip="None" Negative="false" SimulateOverprint="false" PrintCyan="true" PrintMagenta="true" PrintYellow="true" YellowAngle="0" PrintBlack="true" BlackAngle="45" FontDownloading="Complete" DownloadPPDFonts="true" SourceSpace="UseDocument" Intent="AbsoluteColorimetric" OPIImageReplacement="false" OmitEPS="false" OmitPDF="false" OmitBitmaps="false" FlattenerPresetName="$ID/kFlSt_MediumDefaultName" IgnoreSpreadOverrides="false" CompositeScreening="$ID/kDefault" BleedChain="false" BitmapResolution="300" PrintLayers="VisiblePrintableLayers">
<Properties>
<PaperHeight type="enumeration">Auto</PaperHeight>
<PaperWidth type="enumeration">Auto</PaperWidth>
<MarkType type="enumeration">Default</MarkType>
<Screening type="enumeration">Default</Screening>
<Profile type="enumeration">UseDocument</Profile>
<CRD type="enumeration">Default</CRD>
<PageRange type="enumeration">AllPages</PageRange>
</Properties>
</PrintPreference>
<PrintBookletOption BookletType="TwoUpSaddleStitch" SpaceBetweenPages="0" BleedBetweenPages="0" Creep="0" SignatureSize="SignatureSize4" TopMargin="36" BottomMargin="36" LeftMargin="36" RightMargin="36" AutoAdjustMargins="true" MarginsUniformSize="false" PrintBlankPrinterSpreads="true">
<Properties>
<PageRange type="enumeration">AllPages</PageRange>
</Properties>
</PrintBookletOption>
<PrintBookletPrintPreference PrinterList="" PPDList="" PaperSizeList="" ScreeningList="" PrintFile="" Copies="1" Collating="false" ReverseOrder="false" PrintNonprinting="false" PrintBlankPages="false" PrintGuidesGrids="false" PaperOffset="0" PaperGap="0" PaperTransverse="false" PagePosition="UpperLeft" ScaleMode="ScaleWidthHeight" ScaleWidth="100" ScaleHeight="100" ScaleProportional="true" PrintLayers="VisiblePrintableLayers" AllPrinterMarks="false" CropMarks="false" BleedMarks="false" RegistrationMarks="false" ColorBars="false" PageInformationMarks="false" MarkLineWeight="P25pt" MarkOffset="6" UseDocumentBleedToPrint="true" BleedTop="0" BleedBottom="0" BleedInside="0" BleedOutside="0" BleedChain="false" TextAsBlack="false" Trapping="Off" Flip="None" Negative="false" SimulateOverprint="false" PrintCyan="true" PrintMagenta="true" PrintYellow="true" YellowAngle="0" PrintBlack="true" BlackAngle="45" FontDownloading="Complete" DownloadPPDFonts="true" SourceSpace="UseDocument" Intent="AbsoluteColorimetric" OPIImageReplacement="false" OmitEPS="false" OmitPDF="false" OmitBitmaps="false" FlattenerPresetName="$ID/kFlSt_MediumDefaultName" IgnoreSpreadOverrides="false" BitmapResolution="300" CompositeScreening="$ID/kDefault" SpotAngle="45">
<Properties>
<PaperHeight type="enumeration">Auto</PaperHeight>
<PaperWidth type="enumeration">Auto</PaperWidth>
<MarkType type="enumeration">Default</MarkType>
<Screening type="enumeration">Default</Screening>
<Profile type="enumeration">UseDocument</Profile>
<CRD type="enumeration">Default</CRD>
<ActivePrinterPreset type="enumeration">Default</ActivePrinterPreset>
</Properties>
</PrintBookletPrintPreference>
<PageItemDefault FillColor="Swatch/None" FillTint="-1" MiterLimit="4" EndCap="ButtEndCap" EndJoin="MiterEndJoin" StrokeType="StrokeStyle/$ID/Solid" LeftLineEnd="None" RightLineEnd="None" StrokeColor="Swatch/None" StrokeTint="-1" GradientFillAngle="0" GradientStrokeAngle="0" GapColor="Swatch/None" GapTint="-1" StrokeAlignment="CenterAlignment" Nonprinting="false" />
<FrameFittingOption AutoFit="false" BottomCrop="0" FittingOnEmptyFrame="None" />
<StoryPreference OpticalMarginAlignment="false" OpticalMarginSize="12" FrameType="TextFrameType" StoryOrientation="Horizontal" StoryDirection="LeftToRightDirection" />
<TextFramePreference TextColumnCount="1" TextColumnFixedWidth="144" UseFixedColumnWidth="false" FirstBaselineOffset="AscentOffset" MinimumFirstBaselineOffset="0" VerticalJustification="TopAlign" VerticalThreshold="0" IgnoreWrap="false" VerticalBalanceColumns="false">
<Properties>
<InsetSpacing type="list"><ListItem type="unit">0</ListItem><ListItem type="unit">0</ListItem><ListItem type="unit">0</ListItem><ListItem type="unit">0</ListItem></InsetSpacing>
</Properties>
</TextFramePreference>
<TextPreference HighlightHjViolations="false" HighlightKeeps="false" HighlightSubstitutedGlyphs="false" HighlightCustomSpacing="false" HighlightSubstitutedFonts="true" UseOpticalSize="true" UseParagraphLeading="false" SuperscriptSize="58.3" SuperscriptPosition="33.3" SubscriptSize="58.3" SmallCap="70" JustifyTextWraps="false" AbutTextToTextWrap="true" LinkTextFilesWhenImporting="false" HighlightKinsoku="false" UseNewVerticalScaling="false" UseCidMojikumi="false" EnableStylePreviewMode="false" AddPages="EndOfStory" LimitToMasterTextFrames="true" PreserveFacingPageSpreads="false" DeleteEmptyPages="false" />
<TextDefault RightIndent="0" SpaceBefore="0" Justification="LeftAlign" SingleWordJustification="FullyJustified" AutoLeading="120" DropCapLines="0" DropCapCharacters="0" KeepLinesTogether="false" KeepAllLinesTogether="false" KeepWithNext="0" KeepFirstLines="2" KeepLastLines="2" StartParagraph="Anywhere" MinimumWordSpacing="80" MaximumWordSpacing="133" DesiredWordSpacing="100" MinimumLetterSpacing="0" MaximumLetterSpacing="0" DesiredLetterSpacing="0" MinimumGlyphScaling="100" MaximumGlyphScaling="100" DesiredGlyphScaling="100" RuleAbove="false" RuleAboveOverprint="false" RuleAboveTint="-1" RuleAboveLeftIndent="0" RuleAboveRightIndent="0" RuleAboveWidth="ColumnWidth" RuleAboveGapTint="-1" RuleAboveGapOverprint="false" RuleBelow="false" RuleBelowLeftIndent="0" RuleBelowRightIndent="0" RuleBelowWidth="ColumnWidth" RuleBelowGapTint="-1" HyphenateCapitalizedWords="true" HyphenateBeforeLast="2" HyphenateAfterFirst="2" HyphenateWordsLongerThan="5" HyphenateLadderLimit="3" HyphenWeight="5" KerningMethod="$ID/Metrics" Position="Normal" Underline="false" StrikeThru="false" NoBreak="false" HorizontalScale="100" VerticalScale="100" BaselineShift="0" Skew="0" StrokeTint="-1" OverprintStroke="false" OverprintFill="false" OTFOrdinal="false" OTFFraction="false" OTFDiscretionaryLigature="false" OTFTitling="false" OTFSwash="false" UnderlineTint="-1" UnderlineGapTint="-1" UnderlineOverprint="false" UnderlineGapOverprint="false" UnderlineOffset="-9999" UnderlineWeight="-9999" StrikeThroughTint="-1" StrikeThroughGapTint="-1" StrikeThroughOverprint="false" StrikeThroughGapOverprint="false" StrikeThroughOffset="-9999" StrikeThroughWeight="-9999" StrokeColor="Swatch/None" KeepWithPrevious="false" SpanColumnType="SingleColumn" SplitColumnOutsideGutter="0" SpanColumnMinSpaceBefore="0" SpanColumnMinSpaceAfter="0" LastLineIndent="0" HyphenateLastWord="true" OTFSlashedZero="false" OTFHistorical="false" OTFStylisticSets="0" GradientFillLength="-1" GradientFillAngle="0" GradientStrokeLength="-1" GradientStrokeAngle="0" GradientFillStart="0 0" GradientStrokeStart="0 0" RuleBelowOverprint="false" RuleBelowGapOverprint="false" HyphenateAcrossColumns="true" KeepRuleAboveInFrame="false" IgnoreEdgeAlignment="false" OTFMark="true" OTFLocale="true" PositionalForm="None" ParagraphDirection="LeftToRightDirection" ParagraphJustification="DefaultJustification" StrokeAlignment="OutsideAlignment" EndJoin="MiterEndJoin" OTFOverlapSwash="false" OTFStylisticAlternate="false" OTFJustificationAlternate="false" OTFStretchedAlternate="false" CharacterDirection="DefaultDirection" KeyboardDirection="DefaultDirection" DigitsType="DefaultDigits" Kashidas="DefaultKashidas" XOffsetDiacritic="0" YOffsetDiacritic="0" ParagraphBreakType="Anywhere" PageNumberType="AutoPageNumber" CharacterAlignment="AlignEmCenter" Tsume="0" LeadingAki="-1" TrailingAki="-1" CharacterRotation="0" Jidori="0" ShataiMagnification="0" ShataiDegreeAngle="4500" ShataiAdjustRotation="false" ShataiAdjustTsume="true" Tatechuyoko="false" TatechuyokoXOffset="0" TatechuyokoYOffset="0" KentenTint="-1" KentenStrokeTint="-1" KentenWeight="-1" KentenOverprintFill="Auto" KentenOverprintStroke="Auto" KentenKind="None" KentenPlacement="0" KentenAlignment="AlignKentenCenter" KentenPosition="AboveRight" KentenFontSize="-1" KentenXScale="100" KentenYScale="100" KentenCustomCharacter="" KentenCharacterSet="CharacterInput" RubyTint="-1" RubyWeight="-1" RubyOverprintFill="Auto" RubyOverprintStroke="Auto" RubyStrokeTint="-1" RubyFontSize="-1" RubyOpenTypePro="true" RubyXScale="100" RubyYScale="100" RubyType="PerCharacterRuby" RubyAlignment="RubyJIS" RubyPosition="AboveRight" RubyXOffset="0" RubyYOffset="0" RubyParentSpacing="RubyParent121Aki" RubyAutoAlign="true" RubyOverhang="false" RubyAutoScaling="false" RubyParentScalingPercent="66" RubyParentOverhangAmount="RubyOverhangOneRuby" Warichu="false" WarichuSize="50" WarichuLines="2" WarichuLineSpacing="0" WarichuAlignment="Auto" WarichuCharsAfterBreak="2" WarichuCharsBeforeBreak="2" OTFProportionalMetrics="false" OTFHVKana="false" OTFRomanItalics="false" ScaleAffectsLineHeight="false" CjkGridTracking="false" GlyphForm="None" GridAlignFirstLineOnly="false" GridAlignment="None" GridGyoudori="0" AutoTcy="0" AutoTcyIncludeRoman="false" KinsokuType="KinsokuPushInFirst" KinsokuHangType="None" BunriKinshi="true" Rensuuji="true" RotateSingleByteCharacters="false" LeadingModel="LeadingModelAkiBelow" RubyAutoTcyDigits="0" RubyAutoTcyIncludeRoman="false" RubyAutoTcyAutoScale="true" AllowArbitraryHyphenation="false" ParagraphGyoudori="false" NumberingExpression="^#.^t" BulletsTextAfter="^t" NumberingLevel="1" NumberingContinue="true" NumberingStartAt="1" NumberingApplyRestartPolicy="true" BulletsAlignment="LeftAlign" NumberingAlignment="LeftAlign" AppliedNamedGrid="n">
<Properties>
<BalanceRaggedLines type="enumeration">NoBalancing</BalanceRaggedLines>
<RuleAboveColor type="string">Text Color</RuleAboveColor>
<RuleAboveGapColor type="object">Swatch/None</RuleAboveGapColor>
<RuleAboveType type="object">StrokeStyle/$ID/Solid</RuleAboveType>
<RuleBelowGapColor type="object">Swatch/None</RuleBelowGapColor>
<RuleBelowType type="object">StrokeStyle/$ID/Solid</RuleBelowType>
<UnderlineColor type="string">Text Color</UnderlineColor>
<UnderlineGapColor type="object">Swatch/None</UnderlineGapColor>
<UnderlineType type="object">StrokeStyle/$ID/Solid</UnderlineType>
<StrikeThroughColor type="string">Text Color</StrikeThroughColor>
<StrikeThroughGapColor type="object">Swatch/None</StrikeThroughGapColor>
<StrikeThroughType type="object">StrokeStyle/$ID/Solid</StrikeThroughType>
<SpanSplitColumnCount type="enumeration">All</SpanSplitColumnCount>
<KentenFillColor type="string">Text Color</KentenFillColor>
<KentenStrokeColor type="string">Text Color</KentenStrokeColor>
<KentenFont type="string">$ID/</KentenFont>
<KentenFontStyle type="enumeration">Nothing</KentenFontStyle>
<RubyFill type="string">Text Color</RubyFill>
<RubyStroke type="string">Text Color</RubyStroke>
<RubyFont type="string">$ID/</RubyFont>
<RubyFontStyle type="enumeration">Nothing</RubyFontStyle>
<BulletChar BulletCharacterType="UnicodeOnly" BulletCharacterValue="8226" />
<BulletsFont type="string">$ID/</BulletsFont>
<BulletsFontStyle type="enumeration">Nothing</BulletsFontStyle>
<NumberingCharacterStyle type="object">CharacterStyle/$ID/[No character style]</NumberingCharacterStyle>
<AppliedNumberingList type="object">NumberingList/$ID/[Default]</AppliedNumberingList>
<NumberingFormat type="string">1, 2, 3, 4...</NumberingFormat>
<NumberingRestartPolicies RestartPolicy="AnyPreviousLevel" LowerLevel="0" UpperLevel="0" />
</Properties>
</TextDefault>
<DictionaryPreference RecomposeWhenChanged="true" />
<AnchoredObjectDefault AnchorContent="Unassigned" InitialAnchorHeight="72" InitialAnchorWidth="72" AnchoredParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" AnchoredObjectStyle="ObjectStyle/$ID/[None]" />
<AnchoredObjectSetting AnchoredPosition="InlinePosition" SpineRelative="false" LockPosition="false" PinPosition="true" AnchorPoint="BottomRightAnchor" HorizontalAlignment="LeftAlign" HorizontalReferencePoint="TextFrame" VerticalReferencePoint="LineBaseline" AnchorXoffset="0" AnchorYoffset="0" AnchorSpaceAbove="0" />
<BaselineFrameGridOption UseCustomBaselineFrameGrid="false" StartingOffsetForBaselineFrameGrid="0" BaselineFrameGridRelativeOption="TopOfInset" BaselineFrameGridIncrement="12">
<Properties>
<BaselineFrameGridColor type="enumeration">LightBlue</BaselineFrameGridColor>
</Properties>
</BaselineFrameGridOption>
<FootnoteOption StartAt="1" Prefix="" Suffix="" FootnoteMarkerStyle="CharacterStyle/$ID/[No character style]" SeparatorText="&#9;" SpaceBetween="0" Spacer="0" FootnoteFirstBaselineOffset="LeadingOffset" FootnoteMinimumFirstBaselineOffset="0" EosPlacement="false" NoSplitting="false" RuleOn="true" RuleLineWeight="1" RuleTint="100" RuleGapTint="100" RuleGapOverprint="false" RuleOverprint="false" RuleLeftIndent="0" RuleWidth="72" RuleOffset="0" ContinuingRuleOn="true" ContinuingRuleLineWeight="1" ContinuingRuleTint="100" ContinuingRuleGapTint="100" ContinuingRuleOverprint="false" ContinuingRuleGapOverprint="false" ContinuingRuleLeftIndent="0" ContinuingRuleWidth="288" ContinuingRuleOffset="0">
<Properties>
<FootnoteNumberingStyle type="enumeration">Arabic</FootnoteNumberingStyle>
<RestartNumbering type="enumeration">DontRestart</RestartNumbering>
<ShowPrefixSuffix type="enumeration">NoPrefixSuffix</ShowPrefixSuffix>
<MarkerPositioning type="enumeration">SuperscriptMarker</MarkerPositioning>
<RuleType type="object">StrokeStyle/$ID/Solid</RuleType>
<RuleColor type="object">Color/Black</RuleColor>
<RuleGapColor type="object">Swatch/None</RuleGapColor>
<ContinuingRuleType type="object">StrokeStyle/$ID/Solid</ContinuingRuleType>
<ContinuingRuleColor type="object">Color/Black</ContinuingRuleColor>
<ContinuingRuleGapColor type="object">Swatch/None</ContinuingRuleGapColor>
</Properties>
</FootnoteOption>
<TextWrapPreference Inverse="false" ApplyToMasterPageOnly="false" TextWrapSide="BothSides" TextWrapMode="None">
<Properties>
<TextWrapOffset Top="0" Left="0" Bottom="0" Right="0" />
</Properties>
<ContourOption ContourType="SameAsClipping" IncludeInsideEdges="false" ContourPathName="$ID/" />
</TextWrapPreference>
<MojikumiUiPreference MojikumiUiSettings="16383" />
<XMLImportPreference ImportStyle="MergeImport" CreateLinkToXML="false" IgnoreUnmatchedIncoming="false" IgnoreWhitespace="false">
<Properties>
<TransformFilename type="enumeration">StylesheetInXML</TransformFilename>
<TransformParameters></TransformParameters>
</Properties>
</XMLImportPreference>
<XMLExportPreference ViewAfterExport="false" ExportFromSelected="false" FileEncoding="UTF8" Ruby="false" ExcludeDtd="true" CopyOriginalImages="false" CopyOptimizedImages="false" CopyFormattedImages="false" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="Medium" JPEGOptionsFormat="BaselineEncoding" AllowTransform="false" CharacterReferences="false" ExportUntaggedTablesFormat="CALS">
<Properties>
<PreferredBrowser type="enumeration">Nothing</PreferredBrowser>
<TransformFilename type="enumeration">StylesheetInXML</TransformFilename>
</Properties>
</XMLExportPreference>
<XMLPreference>
<Properties>
<DefaultStoryTagColor type="enumeration">BrickRed</DefaultStoryTagColor>
<DefaultTableTagColor type="enumeration">DarkBlue</DefaultTableTagColor>
<DefaultCellTagColor type="enumeration">GrassGreen</DefaultCellTagColor>
<DefaultImageTagColor type="enumeration">Violet</DefaultImageTagColor>
</Properties>
</XMLPreference>
<ExportForWebPreference CopyFormattedImages="false" CopyOptimizedImages="false" CopyOriginalImages="false" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="Medium" JPEGOptionsFormat="BaselineEncoding" />
<IndexOptions TitleStyle="ParagraphStyle/$ID/[No paragraph style]" ReplaceExistingIndex="true" IncludeBookDocuments="false" IncludeHiddenEntries="false" IndexFormat="NestedFormat" IncludeSectionHeadings="true" IncludeEmptyIndexSections="false" Level1Style="ParagraphStyle/$ID/[No paragraph style]" Level2Style="ParagraphStyle/$ID/[No paragraph style]" Level3Style="ParagraphStyle/$ID/[No paragraph style]" Level4Style="ParagraphStyle/$ID/[No paragraph style]" SectionHeadingStyle="ParagraphStyle/$ID/[No paragraph style]" PageNumberStyle="CharacterStyle/$ID/[No character style]" CrossReferenceStyle="CharacterStyle/$ID/[No character style]" CrossReferenceTopicStyle="CharacterStyle/$ID/[No character style]" FollowingTopicSeparator=" " BetweenEntriesSeparator="; " PageRangeSeparator="^=" BetweenPageNumbersSeparator=", " BeforeCrossReferenceSeparator=". " EntryEndSeparator="" />
<IndexHeaderSetting HeaderSetName="$ID/" HeaderSetLanguage="256" IndexHeaderSetHandler="77882" IndexHeaderSetGroupValue="0" IndexHeaderSetGroupOptionValue="0" />
<TinDocumentDataObject>
<Properties>
<GaijiRefMaps>/////wAAAAAAAAAA</GaijiRefMaps>
</Properties>
</TinDocumentDataObject>
<ChapterNumberPreference ChapterNumber="1" ChapterNumberSource="ContinueFromPreviousDocument">
<Properties>
<ChapterNumberFormat type="string">1, 2, 3, 4...</ChapterNumberFormat>
</Properties>
</ChapterNumberPreference>
<DocumentPreference PagesPerDocument="1" DocumentBleedUniformSize="true" SlugTopOffset="0" SlugBottomOffset="0" SlugRightOrOutsideOffset="0" DocumentSlugUniformSize="false" PreserveLayoutWhenShuffling="true" AllowPageShuffle="true" OverprintBlack="true" PageBinding="LeftToRight" ColumnDirection="Horizontal" SnippetImportUsesOriginalLocation="false">
<Properties>
<ColumnGuideColor type="enumeration">Violet</ColumnGuideColor>
<MarginGuideColor type="enumeration">Magenta</MarginGuideColor>
</Properties>
</DocumentPreference>
<GridPreference DocumentGridShown="false" DocumentGridSnapto="false" BaselineGridRelativeOption="TopOfPageOfBaselineGridRelativeOption">
<Properties>
<GridColor type="enumeration">LightGray</GridColor>
<BaselineColor type="enumeration">LightBlue</BaselineColor>
</Properties>
</GridPreference>
<GuidePreference GuidesInBack="false" GuidesShown="true" GuidesSnapto="true" RulerGuidesViewThreshold="5">
<Properties>
<RulerGuidesColor type="enumeration">Cyan</RulerGuidesColor>
</Properties>
</GuidePreference>
<MarginPreference ColumnDirection="Horizontal" />
<PasteboardPreference>
<Properties>
<BleedGuideColor type="enumeration">Fiesta</BleedGuideColor>
<SlugGuideColor type="enumeration">GridBlue</SlugGuideColor>
</Properties>
</PasteboardPreference>
<ViewPreference GuideSnaptoZone="4" TypographicMeasurementUnits="Points" TextSizeMeasurementUnits="Points" PointsPerInch="72" HorizontalCustomPoints="12" VerticalCustomPoints="12" />
<TransparencyPreference GlobalLightAngle="120" GlobalLightAltitude="30" />
<TransparencyDefaultContainerObject>
<TransparencySetting>
<BlendingSetting BlendMode="Normal" Opacity="100" KnockoutGroup="false" IsolateBlending="false" />
<DropShadowSetting Mode="None" BlendMode="Multiply" Opacity="75" XOffset="7" YOffset="7" Size="5" EffectColor="n" Noise="0" Spread="0" UseGlobalLight="false" KnockedOut="true" HonorOtherEffects="false" />
<FeatherSetting Mode="None" Width="9" CornerType="Diffusion" Noise="0" ChokeAmount="0" />
<InnerShadowSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="75" Angle="120" Distance="7" UseGlobalLight="false" ChokeAmount="0" Size="7" Noise="0" />
<OuterGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" />
<InnerGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" Source="EdgeSourced" />
<BevelAndEmbossSetting Applied="false" Style="InnerBevel" Technique="SmoothContour" Depth="100" Direction="Up" Size="7" Soften="0" Angle="120" Altitude="30" UseGlobalLight="false" HighlightColor="n" HighlightBlendMode="Screen" HighlightOpacity="75" ShadowColor="n" ShadowBlendMode="Multiply" ShadowOpacity="75" />
<SatinSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="50" Angle="120" Distance="7" Size="7" InvertEffect="false" />
<DirectionalFeatherSetting Applied="false" LeftWidth="0" RightWidth="0" TopWidth="0" BottomWidth="0" ChokeAmount="0" Angle="0" FollowShapeMode="LeadingEdge" Noise="0" />
<GradientFeatherSetting Applied="false" Type="Linear" Angle="0" Length="0" GradientStart="0 0" HiliteAngle="0" HiliteLength="0" />
</TransparencySetting>
<StrokeTransparencySetting>
<BlendingSetting BlendMode="Normal" Opacity="100" KnockoutGroup="false" IsolateBlending="false" />
<DropShadowSetting Mode="None" BlendMode="Multiply" Opacity="75" XOffset="7" YOffset="7" Size="5" EffectColor="n" Noise="0" Spread="0" UseGlobalLight="false" KnockedOut="true" HonorOtherEffects="false" />
<FeatherSetting Mode="None" Width="9" CornerType="Diffusion" Noise="0" ChokeAmount="0" />
<InnerShadowSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="75" Angle="120" Distance="7" UseGlobalLight="false" ChokeAmount="0" Size="7" Noise="0" />
<OuterGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" />
<InnerGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" Source="EdgeSourced" />
<BevelAndEmbossSetting Applied="false" Style="InnerBevel" Technique="SmoothContour" Depth="100" Direction="Up" Size="7" Soften="0" Angle="120" Altitude="30" UseGlobalLight="false" HighlightColor="n" HighlightBlendMode="Screen" HighlightOpacity="75" ShadowColor="n" ShadowBlendMode="Multiply" ShadowOpacity="75" />
<SatinSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="50" Angle="120" Distance="7" Size="7" InvertEffect="false" />
<DirectionalFeatherSetting Applied="false" LeftWidth="0" RightWidth="0" TopWidth="0" BottomWidth="0" ChokeAmount="0" Angle="0" FollowShapeMode="LeadingEdge" Noise="0" />
<GradientFeatherSetting Applied="false" Type="Linear" Angle="0" Length="0" GradientStart="0 0" HiliteAngle="0" HiliteLength="0" />
</StrokeTransparencySetting>
<FillTransparencySetting>
<BlendingSetting BlendMode="Normal" Opacity="100" KnockoutGroup="false" IsolateBlending="false" />
<DropShadowSetting Mode="None" BlendMode="Multiply" Opacity="75" XOffset="7" YOffset="7" Size="5" EffectColor="n" Noise="0" Spread="0" UseGlobalLight="false" KnockedOut="true" HonorOtherEffects="false" />
<FeatherSetting Mode="None" Width="9" CornerType="Diffusion" Noise="0" ChokeAmount="0" />
<InnerShadowSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="75" Angle="120" Distance="7" UseGlobalLight="false" ChokeAmount="0" Size="7" Noise="0" />
<OuterGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" />
<InnerGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" Source="EdgeSourced" />
<BevelAndEmbossSetting Applied="false" Style="InnerBevel" Technique="SmoothContour" Depth="100" Direction="Up" Size="7" Soften="0" Angle="120" Altitude="30" UseGlobalLight="false" HighlightColor="n" HighlightBlendMode="Screen" HighlightOpacity="75" ShadowColor="n" ShadowBlendMode="Multiply" ShadowOpacity="75" />
<SatinSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="50" Angle="120" Distance="7" Size="7" InvertEffect="false" />
<DirectionalFeatherSetting Applied="false" LeftWidth="0" RightWidth="0" TopWidth="0" BottomWidth="0" ChokeAmount="0" Angle="0" FollowShapeMode="LeadingEdge" Noise="0" />
<GradientFeatherSetting Applied="false" Type="Linear" Angle="0" Length="0" GradientStart="0 0" HiliteAngle="0" HiliteLength="0" />
</FillTransparencySetting>
<ContentTransparencySetting>
<BlendingSetting BlendMode="Normal" Opacity="100" KnockoutGroup="false" IsolateBlending="false" />
<DropShadowSetting Mode="None" BlendMode="Multiply" Opacity="75" XOffset="7" YOffset="7" Size="5" EffectColor="n" Noise="0" Spread="0" UseGlobalLight="false" KnockedOut="true" HonorOtherEffects="false" />
<FeatherSetting Mode="None" Width="9" CornerType="Diffusion" Noise="0" ChokeAmount="0" />
<InnerShadowSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="75" Angle="120" Distance="7" UseGlobalLight="false" ChokeAmount="0" Size="7" Noise="0" />
<OuterGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" />
<InnerGlowSetting Applied="false" BlendMode="Screen" Opacity="75" Noise="0" EffectColor="n" Technique="Softer" Spread="0" Size="7" Source="EdgeSourced" />
<BevelAndEmbossSetting Applied="false" Style="InnerBevel" Technique="SmoothContour" Depth="100" Direction="Up" Size="7" Soften="0" Angle="120" Altitude="30" UseGlobalLight="false" HighlightColor="n" HighlightBlendMode="Screen" HighlightOpacity="75" ShadowColor="n" ShadowBlendMode="Multiply" ShadowOpacity="75" />
<SatinSetting Applied="false" EffectColor="n" BlendMode="Multiply" Opacity="50" Angle="120" Distance="7" Size="7" InvertEffect="false" />
<DirectionalFeatherSetting Applied="false" LeftWidth="0" RightWidth="0" TopWidth="0" BottomWidth="0" ChokeAmount="0" Angle="0" FollowShapeMode="LeadingEdge" Noise="0" />
<GradientFeatherSetting Applied="false" Type="Linear" Angle="0" Length="0" GradientStart="0 0" HiliteAngle="0" HiliteLength="0" />
</ContentTransparencySetting>
</TransparencyDefaultContainerObject>
<LayoutGridDataInformation PointSize="12" CharacterAki="0" LineAki="9" HorizontalScale="100" VerticalScale="100" />
<StoryGridDataInformation PointSize="12" CharacterAki="0" LineAki="9" HorizontalScale="100" VerticalScale="100" LineAlignment="LeftOrTopLineJustify" GridAlignment="AlignEmCenter" CharacterAlignment="AlignEmCenter" GridView="GridViewEnum" CharacterCountLocation="BottomAlign" CharacterCountSize="9.21259842519685" />
<CjkGridPreference ShowAllLayoutGrids="false" ShowAllFrameGrids="true" MinimumScale="50" SnapToLayoutGrid="false" ColorEveryNthCell="10" SingleLineColorMode="true" ICFMode="false" UseCircularCells="false" ShowCharacterCount="true">
<Properties>
<LayoutGridColorIndex type="enumeration">GridGreen</LayoutGridColorIndex>
</Properties>
</CjkGridPreference>
<DataMergeOption FittingOption="Proportional" CenterImage="false" LinkImages="true" RemoveBlankLines="false" CreateNewDocument="false" DocumentSize="50" />
<LayoutAdjustmentPreference EnableLayoutAdjustment="false" AllowGraphicsToResize="true" AllowRulerGuidesToMove="true" IgnoreRulerGuideAlignments="false" IgnoreObjectOrLayerLocks="true" />
<EPubExportPreference EpubPublisher="" ExportOrder="LayoutOrder" EpubCover="FirstPage" CoverImageFile="" BulletExportOption="UnorderedList" NumberedListExportOption="OrderedList" ImageExportResolution="Ppi150" CustomImageSizeOption="SizeFixed" PreserveLayoutAppearence="true" ImageAlignment="AlignCenter" ImageSpaceBefore="0" ImageSpaceAfter="0" UseImagePageBreak="false" ImagePageBreak="PageBreakBefore" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="High" JPEGOptionsFormat="ProgressiveEncoding" IgnoreObjectConversionSettings="false" BreakDocument="false" ParagraphStyleName="$ID/NormalParagraphStyle" StripSoftReturn="false" PreserveLocalOverride="true" EmbedFont="true" IncludeDocumentMetadata="true" Level="5" CSSExportOption="EmbeddedCSS" Format="true" UseTocStyle="false" IncludeCSSDefinition="true" FootnoteFollowParagraph="false" />
<HTMLExportPreference ExportOrder="LayoutOrder" BulletExportOption="UnorderedList" NumberedListExportOption="OrderedList" ViewDocumentAfterExport="true" ImageExportOption="OptimizedImage" ImageExportResolution="Ppi150" CustomImageSizeOption="SizeFixed" PreserveLayoutAppearence="false" ImageAlignment="AlignCenter" ImageSpaceBefore="0" ImageSpaceAfter="0" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="High" JPEGOptionsFormat="ProgressiveEncoding" Level="5" IgnoreObjectConversionSettings="false" ServerPath="" ImageExtension=".jpg" PreserveLocalOverride="true" LeftMargin="0" RightMargin="0" TopMargin="0" BottomMargin="0" MarginUnit="CssPixel" IncludeCSSDefinition="true" CSSExportOption="EmbeddedCSS" />
</Values>
<Values MinimumVersion="12">
<PrintPreference PDFPassthrough="false" />
<PrintBookletPrintPreference PDFPassthrough="false" />
<PageItemDefault ArrowHeadAlignment="InsidePath" LeftArrowHeadScale="100" RightArrowHeadScale="100" />
<TextFramePreference UseFlexibleColumnWidth="false" TextColumnMaxWidth="0" AutoSizingType="Off" AutoSizingReferencePoint="CenterPoint" UseMinimumHeightForAutoSizing="false" MinimumHeightForAutoSizing="0" UseMinimumWidthForAutoSizing="false" MinimumWidthForAutoSizing="0" UseNoLineBreaksForAutoSizing="false" />
<TextDefault ParagraphShadingLeftOffset="0" ParagraphShadingRightOffset="0" ParagraphShadingTopOffset="0" ParagraphShadingBottomOffset="0" ParagraphShadingWidth="ColumnWidth" ParagraphShadingTopOrigin="AscentTopOrigin" ParagraphShadingBottomOrigin="DescentBottomOrigin" ParagraphShadingClipToFrame="false" ParagraphShadingSuppressPrinting="false" ParagraphShadingOn="false" ParagraphShadingOverprint="false" ParagraphKashidaWidth="2" />
<PasteboardPreference MatchPreviewBackgroundToThemeColor="false" />
<EPubExportPreference ExternalStyleSheets="" Javascripts="" GenerateCascadeStyleSheet="true" FootnotePlacement="FootnoteAfterStory" UseOriginalImageOnExport="false" EpubTitle="" EpubCreator="" EpubSubject="" EpubDescription="" EpubDate="" EpubRights="" UseExistingImageOnExport="false" />
<HTMLExportPreference ExternalStyleSheets="" Javascripts="" GenerateCascadeStyleSheet="true" />
<EPubFixedLayoutExportPreference Level="5" EpubPublisher="" Id="urn:uuid:29d919dd-24f5-4384-be78-b447c9dc299b" EpubCover="FirstPage" CoverImageFile="" ImageExportResolution="Ppi150" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="High" JPEGOptionsFormat="ProgressiveEncoding" TocStyleName="$ID/" ExternalStyleSheets="" Javascripts="" EpubTitle="" EpubCreator="" EpubSubject="" EpubDescription="" EpubDate="" EpubRights="" EpubPageRange="" EpubPageRangeFormat="ExportAllPages" EpubSpreadControlOptions="SpreadsBasedOnDoc" EpubNavigationStyles="NoNavigation" />
</Values>
<Values MinimumVersion="15">
<TextFramePreference FootnotesEnableOverrides="false" FootnotesSpanAcrossColumns="false" FootnotesMinimumSpacing="12" FootnotesSpaceBetween="6" ColumnRuleOverride="false" ColumnRuleOffset="0" ColumnRuleTopInset="0" ColumnRuleInsetChainOverride="true" ColumnRuleBottomInset="0" ColumnRuleStrokeWidth="1" ColumnRuleStrokeType="StrokeStyle/$ID/Solid" ColumnRuleStrokeTint="100" ColumnRuleOverprintOverride="false" />
<TextDefault ParagraphBorderOn="false" ParagraphBorderOverprint="false" ParagraphBorderTint="-1" ParagraphBorderGapOverprint="false" ParagraphBorderGapTint="-1" ParagraphBorderStrokeEndCap="ButtEndCap" ParagraphBorderStrokeEndJoin="MiterEndJoin" ParagraphShadingTopLeftCornerOption="None" ParagraphShadingTopRightCornerOption="None" ParagraphShadingBottomLeftCornerOption="None" ParagraphShadingBottomRightCornerOption="None" ParagraphBorderTopLeftCornerOption="None" ParagraphBorderTopRightCornerOption="None" ParagraphBorderBottomLeftCornerOption="None" ParagraphBorderBottomRightCornerOption="None" ParagraphBorderWidth="ColumnWidth" ParagraphBorderTopOrigin="AscentTopOrigin" ParagraphBorderBottomOrigin="DescentBottomOrigin" ParagraphBorderLeftOffset="0" ParagraphBorderRightOffset="0" ParagraphBorderTopOffset="0" ParagraphBorderBottomOffset="0" ParagraphBorderDisplayIfSplits="false" ProviderHyphenationStyle="HyphAll" MergeConsecutiveParaBorders="true">
<Properties>
<ParagraphBorderColor type="object">Color/Black</ParagraphBorderColor>
<ParagraphBorderGapColor type="object">Swatch/None</ParagraphBorderGapColor>
<ParagraphBorderType type="object">StrokeStyle/$ID/Solid</ParagraphBorderType>
</Properties>
</TextDefault>
<XMLPreference DeleteElementOnContentDeletion="false" />
<EPubExportPreference IncludeClassesInHTML="true" UseSVGAs="EmbedCode" />
<HTMLExportPreference IncludeClassesInHTML="true" UseSVGAs="EmbedCode" />
</Values>
</PreferenceValues>
+48 -2
View File
@@ -1,6 +1,7 @@
//! Values written from IDML observation: what every InDesign-exported IDML
//! in the corpus has on the root styles (`root_values.xml`, generated by
//! `tools/root_values.py`). See `docs/format/idml-values.md`.
//! in the corpus has on the root styles (`root_values.xml`) and in its
//! preferences (`preference_values.xml`), both generated by
//! `tools/root_values.py`. See `docs/format/idml-values.md`.
use super::xml::Xml;
@@ -39,6 +40,8 @@ impl Node {
for c in &other.children {
match self.children.iter_mut().find(|m| m.tag == c.tag) {
Some(m) => m.merge(c),
// The schema puts `Properties` before other children.
None if c.tag == "Properties" => self.children.insert(0, c.clone()),
None => self.children.push(c.clone()),
}
}
@@ -83,6 +86,30 @@ pub fn root_style(tag: &str, major: u32) -> Node {
out
}
const PREFERENCE_VALUES: &str = include_str!("preference_values.xml");
/// The observed preference elements (`TextDefault`, ...) for a document of
/// InDesign version `major`, in the order the IDML files list them.
pub fn preferences(major: u32) -> Vec<Node> {
let root = parse(PREFERENCE_VALUES).expect("preference_values.xml is well-formed");
let mut out: Vec<Node> = Vec::new();
for block in &root.children {
let since = block
.attr("MinimumVersion")
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
if since > major {
continue;
}
for n in &block.children {
match out.iter_mut().find(|m| m.tag == n.tag) {
Some(m) => m.merge(n),
None => out.push(n.clone()),
}
}
}
out
}
fn unescape(s: &str) -> String {
s.replace("&lt;", "<")
.replace("&gt;", ">")
@@ -190,4 +217,23 @@ mod tests {
.is_some()
);
}
#[test]
fn gates_preferences_by_version() {
let old = preferences(7);
let new = preferences(21);
assert!(
old.iter()
.all(|n| n.tag != "EPubFixedLayoutExportPreference")
);
assert!(
new.iter()
.any(|n| n.tag == "EPubFixedLayoutExportPreference")
);
let text = new.iter().find(|n| n.tag == "TextDefault").unwrap();
assert!(text.attr("PointSize").is_none());
// Values the converter reads from the INDD are not in the file.
let doc = new.iter().find(|n| n.tag == "DocumentPreference").unwrap();
assert!(doc.attr("PageWidth").is_none());
}
}
+137 -7
View File
@@ -1,17 +1,23 @@
#!/usr/bin/env python3
"""Find the values that every corpus IDML has on its root styles.
"""Find the values that every corpus IDML has on its root styles and in
its preferences.
Reads Resources/Styles.xml of every IDML in the corpus pairs (distinct
files only) and collects each attribute, Properties child and child
element attribute of the root styles. A value is kept when it is the same
in every IDML from some DOM version on and present in all of them; the
Reads Resources/Styles.xml and Resources/Preferences.xml of every IDML in
the corpus pairs (distinct files only) and collects each attribute,
Properties child and child element attribute of the root styles and of
the top-level preference elements. A value is kept when it is the same in
every IDML from some DOM version on and present in all of them; the
earliest such version is its minimum version. Attributes the converter
reads from the INDD (the TEXT_ATTRS table in src/idml/mod.rs) are left
out for the paragraph and character root styles.
out for the paragraph and character root styles, and the document setup
it reads is left out of the preferences. Preference values that refer to
a style other than a root style are left out, since the package need not
have that style.
Usage: python3 -I tools/root_values.py [--write]
Prints the evidence counts. With --write, regenerates
src/idml/root_values.xml. See docs/format/idml-values.md.
src/idml/root_values.xml and src/idml/preference_values.xml. See
docs/format/idml-values.md.
"""
import hashlib
@@ -25,6 +31,38 @@ from xml.sax.saxutils import quoteattr
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "src" / "idml" / "root_values.xml"
PREF_OUT = ROOT / "src" / "idml" / "preference_values.xml"
# Preference attributes the converter reads from the INDD.
PREF_SKIP = {
("DocumentPreference", "PageHeight"), ("DocumentPreference", "PageWidth"),
("DocumentPreference", "FacingPages"), ("DocumentPreference", "Intent"),
("DocumentPreference", "DocumentBleedTopOffset"),
("DocumentPreference", "DocumentBleedBottomOffset"),
("DocumentPreference", "DocumentBleedInsideOrLeftOffset"),
("DocumentPreference", "DocumentBleedOutsideOrRightOffset"),
("ViewPreference", "RulerOrigin"),
}
# Styles a preference value may refer to: those every package has.
ROOT_STYLES = {
"ParagraphStyle/$ID/[No paragraph style]",
"CharacterStyle/$ID/[No character style]",
"ObjectStyle/$ID/[None]",
}
# A preference value first seen in a later version is kept only when at
# least this many files show it.
MIN_FILES = 10
STYLE_REF = re.compile(r"(?:>|^)(Paragraph|Character|Object|Cell|Table)Style/[^<]*")
PREF_HEADER = """<?xml version="1.0" encoding="UTF-8"?>
<!--
Values that every IDML exported by InDesign in the corpus has in
Resources/Preferences.xml. The converter writes them; values it reads
from the INDD take precedence. Values in a block with MinimumVersion are
written only for documents of that InDesign version or later. Generated
by tools/root_values.py; evidence in docs/format/idml-values.md.
-->
"""
TARGETS = OrderedDict([
("ParagraphStyle", "ParagraphStyle/$ID/[No paragraph style]"),
@@ -123,6 +161,83 @@ def analyse():
return pairs, idmls, doms, kept, left_out, order
def since_of(by_file, doms):
"""The first DOM version from which every file has the same value, and
the number of those files; None if there is none."""
for m in sorted({doms[i] for i in by_file}):
files = [i for i, d in enumerate(doms) if d >= m]
if all(i in by_file for i in files):
if len({by_file[i] for i in files}) == 1:
return (m, len(files))
return None
return None
def style_ref(v):
m = STYLE_REF.search(v)
return m and m.group(0).lstrip(">") not in ROOT_STYLES
def analyse_preferences(idmls, doms):
values = defaultdict(dict)
order = defaultdict(dict)
tags = OrderedDict()
for i, (_dom, idml) in enumerate(idmls):
root = ET.fromstring(zipfile.ZipFile(idml).read("Resources/Preferences.xml"))
for el in root:
tags.setdefault(el.tag, len(tags))
out = {}
leaves(el, (), out, order[el.tag])
for k, v in out.items():
values[(el.tag, k)][i] = v
kept = defaultdict(list)
left_out = defaultdict(lambda: defaultdict(list))
for (tag, key), by_file in values.items():
path, name = key
plain = name.split("/", 1)[1] if name.startswith("P/") else name[1:]
if not path and (tag, plain) in PREF_SKIP:
left_out[tag]["read from the INDD"].append(plain)
continue
since = since_of(by_file, doms)
if since is None:
left_out[tag]["varies"].append("/".join(path + (plain,)))
continue
if since[1] < MIN_FILES:
left_out[tag][f"in fewer than {MIN_FILES} files"].append("/".join(path + (plain,)))
continue
value = next(iter(by_file.values()))
if style_ref(value):
left_out[tag]["refers to a style"].append("/".join(path + (plain,)))
continue
kept[tag].append((key, value, since))
return tags, kept, left_out, order
def write_preferences(tags, kept, order, first):
blocks = []
for since in sorted({s for items in kept.values() for _, _, (s, _) in items}):
gate = "" if since == first else f' MinimumVersion="{since}"'
s = f"\t<Values{gate}>\n"
for tag in tags:
items = sorted((it for it in kept[tag] if it[2][0] == since),
key=lambda it: order[tag][it[0]])
if not items:
continue
tree = {"attrs": [], "props": [], "children": OrderedDict()}
for (path, name), v, _ in items:
node = tree
for p in path:
node = node["children"].setdefault(
p, {"attrs": [], "props": [], "children": OrderedDict()})
if name.startswith("@"):
node["attrs"].append((name[1:], v))
else:
node["props"].append(v)
s += element(tag, tree, "\t\t")
blocks.append(s + "\t</Values>\n")
PREF_OUT.write_text(PREF_HEADER + "<PreferenceValues>\n" + "".join(blocks) + "</PreferenceValues>\n")
def element(tag, node, indent):
attrs = "".join(f" {k}={quoteattr(v)}" for k, v in node["attrs"])
if not node["props"] and not node["children"]:
@@ -174,9 +289,24 @@ def main():
print(f" {k:4} values, the same in {n} of {n} IDML files with DOM >= {since}")
for why, names in left_out[tag].items():
print(f" {len(names):4} left out ({why}): {', '.join(sorted(names))}")
tags, pkept, pleft, porder = analyse_preferences(idmls, doms)
print("\nPreferences:")
total = defaultdict(int)
for tag in tags:
for _, _, since in pkept[tag]:
total[since] += 1
for (since, n), k in sorted(total.items()):
print(f" {k:4} values, the same in {n} of {n} IDML files with DOM >= {since}")
for tag in tags:
counts = {why: len(names) for why, names in pleft[tag].items()}
print(f" {tag}: {len(pkept[tag])} kept, left out {counts}")
if pleft[tag].get("refers to a style") or pleft[tag].get("read from the INDD"):
print(f" {pleft[tag].get('refers to a style', [])} {pleft[tag].get('read from the INDD', [])}")
if "--write" in sys.argv:
write(kept, order, min(doms))
print(f"\nwrote {OUT.relative_to(ROOT)}")
write_preferences(tags, pkept, porder, min(doms))
print(f"wrote {PREF_OUT.relative_to(ROOT)}")
if __name__ == "__main__":