use std::fmt;
use f_office_units::Length;
use f_office_units::measure::universal_measure;
use f_office_units::scale::EMUS_PER_INCH;
use serde_json::{Map, Value};
use super::image::{ImageError, image_file};
use super::{Edit, EditLimits, NamedEdit, Path, PathError, Place, XmlEdit};
use crate::{Address, AddressError};
const OPERATIONS: &str = "replace, set-text, insert-before, insert-after, insert-row-before, insert-row-after, insert-image-before, insert-image-after, comment, delete, style, xml";
const XML_FIELDS: [&str; 4] = ["part", "at", "expect", "xml"];
const REPLACE_FIELDS: [&str; 3] = ["at", "find", "with"];
const INSERT_FIELDS: [&str; 3] = ["at", "text", "style"];
const DELETE_FIELDS: [&str; 1] = ["at"];
const STYLE_FIELDS: [&str; 2] = ["at", "style"];
const SET_TEXT_FIELDS: [&str; 2] = ["at", "text"];
const ROW_FIELDS: [&str; 2] = ["at", "cells"];
const COMMENT_FIELDS: [&str; 4] = ["at", "text", "find", "author"];
const IMAGE_FIELDS: [&str; 5] = ["at", "image", "alt", "width", "height"];
#[derive(Clone, Copy)]
pub struct ListContext<'c> {
pub author: Option<&'c str>,
pub read_image: &'c dyn Fn(&str) -> Result<Vec<u8>, String>,
}
impl Default for ListContext<'_> {
fn default() -> Self {
Self {
author: None,
read_image: &no_image_files,
}
}
}
fn no_image_files(_: &str) -> Result<Vec<u8>, String> {
Err("the caller reads no image files".to_owned())
}
impl fmt::Debug for ListContext<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ListContext")
.field("author", &self.author)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ListError {
TooLarge {
limit: usize,
},
TooManyEdits {
limit: usize,
},
Json(String),
NotAList,
Entry {
index: usize,
fault: EntryFault,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryFault {
NotAnObject,
NoOperation,
UnknownOperation(String),
Field(&'static str),
UnknownField(String),
Path(PathError),
Address(AddressError),
NoAuthor,
Cells,
Length(&'static str),
ImageFile(String),
Image(ImageError),
}
impl fmt::Display for ListError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TooLarge { limit } => write!(
f,
"the edit list is larger than {limit} bytes: split it into several lists"
),
Self::TooManyEdits { limit } => write!(
f,
"the edit list holds more than {limit} edits: split it into several lists"
),
Self::Json(message) => write!(f, "the edit list is not JSON: {message}"),
Self::NotAList => {
f.write_str("the edit list must be a JSON list of edits: [{...}, ...]")
}
Self::Entry { index, fault } => write!(f, "edit {index} of the list (from 0): {fault}"),
}
}
}
impl fmt::Display for EntryFault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAnObject => {
f.write_str("an edit must be a JSON object such as {\"op\": \"xml\", ...}")
}
Self::NoOperation => write!(f, "the edit has no \"op\" text: give one of {OPERATIONS}"),
Self::UnknownOperation(operation) => write!(
f,
"the operation {operation} is not one that F-Office makes: give one of {OPERATIONS}"
),
Self::Field(field) => write!(f, "the edit needs the text field \"{field}\""),
Self::UnknownField(field) => write!(
f,
"the edit has the field \"{field}\", which its operation does not take"
),
Self::Path(error) => error.fmt(f),
Self::Address(error) => error.fmt(f),
Self::NoAuthor => f.write_str(
"a comment needs an author: supply a default author or an \"author\" field in the edit",
),
Self::Cells => f.write_str(
"the field \"cells\" must be a list of texts, one for each of the first cells, such as [\"Total\", \"45\"]",
),
Self::Length(field) => write!(
f,
"the field \"{field}\" must be a length with its unit, such as 8cm, 3in or 144pt"
),
Self::ImageFile(why) => write!(f, "the image file does not read: {why}"),
Self::Image(error) => error.fmt(f),
}
}
}
impl std::error::Error for ListError {}
pub fn parse(
json: &[u8],
limits: &EditLimits,
context: &ListContext<'_>,
) -> Result<Vec<Edit>, ListError> {
if json.len() > limits.max_list_bytes {
return Err(ListError::TooLarge {
limit: limits.max_list_bytes,
});
}
let value: Value =
serde_json::from_slice(json).map_err(|error| ListError::Json(error.to_string()))?;
let Value::Array(entries) = value else {
return Err(ListError::NotAList);
};
if entries.len() > limits.max_edits {
return Err(ListError::TooManyEdits {
limit: limits.max_edits,
});
}
entries
.iter()
.enumerate()
.map(|(index, entry)| {
edit(entry, limits, context).map_err(|fault| ListError::Entry { index, fault })
})
.collect()
}
fn edit(entry: &Value, limits: &EditLimits, context: &ListContext<'_>) -> Result<Edit, EntryFault> {
let Value::Object(fields) = entry else {
return Err(EntryFault::NotAnObject);
};
let operation = fields
.get("op")
.and_then(Value::as_str)
.ok_or(EntryFault::NoOperation)?;
match operation {
"xml" => xml(fields),
"replace" => replace(fields),
"insert-before" => insert(fields, Place::Before),
"insert-after" => insert(fields, Place::After),
"delete" => delete(fields),
"style" => style(fields),
"set-text" => set_text(fields),
"insert-row-before" => row(fields, Place::Before),
"insert-row-after" => row(fields, Place::After),
"comment" => comment(fields, context),
"insert-image-before" => image(fields, Place::Before, limits, context),
"insert-image-after" => image(fields, Place::After, limits, context),
other => Err(EntryFault::UnknownOperation(other.to_owned())),
}
}
fn xml(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
known_fields(fields, &XML_FIELDS)?;
Ok(Edit::Xml(XmlEdit {
part: text(fields, "part")?.to_owned(),
at: text(fields, "at")?
.parse::<Path>()
.map_err(EntryFault::Path)?,
expect: text(fields, "expect")?.to_owned(),
xml: text(fields, "xml")?.to_owned(),
}))
}
fn replace(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
known_fields(fields, &REPLACE_FIELDS)?;
Ok(Edit::Named(NamedEdit::Replace {
at: address(fields)?,
find: text(fields, "find")?.to_owned(),
with: text(fields, "with")?.to_owned(),
}))
}
fn insert(fields: &Map<String, Value>, place: Place) -> Result<Edit, EntryFault> {
known_fields(fields, &INSERT_FIELDS)?;
Ok(Edit::Named(NamedEdit::Insert {
at: address(fields)?,
place,
text: text(fields, "text")?.to_owned(),
style: optional_text(fields, "style")?.map(str::to_owned),
}))
}
fn delete(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
known_fields(fields, &DELETE_FIELDS)?;
Ok(Edit::Named(NamedEdit::Delete {
at: address(fields)?,
}))
}
fn style(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
known_fields(fields, &STYLE_FIELDS)?;
Ok(Edit::Named(NamedEdit::Style {
at: address(fields)?,
style: text(fields, "style")?.to_owned(),
}))
}
fn set_text(fields: &Map<String, Value>) -> Result<Edit, EntryFault> {
known_fields(fields, &SET_TEXT_FIELDS)?;
Ok(Edit::Named(NamedEdit::SetText {
at: address(fields)?,
text: text(fields, "text")?.to_owned(),
}))
}
fn row(fields: &Map<String, Value>, place: Place) -> Result<Edit, EntryFault> {
known_fields(fields, &ROW_FIELDS)?;
let cells = match fields.get("cells") {
None => Vec::new(),
Some(Value::Array(items)) => items
.iter()
.map(|item| item.as_str().map(str::to_owned).ok_or(EntryFault::Cells))
.collect::<Result<_, _>>()?,
Some(_) => return Err(EntryFault::Cells),
};
Ok(Edit::Named(NamedEdit::InsertRow {
at: address(fields)?,
place,
cells,
}))
}
fn comment(fields: &Map<String, Value>, context: &ListContext<'_>) -> Result<Edit, EntryFault> {
known_fields(fields, &COMMENT_FIELDS)?;
let author = optional_text(fields, "author")?
.or(context.author)
.ok_or(EntryFault::NoAuthor)?;
Ok(Edit::Named(NamedEdit::Comment {
at: address(fields)?,
text: text(fields, "text")?.to_owned(),
find: optional_text(fields, "find")?.map(str::to_owned),
author: author.to_owned(),
}))
}
fn image(
fields: &Map<String, Value>,
place: Place,
limits: &EditLimits,
context: &ListContext<'_>,
) -> Result<Edit, EntryFault> {
known_fields(fields, &IMAGE_FIELDS)?;
let at = address(fields)?;
let alt = text(fields, "alt")?.to_owned();
let size = (length(fields, "width")?, length(fields, "height")?);
let data = (context.read_image)(text(fields, "image")?).map_err(EntryFault::ImageFile)?;
let image = image_file(data, limits).map_err(EntryFault::Image)?;
Ok(Edit::Named(NamedEdit::InsertImage {
at,
place,
image,
alt,
size,
}))
}
fn length(fields: &Map<String, Value>, name: &'static str) -> Result<Option<Length>, EntryFault> {
optional_text(fields, name)?
.map(|value| {
universal_measure(value, EMUS_PER_INCH)
.and_then(Length::from_emus)
.ok_or(EntryFault::Length(name))
})
.transpose()
}
fn address(fields: &Map<String, Value>) -> Result<Address, EntryFault> {
text(fields, "at")?
.parse::<Address>()
.map_err(EntryFault::Address)
}
fn known_fields(fields: &Map<String, Value>, known: &[&str]) -> Result<(), EntryFault> {
match fields
.keys()
.find(|field| *field != "op" && !known.contains(&field.as_str()))
{
Some(field) => Err(EntryFault::UnknownField(field.clone())),
None => Ok(()),
}
}
fn optional_text<'v>(
fields: &'v Map<String, Value>,
name: &'static str,
) -> Result<Option<&'v str>, EntryFault> {
fields
.get(name)
.map(|value| value.as_str().ok_or(EntryFault::Field(name)))
.transpose()
}
fn text<'v>(fields: &'v Map<String, Value>, name: &'static str) -> Result<&'v str, EntryFault> {
fields
.get(name)
.and_then(Value::as_str)
.ok_or(EntryFault::Field(name))
}