f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The text of a drawn chart's own title and of its axis titles where the target's quirk
//! `ChartPlotArea` is `FontLines` and the reader keeps the title's text. Each paragraph of the
//! chart's title goes on as many lines as its width needs: a line holds the most whole words
//! that are not wider than a share of the frame's width less a length. Each line stands
//! centered on the frame in the title's face at its size, below the frame's top, or, for a
//! title at the corner of its manual layout, centered on its widest line in a box at that
//! corner. An axis title of one line stands beside its side of the plot area, centered on it
//! ([`Layout::axis_title_items`]).

use f_office_paint::{Item, Rgb};
use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Edges, Length};

use crate::chart::{AxisTitle, Columns, LayoutCorner, LegendPlace, PlotPlace, Title, TitleText};
use crate::layout::Layout;
use crate::params::{
    CHART_AXIS_TITLE_GAP, CHART_CATEGORY_TITLE_BOTTOM, CHART_LINES_LABEL_START,
    CHART_TITLE_CORNER_LEFT, CHART_TITLE_CORNER_TOP, CHART_TITLE_LINE_INSET,
    CHART_TITLE_LINE_SHARE, CHART_TITLE_LINE_TOP, CHART_VALUE_TITLE_LEFT,
};
use crate::props::RunProps;

use super::categories::UPWARD;
use super::labels::ChartText;
use super::{LabelLines, ValueAxis, layout_corner};

