use std::collections::{BTreeMap, BTreeSet};
use laminapdf_cos::{Dict, Object, Result};
use crate::annot::{Annot, ReplyType};
use crate::date::PdfDate;
use crate::document::Document;
use crate::id::{AnnotId, PageId};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct AnnotState {
pub model: StateModel,
pub state: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StateModel {
Review,
Marked,
Other(String),
}
impl StateModel {
fn from_text(text: &str) -> Self {
match text {
"Review" => Self::Review,
"Marked" => Self::Marked,
other => Self::Other(other.to_owned()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BrokenThread {
MissingParent,
Cycle,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ThreadMember {
pub page_index: usize,
pub annot: Annot,
}
impl BrokenThread {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::MissingParent => "missing-parent",
Self::Cycle => "cycle",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CommentThread {
pub page: PageId,
pub page_index: usize,
pub comment: Annot,
pub group: Vec<ThreadMember>,
pub replies: Vec<ThreadMember>,
pub states: Vec<ThreadMember>,
pub broken: Option<BrokenThread>,
}
impl CommentThread {
#[must_use]
pub fn latest_state(&self, model: &StateModel) -> Option<&Annot> {
self.latest_state_on(&self.comment.id, model)
}
#[must_use]
pub fn latest_state_on(&self, target: &AnnotId, model: &StateModel) -> Option<&Annot> {
self.states
.iter()
.map(|m| &m.annot)
.filter(|a| a.in_reply_to.as_ref() == Some(target))
.filter(|a| a.state.as_ref().is_some_and(|s| s.model == *model))
.reduce(|latest, a| if is_later(a, latest) { a } else { latest })
}
}
fn is_later(a: &Annot, than: &Annot) -> bool {
match (date(a), date(than)) {
(Some(a), Some(than)) => a >= than,
_ => true,
}
}
fn date(a: &Annot) -> Option<PdfDate> {
a.created
.as_deref()
.or(a.modified.as_deref())
.and_then(|d| d.parse().ok())
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
Comment,
Reply,
Group,
State,
}
fn role(a: &Annot) -> Role {
match (&a.in_reply_to, a.reply_type, &a.state) {
(None, _, _) => Role::Comment,
(Some(_), _, Some(_)) => Role::State,
(Some(_), ReplyType::Group, None) => Role::Group,
(Some(_), ReplyType::Reply, None) => Role::Reply,
}
}
impl Document {
pub fn comment_threads(&self) -> Result<Vec<CommentThread>> {
let pages = self.pages()?;
let mut all: Vec<(usize, PageId, Annot)> = Vec::new();
let mut others: BTreeSet<AnnotId> = BTreeSet::new();
for (index, page) in pages.iter().enumerate() {
for annot in self.annotations_unchecked(&page)? {
if annot.subtype.is_markup() {
all.push((index, page.id().clone(), annot));
} else {
others.insert(annot.id);
}
}
}
let position: BTreeMap<&AnnotId, usize> = all.iter().enumerate().map(|(i, (_, _, a))| (&a.id, i)).collect();
let starts: Vec<(usize, Option<BrokenThread>)> = (0..all.len())
.map(|i| thread_start(i, &all, &position, &others))
.collect();
let mut threads: Vec<CommentThread> = Vec::new();
let mut slot: BTreeMap<usize, usize> = BTreeMap::new();
for (i, (page_index, page, annot)) in all.iter().enumerate() {
let Some((start, broken)) = starts.get(i).copied() else {
continue;
};
if start != i {
continue;
}
slot.insert(i, threads.len());
threads.push(CommentThread {
page: page.clone(),
page_index: *page_index,
comment: annot.clone(),
group: Vec::new(),
replies: Vec::new(),
states: Vec::new(),
broken,
});
}
for (i, (page_index, _, annot)) in all.iter().enumerate() {
let Some(thread) = starts
.get(i)
.filter(|(start, _)| *start != i)
.and_then(|(start, _)| slot.get(start))
.and_then(|t| threads.get_mut(*t))
else {
continue;
};
let member = ThreadMember {
page_index: *page_index,
annot: annot.clone(),
};
match role(annot) {
Role::Group => thread.group.push(member),
Role::State => thread.states.push(member),
Role::Reply | Role::Comment => thread.replies.push(member),
}
}
Ok(threads)
}
pub(crate) fn annot_state(&self, dict: &Dict) -> Result<Option<AnnotState>> {
if dict.get("IRT").is_none() {
return Ok(None);
}
let model = self.name_or_text(dict.get("StateModel"))?;
let state = self.name_or_text(dict.get("State"))?;
Ok(match (model, state) {
(None, None) => None,
(Some(model), state) => {
let model = StateModel::from_text(&model);
let state = state.unwrap_or_else(|| default_state(&model).to_owned());
Some(AnnotState { model, state })
}
(None, Some(state)) => Some(AnnotState {
model: if matches!(state.as_str(), "Marked" | "Unmarked") {
StateModel::Marked
} else {
StateModel::Review
},
state,
}),
})
}
fn name_or_text(&self, value: Option<&Object>) -> Result<Option<String>> {
let Some(value) = value else { return Ok(None) };
Ok(match self.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(String::from_utf8_lossy(n.as_bytes()).into_owned()),
Some(Object::String(s)) => Some(laminapdf_syntax::text::decode_text_string(&s.bytes)),
_ => None,
})
}
}
const fn default_state(model: &StateModel) -> &'static str {
match model {
StateModel::Marked => "Unmarked",
StateModel::Review | StateModel::Other(_) => "None",
}
}
fn thread_start(
i: usize,
all: &[(usize, PageId, Annot)],
position: &BTreeMap<&AnnotId, usize>,
others: &BTreeSet<AnnotId>,
) -> (usize, Option<BrokenThread>) {
let mut seen = vec![i];
let mut at = i;
loop {
let Some(parent) = all.get(at).and_then(|(_, _, a)| a.in_reply_to.as_ref()) else {
return (at, None);
};
let Some(&next) = position.get(parent) else {
let broken = (!others.contains(parent)).then_some(BrokenThread::MissingParent);
return (at, broken);
};
if let Some(from) = seen.iter().position(|&s| s == next) {
let ring = seen.get(from..).unwrap_or_default();
return (ring.iter().copied().min().unwrap_or(next), Some(BrokenThread::Cycle));
}
seen.push(next);
at = next;
}
}