cdx-core 0.7.1

Core library for reading, writing, and validating Codex Document Format (.cdx) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Precise layout presentation layer.
//!
//! Precise layouts provide exact coordinates for every element, enabling
//! pixel-perfect reproduction regardless of rendering implementation.
//! They are **required** for FROZEN and PUBLISHED documents.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::paginated::Margins;
use super::style::Transform;

/// Precise layout for a specific page format.
///
/// Precise layouts store exact positions for all elements, ensuring
/// identical rendering across different implementations. This is
/// required for documents in FROZEN or PUBLISHED state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreciseLayout {
    /// Format version.
    pub version: String,

    /// Presentation type (always "precise").
    pub presentation_type: String,

    /// Target page format name (e.g., "letter", "a4", "legal", "custom").
    pub target_format: String,

    /// Exact page dimensions.
    pub page_size: PrecisePageSize,

    /// Hash of the semantic content layer when this layout was generated.
    /// Used to detect staleness when content changes.
    /// Note: The document ID covers semantic content only; this layout hash
    /// can be included in scoped signatures for layout attestation.
    pub content_hash: String,

    /// Timestamp when this layout was generated.
    pub generated_at: DateTime<Utc>,

    /// Optional page template for headers/footers/margins.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_template: Option<PageTemplate>,

    /// Page definitions with precise element positions.
    pub pages: Vec<PrecisePage>,

    /// Font metrics for exact text reproduction.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub fonts: HashMap<String, FontMetrics>,
}

impl PreciseLayout {
    /// Create a new precise layout for US Letter format.
    #[must_use]
    pub fn new_letter(content_hash: impl Into<String>) -> Self {
        Self {
            version: crate::SPEC_VERSION.to_string(),
            presentation_type: "precise".to_string(),
            target_format: "letter".to_string(),
            page_size: PrecisePageSize::letter(),
            content_hash: content_hash.into(),
            generated_at: Utc::now(),
            page_template: None,
            pages: Vec::new(),
            fonts: HashMap::new(),
        }
    }

    /// Create a new precise layout for A4 format.
    #[must_use]
    pub fn new_a4(content_hash: impl Into<String>) -> Self {
        Self {
            version: crate::SPEC_VERSION.to_string(),
            presentation_type: "precise".to_string(),
            target_format: "a4".to_string(),
            page_size: PrecisePageSize::a4(),
            content_hash: content_hash.into(),
            generated_at: Utc::now(),
            page_template: None,
            pages: Vec::new(),
            fonts: HashMap::new(),
        }
    }

    /// Create a new precise layout for US Legal format.
    #[must_use]
    pub fn new_legal(content_hash: impl Into<String>) -> Self {
        Self {
            version: crate::SPEC_VERSION.to_string(),
            presentation_type: "precise".to_string(),
            target_format: "legal".to_string(),
            page_size: PrecisePageSize::legal(),
            content_hash: content_hash.into(),
            generated_at: Utc::now(),
            page_template: None,
            pages: Vec::new(),
            fonts: HashMap::new(),
        }
    }

    /// Check if this layout is stale (content has changed).
    #[must_use]
    pub fn is_stale(&self, current_content_hash: &str) -> bool {
        self.content_hash != current_content_hash
    }

    /// Add a page to this layout.
    pub fn add_page(&mut self, page: PrecisePage) {
        self.pages.push(page);
    }

    /// Set the page template.
    #[must_use]
    pub fn with_template(mut self, template: PageTemplate) -> Self {
        self.page_template = Some(template);
        self
    }

    /// Add font metrics.
    #[must_use]
    pub fn with_font(mut self, name: impl Into<String>, metrics: FontMetrics) -> Self {
        self.fonts.insert(name.into(), metrics);
        self
    }
}

/// Exact page dimensions for precise layouts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrecisePageSize {
    /// Page width with units (e.g., "8.5in", "210mm").
    pub width: String,
    /// Page height with units (e.g., "11in", "297mm").
    pub height: String,
}

impl PrecisePageSize {
    /// US Letter size (8.5 x 11 in).
    #[must_use]
    pub fn letter() -> Self {
        Self {
            width: "8.5in".to_string(),
            height: "11in".to_string(),
        }
    }

    /// US Legal size (8.5 x 14 in).
    #[must_use]
    pub fn legal() -> Self {
        Self {
            width: "8.5in".to_string(),
            height: "14in".to_string(),
        }
    }

    /// A4 size (210 x 297 mm).
    #[must_use]
    pub fn a4() -> Self {
        Self {
            width: "210mm".to_string(),
            height: "297mm".to_string(),
        }
    }

    /// A5 size (148 x 210 mm).
    #[must_use]
    pub fn a5() -> Self {
        Self {
            width: "148mm".to_string(),
            height: "210mm".to_string(),
        }
    }

