use std::collections::BTreeSet;
use techy::core::node::NodeRef;
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::extract::parse_keyval_drop_annotations;
use crate::core::lowering::{LowerError, Lowerer, chars_at_lowering};
use crate::lang::Flm;
use crate::lang::text::{is_space, plain_text_of};
use crate::stdlib::backends::pres::{I48F16, Length};
use super::OPTIONS_ARG;
pub const ALT_KEY: &str = "alt";
pub const WIDTH_KEY: &str = "width";
pub const HEIGHT_KEY: &str = "height";
pub const KEYS: [&str; 3] = [ALT_KEY, WIDTH_KEY, HEIGHT_KEY];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImageOptions {
pub alt: Option<String>,
pub width: Option<Length>,
pub height: Option<Length>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Finding {
Unreadable,
NoKey,
Unknown(String),
Repeated(String),
NoValue(String),
AltNotText,
NotALength { key: String, value: String },
NotPhysical { key: String, unit: String },
NotPositive { key: String, value: String },
Resized(String),
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.unreadable-options",
message = "Invalid key in the options of ‘\\includegraphics’: keys must be plain text"
)]
pub struct UnreadableOptions;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.missing-key",
message = "Missing key before ‘=’ in the options of ‘\\includegraphics’"
)]
pub struct MissingKey;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.unknown-key",
message = "Invalid key ‘{key}’ in the options of ‘\\includegraphics’: \
valid keys are ‘alt’, ‘width’ and ‘height’"
)]
pub struct UnknownKey {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.repeated-key",
message = "Duplicate key ‘{key}’ in the options of ‘\\includegraphics’"
)]
pub struct RepeatedKey {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.missing-value",
message = "Missing value for key ‘{key}’ of ‘\\includegraphics’: use the syntax ‘{key}=…’"
)]
pub struct MissingValue {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.alt-not-text",
message = "The ‘alt’ text of an image must be plain text, without formulas or commands"
)]
pub struct AltNotText;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.not-a-length",
message = "Invalid length ‘{value}’ for key ‘{key}’ of ‘\\includegraphics’: a length must be \
a number followed directly by a unit, as in ‘5cm’ (supported units: ‘pt’, ‘mm’, \
‘cm’ and ‘in’)"
)]
pub struct NotALength {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.relative-unit",
message = "Unsupported unit ‘{unit}’ for key ‘{key}’ of ‘\\includegraphics’ (supported units: \
‘pt’, ‘mm’, ‘cm’ and ‘in’)"
)]
pub struct RelativeUnit {
pub key: String,
pub unit: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.not-positive",
message = "Invalid length ‘{value}’ for key ‘{key}’ of ‘\\includegraphics’: the length must be \
greater than zero"
)]
pub struct NotPositive {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.resized",
message = "Image resized with key ‘{key}’ of ‘\\includegraphics’: \
for the best quality, prepare the image file at the displayed size"
)]
pub struct Resized {
pub key: String,
}
pub fn image_options(node: &NodeRef<'_, Flm>) -> Result<ImageOptions, LowerError> {
Ok(read(node)?.0)
}
pub fn report(node: &NodeRef<'_, Flm>, lw: &mut dyn Lowerer) -> Result<(), LowerError> {
let (_, findings) = read(node)?;
for finding in findings {
let span = node.span().clone();
lw.diagnose(match finding {
Finding::Unreadable => Diagnostic::error(UnreadableOptions, span),
Finding::NoKey => Diagnostic::error(MissingKey, span),
Finding::Unknown(key) => Diagnostic::error(UnknownKey { key }, span),
Finding::Repeated(key) => Diagnostic::error(RepeatedKey { key }, span),
Finding::NoValue(key) => Diagnostic::error(MissingValue { key }, span),
Finding::AltNotText => Diagnostic::error(AltNotText, span),
Finding::NotALength { key, value } => {
Diagnostic::error(NotALength { key, value }, span)
}
Finding::NotPhysical { key, unit } => {
Diagnostic::error(RelativeUnit { key, unit }, span)
}
Finding::NotPositive { key, value } => {
Diagnostic::error(NotPositive { key, value }, span)
}
Finding::Resized(key) => Diagnostic::warning(Resized { key }, span),
});
}
Ok(())
}
fn read(node: &NodeRef<'_, Flm>) -> Result<(ImageOptions, Vec<Finding>), LowerError> {
let mut options = ImageOptions::default();
let mut findings = Vec::new();
let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
return Ok((options, findings));
};
let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
findings.push(Finding::Unreadable);
return Ok((options, findings));
};
let mut seen: BTreeSet<&str> = BTreeSet::new();
for entry in keyvals.iter() {
let key = entry.key();
if key.is_empty() {
if entry.value_content().is_some() {
findings.push(Finding::NoKey);
}
continue;
}
if !KEYS.contains(&key) {
findings.push(Finding::Unknown(key.to_string()));
continue;
}
if !seen.insert(key) {
findings.push(Finding::Repeated(key.to_string()));
continue;
}
let Some(value) = entry.value_content() else {
findings.push(Finding::NoValue(key.to_string()));
continue;
};
let text = chars_at_lowering(value.iter())?.map(|text| text.trim_matches(is_space).to_string());
if key == ALT_KEY {
match text {
Ok(text) => options.alt = Some(text),
Err(_) => findings.push(Finding::AltNotText),
}
continue;
}
let written = match text {
Ok(text) => text,
Err(_) => plain_text_of(value.iter()).trim_matches(is_space).to_string(),
};
match dimension(key, &written) {
Ok(length) => {
if key == WIDTH_KEY {
options.width = Some(length);
} else {
options.height = Some(length);
}
findings.push(Finding::Resized(key.to_string()));
}
Err(finding) => findings.push(finding),
}
}
Ok((options, findings))
}
fn dimension(key: &str, written: &str) -> Result<Length, Finding> {
let length = Length::parse(written).map_err(|_| Finding::NotALength {
key: key.to_string(),
value: written.to_string(),
})?;
if !length.unit.is_physical() {
return Err(Finding::NotPhysical { key: key.to_string(), unit: length.unit.to_string() });
}
if length.amount <= I48F16::ZERO {
return Err(Finding::NotPositive { key: key.to_string(), value: written.to_string() });
}
Ok(length)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_dimension_is_a_positive_physical_length() {
assert_eq!(dimension("width", "5cm"), Ok(Length::parse("5cm").unwrap()));
assert_eq!(dimension("width", ".5in"), Ok(Length::parse("0.5in").unwrap()));
for text in ["300px", "0.5\\linewidth", "50%", "10bp", "", "5"] {
assert!(matches!(dimension("width", text), Err(Finding::NotALength { .. })), "{text}");
}
assert!(matches!(dimension("width", "1.5em"), Err(Finding::NotPhysical { .. })));
assert!(matches!(dimension("height", "2tab"), Err(Finding::NotPhysical { .. })));
assert!(matches!(dimension("width", "0cm"), Err(Finding::NotPositive { .. })));
assert!(matches!(dimension("width", "-1pt"), Err(Finding::NotPositive { .. })));
}
}