use f_office_units::binary32::Binary32;
use f_office_units::scale::{PERCENT, TENTHS, TENTHS_OF_MM_PER_INCH, THOUSANDTHS};
use f_office_units::{div_round, lowest_terms};
use crate::{Fraction, Orientation};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocumentedSide {
Millimetres(i64),
InchThousandths(i64),
}
impl DocumentedSide {
#[must_use]
pub const fn form_side(self, dots_per_inch: i64) -> FormSide {
match self {
Self::Millimetres(millimetres) => FormSide {
millimetres,
dots: div_round(millimetres * dots_per_inch * TENTHS, TENTHS_OF_MM_PER_INCH),
},
Self::InchThousandths(thousandths) => FormSide {
millimetres: div_round(thousandths * TENTHS_OF_MM_PER_INCH, THOUSANDTHS * TENTHS),
dots: div_round(thousandths * dots_per_inch, THOUSANDTHS),
},
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FormSide {
pub millimetres: i64,
pub dots: i64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaperForm {
pub name: &'static str,
pub across: DocumentedSide,
pub down: DocumentedSide,
pub orientation: Orientation,
}
impl PaperForm {
#[must_use]
pub const fn millimetres(name: &'static str, across: i64, down: i64) -> Self {
Self {
name,
across: DocumentedSide::Millimetres(across),
down: DocumentedSide::Millimetres(down),
orientation: Orientation::Portrait,
}
}
#[must_use]
pub const fn inches(name: &'static str, across: i64, down: i64) -> Self {
Self {
name,
across: DocumentedSide::InchThousandths(across),
down: DocumentedSide::InchThousandths(down),
orientation: Orientation::Portrait,
}
}
#[must_use]
pub const fn rotated(self) -> Self {
Self {
orientation: Orientation::Landscape,
..self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClassRule {
pub forms: &'static [PaperForm],
pub reach: i64,
pub holding: &'static [PaperForm],
pub last: PaperForm,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SizedForm {
pub(crate) form: PaperForm,
pub(crate) across: FormSide,
pub(crate) down: FormSide,
}
impl SizedForm {
pub(crate) const fn of(form: PaperForm, dots_per_inch: i64) -> Self {
Self {
form,
across: form.across.form_side(dots_per_inch),
down: form.down.form_side(dots_per_inch),
}
}
const fn turned(self) -> Self {
Self {
form: self.form,
across: self.down,
down: self.across,
}
}
const fn holds(&self, (across, down): (i64, i64), reach: i64) -> bool {
across <= self.across.dots + reach && down <= self.down.dots + reach
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SizedRule {
forms: Vec<SizedForm>,
reach: i64,
holding: Vec<SizedForm>,
last: SizedForm,
}
impl SizedRule {
pub(crate) fn of(rule: &ClassRule, dots_per_inch: i64) -> Self {
let sized = |forms: &[PaperForm]| {
forms
.iter()
.map(|form| SizedForm::of(*form, dots_per_inch))
.collect()
};
Self {
forms: sized(rule.forms),
reach: rule.reach,
holding: sized(rule.holding),
last: SizedForm::of(rule.last, dots_per_inch),
}
}
pub(crate) fn form(&self, (across, down): (i64, i64), orientation: Orientation) -> SizedForm {
if orientation == Orientation::Landscape && across > down {
return self.form((down, across), Orientation::Portrait).turned();
}
let nearest = self
.forms
.iter()
.filter_map(|form| {
let distance = (across - form.across.dots)
.abs()
.max((down - form.down.dots).abs());
(distance <= self.reach).then_some((distance, form))
})
.min_by_key(|(distance, _)| *distance)
.map(|(_, form)| *form);
match nearest {
Some(form)
if form.form.orientation == Orientation::Portrait
|| orientation == Orientation::Landscape =>
{
form
}
_ => self
.holding
.iter()
.find(|form| form.holds((across, down), self.reach))
.copied()
.unwrap_or(self.last),
}
}
}
#[must_use]
pub fn frame_side(dots: i64, side: FormSide) -> Option<i64> {
if side.millimetres <= 0 || side.dots <= 0 {
return None;
}
let hundredths_per_inch =
Binary32::nearest((TENTHS_OF_MM_PER_INCH * PERCENT / TENTHS).into(), 1);
let scale = hundredths_per_inch.over_below(density(side));
let extent = scale.times_below(dots.checked_sub(1)?);
let frame = extent.plus_below(Binary32::nearest(1, 2)).floor();
(frame > 0).then_some(frame)
}
fn density(side: FormSide) -> Binary32 {
let millimetres_per_inch = Binary32::nearest(TENTHS_OF_MM_PER_INCH.into(), TENTHS.into());
Binary32::below(side.dots.into(), side.millimetres.into()).product_below(millimetres_per_inch)
}
#[must_use]
pub fn page_entry(
dots: i64,
side: FormSide,
(parts, steps_per_inch, dots_per_inch): (i64, i64, i64),
) -> Option<Binary32> {
let frame = frame_side(dots, side)?;
let numerator = [parts, steps_per_inch, dots, PERCENT, side.millimetres]
.into_iter()
.try_fold(1_i128, |product, factor| product.checked_mul(factor.into()))?;
let denominator = [dots_per_inch, side.dots, frame]
.into_iter()
.try_fold(1_i128, |product, factor| product.checked_mul(factor.into()))?;
Some(Binary32::nearest(numerator, denominator))
}
#[must_use]
pub fn entry_steps(
entry: Binary32,
dots: i64,
(parts, steps_per_inch, dots_per_inch): (i64, i64, i64),
) -> Option<Fraction> {
let mantissa = i128::from(entry.mantissa());
let power = 2_i128.checked_pow(entry.exponent().unsigned_abs())?;
let (scaled, power) = if entry.exponent() >= 0 {
(mantissa.checked_mul(power)?, 1_i128)
} else {
(mantissa, power)
};
let base = i128::from(parts)
.checked_mul(steps_per_inch.into())?
.checked_mul(power)?;
let numerator = scaled
.checked_mul(dots_per_inch.into())?
.checked_sub(base)?
.checked_mul(dots.into())?;
let denominator = power
.checked_mul(dots_per_inch.into())?
.checked_mul(parts.into())?;
let (numerator, denominator) = lowest_terms(numerator, denominator);
Some((numerator.try_into().ok()?, denominator.try_into().ok()?))
}
#[cfg(test)]
mod tests;