f-office-paint 0.3.0

Display list: the contract between layout and output.
Documentation
//! The paper forms of a writer whose page offset takes the page entry of a page's paper form,
//! the class rule that gives a page its form, and the chain that gives the entry.
//!
//! Word for Windows gives a page's entry on each axis from its paper form alone: the form's side
//! in whole mm and in dots gives the frame side of the page's side, and the entry is `80 D u / R`,
//! held as the nearest binary32 number.

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};

/// One side of a paper form, in whole mm or in thousandths of an inch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocumentedSide {
    /// Whole millimetres.
    Millimetres(i64),
    /// Thousandths of an inch.
    InchThousandths(i64),
}

impl DocumentedSide {
    /// The side as whole mm and as dots at `dots_per_inch`, each rounded a half up.
    #[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),
            },
        }
    }
}

/// One side of a paper form as its whole mm and its dots; its unit to the dot is
/// `100 mm / dots` hundredths of a mm.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FormSide {
    /// The side in whole mm.
    pub millimetres: i64,
    /// The side in dots.
    pub dots: i64,
}

/// A paper form: a paper that a printer's driver offers, or a standard paper size that the
/// documentation of the `DEVMODE` field `dmPaperSize` names rotated (a `DMPAPER_*_ROTATED` value).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaperForm {
    /// The form's name.
    pub name: &'static str,
    /// The form's width.
    pub across: DocumentedSide,
    /// The form's height.
    pub down: DocumentedSide,
    /// Landscape for a form that the documentation names rotated (`DMPAPER_*_ROTATED`), and
    /// portrait for the others.
    pub orientation: Orientation,
}

impl PaperForm {
    /// The portrait form `name`, `across` by `down` whole mm.
    #[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,
        }
    }

    /// The portrait form `name`, `across` by `down` thousandths of an inch.
    #[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,
        }
    }

    /// The same form, named rotated by its documentation.
    #[must_use]
    pub const fn rotated(self) -> Self {
        Self {
            orientation: Orientation::Landscape,
            ..self
        }
    }
}

/// The class rule that gives a page its paper form, from the page's size in written dots and
/// its section's orientation:
///
/// 1. the form of `forms` whose sides both lie within `reach` dots of the page's, the nearest
///    by the larger of the two differences, the first in `forms` when two are as near; but a
///    page in a portrait section takes no rotated form here, and goes on to step 2;
/// 2. else the first of `holding` whose sides, `reach` dots longer, hold the page;
/// 3. else `last`.
///
/// A page wider than high in a landscape section takes the form that these steps give its page
/// turned upright, height by width, in a portrait section, turned back: its width takes the
/// form's height side and its height the form's width side. A rotated form within the reach of
/// the page as it lies does not decide its form.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClassRule {
    /// The forms, in an order that decides a tie.
    pub forms: &'static [PaperForm],
    /// The dots by which each side of a page may differ from a form's side for the page to take
    /// the form (the reach).
    pub reach: i64,
    /// The forms of step 2, in order.
    pub holding: &'static [PaperForm],
    /// The form of step 3.
    pub last: PaperForm,
}

/// A paper form with its sides in the writer's dots.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SizedForm {
    /// The form.
    pub(crate) form: PaperForm,
    /// Its width.
    pub(crate) across: FormSide,
    /// Its height.
    pub(crate) down: FormSide,
}

impl SizedForm {
    /// `form` with its sides at `dots_per_inch`.
    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),
        }
    }

    /// The form turned a quarter: its height side across and its width side down.
    const fn turned(self) -> Self {
        Self {
            form: self.form,
            across: self.down,
            down: self.across,
        }
    }

    /// Whether the form's sides, `reach` dots longer, hold a page `across` by `down` dots.
    const fn holds(&self, (across, down): (i64, i64), reach: i64) -> bool {
        across <= self.across.dots + reach && down <= self.down.dots + reach
    }
}

/// The forms of a class rule with their sides at the writer's dots per inch, made once.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SizedRule {
    /// The forms of step 1, in order.
    forms: Vec<SizedForm>,
    /// The reach in dots.
    reach: i64,
    /// The forms of step 2, in order.
    holding: Vec<SizedForm>,
    /// The form of step 3.
    last: SizedForm,
}

impl SizedRule {
    /// `rule` with its forms' sides at `dots_per_inch`.
    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),
        }
    }

    /// The form of a page `across` by `down` written dots in a section of `orientation`.
    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))
            })
            // The first of the nearest forms, in the documentation's order.
            .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),
        }
    }
}

/// The frame side `R` of a page side of `dots` written dots for the form side `side`: the
/// binary32 chain `dpi = (dots / mm) * 25.4f`, `scale = 2540 / dpi`, `extent = (D - 1) *
/// scale`, `R = floor(extent + 0.5)`, each operation rounded down: a frame of D dots spans
/// D - 1 intervals. `None` for a form
/// side that is not positive, and for a frame side that is not positive: a page side of one
/// dot or less spans no frame.
#[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)
}

/// The chain's first step for the form side `side`, its dots per inch: `(dots / mm) * 25.4f`,
/// each operation rounded down.
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)
}

/// The page entry of a page side of `dots` written dots for the form side `side`, with the
/// writer's `parts` of a step, `steps_per_inch` and `dots_per_inch`: `parts * (steps_per_inch /
/// dots_per_inch) * D u / R` with `u = 100 mm / dots` of the form side, `16 (5 + c / D)` for 16
/// parts and 5 steps to the dot, held as the nearest binary32 number. `None` where
/// [`frame_side`] gives none or the product does not fit.
#[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))
}

/// The steps `c` of the page form of the writer's offset ([`crate::Offset::Page`]) that the
/// page entry `entry` gives a side of `dots` written dots: `entry = parts (s + c / D)` with `s`
/// steps to the dot, so `c = (entry / parts - s) D`, exactly. `None` where the fraction does
/// not fit.
#[must_use]
pub fn entry_steps(
    entry: Binary32,
    dots: i64,
    (parts, steps_per_inch, dots_per_inch): (i64, i64, i64),
) -> Option<Fraction> {
    // entry = mantissa * 2^exponent; c = (mantissa * 2^exponent - parts s) D / parts, with
    // s = steps_per_inch / dots_per_inch.
    // A power of two or a product that does not fit an `i128` gives `None`.
    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)
    };
    // (scaled / power - parts steps_per_inch / dots_per_inch) D / parts.
    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;