#![deny(clippy::wildcard_enum_match_arm)]
#[cfg(feature = "latex")]
pub mod latex;
#[cfg(any(
feature = "latex",
feature = "typst",
feature = "svg",
feature = "rocq"
))]
pub(crate) mod notation;
#[cfg(feature = "pdf")]
pub mod pdf;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "rocq")]
pub mod rocq;
mod styles;
#[cfg(feature = "svg")]
pub mod svg;
#[cfg(feature = "typst")]
pub mod typst;
pub use styles::Styles;
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
pub(crate) fn printed(
sequent: &crate::linear::Sequent,
mode: crate::linear::Mode,
per_occurrence: u64,
limits: &crate::Limits,
) -> Result<Option<crate::linear::Forest>, crate::Error> {
let name = sequent
.atom_names()
.iter()
.map(String::len)
.max()
.unwrap_or(0);
let estimate = sequent
.occurrences()
.saturating_mul(per_occurrence.saturating_add(name as u64));
if let Some(limit) = limits.derivation_bytes
&& estimate > limit
{
return Err(crate::Error::Refused(crate::limits::Refusal::Output {
what: "sequent",
estimate_bytes: estimate,
limit_bytes: limit,
least_bytes: None,
}));
}
if !mode.is_intuitionistic() {
return Ok(None);
}
crate::linear::Forest::within(sequent, limits).map(Some)
}
#[cfg(any(feature = "latex", feature = "typst"))]
pub(crate) fn math(
sequent: &crate::linear::Sequent,
mode: crate::linear::Mode,
per_occurrence: u64,
limits: &crate::Limits,
notation: &crate::linear::sequents::notation::Notation,
) -> Result<String, crate::Error> {
let mut out = String::from("$");
match printed(sequent, mode, per_occurrence, limits)? {
None => notation.one_sided(&mut out, sequent),
Some(forest) => {
let reading = crate::linear::occurrences::Reading::of_mode(&forest, mode)
.map_err(crate::Error::NotIntuitionistic)?;
let roots = forest.root_members();
notation.sequent(
&mut out,
&forest,
Some(&reading),
None,
&roots,
false,
false,
)
}
}
.map_err(|_| crate::Error::WriteFailed)?;
out.push('$');
Ok(out)
}
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
pub(crate) fn judgement(
drawable: Drawable<'_>,
term: Option<&crate::lambda::Options>,
spelling: &crate::lambda::print::Spelling,
mut stop: impl FnMut(crate::Progress) -> bool,
) -> Result<Option<String>, crate::Error> {
let Some(options) = term else {
return Ok(None);
};
let limits = crate::Limits::default();
let term = match drawable {
Drawable::Linear(derivation) => derivation.term(&limits, &mut stop)?,
Drawable::Ordinary(derivation) => derivation.term(&limits, &mut stop)?,
Drawable::Classical(_) => {
return Err(crate::Error::NoTerm {
reason: crate::lambda::NoTerm::Classical,
});
}
};
let mut out = String::new();
term.write_in(spelling, options.types, true, &mut out, &limits, stop)?;
Ok(Some(out))
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub enum Drawable<'a> {
Linear(&'a crate::linear::Derivation<'a>),
Ordinary(&'a crate::ordinary::Derivation),
Classical(&'a crate::linear::TwoSided<'a>),
}
impl<'a, 'p: 'a> From<&'a crate::linear::Derivation<'p>> for Drawable<'a> {
fn from(derivation: &'a crate::linear::Derivation<'p>) -> Self {
Self::Linear(derivation)
}
}
impl<'a, 'p: 'a> From<&'a crate::linear::TwoSided<'p>> for Drawable<'a> {
fn from(view: &'a crate::linear::TwoSided<'p>) -> Self {
Self::Classical(view)
}
}
impl<'a> From<&'a crate::ordinary::Derivation> for Drawable<'a> {
fn from(derivation: &'a crate::ordinary::Derivation) -> Self {
Self::Ordinary(derivation)
}
}
#[non_exhaustive]
#[cfg(any(feature = "latex", feature = "typst", feature = "rocq"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Form {
#[default]
Fragment,
Standalone,
}
#[cfg(any(feature = "png", feature = "pdf"))]
fn texts(svg: &str) -> (Option<String>, Option<String>) {
let Ok(document) = resvg::usvg::roxmltree::Document::parse(svg) else {
return (None, None);
};
let text = |name: &str| {
let element = document
.root_element()
.children()
.find(|node| node.has_tag_name(name))?;
Some(element.text().unwrap_or_default().to_owned())
};
(text("title"), text("desc"))
}
#[cfg(any(feature = "png", feature = "pdf"))]
fn parse(svg: &str, fonts: &[&[u8]]) -> Result<resvg::usvg::Tree, crate::Error> {
let mut options = resvg::usvg::Options::default();
let database = options.fontdb_mut();
for font in fonts {
database.load_font_data(font.to_vec());
}
resvg::usvg::Tree::from_str(svg, &options).map_err(|e| crate::Error::NotSvg {
message: e.to_string(),
})
}
#[cfg(any(feature = "png", feature = "pdf"))]
#[derive(Clone, Copy, Debug)]
struct Costs {
base: u64,
byte: u64,
element: u64,
glyph: u64,
pixel: u64,
arc_passes: u64,
}
#[cfg(any(feature = "png", feature = "pdf"))]
const BYTES_PER_MICROSECOND: u64 = 134;
#[cfg(feature = "png")]
const PNG: Costs = Costs {
base: 32 << 20,
byte: 2,
element: 4700,
glyph: 1000,
pixel: 14,
arc_passes: 2,
};
#[cfg(feature = "pdf")]
const PDF: Costs = Costs {
base: 32 << 20,
byte: 2,
element: 4400,
glyph: 1300,
pixel: 0,
arc_passes: 1,
};
#[cfg(feature = "pdf")]
const PDF_OUTLINES: Costs = Costs { glyph: 2000, ..PDF };
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_LEAST: u64 = 200;
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_PER_MILLION: u64 = 2000;
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_WIDE: u64 = 1500;
#[cfg(any(feature = "png", feature = "pdf"))]
const WIDE: f64 = 5e5;
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_MOST: u64 = 40_000;
#[cfg(any(feature = "png", feature = "pdf"))]
fn arc_micros(start: f64, radius: f64) -> u64 {
if !start.is_finite() || !radius.is_finite() {
return ARC_MOST;
}
let out = (start.abs() / 1e6 * ARC_PER_MILLION as f64) as u64;
let wide = if radius.abs() >= WIDE { ARC_WIDE } else { 0 };
ARC_LEAST
.saturating_add(out)
.saturating_add(wide)
.min(ARC_MOST)
}
#[cfg(any(feature = "png", feature = "pdf"))]
const ELEMENTS: [&str; 8] = [
"svg", "title", "desc", "g", "text", "path", "rect", "circle",
];
#[cfg(any(feature = "png", feature = "pdf"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Measure {
bytes: u64,
elements: u64,
glyphs: u64,
arcs: u64,
}
#[cfg(any(feature = "png", feature = "pdf"))]
impl Measure {
fn of(svg: &str) -> Result<Self, crate::Error> {
let refused = |what: String| {
Err(crate::Error::NotSvg {
message: format!("{what}, which no drawing of deduxit has"),
})
};
let count = |text: &str| text.chars().filter(|c| !c.is_whitespace()).count() as u64;
let mut measure = Self {
bytes: svg.len() as u64,
..Self::default()
};
let mut rest = svg;
while let Some(start) = rest.find('<') {
measure.glyphs = measure.glyphs.saturating_add(count(&rest[..start]));
rest = &rest[start..];
let start_tag = &rest[..tag_end(rest)];
let empty = start_tag.ends_with("/>");
let text = ["title", "desc"]
.into_iter()
.find(|name| rest[1..].starts_with(name) && !empty);
let plain = !rest.starts_with("<!--") && text.is_none();
let close = if rest.starts_with("<!--") {
rest.find("-->").map_or(rest.len(), |i| i + "-->".len())
} else if let Some(name) = text {
start_tag.len() + through_end_tag(&rest[start_tag.len()..], name)
} else {
start_tag.len()
};
let tag = &rest[..close];
if tag.starts_with("<!") && !tag.starts_with("<!--") {
return refused("a document type".to_owned());
}
if tag.as_bytes().get(1).is_some_and(u8::is_ascii_alphabetic) {
let name = tag[1..]
.split(|c: char| c.is_whitespace() || c == '>' || c == '/')
.next()
.unwrap_or_default();
if !ELEMENTS.contains(&name) {
return refused(format!("the element <{name}>"));
}
if plain && tag.contains("href") {
return refused("a reference".to_owned());
}
measure.elements = measure.elements.saturating_add(1);
if plain {
measure.arcs = measure.arcs.saturating_add(arcs(tag));
}
}
rest = &rest[close..];
}
measure.glyphs = measure.glyphs.saturating_add(count(rest));
Ok(measure)
}
fn estimate(&self, costs: &Costs, pixels: u64) -> u64 {
[
(self.bytes, costs.byte),
(self.elements, costs.element),
(self.glyphs, costs.glyph),
(pixels, costs.pixel),
(
self.arcs,
BYTES_PER_MICROSECOND.saturating_mul(costs.arc_passes),
),
]
.into_iter()
.fold(costs.base, |sum, (n, cost)| {
sum.saturating_add(n.saturating_mul(cost))
})
}
}
#[cfg(any(feature = "png", feature = "pdf"))]
fn tag_end(text: &str) -> usize {
let mut quote = None;
for (i, c) in text.char_indices() {
match (quote, c) {
(None, '>') => return i + 1,
(None, '"' | '\'') => quote = Some(c),
(Some(open), c) if c == open => quote = None,
_ => {}
}
}
text.len()
}
#[cfg(any(feature = "png", feature = "pdf"))]
fn through_end_tag(text: &str, name: &str) -> usize {
let open = format!("</{name}");
let mut from = 0;
while let Some(i) = text[from..].find(&open) {
let after = from + i + open.len();
let rest = text[after..].trim_start();
if rest.starts_with('>') {
return text.len() - rest.len() + 1;
}
from = after;
}
text.len()
}
#[cfg(any(feature = "png", feature = "pdf"))]
fn arcs(tag: &str) -> u64 {
let Some((start, quote)) = [" d=\"", " d='"]
.into_iter()
.find_map(|key| tag.find(key).map(|i| (i + key.len(), &key[3..])))
else {
return 0;
};
let data = &tag[start..];
let data = &data[..data.find(quote).unwrap_or(data.len())];
let mut point = Some((0.0f64, 0.0f64));
let mut micros = 0u64;
let mut rest = data;
while let Some(letter) = rest.chars().next() {
let end = rest[letter.len_utf8()..]
.find(|c: char| c.is_ascii_alphabetic())
.map_or(rest.len(), |i| i + letter.len_utf8());
let numbers: Option<Vec<f64>> = rest[letter.len_utf8()..end]
.split([' ', ','])
.filter(|n| !n.is_empty())
.map(|n| n.parse().ok())
.collect();
let numbers = numbers.unwrap_or_default();
point = match (letter, numbers.as_slice(), point) {
('M' | 'L', [.., x, y], _) => Some((*x, *y)),
('H', [.., x], Some((_, y))) => Some((*x, y)),
('V', [.., y], Some((x, _))) => Some((x, *y)),
('A', arcs, mut at) if !arcs.is_empty() && arcs.len() % 7 == 0 => {
for arc in arcs.chunks(7) {
micros = micros.saturating_add(match at {
Some((x, y)) => {
arc_micros(x.abs().max(y.abs()), arc[0].abs().max(arc[1].abs()))
}
None => ARC_MOST,
});
at = Some((arc[5], arc[6]));
}
at
}
('A' | 'a', ..) => {
micros = micros.saturating_add(ARC_MOST);
None
}
_ => None,
};
rest = &rest[end..];
}
micros
}
#[cfg(feature = "png")]
fn declared_size(svg: &str) -> Option<(f64, f64)> {
let root = &svg[svg.find("<svg")?..];
let root = &root[..root.find('>')?];
let attribute = |name: &str| -> Option<f64> {
let value = &root[root.find(&format!(" {name}=\""))? + name.len() + 3..];
let value = &value[..value.find('"')?];
let number: f64 = value.strip_suffix("px").unwrap_or(value).parse().ok()?;
(number.is_finite() && number > 0.0).then_some(number)
};
Some((attribute("width")?, attribute("height")?))
}