feat: decode page item, preference and resource values

Page items:
- drop shadow KnockedOut (0x1EB6F), true where neither item nor style
  stores it
- text wrap: the u32 at 40 of 0x3703 is the master page flag and the
  wrap side (two u16, as the big-endian pair shows)
- groups get the fill, stroke and corner values all their children have
- dashes (0x5A35: list and corner code) on items whose stroke type in
  effect is Dashed
- BeforeGroupingLayerPosition (0x324) from 21.4; export SizeType
  (0x1E22B); no generated alt text attributes on groups
- anchored settings on items inside anchored items
- IgnoreWrap false without the chunk, MinimumFirstBaselineOffset 0 by
  the baseline category, InsetSpacing before DOM 11 by the general
  category; EPS contents from 0x8C23
- custom striped and dashed stroke styles (classes 0xB016, 0x5A43) and
  StrokeType code 0x5A42

Preferences: column direction (0x555, else the story orientation),
optical margin size by the text size unit, highlight flags false without
their chunk, grid and gutter defaults and print marks by the edition
code, watermark font by the assignment name, EPUB ViewDocumentAfterExport
for DOM 8 and 9, HTMLFXLExportPreference from DOM 10.1, MathML document
values from DOM 20, index header type by variant name, three more
built-in kinsoku and mojikumi tables.

Resources and text: the saving edition from the XMP black name (tints
of black, unknown users, endnote and index titles, endnote marker), TOC
style entries, PageNumberType (0x1B09), CustomGlyph (0x1B5E), alignment
codes of 0x4266, 0x1B3E and 0xB676, spot colour alias and DOM 8 section
pagination (observed values), text variable settings and result texts,
object styles' AppliedParagraphStyle without a chunk and flex spacing,
stories of frames anchored in the XML backing story.

Fixes: flattener resolutions of 0x10833 were swapped; colour group Self
follows the DOM version.

compare.py, trustworthy pairs: value coverage 98.96 % -> 99.48 %
(+150,288 values), documents >= 99 % 914 -> 1,021, story text 37,129 ->
37,147 of 37,150 (0 missing), extras 92,838 -> 92,883 (+788 from the
KnockedOut and group-corner exceptions, -744 from fixed extras). No pair
loses values against f21267f. diff_outputs.py: 5,743 of 5,765 outputs
differ, no failure or warning differs.
This commit is contained in:
aiongg committed 2026-10-10 18:34:10 +00:00
1 parent 6c76bb7451
commit a299387eb0
35 files changed
+2152 -251

No files matched your search