    /// Custom page size.
    #[must_use]
    pub fn custom(width: impl Into<String>, height: impl Into<String>) -> Self {
        Self {
            width: width.into(),
            height: height.into(),
        }
    }
}

/// Page template for headers, footers, and margins.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PageTemplate {
    /// Page margins.
    pub margins: Margins,

    /// Header region.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub header: Option<PageRegion>,

    /// Footer region.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub footer: Option<PageRegion>,
}

impl PageTemplate {
    /// Create a template with default margins and no header/footer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set custom margins.
    #[must_use]
    pub fn with_margins(mut self, margins: Margins) -> Self {
        self.margins = margins;
        self
    }

    /// Set header region.
    #[must_use]
    pub fn with_header(mut self, header: PageRegion) -> Self {
        self.header = Some(header);
        self
    }

    /// Set footer region.
    #[must_use]
    pub fn with_footer(mut self, footer: PageRegion) -> Self {
        self.footer = Some(footer);
        self
    }
}

/// Header or footer region.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PageRegion {
    /// Content template. Supports placeholders:
    /// - `{pageNumber}` - Current page number
    /// - `{totalPages}` - Total page count
    pub content: String,

    /// Y position from top of page.
    pub y: String,

    /// Style name to apply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<String>,
}

impl PageRegion {
    /// Create a new page region.
    #[must_use]
    pub fn new(content: impl Into<String>, y: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            y: y.into(),
            style: None,
        }
    }

    /// Create a page number footer.
    #[must_use]
    pub fn page_number_footer(y: impl Into<String>) -> Self {
        Self {
            content: "Page {pageNumber} of {totalPages}".to_string(),
            y: y.into(),
            style: Some("footer".to_string()),
        }
    }

    /// Set style name.
    #[must_use]
    pub fn with_style(mut self, style: impl Into<String>) -> Self {
        self.style = Some(style.into());
        self
    }
}

/// A page in a precise layout.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrecisePage {
    /// Page number (1-indexed).
    pub number: u32,

    /// Precisely positioned elements on this page.
    #[serde(default)]
    pub elements: Vec<PrecisePageElement>,
}

impl PrecisePage {
    /// Create a new page with the given number.
    #[must_use]
    pub fn new(number: u32) -> Self {
        Self {
            number,
            elements: Vec::new(),
        }
    }

    /// Add an element to this page.
    pub fn add_element(&mut self, element: PrecisePageElement) {
        self.elements.push(element);
    }

    /// Add an element and return self for chaining.
    #[must_use]
    pub fn with_element(mut self, element: PrecisePageElement) -> Self {
        self.elements.push(element);
        self
    }
}

/// A precisely positioned element on a page.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PrecisePageElement {
    /// Reference to content block ID.
    pub block_id: String,

    /// Horizontal position from left edge.
    pub x: String,

    /// Vertical position from top edge.
    pub y: String,

    /// Element width.
    pub width: String,

    /// Element height.
    pub height: String,

    /// True if this element continues to the next page.
    #[serde(default, skip_serializing_if = "is_false")]
    pub continues: bool,

    /// True if this element is continued from the previous page.
    #[serde(default, skip_serializing_if = "is_false")]
    pub continuation: bool,

    /// Line-level precision for legal documents.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lines: Vec<LineInfo>,

    /// 2D transform for rotation, scale, skew.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transform: Option<Transform>,
}

#[allow(clippy::trivially_copy_pass_by_ref)] // Required by serde skip_serializing_if
fn is_false(b: &bool) -> bool {
    !*b
}

impl PrecisePageElement {
    /// Create a new element with precise positioning.
    #[must_use]
    pub fn new(
        block_id: impl Into<String>,
        x: impl Into<String>,
        y: impl Into<String>,
        width: impl Into<String>,
        height: impl Into<String>,
    ) -> Self {
        Self {
            block_id: block_id.into(),
            x: x.into(),
            y: y.into(),
            width: width.into(),
            height: height.into(),
            continues: false,
            continuation: false,
            lines: Vec::new(),
            transform: None,
        }
    }

    /// Set the transform for this element.
    #[must_use]
    pub fn with_transform(mut self, transform: Transform) -> Self {
        self.transform = Some(transform);
        self
    }

    /// Mark this element as continuing to the next page.
    #[must_use]
    pub fn continues(mut self) -> Self {
        self.continues = true;
        self
    }

    /// Mark this element as a continuation from the previous page.
    #[must_use]
    pub fn continuation(mut self) -> Self {
        self.continuation = true;
        self
    }

    /// Add line-level precision information.
    #[must_use]
    pub fn with_lines(mut self, lines: Vec<LineInfo>) -> Self {
        self.lines = lines;
        self
    }
}

