f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
//! DrawingML line dash patterns (`a:prstDash`, `a:custDash`) and end caps (`a:ln/@cap`).

use f_office_paint::stroke::StrokeCap;
use f_office_units::Length;
use f_office_units::scale::DRAWING_WHOLE;
use f_office_xml::{Document, NodeId};

use crate::A;
use crate::color::percentage;

/// Maximum number of dashes emitted along one stroked path.
pub(crate) const MAX_DASHES: usize = 1 << 16;

/// One of the 10 dashed presets of `ST_PresetLineDashVal` (ECMA-376 Part 1, 20.1.10.49) other
/// than `solid`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PresetDash {
    Dot,
    Dash,
    LongDash,
    DashDot,
    LongDashDot,
    LongDashDotDot,
    SystemDash,
    SystemDot,
    SystemDashDot,
    SystemDashDotDot,
}

impl PresetDash {
    /// Parses a preset dash name other than `solid`.
    fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "dot" => Self::Dot,
            "dash" => Self::Dash,
            "lgDash" => Self::LongDash,
            "dashDot" => Self::DashDot,
            "lgDashDot" => Self::LongDashDot,
            "lgDashDotDot" => Self::LongDashDotDot,
            "sysDash" => Self::SystemDash,
            "sysDot" => Self::SystemDot,
            "sysDashDot" => Self::SystemDashDot,
            "sysDashDotDot" => Self::SystemDashDotDot,
            _ => return None,
        })
    }

    /// Alternating dash and gap lengths in multiples of the line's width.
    const fn widths(self) -> &'static [i64] {
        match self {
            Self::Dot => &[1, 3],
            Self::Dash => &[4, 3],
            Self::LongDash => &[8, 3],
            Self::DashDot => &[4, 3, 1, 3],
            Self::LongDashDot => &[8, 3, 1, 3],
            Self::LongDashDotDot => &[8, 3, 1, 3, 1, 3],
            Self::SystemDash => &[3, 1],
            Self::SystemDot => &[1, 1],
            Self::SystemDashDot => &[3, 1, 1, 1],
            Self::SystemDashDotDot => &[3, 1, 1, 1, 1, 1],
        }
    }
}

/// A drawable dash pattern of a DrawingML line (`a:ln`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LineDash {
    /// One of the 10 preset dash patterns.
    Preset(PresetDash),
    /// A custom dash (`a:custDash`): alternating `(dash, space)` stops in thousandths of a
    /// percent of the line's width (`100_000` = 1 width).
    Custom(Vec<[i64; 2]>),
}

/// What `read_dash` found on an `a:ln` element.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ReadDash {
    /// Neither `a:prstDash` nor `a:custDash` was present (a shape inherits from its line style).
    Omitted,
    /// `a:prstDash val="solid"` was set explicitly.
    Solid,
    /// A supported preset or custom dash was read.
    Dashed(LineDash),
    /// A dash element was present but could not be read as a valid dash.
    Unsupported,
}

/// A resolved dash pattern ready to stroke a path with [`f_office_paint::stroke::dashes`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DashStyle {
    /// Alternating on/off lengths along the path, adjusted for `cap`.
    pub(crate) pattern: Vec<Length>,
    /// The cap shape of each dash.
    pub(crate) cap: StrokeCap,
}

impl LineDash {
    /// Resolves the alternating on/off lengths of this dash for a line of drawn width `width`
    /// and end cap `cap`. Under `Flat` caps, dash and gap lengths are exact multiples of `width`.
    /// Under `Round` or `Square` caps, each dash is shortened by `width` (clamped at 0) and each
    /// gap lengthened by `width` so that the painted caps preserve the visual pattern.
    pub(crate) fn resolve(&self, width: Length, cap: StrokeCap) -> Option<DashStyle> {
        let raw: Vec<Length> = match self {
            Self::Preset(preset) => preset
                .widths()
                .iter()
                .map(|&multiple| width.checked_mul(multiple))
                .collect::<Option<_>>()?,
            Self::Custom(stops) => {
                let mut out = Vec::with_capacity(stops.len() * 2);
                for &[dash, space] in stops {
                    out.push(width.checked_mul(dash)?.div_round(DRAWING_WHOLE));
                    out.push(width.checked_mul(space)?.div_round(DRAWING_WHOLE));
                }
                out
            }
        };
        let pattern: Vec<Length> = match cap {
            StrokeCap::Flat => raw,
            StrokeCap::Round | StrokeCap::Square => (0..)
                .zip(raw)
                .map(|(index, len)| {
                    if index % 2 == 0 {
                        Some(len.checked_sub(width)?.max(Length::ZERO))
                    } else {
                        len.checked_add(width)
                    }
                })
                .collect::<Option<_>>()?,
        };
        let total: i128 = pattern.iter().map(|len| i128::from(len.units())).sum();
        (total > 0).then_some(DashStyle { pattern, cap })
    }
}

/// Reads `a:prstDash` or `a:custDash` on `ln`.
pub(crate) fn read_dash(doc: &Document, ln: NodeId) -> ReadDash {
    if let Some(custom) = doc.child(ln, A, "custDash") {
        let stops: Option<Vec<[i64; 2]>> = doc
            .child_elements(custom)
            .filter(|node| doc.is(*node, A, "ds"))
            .map(|stop| {
                let d = doc.attribute(stop, None, "d").and_then(percentage)?;
                let sp = doc.attribute(stop, None, "sp").and_then(percentage)?;
                (d >= 0 && sp >= 0).then_some([d, sp])
            })
            .collect();
        return match stops {
            Some(stops) if !stops.is_empty() && stops.iter().any(|&[d, sp]| d + sp > 0) => {
                ReadDash::Dashed(LineDash::Custom(stops))
            }
            _ => ReadDash::Unsupported,
        };
    }
    let Some(preset) = doc.child(ln, A, "prstDash") else {
        return ReadDash::Omitted;
    };
    match doc.attribute(preset, None, "val") {
        Some("solid") | None => ReadDash::Solid,
        Some(value) => PresetDash::parse(value).map_or(ReadDash::Unsupported, |p| {
            ReadDash::Dashed(LineDash::Preset(p))
        }),
    }
}

/// Reads `a:ln/@cap` (`flat`, `rnd`, `sq`), or `None` when omitted or unrecognized.
pub(crate) fn read_cap(doc: &Document, ln: NodeId) -> Option<StrokeCap> {
    match doc.attribute(ln, None, "cap")? {
        "flat" => Some(StrokeCap::Flat),
        "rnd" => Some(StrokeCap::Round),
        "sq" => Some(StrokeCap::Square),
        _ => None,
    }
}