use laminapdf_cos::{Dict, Object, Result};
use crate::document::Document;
use crate::id::AttachmentId;
use crate::values::{read_name, text_of};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum CollectionView {
#[default]
Details,
Tile,
Hidden,
Custom,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CollectionFieldKind {
Text,
Date,
Number,
FileName,
Description,
Modified,
Created,
Size,
CompressedSize,
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionField {
pub key: String,
pub name: Option<String>,
pub kind: CollectionFieldKind,
pub order: Option<i64>,
pub visible: bool,
pub editable: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum CollectionValue {
Text(String),
Number(f64),
}
impl Eq for CollectionValue {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CollectionFile {
pub attachment: AttachmentId,
pub key: String,
pub values: Vec<(String, CollectionValue)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Collection {
pub schema: Vec<CollectionField>,
pub sort: Vec<(String, bool)>,
pub view: CollectionView,
pub initial: Option<String>,
pub files: Vec<CollectionFile>,
}
impl Document {
pub fn collection(&self) -> Result<Option<Collection>> {
let catalog = self.catalog()?;
let Some(value) = catalog.get("Collection") else {
return Ok(None);
};
let Some(collection) = self.read(value)? else {
return Ok(None);
};
let Some(collection) = collection.as_dict() else {
return Ok(None);
};
let mut out = Collection {
schema: self.collection_schema(collection)?,
sort: self.collection_sort(collection)?,
view: match read_name(self, collection.get("View"))?.as_deref() {
Some(b"T") => CollectionView::Tile,
Some(b"H") => CollectionView::Hidden,
Some(b"C") => CollectionView::Custom,
_ => CollectionView::Details,
},
initial: match collection.get("D") {
Some(d) => self.read(d)?.as_deref().and_then(text_of),
None => None,
},
files: Vec::new(),
};
for found in self.found_attachments()? {
let Some(key) = found.attachment.key else { continue };
out.files.push(CollectionFile {
attachment: found.attachment.id,
key,
values: self.collection_item(&found.spec)?,
});
}
Ok(Some(out))
}
fn collection_schema(&self, collection: &Dict) -> Result<Vec<CollectionField>> {
let Some(schema) = collection.get("Schema") else {
return Ok(Vec::new());
};
let Some(schema) = self.read(schema)? else {
return Ok(Vec::new());
};
let mut fields = Vec::new();
for (key, field) in schema.as_dict().into_iter().flat_map(Dict::iter) {
let Some(field) = self.read(field)? else { continue };
let Some(field) = field.as_dict() else { continue };
let Some(subtype) = read_name(self, field.get("Subtype"))? else {
continue;
};
let flag = |k: &str, default: bool| match field.get(k) {
Some(Object::Bool(b)) => *b,
_ => default,
};
fields.push(CollectionField {
key: String::from_utf8_lossy(key.as_bytes()).into_owned(),
name: self.text_entry(field, "N")?,
kind: field_kind(&subtype),
order: field.get_int("O"),
visible: flag("V", true),
editable: flag("E", false),
});
}
fields.sort_by(|a, b| match (a.order, b.order) {
(Some(x), Some(y)) => x.cmp(&y).then_with(|| a.key.cmp(&b.key)),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => a.key.cmp(&b.key),
});
Ok(fields)
}
fn collection_sort(&self, collection: &Dict) -> Result<Vec<(String, bool)>> {
let Some(sort) = collection.get("Sort") else {
return Ok(Vec::new());
};
let Some(sort) = self.read(sort)? else {
return Ok(Vec::new());
};
let Some(sort) = sort.as_dict() else {
return Ok(Vec::new());
};
let keys: Vec<String> = match sort.get("S").map(|s| self.read(s)).transpose()?.flatten().as_deref() {
Some(Object::Name(n)) => vec![String::from_utf8_lossy(n.as_bytes()).into_owned()],
Some(Object::Array(items)) => items
.iter()
.filter_map(|o| match o {
Object::Name(n) => Some(String::from_utf8_lossy(n.as_bytes()).into_owned()),
_ => None,
})
.collect(),
_ => Vec::new(),
};
let ascending: Vec<bool> = match sort.get("A").map(|a| self.read(a)).transpose()?.flatten().as_deref() {
Some(Object::Bool(b)) => vec![*b],
Some(Object::Array(items)) => items.iter().map(|o| !matches!(o, Object::Bool(false))).collect(),
_ => Vec::new(),
};
Ok(keys
.into_iter()
.enumerate()
.map(|(i, key)| (key, ascending.get(i).copied().unwrap_or(true)))
.collect())
}
fn collection_item(&self, spec: &Dict) -> Result<Vec<(String, CollectionValue)>> {
let Some(item) = spec.get("CI") else {
return Ok(Vec::new());
};
let Some(item) = self.read(item)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for (key, value) in item.as_dict().into_iter().flat_map(Dict::iter) {
if key.as_bytes() == b"Type" {
continue;
}
let Some(value) = self.read(value)? else { continue };
let value = match value.as_dict() {
Some(sub) => match sub.get("D") {
Some(d) => self.read(d)?,
None => None,
},
None => Some(value),
};
let value = match value.as_deref() {
Some(Object::String(s)) => CollectionValue::Text(laminapdf_syntax::text::decode_text_string(&s.bytes)),
Some(other) => match other.as_f64() {
Some(n) => CollectionValue::Number(n),
None => continue,
},
None => continue,
};
out.push((String::from_utf8_lossy(key.as_bytes()).into_owned(), value));
}
Ok(out)
}
}
fn field_kind(subtype: &[u8]) -> CollectionFieldKind {
match subtype {
b"S" => CollectionFieldKind::Text,
b"D" => CollectionFieldKind::Date,
b"N" => CollectionFieldKind::Number,
b"F" => CollectionFieldKind::FileName,
b"Desc" => CollectionFieldKind::Description,
b"ModDate" => CollectionFieldKind::Modified,
b"CreationDate" => CollectionFieldKind::Created,
b"Size" => CollectionFieldKind::Size,
b"CompressedSize" => CollectionFieldKind::CompressedSize,
other => CollectionFieldKind::Other(String::from_utf8_lossy(other).into_owned()),
}
}