f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The frame of a paragraph (`w:framePr`), which takes it out of the text flow.

use f_office_units::Length;
use f_office_xml::NodeId;
use f_office_xml::enumeration::{Values, another, own};

use super::place::{ANCHOR, Align, Anchor, X_ALIGN, XAlign, Y_ALIGN, YAlign};
use crate::reader::PartReader;
use crate::table::{HEIGHT_RULE, HeightRule};

/// The `w:framePr` of a paragraph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FramePr {
    /// The width, or `None` for the width of the content.
    pub width: Option<Length>,
    /// The horizontal position from the anchor.
    pub x: Option<Length>,
    /// The vertical position from the anchor.
    pub y: Option<Length>,
    /// The horizontal alignment, which wins over `x`.
    pub x_align: Option<Align>,
    /// What `x` is measured from.
    pub h_anchor: Anchor,
    /// What `y` is measured from.
    pub v_anchor: Anchor,
    /// Whether the frame lies where its text would lie (`w:yAlign="inline"`).
    pub inline: bool,
    /// The vertical alignment, which wins over `y`: at the top, in the middle or at the
    /// bottom of the anchor area.
    pub y_align: Option<Align>,
    /// Whether `w:vAnchor` is given. Without it, `v_anchor` says `Text`, and layout decides.
    pub v_anchor_named: bool,
    /// How the text around the frame flows (`w:wrap`).
    pub wrap: FrameWrap,
    /// The distances that the text keeps from the frame's sides and from its top and bottom
    /// (`w:hSpace` and `w:vSpace`).
    pub spacing: (Length, Length),
    /// The frame's height (`w:h`): exact, at least, or the content's when `None`.
    pub height: Option<(Length, bool)>,
    /// Whether the frame is a drop cap in the text (`w:dropCap="drop"`).
    pub drop_cap: bool,
    /// Whether the `w:framePr` makes a frame.
    pub mark: FrameMark,
    /// The attributes that the `w:framePr` and those of the styles under it set, from which
    /// the fields above come.
    attributes: Attributes,
}

/// The attributes that a `w:framePr` sets, as it reads them. A paragraph's `w:framePr` sets
/// each of them over that of its style, and a style's over that of the style it is based on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Attributes {
    width: Option<Length>,
    height: Option<Length>,
    x: Option<Length>,
    y: Option<Length>,
    h_space: Option<Length>,
    v_space: Option<Length>,
    x_align: Option<XAlign>,
    y_align: Option<YAlign>,
    h_anchor: Option<Anchor>,
    v_anchor: Option<Anchor>,
    wrap: Option<Wrap>,
    drop_cap: Option<bool>,
    rule: Option<HeightRule>,
}

impl Attributes {
    /// These attributes, with each that they do not set taken from `under`.
    fn over(self, under: Self) -> Self {
        Self {
            width: self.width.or(under.width),
            height: self.height.or(under.height),
            x: self.x.or(under.x),
            y: self.y.or(under.y),
            h_space: self.h_space.or(under.h_space),
            v_space: self.v_space.or(under.v_space),
            x_align: self.x_align.or(under.x_align),
            y_align: self.y_align.or(under.y_align),
            h_anchor: self.h_anchor.or(under.h_anchor),
            v_anchor: self.v_anchor.or(under.v_anchor),
            wrap: self.wrap.or(under.wrap),
            drop_cap: self.drop_cap.or(under.drop_cap),
            rule: self.rule.or(under.rule),
        }
    }
}

/// What a `w:framePr` does to its paragraph.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FrameMark {
    /// It makes a frame, which takes the paragraph out of the flow.
    #[default]
    Frame,
    /// It makes no frame, so its paragraph stays in the flow: neither it nor the `w:framePr`
    /// of a style under it sets an attribute that makes one.
    Plain,
}

/// How the text around a frame flows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FrameWrap {
    /// Lines flow beside the frame (`around`, `tight` and `through`), and also when `w:wrap`
    /// is `auto` or missing.
    #[default]
    Around,
    /// Lines go below the frame (`notBeside`).
    NotBeside,
    /// Lines do not move for the frame (`none`).
    None,
}

/// A value of `ST_Wrap`, with `auto` apart from `none`, which the mark of a frame tells apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Wrap {
    Auto,
    NotBeside,
    Around,
    Tight,
    Through,
    None,
}

impl Wrap {
    /// How the text flows around the frame: `auto`, `tight` and `through` as `around`.
    const fn flow(self) -> FrameWrap {
        match self {
            Self::None => FrameWrap::None,
            Self::NotBeside => FrameWrap::NotBeside,
            Self::Auto | Self::Around | Self::Tight | Self::Through => FrameWrap::Around,
        }
    }
}

/// `ST_Wrap`: `auto`, `tight` and `through` are drawn as `around`.
pub(super) const WRAP: &Values<Wrap> = &Values::new(&[
    another("auto", Wrap::Auto),
    own("notBeside", Wrap::NotBeside),
    own("around", Wrap::Around),
    another("tight", Wrap::Tight),
    another("through", Wrap::Through),
    own("none", Wrap::None),
]);

