mirror of
https://github.com/storytold/indd-utils.git
synced 2026-11-24 19:20:46 +01:00
feat: write link attributes and placed graphic settings
Links: LinkResourceModified, ShowInUI, LinkImportStamp and the two link times from chunk 0x8C9B, PDFIdentifier from chunk 0x1B6, the size and format name from the resource's chunk 0x8C92, and the values every link has. Link times are written in the time zone of the XMP date nearest in day of the year (the INDD has no time zone; compare.py does not score them): 3,886 of 4,446 import times and 3,316 of 4,434 modification times right. Images, PDF, EPS and SVG graphics: the page item settings and object style, Space, ActualPpi and EffectivePpi (chunk 0x1708 and the scale on the spread), ImageTypeName, Profile (chunk 0x7C0F), fill colour and gradients, vector colour policies (chunk 0x7C42 or the document's policies), PDFAttribute (chunk 0x251B), GraphicLayerOption with the GraphicLayer tree (chunk 0x177A) and LayerCompOption (chunk 0x9209), and ImageIOPreference from chunk 0x1714 in place of chunk 0x8C39. The placed graphic writer moves to idml/graphic.rs. compare.py --all --exclude own/ (trustworthy pairs): value coverage 90.00% -> 91.61% (+179,834 values); documents >= 99 %: 1 -> 5; median 94.2% -> 95.7%; no key lower. Extra values 709,643 -> 709,654 (+11 in SVG elements that are not in the reference). New warnings: 178 layer chunks in 3 InDesign 3.0 files, whose layout differs, are left out. 0 conversion and 0 schema failures.
This commit is contained in:
1 parent
9de24aa28f
commit
5b7e0ecf1f
14 files changed
+1223
-178
No files matched your search
@@ -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
|
||||
|
||||
|
||||
+228
-10
@@ -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 <n> <size>`, and
|
||||
`<n>` 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 `<high>~<low>` 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
|
||||
|
||||
+7
-1
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<u32>) -> 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<u32>,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -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;
|
||||
|
||||
+35
-129
@@ -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<bool>) {
|
||||
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<String> {
|
||||
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()
|
||||
|
||||
+1
-1
@@ -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) => {
|
||||
|
||||
+5
-1
@@ -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
|
||||
|
||||
@@ -83,6 +83,9 @@ pub struct Document {
|
||||
/// XML tags (class 0xBF19).
|
||||
pub xml_tags: Vec<XmlTag>,
|
||||
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<super::xmp::XmpDate>,
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
})
|
||||
|
||||
+16
-1
@@ -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).
|
||||
|
||||
+275
-27
@@ -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<Matrix, Error> {
|
||||
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<bool>,
|
||||
/// Chunk 0x8C9B, u16 at 20: 1 when the link is shown.
|
||||
pub shown: Option<bool>,
|
||||
/// The import stamp (`file <time> <size>`); `None` when empty.
|
||||
pub stamp: Option<String>,
|
||||
/// The file's modification time and the time it was placed or
|
||||
/// updated, as FILETIME (100 ns since 1601-01-01 UTC).
|
||||
pub times: Option<[u64; 2]>,
|
||||
/// Chunk 0x1B6 of the link.
|
||||
pub pdf_identifier: Option<u32>,
|
||||
/// The file size of the resource: high and low u32.
|
||||
pub size: Option<[u32; 2]>,
|
||||
/// The format name of the resource (`JPEG`, `Photoshop`, ...).
|
||||
pub format: Option<String>,
|
||||
}
|
||||
|
||||
/// The bytes of a file stored in the document, if there is one.
|
||||
@@ -182,8 +214,63 @@ pub struct Graphic {
|
||||
pub contour_type: Option<u32>,
|
||||
/// Clipping path settings (chunk 0x2C1A), if stored.
|
||||
pub clipping: Option<ClippingPath>,
|
||||
/// Chunk 0x8C39, u16 at 0: apply the Photoshop clipping path (1 true).
|
||||
pub photoshop_clipping: Option<u16>,
|
||||
/// Name, visibility, change counts and the other page item settings.
|
||||
pub props: ItemProps,
|
||||
/// Chunk 0x1B916.
|
||||
pub object_style: Option<u32>,
|
||||
/// The attribute list (chunk 0x6E03).
|
||||
pub attrs: Attrs,
|
||||
/// Image properties (chunk 0x1708 of an image).
|
||||
pub image: Option<ImageProperties>,
|
||||
/// Colour profile code (chunk 0x7C0F, u32 at 0).
|
||||
pub profile: Option<u32>,
|
||||
/// Grey, RGB, grey again and CMYK vector policy codes of a PDF or EPS
|
||||
/// (chunk 0x7C42, four u32); only the RGB and CMYK codes are known.
|
||||
pub vector_policies: Option<[u32; 4]>,
|
||||
/// PDF placement (chunk 0x251B): page number, transparent background
|
||||
/// byte, crop code.
|
||||
pub pdf: Option<(u32, u8, u32)>,
|
||||
/// Layers of an image, PDF or imported page (chunk 0x177A).
|
||||
pub layers: Option<GraphicLayers>,
|
||||
/// Applied layer comp (chunk 0x9209, i32 at 4).
|
||||
pub layer_comp: Option<i32>,
|
||||
/// Image import options (chunk 0x1714): apply the Photoshop clipping
|
||||
/// path, alpha channel name.
|
||||
pub import: Option<(bool, Name)>,
|
||||
}
|
||||
|
||||
/// Image properties (chunk 0x1708): u32 count, then records of u32 key,
|
||||
/// u32 length *n*, u8, *n* bytes. See `docs/format/objects.md`, image
|
||||
/// properties.
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct ImageProperties {
|
||||
/// Key 0x67: 1 grey, 2 RGB, 4 CMYK.
|
||||
pub color_space: Option<u32>,
|
||||
/// Key 0x6F (a colour table) is present.
|
||||
pub indexed: bool,
|
||||
/// Keys 0x6C and 0x6D, 16.16 fixed point.
|
||||
pub resolution: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// Layers of a placed graphic (chunk 0x177A).
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct GraphicLayers {
|
||||
/// The u16 at 0 is 1.
|
||||
pub option: bool,
|
||||
/// In IDML order.
|
||||
pub layers: Vec<GraphicLayer>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GraphicLayer {
|
||||
pub name: Name,
|
||||
pub id: u32,
|
||||
pub original_visibility: bool,
|
||||
pub current_visibility: bool,
|
||||
/// The parent layer's ID, −1 for a top-level layer.
|
||||
pub parent: i32,
|
||||
/// 0x01 separator, 0x04 effects layer, 0x08 locked.
|
||||
pub flags: u32,
|
||||
}
|
||||
|
||||
/// Clipping path settings of a graphic (chunk 0x2C1A, 37 bytes): u32 type
|
||||
@@ -752,13 +839,123 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
photoshop_clipping: match self.chunk(uid, chunk::PHOTOSHOP_CLIPPING)? {
|
||||
Some(d) if d.len() >= 2 => Some(self.cursor(&d).u16()?),
|
||||
props: self.item_props(uid).unwrap_or_else(|e| {
|
||||
self.warn(format!("graphic {uid}: settings left out: {e}"));
|
||||
ItemProps::default()
|
||||
}),
|
||||
object_style: match self.chunk(uid, chunk::ITEM_OBJECT_STYLE)? {
|
||||
Some(d) if d.len() >= 4 => uid_or_none(self.cursor(&d).u32()?),
|
||||
_ => None,
|
||||
},
|
||||
attrs: match self.chunk(uid, chunk::ITEM_ATTRS)? {
|
||||
Some(d) => self
|
||||
.attrs_or_warn(
|
||||
|| format!("graphic {uid}"),
|
||||
Attrs::parse(self.enc(), &d, List::Item, self.db.recorder()),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
None => Attrs::default(),
|
||||
},
|
||||
image: match self.chunk(uid, chunk::IMAGE_PROPERTIES)? {
|
||||
Some(d) if kind == GraphicKind::Image => self.image_properties(&d),
|
||||
_ => None,
|
||||
},
|
||||
profile: match self.chunk(uid, chunk::IMAGE_PROFILE)? {
|
||||
Some(d) if d.len() >= 4 => Some(self.cursor(&d).u32()?),
|
||||
_ => None,
|
||||
},
|
||||
vector_policies: match self.chunk(uid, chunk::VECTOR_POLICIES)? {
|
||||
Some(d) if d.len() >= 16 => {
|
||||
let mut c = self.cursor(&d);
|
||||
Some([c.u32()?, c.u32()?, c.u32()?, c.u32()?])
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
pdf: match self.chunk(uid, chunk::PDF_PLACEMENT)? {
|
||||
Some(d) if d.len() >= 12 => {
|
||||
Some((self.cursor(&d).u32()?, d[6], self.cursor(&d[8..]).u32()?))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
layers: match self.chunk(uid, chunk::GRAPHIC_LAYERS)? {
|
||||
Some(d) => self.graphic_layers(&d).unwrap_or_else(|e| {
|
||||
self.warn(format!("graphic {uid}: layers left out: {e}"));
|
||||
None
|
||||
}),
|
||||
None => None,
|
||||
},
|
||||
layer_comp: match self.chunk(uid, chunk::LAYER_COMP)? {
|
||||
Some(d) if d.len() >= 8 => Some(self.cursor(&d[4..]).i32()?),
|
||||
_ => None,
|
||||
},
|
||||
import: match self.chunk(uid, chunk::IMAGE_IMPORT)? {
|
||||
Some(d) if d.len() >= 9 => {
|
||||
let mut c = self.cursor(&d[4..]);
|
||||
let clipping = c.u16()?;
|
||||
c.u16()?;
|
||||
match (clipping, c.name()) {
|
||||
(0 | 1, Ok(name)) => Some((clipping == 1, name)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
/// Image properties from chunk 0x1708; `None` if the record list is
|
||||
/// cut short.
|
||||
fn image_properties(&self, d: &[u8]) -> Option<ImageProperties> {
|
||||
let mut c = self.cursor(d);
|
||||
let n = c.u32().ok()?;
|
||||
let mut p = ImageProperties::default();
|
||||
let mut resolution = [None, None];
|
||||
for _ in 0..n {
|
||||
let key = c.u32().ok()?;
|
||||
let len = c.u32().ok()? as usize;
|
||||
c.u8().ok()?;
|
||||
let data = c.bytes(len).ok()?;
|
||||
let value = || (len >= 4).then(|| self.cursor(data).u32().ok()).flatten();
|
||||
match key {
|
||||
0x67 => p.color_space = value(),
|
||||
0x6C => resolution[0] = value().map(|v| f64::from(v) / 65536.0),
|
||||
0x6D => resolution[1] = value().map(|v| f64::from(v) / 65536.0),
|
||||
0x6F => p.indexed = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let [Some(h), Some(v)] = resolution {
|
||||
p.resolution = Some([h, v]);
|
||||
}
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// Layers of a placed graphic (chunk 0x177A): u16 option flag, 8
|
||||
/// bytes, u32 count, then per layer a flagged name, u32 ID, u32
|
||||
/// original and current visibility, i32 parent ID and u32 flags.
|
||||
fn graphic_layers(&self, d: &[u8]) -> Result<Option<GraphicLayers>, Error> {
|
||||
let mut c = self.cursor(d);
|
||||
let option = c.u16()? == 1;
|
||||
c.skip(8)?;
|
||||
let n = c.u32()? as usize;
|
||||
if n > d.len() / 20 {
|
||||
return Err(Error::Corrupt(format!("{n} graphic layers")));
|
||||
}
|
||||
let mut layers = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
let name = c.name()?;
|
||||
layers.push(GraphicLayer {
|
||||
name,
|
||||
id: c.u32()?,
|
||||
original_visibility: c.u32()? == 1,
|
||||
current_visibility: c.u32()? == 1,
|
||||
parent: c.i32()?,
|
||||
flags: c.u32()?,
|
||||
});
|
||||
}
|
||||
Ok(Some(GraphicLayers { option, layers }))
|
||||
}
|
||||
|
||||
/// The bytes of raw data object `uid` (`None` if `uid` is not one).
|
||||
pub(super) fn raw_data(&self, uid: u32) -> Result<EmbeddedFile, Error> {
|
||||
if uid == 0 || self.class(uid) != Some(class::RAW_DATA) {
|
||||
@@ -771,7 +968,8 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// A link, the URI of its resource and, for an embedded link, the
|
||||
/// embedded file.
|
||||
/// embedded file. Fields after the URI that are cut short are left
|
||||
/// out (`None`).
|
||||
pub(super) fn link(&self, uid: u32) -> Result<Option<(Link, EmbeddedFile)>, Error> {
|
||||
if uid == 0 || self.db.object(uid)?.is_none() {
|
||||
return Ok(None);
|
||||
@@ -783,28 +981,78 @@ impl<'a> Reader<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let resource = self.cursor(&info[8..]).u32()?;
|
||||
let (uri, data) = match self.chunk(resource, chunk::LINK_RESOURCE_URI)? {
|
||||
Some(d) if d.len() >= 5 => {
|
||||
let mut c = self.cursor(&d);
|
||||
c.u8()?;
|
||||
let n = c.u32()? as usize;
|
||||
let uri = String::from_utf8_lossy(c.bytes(n.min(c.remaining()))?).into_owned();
|
||||
// After the URI: 12 bytes, then the UID of the embedded
|
||||
// file's raw data object (0 for a normal link).
|
||||
let data = if c.remaining() >= 16 {
|
||||
c.skip(12)?;
|
||||
self.raw_data(c.u32()?)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(uri, data)
|
||||
}
|
||||
_ => (String::new(), None),
|
||||
};
|
||||
let link = Link {
|
||||
let mut link = Link {
|
||||
uid,
|
||||
uri,
|
||||
embedded: data.is_some(),
|
||||
..Link::default()
|
||||
};
|
||||
let mut data = None;
|
||||
if let Some(d) = self.chunk(resource, chunk::LINK_RESOURCE_URI)?
|
||||
&& d.len() >= 5
|
||||
{
|
||||
let mut c = self.cursor(&d);
|
||||
c.u8()?;
|
||||
let n = c.u32()? as usize;
|
||||
link.uri = String::from_utf8_lossy(c.bytes(n.min(c.remaining()))?).into_owned();
|
||||
// After the URI: 12 bytes, then the UID of the embedded
|
||||
// file's raw data object (0 for a normal link).
|
||||
if c.remaining() >= 16 {
|
||||
c.skip(12)?;
|
||||
data = self.raw_data(c.u32()?)?;
|
||||
// Then the stamp, the modification time, the file size,
|
||||
// a byte and the format name.
|
||||
let rest = (|| -> Result<_, Error> {
|
||||
let n = c.u32()? as usize;
|
||||
c.segments(n)?;
|
||||
c.skip(8)?;
|
||||
let size = [c.u32()?, c.u32()?];
|
||||
let format = c.name()?.name;
|
||||
Ok((size, format))
|
||||
})();
|
||||
if let Ok((size, format)) = rest {
|
||||
link.size = Some(size);
|
||||
link.format = Some(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
link.embedded = data.is_some();
|
||||
let mut c = self.cursor(&info);
|
||||
let head = (|| -> Result<_, Error> {
|
||||
c.skip(12)?;
|
||||
let modified = c.u32()?;
|
||||
c.skip(4)?;
|
||||
let shown = c.u16()?;
|
||||
c.skip(10)?;
|
||||
Ok((modified, shown))
|
||||
})();
|
||||
if let Ok((modified, shown)) = head {
|
||||
link.modified = match modified {
|
||||
0 => Some(true),
|
||||
1 => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
link.shown = match shown {
|
||||
0 => Some(false),
|
||||
1 => Some(true),
|
||||
_ => None,
|
||||
};
|
||||
let stamp = (|| -> Result<_, Error> {
|
||||
let n = c.u32()? as usize;
|
||||
let stamp = c.segments(n)?;
|
||||
let mut time = || -> Result<u64, Error> {
|
||||
let high = c.u32()?;
|
||||
Ok(u64::from(high) << 32 | u64::from(c.u32()?))
|
||||
};
|
||||
let times = [time()?, time()?];
|
||||
Ok((stamp, times))
|
||||
})();
|
||||
if let Ok((stamp, times)) = stamp {
|
||||
link.stamp = (!stamp.is_empty()).then_some(stamp);
|
||||
link.times = Some(times);
|
||||
}
|
||||
}
|
||||
link.pdf_identifier = match self.chunk(uid, chunk::LINK_PDF_IDENTIFIER)? {
|
||||
Some(d) if d.len() >= 4 => Some(self.cursor(&d).u32()?),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Some((link, data)))
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ mod style;
|
||||
pub mod table;
|
||||
pub mod variable;
|
||||
pub mod xml;
|
||||
pub mod xmp;
|
||||
pub mod xref;
|
||||
|
||||
pub use document::*;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! 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).
|
||||
|
||||
/// An XMP date with a UTC offset: the instant (seconds since 1970 UTC)
|
||||
/// and the offset in seconds.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct XmpDate {
|
||||
pub utc: i64,
|
||||
pub offset: i64,
|
||||
}
|
||||
|
||||
/// The properties whose dates are read.
|
||||
const DATE_PROPERTIES: [&str; 4] = [
|
||||
"xmp:CreateDate",
|
||||
"xmp:MetadataDate",
|
||||
"xmp:ModifyDate",
|
||||
"stEvt:when",
|
||||
];
|
||||
|
||||
/// The dates of `packet` that have a UTC offset (`Z` or `±HH:MM`), from
|
||||
/// the properties `xmp:CreateDate`, `xmp:MetadataDate`, `xmp:ModifyDate`
|
||||
/// and `stEvt:when` (each in attribute or element form). Dates without
|
||||
/// an offset or that do not parse are left out.
|
||||
pub fn dates(packet: &[u8]) -> Vec<XmpDate> {
|
||||
let text = String::from_utf8_lossy(packet);
|
||||
let mut out = Vec::new();
|
||||
for name in DATE_PROPERTIES {
|
||||
let mut rest = &text[..];
|
||||
while let Some(i) = rest.find(name) {
|
||||
rest = &rest[i + name.len()..];
|
||||
let value = if let Some(r) = rest.strip_prefix("=\"") {
|
||||
r
|
||||
} else if let Some(r) = rest.strip_prefix('>') {
|
||||
r
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if let Some(d) = parse(value) {
|
||||
out.push(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let num = |from: usize, len: usize| -> Option<i64> {
|
||||
let t = s.get(from..from + len)?;
|
||||
t.bytes()
|
||||
.all(|c| c.is_ascii_digit())
|
||||
.then(|| t.parse().ok())?
|
||||
};
|
||||
let (year, month, day) = (num(0, 4)?, num(5, 2)?, num(8, 2)?);
|
||||
if b.get(4) != Some(&b'-') || b.get(7) != Some(&b'-') || b.get(10) != Some(&b'T') {
|
||||
return None;
|
||||
}
|
||||
let (hour, minute) = (num(11, 2)?, num(14, 2)?);
|
||||
let mut i = 16;
|
||||
let mut second = 0;
|
||||
if b.get(i) == Some(&b':') {
|
||||
second = num(17, 2)?;
|
||||
i = 19;
|
||||
if b.get(i) == Some(&b'.') {
|
||||
i += 1;
|
||||
while b.get(i).is_some_and(u8::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let offset = match b.get(i)? {
|
||||
b'Z' => 0,
|
||||
&c @ (b'+' | b'-') => {
|
||||
let v = num(i + 1, 2)? * 3600 + num(i + 4, 2)? * 60;
|
||||
if c == b'-' { -v } else { v }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 {
|
||||
return None;
|
||||
}
|
||||
let local = days_from_civil(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second;
|
||||
Some(XmpDate {
|
||||
utc: local - offset,
|
||||
offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 of a date in the proleptic Gregorian calendar.
|
||||
pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
|
||||
let y = if month <= 2 { year - 1 } else { year };
|
||||
let era = y.div_euclid(400);
|
||||
let yoe = y - era * 400;
|
||||
let mp = (month + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + day - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
/// The date (year, month, day) of a day count since 1970-01-01.
|
||||
pub fn civil_from_days(days: i64) -> (i64, i64, i64) {
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
(year, month, day)
|
||||
}
|
||||
|
||||
/// The day of the year (0-based) of an instant, in UTC.
|
||||
pub fn day_of_year(utc: i64) -> i64 {
|
||||
let days = utc.div_euclid(86_400);
|
||||
let (year, _, _) = civil_from_days(days);
|
||||
days - days_from_civil(year, 1, 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_dates_with_offsets() {
|
||||
let packet = br#"<x xmp:CreateDate="2020-03-01T10:00:00+01:00" xmp:ModifyDate="2020-07-01T10:00:00.25-04:00">
|
||||
<stEvt:when>2021-01-02T03:04:05Z</stEvt:when><xmp:MetadataDate>2020-01-01T00:00</xmp:MetadataDate></x>"#;
|
||||
let d = dates(packet);
|
||||
assert_eq!(d.len(), 3);
|
||||
assert_eq!(d[0].offset, 3600);
|
||||
assert_eq!(d[0].utc, days_from_civil(2020, 3, 1) * 86_400 + 9 * 3600);
|
||||
assert_eq!(d[1].offset, -4 * 3600);
|
||||
assert_eq!(d[2].offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_between_days_and_dates() {
|
||||
assert_eq!(days_from_civil(1970, 1, 1), 0);
|
||||
assert_eq!(civil_from_days(days_from_civil(2024, 2, 29)), (2024, 2, 29));
|
||||
assert_eq!(civil_from_days(days_from_civil(1601, 1, 1)), (1601, 1, 1));
|
||||
assert_eq!(day_of_year(days_from_civil(2023, 12, 31) * 86_400), 364);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user