revenant-sign-core 3.0.5

Cross-platform client library for ARX CoSign / DocuSign Signature Appliance electronic signatures via the OASIS DSS SOAP API
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
//! Signature field positioning and page selection.
//!
//! Pure geometry: where to place the signature rectangle on a page given a
//! preset (`bottom-right`, `br`, ...) or explicit coordinates, and how to
//! resolve a user-facing page specifier (`first`, `last`, or a 1-based number)
//! to a concrete 0-based index. Reading actual page dimensions from a PDF lives
//! in [`super::reader`]; this module never touches a document.

use std::str::FromStr;

use crate::{Result, RevenantError};

// ── Signature field size defaults (PDF points) ──────────────────────────

/// Default signature field width (3:1 aspect, ~75 mm).
pub const SIG_WIDTH: f64 = 210.0;
/// Default signature field height (~25 mm).
pub const SIG_HEIGHT: f64 = 70.0;
/// Horizontal margin from the left/right page edge (~13 mm).
pub const SIG_MARGIN_H: f64 = 36.0;
/// Vertical margin from the top/bottom page edge (~21 mm).
pub const SIG_MARGIN_V: f64 = 60.0;

/// A signature placement preset, decomposed into an anchor corner/edge.
///
/// An exhaustive enum rather than free-form strings, so the geometry in
/// [`compute_sig_rect`] can never be reached with an unrecognized position name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Position {
    BottomRight,
    TopRight,
    BottomLeft,
    TopLeft,
    BottomCenter,
}

#[derive(Debug, Clone, Copy)]
enum Horizontal {
    Right,
    Left,
    Center,
}

#[derive(Debug, Clone, Copy)]
enum Vertical {
    Bottom,
    Top,
}

impl Position {
    fn horizontal(self) -> Horizontal {
        match self {
            Position::BottomRight | Position::TopRight => Horizontal::Right,
            Position::BottomLeft | Position::TopLeft => Horizontal::Left,
            Position::BottomCenter => Horizontal::Center,
        }
    }

    fn vertical(self) -> Vertical {
        match self {
            Position::BottomRight | Position::BottomLeft | Position::BottomCenter => {
                Vertical::Bottom
            }
            Position::TopRight | Position::TopLeft => Vertical::Top,
        }
    }

    /// The canonical preset name (e.g. `"bottom-right"`).
    #[must_use]
    pub fn canonical_name(self) -> &'static str {
        match self {
            Position::BottomRight => "bottom-right",
            Position::TopRight => "top-right",
            Position::BottomLeft => "bottom-left",
            Position::TopLeft => "top-left",
            Position::BottomCenter => "bottom-center",
        }
    }
}

/// Full preset names, sorted for stable error messages.
const PRESET_NAMES: [&str; 5] = [
    "bottom-center",
    "bottom-left",
    "bottom-right",
    "top-left",
    "top-right",
];

/// Short aliases -> canonical name, sorted by alias.
const ALIASES: [(&str, Position); 5] = [
    ("bc", Position::BottomCenter),
    ("bl", Position::BottomLeft),
    ("br", Position::BottomRight),
    ("tl", Position::TopLeft),
    ("tr", Position::TopRight),
];

impl FromStr for Position {
    type Err = RevenantError;

    /// Parse a placement preset from its canonical name (`bottom-right`, ...) or
    /// short alias (`br`, `tr`, `bl`, `tl`, `bc`), case-insensitively with
    /// surrounding whitespace trimmed.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] for an unrecognized position.
    fn from_str(s: &str) -> Result<Self> {
        let name = s.trim().to_lowercase();

        if let Some((_, pos)) = ALIASES.iter().find(|(alias, _)| *alias == name) {
            return Ok(*pos);
        }
        match name.as_str() {
            "bottom-right" => Ok(Position::BottomRight),
            "top-right" => Ok(Position::TopRight),
            "bottom-left" => Ok(Position::BottomLeft),
            "top-left" => Ok(Position::TopLeft),
            "bottom-center" => Ok(Position::BottomCenter),
            _ => {
                let aliases: Vec<&str> = ALIASES.iter().map(|(a, _)| *a).collect();
                let valid = [PRESET_NAMES.as_slice(), aliases.as_slice()]
                    .concat()
                    .join(", ");
                Err(RevenantError::Pdf(format!(
                    "Unknown position {s:?}. Valid: {valid}"
                )))
            }
        }
    }
}

// ── Page specifier ──────────────────────────────────────────────────────

/// A user-facing page selection: an edge keyword or a concrete 0-based index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageSpec {
    First,
    Last,
    /// 0-based page index.
    Index(usize),
}

impl FromStr for PageSpec {
    type Err = RevenantError;