/// Line-level precision for legal documents.
///
/// Optional - only needed for legal/court documents where line numbers
/// are referenced (e.g., "page 7, line 23").
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LineInfo {
    /// Line number (1-indexed within the block).
    pub number: u32,

    /// Y position of this line.
    pub y: String,

    /// Height of this line.
    pub height: String,
}

impl LineInfo {
    /// Create line information.
    #[must_use]
    pub fn new(number: u32, y: impl Into<String>, height: impl Into<String>) -> Self {
        Self {
            number,
            y: y.into(),
            height: height.into(),
        }
    }
}

/// Font metrics for exact text reproduction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FontMetrics {
    /// Font family name.
    pub family: String,

    /// Font style (normal, italic).
    #[serde(default = "default_font_style")]
    pub style: String,

    /// Font weight (100-900).
    #[serde(default = "default_font_weight")]
    pub weight: u16,

    /// Units per em.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub units_per_em: Option<u16>,

    /// Ascender height in font units.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ascender: Option<i32>,

    /// Descender depth in font units (typically negative).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub descender: Option<i32>,
}

fn default_font_style() -> String {
    "normal".to_string()
}

fn default_font_weight() -> u16 {
    400
}

impl FontMetrics {
    /// Create font metrics for a font family.
    #[must_use]
    pub fn new(family: impl Into<String>) -> Self {
        Self {
            family: family.into(),
            style: default_font_style(),
            weight: default_font_weight(),
            units_per_em: None,
            ascender: None,
            descender: None,
        }
    }

    /// Set font style.
    #[must_use]
    pub fn with_style(mut self, style: impl Into<String>) -> Self {
        self.style = style.into();
        self
    }

    /// Set font weight.
    #[must_use]
    pub fn with_weight(mut self, weight: u16) -> Self {
        self.weight = weight;
        self
    }

    /// Set detailed font metrics.
    #[must_use]
    pub fn with_metrics(mut self, units_per_em: u16, ascender: i32, descender: i32) -> Self {
        self.units_per_em = Some(units_per_em);
        self.ascender = Some(ascender);
        self.descender = Some(descender);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_precise_layout_new() {
        let layout = PreciseLayout::new_letter("sha256:abc123");
        assert_eq!(layout.presentation_type, "precise");
        assert_eq!(layout.target_format, "letter");
        assert_eq!(layout.page_size.width, "8.5in");
        assert_eq!(layout.page_size.height, "11in");
        assert_eq!(layout.content_hash, "sha256:abc123");
    }

    #[test]
    fn test_staleness_detection() {
        let layout = PreciseLayout::new_letter("sha256:abc123");
        assert!(!layout.is_stale("sha256:abc123"));
        assert!(layout.is_stale("sha256:xyz789"));
    }

    #[test]
    fn test_page_element_continuation() {
        let elem = PrecisePageElement::new("block-1", "1in", "2in", "6in", "3in").continues();
        assert!(elem.continues);
        assert!(!elem.continuation);

        let next = PrecisePageElement::new("block-1", "1in", "1in", "6in", "1in").continuation();
        assert!(!next.continues);
        assert!(next.continuation);
    }

    #[test]
    fn test_line_level_precision() {
        let lines = vec![
            LineInfo::new(1, "3in", "0.2in"),
            LineInfo::new(2, "3.25in", "0.2in"),
            LineInfo::new(3, "3.5in", "0.2in"),
        ];
        let elem =
            PrecisePageElement::new("block-5", "1in", "3in", "6.5in", "1.5in").with_lines(lines);
        assert_eq!(elem.lines.len(), 3);
        assert_eq!(elem.lines[0].number, 1);
    }

    #[test]
    fn test_serialization() {
        let mut layout = PreciseLayout::new_letter("sha256:abc123");
        layout.add_page(PrecisePage::new(1).with_element(PrecisePageElement::new(
            "block-1", "1in", "1in", "6.5in", "0.5in",
        )));

        let json = serde_json::to_string_pretty(&layout).unwrap();
        assert!(json.contains("\"presentationType\": \"precise\""));
        assert!(json.contains("\"targetFormat\": \"letter\""));
        assert!(json.contains("\"blockId\": \"block-1\""));
    }

    #[test]
    fn test_page_template() {
        let template = PageTemplate::new()
            .with_margins(Margins::all("1.5in"))
            .with_footer(PageRegion::page_number_footer("10.5in"));

        assert_eq!(template.margins.top, "1.5in");
        assert!(template.footer.is_some());
        assert!(template.header.is_none());
    }

    #[test]
    fn test_font_metrics() {
        let metrics = FontMetrics::new("Times New Roman")
            .with_weight(700)
            .with_metrics(2048, 1825, -443);

        assert_eq!(metrics.family, "Times New Roman");
        assert_eq!(metrics.weight, 700);
        assert_eq!(metrics.units_per_em, Some(2048));
    }
}