impl Layout<'_> {
    /// The lines of the chart's title `title` in the frame `frame`, or `None` when F-Office does
    /// not draw its text ([`Title::text`]) or does not break it ([`Self::title_lines`]). Each
    /// line is centered by the sum of its advances in the title's face at its size: on the
    /// frame, or on the title's widest line at the corner of its manual layout
    /// ([`corner_place`]). The first baseline lies the face's single line, less its win
    /// descent, below the line's top: [`CHART_TITLE_LINE_TOP`] below the frame's top, or
    /// [`CHART_TITLE_CORNER_TOP`] below the corner. Each further line lies one single line
    /// lower. An empty line draws nothing and keeps its place.
    pub(super) fn chart_title(&mut self, title: &Title, frame: Edges<Length>) -> Option<Vec<Item>> {
        let text = title.text.as_ref()?;
        let lines = self.title_lines(title, frame)?;
        let props = title_props(title.size, text);
        let face = self.shaper.face(&props, true)?;
        let face = self.shaper.faces().get(face)?;
        let line = face.line_height();
        let descent = face.win_line() - face.win_top();
        let color = self.label_color(text.fill.as_ref());
        let (middle, top) = match title.corner {
            None => (
                (frame.left + frame.right).div_toward_zero(2),
                frame.top + CHART_TITLE_LINE_TOP,
            ),
            Some(corner) => corner_place(frame, corner, &lines)?,
        };
        let mut baseline = top + line - descent;
        let mut items = Vec::with_capacity(lines.len());
        for shaped in lines {
            if let Some(shaped) = shaped {
                let width = shaped.width();
                items.push(shaped.item(middle - width.div_toward_zero(2), baseline, color)?);
            }
            baseline += line;
        }
        Some(items)
    }

    /// The rooms that the chart's axis titles take from the plot area, at its left and at its
    /// bottom: each the single line of its face at its size (its win line and its external
    /// leading) and [`CHART_AXIS_TITLE_GAP`], or nothing without the title. Manual-layout axis
    /// titles still reserve this room from an automatic plot area.
    pub(super) fn axis_title_rooms(&mut self, chart: &Columns) -> Option<(Length, Length)> {
        let (left, bottom) = chart.axis_titles.sides(&chart.group)?;
        let mut room = |title: Option<&AxisTitle>| {
            title.map_or(Some(Length::ZERO), |title| {
                Some(self.lines_of(&axis_title_props(title))?.single_line + CHART_AXIS_TITLE_GAP)
            })
        };
        Some((room(left)?, room(bottom)?))
    }

    /// The items of the chart's axis titles beside its plot area `plot` in the frame `frame`,
    /// or `None` when a title does not shape in one face or an automatic title is longer than its
    /// side of the plot area, which F-Office does not break.
    pub(super) fn axis_title_items(
        &mut self,
        chart: &Columns,
        (axis, plot): (&ValueAxis, Edges<Length>),
        frame: Edges<Length>,
    ) -> Option<Vec<Item>> {
        let (left, bottom) = chart.axis_titles.sides(&chart.group)?;
        let mut items = Vec::with_capacity(2);
        if let Some(title) = left {
            items.push(self.left_axis_title_item(chart, title, (axis, plot), frame)?);
        }
        if let Some(title) = bottom {
            items.push(self.bottom_axis_title_item(chart, title, (axis, plot), frame)?);
        }
        Some(items)
    }

    /// The upward-rotated item of the left axis title `title`: at its manual layout corner
    /// (the `-90°` transpose of [`corner_place`]), at [`CHART_VALUE_TITLE_LEFT`] on an automatic
    /// plot area, or beside the left tick labels on a manual plot area.
    fn left_axis_title_item(
        &mut self,
        chart: &Columns,
        title: &AxisTitle,
        (axis, plot): (&ValueAxis, Edges<Length>),
        frame: Edges<Length>,
    ) -> Option<Item> {
        let (shaped, lines, color) = self.axis_title_text(title)?;
        let width = shaped.width();
        let start = if let Some(corner) = title.corner {
            let (left, top) = layout_corner(frame, corner)?;
            let box_left = left.min(
                frame.right - lines.single_line - CHART_TITLE_CORNER_TOP - CHART_TITLE_CORNER_TOP,
            );
            let box_top =
                top.min(frame.bottom - width - CHART_TITLE_CORNER_LEFT - CHART_TITLE_CORNER_LEFT);
            (
                box_left + CHART_TITLE_CORNER_TOP + lines.single_top,
                box_top + CHART_TITLE_CORNER_LEFT + width,
            )
        } else {
            if width > plot.bottom - plot.top {
                return None;
            }
            let box_left = match chart.plot_place {
                PlotPlace::Automatic => frame.left + CHART_VALUE_TITLE_LEFT,
                PlotPlace::Manual(_) => {
                    let labels = self.left_labels_room(chart, axis)?;
                    (plot.left - labels) - (lines.single_line + CHART_AXIS_TITLE_GAP)
                        + (CHART_VALUE_TITLE_LEFT - CHART_LINES_LABEL_START)
                }
                PlotPlace::Other => return None,
            };
            (
                box_left + lines.single_top,
                (plot.top + plot.bottom + width).div_toward_zero(2),
            )
        };
        shaped.turned_item(start, (UPWARD, color), |reached| {
            Some((Length::ZERO, -reached))
        })
    }

    /// The upright item of the bottom axis title `title`: at its manual layout corner
    /// ([`CHART_TITLE_CORNER_LEFT`], [`CHART_TITLE_CORNER_TOP`]), above any bottom legend at
    /// [`CHART_CATEGORY_TITLE_BOTTOM`] on an automatic plot area, or below the bottom tick labels
    /// on a manual plot area.
    fn bottom_axis_title_item(
        &mut self,
        chart: &Columns,
        title: &AxisTitle,
        (axis, plot): (&ValueAxis, Edges<Length>),
        frame: Edges<Length>,
    ) -> Option<Item> {
        let (shaped, lines, color) = self.axis_title_text(title)?;
        let width = shaped.width();
        let (start, baseline) = if let Some(corner) = title.corner {
            let (left, top) = layout_corner(frame, corner)?;
            let box_left =
                left.min(frame.right - width - CHART_TITLE_CORNER_LEFT - CHART_TITLE_CORNER_LEFT);
            let box_top = top.min(
                frame.bottom - lines.single_line - CHART_TITLE_CORNER_TOP - CHART_TITLE_CORNER_TOP,
            );
            (
                box_left + CHART_TITLE_CORNER_LEFT,
                box_top + CHART_TITLE_CORNER_TOP + lines.single_top,
            )
        } else {
            if width > plot.right - plot.left {
                return None;
            }
            let baseline = match chart.plot_place {
                PlotPlace::Automatic => {
                    let legend = if chart.legend == Some(LegendPlace::Bottom) {
                        let leg_lines = self.legend_lines(chart)?;
                        self.horizontal_legend_room(chart, leg_lines, frame)?
                    } else {
                        Length::ZERO
                    };
                    frame.bottom - legend - CHART_CATEGORY_TITLE_BOTTOM - (lines.line - lines.top)
                }
                PlotPlace::Manual(_) => {
                    let below = self.below_labels_room(chart, axis, plot, frame)?;
                    plot.bottom + below + (lines.single_line + CHART_AXIS_TITLE_GAP)
                        - CHART_CATEGORY_TITLE_BOTTOM
                        - (lines.line - lines.top)
                }
                PlotPlace::Other => return None,
            };
            (
                (plot.left + plot.right - width).div_toward_zero(2),
                baseline,
            )
        };
        shaped.item(start, baseline, color)
    }

    /// The axis title `title` shaped in its face at its size, with the win line and the top of
    /// that face and the title's color.
    fn axis_title_text(&mut self, title: &AxisTitle) -> Option<(ChartText, LabelLines, Rgb)> {
        let props = axis_title_props(title);
        let line = title.text.lines.first()?;
        let shaped = self.chart_text(&props, line)?;
        let lines = self.lines_of(&props)?;
        Some((shaped, lines, self.label_color(title.text.fill.as_ref())))
    }

    /// The number of lines of the title `title` in the frame `frame`: the lines of its text as
    /// [`Self::title_lines`] breaks them, or the number that the reader gives ([`Title::lines`])
    /// when F-Office does not draw its text.
    pub(super) fn title_line_count(&mut self, title: &Title, frame: Edges<Length>) -> Option<i64> {
        let count = self
            .title_lines(title, frame)
            .map_or(title.lines, |lines| lines.len());
        i64::try_from(count).ok()
    }

    /// The lines of the title's text in the frame `frame`, each shaped, or `None` for an empty
    /// line: each paragraph on one line when the sum of its advances is at most
    /// [`CHART_TITLE_LINE_SHARE`] of the frame's width less [`CHART_TITLE_LINE_INSET`], else
    /// broken at its spaces so that each line holds the most whole words that fit that width. `None` when F-Office does not draw
    /// the text, when a line does not shape in one face, when a word alone is wider, or when a
    /// paragraph to break holds two spaces in a row, at its start or at its end.
    fn title_lines(
        &mut self,
        title: &Title,
        frame: Edges<Length>,
    ) -> Option<Vec<Option<ChartText>>> {
        let text = title.text.as_ref()?;
        let props = title_props(title.size, text);
        let limit = (frame.right - frame.left)
            .checked_mul(CHART_TITLE_LINE_SHARE)?
            .div_toward_zero(THOUSANDTHS)
            - CHART_TITLE_LINE_INSET;
        let mut lines = Vec::with_capacity(text.lines.len());
        for paragraph in &text.lines {
            if paragraph.is_empty() {
                lines.push(None);
                continue;
            }
            let whole = self.chart_text(&props, paragraph)?;
            if whole.width() <= limit {
                lines.push(Some(whole));
                continue;
            }
            for broken in self.broken_lines(&props, paragraph, limit)? {
                lines.push(Some(broken));
            }
        }
        Some(lines)
    }

    /// The paragraph `paragraph` in `props` broken at its spaces: each line holds the most
    /// whole words whose sum of advances is at most `limit`, or `None` when a word alone is
    /// wider or the paragraph holds an empty word (two spaces in a row, or one at its start
    /// or end).
    fn broken_lines(
        &mut self,
        props: &RunProps,
        paragraph: &str,
        limit: Length,
    ) -> Option<Vec<ChartText>> {
        let words: Vec<&str> = paragraph.split(' ').collect();
        if words.iter().any(|word| word.is_empty()) {
            return None;
        }
        let mut lines = Vec::new();
        let mut start = 0;
        while start < words.len() {
            let mut end = start + 1;
            let mut line = self.chart_text(props, &words.get(start..end)?.join(" "))?;
            if line.width() > limit {
                return None;
            }
            while end < words.len() {
                let longer = self.chart_text(props, &words.get(start..=end)?.join(" "))?;
                if longer.width() > limit {
                    break;
                }
                line = longer;
                end += 1;
            }
            lines.push(line);
            start = end;
        }
        Some(lines)
    }
}