    /// Parse a page specifier: `first`, `last`, or a 1-based page number
    /// (converted to a 0-based index), case-insensitively with surrounding
    /// whitespace trimmed.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if the specifier is not a keyword or a
    /// positive integer.
    fn from_str(s: &str) -> Result<Self> {
        let spec = s.trim().to_lowercase();
        if spec == "first" {
            return Ok(PageSpec::First);
        }
        if spec == "last" {
            return Ok(PageSpec::Last);
        }
        let page_num: i64 = spec.parse().map_err(|_| {
            RevenantError::Pdf(format!(
                "Invalid page: {s:?}. Use 'first', 'last', or a page number."
            ))
        })?;
        if page_num < 1 {
            return Err(RevenantError::Pdf(format!(
                "Page number must be 1 or greater, got {page_num}"
            )));
        }
        // 1-based -> 0-based; page_num >= 1 so the subtraction is non-negative.
        let idx = usize::try_from(page_num - 1)
            .map_err(|_| RevenantError::Pdf(format!("Page number too large: {page_num}")))?;
        Ok(PageSpec::Index(idx))
    }
}

/// Resolve a [`PageSpec`] to a concrete 0-based index against a page count.
///
/// # Errors
///
/// Returns [`RevenantError::Pdf`] if the resulting index is out of range, or if
/// the document reports zero pages.
pub fn resolve_page_index(spec: PageSpec, total_pages: usize) -> Result<usize> {
    if total_pages == 0 {
        return Err(RevenantError::Pdf("PDF has no pages.".to_owned()));
    }
    let idx = match spec {
        PageSpec::First => 0,
        PageSpec::Last => total_pages - 1,
        PageSpec::Index(i) => i,
    };
    if idx >= total_pages {
        return Err(RevenantError::Pdf(format!(
            "Page {idx} out of range (PDF has {total_pages} page(s), 0-based)."
        )));
    }
    Ok(idx)
}

// ── Rectangle computation ───────────────────────────────────────────────

/// A signature rectangle in PDF coordinate space (origin = bottom-left).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SigRect {
    pub x: f64,
    pub y: f64,
    pub w: f64,
    pub h: f64,
}