/// `ST_DropCap`, as whether the frame is a drop cap in the text: a drop cap in the margin is
/// drawn as no drop cap.
pub(super) const DROP_CAP: &Values<bool> = &Values::new(&[
    own("none", false),
    own("drop", true),
    another("margin", false),
]);

impl FramePr {
    /// Whether the frame lies where its text would lie: inline, from the start of the text
    /// column, by its left alignment, which wins over `x`, or by an `x` of 0 or none.
    #[must_use]
    pub fn in_place(&self) -> bool {
        self.inline
            && self.h_anchor == Anchor::Text
            && match self.x_align {
                Some(align) => align == Align::Start,
                None => self.x.is_none_or(|x| x == Length::ZERO),
            }
    }

    /// Whether a `w:framePr` makes a frame: an attribute of place or wrap has a value that
    /// takes the paragraph out of the flow (`named`), or one of `lengths`, the width, the height
    /// and the place that the frame reads, is not 0.
    fn mark(named: bool, lengths: [Option<Length>; 4]) -> FrameMark {
        let sized = lengths
            .iter()
            .any(|length| length.is_some_and(|length| length != Length::ZERO));
        if named || sized {
            FrameMark::Frame
        } else {
            FrameMark::Plain
        }
    }

    /// Reads `w:framePr` (ECMA-376 Part 1, 17.3.1.11).
    pub(super) fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let [width, height, x, y] = ["w", "h", "x", "y"].map(|name| reader.twips(node, name));
        let [h_space, v_space] = ["hSpace", "vSpace"].map(|name| reader.twips(node, name));
        Self::of(Attributes {
            width,
            height,
            x,
            y,
            h_space,
            v_space,
            x_align: reader.enumeration(node, "xAlign", X_ALIGN),
            y_align: reader.enumeration(node, "yAlign", Y_ALIGN),
            h_anchor: reader.enumeration(node, "hAnchor", ANCHOR),
            v_anchor: reader.enumeration(node, "vAnchor", ANCHOR),
            wrap: reader.enumeration(node, "wrap", WRAP),
            drop_cap: reader.enumeration(node, "dropCap", DROP_CAP),
            rule: reader.enumeration(node, "hRule", HEIGHT_RULE),
        })
    }

    /// Sets the frame of `nearer`, a paragraph's or a style's, over `frame`, that of the style
    /// under it: each attribute that `nearer` sets wins, and the others stay. Whether the frame
    /// is one follows from the attributes together.
    pub(super) fn overlay(frame: &mut Option<Box<Self>>, nearer: Option<&Self>) {
        if let Some(nearer) = nearer {
            let attributes = frame.as_deref().map_or(nearer.attributes, |under| {
                nearer.attributes.over(under.attributes)
            });
            *frame = Some(Box::new(Self::of(attributes)));
        }
    }

    /// The frame that `attributes` give.
    fn of(attributes: Attributes) -> Self {
        let Attributes {
            width,
            height,
            x,
            y,
            h_space,
            v_space,
            x_align,
            y_align,
            h_anchor,
            v_anchor,
            wrap,
            drop_cap,
            rule,
        } = attributes;
        // Each of these attributes makes a frame unless its value is one that makes none:
        // `auto` of `w:wrap`, `text` of `w:hAnchor`, `margin` and `page` of `w:vAnchor`, `left`
        // of `w:xAlign` and `inline` of `w:yAlign`. A value that does not read makes none.
        let named = wrap.is_some_and(|wrap| wrap != Wrap::Auto)
            || h_anchor.is_some_and(|anchor| anchor != Anchor::Text)
            || v_anchor == Some(Anchor::Text)
            || x_align.is_some_and(|align| align != XAlign::Left)
            || y_align.is_some_and(|align| align != YAlign::Inline);
        Self {
            width: width.filter(|w| *w > Length::ZERO),
            x,
            y,
            x_align: x_align.map(XAlign::align),
            h_anchor: h_anchor.unwrap_or_default(),
            v_anchor: v_anchor.unwrap_or_default(),
            v_anchor_named: v_anchor.is_some(),
            inline: y_align == Some(YAlign::Inline),
            y_align: y_align.and_then(YAlign::align),
            wrap: wrap.map_or_else(FrameWrap::default, Wrap::flow),
            spacing: (
                h_space.unwrap_or(Length::ZERO),
                v_space.unwrap_or(Length::ZERO),
            ),
            // The frame is as tall as `w:h` when the rule is exact, at least `w:h` when it is
            // at least or missing, and as its content when it is `auto`, as a table row is.
            height: height
                .filter(|h| *h > Length::ZERO)
                .and_then(|h| match rule {
                    Some(HeightRule::Exact) => Some((h, true)),
                    Some(HeightRule::Auto) => None,
                    Some(HeightRule::AtLeast) | None => Some((h, false)),
                }),
            drop_cap: drop_cap.unwrap_or(false),
            mark: Self::mark(named, [width, height, x, y]),
            attributes,
        }
    }
}