use std::collections::BTreeSet;
use laminapdf_cos::{Dict, ObjRef, Object, Result};
use super::{FieldFlags, Form, TerminalField};
use crate::document::Document;
use crate::id::{AnnotId, FieldId};
use crate::outline::Outline;
use crate::values::text_of;
const MAX_ACTIONS: usize = 64;
const MAX_TARGETS: usize = 10_000;
pub const MAX_ADDRESS_LEN: usize = 8 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ActionTrigger {
Click,
MouseDown,
MouseEnter,
MouseExit,
Focus,
Blur,
}
impl ActionTrigger {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Click => "click",
Self::MouseDown => "mouseDown",
Self::MouseEnter => "mouseEnter",
Self::MouseExit => "mouseExit",
Self::Focus => "focus",
Self::Blur => "blur",
}
}
const AA: [(&'static str, Self); 6] = [
("U", Self::Click),
("D", Self::MouseDown),
("E", Self::MouseEnter),
("X", Self::MouseExit),
("Fo", Self::Focus),
("Bl", Self::Blur),
];
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NamedAction {
NextPage,
PrevPage,
FirstPage,
LastPage,
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HideTarget {
Field(FieldId),
Annotation(AnnotId),
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct FieldSelection {
pub names: Vec<String>,
pub exclude: bool,
}
impl FieldSelection {
#[must_use]
pub const fn new(names: Vec<String>, exclude: bool) -> Self {
Self { names, exclude }
}
#[must_use]
pub fn covers(&self, name: &str) -> bool {
if self.names.is_empty() {
return true;
}
let listed = self
.names
.iter()
.any(|n| name == n || name.strip_prefix(n.as_str()).is_some_and(|rest| rest.starts_with('.')));
listed != self.exclude
}
#[must_use]
pub fn fields<'f>(&self, form: &'f Form) -> Vec<&'f TerminalField> {
form.fields
.iter()
.filter(|f| f.takes_value() && self.covers(&f.name))
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct SubmitFlags(pub u32);
impl SubmitFlags {
pub const EXCLUDE: u32 = 1;
pub const INCLUDE_NO_VALUE_FIELDS: u32 = 1 << 1;
pub const EXPORT_FORMAT: u32 = 1 << 2;
pub const GET_METHOD: u32 = 1 << 3;
pub const XFDF: u32 = 1 << 5;
pub const SUBMIT_PDF: u32 = 1 << 8;
#[must_use]
pub const fn has(self, flag: u32) -> bool {
self.0 & flag != 0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SubmitForm {
pub url: String,
pub flags: SubmitFlags,
pub selection: FieldSelection,
}
impl SubmitForm {
#[must_use]
pub const fn new(url: String, flags: SubmitFlags, selection: FieldSelection) -> Self {
Self { url, flags, selection }
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FormAction {
GoTo {
page_index: Option<usize>,
},
Named(NamedAction),
Uri(String),
ResetForm(FieldSelection),
Hide {
targets: Vec<HideTarget>,
hide: bool,
},
SubmitForm(SubmitForm),
ImportData,
JavaScript,
Launch,
GoToR,
GoToE,
Other(String),
}
impl FormAction {
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::GoTo { .. } => "GoTo",
Self::Named(_) => "Named",
Self::Uri(_) => "URI",
Self::ResetForm(_) => "ResetForm",
Self::Hide { .. } => "Hide",
Self::SubmitForm(_) => "SubmitForm",
Self::ImportData => "ImportData",
Self::JavaScript => "JavaScript",
Self::Launch => "Launch",
Self::GoToR => "GoToR",
Self::GoToE => "GoToE",
Self::Other(name) => name,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct FieldAction {
pub trigger: ActionTrigger,
pub action: FormAction,
}
impl Document {
pub fn form_actions(&self, field: &TerminalField) -> Result<Vec<FieldAction>> {
let mut out = Vec::new();
let mut seen = BTreeSet::new();
let mut owners: Vec<ObjRef> = field
.widgets
.iter()
.filter_map(|w| w.id.as_lamina_id().obj_ref())
.collect();
owners.extend(field.id.as_lamina_id().obj_ref().filter(|r| !owners.contains(r)));
let form = self.form()?;
let outline = Outline::destinations_only(self);
for owner in owners {
let Some(dict) = self.read(&Object::Ref(owner))?.and_then(|o| o.as_dict().cloned()) else {
continue;
};
if let Some(a) = dict.get("A") {
self.action_chain(a, ActionTrigger::Click, &form, &outline, &mut seen, &mut out)?;
}
let Some(aa) = dict.get("AA") else { continue };
let Some(aa) = self.read(aa)?.and_then(|o| o.as_dict().cloned()) else {
continue;
};
for (key, trigger) in ActionTrigger::AA {
if let Some(a) = aa.get(key) {
self.action_chain(a, trigger, &form, &outline, &mut seen, &mut out)?;
}
}
}
Ok(out)
}
fn action_chain(
&self,
start: &Object,
trigger: ActionTrigger,
form: &Form,
outline: &Outline<'_>,
seen: &mut BTreeSet<u32>,
out: &mut Vec<FieldAction>,
) -> Result<()> {
let mut stack = vec![start.clone()];
while let Some(obj) = stack.pop() {
if out.len() >= MAX_ACTIONS {
return Ok(());
}
if let Some(r) = obj.as_ref()
&& !seen.insert(r.num)
{
continue;
}
let Some(action) = self.read(&obj)? else { continue };
if let Some(items) = action.as_array() {
stack.extend(items.iter().rev().cloned());
continue;
}
let Some(dict) = action.as_dict() else { continue };
let Some(kind) = dict.get_name("S") else { continue };
out.push(FieldAction {
trigger,
action: self.typed_action(kind, dict, form, outline)?,
});
if let Some(next) = dict.get("Next") {
stack.push(next.clone());
}
}
Ok(())
}
fn typed_action(&self, kind: &[u8], dict: &Dict, form: &Form, outline: &Outline<'_>) -> Result<FormAction> {
Ok(match kind {
b"GoTo" => FormAction::GoTo {
page_index: match dict.get("D") {
Some(d) => outline.destination(d)?.and_then(|d| d.page_index),
None => None,
},
},
b"Named" => FormAction::Named(match dict.get_name("N") {
Some(b"NextPage") => NamedAction::NextPage,
Some(b"PrevPage") => NamedAction::PrevPage,
Some(b"FirstPage") => NamedAction::FirstPage,
Some(b"LastPage") => NamedAction::LastPage,
other => NamedAction::Other(String::from_utf8_lossy(other.unwrap_or_default()).into_owned()),
}),
b"URI" => FormAction::Uri(match dict.get("URI") {
Some(u) => self.address(u)?.unwrap_or_default(),
None => String::new(),
}),
b"ResetForm" => FormAction::ResetForm(self.selection(dict, 1 << 0, form)?),
b"Hide" => FormAction::Hide {
targets: self.hide_targets(dict, form)?,
hide: match dict.get("H") {
Some(h) => !matches!(self.read(h)?.as_deref(), Some(Object::Bool(false))),
None => true,
},
},
b"SubmitForm" => {
let flags = SubmitFlags(u32::try_from(dict.get_int("Flags").unwrap_or(0)).unwrap_or(0));
FormAction::SubmitForm(SubmitForm {
url: match dict.get("F") {
Some(f) => self.file_address(f)?.unwrap_or_default(),
None => String::new(),
},
selection: self.selection(dict, SubmitFlags::EXCLUDE, form)?,
flags,
})
}
b"ImportData" => FormAction::ImportData,
b"JavaScript" => FormAction::JavaScript,
b"Launch" => FormAction::Launch,
b"GoToR" => FormAction::GoToR,
b"GoToE" => FormAction::GoToE,
other => FormAction::Other(String::from_utf8_lossy(other).into_owned()),
})
}
fn address(&self, value: &Object) -> Result<Option<String>> {
Ok(match self.read(value)?.as_deref() {
Some(Object::String(s)) if s.bytes.len() <= MAX_ADDRESS_LEN => {
Some(String::from_utf8_lossy(&s.bytes).trim().to_owned())
}
_ => None,
})
}
fn file_address(&self, value: &Object) -> Result<Option<String>> {
let Some(resolved) = self.read(value)? else {
return Ok(None);
};
match &*resolved {
Object::String(_) => self.address(&resolved),
Object::Dict(d) => match d.get("F") {
Some(f) => self.address(f),
None => Ok(None),
},
_ => Ok(None),
}
}
fn selection(&self, dict: &Dict, exclude_bit: u32, form: &Form) -> Result<FieldSelection> {
let flags = u32::try_from(dict.get_int("Flags").unwrap_or(0)).unwrap_or(0);
let mut names = Vec::new();
if let Some(fields) = dict.get("Fields")
&& let Some(fields) = self.read(fields)?
{
let items: Vec<Object> = match fields.as_array() {
Some(items) => items.to_vec(),
None => vec![(*fields).clone()],
};
for item in items.iter().take(MAX_TARGETS) {
if let Some(name) = self.entry_name(item, form)? {
names.push(name);
}
}
}
Ok(FieldSelection {
names,
exclude: flags & exclude_bit != 0,
})
}
fn entry_name(&self, item: &Object, form: &Form) -> Result<Option<String>> {
if let Some(r) = item.as_ref() {
if let Some(f) = form.fields.iter().find(|f| {
f.id.as_lamina_id().obj_ref() == Some(r)
|| f.shared.iter().any(|s| s.as_lamina_id().obj_ref() == Some(r))
}) {
return Ok(Some(f.name.clone()));
}
return self.field_name(r);
}
Ok(self.read(item)?.and_then(|o| text_of(&o)))
}
fn hide_targets(&self, dict: &Dict, form: &Form) -> Result<Vec<HideTarget>> {
let Some(t) = dict.get("T") else { return Ok(Vec::new()) };
let Some(resolved) = self.read(t)? else {
return Ok(Vec::new());
};
let items: Vec<Object> = match resolved.as_array() {
Some(items) => items.to_vec(),
None => vec![t.clone()],
};
let mut out = Vec::new();
for item in items.iter().take(MAX_TARGETS) {
if let Some(r) = item.as_ref() {
let by_widget = form
.fields
.iter()
.find(|f| f.widgets.iter().any(|w| w.id.as_lamina_id().obj_ref() == Some(r)));
let target = match by_widget {
Some(f) => Some(HideTarget::Field(f.id.clone())),
None => match self.entry_name(item, form)? {
Some(name) => form.field_named(&name).map(|f| HideTarget::Field(f.id.clone())),
None => None,
},
};
out.push(target.unwrap_or_else(|| HideTarget::Annotation(AnnotId::object(r))));
} else if let Some(name) = self.read(item)?.and_then(|o| text_of(&o))
&& let Some(f) = form.field_named(&name)
{
out.push(HideTarget::Field(f.id.clone()));
}
}
Ok(out)
}
}
impl TerminalField {
#[must_use]
pub const fn no_export(&self) -> bool {
self.flags.has(FieldFlags::NO_EXPORT)
}
}