/// Compute the signature rectangle for a page, given its dimensions and a preset.
///
/// # Errors
///
/// Returns [`RevenantError::Pdf`] if the page or signature dimensions are
/// non-positive, or if the signature does not fit on the page (negative
/// computed origin).
pub fn compute_sig_rect(
    page_width: f64,
    page_height: f64,
    position: Position,
    sig_w: f64,
    sig_h: f64,
    margin_h: f64,
    margin_v: f64,
) -> Result<SigRect> {
    if page_width <= 0.0 || page_height <= 0.0 {
        return Err(RevenantError::Pdf(format!(
            "Invalid page dimensions: {page_width:.1} x {page_height:.1} pt"
        )));
    }
    if sig_w <= 0.0 || sig_h <= 0.0 {
        return Err(RevenantError::Pdf(format!(
            "Invalid signature dimensions: {sig_w:.1} x {sig_h:.1} pt"
        )));
    }

    let x = match position.horizontal() {
        Horizontal::Right => page_width - margin_h - sig_w,
        Horizontal::Left => margin_h,
        Horizontal::Center => (page_width - sig_w) / 2.0,
    };
    let y = match position.vertical() {
        Vertical::Bottom => margin_v,
        Vertical::Top => page_height - margin_v - sig_h,
    };

    // The stamp must fit entirely within the page. A non-negative origin is not
    // sufficient: a fixed-size stamp on a very small page can clear the near edge
    // yet overrun the far one (e.g. a multi-line stamp taller than a short page
    // overflows the top edge, which a `y < 0` check alone misses). Check all four
    // bounds so such a page is rejected rather than emitting a clipped appearance.
    if x < 0.0 || y < 0.0 || x + sig_w > page_width || y + sig_h > page_height {
        return Err(RevenantError::Pdf(format!(
            "Signature does not fit on page: rect ({x:.1}, {y:.1}) size {sig_w:.0}x{sig_h:.0} pt \
             exceeds the page. Page: {page_width:.0}x{page_height:.0} pt, \
             margins: {margin_h:.0}x{margin_v:.0} pt"
        )));
    }

    Ok(SigRect {
        x,
        y,
        w: sig_w,
        h: sig_h,
    })
}

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

    #[test]
    fn resolves_aliases_and_full_names() {
        assert_eq!("br".parse::<Position>().unwrap(), Position::BottomRight);
        assert_eq!("  BR ".parse::<Position>().unwrap(), Position::BottomRight);
        assert_eq!(
            "bottom-right".parse::<Position>().unwrap(),
            Position::BottomRight
        );
        assert_eq!("TL".parse::<Position>().unwrap(), Position::TopLeft);
        assert_eq!(
            "bottom-center".parse::<Position>().unwrap(),
            Position::BottomCenter
        );
    }

    #[test]
    fn rejects_unknown_position() {
        let err = "middle".parse::<Position>().unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Unknown position"), "{msg}");
        assert!(msg.contains("bottom-right"), "{msg}");
        assert!(msg.contains("br"), "{msg}");
    }

    #[test]
    fn bottom_right_rectangle() {
        // A4-ish page 595x842.
        let r = compute_sig_rect(
            595.0,
            842.0,
            Position::BottomRight,
            SIG_WIDTH,
            SIG_HEIGHT,
            SIG_MARGIN_H,
            SIG_MARGIN_V,
        )
        .unwrap();
        assert!((r.x - (595.0 - 36.0 - 210.0)).abs() < 1e-9);
        assert!((r.y - 60.0).abs() < 1e-9);
        assert!((r.w - SIG_WIDTH).abs() < 1e-9);
        assert!((r.h - SIG_HEIGHT).abs() < 1e-9);
    }

    #[test]
    fn top_left_rectangle() {
        let r = compute_sig_rect(
            595.0,
            842.0,
            Position::TopLeft,
            SIG_WIDTH,
            SIG_HEIGHT,
            SIG_MARGIN_H,
            SIG_MARGIN_V,
        )
        .unwrap();
        assert!((r.x - 36.0).abs() < 1e-9);
        assert!((r.y - (842.0 - 60.0 - 70.0)).abs() < 1e-9);
    }

    #[test]
    fn center_is_horizontally_centered() {
        let r = compute_sig_rect(
            600.0,
            800.0,
            Position::BottomCenter,
            200.0,
            70.0,
            36.0,
            60.0,
        )
        .unwrap();
        assert!((r.x - 200.0).abs() < 1e-9); // (600 - 200) / 2
    }

    #[test]
    fn rejects_signature_larger_than_page() {
        let err = compute_sig_rect(
            100.0,
            100.0,
            Position::BottomRight,
            SIG_WIDTH,
            SIG_HEIGHT,
            SIG_MARGIN_H,
            SIG_MARGIN_V,
        )
        .unwrap_err();
        assert!(err.to_string().contains("does not fit"), "{err}");
    }

    #[test]
    fn rejects_stamp_overrunning_far_edge() {
        // The near edges clear (x = margin >= 0, y = margin >= 0) but the stamp
        // is taller than the short page, so it overruns the top edge. A
        // `x < 0 || y < 0` check alone would wrongly accept this and emit a
        // clipped appearance; the full bounds check must reject it.
        let err = compute_sig_rect(
            250.0,
            100.0,
            Position::BottomLeft,
            SIG_WIDTH,
            SIG_HEIGHT,
            SIG_MARGIN_H,
            SIG_MARGIN_V,
        )
        .unwrap_err();
        assert!(err.to_string().contains("does not fit"), "{err}");
    }

    #[test]
    fn rejects_invalid_page_dimensions() {
        let err = compute_sig_rect(
            0.0,
            800.0,
            Position::BottomRight,
            SIG_WIDTH,
            SIG_HEIGHT,
            SIG_MARGIN_H,
            SIG_MARGIN_V,
        )
        .unwrap_err();
        assert!(err.to_string().contains("Invalid page dimensions"), "{err}");
    }

    #[test]
    fn parses_page_specs() {
        assert_eq!("first".parse::<PageSpec>().unwrap(), PageSpec::First);
        assert_eq!(" LAST ".parse::<PageSpec>().unwrap(), PageSpec::Last);
        assert_eq!("1".parse::<PageSpec>().unwrap(), PageSpec::Index(0));
        assert_eq!("5".parse::<PageSpec>().unwrap(), PageSpec::Index(4));
    }

    #[test]
    fn rejects_bad_page_specs() {
        assert!("zero"
            .parse::<PageSpec>()
            .unwrap_err()
            .to_string()
            .contains("Invalid page"));
        assert!("0"
            .parse::<PageSpec>()
            .unwrap_err()
            .to_string()
            .contains("1 or greater"));
    }

    #[test]
    fn resolves_page_index() {
        assert_eq!(resolve_page_index(PageSpec::First, 3).unwrap(), 0);
        assert_eq!(resolve_page_index(PageSpec::Last, 3).unwrap(), 2);
        assert_eq!(resolve_page_index(PageSpec::Index(1), 3).unwrap(), 1);
        assert!(resolve_page_index(PageSpec::Index(3), 3).is_err());
        assert!(resolve_page_index(PageSpec::First, 0).is_err());
    }
}