/// The middle of a title's widest line and the top of its first line, for a title of the
/// shaped lines `lines` at the corner `corner` of its manual layout in the frame `frame`. The
/// title's box starts at the corner, or further left when its widest line, with
/// [`CHART_TITLE_CORNER_LEFT`] on each side, would end past the frame's right edge; the widest
/// line starts [`CHART_TITLE_CORNER_LEFT`] right of the box's left. The line's top lies
/// [`CHART_TITLE_CORNER_TOP`] below the corner.
fn corner_place(
    frame: Edges<Length>,
    corner: LayoutCorner,
    lines: &[Option<ChartText>],
) -> Option<(Length, Length)> {
    let (left, top) = layout_corner(frame, corner)?;
    let widest = lines
        .iter()
        .flatten()
        .map(ChartText::width)
        .max()
        .unwrap_or_default();
    let start = left.min(frame.right - widest - CHART_TITLE_CORNER_LEFT - CHART_TITLE_CORNER_LEFT);
    Some((
        start + CHART_TITLE_CORNER_LEFT + widest.div_toward_zero(2),
        top + CHART_TITLE_CORNER_TOP,
    ))
}

/// The run properties of the axis title `title`: its font, bold and italic at its size.
fn axis_title_props(title: &AxisTitle) -> RunProps {
    title_props(title.size, &title.text)
}

/// The run properties of a title's text `text` at `size` half-points: its font, bold and
/// italic as it says.
fn title_props(size: i64, text: &TitleText) -> RunProps {
    RunProps {
        font_ascii: Some(text.font.clone()),
        font_hansi: Some(text.font.clone()),
        size: Some(size),
        bold: text.bold.then_some(true),
        italic: text.italic.then_some(true),
        ..RunProps::default()
    }
}