+1 -1
View File
@@ -90,7 +90,7 @@ group cycles, table sizes larger than their cell data.
| `color.rs`, `font.rs`, `cjk.rs` | swatches and inks; font families; composite fonts and kinsoku and mojikumi tables |
| `hyperlink.rs`, `xref.rs`, `variable.rs`, `xml.rs` | hyperlinks and bookmarks; cross-reference formats; text variables; the XML structure |
| `settings.rs`, `prefs.rs` | document-level lists and preferences |
| `xmp.rs` | dates of the XMP packet (time zone offsets for link times) |
| `xmp.rs` | dates of the XMP packet (time zone offsets for link times) and its black swatch name (the saving edition) |
| `strings.rs` | searches for names at positions that are not decoded |
### `src/idml/`
+134 -16
View File
@@ -123,11 +123,48 @@ style, below) and on items with stored values not decoded then (77
alignment `OutsideAlignment` and stroke types; strokes, below). Over all pairs, 4 extra `StrokeWeight` values appear,
in 3 stale pairs.
Groups are left out: their fill and stroke attributes in IDML were not
studied (1,844 groups of the trustworthy pairs have a `StrokeWeight`
that the converter does not write). IDML writes no corner attributes
for EPS text (class 0x660B; none in 634 elements), so only its other
attributes follow the rule.
IDML writes no corner attributes for EPS text (class 0x660B; none in
634 elements), so only its other attributes follow the rule.
**Groups.** A group (class 0x401) stores none of these attributes. IDML
gives a group, for each fill, stroke and corner attribute, the value
that all its child page items have in effect: the child's own value
(stored, or from the base list where IDML writes it), else its object
style's effective value; for a child group, its own shared value. EPS
text has no corner values and is left out for the corners. IDML writes
the shared value when it differs from the group's object style value,
when the style turns the category off, when the group has no object
style, and for a stroke tint that every child stores as 100 (written
−1, above); it leaves the attribute out when the children differ.
With this rule the converter reproduces, over the groups of the 1,251
trustworthy pairs of the corpus after 2026-10 (none was written
before):
| Attribute | Values |
|---|---:|
| `StrokeWeight` | 4,741 of 4,741 |
| `FillColor` | 3,813 of 3,813 |
| `MiterLimit` | 3,679 of 3,679 |
| `StrokeColor` | 1,221 of 1,221 |
| `CornerRadius`, `TopLeftCornerRadius` | 1,001 of 1,001 each |
| `StrokeTint` | 664 of 664 |
| `FillTint` | 379 of 417 |
| `BottomLeftCornerRadius`, `BottomRightCornerRadius` | 326 of 326 each |
| `TopRightCornerRadius` | 296 of 296 |
| `GapColor` | 124 of 124 |
| corner options (five attributes) | 92 to 103 of as many |
| `LeftLineEnd`, `RightLineEnd`, `StrokeAlignment`, `EndJoin`, `EndCap` | 40, 9, 15, 7 and 2 of as many |
| `StrokeType` | 15 of 17 |
The 38 `FillTint` values follow children whose own `FillTint` the
converter writes as 100 where IDML has −1 (a difference of the children,
not of the group rule). The rule adds 27 extra values: 3 documents of
versions 10 to 12 whose groups have `CornerRadius` and
`TopLeftCornerRadius` but not the other three radii, although every
child has all four, and one `StrokeType`. `OverprintFill` (313 values)
does not follow the rule in 75 groups that have a child without the
attribute, and is not written on groups.
**Category turned off.** When the item's object style (other than the
root `[None]`) turns a category off, IDML writes the item's values of
@@ -201,9 +238,44 @@ corpus after 2026-10 with reference 0, IDML value against stored code.
No code has two IDML values. The codes are the same in every list that
names a stroke style (items, object styles, cells, tables, paragraph
rules, underlines and strike-throughs), so the converter uses one table.
Custom stroke styles (a non-zero reference, 17 items in 2 files, for
example `DashedStrokeStyle/Rounded`) are left out. Codes 0x5A3D and
0xB008 occur only in files without a trustworthy IDML.
Codes 0x5A3D and 0xB008 occur only in files without a trustworthy IDML.
**Custom stroke styles.** A record with code 0x5A42 and a non-zero
reference names a custom stroke style: the reference is the UID of an
object of class 0xB016 (striped) or 0x5A43 (dashed). IDML defines each
in `Resources/Graphic.xml` after the built-in `StrokeStyle` elements and
names it in `StrokeType` as `StripedStrokeStyle/<name>` or
`DashedStrokeStyle/<name>`.
| Class | Chunk | Layout | IDML |
|---|---|---|---|
| 0xB016 | 0xB023 | flag byte, in-object string | `Name` |
| 0xB016 | 0xB002 | u32 *n*, then *n* pairs of f64 (start, width), fractions of the stroke weight | `StripeArray`: each value × 100, in stored order |
| 0x5A43 | 0x5A48 | flag byte, in-object string | `Name` |
| 0x5A43 | 0x5A4F | u32 *n*, *n* f64 dash and gap lengths in points, u16 corner adjustment, u32 end cap | `DashArray` (the values as stored), `StrokeCornerAdjustment` (3 `DashesAndGaps`), `EndCap` (as 0x6E6B) |
IDML writes `Self`, `StripeArray`, `Name` for a striped style and
`Self`, `DashArray`, `StrokeCornerAdjustment`, `EndCap`, `Name` for a
dashed one; `Self` is `StripedStrokeStyle/<name>` or
`DashedStrokeStyle/<name>`. Every object of the two classes is written,
also where nothing uses it, in UID order.
Evidence over the trustworthy pairs of the corpus after 2026-10: the
converter reproduces 21 of 21 `StripedStrokeStyle` elements (one
definition, (0, 0.05), IDML `StripeArray="0 5"`) and 5 of 5
`DashedStrokeStyle` elements (one definition: 24, 0, corner 3, cap 1,
IDML `DashArray="24 0"`, `StrokeCornerAdjustment="DashesAndGaps"`,
`EndCap="RoundEndCap"`), with every attribute, and with them 21 more
object style `StrokeType` values, 5 graphic line values and one of
`PageItemDefault`. Four of the five files with the dashed style use it
nowhere. A chunk whose length is not that of its layout leaves the
style out with a warning. Over the 6,039 distinct INDD and INDT files of
the corpus outside the privately held samples, 78 files have such
styles: all 98 striped and 119 dashed objects have the chunk lengths of
the layout (4 + 16*n* and 4 + 8*n* + 6, either byte order). Striped
styles have 1, 2, 3, 5, 6 or 7 stripes; every dashed style has an even
number of lengths, corner code 3 (117) or 0 (2) and end cap 0 (108) or
1 (11). Only the one-stripe form and corner code 3 occur in a pair.
**Stroke alignment (0x6E8C).** 0 `CenterAlignment`, 1 `InsideAlignment`
(3,238 items in 44 files), 2 `OutsideAlignment` (196 items in 50 files).
@@ -243,9 +315,8 @@ stroke alignment by the rule of the fill and stroke colour: the value
the item stores (or that of the base list) where it differs from the
applied object style's effective value, every value where the style
turns the category off, and every value without a style (above). Groups
never store these IDs, and IDML writes values on groups whose source is
not shown (664 groups with `StrokeTint`, 40 with `LeftLineEnd`), so the
converter writes none on groups.
never store these IDs; their values come from their children (values an
item does not store, groups).
A tint is compared as stored: an item that stores 100 differs from a
style value of −1, and IDML writes it as −1. 4,508 items in 192 files
@@ -283,8 +354,21 @@ their order on `PageItemDefault`, where the values are equal in every
file (`preferences.md`, page item defaults). 0x6E78 is 0 in every style,
0x6E73 in all but 2; 0x6E78 is `Nonprinting` of `PageItemDefault`. 0x6E67, 0x6E6A and 0x6E8B are the
overprint flags (`objects.md`, object style settings).
`StrokeCornerAdjustment` and `StrokeDashAndGap` do not occur in the
corpus IDML files.
**Dashes (0x5A35).** Page item attribute 0x5A35 (value type 0x5A36):
8 bytes (0 in every sample), u32 count *n*, *n* f64, u16 corner
adjustment. IDML writes the f64 list as `StrokeDashAndGap` (numbers
separated by spaces) and the code as `StrokeCornerAdjustment`: 3
`DashesAndGaps`, the only code in the samples, which the dashed stroke
style's chunk 0x5A4F also stores for `DashesAndGaps`. IDML has the two
attributes only on items whose stroke type in effect is `Dashed`
(`StrokeStyle/$ID/Dashed`; every such item has them), and on groups by
the group rule: no item with another stroke type has them, though 1,251
documents store the attribute in the page item defaults and many items
of other stroke types store it. Object styles never have them. With
these rules the converter reproduces 2,312 of 2,316 graphic line values
of each attribute, 8 of 9 for polygons and 10 of 24 and 29 for groups,
with no extra value. The values of 9 rectangles and 7 EPS text items
are not written (not examined).
## Text attribute lists
@@ -399,7 +483,7 @@ styles with INDD styles of the same name (486 styles), then checked with
| 0x1DF04 | `ParagraphBorderBottomOffset` | f64 | 83/83 styles |
| 0x1DF21 | `SameParaStyleSpacing` (Properties) | f64; −1 = SetIgnore | 15/15 ranges, 100/100 styles |
| 0x4265 | `GridAlignFirstLineOnly` | 1 = true | 81/81 styles |
| 0x4266 | `GridAlignment` | 0 None, 1 AlignBaseline | 86/86 styles |
| 0x4266 | `GridAlignment` | 0 None, 1 AlignBaseline, 2 AlignEmTop, 3 AlignEmCenter (below) | 86/86 styles |
| 0x425E | `Tatechuyoko` | 1 = true | root styles; 1 from a sample typeset vertically and its print PDF, see below |
| 0x4279 | `ShataiDegreeAngle` | degrees, written ×100 | root styles; see below |
| 0x427A | `ShataiAdjustTsume` | 1 = true | root styles; see below |
@@ -432,7 +516,15 @@ enumeration: `kHardKinsokuName` `HardKinsoku` (51 styles),
`SimplifiedChineseKinsoku` (1), `kMojikumiDefaultName1`
`LineEndAllOneHalfEmEnum` (55) and `kMojikumiDefaultName16`
`SimpChineseDefault` (1); a custom kinsoku table (class 0x4204) as the
object `KinsokuTable/<name>` (38). Other built-in tables are not written.
object `KinsokuTable/<name>` (38). The corpus of 2026-10 adds three
built-in tables, each from the `TextDefault` of every trustworthy pair
that uses it: `kTradChineseKinsokuName` `TraditionalChineseKinsoku` (90
documents), `kMojikumiDefaultName15` `TradChineseDefault` (80) and
`kMojikumiDefaultName2` `OneEmIndentLineEndUkeOneHalfEmEnum` (1). With
them the converter reproduces 1,251 of 1,251 `TextDefault` `KinsokuSet`
and `Mojikumi` values, 1,430 of 1,430 `KinsokuSet` and 1,532 of 1,532
`Mojikumi` values of paragraph styles. Other built-in tables are not
written.
A custom mojikumi table (class 0x4203, `objects.md`) is the object
`MojikumiTable/<name>`. In the trustworthy pairs of the corpus of
2026-10 this gives the IDML value for 576 paragraph ranges, 105
@@ -798,7 +890,7 @@ not listed leaves the attribute out.
| 0x1B21 | `HyphenateBeforeLast` | num | 580 (85) |
| 0x1B30 | `DesiredLetterSpacing` | pct | 559 (64) |
| 0x1B38 | `KeepAllLinesTogether` | bool | 556 (61) |
| 0x1B3E | `CharacterAlignment` | 0 `AlignBaseline`, 1 `AlignEmCenter`, 2 `AlignEmBottom` | 551 (56) |
| 0x1B3E | `CharacterAlignment` | 0 `AlignBaseline`, 1 `AlignEmCenter`, 2 `AlignEmBottom`, 3 `AlignEmTop`, 4 `AlignICFTop`, 5 `AlignICFBottom` (below) | 551 (56) |
| 0x1B4C | `RuleAboveColor` (Properties) | swatch | 546 (51) |
| 0x1B5C | `RuleAbove` | bool | 541 (46) |
| 0x1B83 | `HyphenWeight` | num | 541 (46) |
@@ -917,6 +1009,32 @@ defaults and text ranges; 120,409 reproduced, 3 wrong (`TextDefault`
`DesiredLetterSpacing`, `DesiredWordSpacing` and `UnderlineType` in one
document each), the rest in stories whose text differs.
**More codes, corpus of 2026-10.** Over the 1,251 trustworthy pairs,
the converter's output with these codes reproduces the IDML values below
and adds no extra value:
| ID | Code | IDML | Evidence (converter's output, trustworthy pairs) |
|---|---|---|---|
| 0x4266 | 2 | `GridAlignment="AlignEmTop"` | with code 3: 11,024 of 11,024 range values (2,333 more than before), 1,826 of 1,826 paragraph style values |
| 0x4266 | 3 | `GridAlignment="AlignEmCenter"` | |
| 0x1B3E | 3 | `CharacterAlignment="AlignEmTop"` | with codes 4 and 5: 9,603 of 9,605 range values (1,699 more) |
| 0x1B3E | 4, 5 | `AlignICFTop`, `AlignICFBottom` | one run each, one document |
| 0xB676 (cells) | 3 | `FirstBaselineOffset="EmboxHeight"` | 6,668 of 6,668 cell values (2,143 more) |
**Page number type (0x1B09).** A u16 enumeration: 0 `AutoPageNumber`, 2
`NextPageNumber`, 3 `TextVariable`, written as the range's
`PageNumberType`. The root paragraph style has 0, the `AutoPageNumber`
of IDML's root style. In the trustworthy pairs the ranges with
`TextVariable` are those that hold a text variable instance; the
converter reproduces 278 of 278 values with no extra value.
**Custom glyph (0x1B5E).** Value type 0x1B26: u16 length *n*, *n* bytes
of a glyph name, u32 glyph ID. IDML writes `Properties/CustomGlyph`
(type `string`) as `$ID/` and the name, for example `$ID/ampersand.smcp`.
The converter leaves out records with an empty name. It reproduces 1,499
of 1,499 values in the trustworthy pairs, with no extra value. The glyph
ID is not used.
### Ruby, kenten and warichu
These attributes are in story runs (character and paragraph runs, chunk
+9 -4
View File
@@ -261,10 +261,15 @@ text styles are the defaults, which the converter writes. The title is
the exporting InDesign's localized default (`Endnotes` 108, `Notes de
fin` 18, `Eindnoten` 12, 4 others in the 654 pairs before 2026-10), and
the separator and marker position follow its language. The converter
writes U+3000 and `RubyMarker` when the last session of the save history
has language code 0x0101, and tab and `SuperscriptMarker` otherwise
(140 of 141 pairs; `objects.md`, save history). The title is left
out.
writes the separator U+3000 when the last session of the save history
has language code 0x0101, and tab otherwise (140 of 141 pairs before
2026-10; `objects.md`, save history). The title and the marker position
follow the saving edition that the XMP black name shows (`objects.md`,
saving edition): `RubyMarker` for a Japanese edition only, so Korean
editions, which also have code 0x0101, get `SuperscriptMarker`. Over the
trustworthy pairs of the corpus after 2026-10 this gives 917 of 918
titles and 916 of 918 marker positions (692 and 876 before); without a
black name the marker follows the code.
## IsEndnoteStory
+43 -10
View File
@@ -113,6 +113,16 @@ next to it are read from the INDD (`preferences.md`).
`Name` (the package's file name) is on the `Document` element from DOM
13 only: 321 of 321 trustworthy references from DOM 13, 0 of 168 before.
From DOM 20.0 every `Document` element has `AppliedMathMLRgbColor="0 0
0"` and `TintValue="100"`, and a `Properties` child
`AppliedMathMLSwatch` (type `enumeration`) `Nothing`, after `Label`;
from DOM 20.4 also `PreferMathMLInEpubExport="false"` (all 99 and 72
distinct corpus IDML files of those versions; none before). The
converter writes them by the DOM version it writes, which the per-major
blocks cannot express for 20.4. `AppliedMathMLFontSize` is `10` in 96
of these files and `16` in 3 of DOM 20.2, with no field found, so it is
left out.
## Default numbering list
The root paragraph style refers to `NumberingList/$ID/[Default]`. Every
@@ -361,9 +371,17 @@ all of them have; the converter writes it in the order of the IDML files.
| `WatermarkPreference` | 7 | 11 | the font family, style and colour |
| `TaggedPDFPreference` | 8 | (element only) | `StructureOrder` |
| `AdjustLayoutPreference` | 14 | 4 | `EnableAdjustLayout`, `EnableAutoAdjustMargins`, `AllowFontSizeAndLeadingAdjustment` |
| `HTMLFXLExportPreference` | 11 | both | |
| `HTMLFXLExportPreference` | 10.1 | both | |
| `PublishExportPreference` | 11 | 7 | `ImageExportResolution`, `PublishPdf`, `CoverPage`, `PublishDescription`, `PublishFileName`, `PublishPageRange` |
`HTMLFXLExportPreference` (`EpubPageRange=""`,
`EpubPageRangeFormat="ExportAllPages"`) is in every IDML from DOM 10.1
(all 1,556 distinct corpus files of DOM 10.1 and later) and in none of
DOM 10.0 (10 files) or earlier. The converter writes it by the DOM
version it writes (10.1 for files of version 10 last saved by 10.1 or
later). Over the trustworthy pairs it reproduces the element in 1,139
of 1,139 documents.
The values left out here are read from the INDD or follow the rules of
`preferences.md` (adjust layout; EPUB, HTML and Publish Online export;
values of the exporting edition). The converter writes
@@ -423,6 +441,18 @@ in 2), Korean (457 and 7) and Hebrew (74 and 1, `‘’` and `“”`). No
stored value tells the exceptions apart; they follow the dictionary
preferences of the exporting computer.
These exceptions follow no stored value, so the converter writes no
quotes for Japanese, Korean and Hebrew languages without the chunk
(writing the common value would be a majority rule).
Colours are keyed by `Model`: every spot colour has
`SpotInkAliasSpotColorReference="n"` (5,182 of 5,182 in the 1,689
distinct corpus IDML files outside the privately held samples, DOM 8 to
21), and no process (46,211) or registration (1,685) colour has the
attribute. No ink of the corpus has an alias. The converter writes it
after `ColorOverride` on spot colours: 5,090 of 5,090 values of the
trustworthy pairs.
Pasted smooth shades are keyed the same way by `ContentsType`: every
`ConstantShade` (and every `AxialShade`) has `ContentsVersion="0"`,
`SpotColorList=""`, `ContentsEncoding="Ascii64Encoding"`,
@@ -457,6 +487,15 @@ with 44 files) and `ExtendedKeyboardShortcut="0 0 0"` from DOM 15; the
converter writes them. `Imported` and `StyleUniqueId` come from the INDD
(`objects.md`, styles).
### Sections
Every `Section` of DOM 8 (96 sections in the corpus IDML files) has
`Pagination="AutoPaginate"` and `PaginationMaster="n"`, after
`AlternateLayout`; no section of another DOM version has them. The tool
keeps them for DOM 8 (`Values` block of version 8 to 8), and the
converter writes them there: 85 of 85 values each in the trustworthy
pairs.
### Swatches
| Element | Values kept |
@@ -552,11 +591,8 @@ values on those items.
## Column direction of pages
The `ColumnDirection` of pages is read from the INDD (`objects.md`,
page settings). The `MarginPreference` and `DocumentPreference` of the
preferences keep the observed `Horizontal` of `preference_values.xml`;
8 of the 489 trustworthy pairs have `Vertical` there, and no field was
found for it (chunk 0x555 does not separate them, and 4 of the 8 lack
it).
page settings), and that of `MarginPreference` and `DocumentPreference`
too (`preferences.md`, margins and columns of new pages).
## Font platform name
@@ -659,8 +695,5 @@ 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. A
sample typeset vertically shows this: two 2-byte fields of the
preferences object (chunks 0xCD14 and 0xCD1C) are 1 there and 0 in all
250 distinct little-endian public files, and the values most likely to
depend on vertical layout (`StoryPreference` `StoryOrientation`,
`DocumentPreference` and `MarginPreference` `ColumnDirection`) are
written as observed. The print PDF cannot show which preference each
250 distinct little-endian public files. The print PDF cannot show which preference each
field holds, so they are not mapped.
+262 -43
View File
@@ -98,9 +98,14 @@ has its stored name as `UserName` (1,724 of 1,724). Flag 2 marks the
placeholder for an unknown user, stored with a name such as
`Unknown User Name` or the same words in the language of the computer
that saved it; IDML writes `$ID/Unknown User Name` for 495 of the 586
such users, and the stored name for the other 91. The schema requires
`UserName`, so the converter writes `$ID/Unknown User Name` for every
flag 2 user. The colour UID names an interface colour, but the IDML
such users, and the stored name for the other 91. The rule is the
saving edition's name for an unknown user (saving edition, below):
IDML writes `$ID/Unknown User Name` for every user, of either flag,
whose stored name is that edition's, and the stored name for every
other user, also a flag 2 user named in another language (for example
`Unknown User Name` in a document last saved by a Korean edition).
Without a black name the converter writes `$ID/Unknown User Name` for
every flag 2 user (the schema requires `UserName`). The colour UID names an interface colour, but the IDML
`UserColor` does not follow from it (users stored with 0.6, 0.4, 0 are
`BrickRed` in 4 files and `Gold` in 1), so it is left out of the
conversion and of the measurement (`measurement.md`).
@@ -189,12 +194,76 @@ So that IDML was exported in a session the INDD does not record, by an
application of another language.
The converter uses the code where it decides the value: the flattener
resolutions, the index separator, the index title `索引` for 0x0101,
and the endnote separator and marker position. It writes no index
title for other codes (the code does not tell the Latin-script
languages apart), no endnote title without the chunk, and no
assignment `Name`: names that are not `$ID/UnassignedInCopy` occur
with every code.
resolutions, the index separator and the endnote separator. The index
title, the endnote title and marker position and the unknown user
follow the saving edition (below). It writes no assignment `Name`:
names that are not `$ID/UnassignedInCopy` occur with every code.
**Saving edition (the XMP black name).** The XMP packet of the INDD
lists the document's colours in `xmpTPg:Colorants`, each with
`xmpG:swatchName`, `xmpG:mode`, `xmpG:type` and its values (`cyan` to
`black` in percent, `red`, `green`, `blue` 0 to 255). Tints have an
`xmpG:tint` and keep the stored name of their base colour. The black
swatch is listed with the name the InDesign that saved the document
gives it: `Black`, `검정`, `黒`, `黑色`, `Schwarz`, `Noir`, `Nero`,
`Zwart`, `Černá`, `Preto`, `Черный`. The converter takes as the black
name the `swatchName` of the one colorant that is not a tint, is a
process colour, has the mode and values of the document's black colour
(`Color/Black`, as IDML writes its values) and whose name no other
colour of the document has. Over the 1,251 trustworthy pairs of the
corpus after 2026-10 there is exactly one such colorant in each: 502
`검정`, 431 `Black`, 126 `黒`, 93 `黑色`, 45 `Schwarz`, 44 `Noir`, 4
`Nero`, 3 `Zwart` and one each of `Černá`, `Preto` and `Черный`.
This is a rule over stored data: the packet records the edition of the
last save, and IDML follows the edition that exported it. Where a
document was exported by another installation than the one that saved
it last, the IDML has the other edition's values; the exceptions below
are such documents.
IDML writes these values in the language of that edition:
| Black name | Tint of black | Unknown user | Endnote title (no chunk 0x2261E) | Index title (no chunk 0x13010) |
|---|---|---|---|---|
| `Black` | `[Black] 40%` | `Unknown User Name` | `Endnotes` | `Index` |
| `검정` | `[검정] 40%` | `알 수 없는 사용자 이름` | `미주` | `색인` |
| `黒` | | `不明なユーザー名` | `文末脚注` (DOM 13), `後注` (DOM 19, 20) | `索引` |
| `黑色` | `[黑色] 40%` | `不明的使用者名稱`, `未知用户名` | | `索引` |
| `Schwarz` | `[Schwarz] 40%` | `Unbekannter Benutzername` | `Endnoten` | `Index` |
| `Noir` | `[Noir] 40%` | `Nom d'utilisateur inconnu` | `Notes de fin` | `Index` |
| `Nero` | | `Nome ut. sconosciuto` | `Note di chiusura` | `Indice` |
| `Zwart` | | `Onbekende gebruikersnaam` | `Eindnoten` | `Index` |
| `Černá` | | `Neznámé jméno uživatele` | | `Rejstřík` |
| `Preto` | | `Nome de usuário desconhecido` | | `Índice` |
| `Черный` | | `Неизвестное имя пользователя` | | `Указатель` |
An empty cell has no sample. The endnote marker is `RubyMarker` for
`黒` and `SuperscriptMarker` for every other black name.
With these rules the converter reproduces, over the trustworthy pairs:
| Value | Reproduced | Before (assignment name and code rules) |
|---|---|---|
| `Tint` elements and their names (tints of black) | 204 of 204 tints, no extra tint | 171, and 409 extra values in 27 documents |
| `DocumentUser` `UserName` | 3,208 of 3,212 | 3,000 |
| `EndnoteOption` `EndnoteTitle` | 917 of 918 | 692 (no title without the chunk) |
| `EndnoteOption` `EndnoteMarkerPositioning` | 916 of 918 | 876 |
| `IndexOptions` `Title` | 1,250 of 1,251 | 1,162 |
The remaining differences are the 16.1 document above (exported by
another edition: three users, its endnote title and its index title),
one 20.0 document whose black name is `Black` but whose IDML writes the
German name of the unknown user as `$ID/Unknown User Name` (two users),
and DOM 7 documents whose IDML lists one user more than the INDD. In 8
stale pairs the rule loses 1 to 3 values each: their IDML was exported
by another edition than the one that saved the INDD later (for example
a Dutch endnote title in a document whose last save has `Black`).
Not explained by the black name: `BaselineFrameGridColor`,
`ColumnGuideColor`, the grid and gutter defaults and the print marks of
the Korean documents with code 0x0101 whose IDML has the values of a
Roman edition (`preferences.md`, values of the exporting edition), the
language quotes and the trimmed language lists.
## Spreads (0x501) and master spreads (0x1401)
@@ -258,9 +327,11 @@ child. Chunk 0x10833 (52 bytes) is in 20 spreads of 5 trustworthy
documents, always with the same bytes: f64 0.5 at offset 8, f64 400 at
offsets 20 and 28, 2 at 36 and 800 at 44. Their IDML has
`LineArtAndTextResolution` and `GradientAndMeshResolution` 400 and
`RasterVectorBalance` 50. The converter writes the f64 at 20 and 28 as
the two resolutions; which is which is not known, as they are equal in
every sample. Without the chunk, the IDML has 400 and 400 when the
`RasterVectorBalance` 50. In the corpus of 2026-10, 182 spreads of 20
trustworthy documents store 150 at 20 and 300 at 28, and their IDML has
`LineArtAndTextResolution="300"` and `GradientAndMeshResolution="150"`
(182 of 182): the f64 at 28 is `LineArtAndTextResolution` and the f64 at
20 `GradientAndMeshResolution`. Without the chunk, the IDML has 400 and 400 when the
last session of the save history (document, above) has code 0x0101,
and 300 and 150 otherwise: 7,481 of the 7,490 spreads of all 803 pairs
match, the other 9 being the spreads of the pair exported in a
@@ -507,27 +578,37 @@ Every chunk of the 654 pairs parses to its end with this layout. The
variants and sections have the same fields as the list that IDML writes
under `IndexHeaderSetting` (`preferences.md`), which the converter takes
from chunk 0x1300E. The converter uses the name, include byte and header
variant of each group.
variant of each group, and the internal name of the variant that the
header variant indexes in the group's variant list.
IDML writes an `IndexingSortOption` per group, in the stored order:
`Self` `dIndexingSortOptionn` and the name, `Name` `$ID/` and the name,
`Include`, `Priority` (the position, from 0) and `HeaderType`:
`Include`, `Priority` (the position, from 0) and `HeaderType`, which
follows the internal name of the chosen variant:
| Group | Variant | `HeaderType` |
|---|---|---|
| `kIndexGroup_Alphabet` | 0, 3, 5 | `BasicLatin`, `Spanish`, `Czech` |
| `kWRIndexGroup_CyrillicAlphabet` | 2 | `Russian` |
| `kIndexGroup_Kana` | 0 | `HiraganaAll` |
| `kIndexGroup_Chinese` | 0 | `ChinesePinyin` |
| `kIndexGroup_Korean` | 0 | `KoreanConsonant` |
| Symbol, numeric, Greek, Arabic and Hebrew groups | 0 | `Nothing` |
| Variant name | `HeaderType` |
|---|---|
| `IDX_Basic` | `BasicLatin` |
| `IDX_Spanish` | `Spanish` |
| `IDX_Czech` | `Czech` |
| `IDX_Russian` | `Russian` |
| `IDX_AllHira` | `HiraganaAll` |
| `IDX_ChinesePinyin` | `ChinesePinyin` |
| `IDX_ChineseStroke` | `ChineseStrokeCount` |
| `IDX_KoreanConsonant` | `KoreanConsonant` |
| the group's own name (symbol, numeric, Greek, Arabic and Hebrew groups) | `Nothing` |
The converter leaves `HeaderType` out for other combinations. Evidence:
the 495 trustworthy pairs have 11 different lists (8 or 10 groups, in
different orders, with different groups included); the converted groups
match the IDML in all 4,934 groups on every attribute. Over all 654
pairs the Alphabet variant is 0 in 652 files, 3 and 5 in one each, and
the Cyrillic variant is 2 in all.
The converter leaves `HeaderType` out for other names. Evidence: the
495 trustworthy pairs before 2026-10 have 11 different lists (8 or 10
groups, in different orders, with different groups included). Over the
1,251 trustworthy pairs of the corpus after 2026-10 the converter
reproduces all 12,472 `HeaderType` values. The variant index decides
where the list order differs: the Chinese group has variant 0 in every
file, but in 83 documents its list starts with `IDX_ChineseStroke`, and
their IDML has `ChineseStrokeCount` (83 of 83); a table by group and
variant number, used before, gave `ChinesePinyin` there. Over all 654
pairs before 2026-10 the Alphabet variant is 0 in 652 files, 3 and 5 in
one each, and the Cyrillic variant is 2 in all.
## Numbering lists (0x1A483)
@@ -635,9 +716,48 @@ whose IDML style has the same name (1,304 trustworthy; 15 with
`IncludeBookDocuments="true"`, one with `CreateBookmarks="false"`, in a
stale pair). The flagged string after the title is the path of a book
file in some of these styles, but it does not decide
`IncludeBookDocuments`. The entries (`TOCStyleEntry`, 130 in all corpus
IDML files) are not decoded: the converter writes the styles without
them.
`IncludeBookDocuments`.
**Entries.** After the u16 fields (two before version 9, three before
13, four from 13) the chunk holds a u16 entry count and the entries:
| Field | IDML |
|---|---|
| flag byte, in-object string | `Name`: the paragraph style's name, with `$ID/` first for flag 1; the group separator U+E00B is written `:` |
| flag byte, in-object string | a document path; not in IDML |
| u32 | `FormatStyle`: paragraph style UID |
| u32 | `Level` |
| u16 | `PageNumberPosition`: 0 `AfterEntry`, 1 `BeforeEntry`, 2 `None` |
| u32 | `PageNumberStyle`: character style UID |
| u32 *n*, segments | `Separator` |
| u32 | `SeparatorStyle`: character style UID |
| u16 | 0 in every entry |
| u32 *n*, segments | `; `, `;` or `、`; not in IDML |
| u16 | 1 in every entry |
IDML writes each entry as a `TOCStyleEntry` child of its `TOCStyle`:
`Self` is `u`, the TOC style's UID in hexadecimal, `TOCStyleEntry` and
the entry's index (0 to 5 in the samples, so whether the index is
hexadecimal is not shown), then
`Name`, `Level`, `PageNumberPosition`, `Separator`,
`SortAlphabet="false"` (every entry), and `Properties` with
`FormatStyle`, `PageNumberStyle` and `SeparatorStyle`: a user style as
`type="object"` and its `Self`; the root style as `type="string"`
`$ID/[No paragraph style]` or `$ID/[No character style]`; UID 0 as
`type="string"`, `$ID/kSameStyleWithBracket` for `FormatStyle` and
`$ID/[Same Style]` for the other two. `Separator` is `$ID/` and the text,
with tab written `^t`, U+0008 `^y`, line feed `^n`, U+2003 `^m` and
U+2014 `^_`.
Evidence: every TOC style with entries in the trustworthy pairs
(versions 8.0 to 21.3) parses to the end of the chunk with this layout,
and the converter reproduces all 255 `TOCStyleEntry` elements with all
their values: `Name`, `Level`, `PageNumberPosition`, `Separator`,
`SortAlphabet` and the three style properties, 255 of 255 each.
`SortAlphabet` is `false` in all; neither constant u16 can be shown to
hold it. A chunk whose entries do not parse to its end keeps its style
and loses its entries, with a warning.
Two TOC styles of the corpus pairs have another value at the
`SetStoryDirection` field: 0x40 with no `SetStoryDirection` in the IDML
(version 15.0) and 0xF6FC with `Horizontal` (a stale pair of version
@@ -932,6 +1052,7 @@ IDML value is the default in the table.
| 0x21D53 | same | `LastUpdatedInterfaceChangeCount` | empty |
| 0x1424 | u32 master page item, UID list | `OverriddenPageItemProps`: the list in decimal; empty if the master item is 0 | empty |
| 0x22228 | u8 flags | `HorizontalLayoutConstraints` (bits 4–6), `VerticalLayoutConstraints` (bits 0–2): per bit `FixedDimension` if set, else `FlexibleDimension` | as 0x22 |
| 0x324 | i32 at 4 | `BeforeGroupingLayerPosition`, after `ItemTransform`, from 21.4 (also on placed graphics) | `-1` |
| Attribute | IDML | Without the attribute |
|---|---|---|
@@ -987,6 +1108,15 @@ set the converter leaves both attributes out. In 14,918 items with
chunk 0x1424 the master item is 0; in 197 of them the list still holds
IDs, and IDML writes the attribute empty.
**Layer position before grouping.** From 21.4 every page item and
placed graphic in IDML has `BeforeGroupingLayerPosition`; no IDML before
21.4 has it (13 distinct corpus IDML files from 21.4, none of the 1,673
earlier ones). Its value is the i32 at 4 of chunk 0x324, or −1 without the
chunk. The converter writes it for files saved by 21.4 or later: 1,793 of 1,793
values over the trustworthy pairs (1,308 polygons, 241 text frames, 131
rectangles, 53 groups, 38 images, 16 EPS, 3 graphic lines and 3 SVG).
`BeforeGroupingLayerReference` (50 values) is not decoded.
**Stroke weight without an attribute.** An item whose attribute list has
no stroke weight (attribute 0x6E65) takes it from the document's base
list (class 0x6E02, `attributes.md`, values an item does not store):
@@ -1048,6 +1178,19 @@ files. The converter leaves out an attribute whose code is not in the
table. Which other attributes `ObjectExportOption` has depends on the
version (`idml-values.md`, export options of page items).
**Export size (chunk 0x1E22B).** A list of keys and values: u32 count;
per entry a u32 length and the key in text segments, a flag byte, two
bytes, a u16 value count and the values, each a u8 length, a u8 and that
many bytes of text. The keys are `UseOrigImage`, `CustomSizeType`,
`CustomSizeValue` and `CustomContentConversion`. `CustomSizeType` is IDML
`SizeType`: `1` `DefaultSize`, `2` `FixedSize`, `3` `RelativeToTextFlow`,
`4` `RelativeToTextSize`; an item without the chunk has `DefaultSize`.
**Groups** have no `AIGeneratedAltText` and `AltTextGenerationError` in
their `ObjectExportOption`: none of the 53 groups of the 7 trustworthy
documents from 21.4 has them. The converter leaves them out on groups,
which removes 106 extra values.
## Text wrap
Page items (class 0x6201 and groups, 0x401) and placed graphics have
@@ -1058,7 +1201,8 @@ chunk 0x3703 (44 bytes):
| 0 | u32 wrap mode: 0 `None`, 1 `JumpObjectTextWrap`, 3 `BoundingBoxTextWrap`, 6 `Contour` |
| 4 | u32 UID of the wrap path object (class 0x3702), or 0 |
| 8 | Four f64 offsets: left, top, right, bottom (IDML `TextWrapOffset`) |
| 40 | u32, not fully identified; 1 in all but one element of the pairs |
| 40 | u16 master page flag: 1 `ApplyToMasterPageOnly="false"`, 0 `true` |
| 42 | u16 `TextWrapSide`: 0 `BothSides`, 1 `LeftSide`, 2 `RightSide`, 3 `SideTowardsSpine`, 4 `SideAwayFromSpine`, 5 `LargestArea` |
The wrap path object holds the contour as path geometry (chunk 0x162B,
as for page items) and names the item in chunk 0x3709.
@@ -1079,9 +1223,26 @@ the pairs whose IDML is from an older version:
| Mode 3 | `TextWrapMode="BoundingBoxTextWrap"` | 1 of 1 (an image) | none |
| Mode 6 | `TextWrapMode="Contour"` | 3 of 3 (one file) | 1 of 1 (an image) |
| Offsets as left, top, right, bottom | `TextWrapOffset` | 2,631 of 2,631 | 616 of 616 |
| u32 at 40 = 1 | `Inverse="false"`, `ApplyToMasterPageOnly="false"`, `TextWrapSide="BothSides"` | 2,630 of 2,630 | 616 of 616 |
| u32 at 40 = 1 (little-endian) | `Inverse="false"`, `ApplyToMasterPageOnly="false"`, `TextWrapSide="BothSides"` | 2,630 of 2,630 | 616 of 616 |
| 0x373D type 5 | `ContourType="SameAsClipping"` | 224 of 225 (1 has no `ContourOption`) | 75 of 75 |
**Master page flag and side.** The 4 bytes at 40 are two u16 in the
file's byte order. The big-endian pair shows it: its 261 page items
store `00 01 00 00` (251, IDML `ApplyToMasterPageOnly="false"`) or
`00 00 00 00` (10, `true`), all with `TextWrapSide="BothSides"`. In
little-endian files the u32 1 is therefore the u16 1 at 40 and the u16 0
at 42. With this layout the converter reproduces, over the 1,251
trustworthy pairs of the corpus after 2026-10, all 256,651
`ApplyToMasterPageOnly` and `TextWrapSide` values of page items, form
fields and placed graphics, where the u32 reading had left 6,322 of
each out (items storing 0 at 40 or a side code). Side codes 1 to 5
occur on few items (14, 4, 9, 1 and 32 in the trustworthy pairs).
Items without the chunk have `false` and `BothSides`.
`Inverse` is `false` on every item of the corpus IDML files (256,651 of
256,651 in the trustworthy pairs); no INDD field is known for it, and
the converter writes `false`.
**Order of the offsets.** Most offsets in the pairs are 0, so the order
rests on a few elements:
@@ -1725,9 +1886,16 @@ itself:
| Class | Chunk | Contents |
|---|---|---|
| Image (0x1702) | 0x8C23 | u32 raw data object (0 = none) |
| Image (0x1702), EPS (0x6601) | 0x8C23 | u32 raw data object (0 = none) |
| PDF (0x2501) | 0x2521 | u32 raw data object (0 = none) |
EPS graphics (class 0x6601) without a link name their raw data object in
chunk 0x8C23 too: over the trustworthy pairs of the corpus after
2026-10 the converter reproduces 497 of the 515 EPS `Contents` (483
were missing before; 18 differ and are not examined). Linked graphics
can have the chunk as well; their IDML has no `Contents`, and the
converter does not use it for them.
Evidence from the corpus pairs: the raw data object equals the IDML
`Contents` for 124 of 124 PDFs and 2 of 2 images without a link. One
more image without a link has 0x8C23 = 0; its IDML `Contents` equals the
@@ -1770,6 +1938,17 @@ Each record starts with a u32 run length in UTF-16 code units. Text
records continue with text segments. Style records continue with the
style UID.
**Stories outside the document's list.** The document's story list does
not name the stories of text frames anchored in the XML backing story.
IDML writes them like the others and lists them at the end of
`StoryList`: one trustworthy document (in two pairs) has 9 such stories,
whose frames are anchored in its backing story; its IDML has all 9
after the listed stories. The converter adds the stories of the text
frames anchored in the backing story, and of frames anchored in those
stories, after the listed ones, in text order. The order IDML gives
them is not that order (it starts with a later one), so `StoryList`
stays different there.
**Story settings.** Three chunks of the story object (trustworthy
pairs, 18,610 stories):
@@ -2017,6 +2196,18 @@ every value, it also writes `LockPosition="false"` and
`AnchorSpaceAbove="0"`, the values of every such element in the corpus
(`idml-values.md`).
**Items inside an anchored item.** The children of an anchored group
(and the items inside them) have an `AnchoredObjectSetting` too. IDML
applies the rule above to each of them with the anchor's chunk 0x2800
values and the child's own object style: every value where the child's
style turns the category off, else the values that differ from that
style. With this rule the converter writes 584 more `AnchoredObjectSetting`
elements over the trustworthy pairs of the corpus after 2026-10 (344 on
text frames, 114 ovals, 61 rectangles, 30 polygons, 22 graphic lines, 7
groups, 6 text boxes), with every value equal and no extra value; 6,503
values of these elements were missing before, and 388 in 2 or 3
documents per element still are (not examined).
**Positions count characters.** A text record's run length counts
UTF-16 code units, but every other position counts characters, a
surrogate pair being one: the lengths in a strand's chunk 0x261 (also
@@ -2232,13 +2423,22 @@ counts are matches of 337 unless stated.
| 0x50F28 | u16 story direction | `StoryPreference/StoryDirection` |
| 0x3776, 0x3777 | Text wrap, as chunks 0x3703 and 0x373D of page items | `TextWrapPreference` |
| 0x1B92E | u32 count, IDs of the categories the style turns on | `Enable…` attributes (below) |
| 0x1B946 | u32 paragraph style, 0 = none | `AppliedParagraphStyle` (`n` for none) |
| 0x1B946 | u32 paragraph style, 0 = none | `AppliedParagraphStyle` (`n` for none, and for a style without the chunk: 5,556 of 5,556 values of the trustworthy pairs of the corpus after 2026-10, 173 of them without the chunk) |
| 0x1E244 | 78 bytes: six f64 at 30 | `FlexLayoutAttributeOption` `FlexPaddingTop`, `FlexPaddingRight`, `FlexPaddingBottom`, `FlexPaddingLeft`, `FlexGapRow`, `FlexGapColumn`; without the chunk 12, 12, 12, 12, 20, 20 (below) |
| 0xCD32 | u16 0 for none, or u16 1 and the UID of a named grid | `AppliedNamedGrid` (named grids, above) |
| 0x1B94D | u16, 1 = true | `ApplyNextParagraphStyle` (below) |
| 0x2800 | Anchored object settings, as in the preferences | `AnchoredObjectSetting` (below) |
| 0x1B907 | u32 based-on style, flag byte and name, u32 shortcut key | `BasedOn`, `Name`, `KeyboardShortcut` (below) |
| 0x1E234 | 52 bytes: u16 flags at 8, 10, 12 and 14, f64 at 16, 24, 32 and 40 | `TransformAttributeOption`: `TransformAttrX`, `TransformAttrY`, `TransformAttrHeight` and `TransformAttrWidth`, each written when its flag is 1 (below) |
**Flex layout spacing.** In chunk 0x1E244 the six f64 at 30 are the
four paddings and the two gaps. A style without the chunk (`[None]`
included) has 12 for each padding and 20 for each gap. With this the
converter reproduces all 226 values of each of the six attributes in the
trustworthy pairs (none was written before). The four paddings are
equal in every sample, as are the two gaps, so the order inside each
group follows the IDML attribute order and is not proven.
**Settings found in the corpus after 2026-10.** Object styles other
than `[None]`, matched by `Self` with their IDML style over the 1,251
trustworthy pairs (4,305 styles; with `[None]`, 5,556):
@@ -2627,8 +2827,9 @@ each (5 frames with 108 pt minimums, 4 without line breaks),
`UseFixedColumnWidth` 747 of 747 (9 true), `TextColumnMaxWidth` 23,043
of 23,043 (one frame with 210.24; the 30-byte chunks of DOM 7 files have
no such field and their IDML no such attribute), `IgnoreWrap` 643 of the
817 frames that have it (74 true; 174 frames without the chunk have
`false` in IDML and are left without it), column rule width and colour
817 frames that have it (74 true; frames without the chunk have `false`,
which the converter writes: 1,871 of 1,871 values in the corpus after
2026-10), column rule width and colour
7,277 and 7,323 of 7,277 and 7,323, footnote spacings 4,351 of 4,351
each. Without chunk 0x22646 the IDML has width 1 and `Color/Black`
(2,816 frames); without chunk 0x22608, 12 and 6 (1,430 frames). The
@@ -2638,8 +2839,22 @@ which IDML has them (`idml-values.md`).
`InsetSpacing`: 16,560 of 18,091 frames. IDML gives 870 frames a single
number instead of a list (the first f64 of chunk 0x3723 in most of
them); what decides this was not found, and the converter writes the
list for every frame from DOM 11 on. DOM 7 to 10 files give most frames
no `InsetSpacing` at all, and the converter writes none for them.
list. From DOM 11 every frame has `InsetSpacing`. Before DOM 11 it
follows the rule of the general category below: IDML writes it where
the frame's insets differ from its object style's (chunk 0x1B924 at 34,
compared as a set of four values, since the order of the style's
fields is not shown) or the style turns the category off. Over the
trustworthy pairs of the corpus after 2026-10 the converter reproduces
40,619 of 42,335 `InsetSpacing` values; 1,645 differ (most are the
single-number form, which the list does not match) and 71 are missing,
where it had 39,762 with 1,057 missing before applying the rule to DOM
7 to 10.
`MinimumFirstBaselineOffset` is 0 on every frame and object style of the
corpus IDML files, so its field cannot be found. IDML writes it on a
frame exactly where the baseline category rule below writes the
baseline attributes; the converter writes `0` under that rule: 1,753 of
1,753 values, none extra.
**Values written on frames.** IDML writes an attribute of a frame's
`TextFramePreference` when its category is off in the frame's object
@@ -3115,10 +3330,14 @@ others `false` (77 of 77 pairs; the DOM 7 pair has no chunk 0x1F61 and
no groups). The root group is named `[Root Color Group]` with no `$ID/`,
though its flag byte is 0.
Before InDesign 11.3 (INDD header version), `Self` is the group's UID
(`u<hex>`) instead: in 58 of the 59 trustworthy pairs of versions 10.0
to 11.2 that have groups (one 11.0 file uses names), and names in 358 of
358 pairs from 11.3 on.
Before DOM 11.3, `Self` is the group's UID (`u<hex>`) instead: in 58 of
the 59 trustworthy pairs of versions 10.0 to 11.2 that have groups (one
11.0 file uses names), and names in 358 of 358 pairs from 11.3 on. The
DOM version decides, not the header: header 11.4 files whose last
session was 11.0 (DOM 11.0) use the UID. With the DOM version the
converter writes (`idml-values.md`, DOM version), the extra `ColorGroup`
elements of the trustworthy pairs fall from 15 values in 5 documents to
6 in 2 (not examined), and 3 more groups are reproduced.
Each swatch of the list is a `ColorGroupSwatch` with
`Self="u<group UID>ColorGroupSwatch<index in hex>"` and `SwatchItemRef`
+47 -15
View File
@@ -102,7 +102,11 @@ value of every file without it.
Without one of the three highlight chunks, IDML has `false` in all but 4
or 5 files, which have no highlight chunk at all and every highlight on
in IDML (or are one collection with other values); no stored value
separates them, so the converter writes these three only from the chunk.
separates them. The converter writes `false` without the chunk, as for
the flags above: 1,247, 1,246 and 1,246 of 1,251 values in the
trustworthy pairs of the corpus after 2026-10 (`HighlightHjViolations`,
`HighlightCustomSpacing`, `HighlightSubstitutedGlyphs`), where it had
56, 52 and 52 from the chunk alone. The exceptions are those files.
`HighlightKeeps` and `HighlightSubstitutedFonts` have no chunk; they are
left to the value files, which do not have them because they vary.
@@ -160,9 +164,10 @@ f64 at 10 `BaselineStart`, f64 at 18 the view threshold as a fraction
Chunk 0x545 (16 files): f64 at 8 `HorizontalGridlineDivision`, u32 at
16 `HorizontalGridSubdivision`, f64 at 20 `VerticalGridlineDivision`,
u32 at 28 `VerticalGridSubdivision`; 16 of 16. Of the 638 files without
it, 627 have 72 and 8 for both directions, which the converter writes;
11 have other values stored elsewhere.
u32 at 28 `VerticalGridSubdivision`; 16 of 16. Without the chunk the
values follow the edition (values of the exporting edition, below):
20 mm (`56.69291338582678`) and 10 after a last session with code
0x0101, else 72 and 8.
## Watermark (`WatermarkPreference` in designmap.xml)
@@ -171,7 +176,8 @@ style, each a u32 length in code units followed by text segments, then
u32 point size and u32 UID of an interface colour (`objects.md`,
interface colours), written as `WatermarkFontColor`. Family, style and
size match 621 of 621. The 33 files without the chunk are left with the
observed values only.
observed values only. Without the chunk the font follows the language
of the assignment name (values of the exporting edition, below).
## Text defaults (`TextDefault`)
@@ -268,9 +274,20 @@ trustworthy pairs.
Chunk 0x550: f64 `Left`, `Top`, `Right`, `Bottom` at 0, 8, 16, 24 (528
of 528 files). The 126 files without it have 36 for all four.
Chunk 0x555: u32 `ColumnCount` at 0, f64 `ColumnGutter` at 4 (119 of
119). Without it, `ColumnCount` is 1 (535 of 535) and `ColumnGutter` 12
(526 of 535; 9 files have another gutter stored elsewhere).
Chunk 0x555 (24 bytes): u32 `ColumnCount` at 0, f64 `ColumnGutter` at 4
(119 of 119), u16 at 12 the column direction: 0 `Horizontal`, 1
`Vertical`. Without it, `ColumnCount` is 1 (535 of 535) and
`ColumnGutter` follows the edition (values of the exporting edition,
below).
**Column direction.** `DocumentPreference` and `MarginPreference`
`ColumnDirection` take the u16 at 12; without the chunk, they equal the
`StoryOrientation` of the story settings (chunk 0x280, byte 116). With
both rules the converter reproduces 1,249 of 1,251 values of each in
the trustworthy pairs of the corpus after 2026-10 (75 of them
`Vertical`). The 2 others have no chunk, horizontal
story orientation and horizontal master pages, but `Vertical` in IDML;
no field was found for them.
## Anchored objects (`AnchoredObjectSetting`)
@@ -309,10 +326,13 @@ the chunk, for each attribute. The u16 at 0 is 0 in all 197, also in
documents with vertical stories; the orientation is in chunk 0x280
(above). Without the chunk, IDML has `OpticalMarginAlignment="false"`
and `FrameType="TextFrameType"` (1,263 of 1,263), but
`OpticalMarginSize` is 12 in 1,207 files and 9.2126 (13 Q) in 56. No
stored value was found that separates the 56 (all have a session of a
Japanese edition in the save history, but so do 326 files with 12), so
the converter leaves the size out without the chunk.
`OpticalMarginSize` is 12 in 1,207 files and 9.2126 (13 Q) in 56. The
text size unit separates them: without the chunk IDML has
`OpticalMarginSize="9.2125984251969"` (13 Q, written with these digits)
when `ViewPreference` `TextSizeMeasurementUnits` is `Q` (chunk 0x1202,
above), and `12` otherwise. The converter writes the size by this rule:
1,251 of 1,251 values in the trustworthy pairs of the corpus after
2026-10 (1,079 of them without the chunk).
## Text wrap of new page items (`TextWrapPreference`)
@@ -475,7 +495,7 @@ IDML ends the base64 text with a line feed when its last line is full
| | u16 at D+30 | `BitmapResolution` |
| | u8 at D+42 | `FontDownloading`: 0 `None`, 1 `Complete`, 2 `Subset` |
| | u8 at D+46 | `DownloadPPDFonts` |
| String | | `MarkType` (enumeration): built-in empty `Default`, built-in `kJMarksWithCircle` `JMarkWithCircle` |
| String | | `MarkType` (enumeration): built-in empty `Default`, built-in `kJMarksWithCircle` `JMarkWithCircle` after a last session with code 0x0101, else `Default` (values of the exporting edition, below) |
| E (72 bytes) | u8 at E+0 | `MarkLineWeight`: 1 `P25pt`, 2 `P50pt`, 4 `P07mm`, 5 `P10mm` |
| | f64 at E+4 | `MarkOffset` |
| | u8 at E+12, 14, 16, 18, 20 | `CropMarks`, `PageInformationMarks`, `ColorBars`, `RegistrationMarks`, `BleedMarks` |
@@ -523,7 +543,8 @@ Evidence: each attribute above was compared over the 489 trustworthy
pairs for both elements; every one matches in all 489, except
`PreserveColorNumbers` (487, the two `CompositeGray` documents) and
`MarkType` (488: one DOM 16.1 document stores `kJMarksWithCircle` and
its IDML has `Default`). Over all 654 pairs, the only further misses are
its IDML has `Default`; in the corpus of 2026-10 every document with
code 0x0100 that stores it has `Default`, 140 and 175 of each element). Over all 654 pairs, the only further misses are
`PPDFile` of two stale booklet pairs (a built-in path written without
`$ID/`). The paper rectangles are written as IDML writes them: with the
digits of the shortest form that reads back, the last rounded half to
@@ -749,6 +770,13 @@ The version boundaries are those of the INDD header: no IDML of an
earlier version has these attributes, every IDML from that version on
has them.
`EPubExportPreference` `ViewDocumentAfterExport="true"` is in the IDML
of DOM 8 and 9 only, with the chunk or without it: 107 of the 108
distinct corpus IDML files of those versions (the other, a DOM 8 file,
has `false`); one DOM 7 file has it too, and no file of DOM
10 or later. The chunks read above do not hold it. The converter writes
`true` for DOM 8 and 9: 97 of 97 values in the trustworthy pairs.
## Adjust layout (`AdjustLayoutPreference` in designmap.xml)
From DOM 14. Chunk 0x7020 of the preferences object (26 bytes, 83
@@ -775,9 +803,13 @@ the one that saved it last; the counts give them. Over the corpus of
|---|---|---|
| `BaselineFrameGridColor` (preference and object styles) where chunk 0x2834 names no colour | `Charcoal` when the last session's language code is 0x0101, else `LightBlue` | 1,112 of 1,209 (1,318 of 1,416); the byte-168 rule matched 892. 96 exceptions are two collections of one Korean publisher (code 0x0101, IDML `LightBlue`) |
| `DocumentPreference` `ColumnGuideColor` without chunk 0x555 | `Lavender` for code 0x0101, else `Violet` | 822 of 845 (965 of 989); 22 exceptions in the same collections |
| `GridPreference` gridline divisions and subdivisions without chunk 0x545 | code 0x0101: `56.69291338582678` (20 mm) and `10`; else `72` and `8` | with the documents that have the chunk, 1,152 of 1,251 for each of the four values (915 with 72 and 8 for every document); 96 of the 99 exceptions are the same two collections, 3 are other documents (one with code 0x0101 and 72, one with another code and 20 mm, one with 28.35) |
| `MarginPreference` `ColumnGutter` without chunk 0x555 | code 0x0101: `14.173228346456694` (5 mm); else `12` | with the documents that have the chunk, 1,223 of 1,251 (1,021 with 12 for every document); 22 of the 28 exceptions are the two collections, 6 others have 17, 20 or 5 mm with another code |
| `PrintPreference` and `PrintBookletPrintPreference` `MarkType` stored as `kJMarksWithCircle` | `JMarkWithCircle` for code 0x0101, else `Default` | 1,154 and 1,131 of 1,251 (1,014 and 956 with the stored name alone); the exceptions are 96 documents of the two collections with `Default` in each element, one more for `PrintPreference`, and the booklet settings of 24 documents without chunk 0xAF2 (below) |
| `WatermarkPreference` `WatermarkFontFamily`, `WatermarkFontStyle` without chunk 0x16344 | by the assignment name: English `Minion Pro` `Regular`, Korean `Adobe Myungjo Std` `M`, traditional Chinese (`未指定的 InCopy 內容`) `Adobe Ming Std` `L`, Japanese `Kozuka Mincho Pro` `R`; other languages none | 1,251 of 1,251 each (57 without the chunk) |
| `PublishExportPreference` `ImageExportResolution`, `PublishPdf` | by the last session's version: 11.0 `Ppi72` and no `PublishPdf`; 11.1 `Ppi96` and no `PublishPdf`; 11.2 and later `Ppi96` and `PublishPdf="false"` | 1,021 of 1,023 trustworthy pairs from 11.0 (the two exceptions have an IDML of another release than the last session); by the header version 5 more fail, among them 3 files of header 11.4 last saved by 11.0 |
| `AdjustLayoutPreference` `EnableAdjustLayout` without chunk 0x7020 | `true` when the last session's version string starts with 14.0.0 or 14.0.1, else `false` | 634 of 634 files from version 14 without the chunk (547 trustworthy) |
| `IndexOptions` `Title` and `BetweenEntriesSeparator` without chunk 0x13010 | by the assignment name: Japanese `索引` and `、`; Chinese `索引` and `; `; Korean `색인` and `; `; English, French, German, Dutch `Index` and `; `; Italian `Indice` and `; `; other languages `; ` and no title; English with a last session of code 0x0101 `; ` and no title | title 1,096 of 1,155 written (59 English documents exported by a Korean or Italian edition), 30 left out; separator 1,183 of 1,185 |
| `IndexOptions` `Title` and `BetweenEntriesSeparator` without chunk 0x13010 | the title by the saving edition (`objects.md`, saving edition); without a black name, and for the separator, by the assignment name: Japanese `索引` and `、`; Chinese `索引` and `; `; Korean `색인` and `; `; English, French, German, Dutch `Index` and `; `; Italian `Indice` and `; `; other languages `; ` and no title; English with a last session of code 0x0101 `; ` and no title | title 1,250 of 1,251 (by the assignment name 1,096 of 1,155 written, 59 English documents saved by a Korean or Italian edition, 30 left out); separator 1,183 of 1,185 |
| `LayoutAdjustmentPreference` `SnapZone` without chunk 0x7006 | `0.70866141732283` (0.25 mm) when the horizontal ruler unit is millimetres or centimetres or the assignment name is not English, else `2` | 1,172 of 1,183 (1,358 of 1,377); the exceptions are English documents in picas, points, inches or pixels |
| `DOMVersion` of every part | by the last session's version (`idml-values.md`, DOM version) | 1,164 of 1,251 |
| `KeyboardShortcut` of a style with a digit key | by the platform of the last session (`objects.md`, styles) | 3,154 of 3,154 character and 6,927 of 6,928 paragraph styles |
+1 -1
View File
@@ -226,7 +226,7 @@ files), where every attribute of the table now matches on every cell.
| 0xB63E | `FillTint` | f64 | 142 (2) |
| 0xB639 | `OverprintFill` | u16, 0 = false | 153 (1); 6 cell styles |
| 0xB677 | `VerticalJustification` | 0 `TopAlign`, 1 `CenterAlign`, 2 `BottomAlign`, 3 `JustifyAlign` | 5,361 (21); 383 cells with 0 (1 file); 3 in 1 cell style |
| 0xB676 | `FirstBaselineOffset` | 0 `LeadingOffset`, 1 `AscentOffset` | 4,445 (3); 2 cell styles |
| 0xB676 | `FirstBaselineOffset` | 0 `LeadingOffset`, 1 `AscentOffset`, 3 `EmboxHeight` | 4,445 (3); 2 cell styles; code 3: 2,143 cells of the corpus of 2026-10 (`attributes.md`, more codes) |
| 0xB6E1 | `WritingDirection` | 1 = true | 4,445 (3) |
| 0xB675 | `RotationAngle` | f64 | 1 (270) |
| 0xB6DE | `ClipContentToCell` | 0 = false | 664 (5, one value) |
+37 -4
View File
@@ -24,7 +24,14 @@ lacks an IDML element. The layout below also holds for all 2,496 class
| u32 *n*, segments | Name: *n* UTF-16 code units as text segments (`objects.md`) |
| u32 *n*, segments | Text: the date format of date variables (below) |
| u32 | Type code |
| 20 bytes | Settings, mostly not identified (below) |
| u32 *a*, u32 *b*, u32 *c* | Settings (below) |
| u32 *n*, segments | `TextBefore` |
| u32 *n*, segments | `TextAfter` |
The "20 bytes" of the definitions of the earlier pairs are this layout
with empty texts. The running header and chapter number definitions of
the trustworthy pairs of the corpus of 2026-10 parse to the end of their
chunk with it (their settings are all reproduced, below).
**Type codes** (each code with its `VariableType` in every pair):
@@ -58,6 +65,20 @@ settings is a paragraph style UID. It differs between files, but in all
135 pairs it is the style that IDML writes as
`AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"`.
## Settings
- `TextBefore` and `TextAfter` are the two texts; IDML writes U+3000 as
`^(`. With them the converter reproduces every `TextBefore` and
`TextAfter` of the running header and chapter number settings of the
trustworthy pairs (1,287 and 1,227 elements), among them chapter
numbers with text before or after the number.
- Running header (0xCAAA): *b* is the paragraph style; *c* is
`SearchStrategy`, 0 `FirstOnPage`, 1 `LastOnPage`; *a* is `ChangeCase`,
0 or 0xCAC9 `None`, 0xCAD0 `Sentencecase`. 1,287 of 1,287 values each
in the trustworthy pairs.
- Chapter number (0xCAA9): *a* is `Format`, 0 `Current`; 0x4C15
`Arabic` (one definition, in a trustworthy pair).
## Settings with one value in the corpus
The other IDML settings have the same value in every pair:
@@ -116,6 +137,18 @@ The INDD does not store it: the four pairs' modification date text
(`October 31, 2023 4:06 PM`) does not occur in the INDD files, either as
single bytes or as UTF-16. The file name instances (4 of 4) show the
INDD file name without its extension, as their settings
(`IncludePath="false"`, `IncludeExtension="false"`) say. The converter
writes `ResultText` only for file name variables with those settings,
and leaves it out (it is optional in the schema) for all others.
(`IncludePath="false"`, `IncludeExtension="false"`) say.
In the corpus of 2026-10 two more kinds of instance show their text:
- A running header on a master page shows `TextBefore`, `<`, the
variable's name, `>` and `TextAfter`.
- A chapter number in the `Current` format shows `TextBefore`, the
document's chapter number (`ChapterNumberPreference`) and
`TextAfter`.
The converter writes `ResultText` for these and for the file name
variables above, and leaves it out (it is optional in the schema) for
all others: page numbers, dates and cross-reference page numbers depend
on the layout or the export time. Over the trustworthy pairs it
reproduces 80 of the 280 `ResultText` values, with 1 different.
+26 -4
View File
@@ -82,6 +82,7 @@ nothing else in the transparency settings of the trustworthy pairs.
| 0x10820 | `DropShadowSetting/Size` | f64 | 6 items, two values; 406 of 406 rectangles and text frames over the 654 pairs of the later corpus |
| 0x1084A | `DropShadowSetting/Spread` | f64, percent | 28 of 28 items in 9 files |
| 0x10837 | `DropShadowSetting/EffectColor` | swatch UID | 11 of 11 items in 6 files (below) |
| 0x1EB6F | `DropShadowSetting/KnockedOut` | u16: 1 true, 0 false; `true` where not stored | 30,692 of 30,692 items (below) |
| 0x1084D | `InnerShadowSetting/Applied` | u16: 1 true, 0 false | 10 items with 1 |
| 0x1084E | `InnerShadowSetting/EffectColor` | swatch UID | 10 items (below) |
| 0x10852 | `InnerShadowSetting/Distance` | f64 | 10 items with 0 |
@@ -116,9 +117,8 @@ value maps one to one onto the IDML value in all rows):
IDML writes `OuterGlowSetting` and `InnerGlowSetting` after
`InnerShadowSetting`, as the schema lists them. Not identified: the
inner glow's `Opacity`, `Spread` and `EffectColor`, the outer glow's
`Noise`, and drop shadow `KnockedOut` (497 items of one 8.0 document,
`true` in all, no local ID varies).
inner glow's `Opacity`, `Spread` and `EffectColor` and the outer glow's
`Noise`. Drop shadow `KnockedOut` is 0x1EB6F (below).
All items whose value is not on the IDML item (it comes from the style
or the default) match as well: for example 743 items for
@@ -164,6 +164,28 @@ style stores 0 has the Black swatch, and its IDML has no
leaves the value out for another reason; the converter leaves out
Black when the style stores 0.
**Drop shadow knockout.** Page item attribute 0x1EB6F is
`DropShadowSetting/KnockedOut`: a u16, 1 `true`, 0 `false` (value type
0x6E65). Object styles hold it in their transparency list (chunk
0x1B92C); `[None]` stores 1, and the styles that store 0 are mostly
`[Normal Graphics Frame]`, `[Normal Text Frame]` and user styles of
older documents. The document's base list (class 0x6E02) does not have
it. An item or a style chain that does not store it has `true`, the
value of `TransparencyDefaultContainerObject` in every corpus IDML.
IDML writes `KnockedOut` on the item when this value differs from the
style's, by the rule above; an item without an object style gets no
value it does not store.
With this rule the converter reproduces, over the trustworthy pairs,
every `KnockedOut` of the items: 17,543 of 17,543 rectangles, 9,505 of
9,505 text frames, 1,911 of 1,911 polygons, 1,578 of 1,578 graphic
lines and 155 of 155 ovals. Before the rule, 25, 13, 14, 23 and 8
documents missed these `DropShadowSetting` elements. It also writes 380
elements that IDML does not have (760 extra values in 3 documents):
items that store nothing, whose style stores 0, and whose IDML has no
`KnockedOut`. Nothing stored in the items or their styles separates
them from the items that follow the rule; they stay open (`unknowns.md`).
Not covered: items whose drop shadow is off (`Mode="None"`) for which
IDML still writes a `DropShadowSetting` (the "D empty, IDML writes it"
column above).
@@ -214,7 +236,7 @@ settings), 170 of 170.
## Not converted
- Drop shadow `Noise`, `KnockedOut` and `UseGlobalLight`.
- Drop shadow `Noise` and `UseGlobalLight`.
- Stroke, fill and content blending (opacity and blend mode) and the
other effects (feather, outer and inner glow, bevel and emboss, satin,
directional feather): no item or style in the pairs has a value other
+5
View File
@@ -23,6 +23,8 @@ pub(super) struct StyleValues {
pub footnote: Option<(bool, f64, f64)>,
/// Baseline frame grid of the text frame settings.
pub baseline: Option<crate::model::BaselineGrid>,
/// Insets of the text frame settings, in stored order.
pub insets: Option<[f64; 4]>,
}
impl StyleValues {
@@ -112,6 +114,9 @@ impl Writer<'_> {
if out.baseline.is_none() {
out.baseline = f.baseline_grid;
}
if out.insets.is_none() {
out.insets = f.insets;
}
}
if (s.frame.is_some() || is_root)
&& let Some(t) = node.child("TextFramePreference")
+72 -2
View File
@@ -137,6 +137,20 @@ pub(super) fn text_wrap_mode(wrap: Option<&TextWrap>) -> Option<&'static str> {
}
}
/// IDML `TextWrapSide` of the side code of a text wrap; `None` for a code
/// without evidence. See `docs/format/objects.md`, text wrap.
pub(super) fn text_wrap_side(code: u16) -> Option<&'static str> {
Some(match code {
0 => "BothSides",
1 => "LeftSide",
2 => "RightSide",
3 => "SideTowardsSpine",
4 => "SideAwayFromSpine",
5 => "LargestArea",
_ => return None,
})
}
/// IDML `TextWrapOffset` attributes of a text wrap (0 without one).
pub(super) fn text_wrap_offsets(wrap: Option<&TextWrap>) -> Vec<(&'static str, String)> {
let [left, top, right, bottom] = wrap.map_or([0.0; 4], |w| w.offsets);
@@ -179,6 +193,37 @@ pub(super) const STROKE_TYPES: &[(u32, &str)] = &[
(0xB01A, "Triple_Stroke"),
];
/// Whether a dash attribute (`StrokeDashAndGap`, `StrokeCornerAdjustment`)
/// is written: IDML has them only where the stroke type in effect is
/// `Dashed` (attributes.md, dashes).
pub(super) fn dash_written(name: &str, stroke_type: Option<&str>) -> bool {
!matches!(name, "StrokeDashAndGap" | "StrokeCornerAdjustment")
|| stroke_type == Some("StrokeStyle/$ID/Dashed")
}
/// The stroke type code of a custom stroke style, stored with its UID.
pub(super) const CUSTOM_STROKE_TYPE: u32 = 0x5A42;
/// The `Self` of a custom stroke style.
pub(super) fn custom_stroke_ref(st: &crate::model::StrokeStyle) -> String {
let kind = if st.dashed {
"DashedStrokeStyle"
} else {
"StripedStrokeStyle"
};
format!("{kind}/{}", self_name(&st.name))
}
/// IDML `EndCap` of an end cap code (attribute 0x6E6B).
pub(super) fn end_cap(code: u32) -> Option<&'static str> {
Some(match code {
0 => "ButtEndCap",
1 => "RoundEndCap",
2 => "ProjectingEndCap",
_ => return None,
})
}
/// The stroke styles every corpus IDML lists in `Graphic.xml`, in order.
/// See `docs/format/idml-values.md`.
pub(super) const BUILTIN_STROKE_STYLES: &[&str] = &[
@@ -446,7 +491,12 @@ pub(super) const TEXT_ATTRS: &[(u32, &str, Kind, bool)] = &[
(
0x4266,
"GridAlignment",
Kind::Enum(&[(0, "None"), (1, "AlignBaseline")]),
Kind::Enum(&[
(0, "None"),
(1, "AlignBaseline"),
(2, "AlignEmTop"),
(3, "AlignEmCenter"),
]),
false,
),
(
@@ -491,9 +541,23 @@ pub(super) const TEXT_ATTRS: &[(u32, &str, Kind, bool)] = &[
(0, "AlignBaseline"),
(1, "AlignEmCenter"),
(2, "AlignEmBottom"),
(3, "AlignEmTop"),
(4, "AlignICFTop"),
(5, "AlignICFBottom"),
]),
false,
),
(
0x1B09,
"PageNumberType",
Kind::Enum(&[
(0, "AutoPageNumber"),
(2, "NextPageNumber"),
(3, "TextVariable"),
]),
false,
),
(0x1B5E, "CustomGlyph", Kind::GlyphName, true),
(0x1B4C, "RuleAboveColor", Kind::SwatchOrText, true),
(0x1B5C, "RuleAbove", Kind::Bool, false),
(0x1B83, "HyphenWeight", Kind::Number, false),
@@ -951,6 +1015,8 @@ pub(super) const ITEM_ATTRS: &[(u32, &str, Kind)] = &[
]),
),
(0x6E66, "StrokeTint", Kind::Tint),
(0x5A35, "StrokeDashAndGap", Kind::Dashes),
(0x5A35, "StrokeCornerAdjustment", Kind::DashCorner),
(0x6E89, "GapColor", Kind::Swatch),
(0x6E8A, "GapTint", Kind::Tint),
(
@@ -1077,7 +1143,11 @@ pub(super) const CELL_ATTRS: &[(u32, &[&str], Kind)] = &[
(
0xB676,
&["FirstBaselineOffset"],
Kind::Enum(&[(0, "LeadingOffset"), (1, "AscentOffset")]),
Kind::Enum(&[
(0, "LeadingOffset"),
(1, "AscentOffset"),
(3, "EmboxHeight"),
]),
),
(0xB6E1, &["WritingDirection"], Kind::Enum(&[(1, "true")])),
(0xB675, &["RotationAngle"], Kind::Number),
+302 -60
View File
@@ -7,25 +7,20 @@
use super::*;
/// IDML `HeaderType` of an index group by its name and header variant.
/// See `docs/format/objects.md`, index sort options.
pub(super) fn index_header_type(group: &str, variant: u16) -> Option<&'static str> {
Some(match (group, variant) {
("kIndexGroup_Alphabet", 0) => "BasicLatin",
("kIndexGroup_Alphabet", 3) => "Spanish",
("kIndexGroup_Alphabet", 5) => "Czech",
("kWRIndexGroup_CyrillicAlphabet", 2) => "Russian",
("kIndexGroup_Kana", 0) => "HiraganaAll",
("kIndexGroup_Chinese", 0) => "ChinesePinyin",
("kIndexGroup_Korean", 0) => "KoreanConsonant",
(
"kIndexGroup_Symbol"
| "kIndexGroup_Numeric"
| "kWRIndexGroup_GreekAlphabet"
| "kWRIndexGroup_ArabicAlphabet"
| "kWRIndexGroup_HebrewAlphabet",
0,
) => "Nothing",
/// IDML `HeaderType` of an index group by the name of its header variant;
/// a variant named like its group has none (objects.md, index sort
/// options).
pub(super) fn index_header_type(group: &str, variant: &str) -> Option<&'static str> {
Some(match variant {
"IDX_Basic" => "BasicLatin",
"IDX_Spanish" => "Spanish",
"IDX_Czech" => "Czech",
"IDX_Russian" => "Russian",
"IDX_AllHira" => "HiraganaAll",
"IDX_ChinesePinyin" => "ChinesePinyin",
"IDX_ChineseStroke" => "ChineseStrokeCount",
"IDX_KoreanConsonant" => "KoreanConsonant",
v if v == group => "Nothing",
_ => return None,
})
}
@@ -140,6 +135,25 @@ impl Writer<'_> {
("EnableAutoAdjustMargins", "false"),
]
}
// Without chunk 0x16344 the font follows the language of the
// assignment name (preferences.md, watermark).
"WatermarkPreference" => {
let font = match self.doc.assignment_name.as_deref() {
Some("未指定的 InCopy 內容") => Some(("Adobe Ming Std", "L")),
_ => match self.edition() {
Some(Edition::English) => Some(("Minion Pro", "Regular")),
Some(Edition::Korean) => Some(("Adobe Myungjo Std", "M")),
Some(Edition::Japanese) => Some(("Kozuka Mincho Pro", "R")),
_ => None,
},
};
font.map_or_else(Vec::new, |(family, style)| {
vec![
("WatermarkFontFamily", family),
("WatermarkFontStyle", style),
]
})
}
_ => Vec::new(),
}
}
@@ -177,12 +191,31 @@ impl Writer<'_> {
}
// `false` in every corpus IDML (docs/format/idml-values.md).
x.attr("AccurateLABSpots", "false");
if !doc.label.is_empty() {
x.start("Properties").start("Label");
for (k, v) in &doc.label {
x.empty("KeyValuePair", &[("Key", k.clone()), ("Value", v.clone())]);
// The MathML settings every IDML of DOM 20 has, and of 20.4
// (idml-values.md, document attributes).
let mathml = self.dom_version() >= (20, 0);
if mathml {
x.attr("AppliedMathMLRgbColor", "0 0 0")
.attr("TintValue", "100");
}
if self.dom_version() >= (20, 4) {
x.attr("PreferMathMLInEpubExport", "false");
}
if !doc.label.is_empty() || mathml {
x.start("Properties");
if !doc.label.is_empty() {
x.start("Label");
for (k, v) in &doc.label {
x.empty("KeyValuePair", &[("Key", k.clone()), ("Value", v.clone())]);
}
x.end();
}
if mathml {
x.start("AppliedMathMLSwatch")
.attr("type", "enumeration")
.text("Nothing")
.end();
}
x.end();
x.end();
}
self.languages(&mut x);
@@ -247,12 +280,19 @@ impl Writer<'_> {
let singleton = |x: &mut Xml, tag: &str| {
// Every IDML from 7.5 has the tagged PDF settings, none of 7.0
// (preferences.md, tagged PDF).
// Every IDML from DOM 10.1 has the fixed-layout HTML export
// settings, none of 10.0 (idml-values.md, document elements).
let present = values::present(&format!("Document/{tag}"), major).or_else(|| {
(tag == "TaggedPDFPreference" && (major, doc.version.minor) >= (7, 5)).then(|| {
Node {
let since = match tag {
"TaggedPDFPreference" => (major, doc.version.minor) >= (7, 5),
"HTMLFXLExportPreference" => self.dom_version() >= (10, 1),
_ => false,
};
since.then(|| {
values::element(&format!("Document/{tag}"), major).unwrap_or_else(|| Node {
tag: tag.to_string(),
..Node::default()
}
})
})
});
if let Some(n) = present {
@@ -380,6 +420,10 @@ impl Writer<'_> {
x.attr("AlternateLayoutLength", layout_lengths[k].to_string())
.attr("AlternateLayout", name);
}
// The pagination values of DOM 8 (idml-values.md, sections).
if let Some(n) = values::element("Section", doc.version.major) {
x.attrs_missing(n.attrs.iter());
}
// IDML gives a start number only to sections that restart
// numbering.
if !section.continue_numbering {
@@ -396,11 +440,17 @@ impl Writer<'_> {
}
x.end();
}
// Document users. A user with flag 2 is the placeholder for an
// unknown user, which IDML names `$ID/Unknown User Name`; the
// colours are left out (docs/format/objects.md, document users).
// Document users. IDML names `$ID/Unknown User Name` a user whose
// name is the saving edition's name for an unknown user; without
// the edition, a user with flag 2. The colours are left out
// (docs/format/objects.md, document users and saving edition).
let unknown = self.saving_edition().map(Edition::unknown_user);
for (i, (flag, name)) in doc.users.iter().enumerate() {
let name = if *flag == 2 {
let placeholder = match unknown {
Some(names) => names.contains(&name.as_str()),
None => *flag == 2,
};
let name = if placeholder {
"$ID/Unknown User Name"
} else {
name.as_str()
@@ -462,7 +512,7 @@ impl Writer<'_> {
.attr("Name", builtin_key(name))
.attr("Include", include.to_string())
.attr("Priority", i.to_string());
if let Some(h) = index_header_type(name, *variant) {
if let Some(h) = variant.as_deref().and_then(|v| index_header_type(name, v)) {
x.attr("HeaderType", h);
}
x.end();
@@ -568,10 +618,85 @@ impl Writer<'_> {
}
x.attrs_missing(self.observed("TOCStyle").iter());
x.attrs_missing(values::when_written("TOCStyle", major).iter());
let observed = self.observed("TOCStyleEntry");
for (i, e) in t.entries.iter().enumerate() {
self.toc_entry(x, t.uid, i, e, &observed);
}
x.end();
}
}
/// An entry of a table of contents style (`objects.md`, table of
/// contents styles).
fn toc_entry(
&self,
x: &mut Xml,
toc: u32,
i: usize,
e: &crate::model::TocEntry,
observed: &[(String, String)],
) {
let name = e.name.replace('\u{E00B}', ":");
let name = if e.builtin {
format!("$ID/{name}")
} else {
name
};
let position = match e.page_number_position {
0 => Some("AfterEntry"),
1 => Some("BeforeEntry"),
2 => Some("None"),
_ => None,
};
x.start("TOCStyleEntry")
.attr("Self", format!("u{toc:x}TOCStyleEntry{i:x}"))
.attr("Name", name)
.attr("Level", e.level.to_string());
if let Some(p) = position {
x.attr("PageNumberPosition", p);
}
x.attr("Separator", toc_separator(&e.separator));
x.attrs_missing(observed.iter());
let style = |uid: u32, paragraph: bool, same: &str| -> Option<(&'static str, String)> {
if uid == 0 {
return Some(("string", same.to_string()));
}
self.doc.styles.get(&uid)?;
let r = self.style_ref(Some(uid), paragraph);
Some(match r.split_once('/') {
Some((_, root @ ("$ID/[No paragraph style]" | "$ID/[No character style]"))) => {
("string", root.to_string())
}
_ => ("object", r),
})
};
let props: Vec<_> = [
(
"FormatStyle",
style(e.format_style, true, "$ID/kSameStyleWithBracket"),
),
(
"PageNumberStyle",
style(e.page_number_style, false, "$ID/[Same Style]"),
),
(
"SeparatorStyle",
style(e.separator_style, false, "$ID/[Same Style]"),
),
]
.into_iter()
.filter_map(|(k, v)| v.map(|v| (k, v)))
.collect();
if !props.is_empty() {
x.start("Properties");
for (k, (ty, v)) in props {
x.start(k).attr("type", ty).text(&v).end();
}
x.end();
}
x.end();
}
/// The document's languages, in UID order. See
/// `docs/format/objects.md`, languages.
pub(super) fn languages(&self, x: &mut Xml) {
@@ -633,10 +758,9 @@ impl Writer<'_> {
/// Colour groups and their swatches. See `docs/format/objects.md`.
pub(super) fn color_groups(&self, x: &mut Xml) {
let v = self.doc.version;
for (i, g) in self.doc.color_groups.iter().enumerate() {
// Named by UID before 11.3 (objects.md, colour groups).
let id = if (v.major, v.minor) < (11, 3) {
// Named by UID before DOM 11.3 (objects.md, colour groups).
let id = if self.dom_version() < (11, 3) {
uref(Some(g.uid))
} else {
format!("ColorGroup/{}", self_name(&g.name))
@@ -707,12 +831,41 @@ impl Writer<'_> {
.push(("EndnoteMarkerStyle".into(), self.style_ref(None, false)));
n.attrs
.push(("EndnoteTextStyle".into(), self.style_ref(None, true)));
// The title and the marker position follow the saving edition
// where the black name shows it (objects.md, saving edition).
let saved = self.saving_edition();
let title = saved.and_then(|e| {
Some(match e {
Edition::English => "Endnotes",
Edition::Korean => "미주",
Edition::Japanese => match self.dom_version().0 {
..=13 => "文末脚注",
19.. => "後注",
_ => return None,
},
Edition::German => "Endnoten",
Edition::French => "Notes de fin",
Edition::Italian => "Note di chiusura",
Edition::Dutch => "Eindnoten",
_ => return None,
})
});
if let Some(t) = title {
n.attrs.insert(0, ("EndnoteTitle".into(), t.into()));
}
if let Some(japanese) = self.japanese_session() {
let (separator, position) = if japanese {
let (separator, mut position) = if japanese {
("\u{3000}", "RubyMarker")
} else {
("\t", "SuperscriptMarker")
};
if let Some(e) = saved.filter(|e| *e != Edition::Other) {
position = if e == Edition::Japanese {
"RubyMarker"
} else {
"SuperscriptMarker"
};
}
n.attrs
.push(("EndnoteSeparatorText".into(), separator.into()));
n.children.push(Node {
@@ -1050,10 +1203,21 @@ impl Writer<'_> {
/// those samples have in IDML.
pub(super) fn variable_preference(&self, x: &mut Xml, v: &TextVariable) {
let same = v.as_in_samples;
let text = |x: &mut Xml, name: &str| {
if same {
// The text before and after the value, from the settings
// (text-variables.md, settings).
let text = |x: &mut Xml, name: &str| match &v.settings {
Some(st) => {
let t = if name == "TextBefore" {
&st.before
} else {
&st.after
};
x.attr(name, t.replace('\u{3000}', "^("));
}
None if same => {
x.attr(name, "");
}
None => {}
};
match v.kind {
0xCAA1 | 0xCAAB | 0xCAAC => {
@@ -1068,11 +1232,45 @@ impl Writer<'_> {
text(x, "TextBefore");
text(x, "TextAfter");
x.attr("AppliedParagraphStyle", self.style_ref(v.style, true));
if same {
x.attr("SearchStrategy", "FirstOnPage")
.attr("ChangeCase", "None")
.attr("DeleteEndPunctuation", "false");
if let Some(st) = &v.settings {
match st.c {
0 => {
x.attr("SearchStrategy", "FirstOnPage");
}
1 => {
x.attr("SearchStrategy", "LastOnPage");
}
_ => {}
}
match st.a {
0 | 0xCAC9 => {
x.attr("ChangeCase", "None");
}
0xCAD0 => {
x.attr("ChangeCase", "Sentencecase");
}
_ => {}
}
}
if same {
x.attr("DeleteEndPunctuation", "false");
}
x.end();
}
// Chapter numbers: the format code is the first u32
// (text-variables.md, settings).
0xCAA9 if v.settings.is_some() => {
let format = match v.settings.as_ref().map(|st| st.a) {
Some(0) => Some("Current"),
Some(0x4C15) => Some("Arabic"),
_ => None,
};
x.start("ChapterNumberVariablePreference");
text(x, "TextBefore");
if let Some(f) = format {
x.attr("Format", f);
}
text(x, "TextAfter");
x.end();
}
_ if !same => {}
@@ -1107,16 +1305,7 @@ impl Writer<'_> {
],
);
}
0xCAA9 => {
x.empty(
"ChapterNumberVariablePreference",
&[
("TextBefore", String::new()),
("Format", "Current".into()),
("TextAfter", String::new()),
],
);
}
0xCAC0 => {
x.empty(
"CaptionMetadataVariablePreference",
@@ -1131,21 +1320,56 @@ impl Writer<'_> {
}
}
/// Whether a text frame of a master spread shows story `story`.
fn on_master(&self, story: u32) -> bool {
fn has(items: &[crate::model::PageItem], story: u32) -> bool {
items.iter().any(|i| {
matches!(i.kind, ItemKind::TextFrame { story: Some(s), .. } if s == story)
|| has(&i.children, story)
})
}
self.doc.master_spreads.iter().any(|s| has(&s.items, story))
}
/// A text variable instance in place of its U+0018.
pub(super) fn variable_instance(&self, x: &mut Xml, v: &Instance) {
pub(super) fn variable_instance(&self, x: &mut Xml, v: &Instance, story: u32) {
let name = variable_name(&v.name);
x.start("TextVariableInstance")
.attr("Self", uref(Some(v.uid)))
.attr("Name", &name);
// The displayed text is not stored. A file name variable with the
// sample settings shows the document's name without extension.
// sample settings shows the document's name without extension; a
// running header on a master page shows the variable's name, and a
// chapter number in the current format the document's number,
// each between the text before and after (text-variables.md,
// result text).
let def = self.doc.text_variables.iter().find(|d| d.name == v.name);
if let Some(d) = def
&& d.kind == 0xCAA6
&& d.as_in_samples
{
let stem = self.name.strip_suffix(".indd").unwrap_or(&self.name);
x.attr("ResultText", stem);
let around = |d: &TextVariable, t: &str| {
d.settings
.as_ref()
.map(|s| format!("{}{t}{}", s.before, s.after))
};
let result = match def {
Some(d) if d.kind == 0xCAA6 && d.as_in_samples => Some(
self.name
.strip_suffix(".indd")
.unwrap_or(&self.name)
.to_string(),
),
Some(d) if d.kind == 0xCAAA && self.on_master(story) => {
around(d, &format!("<{}>", d.name))
}
Some(d) if d.kind == 0xCAA9 && d.settings.as_ref().is_some_and(|s| s.a == 0) => self
.doc
.prefs
.values
.iter()
.find(|p| p.element == "ChapterNumberPreference" && p.name == "ChapterNumber")
.and_then(|p| around(d, &p.value)),
_ => None,
};
if let Some(r) = result {
x.attr("ResultText", r);
}
x.attr("AssociatedTextVariable", format!("dTextVariablen{name}"));
x.end();
@@ -1234,3 +1458,21 @@ fn custom_mojikumi(x: &mut Xml, m: &crate::model::cjk::MojikumiSettings) {
x.end();
x.end();
}
/// A TOC entry separator as IDML writes it: `$ID/`, then the text with
/// tab, U+0008, line feed, em space and em dash as `^t`, `^y`, `^n`, `^m`
/// and `^_` (`objects.md`, table of contents styles).
fn toc_separator(s: &str) -> String {
let mut out = String::from("$ID/");
for ch in s.chars() {
match ch {
'\t' => out.push_str("^t"),
'\u{8}' => out.push_str("^y"),
'\n' => out.push_str("^n"),
'\u{2003}' => out.push_str("^m"),
'\u{2014}' => out.push_str("^_"),
c => out.push(c),
}
}
out
}
+6
View File
@@ -175,6 +175,9 @@ tools/element_values.py; evidence in docs/format/idml-values.md.
<HTMLExportPreference BulletExportOption="UnorderedList" NumberedListExportOption="OrderedList" ImageExportOption="OptimizedImage" ImageExportResolution="Ppi150" CustomImageSizeOption="SizeFixed" ImageAlignment="AlignCenter" ImageSpaceBefore="0" ImageSpaceAfter="0" ImageConversion="Automatic" GIFOptionsPalette="AdaptivePalette" GIFOptionsInterlaced="false" JPEGOptionsQuality="High" JPEGOptionsFormat="ProgressiveEncoding" Level="5" IgnoreObjectConversionSettings="false" ServerPath="" ImageExtension=".jpg" LeftMargin="0" RightMargin="0" TopMargin="0" BottomMargin="0" MarginUnit="CssPixel" IncludeCSSDefinition="true" CSSExportOption="EmbeddedCSS" />
</Preferences>
</Values>
<Values MinimumVersion="8" MaximumVersion="8">
<Section Pagination="AutoPaginate" PaginationMaster="n" />
</Values>
<Values MinimumVersion="8" MaximumVersion="13">
<Button AppliedObjectStyle="ObjectStyle/$ID/[None]" />
<MultiStateObject InitiallyHidden="false" TargetInterfaceChangeCount="" LastUpdatedInterfaceChangeCount="" OverriddenPageItemProps="" HorizontalLayoutConstraints="FlexibleDimension FixedDimension FlexibleDimension" VerticalLayoutConstraints="FlexibleDimension FixedDimension FlexibleDimension" GradientFillStart="0 0" GradientFillLength="0" GradientFillAngle="0" GradientStrokeStart="0 0" GradientStrokeLength="0" GradientStrokeAngle="0" LocalDisplaySetting="Default" GradientFillHiliteLength="0" GradientFillHiliteAngle="0" GradientStrokeHiliteLength="0" GradientStrokeHiliteAngle="0" AppliedObjectStyle="ObjectStyle/$ID/[None]" Visible="true" />
@@ -497,6 +500,9 @@ tools/element_values.py; evidence in docs/format/idml-values.md.
<Language Name="$ID/ta_IN" SingleQuotes="''" DoubleQuotes='""' />
<Language Name="$ID/te_IN" SingleQuotes="''" DoubleQuotes='""' />
</Keyed>
<Keyed Tag="Color" Key="Model">
<Color Model="Spot" SpotInkAliasSpotColorReference="n" />
</Keyed>
<Keyed Tag="PastedSmoothShade" Key="ContentsType">
<PastedSmoothShade ContentsType="AxialShade" ContentsVersion="0" SpotColorList="" ContentsEncoding="Ascii64Encoding" Name="$ID/" ColorEditable="true" ColorRemovable="true" Visible="false" SwatchCreatorID="7937" />
<PastedSmoothShade ContentsType="ConstantShade" ContentsVersion="0" SpotColorList="" ContentsEncoding="Ascii64Encoding" ContentsMatrix="1 0 0 1 0 0" ColorEditable="true" ColorRemovable="true" Visible="false" SwatchCreatorID="7937" />
+35 -14
View File
@@ -60,16 +60,25 @@ fn text(n: &Name) -> String {
n.idml()
}
/// The `ObjectExportOption` of a page item (`style` false) or an object
/// style, or `None` for versions whose IDML has none: page items before
/// Whose `ObjectExportOption` is written.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Owner {
Item,
Group,
Style,
}
/// The `ObjectExportOption` of a page item, a group or an object style, or `None` for versions whose IDML has none: page items before
/// 8, object styles before 9. `options` are the item's values from chunk
/// 0x1E206; without them the values of an item without the chunk apply.
/// Codes not identified leave their attribute out.
pub(super) fn object_export_option(
version: Version,
options: Option<&ExportOptions>,
style: bool,
size_type: Option<u32>,
owner: Owner,
) -> Option<Node> {
let style = owner == Owner::Style;
let v = (version.major, version.minor);
if v < (8, 0) || style && v < (9, 0) {
return None;
@@ -125,7 +134,17 @@ pub(super) fn object_export_option(
} else if v >= (10, 1) {
for (name, value) in [
("EpubType", "$ID/"),
("SizeType", "DefaultSize"),
(
"SizeType",
// Chunk 0x1E22B; without it the default (objects.md,
// export options).
match size_type {
Some(2) => "FixedSize",
Some(3) => "RelativeToTextFlow",
Some(4) => "RelativeToTextSize",
_ => "DefaultSize",
},
),
("CustomSize", "$ID/"),
("PreserveAppearanceFromLayout", "PreserveAppearanceDefault"),
] {
@@ -140,7 +159,9 @@ pub(super) fn object_export_option(
add("EpubAriaLabelSourceType", "AutomaticARIALabel".into());
}
if v >= (21, 4) {
if !style {
// Groups and styles have no generated alternative text
// (idml-values.md, export options).
if owner == Owner::Item {
add("AIGeneratedAltText", "false".into());
add("AltTextGenerationError", "false".into());
}
@@ -197,22 +218,22 @@ mod tests {
#[test]
fn writes_attributes_by_version() {
assert!(object_export_option(version(7, 5), None, false).is_none());
assert!(object_export_option(version(8, 0), None, true).is_none());
let n = object_export_option(version(9, 2), None, true).unwrap();
assert!(object_export_option(version(7, 5), None, None, Owner::Item).is_none());
assert!(object_export_option(version(8, 0), None, None, Owner::Style).is_none());
let n = object_export_option(version(9, 2), None, None, Owner::Style).unwrap();
assert!(names(&n).contains(&"CustomImageConversion"));
assert_eq!(names(&n).last(), Some(&"UseOriginalImage"));
let n = object_export_option(version(10, 0), None, false).unwrap();
let n = object_export_option(version(10, 0), None, None, Owner::Item).unwrap();
assert!(names(&n).contains(&"CustomWidthType"));
assert!(!names(&n).contains(&"SizeType"));
let n = object_export_option(version(10, 1), None, false).unwrap();
let n = object_export_option(version(10, 1), None, None, Owner::Item).unwrap();
assert!(names(&n).contains(&"SizeType"));
assert!(!names(&n).contains(&"CustomImageConversion"));
assert!(!names(&n).contains(&"EpubAriaRole"));
let n = object_export_option(version(21, 4), None, true).unwrap();
let n = object_export_option(version(21, 4), None, None, Owner::Style).unwrap();
assert!(names(&n).contains(&"AltTextCropSyncRect"));
assert!(!names(&n).contains(&"AIGeneratedAltText"));
let n = object_export_option(version(21, 4), None, false).unwrap();
let n = object_export_option(version(21, 4), None, None, Owner::Item).unwrap();
assert!(names(&n).contains(&"AIGeneratedAltText"));
assert_eq!(n.attr("CustomAltText"), Some("$ID/"));
assert_eq!(n.attr("AltTextSourceType"), Some("SourceXMLStructure"));
@@ -230,13 +251,13 @@ mod tests {
tag_type: 1,
..ExportOptions::default()
};
let n = object_export_option(version(20, 5), Some(&o), false).unwrap();
let n = object_export_option(version(20, 5), Some(&o), None, Owner::Item).unwrap();
assert_eq!(n.attr("AltTextSourceType"), Some("SourceDecorativeImage"));
assert_eq!(n.attr("ActualTextSourceType"), Some("SourceXMPAltText"));
assert_eq!(n.attr("CustomAltText"), Some("A tree"));
assert_eq!(n.attr("ApplyTagType"), Some("TagArtifact"));
let o = ExportOptions { alt_source: 3, ..o };
let n = object_export_option(version(20, 5), Some(&o), false).unwrap();
let n = object_export_option(version(20, 5), Some(&o), None, Owner::Item).unwrap();
assert_eq!(n.attr("AltTextSourceType"), None);
}
}
+7
View File
@@ -270,6 +270,13 @@ impl Writer<'_> {
x.attr("AppliedObjectStyle", style);
}
x.attr("ItemTransform", matrix(&g.transform));
// From 21.4; -1 without the chunk (objects.md, page item settings).
if self.saved_by((21, 4)) {
x.attr(
"BeforeGroupingLayerPosition",
g.props.grouping_layer_position.unwrap_or(-1).to_string(),
);
}
// IDML has no `AllowOverrides` on placed graphics.
let props = crate::model::ItemProps {
allow_overrides: None,
+35 -1
View File
@@ -72,6 +72,12 @@ pub(super) enum Kind {
EnumString(&'static [(u32, &'static str)]),
/// A string.
String,
/// A glyph name, written as `$ID/<name>`; left out when empty.
GlyphName,
/// Dash and gap lengths, separated by spaces.
Dashes,
/// The corner adjustment of a dash list: 3 `DashesAndGaps`.
DashCorner,
/// A string, or the empty string for `Nothing`.
StringOrNothing,
/// The empty string, written as `Nothing`; other strings are left out.
@@ -112,12 +118,18 @@ impl Kind {
/// 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] = [
const BUILTIN_CJK_TABLES: [(&str, &str); 9] = [
("kHardKinsokuName", "HardKinsoku"),
("kSoftKinsokuName", "SoftKinsoku"),
("kKoreanKinsokuName", "KoreanKinsoku"),
("kSimpChineseKinsokuName", "SimplifiedChineseKinsoku"),
("kTradChineseKinsokuName", "TraditionalChineseKinsoku"),
("kMojikumiDefaultName1", "LineEndAllOneHalfEmEnum"),
(
"kMojikumiDefaultName2",
"OneEmIndentLineEndUkeOneHalfEmEnum",
),
("kMojikumiDefaultName15", "TradChineseDefault"),
("kMojikumiDefaultName16", "SimpChineseDefault"),
];
@@ -193,6 +205,14 @@ impl Writer<'_> {
.iter()
.find(|(k, _)| k == code)
.map(|(_, n)| text("object", format!("{prefix}{n}"))),
// A custom stroke style, by its UID (attributes.md, custom
// stroke styles).
Value::RefOrCode(r, CUSTOM_STROKE_TYPE) if map == STROKE_TYPES => self
.doc
.stroke_styles
.iter()
.find(|s| s.uid == *r)
.map(|s| text("object", custom_stroke_ref(s))),
_ => None,
},
Kind::StrokeType => match *v {
@@ -242,6 +262,20 @@ impl Writer<'_> {
.map(|f| text("string", self.family_names(f).0)),
},
Kind::String => v.as_string().map(|s| text("string", s)),
Kind::Dashes => match v {
Value::Dashes(d, _) => Some(text("unit", nums(d))),
_ => None,
},
Kind::DashCorner => match v {
Value::Dashes(_, 3) => Some(text("enumeration", "DashesAndGaps".into())),
_ => None,
},
Kind::GlyphName => match v {
Value::Glyph(name) if !name.is_empty() => {
Some(text("string", format!("$ID/{name}")))
}
_ => None,
},
Kind::StringOrNothing => v.as_string().map(|s| {
if s.is_empty() {
text("enumeration", "Nothing".into())
+57 -3
View File
@@ -76,15 +76,21 @@ struct Writer<'a> {
std::cell::RefCell<std::collections::HashMap<u32, std::rc::Rc<applied::StyleValues>>>,
/// The `Self` of the index topic of each page reference UID.
topics: std::collections::HashMap<u32, String>,
/// The anchored object settings of the anchored items being written,
/// innermost last: items inside them carry the settings too.
anchors: std::cell::RefCell<Vec<crate::model::AnchorSettings>>,
}
/// Attributes observed on an element path (`values::element_attrs`).
type Observed = std::rc::Rc<Vec<(String, String)>>;
impl Writer<'_> {
/// Whether the last session in the save history was one of a
/// Japanese or Chinese edition (code 0x0101); `None` when the history
/// cannot be read. Values that follow the exporting InDesign's
/// The `DOMVersion` written, as (major, minor).
pub(super) fn dom_version(&self) -> (u32, u32) {
let mut parts = self.dom.split('.').map(|p| p.parse().unwrap_or(0));
(parts.next().unwrap_or(0), parts.next().unwrap_or(0))
}
/// Whether the document's version, or the application version of its
/// last session, is at least `v`. IDML follows the exporting
/// application, which can be later than the version in the header
@@ -110,6 +116,28 @@ impl Writer<'_> {
})
}
/// The edition that saved the document, by the black name of the XMP
/// packet (`docs/format/objects.md`, saving edition).
pub(super) fn saving_edition(&self) -> Option<Edition> {
Some(match self.doc.black_name.as_deref()? {
"Black" => Edition::English,
"검정" => Edition::Korean,
"黒" => Edition::Japanese,
"黑色" => Edition::Chinese,
"Schwarz" => Edition::German,
"Noir" => Edition::French,
"Nero" => Edition::Italian,
"Zwart" => Edition::Dutch,
"Černá" => Edition::Czech,
"Preto" => Edition::Portuguese,
"Черный" => Edition::Russian,
_ => Edition::Other,
})
}
/// Whether the last session in the save history was one of a
/// Japanese or Chinese edition (code 0x0101); `None` when the history
/// cannot be read. Values that follow the exporting InDesign's
/// language depend on it (`docs/format/objects.md`, save history).
pub(super) fn japanese_session(&self) -> Option<bool> {
self.doc.last_session_code.map(|c| c == 0x0101)
@@ -215,9 +243,33 @@ pub(super) enum Edition {
Korean,
Japanese,
Chinese,
Czech,
Portuguese,
Russian,
Other,
}
impl Edition {
/// The name this edition gives an unknown document user; Chinese
/// documents show two (`objects.md`, saving edition).
pub(super) fn unknown_user(self) -> &'static [&'static str] {
match self {
Edition::English => &["Unknown User Name"],
Edition::Korean => &["알 수 없는 사용자 이름"],
Edition::Japanese => &["不明なユーザー名"],
Edition::Chinese => &["不明的使用者名稱", "未知用户名"],
Edition::German => &["Unbekannter Benutzername"],
Edition::French => &["Nom d'utilisateur inconnu"],
Edition::Italian => &["Nome ut. sconosciuto"],
Edition::Dutch => &["Onbekende gebruikersnaam"],
Edition::Czech => &["Neznámé jméno uživatele"],
Edition::Portuguese => &["Nome de usuário desconhecido"],
Edition::Russian => &["Неизвестное имя пользователя"],
Edition::Other => &[],
}
}
}
/// The `DOMVersion` of the application that saved the document last, by
/// the save history, else by the header (`idml-values.md`, DOM version).
/// Several releases keep the DOM version of an earlier one.
@@ -251,6 +303,7 @@ pub fn write(doc: &Document, name: &str, out: impl std::io::Write) -> std::io::R
page_layouts: alternate_layouts(doc).1,
page_sections: page_sections(doc),
topics: designmap::topic_refs(doc),
anchors: Default::default(),
};
let mut files: BTreeMap<String, String> = BTreeMap::new();
files.insert(
@@ -331,6 +384,7 @@ impl<'a> Writer<'a> {
page_layouts: Vec::new(),
page_sections: Vec::new(),
topics: Default::default(),
anchors: Default::default(),
}
}
}
+80 -12
View File
@@ -136,21 +136,34 @@ impl Writer<'_> {
("Space", c.space_name().into()),
("ColorValue", nums(&c.idml_values())),
("ColorOverride", c.override_name().into()),
("Name", name),
("ColorEditable", c.editable.to_string()),
("ColorRemovable", c.removable.to_string()),
("Visible", c.visible.to_string()),
]);
// Values that follow the model (idml-values.md, keyed values).
let keyed: Vec<(String, String)> = c
.model_name()
.and_then(|m| values::keyed("Color", m))
.map(|n| n.attrs.into_iter().filter(|(k, _)| k != "Model").collect())
.unwrap_or_default();
let mut attrs: Vec<(String, String)> = attrs
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.chain(keyed)
.collect();
attrs.extend([
("Name".to_string(), name),
("ColorEditable".to_string(), c.editable.to_string()),
("ColorRemovable".to_string(), c.removable.to_string()),
("Visible".to_string(), c.visible.to_string()),
]);
if let Some((space, values)) = c.idml_alternate() {
attrs.push(("AlternateSpace", space.into()));
attrs.push(("AlternateColorValue", nums(&values)));
attrs.push(("AlternateSpace".to_string(), space.into()));
attrs.push(("AlternateColorValue".to_string(), nums(&values)));
}
if let Some(id) = c.creator {
attrs.push(("SwatchCreatorID", id.to_string()));
attrs.push(("SwatchCreatorID".to_string(), id.to_string()));
}
if self.doc.version.major >= 16 {
let hsb = c.space == crate::model::color::Space::Hsb;
attrs.push(("ConvertToHsb", hsb.to_string()));
attrs.push(("ConvertToHsb".to_string(), hsb.to_string()));
}
x.start("Color");
for (k, v) in &attrs {
@@ -405,6 +418,27 @@ impl Writer<'_> {
],
);
}
// Custom stroke styles, in UID order (attributes.md, custom
// stroke styles).
for st in &self.doc.stroke_styles {
if st.dashed {
x.start("DashedStrokeStyle")
.attr("Self", custom_stroke_ref(st))
.attr("DashArray", nums(&st.values));
if st.corner == 3 {
x.attr("StrokeCornerAdjustment", "DashesAndGaps");
}
if let Some(cap) = end_cap(st.cap) {
x.attr("EndCap", cap);
}
} else {
let stripes: Vec<f64> = st.values.iter().map(|v| v * 100.0).collect();
x.start("StripedStrokeStyle")
.attr("Self", custom_stroke_ref(st))
.attr("StripeArray", nums(&stripes));
}
x.attr("Name", &st.name).end();
}
x.end();
x.finish()
}
@@ -775,8 +809,37 @@ impl Writer<'_> {
/// entries of a document without index options. Both follow the
/// edition that made the document (preferences.md, index options).
fn index_title(&self) -> Option<(Option<&'static str>, &'static str)> {
// The title follows the edition that saved the document, where
// its black name shows it (objects.md, saving edition).
let saved = self.saving_edition().and_then(|e| {
Some(match e {
Edition::English | Edition::German | Edition::French | Edition::Dutch => "Index",
Edition::Korean => "색인",
Edition::Japanese | Edition::Chinese => "索引",
Edition::Italian => "Indice",
Edition::Czech => "Rejstřík",
Edition::Portuguese => "Índice",
Edition::Russian => "Указатель",
Edition::Other => return None,
})
});
let edition = match self.edition() {
Some(e) => e,
None => {
let e = self.saving_edition()?;
let separator = if e == Edition::Japanese { "、" } else { "; " };
return Some((saved, separator));
}
};
let (title, separator) = self.assigned_index_title(edition);
Some((saved.or(title), separator))
}
/// The index title and separator by the edition of the assignment
/// name (preferences.md, index options).
fn assigned_index_title(&self, edition: Edition) -> (Option<&'static str>, &'static str) {
let japanese_session = self.japanese_session() == Some(true);
Some(match self.edition()? {
match edition {
Edition::Japanese => (Some("索引"), "、"),
Edition::Chinese => (Some("索引"), "; "),
Edition::Korean => (Some("색인"), "; "),
@@ -785,8 +848,8 @@ impl Writer<'_> {
(Some("Index"), "; ")
}
Edition::Italian => (Some("Indice"), "; "),
Edition::Other => (None, "; "),
})
_ => (None, "; "),
}
}
pub(super) fn preferences(&self) -> String {
@@ -938,7 +1001,12 @@ impl Writer<'_> {
}
if let Some(a) = &prefs.item_defaults {
let i = ours_of(&mut ours, "PageItemDefault");
let values = self.item_default_values(a);
let mut values = self.item_default_values(a);
let stroke = values
.iter()
.find(|(k, _)| *k == "StrokeType")
.map(|(_, v)| v.clone());
values.retain(|(k, _)| dash_written(k, stroke.as_deref()));
ours[i]
.attrs
.extend(values.into_iter().map(|(k, v)| (k.to_string(), v)));
+225 -14
View File
@@ -88,6 +88,8 @@ const STYLE_COMPARED: &[&str] = &[
"StrokeType",
"StrokeAlignment",
"StrokeTint",
"StrokeDashAndGap",
"StrokeCornerAdjustment",
"GapColor",
"GapTint",
"EndCap",
@@ -334,9 +336,11 @@ impl Writer<'_> {
attrs.push(("MinimumWidthForAutoSizing", num(width)));
attrs.push(("UseNoLineBreaksForAutoSizing", no_breaks.to_string()));
}
if let Some(v) = p.ignore_wrap {
attrs.push(("IgnoreWrap", v.to_string()));
}
// Without the chunk, `false` (objects.md, text frame preferences).
attrs.push(("IgnoreWrap", p.ignore_wrap.unwrap_or(false).to_string()));
// 0 on every frame of the samples; IDML writes it by the baseline
// category rule below (objects.md, text frame preferences).
attrs.push(("MinimumFirstBaselineOffset", "0".into()));
// Values every IDML of the version has where it writes them; they
// also say from which version the column rule and footnote
// settings exist (idml-values.md). Footnote values from 13.1.
@@ -388,13 +392,24 @@ impl Writer<'_> {
|id: u32| style.is_none_or(|s| !s.enabled.as_ref().is_some_and(|on| on.contains(&id)));
let footnote_options = self.frame_footnote_options(p, style, off(0xADCA));
let baseline = self.frame_baseline_grid(p, style, off(0xADC8));
// Before DOM 11 the insets follow the rule of the general
// attributes: written where they differ from the style's, in any
// order, or the style turns the category off (objects.md, text
// frame preferences).
let sorted = |mut v: [f64; 4]| {
v.sort_by(f64::total_cmp);
v
};
let insets = major >= 11
|| off(0x1B93E)
|| style.is_some_and(|s| sorted(s.insets.unwrap_or([0.0; 4])) != sorted(p.inset));
// Before DOM 11 IDML gives a frame without values no element.
if !attrs.is_empty() || major >= 11 {
if !attrs.is_empty() || insets {
x.start("TextFramePreference");
for (k, val) in attrs {
x.attr(k, val);
}
if major >= 11 {
if insets {
let [top, left, bottom, right] = p.inset;
let item = |v: f64| Node {
tag: "ListItem".into(),
@@ -531,10 +546,20 @@ impl Writer<'_> {
return;
};
x.start("TextWrapPreference");
if wrap.is_none_or(|w| w.flags == 1) {
x.attr("Inverse", "false")
.attr("ApplyToMasterPageOnly", "false")
.attr("TextWrapSide", "BothSides");
// `Inverse` is false on every item of the samples
// (objects.md, text wrap).
x.attr("Inverse", "false");
match wrap {
None => {
x.attr("ApplyToMasterPageOnly", "false")
.attr("TextWrapSide", "BothSides");
}
Some(w) => {
x.attr("ApplyToMasterPageOnly", (w.master_flag == 0).to_string());
if let Some(side) = text_wrap_side(w.side) {
x.attr("TextWrapSide", side);
}
}
}
x.attr("TextWrapMode", mode);
x.start("Properties")
@@ -682,7 +707,19 @@ impl Writer<'_> {
} else {
self.item_attr_values(&item.attrs)
};
// The stroke type in effect decides the dash attributes.
let stroke_type = (tag != "Group")
.then(|| {
self.values_in_effect(item)
.into_iter()
.find(|(n, ..)| *n == "StrokeType")
.map(|(_, v, _)| v)
})
.flatten();
for (name, v) in own {
if !dash_written(name, stroke_type.as_deref()) {
continue;
}
// Fill, stroke and corner values equal to the object style's
// are left out (attributes.md, page item attributes).
let same = STYLE_COMPARED.contains(&name)
@@ -710,7 +747,9 @@ impl Writer<'_> {
rest.values.retain(|(id, _)| item.attrs.get(*id).is_none());
for (name, v) in self.item_attr_values(&rest) {
// IDML writes no corner attributes for EPS text.
if tag == "EPSText" && name.contains("Corner") {
if tag == "EPSText" && name.contains("Corner")
|| !dash_written(name, stroke_type.as_deref())
{
continue;
}
let write = match &applied {
@@ -724,6 +763,29 @@ impl Writer<'_> {
}
}
}
// A group stores none of these values; IDML gives it the value
// all its children have in effect (attributes.md, groups).
if tag == "Group" {
let shared = self.shared_values(item);
for name in STYLE_COMPARED {
let Some((v, full)) = shared
.iter()
.find(|(n, ..)| n == name)
.map(|(_, v, f)| (v, *f))
else {
continue;
};
let write = forced(name)
|| full
|| applied
.as_ref()
.and_then(|a| a.item(name))
.is_none_or(|s| !applied::same_value(s, v));
if write {
x.attr(name, v.clone());
}
}
}
if tag != "Group" && !form {
self.item_overprint(x, item, applied.as_deref(), &forced);
}
@@ -743,6 +805,13 @@ impl Writer<'_> {
x.attr("ItemLayer", uref(Some(layer)));
}
x.attr("ItemTransform", matrix(&item.transform));
// From 21.4; -1 without the chunk (objects.md, page item settings).
if self.saved_by((21, 4)) {
x.attr(
"BeforeGroupingLayerPosition",
item.props.grouping_layer_position.unwrap_or(-1).to_string(),
);
}
self.item_settings(x, item, nested);
if let ItemKind::Form(f) = &item.kind {
Self::form_attrs(x, f);
@@ -820,8 +889,16 @@ impl Writer<'_> {
// EPS text and form fields have no export options (objects.md,
// EPS text and form fields).
if !matches!(item.kind, ItemKind::EpsText(_) | ItemKind::Form(_))
&& let Some(n) =
export::object_export_option(self.doc.version, item.export.as_ref(), false)
&& let Some(n) = export::object_export_option(
self.doc.version,
item.export.as_ref(),
item.props.export_size_type,
if tag == "Group" {
export::Owner::Group
} else {
export::Owner::Item
},
)
{
n.write(x);
}
@@ -830,7 +907,17 @@ impl Writer<'_> {
// them where the style turns the category off (objects.md,
// anchored object settings).
let unknown_style = form && item.object_style.is_none();
if let Some(d) = item.anchor.as_ref().filter(|_| !unknown_style) {
// An item inside an anchored item has the anchor's settings
// (objects.md, anchored object settings).
let inherited = (nested && item.anchor.is_none())
.then(|| self.anchors.borrow().last().cloned())
.flatten();
if let Some(d) = item
.anchor
.as_ref()
.or(inherited.as_ref())
.filter(|_| !unknown_style)
{
let style = item
.object_style
.and_then(|u| self.doc.object_styles.get(&u));
@@ -883,9 +970,15 @@ impl Writer<'_> {
item.uid
));
}
if let Some(a) = &item.anchor {
self.anchors.borrow_mut().push(a.clone());
}
for child in &item.children {
self.page_item(x, child, true, &item.transform.then(outer));
}
if item.anchor.is_some() {
self.anchors.borrow_mut().pop();
}
if let ItemKind::Form(f) = &item.kind {
self.form_states(x, item, f, &item.transform.then(outer));
}
@@ -895,6 +988,122 @@ impl Writer<'_> {
x.end();
}
/// The fill, stroke and corner values (`STYLE_COMPARED`) a page item
/// has in effect, with the stored-100 tint flag: its own value, else
/// the document's base list value where IDML writes it, else its
/// object style's. A group has the value all its children share; a
/// form field has none (attributes.md, groups).
fn values_in_effect(&self, item: &PageItem) -> Vec<(&'static str, String, bool)> {
match item.kind {
ItemKind::Group => return self.shared_values(item),
ItemKind::Form(_) => return Vec::new(),
_ => {}
}
let applied = item.object_style.and_then(|u| self.style_values(u));
let on = match (&applied, item.object_style) {
(Some(a), Some(u))
if !self
.doc
.object_styles
.get(&u)
.is_some_and(Self::is_root_object_style) =>
{
a.enabled.as_deref()
}
_ => None,
};
let own = self.item_attr_values(&item.attrs);
let base = match &self.doc.prefs.item_base {
Some(b) if applied.is_some() || item.object_style.is_none() => {
let mut rest = b.clone();
rest.values.retain(|(id, _)| item.attrs.get(*id).is_none());
self.item_attr_values(&rest)
}
_ => Vec::new(),
};
let mut out: Vec<(&'static str, String, bool)> = Vec::new();
for &name in STYLE_COMPARED {
if matches!(item.kind, ItemKind::EpsText(_)) && name.contains("Corner") {
continue;
}
// StrokeType comes before the dash attributes in the list.
let stroke = out
.iter()
.find(|(n, ..)| *n == "StrokeType")
.map(|(_, v, _)| v.as_str());
if !dash_written(name, stroke) {
continue;
}
let style = applied.as_ref().and_then(|a| a.item(name));
if let Some((_, v)) = own.iter().find(|(n, _)| *n == name) {
let id = match name {
"StrokeTint" => Some(0x6E66),
"GapTint" => Some(0x6E8A),
_ => None,
};
let full =
id.is_some_and(|id| item.attrs.get(id).and_then(Value::as_f64) == Some(100.0));
out.push((name, v.clone(), full));
continue;
}
if let Some((_, b)) = base.iter().find(|(n, _)| *n == name) {
let forced = on.is_some_and(|on| category_off(name, on));
let written = applied.is_none()
|| style.is_some_and(|s| forced || !applied::same_value(s, b));
if written {
out.push((name, b.clone(), false));
continue;
}
}
if let Some(s) = style {
out.push((name, s.to_string(), false));
}
}
out
}
/// The values of `values_in_effect` that all children of `group`
/// have. EPS text has no corner values and is left out for those.
fn shared_values(&self, group: &PageItem) -> Vec<(&'static str, String, bool)> {
let children: Vec<_> = group
.children
.iter()
.map(|c| {
(
matches!(c.kind, ItemKind::EpsText(_)),
self.values_in_effect(c),
)
})
.collect();
let mut out = Vec::new();
for &name in STYLE_COMPARED {
let mut shared: Option<(String, bool)> = None;
let mut all = true;
let mut any = false;
for (eps, values) in &children {
if *eps && name.contains("Corner") {
continue;
}
any = true;
match values.iter().find(|(n, ..)| *n == name) {
Some((_, v, full)) => match &mut shared {
None => shared = Some((v.clone(), *full)),
Some((s, f)) if applied::same_value(s, v) => *f &= *full,
Some(_) => all = false,
},
None => all = false,
}
}
if all
&& any
&& let Some((v, full)) = shared
{
out.push((name, v, full));
}
}
out
}
/// The attributes of a form field that its attribute list holds
/// (objects.md, form fields).
fn form_attrs(x: &mut Xml, f: &Form) {
@@ -1521,12 +1730,14 @@ mod tests {
let wrap = TextWrap {
mode: wrap_mode::BOUNDING_BOX,
offsets: [1.0, 2.0, 3.0, 4.0],
flags: 1,
master_flag: 0,
side: 5,
};
let mut x = Xml::new();
Writer::text_wrap_preference(&mut x, Some(&wrap), None);
let out = x.finish();
assert!(out.contains("TextWrapMode=\"BoundingBoxTextWrap\""));
assert!(out.contains("ApplyToMasterPageOnly=\"true\" TextWrapSide=\"LargestArea\""));
assert!(out.contains("<TextWrapOffset Top=\"2\" Left=\"1\" Bottom=\"4\" Right=\"3\" />"));
}
+1 -1
View File
@@ -813,7 +813,7 @@ impl Writer<'_> {
'\u{17}' => {}
'\u{18}' if story.text_variables.contains_key(&pos) => {
flush(x, &mut buf);
self.variable_instance(x, &story.text_variables[&pos]);
self.variable_instance(x, &story.text_variables[&pos], story.uid);
}
c => buf.push(c),
}
+26 -4
View File
@@ -430,7 +430,9 @@ impl Writer<'_> {
// The export options of the version (idml-values.md) in place of
// those of the value files.
node.children.retain(|c| c.tag != "ObjectExportOption");
if let Some(e) = export::object_export_option(self.doc.version, None, true) {
if let Some(e) =
export::object_export_option(self.doc.version, None, None, export::Owner::Style)
{
node.children.insert(0, e);
}
// The transform values the style sets, where IDML has the element
@@ -448,6 +450,25 @@ impl Writer<'_> {
if !transform.is_empty() && node.child("TransformAttributeOption").is_some() {
node.set(&["TransformAttributeOption"], transform);
}
// Flex paddings and gaps; without the chunk 12 and 20 (objects.md,
// object style settings).
if node.child("FlexLayoutAttributeOption").is_some() {
let v = os
.flex_spacing
.unwrap_or([12.0, 12.0, 12.0, 12.0, 20.0, 20.0]);
let names = [
"FlexPaddingTop",
"FlexPaddingRight",
"FlexPaddingBottom",
"FlexPaddingLeft",
"FlexGapRow",
"FlexGapColumn",
];
node.set(
&["FlexLayoutAttributeOption"],
names.into_iter().zip(v).map(|(n, v)| (n, num(v))).collect(),
);
}
let mut attrs = self.item_attr_values(&os.attrs);
for (id, name) in [
(0x551E, "GradientFillAngle"),
@@ -486,7 +507,8 @@ impl Writer<'_> {
attrs.push((name, value.into()));
}
match os.paragraph_style {
Some(0) => attrs.push(("AppliedParagraphStyle", "n".into())),
// No chunk 0x1B946 is no style too (objects.md, object styles).
Some(0) | None => attrs.push(("AppliedParagraphStyle", "n".into())),
Some(p) if self.doc.styles.contains_key(&p) => {
attrs.push(("AppliedParagraphStyle", self.style_ref(Some(p), true)))
}
@@ -751,10 +773,10 @@ impl Writer<'_> {
_ => {}
}
node.set(&["StoryPreference"], story);
// The u32 at 40 of the wrap chunk: 0 for `ApplyToMasterPageOnly`;
// The u16 at 40 of the wrap chunk: 0 for `ApplyToMasterPageOnly`;
// without the chunk, false (objects.md, object style settings).
if node.child("TextWrapPreference").is_some() {
match os.text_wrap.as_ref().map(|w| w.flags) {
match os.text_wrap.as_ref().map(|w| w.master_flag) {
Some(1) | None => {
node.set(
&["TextWrapPreference"],
+23 -2
View File
@@ -124,6 +124,13 @@ const ATTRS: &[(u32, &str, &str, &str, Kind)] = &[
"EffectColor",
Kind::Swatch,
),
(
KNOCKED_OUT,
"TransparencySetting",
"DropShadowSetting",
"KnockedOut",
Kind::Bool,
),
(
0x1084D,
"TransparencySetting",
@@ -340,6 +347,18 @@ const COLOR_APPLIED: &[(&str, u32)] = &[("InnerShadowSetting", 0x1084D)];
/// colour).
const DROP_SHADOW_COLOR: u32 = 0x10837;
/// The drop shadow's `KnockedOut`. An item or object style chain that
/// does not store it has `true` (`docs/format/transparency.md`, drop
/// shadow knockout).
const KNOCKED_OUT: u32 = 0x1EB6F;
/// The value of an attribute that an item or style chain does not store,
/// where the samples show one.
fn unstored(id: u32) -> Option<&'static Value> {
const TRUE: Value = Value::Enum(1);
(id == KNOCKED_OUT).then_some(&TRUE)
}
/// An effect element: name, attributes and opacity stops.
type Effect = (&'static str, Vec<(&'static str, String)>, Vec<Stop>);
@@ -405,7 +424,9 @@ pub(super) fn write(
{
continue;
}
let Some(v) = attrs.get(id) else { continue };
let Some(v) = attrs.get(id).or_else(|| style.and_then(|_| unstored(id))) else {
continue;
};
if let Kind::Range(lo, hi) = kind
&& let Some(f) = v.as_f64()
&& !(lo..=hi).contains(&f)
@@ -416,7 +437,7 @@ pub(super) fn write(
match w.value_text(kind, v) {
Some(t) => {
let style_text = style
.and_then(|s| s.transparency(id))
.and_then(|s| s.transparency(id).or_else(|| unstored(id)))
.and_then(|sv| w.value_text(kind, sv));
let same = style_text.as_ref().is_some_and(|st| *st == t);
let unshown = id == DROP_SHADOW_COLOR
+3 -2
View File
@@ -219,9 +219,10 @@ fn convert_with(
db.set_recorder(r);
}
let mut doc = model::Reader::new(&db).document(container.header.version)?;
// A damaged XMP packet only loses the time zone of link times.
// A damaged XMP packet only loses the time zone of link times and
// the black name.
if let Ok(Some(packet)) = container.xmp() {
doc.xmp_dates = model::xmp::dates(packet);
doc.read_xmp(packet);
}
let mut warnings = doc.warnings.clone();
warnings.extend(idml::write(&doc, name, out)?);
+60
View File
@@ -51,6 +51,11 @@ pub enum Value {
kind: u32,
value: u32,
},
/// Dash and gap lengths of a stroke and the corner adjustment code
/// (page item attribute 0x5A35).
Dashes(Vec<f64>, u16),
/// A custom glyph: its name (the glyph ID that follows is not used).
Glyph(String),
/// Opacity gradient stops: location (0–1), absolute position of the
/// midpoint to the next stop (0–1), opacity in percent.
Stops(Vec<[f64; 3]>),
@@ -357,6 +362,8 @@ enum Layout {
Words,
/// u32 reference (0 for a built-in) and u32 code.
RefOrCode,
/// u16 length, that many bytes of a glyph name, u32 glyph ID.
Glyph,
}
fn text_layout(id: u32) -> Option<Layout> {
@@ -374,6 +381,7 @@ fn text_layout(id: u32) -> Option<Layout> {
0x1BBA => Layout::GrepStyles,
0x1BBB => Layout::LineStyles,
0x1A406 => Layout::BulletChar,
0x1B5E => Layout::Glyph,
// Stroke types of cell edges, table borders, rows and columns
// (tables.md).
0xB64D | 0xB64E | 0xB64F | 0xB650 | 0xB655 | 0xB658 | 0xB65B | 0xB65E | 0xB688 | 0xB689
@@ -433,6 +441,16 @@ fn decode_text(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
(|| Ok::<_, Error>(Value::RefOrCode(c.u32()?, c.u32()?)))().ok()
}
Layout::RefOrCode => None,
Layout::Glyph => (|| {
let n = c.u16().ok()? as usize;
let name = c.bytes(n).ok()?.to_vec();
c.u32().ok()?;
if c.remaining() != 0 {
return None;
}
String::from_utf8(name).ok()
})()
.map(Value::Glyph),
};
value.unwrap_or_else(|| Value::Other(t, data.to_vec()))
}
@@ -521,8 +539,21 @@ fn style_items(layout: Layout, c: &mut Cursor) -> Option<StyleItems> {
/// u32 count, then three f64 per stop. See `docs/format/transparency.md`.
pub const OPACITY_STOPS: [u32; 3] = [0x1EB8C, 0x1EB95, 0x1EB9E];
/// The page item attribute of a stroke's dashes and gaps: 8 bytes (0 in
/// every sample), u32 count, that many f64, u16 corner adjustment. See
/// `docs/format/attributes.md`, dashes.
pub const DASHES: u32 = 0x5A35;
fn decode(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
let f = |o: usize| enc.f64_at(data, o);
if id == DASHES
&& let Some(n) = enc.u32_at(data, 8).map(|n| n as usize)
&& data.len().checked_sub(14) == n.checked_mul(8)
&& let Some(v) = (0..n).map(|i| f(12 + 8 * i)).collect::<Option<Vec<_>>>()
&& let Some(corner) = enc.u16_at(data, 12 + 8 * n)
{
return Value::Dashes(v, corner);
}
if OPACITY_STOPS.contains(&id)
&& let Some(n) = enc.u32_at(data, 0).map(|n| n as usize)
&& n > 0
@@ -579,6 +610,35 @@ mod tests {
assert_eq!(a.get(0x6E65), Some(&Value::Double(0.25)));
}
#[test]
fn decodes_dashes_and_glyph_names() {
let enc = Encoding::default();
// 8 bytes, count 2, two f64, corner code 3.
let mut d = vec![0; 8];
d.extend_from_slice(&2u32.to_le_bytes());
d.extend_from_slice(&4.0f64.to_le_bytes());
d.extend_from_slice(&2.0f64.to_le_bytes());
d.extend_from_slice(&3u16.to_le_bytes());
assert_eq!(
decode(enc, DASHES, 0x5A36, &d),
Value::Dashes(vec![4.0, 2.0], 3)
);
// A count that does not fit the length is not a dash list.
d[8] = 3;
assert!(matches!(decode(enc, DASHES, 0x5A36, &d), Value::Other(..)));
let mut g = 5u16.to_le_bytes().to_vec();
g.extend_from_slice(b"a.alt");
g.extend_from_slice(&7u32.to_le_bytes());
assert_eq!(
decode_text(enc, 0x1B5E, 0x1B26, &g),
Value::Glyph("a.alt".into())
);
assert!(matches!(
decode_text(enc, 0x1B5E, 0x1B26, &g[..6]),
Value::Other(..)
));
}
#[test]
fn parses_a_stroke_type_code() {
// 0x6E6E: reference 0, code 0x5A39, then the 6-byte trailer value.
+15 -7
View File
@@ -169,19 +169,27 @@ impl Tint {
/// IDML `Name`: the base colour's name and the tint value, with the
/// black swatch written as `[Black]`.
pub fn idml_name(&self, base: &Color) -> String {
let name = if base.color_override == 2 {
format!("[{}]", base.name)
if base.color_override == 2 {
self.named(&format!("[{}]", base.name))
} else {
base.name.clone()
};
format!("{name} {}%", crate::idml::num(self.value))
self.named(&base.name)
}
}
/// The name of this tint of a colour written `base`.
pub fn named(&self, base: &str) -> String {
format!("{base} {}%", crate::idml::num(self.value))
}
pub fn reference(&self, base: &Color) -> String {
Self::reference_of(&self.idml_name(base))
}
/// The `Tint/…` reference of a tint named `name`.
pub fn reference_of(name: &str) -> String {
format!(
"Tint/{}",
self.idml_name(base)
.replace('%', "%25")
name.replace('%', "%25")
.replace(':', "%3a")
.replace('\r', "%0d")
)
+88 -4
View File
@@ -38,8 +38,8 @@ pub struct Document {
/// The numbering lists, the default list first.
pub numbering_lists: Vec<NumberingList>,
/// Index sort groups (preferences chunk 0x1307E), in order: name,
/// include flag and header variant.
pub index_groups: Vec<(String, bool, u16)>,
/// include flag and the name of the header variant.
pub index_groups: Vec<(String, bool, Option<String>)>,
/// The index (class 0x13004) and its topics.
pub index: Option<super::index::Index>,
/// The constant shade the document lists (the class 0x5533 object of
@@ -62,6 +62,8 @@ pub struct Document {
pub stories: Vec<Story>,
pub styles: BTreeMap<u32, Style>,
pub toc_styles: Vec<TocStyle>,
/// Custom stroke styles, in UID order.
pub stroke_styles: Vec<StrokeStyle>,
pub colors: Vec<Color>,
/// Mixed inks and mixed ink groups, in UID order.
pub mixed_inks: Vec<MixedInk>,
@@ -113,6 +115,62 @@ pub struct Document {
/// The dates of the XMP packet that have a UTC offset; link times are
/// written with their offsets (`objects.md`, link times).
pub xmp_dates: Vec<super::xmp::XmpDate>,
/// The black swatch's name in the XMP packet: the language of the
/// edition that saved the document (`objects.md`, saving edition).
pub black_name: Option<String>,
}
/// The stories of the text frames anchored in `story`, in text order
/// (nested items included).
fn anchored_stories(story: &Story) -> Vec<u32> {
fn walk(items: &[PageItem], out: &mut Vec<u32>) {
for i in items {
if let ItemKind::TextFrame { story: Some(s), .. } = i.kind {
out.push(s);
}
walk(&i.children, out);
}
}
let mut out = Vec::new();
for items in story.anchors.values() {
walk(items, &mut out);
}
out
}
impl Document {
/// Read the dates and the black name of the XMP packet. IDML names a
/// tint of black with the black name (`objects.md`, saving edition).
pub fn read_xmp(&mut self, packet: &[u8]) {
self.xmp_dates = super::xmp::dates(packet);
let Some(black) = self.colors.iter().find(|c| c.reference() == "Color/Black") else {
return;
};
let values = black.idml_values();
let others: Vec<&str> = self
.colors
.iter()
.filter(|c| c.uid != black.uid)
.map(|c| c.name.as_str())
.collect();
let colorants = super::xmp::colorants(packet);
self.black_name =
super::xmp::black_name(&colorants, (black.space_name(), &values), &others);
let (Some(name), uid, bracket) = (&self.black_name, black.uid, black.color_override == 2)
else {
return;
};
if !bracket {
return;
}
for (t, reference, idml) in &mut self.tints {
if t.base == uid {
*idml = t.named(&format!("[{name}]"));
*reference = Tint::reference_of(idml);
self.swatches.insert(t.uid, reference.clone());
}
}
}
}
/// An XML tag: its name and colour (red, green, blue).
@@ -175,6 +233,30 @@ impl<'a> Reader<'a> {
.transpose()?;
let (spreads, master_spreads) = self.document_spreads()?;
let mut stories = self.document_stories()?;
let xml_story = self.xml_story()?;
// Stories of text frames anchored in the XML backing story are not
// in the document's list; IDML writes them after the listed ones
// (objects.md, stories).
if let Some(x) = &xml_story {
let mut known: std::collections::HashSet<u32> = stories.iter().map(|s| s.uid).collect();
known.insert(x.uid);
let mut next = anchored_stories(x);
next.reverse();
while let Some(uid) = next.pop() {
if !known.insert(uid) || !matches!(self.class(uid), Some(class::STORY)) {
continue;
}
match self.story(uid) {
Ok(s) => {
let mut more = anchored_stories(&s);
more.reverse();
next.extend(more);
stories.push(s);
}
Err(e) => self.warn(format!("story {uid} left out: {e}")),
}
}
}
let mut objects = self.class_objects()?;
// Cell spans depend on insets that cells inherit from styles.
let table_styles = table::TableStyles::new(&objects.cell_styles, &objects.table_styles);
@@ -183,7 +265,6 @@ impl<'a> Reader<'a> {
t.resolve_spans(&table_styles);
}
}
let xml_story = self.xml_story()?;
for story in &mut stories {
story.orientation = self.story_orientation(story.uid);
}
@@ -195,7 +276,8 @@ impl<'a> Reader<'a> {
prune_style_groups(&mut objects.style_groups, |m| self.warn(m));
let preferences = self.document_preferences()?;
let prefs = self.prefs(version)?;
let toc_styles = self.toc_styles();
let toc_styles = self.toc_styles(version);
let stroke_styles = self.stroke_styles();
let named_grids = self.named_grids();
let index_groups = self.index_groups();
let index = self.index().unwrap_or_else(|e| {
@@ -293,6 +375,7 @@ impl<'a> Reader<'a> {
languages: objects.languages,
language_list: objects.language_list,
toc_styles,
stroke_styles,
named_grids,
index_groups,
index,
@@ -331,6 +414,7 @@ impl<'a> Reader<'a> {
xml_tags: objects.xml_tags,
xml,
xmp_dates: Vec::new(),
black_name: None,
// Last, so that it holds every warning of the model.
warnings: self.warnings.borrow().clone(),
})
+16
View File
@@ -36,6 +36,9 @@ pub mod class {
pub const FONT_FAMILY: u32 = 0x3E03;
pub const LANGUAGE: u32 = 0x2D07;
pub const TOC_STYLE: u32 = 0x11605;
/// Custom stroke styles (`attributes.md`, custom stroke styles).
pub const DASHED_STROKE_STYLE: u32 = 0x5A43;
pub const STRIPED_STROKE_STYLE: u32 = 0xB016;
pub const NAMED_GRID: u32 = 0xCD12;
pub const ASSIGNMENT: u32 = 0x1BE01;
pub const SMOOTH_SHADE: u32 = 0x5533;
@@ -176,6 +179,8 @@ pub mod chunk {
pub const GROUP_TRANSFORM: u32 = 0x40D;
/// u16 1 for a frame meant for a graphic.
pub const ITEM_CONTENT: u32 = 0x1623;
/// The item's layer position before it was grouped: i32 at 4.
pub const ITEM_GROUPING_LAYER: u32 = 0x324;
pub const ITEM_PATHS: u32 = 0x162B;
pub const ITEM_HIERARCHY: u32 = 0x15B;
/// u32: 1 when a master page item cannot be overridden.
@@ -193,6 +198,13 @@ pub mod chunk {
pub const STORY_OPTICAL_MARGIN: u32 = 0x2EE;
/// The TOC style of a table of contents.
pub const TOC_STYLE_OF: u32 = 0x11613;
/// Name of a dashed and of a striped stroke style: flag byte, string.
pub const DASHED_STROKE_NAME: u32 = 0x5A48;
pub const STRIPED_STROKE_NAME: u32 = 0xB023;
/// Dashed stroke style: u32 count, f64 lengths, u16 corner, u32 cap.
pub const DASHED_STROKE: u32 = 0x5A4F;
/// Striped stroke style: u32 count, pairs of f64 (start, width).
pub const STRIPED_STROKE: u32 = 0xB002;
pub const TOC_STYLE: u32 = 0x11605;
pub const NAMED_GRID: u32 = 0xCD28;
/// The named grid of a story or object style: u16 1, then the named
@@ -242,6 +254,8 @@ pub mod chunk {
pub const ITEM_LAYOUT_CONSTRAINTS: u32 = 0x22228;
/// Export options: alternative text, actual text, tagging.
pub const ITEM_EXPORT: u32 = 0x1E206;
/// Export size settings: a list of keys and string values.
pub const ITEM_EXPORT_SIZE: u32 = 0x1E22B;
pub const ROOT_GROUP_KIND: u32 = 0x28C2;
pub const SECTION_INFO: u32 = 0x4C02;
pub const DOCUMENT_PREFERENCES: u32 = 0x533;
@@ -307,6 +321,8 @@ pub mod chunk {
pub const OBJECT_STYLE_STORY: u32 = 0x285B;
pub const OBJECT_STYLE_DIRECTION: u32 = 0x50F28;
pub const OBJECT_STYLE_WRAP: u32 = 0x3776;
/// Flex layout settings (78 bytes): six f64 at 30, paddings and gaps.
pub const OBJECT_STYLE_FLEX: u32 = 0x1E244;
pub const OBJECT_STYLE_CONTOUR: u32 = 0x3777;
pub const OBJECT_STYLE_ENABLED: u32 = 0x1B92E;
pub const OBJECT_STYLE_PARAGRAPH_STYLE: u32 = 0x1B946;
+83 -8
View File
@@ -246,6 +246,12 @@ pub struct ItemProps {
/// Chunk 0x1623 is 1: a frame for a graphic (`ContentType`
/// `GraphicType` without a graphic).
pub graphic_frame: bool,
/// The i32 at 4 of chunk 0x324: the layer position before grouping
/// (`objects.md`, page item settings).
pub grouping_layer_position: Option<i32>,
/// The value of key `CustomSizeType` of chunk 0x1E22B (`objects.md`,
/// export options).
pub export_size_type: Option<u32>,
}
/// A page item name: a built-in key or a name given by the user.
@@ -262,10 +268,33 @@ pub struct TextWrap {
pub mode: u32,
/// The four offsets: left, top, right, bottom.
pub offsets: [f64; 4],
/// The u32 at offset 40; 1 in every sample whose IDML has
/// `Inverse="false"`, `ApplyToMasterPageOnly="false"` and
/// `TextWrapSide="BothSides"`.
pub flags: u32,
/// The u16 at offset 40: 0 for `ApplyToMasterPageOnly`, 1 otherwise.
pub master_flag: u16,
/// The u16 at offset 42: the `TextWrapSide` code (`TEXT_WRAP_SIDES`
/// of the writer).
pub side: u16,
}
/// A list of keys with string values (chunk 0x1E22B): u32 count; per
/// entry a u32-counted key in text segments, a flag byte, two bytes, a u16
/// value count and the values, each a u8 length, a u8 and that many bytes.
fn key_values(c: &mut Cursor) -> Result<Vec<(String, Vec<String>)>, Error> {
let n = c.u32()?;
let mut out = Vec::new();
for _ in 0..n {
let len = c.u32()? as usize;
let key = c.segments(len)?;
c.skip(3)?;
let count = c.u16()?;
let mut values = Vec::new();
for _ in 0..count {
let m = c.u8()? as usize;
c.u8()?;
values.push(String::from_utf8_lossy(c.bytes(m)?).into_owned());
}
out.push((key, values));
}
Ok(out)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -748,6 +777,20 @@ impl<'a> Reader<'a> {
graphic_frame: self
.chunk(uid, chunk::ITEM_CONTENT)?
.is_some_and(|d| d.len() >= 2 && self.cursor(&d).u16().ok() == Some(1)),
grouping_layer_position: self
.chunk(uid, chunk::ITEM_GROUPING_LAYER)?
.and_then(|d| self.enc().i32_at(&d, 4)),
export_size_type: match self.chunk(uid, chunk::ITEM_EXPORT_SIZE)? {
Some(d) => key_values(&mut self.cursor(&d)).ok().and_then(|kv| {
kv.into_iter()
.find(|(k, _)| k == "CustomSizeType")?
.1
.first()?
.parse()
.ok()
}),
None => None,
},
})
}
@@ -778,7 +821,8 @@ impl<'a> Reader<'a> {
}
/// Text wrap of a page item or graphic, from chunk 0x3703: u32 mode,
/// u32 contour path object, four f64 offsets, u32 flags.
/// u32 contour path object, four f64 offsets, u16 master page flag,
/// u16 side.
pub(super) fn text_wrap(&self, uid: u32) -> Result<Option<TextWrap>, Error> {
self.wrap_chunk(uid, chunk::TEXT_WRAP)
}
@@ -795,7 +839,8 @@ impl<'a> Reader<'a> {
let mode = c.u32()?;
c.skip(4)?;
let offsets = [c.f64()?, c.f64()?, c.f64()?, c.f64()?];
let flags = c.u32()?;
let master_flag = c.u16()?;
let side = c.u16()?;
if !matches!(
mode,
wrap_mode::NONE | wrap_mode::JUMP_OBJECT | wrap_mode::BOUNDING_BOX | wrap_mode::CONTOUR
@@ -807,7 +852,8 @@ impl<'a> Reader<'a> {
Ok(Some(TextWrap {
mode,
offsets,
flags,
master_flag,
side,
}))
}
@@ -1207,7 +1253,9 @@ impl<'a> Reader<'a> {
Some((link, data)) => (Some(link), data),
None => {
let id = match kind {
GraphicKind::Image => Some(chunk::IMAGE_DATA),
// EPS graphics name their data as images do
// (objects.md, embedded graphics).
GraphicKind::Image | GraphicKind::Eps => Some(chunk::IMAGE_DATA),
GraphicKind::Pdf => Some(chunk::PDF_DATA),
_ => None,
};
@@ -1780,3 +1828,30 @@ mod eps_text_tests {
assert!(eps_text_data(enc, &d[..d.len() - 1]).is_err());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::object::Encoding;
#[test]
fn reads_export_size_keys() {
let enc = Encoding::default();
let mut d = enc.u32_bytes(2).to_vec();
for (key, values) in [("CustomSizeType", &["2"][..]), ("CustomSizeValue", &[][..])] {
d.extend(enc.u32_bytes(key.len() as u32));
d.extend(enc.u16_bytes(0x4000 | key.len() as u16));
d.extend(key.bytes());
d.extend([0, 2, 3]);
d.extend(enc.u16_bytes(values.len() as u16));
for v in values {
d.extend([v.len() as u8, 0x40]);
d.extend(v.bytes());
}
}
let kv = key_values(&mut enc.cursor(&d)).unwrap();
assert_eq!(kv[0], ("CustomSizeType".to_string(), vec!["2".to_string()]));
assert!(kv[1].1.is_empty());
assert!(key_values(&mut enc.cursor(&d[..d.len() - 3])).is_err());
}
}
+80 -2
View File
@@ -1191,6 +1191,10 @@ impl Reader<'_> {
return Ok(Prefs::default());
};
let get = |id: u32| self.chunk(uid, id);
// The code of the last session of the save history (document UID
// 1): 0x0101 for a Japanese or other CJK edition. Values without a
// chunk follow it (preferences.md, values of the exporting edition).
let cjk = self.last_session(1).map(|(code, _)| code == 0x0101);
let mut set = |element: &'static str, name: &'static str, value: String| {
values.push(PrefValue {
element,
@@ -1351,7 +1355,9 @@ impl Reader<'_> {
set(element, name, v);
}
}
// Flags whose documents without the chunk do not have one value.
// The highlight flags are `false` without their chunk, except in
// a few documents that no stored value separates (preferences.md,
// flags in their own chunks).
for (id, element, name) in [
(
id::HIGHLIGHT_HJ_VIOLATIONS,
@@ -1368,6 +1374,13 @@ impl Reader<'_> {
"TextPreference",
"HighlightSubstitutedGlyphs",
),
] {
if let Some(v) = flag(id, false)? {
set(element, name, v);
}
}
// Flags whose documents without the chunk do not have one value.
for (id, element, name) in [
(
id::SNAP_TO_LAYOUT_GRID,
"CjkGridPreference",
@@ -1440,6 +1453,21 @@ impl Reader<'_> {
None => {
set("StoryPreference", "OpticalMarginAlignment", "false".into());
set("StoryPreference", "FrameType", "TextFrameType".into());
// 13 Q where text sizes are in Q, 12 pt otherwise, as
// IDML writes them (preferences.md, story settings).
let q = get(id::VIEW)?
.filter(|d| d.len() == 56)
.and_then(|d| self.enc().u32_at(&d, 12))
.map(|u| unit(u) == Some("Q"));
match q {
Some(true) => set(
"StoryPreference",
"OpticalMarginSize",
"9.2125984251969".into(),
),
Some(false) => set("StoryPreference", "OpticalMarginSize", "12".into()),
None => {}
}
}
}
// Text wrap of new page items: u32 mode, four f64 offsets (left,
@@ -1631,12 +1659,38 @@ impl Reader<'_> {
let columns = match get(id::COLUMNS)? {
Some(d) if d.len() >= 12 => Some((self.cursor(&d).u32()?, self.cursor(&d[4..]).f64()?)),
Some(_) => None,
None => Some((1, 12.0)),
// 5 mm after a CJK session, 12 pt otherwise.
None => Some((
1,
if cjk == Some(true) {
14.173228346456694
} else {
12.0
},
)),
};
if let Some((count, gutter)) = columns {
set("MarginPreference", "ColumnCount", count.to_string());
set("MarginPreference", "ColumnGutter", num(gutter));
}
// Column direction: u16 at 12 of the column chunk; without it,
// the story orientation of new frames (preferences.md, columns).
let direction = match get(id::COLUMNS)? {
Some(d) if d.len() >= 14 => self.enc().u16_at(&d, 12).map(u32::from),
Some(_) => None,
None => get(id::TEXT)?
.and_then(|d| d.get(116).copied())
.map(u32::from),
};
let direction = match direction {
Some(0) => Some("Horizontal"),
Some(1) => Some("Vertical"),
_ => None,
};
if let Some(dir) = direction {
set("DocumentPreference", "ColumnDirection", dir.into());
set("MarginPreference", "ColumnDirection", dir.into());
}
let anchor = get(id::ANCHOR)?;
// Pasteboard: f64 horizontal and vertical margins.
@@ -1810,6 +1864,19 @@ impl Reader<'_> {
for pv in v {
set(pv.element, pv.name, pv.value);
}
// Stored Japanese marks are `Default` unless the last
// session was a CJK edition's (preferences.md, print
// settings).
if cjk == Some(false) {
for (_, name, value) in &mut p {
if *name == "MarkType"
&& let PrefProp::Text(_, v) = value
&& v == "JMarkWithCircle"
{
*v = "Default".into();
}
}
}
props.extend(p);
print_records.extend(r);
}
@@ -2119,6 +2186,15 @@ impl Reader<'_> {
// and Publish Online export).
if major >= 8 {
let v = (major, version.minor);
// Every IDML of DOM 8 and 9 has it (preferences.md, EPUB,
// HTML and Publish Online export).
if major <= 9 {
set(
"EPubExportPreference",
"ViewDocumentAfterExport",
"true".into(),
);
}
match get(id::EPUB)? {
Some(d) => match epub_export(self.enc(), &d) {
Some(e) => {
@@ -2304,6 +2380,8 @@ impl Reader<'_> {
(f(8)?, u(16)?, f(20)?, u(28)?)
}
Some(_) => (f64::NAN, 0, f64::NAN, 0),
// 20 mm and 10 after a CJK session, 72 pt and 8 otherwise.
None if cjk == Some(true) => (56.69291338582678, 10, 56.69291338582678, 10),
None => (72.0, 8, 72.0, 8),
};
if !h.is_nan() {
+17 -10
View File
@@ -374,7 +374,7 @@ impl<'a> Reader<'a> {
/// name, include flag and header variant of each group, in stored
/// order. Empty when the chunk does not parse to its end. See
/// `docs/format/objects.md`, index sort options.
pub(super) fn index_groups(&self) -> Vec<(String, bool, u16)> {
pub(super) fn index_groups(&self) -> Vec<(String, bool, Option<String>)> {
let Some(&(uid, _)) = self
.db
.classes()
@@ -612,10 +612,13 @@ fn counted_string(c: &mut crate::object::Cursor) -> Result<String, Error> {
}
/// The groups of chunk 0x1307E (`objects.md`, index sort options): for
/// each, a flagged name, u8 include, u8, u16 header variant, u16 and its
/// header variants with their sections. Returns name, include and
/// variant of each group.
fn index_groups(c: &mut crate::object::Cursor) -> Result<Vec<(String, bool, u16)>, Error> {
/// each, a flagged name, u8 include, u8, u16 header variant (an index into
/// the variant list), u16 and its header variants with their sections.
/// Returns name, include and the name of the chosen variant (the first
/// string of its record) of each group.
fn index_groups(
c: &mut crate::object::Cursor,
) -> Result<Vec<(String, bool, Option<String>)>, Error> {
let count = c.u32()?;
let mut out = Vec::new();
for _ in 0..count {
@@ -625,11 +628,15 @@ fn index_groups(c: &mut crate::object::Cursor) -> Result<Vec<(String, bool, u16)
c.u8()?;
let variant = c.u16()?;
c.u16()?;
for _ in 0..c.u32()? {
for _ in 0..2 {
c.u8()?;
c.string()?;
let mut chosen = None;
for i in 0..c.u32()? {
c.u8()?;
let variant_name = c.string()?;
if i == u32::from(variant) {
chosen = Some(variant_name);
}
c.u8()?;
c.string()?;
counted_string(c)?;
c.skip(2)?;
for _ in 0..c.u32()? {
@@ -640,7 +647,7 @@ fn index_groups(c: &mut crate::object::Cursor) -> Result<Vec<(String, bool, u16)
c.u16()?;
}
}
out.push((name, include, variant));
out.push((name, include, chosen));
}
if c.remaining() != 0 {
return Err(Error::Corrupt(format!("{} bytes left", c.remaining())));
+5 -3
View File
@@ -151,7 +151,8 @@ pub struct Spread {
pub guides: Vec<Guide>,
/// Chunk 0x1A8: `None` without it.
pub shuffle: Option<u16>,
/// The two resolutions in chunk 0x10833, when it is there.
/// The line art and text and the gradient and mesh resolutions in
/// chunk 0x10833, when it is there.
pub flattener_resolution: Option<[f64; 2]>,
/// Master spreads: chunk 0x140D.
pub show_master_items: Option<u16>,
@@ -468,8 +469,9 @@ impl<'a> Reader<'a> {
}
}
let flattener_resolution = match self.chunk(uid, chunk::SPREAD_FLATTENER)? {
Some(d) => match (self.enc().f64_at(&d, 20), self.enc().f64_at(&d, 28)) {
(Some(a), Some(b)) => Some([a, b]),
// f64 at 28 line art and text, at 20 gradient and mesh.
Some(d) => match (self.enc().f64_at(&d, 28), self.enc().f64_at(&d, 20)) {
(Some(line_art), Some(gradient)) => Some([line_art, gradient]),
_ => None,
},
None => None,
+194 -2
View File
@@ -114,6 +114,43 @@ pub struct TocStyle {
/// make anchor and at 6 remove forced line breaks, where the chunk
/// has them.
pub flags: Vec<u16>,
/// The entries (`objects.md`, table of contents styles); empty where
/// they do not parse.
pub entries: Vec<TocEntry>,
}
/// A custom stroke style. See `docs/format/attributes.md`, custom stroke
/// styles.
#[derive(Debug, Clone, PartialEq)]
pub struct StrokeStyle {
pub uid: u32,
/// Dashed (class 0x5A43) or striped (class 0xB016).
pub dashed: bool,
pub name: String,
/// Dashed: dash and gap lengths in points. Striped: start and width of
/// each stripe, as fractions of the stroke weight.
pub values: Vec<f64>,
/// Dashed: corner adjustment code and end cap code.
pub corner: u16,
pub cap: u32,
}
/// An entry of a table of contents style: a paragraph style the table
/// lists and how. See `docs/format/objects.md`, table of contents styles.
#[derive(Debug, Clone, PartialEq)]
pub struct TocEntry {
/// The paragraph style's name, and whether it is a built-in key.
pub name: String,
pub builtin: bool,
/// Paragraph style UID; 0 for the same style.
pub format_style: u32,
pub level: u32,
/// 0 after the entry, 1 before it, 2 none.
pub page_number_position: u16,
/// Character style UIDs; 0 for the same style.
pub page_number_style: u32,
pub separator: String,
pub separator_style: u32,
}
/// A style group: a root group of styles, or a named group in it.
@@ -137,6 +174,9 @@ pub struct ObjectStyle {
pub fitting: Attrs,
/// Page item attributes (chunk 0x1B92B): fill, stroke, corners.
pub attrs: Attrs,
/// Flex layout paddings (top, right, bottom, left) and gaps (row,
/// column), from chunk 0x1E244; `None` without it.
pub flex_spacing: Option<[f64; 6]>,
/// Transparency attributes (chunk 0x1B92C), the IDs of page items.
pub transparency: Attrs,
/// Text frame settings (chunk 0x1B924).
@@ -304,7 +344,7 @@ impl<'a> Reader<'a> {
}
/// The table of contents styles, in UID order.
pub(super) fn toc_styles(&self) -> Vec<TocStyle> {
pub(super) fn toc_styles(&self, version: crate::header::Version) -> Vec<TocStyle> {
let mut out = Vec::new();
for &(uid, cls) in self.db.classes() {
if cls != class::TOC_STYLE {
@@ -325,10 +365,25 @@ impl<'a> Reader<'a> {
let title = c.string()?;
c.flag()?;
c.string()?;
// Two u16 before version 9, three before 13, four from 13,
// then the entries.
let count = match version.major {
..=8 => 2,
9..=12 => 3,
_ => 4,
};
let mut flags = Vec::new();
while flags.len() < 4 && c.remaining() >= 2 {
while flags.len() < count && c.remaining() >= 2 {
flags.push(c.u16()?);
}
let entries = if c.remaining() >= 2 {
toc_entries(&mut c).unwrap_or_else(|_| {
self.warn(format!("TOC style {uid}: entries left out"));
Vec::new()
})
} else {
Vec::new()
};
Ok(Some(TocStyle {
uid,
name,
@@ -338,6 +393,7 @@ impl<'a> Reader<'a> {
include_book_documents,
create_bookmarks,
flags,
entries,
}))
})();
match read {
@@ -351,7 +407,100 @@ impl<'a> Reader<'a> {
}
}
/// The entries of a TOC style chunk after its fields: u16 count, then per
/// entry the style name (flag byte, string), a document path (flag byte,
/// string), u32 format style, u32 level, u16 page number position, u32
/// page number style, u32-counted separator text, u32 separator style,
/// u16, a u32-counted text and a u16. The chunk must end after them.
fn toc_entries(c: &mut crate::object::Cursor) -> Result<Vec<TocEntry>, Error> {
let n = c.u16()?;
let mut out = Vec::new();
for _ in 0..n {
let builtin = c.flag()? == 1;
let name = c.string()?;
c.flag()?;
c.string()?;
let format_style = c.u32()?;
let level = c.u32()?;
let page_number_position = c.u16()?;
let page_number_style = c.u32()?;
let len = c.u32()? as usize;
let separator = c.segments(len)?;
let separator_style = c.u32()?;
c.u16()?;
let len = c.u32()? as usize;
c.segments(len)?;
c.u16()?;
out.push(TocEntry {
name,
builtin,
format_style,
level,
page_number_position,
page_number_style,
separator,
separator_style,
});
}
if c.remaining() != 0 {
return Err(Error::Corrupt("TOC entries do not fill the chunk".into()));
}
Ok(out)
}
impl<'a> Reader<'a> {
/// The custom stroke styles, in UID order. A style whose chunks do not
/// have the lengths of the documented layout is left out with a
/// warning.
pub(super) fn stroke_styles(&self) -> Vec<StrokeStyle> {
let mut out = Vec::new();
for &(uid, cls) in self.db.classes() {
let dashed = match cls {
class::DASHED_STROKE_STYLE => true,
class::STRIPED_STROKE_STYLE => false,
_ => continue,
};
let read = (|| -> Result<Option<StrokeStyle>, Error> {
let (name_id, data_id) = if dashed {
(chunk::DASHED_STROKE_NAME, chunk::DASHED_STROKE)
} else {
(chunk::STRIPED_STROKE_NAME, chunk::STRIPED_STROKE)
};
let (Some(n), Some(d)) = (self.chunk(uid, name_id)?, self.chunk(uid, data_id)?)
else {
return Ok(None);
};
let mut c = self.cursor(&n);
c.flag()?;
let name = c.string()?;
let mut c = self.cursor(&d);
let count = c.u32()? as usize;
let (values, extra) = if dashed { (count, 6) } else { (2 * count, 0) };
if values.checked_mul(8).and_then(|v| v.checked_add(4 + extra)) != Some(d.len()) {
return Ok(None);
}
let values = (0..values)
.map(|_| c.f64())
.collect::<Result<Vec<_>, _>>()?;
let (corner, cap) = if dashed { (c.u16()?, c.u32()?) } else { (0, 0) };
Ok(Some(StrokeStyle {
uid,
dashed,
name,
values,
corner,
cap,
}))
})();
match read {
Ok(Some(s)) => out.push(s),
Ok(None) | Err(_) => self.warn(format!("stroke style {uid} left out")),
}
}
out.sort_by_key(|s| s.uid);
out
}
/// A root style group (the root of paragraph and character, object,
/// cell or table styles): its kind (chunk 0x28C2) and children.
pub(super) fn style_root_group(&self, uid: u32) -> Result<StyleGroup, Error> {
@@ -491,6 +640,13 @@ impl<'a> Reader<'a> {
_ => None,
},
text_wrap: self.wrap_chunk(uid, chunk::OBJECT_STYLE_WRAP)?,
flex_spacing: match self.chunk(uid, chunk::OBJECT_STYLE_FLEX)? {
Some(d) if d.len() == 78 => {
let f = |i: usize| self.enc().f64_at(&d, 30 + 8 * i);
(|| Some([f(0)?, f(1)?, f(2)?, f(3)?, f(4)?, f(5)?]))()
}
_ => None,
},
contour_type: u32_chunk(chunk::OBJECT_STYLE_CONTOUR)?,
enabled: match self.chunk(uid, chunk::OBJECT_STYLE_ENABLED)? {
Some(d) => Some(self.cursor(&d).u32_list()?),
@@ -691,6 +847,42 @@ mod tests {
d
}
#[test]
fn reads_toc_entries() {
use crate::database::synthetic::flagged_string;
let be = Encoding::new(
crate::header::ByteOrder::Big,
crate::header::Version { major: 4, minor: 0 },
);
for enc in [Encoding::default(), be] {
let mut d = enc.u16_bytes(1).to_vec();
d.extend(flagged_string(enc, 1, "Heading"));
d.extend(flagged_string(enc, 2, ""));
for v in [0x51u32, 2] {
d.extend(enc.u32_bytes(v));
}
d.extend(enc.u16_bytes(2));
d.extend(enc.u32_bytes(0));
d.extend(export_string(enc, "\t"));
d.extend(enc.u32_bytes(0x60));
d.extend(enc.u16_bytes(0));
d.extend(export_string(enc, "; "));
d.extend(enc.u16_bytes(1));
let e = toc_entries(&mut enc.cursor(&d)).unwrap();
assert_eq!(e.len(), 1);
assert_eq!((e[0].name.as_str(), e[0].builtin), ("Heading", true));
assert_eq!((e[0].format_style, e[0].level), (0x51, 2));
assert_eq!(e[0].page_number_position, 2);
assert_eq!(
(e[0].separator.as_str(), e[0].separator_style),
("\t", 0x60)
);
// Bytes after the entries: not read.
d.push(0);
assert!(toc_entries(&mut enc.cursor(&d)).is_err());
}
}
#[test]
fn reads_export_tag_maps_and_flags() {
let enc = Encoding::default();
+34
View File
@@ -40,6 +40,20 @@ pub struct TextVariable {
/// The fields not identified hold the values every corpus sample of
/// this type has, so the IDML settings are those of the samples.
pub as_in_samples: bool,
/// The settings after the type code, where they parse to the end of
/// the chunk.
pub settings: Option<Settings>,
}
/// The settings of a definition (`text-variables.md`, settings): three
/// u32, then the text before and after the value.
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
pub a: u32,
pub b: u32,
pub c: u32,
pub before: String,
pub after: String,
}
impl TextVariable {
@@ -69,6 +83,25 @@ fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
let name = counted(&mut c)?;
let text = counted(&mut c)?;
let kind = c.u32()?;
let settings = {
let mut s = c.clone();
(|| -> Result<Settings, Error> {
let (a, b, c3) = (s.u32()?, s.u32()?, s.u32()?);
let before = counted(&mut s)?;
let after = counted(&mut s)?;
if s.remaining() != 0 {
return Err(Error::Corrupt("text variable settings".into()));
}
Ok(Settings {
a,
b,
c: c3,
before,
after,
})
})()
.ok()
};
let rest = c.bytes(c.remaining())?;
let zero = |r: &[u8]| r.iter().all(|&b| b == 0);
let mut style = None;
@@ -93,6 +126,7 @@ fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
text,
style: style.filter(|&s| s != 0),
as_in_samples,
settings,
})
}
+121 -1
View File
@@ -1,6 +1,7 @@
//! Dates of the document's XMP packet, which give the time zone offsets
//! that IDML link times are written in (`docs/format/objects.md`, link
//! times).
//! times), and the name of its black swatch, which shows the language of
//! the edition that saved it (`docs/format/objects.md`, saving edition).
/// An XMP date with a UTC offset: the instant (seconds since 1970 UTC)
/// and the offset in seconds.
@@ -44,6 +45,105 @@ pub fn dates(packet: &[u8]) -> Vec<XmpDate> {
out
}
/// A colour of the packet's `xmpTPg:Colorants` list.
#[derive(Debug, Clone, PartialEq)]
pub struct Colorant {
pub name: String,
/// `CMYK`, `RGB` or `LAB`.
pub mode: String,
/// `PROCESS` or `SPOT`, in either case.
pub kind: String,
/// The colorant is a tint (`xmpG:tint`).
pub tint: bool,
/// Cyan, magenta, yellow, black in percent, or red, green, blue
/// (0–255), or L, a, b; as many as the mode has.
pub values: Vec<f64>,
}
/// The value of property `name` in `item`, in element (`<name>v</name>`)
/// or attribute (`name="v"`) form, with the XML entities resolved.
fn property(item: &str, name: &str) -> Option<String> {
let raw = if let Some(i) = item.find(&format!("<{name}>")) {
let rest = &item[i + name.len() + 2..];
&rest[..rest.find('<')?]
} else {
let i = item.find(&format!("{name}=\""))?;
let rest = &item[i + name.len() + 2..];
&rest[..rest.find('"')?]
};
Some(
raw.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&amp;", "&"),
)
}
/// The colours of the `xmpTPg:Colorants` list of `packet`. Items without
/// a name or a mode are left out.
pub fn colorants(packet: &[u8]) -> Vec<Colorant> {
let text = String::from_utf8_lossy(packet);
let Some(start) = text.find("<xmpTPg:Colorants") else {
return Vec::new();
};
let list = &text[start..];
let list = &list[..list.find("</xmpTPg:Colorants").unwrap_or(list.len())];
let mut out = Vec::new();
for item in list.split("<rdf:li").skip(1) {
let (Some(name), Some(mode)) = (
property(item, "xmpG:swatchName"),
property(item, "xmpG:mode"),
) else {
continue;
};
let components: &[&str] = match mode.as_str() {
"CMYK" => &["cyan", "magenta", "yellow", "black"],
"RGB" => &["red", "green", "blue"],
"LAB" => &["L", "A", "B"],
_ => &[],
};
let values = components
.iter()
.filter_map(|c| property(item, &format!("xmpG:{c}"))?.trim().parse().ok())
.collect();
out.push(Colorant {
name,
mode,
kind: property(item, "xmpG:type").unwrap_or_default(),
tint: property(item, "xmpG:tint").is_some(),
values,
});
}
out
}
/// The name the packet gives the black swatch: the one colorant that is
/// not a tint, is a process colour, has the mode and values of `black`
/// (as IDML writes them: CMYK in percent, RGB 0–255) and whose name no
/// other colour of the document (`others`) has. `None` if there is no
/// such colorant or more than one.
pub fn black_name(
colorants: &[Colorant],
black: (&str, &[f64]),
others: &[&str],
) -> Option<String> {
let (mode, values) = black;
let mut found = colorants.iter().filter(|c| {
!c.tint
&& c.kind.eq_ignore_ascii_case("process")
&& c.mode == mode
&& c.values.len() == values.len()
&& c.values
.iter()
.zip(values)
.all(|(a, b)| (a - b).abs() < 1e-3)
&& !others.contains(&c.name.as_str())
});
let first = found.next()?;
found.next().is_none().then(|| first.name.clone())
}
/// A date `YYYY-MM-DDTHH:MM[:SS[.fff]]` followed by `Z` or `±HH:MM`.
fn parse(s: &str) -> Option<XmpDate> {
let b = s.as_bytes();
@@ -136,6 +236,26 @@ mod tests {
assert_eq!(d[2].offset, 0);
}
#[test]
fn finds_the_black_name() {
let packet = r#"<xmpTPg:Colorants><rdf:Seq>
<rdf:li rdf:parseType="Resource"><xmpG:swatchName>Schwarz</xmpG:swatchName><xmpG:mode>CMYK</xmpG:mode><xmpG:type>PROCESS</xmpG:type><xmpG:cyan>0</xmpG:cyan><xmpG:magenta>0</xmpG:magenta><xmpG:yellow>0</xmpG:yellow><xmpG:black>100</xmpG:black></rdf:li>
<rdf:li xmpG:swatchName="Schwarz" xmpG:mode="CMYK" xmpG:type="PROCESS" xmpG:tint="40" xmpG:cyan="0" xmpG:magenta="0" xmpG:yellow="0" xmpG:black="100"/>
<rdf:li xmpG:swatchName="Ink &amp; More" xmpG:mode="CMYK" xmpG:type="PROCESS" xmpG:cyan="0" xmpG:magenta="0" xmpG:yellow="0" xmpG:black="100"/>
</rdf:Seq></xmpTPg:Colorants>"#;
let c = colorants(packet.as_bytes());
assert_eq!(c.len(), 3);
assert!(c[1].tint);
assert_eq!(c[2].name, "Ink & More");
let black = ("CMYK", &[0.0, 0.0, 0.0, 100.0][..]);
// Two candidates: ambiguous.
assert_eq!(black_name(&c, black, &[]), None);
assert_eq!(
black_name(&c, black, &["Ink & More"]).as_deref(),
Some("Schwarz")
);
}
#[test]
fn converts_between_days_and_dates() {
assert_eq!(days_from_civil(1970, 1, 1), 0);
+2 -1
View File
@@ -79,7 +79,7 @@ ELEMENTS = [
"Polygon/InCopyExportOption", "Image/ClippingPathSettings",
"PDF/ClippingPathSettings", "EPS/ClippingPathSettings", "Ink",
"Button", "CheckBox", "RadioButton", "TextBox", "ComboBox", "SignatureField",
"MultiStateObject",
"MultiStateObject", "Section",
]
# The top-level elements of Resources/Preferences.xml, as paths
# "Preferences/<tag>". tools/root_values.py collects them from the IDML
@@ -115,6 +115,7 @@ LISTS = ["TrapPreset"]
# MIN_KEYED_FILES files.
KEYED = {
"Language": ("Name", ["SingleQuotes", "DoubleQuotes"]),
"Color": ("Model", ["SpotInkAliasSpotColorReference"]),
"PastedSmoothShade": ("ContentsType", [
"ContentsVersion", "SpotColorList", "ContentsEncoding", "ContentsMatrix",
"Name", "ColorEditable", "ColorRemovable", "Visible", "SwatchCreatorID"]),