diff --git a/docs/format/idml-values.md b/docs/format/idml-values.md index aa1d06c..19c61fc 100644 --- a/docs/format/idml-values.md +++ b/docs/format/idml-values.md @@ -141,10 +141,31 @@ All 496 `Image` elements in the 240 corpus IDML files (119 files) have `ClippingPathSettings` with `InvertPath="false"`, `IncludeInsideEdges="false"`, `RestrictToFrame="false"` and `AppliedPathName="$ID/"`, and `ImageIOPreference` with -`AllowAutoEmbedding="true"` and `AlphaChannelName="$ID/"`. The 386 PDF -and 49 EPS graphics with `ClippingPathSettings` have the same four -values. The converter writes them (`objects.md`, clipping path -settings). +`AllowAutoEmbedding="true"`. The 386 PDF and 49 EPS graphics with +`ClippingPathSettings` have the same four values. The converter writes +them (`objects.md`, clipping path settings). + +Over the 5,131 graphics of the trustworthy pairs, every graphic has +`LocalDisplaySetting="Default"`; every image (3,607) +`ImageRenderingIntent="UseColorSettings"`; every PDF and EPS (1,339) +`GrayVectorPolicy="IgnoreAll"`; every SVG (146) `UseSVGAs="EmbedCode"`. +From DOM 21 every image, PDF and SVG has `FlexItemWidthMode="FlexFixed"` +and `FlexItemHeightMode="FlexFixed"` (81 of 81), and SVG graphics from +21.2 have `IsMathMLObject="false"` (4 of 4). The constant values of +graphic layers are in `objects.md` (graphic layers). The converter +writes all of these. + +## Links + +These `Link` values are the same in all 4,699 links of the trustworthy +pairs, and the converter writes them on every link: `AssetURL="$ID/"`, +`AssetID="$ID/"`, `LinkClassID="35906"` (0x8C42, the class of links), +`LinkClientID="257"` (the u32 at offset 4 of chunk 0x8C9B is 0x101 in +every link), `LinkObjectModified="false"`, `CanEmbed="true"`, +`CanUnembed="true"`, `CanPackage="true"`, `ImportPolicy="NoAutoImport"` +and `ExportPolicy="NoAutoExport"`. `RenditionData="Actual"` is on every +link from DOM 13 on (3,043 of 3,043) and on none before (1,656 of +1,656); the converter writes it from version 13. ## Object styles other than the root diff --git a/docs/format/objects.md b/docs/format/objects.md index 678e448..6790f2e 100644 --- a/docs/format/objects.md +++ b/docs/format/objects.md @@ -810,11 +810,21 @@ identified field. All 496 images, 386 PDF and 49 EPS graphics with the element in the corpus IDML files have these values, and the converter writes them (`idml-values.md`). -**ImageIOPreference.** Chunk 0x8C39 of an image, u16 at 0: -`ApplyPhotoshopClippingPath` (1 true, 0 false); 235 of 235 images (293 -of 293 with the older-version pairs, 11 of them false). -`AllowAutoEmbedding="true"` and `AlphaChannelName="$ID/"` are in all 496 -images of the corpus IDML files and are written from that observation. +**ImageIOPreference.** Chunk 0x1714 of an image: + +| Offset | Size | IDML `ImageIOPreference` | +|---|---|---| +| 0 | u32 | 72 in all 1,300 images with the chunk | +| 4 | u16 | `ApplyPhotoshopClippingPath`: 1 `true`, 0 `false` | +| 6 | u16 | 1 in all (`AllowAutoEmbedding="true"` in all IDML) | +| 8 | flagged string | `AlphaChannelName` (an empty key is `$ID/`) | + +Without the chunk, IDML has `ApplyPhotoshopClippingPath="true"` and +`AlphaChannelName="$ID/"`. Evidence: 3,607 of 3,607 images of the +trustworthy pairs for both attributes (14 `false`, 92 `$ID/kNoneName`, +2 plain names). Chunk 0x8C39 (u16 at 0), which looked like the clipping +flag in fewer samples, gives the wrong value in 6 images and is missing +in 549. `AllowAutoEmbedding="true"` is written from observation. ## Placed graphics @@ -827,11 +837,36 @@ of a frame (in its 0x15B list) and share these chunks: | 0x1633 | Four f64: `GraphicBounds` left, top, right, bottom | | 0x8CBC | u32, u32, u32 link UID | -**Links (0x8C42).** Chunk 0x8C9B: u32 0, u32, u32 link resource UID, u32, -u32 graphic UID, fields, then the import stamp as a u32 length and text -segments, then two 8-byte timestamps. **Link resources (0x8C41)**: chunk -0x8C92 is a flag byte, u32 length, then the URI as bytes -(`LinkResourceURI`; 335/340 match, the rest were relinked after export). +**Links (0x8C42).** Chunk 0x8C9B: + +| Offset | Size | Contents | IDML `Link` | +|---|---|---|---| +| 0 | 4 | 0 in all links | | +| 4 | 4 | 0x101 in all links | (`LinkClientID="257"`) | +| 8 | 4 | UID of the link resource (class 0x8C41) | | +| 12 | 4 | 1 or 0 | `LinkResourceModified`: 1 `false`, 0 `true` | +| 16 | 4 | UID of the graphic | | +| 20 | 2 | 1 or 0 | `ShowInUI`: 1 `true`, 0 `false` | +| 22 | 6 | three u16, 1 in all links | | +| 28 | 4 | 0 in all links | | +| 32 | 4 + text | import stamp: u32 length, then text segments | `LinkImportStamp` | +| then | 8 | modification time of the file (FILETIME) | `LinkImportModificationTime` | +| then | 8 | time the file was placed or updated (FILETIME) | `LinkImportTime` | + +A FILETIME here is the count of 100 ns intervals since 1601-01-01 UTC, +stored as two u32: the high half first, then the low half (each in the +file's byte order). Evidence: the stamp text is `file `, and +`` equals the first time value in 4,686 of 4,686 links with a stamp. +A link with an empty stamp (length 0) has neither `LinkImportStamp` nor +`LinkImportModificationTime` in IDML, but has `LinkImportTime` (13 of +13). + +Chunk 0x1B6 of a link (u32, on 59 links) is `PDFIdentifier`, which IDML +writes from DOM 21 on; links without the chunk have `PDFIdentifier="0"` +(81 of 81 DOM 21 links). + +**Link resources (0x8C41)**: chunk 0x8C92 is a flag byte, u32 length, +then the URI as bytes (`LinkResourceURI`). After the URI, chunk 0x8C92 continues: @@ -841,6 +876,63 @@ After the URI, chunk 0x8C92 continues: | 4 | u32 0 or 1, not identified | | 8 | u32 0, 2 or 3 | | 12 | u32 UID of a raw data object (class 0x129), or 0 | +| 16 | stamp: u32 length, text segments (as in the link) | +| then | modification time (FILETIME, as in the link) | +| then | file size: u32 high half, u32 low half; `LinkResourceSize` is `~` in lower-case hexadecimal without leading zeros (`0~42ebd`) | +| then | u8, 1 in all resources | +| then | in-object string: the format name; `LinkResourceFormat` is `$ID/` and the name, and the graphic's `ImageTypeName` is the same | + +Evidence over the 4,699 links of the trustworthy pairs (4,697 with a +resource object), with the converter's output compared with the +reference: + +| IDML | Equal | +|---|---| +| `LinkResourceModified` | all 4,699 (5 with 0 = `true`) | +| `ShowInUI` | all 4,699 (2 with 0 = `false`) | +| `LinkImportStamp` | 4,105 of 4,105 links with the same URI in the INDD and the IDML | +| `LinkResourceSize`, `LinkResourceFormat` | 4,118 of 4,118 links with the same URI | +| `PDFIdentifier` | 81 of 81 | + +The resource's stamp differs from the link's in 184 links; IDML then has +the link's stamp and the resource's size. All 63,470 link chunks and +their resource chunks in the distinct little-endian corpus files parse +with this layout. + +**Links resolved to another file at export.** In 19 trustworthy +documents, 529 links differ from the INDD: the IDML names the same file +in another folder (344) or a newer file (185). InDesign wrote the +location and state of the file it found on the exporting computer; the +INDD keeps the state of its last save. These values cannot come from the +INDD, and `compare.py` leaves such links out (`docs/measurement.md`). + +**Link times.** IDML writes `LinkImportTime` and +`LinkImportModificationTime` as `YYYY-MM-DDTHH:MM:SS` (seconds +truncated) in the local time of the computer that exported the IDML: + +- IDML equals the INDD's UTC time plus a whole number of hours in 9,009 + of 9,385 time values; the other 376 belong to links resolved to + another file at export or have no stamp. +- The offset differs between documents (−8 to +13 hours) and, in 71 of + 284 documents, between links of the same document in step with the + season (for example 1 and 2 hours, −5 and −4, +10 and +11), with the + larger offset on summer dates of that hemisphere: the daylight-saving + rule of the exporting computer's time zone, which the INDD does not + store. + +The converter estimates the offset from the dates of the XMP packet that +have a UTC offset (`xmp:CreateDate`, `xmp:MetadataDate`, +`xmp:ModifyDate`, every `stEvt:when`): it takes the offset of the date +nearest to the link time in day of the year (difference of the days of +the year, not wrapping at the year end; ties: the latest date), and UTC +when there is no such date. Over the trustworthy pairs this gives +`LinkImportTime` for 3,886 of 4,446 links and +`LinkImportModificationTime` for 3,316 of 4,434 (links with the same URI: +3,748 of 4,118 and 3,019 of 4,105). Other rules give less: UTC about +155 values of 9,385, the offset of `xmp:ModifyDate` 6,488, the same rule +with the day difference wrapping at the year end 3,840 import times. +`compare.py` leaves both times out of the value coverage +(`docs/measurement.md`). **Embedded links.** A link is embedded (`StoredState="Embedded"`) when its resource names a raw data object at offset 12. That object holds the @@ -858,6 +950,132 @@ Evidence: base64-decoded `Contents` of the IDML graphic (JPEG, PNG, PDF, EPS and SVG files, 2 KB to 11 MB). +**Settings shared with page items.** Images, PDF, EPS and SVG graphics +carry the page item setting chunks (page item settings, above): 0x2C10 +name, 0x2C32 visibility, 0x21D4E, 0x21D50 and 0x21D53 change counts, +0x1424 overridden properties, 0x22228 layout constraints, and 0x1B916 +object style (`AppliedObjectStyle`). Many graphics (2,396 images) lack +0x2C10 and 0x2C32; the defaults of the page item table then apply. +Graphics never have `Locked`. Evidence over the 5,131 graphics of the +trustworthy pairs: `Visible`, `Name` and `AppliedObjectStyle` 5,131 of +5,131; the change counts, `OverriddenPageItemProps` and both layout +constraints 5,079 of 5,079 from DOM 8 on, and absent in all 52 DOM 7 +graphics. Images also have the five fill gradient attributes +(`GradientFillStart`, `…Length`, `…Angle`, `…HiliteLength`, +`…HiliteAngle`) from their attribute list (chunk 0x6E03) with the +defaults of page items, and `FillColor` when the list has attribute +0x6E68 (77 of 77 images; no image without it has `FillColor`). PDF, EPS +and SVG graphics have no gradient attributes. + +**`ImageTypeName`** is `$ID/` and the format name of the link resource +(links, above), on graphics with a link only: 4,696 of 4,699 linked +graphics; no graphic without a link has it (308 images, 111 PDF, 12 +EPS). + +**Image properties (chunk 0x1708 of an image).** u32 count, then per +record u32 key, u32 data length *n*, a u8 (meaning unknown), *n* bytes; +then 4 zero bytes: + +| Key | Data | Meaning | +|---|---|---| +| 0x64 | u32 | width in pixels | +| 0x65 | u32 | height in pixels | +| 0x67 | u32 | colour space: 1 grey, 2 RGB, 4 CMYK | +| 0x6C | u32, 16.16 fixed point | horizontal resolution (ppi) | +| 0x6D | u32, 16.16 fixed point | vertical resolution | +| 0x6F | colour table | present only for indexed colour | + +In all 3,607 images of the trustworthy pairs, `GraphicBounds` width and +height equal pixels × 72 / resolution. All 29,055 image property chunks +of the distinct little-endian corpus files parse. IDML writes these +values only on images with a link (3,299 of 3,299; no image without a +link has them): + +| IDML | Rule | Equal | +|---|---|---| +| `Space` | 1 `$ID/#Links_Grayscale`, 2 `$ID/#Links_RGB`, 2 with key 0x6F `$ID/#Links_Indexed RGB`, 4 `$ID/#Links_CMYK` | 3,299 of 3,299 | +| `ActualPpi` | both resolutions rounded half up to integers (72.009 → 72) | 3,299 of 3,299 | +| `EffectivePpi` | each `ActualPpi` value divided by the image's scale on the spread, rounded half up | 3,299 of 3,299 | + +The scale on the spread: multiply the `ItemTransform` of the image with +those of all its ancestors (frames, groups, the spread; for an item +anchored in text, its own chain only) to get *a b c d tx ty*. The +horizontal scale is √(a² + b²); the vertical scale is |ad − bc| divided +by the horizontal scale. Using √(c² + d²) for the vertical scale fails on +87 skewed images; rounding half to even fails on one image whose value +is exactly 76.5 (IDML: 77). + +**Profile** (`Properties/Profile` of `Image`, chunk 0x7C0F): u32 at 0 is +3 → `$ID/Embedded`, 1 → `$ID/Use Document Default`; 0 or no chunk → +`$ID/None`. A profile name follows as an in-object string. 3,607 of +3,607 images (751, 1,652 and 1,204). + +**Vector colour policies of PDF and EPS graphics (chunk 0x7C42).** 16 +bytes, four u32. Offset 4 is `RGBVectorPolicy`, offset 12 +`CMYKVectorPolicy`: 1 `IgnoreAll`, 3 `HonorAllProfiles`. Offset 0 is 1 +and offset 8 is 3 in all 334 graphics with the chunk. Without the chunk +the policies follow the document's colour policies (chunk 0x7C44 of the +preferences, `preferences.md`): `RGBVectorPolicy` is `IgnoreAll` when +`RGBPolicy` is `ColorPolicyOff`, else `HonorAllProfiles`; +`CMYKVectorPolicy` is `IgnoreAll` for `ColorPolicyOff` and +`CombinationOfPreserveAndSafeCmyk`, `HonorAllProfiles` for +`PreserveEmbeddedProfiles` and `ConvertToWorkingSpace`. Evidence: with +the chunk 334 of 334 graphics; without it 1,005 of 1,005 graphics in 128 +documents (5 combinations of document policies). + +**PDF placement (chunk 0x251B of a PDF).** + +| Offset | Size | IDML `PDFAttribute` | +|---|---|---| +| 0 | u32 | `PageNumber` | +| 6 | u8 | `TransparentBackground`: 1 `true`, 0 `false` | +| 8 | u32 | `PDFCrop`: 0 `CropContentVisibleLayers`, 2 `CropArt`, 3 `CropPDF`, 4 `CropTrim`, 6 `CropMedia`, 7 `CropContentAllLayers` | + +Evidence: 492 of 492 PDFs with the chunk (28 bytes in 486, 64 in 6), +all three fields. Without the chunk, IDML has `PageNumber="1"`, +`TransparentBackground="true"` and `PDFCrop="CropContentVisibleLayers"` +in 507 of 509 PDFs; the other 2 (one document) have `CropArt`, not +explained. Every PDF has `PDFAttribute` (1,001 of 1,001). + +**Graphic layers (chunk 0x177A of images, PDFs and imported pages).** + +| Offset | Size | Contents | +|---|---|---| +| 0 | 2 | 1 if an image has a `GraphicLayerOption` | +| 2 | 8 | unknown | +| 10 | 4 | layer count *n* | +| 14 | | *n* layer records, in IDML order | + +A layer record is a flagged string (`Name`; a key is written with +`$ID/`), u32 layer ID (`Id`), u32 original and u32 current visibility (1 += visible: `OriginalVisibility`, `CurrentVisibility`), i32 ID of the +parent layer (−1 for a top-level layer), and u32 flags: 0x01 +`SeparatorLayer`, 0x04 `FXLayer`, 0x08 `Locked`. A layer whose parent +ID is *p* is a child element of the `GraphicLayer` with `Id` *p*. +`Self` is the graphic's `Self`, `GraphicLayerOption1`, and `i` and the +layer ID in hexadecimal for each layer from the top level down +(`u5dbcGraphicLayerOption1i92i8e` is layer 0x8E inside layer 0x92). + +Evidence: all 1,064 `GraphicLayer` elements of the trustworthy pairs +(679 PDF, 291 image and 94 imported page layers, 262 of them nested): +name, `Id`, `Self`, both visibilities and nesting 1,064 of 1,064; flag +0x04 ↔ `FXLayer="true"` 11 of 11; flag 0x08 ↔ `Locked="true"` 37 of 37; +flag 0x01 ↔ `SeparatorLayer="true"` 1 of 1. Flags 0x400 (10 group +layers) and 0x800 (5) have no IDML counterpart. `AdjustmentLayer`, +`HasViewState`, `ViewState`, `HasExportState`, `ExportState`, +`HasPrintState` and `PrintState` are `false` in all 1,064. +`GraphicLayerOption` with `UpdateLinkOption="KeepOverrides"` is on every +PDF and imported page (1,039 of 1,039, also when the layer count is 0) +and on the images whose chunk has 1 at offset 0 (11 of 11; the 1,212 +images with 0 there have no element). All 38,087 layer chunks of the +distinct little-endian corpus files from InDesign 4.0 on parse; 172 in +InDesign 3.0 files do not, and the converter leaves their layers out +with a warning. + +**Layer comps.** Images with a `GraphicLayerOption` also have +`LayerCompOption AppliedLayerComp`: chunk 0x9209 of the image, i32 at +offset 4 (−1, −2 or a comp number). 11 of 11. + ## Graphics pasted without a link A graphic with no link (its chunk 0x8CBC names no link) can hold its file diff --git a/src/idml/attrs.rs b/src/idml/attrs.rs index e70a64d..c694c30 100644 --- a/src/idml/attrs.rs +++ b/src/idml/attrs.rs @@ -671,10 +671,16 @@ impl Writer<'_> { }) .collect(); } + Self::gradient_values(&item.attrs) + } + + /// The gradient attributes of an attribute list, with the defaults + /// for those it lacks. + pub(super) fn gradient_values(attrs: &Attrs) -> Vec<(&'static str, String)> { GRADIENT_ATTRS .iter() .map(|&(id, name, default)| { - let v = match item.attrs.get(id) { + let v = match attrs.get(id) { Some(Value::Point(x, y)) => Some(nums(&[*x, *y])), Some(v) => v.as_f64().map(num), None => None, diff --git a/src/idml/format.rs b/src/idml/format.rs index e61c0b3..cebf0a8 100644 --- a/src/idml/format.rs +++ b/src/idml/format.rs @@ -3,6 +3,7 @@ //! follow the IDML specification; they hold no INDD facts. use super::*; +use crate::model::xmp::{XmpDate, civil_from_days, day_of_year}; /// The IDML name of an XML tag colour (red, green, blue fractions); /// `None` for colours without evidence. See `docs/format/objects.md`. @@ -191,6 +192,31 @@ fn significant_digits(text: &str) -> usize { } } +/// A link time (FILETIME: 100 ns intervals since 1601-01-01 UTC) as IDML +/// writes it, `YYYY-MM-DDTHH:MM:SS` in the local time of the computer that +/// exported the IDML. The INDD does not store that time zone; the offset +/// is taken from the XMP date nearest in day of the year (ties: the +/// latest date), or UTC without XMP dates. See `docs/format/objects.md`, +/// link times. +pub(super) fn link_time(filetime: u64, dates: &[XmpDate]) -> String { + let utc = (filetime / 10_000_000) as i64 - 11_644_473_600; + let day = day_of_year(utc); + let distance = |d: &XmpDate| (day_of_year(d.utc) - day).abs(); + let offset = dates + .iter() + .min_by(|a, b| distance(a).cmp(&distance(b)).then(b.utc.cmp(&a.utc))) + .map_or(0, |d| d.offset); + let local = utc + offset; + let (year, month, day) = civil_from_days(local.div_euclid(86_400)); + let secs = local.rem_euclid(86_400); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}", + secs / 3600, + secs / 60 % 60, + secs % 60 + ) +} + /// Round away binary noise from scaled values (0.8 * 100 = 80.00000000000001). pub(crate) fn round(v: f64) -> f64 { (v * 1e9).round() / 1e9 diff --git a/src/idml/graphic.rs b/src/idml/graphic.rs new file mode 100644 index 0000000..bb0063c --- /dev/null +++ b/src/idml/graphic.rs @@ -0,0 +1,448 @@ +//! Placed graphics (images, PDF, EPS, SVG) with their settings, clipping +//! path, import options, layers and links. +//! +//! Evidence: `docs/format/objects.md` (placed graphics, links, clipping +//! path settings, graphic layers) and `idml-values.md`. + +use super::*; +use crate::model::{GraphicLayer, Name}; + +/// `Space` of an image by its colour space code (and whether it has a +/// colour table). +fn color_space(code: u32, indexed: bool) -> Option<&'static str> { + match (code, indexed) { + (1, _) => Some("$ID/#Links_Grayscale"), + (2, false) => Some("$ID/#Links_RGB"), + (2, true) => Some("$ID/#Links_Indexed RGB"), + (4, _) => Some("$ID/#Links_CMYK"), + _ => None, + } +} + +/// `Properties/Profile` of an image by the code of chunk 0x7C0F. +fn profile(code: Option) -> Option<&'static str> { + match code { + None | Some(0) => Some("$ID/None"), + Some(1) => Some("$ID/Use Document Default"), + Some(3) => Some("$ID/Embedded"), + _ => None, + } +} + +/// A vector colour policy code of chunk 0x7C42. +fn vector_policy(code: u32) -> Option<&'static str> { + match code { + 1 => Some("IgnoreAll"), + 3 => Some("HonorAllProfiles"), + _ => None, + } +} + +/// `PDFCrop` by the crop code of chunk 0x251B. +fn pdf_crop(code: u32) -> Option<&'static str> { + match code { + 0 => Some("CropContentVisibleLayers"), + 2 => Some("CropArt"), + 3 => Some("CropPDF"), + 4 => Some("CropTrim"), + 6 => Some("CropMedia"), + 7 => Some("CropContentAllLayers"), + _ => None, + } +} + +/// A value rounded half up, as IDML rounds resolutions. +fn round_half_up(v: f64) -> f64 { + (v + 0.5).floor() +} + +/// The horizontal and vertical scale of a transform: √(a² + b²), and +/// |ad − bc| divided by the horizontal scale. +fn scales(m: &Matrix) -> (f64, f64) { + let [a, b, c, d, ..] = m.0; + let h = a.hypot(b); + (h, (a * d - b * c).abs() / h) +} + +impl Writer<'_> { + /// `ClippingPathSettings` of an image, PDF or EPS graphic, and + /// `ImageIOPreference` of an image. Values without an INDD field are + /// those every exported IDML has, and a graphic without chunk 0x2C1A + /// has the values every such graphic has in IDML. See + /// `docs/format/objects.md`. + pub(super) fn clipping(x: &mut Xml, g: &Graphic) { + let (high_resolution, threshold, tolerance, inset, index) = match &g.clipping { + Some(c) if c.kind == 0 => ( + match c.high_resolution { + 2 => Some("true"), + 0 => Some("false"), + _ => None, + }, + c.threshold.to_string(), + num(c.tolerance), + num(c.inset), + c.index.to_string(), + ), + Some(_) => return, + None => ( + Some("true"), + "25".into(), + "2".into(), + "0".into(), + "-1".into(), + ), + }; + x.start("ClippingPathSettings") + .attr("ClippingType", "None") + .attr("InvertPath", "false") + .attr("IncludeInsideEdges", "false") + .attr("RestrictToFrame", "false"); + if let Some(h) = high_resolution { + x.attr("UseHighResolutionImage", h); + } + x.attr("Threshold", threshold) + .attr("Tolerance", tolerance) + .attr("InsetFrame", inset) + .attr("AppliedPathName", "$ID/") + .attr("Index", index); + x.end(); + } + + /// `ImageIOPreference` of an image, from chunk 0x1714; without the + /// chunk, the values every image without it has. + fn image_io(x: &mut Xml, g: &Graphic) { + let (clipping, alpha) = match &g.import { + Some((clipping, alpha)) => (*clipping, alpha.idml()), + None => (true, "$ID/".to_string()), + }; + x.empty( + "ImageIOPreference", + &[ + ("ApplyPhotoshopClippingPath", clipping.to_string()), + ("AllowAutoEmbedding", "true".into()), + ("AlphaChannelName", alpha), + ], + ); + } + + /// A `Link` element. Values without an INDD field are those of every + /// link in the corpus IDML files (`idml-values.md`, links). See + /// `docs/format/objects.md`, links. + pub(super) fn link(&self, x: &mut Xml, link: &Link) { + let major = self.doc.version.major; + x.start("Link") + .attr("Self", uref(Some(link.uid))) + .attr("AssetURL", "$ID/") + .attr("AssetID", "$ID/") + .attr("LinkResourceURI", link.uri.clone()); + if let Some(f) = &link.format { + x.attr("LinkResourceFormat", builtin_key(f)); + } + x.attr( + "StoredState", + if link.embedded { "Embedded" } else { "Normal" }, + ) + .attr("LinkClassID", "35906") + .attr("LinkClientID", "257"); + if let Some(m) = link.modified { + x.attr("LinkResourceModified", m.to_string()); + } + x.attr("LinkObjectModified", "false"); + if let Some(s) = link.shown { + x.attr("ShowInUI", s.to_string()); + } + x.attr("CanEmbed", "true") + .attr("CanUnembed", "true") + .attr("CanPackage", "true") + .attr("ImportPolicy", "NoAutoImport") + .attr("ExportPolicy", "NoAutoExport"); + if let Some(stamp) = &link.stamp { + x.attr("LinkImportStamp", stamp.clone()); + } + if let Some([modified, imported]) = link.times { + if link.stamp.is_some() { + x.attr( + "LinkImportModificationTime", + link_time(modified, &self.doc.xmp_dates), + ); + } + x.attr("LinkImportTime", link_time(imported, &self.doc.xmp_dates)); + } + if let Some([high, low]) = link.size { + x.attr("LinkResourceSize", format!("{high:x}~{low:x}")); + } + if major >= 13 { + x.attr("RenditionData", "Actual"); + } + if major >= 21 { + x.attr( + "PDFIdentifier", + link.pdf_identifier.unwrap_or(0).to_string(), + ); + } + x.end(); + } + + /// The vector colour policies of a PDF or EPS: from chunk 0x7C42, or + /// without it from the document's colour policies (`objects.md`, + /// vector colour policies). + fn vector_policies(&self, g: &Graphic) -> [Option<&'static str>; 2] { + let document = |name: &str| { + self.doc + .prefs + .values + .iter() + .find(|v| v.element == "Document" && v.name == name) + .map(|v| v.value.as_str()) + }; + let rgb = match document("RGBPolicy") { + Some("ColorPolicyOff") => Some("IgnoreAll"), + Some(_) => Some("HonorAllProfiles"), + None => None, + }; + let cmyk = match document("CMYKPolicy") { + Some("ColorPolicyOff" | "CombinationOfPreserveAndSafeCmyk") => Some("IgnoreAll"), + Some("PreserveEmbeddedProfiles" | "ConvertToWorkingSpace") => Some("HonorAllProfiles"), + _ => None, + }; + match g.vector_policies { + Some([_, r, _, c]) => [vector_policy(r).or(rgb), vector_policy(c).or(cmyk)], + None => [rgb, cmyk], + } + } + + /// `outer` is the transform from the graphic's parent to the spread. + pub(super) fn placed_graphic(&self, x: &mut Xml, g: &Graphic, outer: &Matrix) { + let major = self.doc.version.major; + let tag = match g.kind { + GraphicKind::Image => "Image", + GraphicKind::Pdf => "PDF", + GraphicKind::Eps => "EPS", + GraphicKind::Svg => "SVG", + }; + let [left, top, right, bottom] = g.bounds; + x.start(tag).attr("Self", uref(Some(g.uid))); + match g.kind { + GraphicKind::Image => { + if g.link.is_some() + && let Some(p) = &g.image + { + if let Some(space) = p.color_space.and_then(|c| color_space(c, p.indexed)) { + x.attr("Space", space); + } + if let Some([h, v]) = p.resolution { + let actual = [round_half_up(h), round_half_up(v)]; + x.attr("ActualPpi", nums(&actual)); + let (sh, sv) = scales(&g.transform.then(outer)); + if sh > 0.0 && sv > 0.0 { + let effective = + [round_half_up(actual[0] / sh), round_half_up(actual[1] / sv)]; + if effective.iter().all(|e| e.is_finite()) { + x.attr("EffectivePpi", nums(&effective)); + } + } + } + } + x.attr("ImageRenderingIntent", "UseColorSettings"); + } + GraphicKind::Pdf | GraphicKind::Eps => { + x.attr("GrayVectorPolicy", "IgnoreAll"); + let [rgb, cmyk] = self.vector_policies(g); + if let Some(v) = rgb { + x.attr("RGBVectorPolicy", v); + } + if let Some(v) = cmyk { + x.attr("CMYKVectorPolicy", v); + } + } + GraphicKind::Svg => { + x.attr("UseSVGAs", "EmbedCode"); + } + } + x.attr("LocalDisplaySetting", "Default"); + if let Some(f) = g.link.as_ref().and_then(|l| l.format.as_ref()) { + x.attr("ImageTypeName", builtin_key(f)); + } + if let Some(style) = g.object_style.and_then(|u| self.object_style_ref(u)) { + x.attr("AppliedObjectStyle", style); + } + x.attr("ItemTransform", matrix(&g.transform)); + self.settings(x, &g.props, None); + if g.kind == GraphicKind::Image { + for (name, v) in self.item_attr_values(&g.attrs) { + if name == "FillColor" { + x.attr(name, v); + } + } + for (name, v) in Self::gradient_values(&g.attrs) { + if name.starts_with("GradientFill") { + x.attr(name, v); + } + } + } + if major >= 21 && g.kind != GraphicKind::Eps { + x.attr("FlexItemWidthMode", "FlexFixed") + .attr("FlexItemHeightMode", "FlexFixed"); + } + if g.kind == GraphicKind::Svg && (major, self.doc.version.minor) >= (21, 2) { + x.attr("IsMathMLObject", "false"); + } + x.start("Properties"); + if g.kind == GraphicKind::Image + && let Some(p) = profile(g.profile) + { + x.start("Profile").attr("type", "string").text(p).end(); + } + if let Some(data) = &g.contents { + x.start("Contents") + .cdata(&base64_lines(data), CDATA_SECTION) + .end(); + } + x.empty( + "GraphicBounds", + &[ + ("Left", num(left)), + ("Top", num(top)), + ("Right", num(right)), + ("Bottom", num(bottom)), + ], + ); + x.end(); + if g.kind != GraphicKind::Svg { + Self::clipping(x, g); + } + if g.kind == GraphicKind::Image { + Self::image_io(x, g); + } + if g.kind == GraphicKind::Pdf + || g.kind == GraphicKind::Image && g.layers.as_ref().is_some_and(|l| l.option) + { + self.graphic_layers(x, g); + } + Self::text_wrap_preference(x, g.text_wrap.as_ref(), g.contour_type); + if let Some(link) = &g.link { + self.link(x, link); + } + if g.kind == GraphicKind::Pdf { + let (page, transparent, crop) = match g.pdf { + Some((page, transparent, crop)) => ( + page.to_string(), + match transparent { + 0 => Some("false"), + 1 => Some("true"), + _ => None, + }, + pdf_crop(crop), + ), + None => ( + "1".to_string(), + Some("true"), + Some("CropContentVisibleLayers"), + ), + }; + x.start("PDFAttribute").attr("PageNumber", page); + if let Some(c) = crop { + x.attr("PDFCrop", c); + } + if let Some(t) = transparent { + x.attr("TransparentBackground", t); + } + x.end(); + } + x.end(); + } + + /// `GraphicLayerOption` with the graphic's layers, and for an image + /// `LayerCompOption`. See `docs/format/objects.md`, graphic layers. + fn graphic_layers(&self, x: &mut Xml, g: &Graphic) { + let layers = g.layers.as_ref().map_or(&[][..], |l| &l.layers[..]); + x.start("GraphicLayerOption") + .attr("UpdateLinkOption", "KeepOverrides"); + let base = format!("{}GraphicLayerOption1", uref(Some(g.uid))); + // Top-level layers, then each layer's children, in record order. A + // layer whose parent is not listed is left out. + let mut path = Vec::new(); + Self::layer_children(x, layers, -1, &base, &mut path); + x.end(); + if g.kind == GraphicKind::Image + && let Some(comp) = g.layer_comp + { + x.empty("LayerCompOption", &[("AppliedLayerComp", comp.to_string())]); + } + } + + fn layer_children( + x: &mut Xml, + layers: &[GraphicLayer], + parent: i32, + base: &str, + path: &mut Vec, + ) { + for l in layers.iter().filter(|l| l.parent == parent) { + // A layer that contains itself would never end. + if path.contains(&l.id) || i32::try_from(l.id).is_err() { + continue; + } + path.push(l.id); + let id: String = path.iter().map(|i| format!("i{i:x}")).collect(); + x.start("GraphicLayer") + .attr("Self", format!("{base}{id}")) + .attr("Name", layer_name(&l.name)) + .attr("OriginalVisibility", l.original_visibility.to_string()) + .attr("CurrentVisibility", l.current_visibility.to_string()) + .attr("SeparatorLayer", (l.flags & 0x01 != 0).to_string()) + .attr("AdjustmentLayer", "false") + .attr("FXLayer", (l.flags & 0x04 != 0).to_string()) + .attr("Locked", (l.flags & 0x08 != 0).to_string()); + for name in [ + "HasViewState", + "ViewState", + "HasExportState", + "ExportState", + "HasPrintState", + "PrintState", + ] { + x.attr(name, "false"); + } + x.attr("Id", l.id.to_string()); + Self::layer_children(x, layers, l.id as i32, base, path); + x.end(); + path.pop(); + } + } +} + +/// A layer name: a key (flag 1) is written with `$ID/`. +fn layer_name(n: &Name) -> String { + n.idml() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn measures_scales_of_skewed_transforms() { + let (h, v) = scales(&Matrix([2.0, 0.0, 0.0, 3.0, 5.0, 5.0])); + assert_eq!((h, v), (2.0, 3.0)); + // A skew keeps the area: the vertical scale is the determinant + // over the horizontal scale. + let (h, v) = scales(&Matrix([1.0, 0.0, 0.5, 1.0, 0.0, 0.0])); + assert_eq!((h, v), (1.0, 1.0)); + } + + #[test] + fn rounds_resolutions_half_up() { + assert_eq!(round_half_up(76.5), 77.0); + assert_eq!(round_half_up(72.009), 72.0); + } + + #[test] + fn names_colour_spaces() { + assert_eq!(color_space(2, true), Some("$ID/#Links_Indexed RGB")); + assert_eq!(color_space(4, false), Some("$ID/#Links_CMYK")); + assert_eq!(color_space(3, false), None); + assert_eq!(profile(None), Some("$ID/None")); + assert_eq!(profile(Some(2)), None); + } +} diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 5d10ff4..8baee73 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -11,6 +11,7 @@ mod attrs; mod designmap; mod export; mod format; +mod graphic; mod kind; mod pages; mod resources; @@ -34,10 +35,11 @@ use std::collections::BTreeMap; use crate::model::prefs::PrefProp; use crate::model::{ - Attrs, Document, Graphic, GraphicKind, Guide, ItemKind, Matrix, Orientation, Page, PageItem, - Path, Section, Shape, Spread, Story, Style, StyleGroup, Table, TextFramePreferences, TextRun, - TextVariable, TextWrap, UiColorRef, Value, XmlElement, XmlMarker, hyperlink::DestinationKind, - numbering, root_kind, variable::Instance, wrap_mode, xml::Key as XmlKey, + Attrs, Document, Graphic, GraphicKind, Guide, ItemKind, ItemProps, Link, Matrix, Orientation, + Page, PageItem, Path, Section, Shape, Spread, Story, Style, StyleGroup, Table, + TextFramePreferences, TextRun, TextVariable, TextWrap, UiColorRef, Value, XmlElement, + XmlMarker, hyperlink::DestinationKind, numbering, root_kind, variable::Instance, wrap_mode, + xml::Key as XmlKey, }; use crate::object::builtin_key; diff --git a/src/idml/spread.rs b/src/idml/spread.rs index f4469b3..6852a1b 100644 --- a/src/idml/spread.rs +++ b/src/idml/spread.rs @@ -180,117 +180,23 @@ impl Writer<'_> { x.end(); } - /// `ClippingPathSettings` of an image, PDF or EPS graphic, and - /// `ImageIOPreference` of an image. Values without an INDD field are - /// those every exported IDML has, and a graphic without chunk 0x2C1A - /// has the values every such graphic has in IDML. See - /// `docs/format/objects.md`. - pub(super) fn clipping(x: &mut Xml, g: &Graphic) { - let (high_resolution, threshold, tolerance, inset, index) = match &g.clipping { - Some(c) if c.kind == 0 => ( - match c.high_resolution { - 2 => Some("true"), - 0 => Some("false"), - _ => None, - }, - c.threshold.to_string(), - num(c.tolerance), - num(c.inset), - c.index.to_string(), - ), - Some(_) => return, - None => ( - Some("true"), - "25".into(), - "2".into(), - "0".into(), - "-1".into(), - ), - }; - x.start("ClippingPathSettings") - .attr("ClippingType", "None") - .attr("InvertPath", "false") - .attr("IncludeInsideEdges", "false") - .attr("RestrictToFrame", "false"); - if let Some(h) = high_resolution { - x.attr("UseHighResolutionImage", h); - } - x.attr("Threshold", threshold) - .attr("Tolerance", tolerance) - .attr("InsetFrame", inset) - .attr("AppliedPathName", "$ID/") - .attr("Index", index); - x.end(); - if g.kind != GraphicKind::Image { - return; - } - x.start("ImageIOPreference"); - match g.photoshop_clipping { - Some(1) => { - x.attr("ApplyPhotoshopClippingPath", "true"); - } - Some(0) => { - x.attr("ApplyPhotoshopClippingPath", "false"); - } - _ => {} - } - x.attr("AllowAutoEmbedding", "true") - .attr("AlphaChannelName", "$ID/"); - x.end(); - } - - pub(super) fn placed_graphic(x: &mut Xml, g: &Graphic) { - let tag = match g.kind { - GraphicKind::Image => "Image", - GraphicKind::Pdf => "PDF", - GraphicKind::Eps => "EPS", - GraphicKind::Svg => "SVG", - }; - let [left, top, right, bottom] = g.bounds; - x.start(tag) - .attr("Self", uref(Some(g.uid))) - .attr("ItemTransform", matrix(&g.transform)); - x.start("Properties"); - if let Some(data) = &g.contents { - x.start("Contents") - .cdata(&base64_lines(data), CDATA_SECTION) - .end(); - } - x.empty( - "GraphicBounds", - &[ - ("Left", num(left)), - ("Top", num(top)), - ("Right", num(right)), - ("Bottom", num(bottom)), - ], - ); - x.end(); - if g.kind != GraphicKind::Svg { - Self::clipping(x, g); - } - Self::text_wrap_preference(x, g.text_wrap.as_ref(), g.contour_type); - if let Some(link) = &g.link { - x.empty( - "Link", - &[ - ("Self", uref(Some(link.uid))), - ("LinkResourceURI", link.uri.clone()), - ( - "StoredState", - if link.embedded { "Embedded" } else { "Normal" }.into(), - ), - ], - ); - } - x.end(); - } - /// The name, visibility, lock and the other settings every page item /// has; `nested` for an item inside another page item, which IDML /// writes without `Locked`. See `docs/format/objects.md`. pub(super) fn item_settings(&self, x: &mut Xml, item: &PageItem, nested: bool) { - let p = &item.props; + let locked = (!nested).then_some(item.props.locked); + self.settings(x, &item.props, locked); + for (name, v) in Self::gradients(item) { + if !x.has_attr(name) { + x.attr(name, v); + } + } + } + + /// The settings of `ItemProps` (page items and placed graphics): + /// `Locked` only when `locked` is given. See `docs/format/objects.md`, + /// page item settings. + pub(super) fn settings(&self, x: &mut Xml, p: &ItemProps, locked: Option) { let name = match &p.name { Some(n) if n.builtin => builtin_key(&n.name), Some(n) => n.name.clone(), @@ -298,8 +204,8 @@ impl Writer<'_> { }; x.attr("Name", name) .attr("Visible", (!p.hidden).to_string()); - if !nested { - x.attr("Locked", p.locked.to_string()); + if let Some(l) = locked { + x.attr("Locked", l.to_string()); } if self.doc.version.major >= 8 { for (name, counts) in [ @@ -322,15 +228,23 @@ impl Writer<'_> { .attr("VerticalLayoutConstraints", v); } } - for (name, v) in Self::gradients(item) { - if !x.has_attr(name) { - x.attr(name, v); - } - } } - /// `nested` for an item inside another page item. - pub(super) fn page_item(&self, x: &mut Xml, item: &PageItem, nested: bool) { + /// The `AppliedObjectStyle` reference of an object style UID. + pub(super) fn object_style_ref(&self, uid: u32) -> Option { + let os = self.doc.object_styles.get(&uid)?; + let name = if os.builtin { + builtin_key(&os.name) + } else { + os.name.clone() + }; + Some(format!("ObjectStyle/{}", self_name(&name))) + } + + /// `nested` for an item inside another page item; `outer` is the + /// transform from the item's parent to the spread (for anchored items, + /// to the anchor). + pub(super) fn page_item(&self, x: &mut Xml, item: &PageItem, nested: bool, outer: &Matrix) { let tag = match &item.kind { ItemKind::TextFrame { .. } => "TextFrame", ItemKind::Group => "Group", @@ -372,16 +286,8 @@ impl Writer<'_> { { x.attr("StrokeWeight", "1"); } - if let Some(os) = style { - let name = if os.builtin { - builtin_key(&os.name) - } else { - os.name.clone() - }; - x.attr( - "AppliedObjectStyle", - format!("ObjectStyle/{}", self_name(&name)), - ); + if let Some(r) = item.object_style.and_then(|u| self.object_style_ref(u)) { + x.attr("AppliedObjectStyle", r); } if let Some(layer) = item.layer { x.attr("ItemLayer", uref(Some(layer))); @@ -441,10 +347,10 @@ impl Writer<'_> { )); } for child in &item.children { - self.page_item(x, child, true); + self.page_item(x, child, true, &item.transform.then(outer)); } for g in &item.graphics { - Self::placed_graphic(x, g); + self.placed_graphic(x, g, &item.transform.then(outer)); } x.end(); } @@ -795,7 +701,7 @@ impl Writer<'_> { x.end(); } for item in &s.items { - self.page_item(&mut x, item, false); + self.page_item(&mut x, item, false, &s.transform); } x.end(); x.finish() diff --git a/src/idml/story.rs b/src/idml/story.rs index b52de60..a9a93a6 100644 --- a/src/idml/story.rs +++ b/src/idml/story.rs @@ -304,7 +304,7 @@ impl Writer<'_> { '\u{FFFC}' if story.anchors.contains_key(&pos) => { flush(x, &mut buf); for item in &story.anchors[&pos] { - self.page_item(x, item, false); + self.page_item(x, item, false, &Matrix::IDENTITY); } } '\u{16}' if story.tables.contains_key(&pos) => { diff --git a/src/lib.rs b/src/lib.rs index e7d3dfa..6fb1a8c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -199,7 +199,11 @@ fn convert_with( if let Some(r) = recorder { db.set_recorder(r); } - let doc = model::Reader::new(&db).document(container.header.version)?; + let mut doc = model::Reader::new(&db).document(container.header.version)?; + // A damaged XMP packet only loses the time zone of link times. + if let Ok(Some(packet)) = container.xmp() { + doc.xmp_dates = model::xmp::dates(packet); + } let mut warnings = doc.warnings.clone(); warnings.extend(idml::write(&doc, name, out)?); Ok(warnings diff --git a/src/model/document.rs b/src/model/document.rs index 754f4c4..7f54ade 100644 --- a/src/model/document.rs +++ b/src/model/document.rs @@ -83,6 +83,9 @@ pub struct Document { /// XML tags (class 0xBF19). pub xml_tags: Vec, pub xml: XmlStructure, + /// 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, } /// An XML tag: its name and colour (red, green, blue). @@ -231,6 +234,7 @@ impl<'a> Reader<'a> { bullets, xml_tags: objects.xml_tags, xml, + xmp_dates: Vec::new(), // Last, so that it holds every warning of the model. warnings: self.warnings.borrow().clone(), }) diff --git a/src/model/ids.rs b/src/model/ids.rs index 87c68c7..c04a418 100644 --- a/src/model/ids.rs +++ b/src/model/ids.rs @@ -175,6 +175,8 @@ pub mod chunk { pub const GRAPHIC_LINK: u32 = 0x8CBC; pub const LINK_INFO: u32 = 0x8C9B; pub const LINK_RESOURCE_URI: u32 = 0x8C92; + /// u32 PDF identifier of a link. + pub const LINK_PDF_IDENTIFIER: u32 = 0x1B6; /// Pasted image without a link: u32 raw data object. pub const IMAGE_DATA: u32 = 0x8C23; /// Pasted PDF without a link: u32 raw data object. @@ -183,7 +185,20 @@ pub mod chunk { pub const TEXT_WRAP: u32 = 0x3703; pub const CONTOUR_OPTION: u32 = 0x373D; pub const CLIPPING_PATH: u32 = 0x2C1A; - pub const PHOTOSHOP_CLIPPING: u32 = 0x8C39; + /// Image properties: record list (pixels, colour space, resolution). + pub const IMAGE_PROPERTIES: u32 = 0x1708; + /// Colour profile of an image: u32 code, then a name. + pub const IMAGE_PROFILE: u32 = 0x7C0F; + /// Image import options: clipping path flag, alpha channel name. + pub const IMAGE_IMPORT: u32 = 0x1714; + /// Vector colour policies of a PDF or EPS: four u32. + pub const VECTOR_POLICIES: u32 = 0x7C42; + /// PDF placement: page number, transparent background, crop. + pub const PDF_PLACEMENT: u32 = 0x251B; + /// Layers of an image, PDF or imported page. + pub const GRAPHIC_LAYERS: u32 = 0x177A; + /// Applied layer comp of an image (i32 at 4). + pub const LAYER_COMP: u32 = 0x9209; /// Frame fitting attributes of an object style (u16 count, records). pub const OBJECT_STYLE_FITTING: u32 = 0x1B956; /// Page item attributes of an object style (u16 count, records). diff --git a/src/model/item.rs b/src/model/item.rs index 2ce7fc9..92da41f 100644 --- a/src/model/item.rs +++ b/src/model/item.rs @@ -14,6 +14,21 @@ pub struct Matrix(pub [f64; 6]); impl Matrix { pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + /// This transform followed by `outer` (points are row vectors, as + /// in IDML). + pub fn then(&self, outer: &Matrix) -> Matrix { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = outer.0; + Matrix([ + a * p + b * r, + a * q + b * s, + c * p + d * r, + c * q + d * s, + e * p + f * r + t, + e * q + f * s + u, + ]) + } + pub(super) fn read(c: &mut Cursor) -> Result { let mut m = [0.0; 6]; for v in &mut m { @@ -154,13 +169,30 @@ pub enum GraphicKind { Svg, } -#[derive(Debug, Clone, PartialEq)] +/// A link (class 0x8C42) and its link resource (class 0x8C41). See +/// `docs/format/objects.md`, links. +#[derive(Debug, Clone, PartialEq, Default)] pub struct Link { pub uid: u32, /// `LinkResourceURI`, for example `file:/Users/me/image.jpg`. pub uri: String, /// The linked file is stored in the document (`StoredState="Embedded"`). pub embedded: bool, + /// Chunk 0x8C9B, u32 at 12: 0 when the linked file was modified. + pub modified: Option, + /// Chunk 0x8C9B, u16 at 20: 1 when the link is shown. + pub shown: Option, + /// The import stamp (`file