use laminapdf_cos::{Dict, Object, Result};
use crate::document::Document;
use crate::values::{array_items, name_bytes_text, read_name, text_of};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LockAction {
All,
Include,
Exclude,
}
impl LockAction {
pub const ALL: [Self; 3] = [Self::All, Self::Include, Self::Exclude];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::All => "all",
Self::Include => "include",
Self::Exclude => "exclude",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|a| a.as_str() == name)
}
#[must_use]
pub fn from_pdf_name(name: &[u8]) -> Option<Self> {
Self::ALL.into_iter().find(|a| a.pdf_name().as_bytes() == name)
}
#[must_use]
pub const fn pdf_name(self) -> &'static str {
match self {
Self::All => "All",
Self::Include => "Include",
Self::Exclude => "Exclude",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignatureLock {
pub action: LockAction,
pub fields: Vec<String>,
pub permission: Option<u8>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SeedEntry {
Filter,
SubFilter,
Reasons,
}
impl SeedEntry {
pub const ALL: [Self; 3] = [Self::Filter, Self::SubFilter, Self::Reasons];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Filter => "filter",
Self::SubFilter => "subFilter",
Self::Reasons => "reasons",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|e| e.as_str() == name)
}
#[must_use]
pub const fn flag(self) -> u32 {
match self {
Self::Filter => 1,
Self::SubFilter => 1 << 1,
Self::Reasons => 1 << 3,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SignatureSeed {
pub filter: Option<String>,
pub sub_filters: Vec<String>,
pub reasons: Vec<String>,
pub mdp: Option<u8>,
pub required: Vec<SeedEntry>,
}
pub(super) fn read_lock(doc: &Document, value: Option<&Object>) -> Result<Option<SignatureLock>> {
let Some(dict) = dict_of(doc, value)? else {
return Ok(None);
};
let action = read_name(doc, dict.get("Action"))?
.and_then(|name| LockAction::from_pdf_name(&name))
.unwrap_or(LockAction::All);
let listed = if action == LockAction::All {
Some(Vec::new())
} else {
names(doc, dict.get("Fields"))?
};
let (action, fields) = match listed {
Some(fields) => (action, fields),
None => (LockAction::All, Vec::new()),
};
let permission = small_number(doc, dict.get("P"), 1..=3)?;
Ok(Some(SignatureLock {
action,
fields,
permission,
}))
}
pub(super) fn read_seed(doc: &Document, value: Option<&Object>) -> Result<Option<SignatureSeed>> {
let Some(dict) = dict_of(doc, value)? else {
return Ok(None);
};
let filter = read_name(doc, dict.get("Filter"))?.map(|n| name_bytes_text(&n));
let mut sub_filters = Vec::new();
for item in array_items(doc, dict.get("SubFilter"))? {
if let Some(name) = read_name(doc, Some(&item))? {
sub_filters.push(name_bytes_text(&name));
}
}
let mut reasons = Vec::new();
for item in array_items(doc, dict.get("Reasons"))? {
if let Some(reason) = doc.read(&item)?.as_deref().and_then(text_of) {
reasons.push(reason);
}
}
let mdp = match dict_of(doc, dict.get("MDP"))? {
Some(mdp) => small_number(doc, mdp.get("P"), 0..=3)?,
None => None,
};
let ff = match dict.get("Ff") {
Some(ff) => doc.read(ff)?.and_then(|o| o.as_int()).unwrap_or(0),
None => 0,
};
let required = SeedEntry::ALL
.into_iter()
.filter(|e| ff & i64::from(e.flag()) != 0)
.collect();
Ok(Some(SignatureSeed {
filter,
sub_filters,
reasons,
mdp,
required,
}))
}
fn small_number(doc: &Document, value: Option<&Object>, range: std::ops::RangeInclusive<u8>) -> Result<Option<u8>> {
let Some(value) = value else { return Ok(None) };
Ok(doc
.read(value)?
.and_then(|o| o.as_int())
.and_then(|n| u8::try_from(n).ok())
.filter(|n| range.contains(n)))
}
fn dict_of(doc: &Document, value: Option<&Object>) -> Result<Option<Dict>> {
let Some(value) = value else { return Ok(None) };
Ok(doc.read(value)?.and_then(|o| o.as_dict().cloned()))
}
fn names(doc: &Document, value: Option<&Object>) -> Result<Option<Vec<String>>> {
let Some(value) = value else { return Ok(None) };
let Some(list) = doc.read(value)? else {
return Ok(None);
};
let Some(items) = list.as_array() else {
return Ok(None);
};
let mut out = Vec::with_capacity(items.len());
for item in items {
match doc.read(item)?.as_deref().and_then(text_of) {
Some(name) => out.push(name),
None => return Ok(None),
}
}
Ok(Some(out))
}
#[must_use]
pub fn is_signature_dictionary(dict: &Dict) -> bool {
matches!(dict.get_name("Type"), Some(b"Sig" | b"DocTimeStamp"))
|| (dict.get("ByteRange").and_then(Object::as_array).is_some()
&& matches!(dict.get("Contents"), Some(Object::String(_))))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_should_list_every_lock_action_once_in_declaration_order() {
let next = |v: LockAction| match v {
LockAction::All => Some(LockAction::Include),
LockAction::Include => Some(LockAction::Exclude),
LockAction::Exclude => None,
};
let mut chain = vec![LockAction::All];
while let Some(more) = chain.last().and_then(|v| next(*v)) {
chain.push(more);
}
assert_eq!(chain, LockAction::ALL);
}
#[test]
fn all_should_list_every_seed_entry_once_in_declaration_order() {
let next = |v: SeedEntry| match v {
SeedEntry::Filter => Some(SeedEntry::SubFilter),
SeedEntry::SubFilter => Some(SeedEntry::Reasons),
SeedEntry::Reasons => None,
};
let mut chain = vec![SeedEntry::Filter];
while let Some(more) = chain.last().and_then(|v| next(*v)) {
chain.push(more);
}
assert_eq!(chain, SeedEntry::ALL);
}
#[test]
fn from_pdf_name_should_read_every_action_and_nothing_else() {
let read = LockAction::ALL.map(|a| LockAction::from_pdf_name(a.pdf_name().as_bytes()));
assert_eq!(read, LockAction::ALL.map(Some));
assert_eq!(LockAction::from_pdf_name(b"Some"), None);
}
#[test]
fn a_signature_dictionary_needs_no_type() {
let untyped: Dict = [
("ByteRange", Object::Array(vec![0.into(), 1.into(), 2.into(), 3.into()])),
("Contents", Object::String(laminapdf_cos::PdfString::hex(vec![0]))),
]
.into_iter()
.collect();
let field: Dict = [("FT", Object::name("Sig"))].into_iter().collect();
assert_eq!(
(is_signature_dictionary(&untyped), is_signature_dictionary(&field)),
(true, false)
);
}
}