f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! Where the text after a tab to a right or a center stop starts on a device that starts an
//! aligned line on a dot.

use f_office_units::Length;

use super::Origin;
use crate::grid::{Device, EdgeSteps, Rounding};
use crate::layout::Layout;
use crate::lines::{Line, Piece, Placed, following_width};
use crate::props::TabKind;

/// The text after a tab to a right or a center stop, as a drawing of its line places it.
#[derive(Clone, Copy, Debug)]
pub(super) struct TabText {
    /// The index of the tab's piece in its line.
    tab: usize,
    /// Whether the stop is a center stop; else it is a right stop.
    centered: bool,
    /// The dot and the exact place of the text's first glyph.
    first: Option<(Length, Length)>,
    /// The exact right edge of the text's last glyph that is not a space.
    visible_end: Option<Length>,
    /// The dot of the first space after the text's last glyph that is not a space.
    trails: Option<Length>,
    /// The dot where the text's written end lies.
    end: Option<Length>,
}

/// What a drawing of a line does with the text after its tabs to right and center stops.
#[derive(Debug)]
pub(super) enum TabTexts {
    /// Draws the line as its exact places give it, and keeps where the text after each such
    /// tab starts and ends.
    Find {
        open: Option<TabText>,
        found: Vec<TabText>,
    },
    /// Puts the first glyph after each tab of `starts`, by its piece's index, on the dot
    /// that it names.
    Place {
        starts: Vec<(usize, Length)>,
        pending: Option<Length>,
    },
}

impl Default for TabTexts {
    fn default() -> Self {
        Self::Place {
            starts: Vec::new(),
            pending: None,
        }
    }
}

/// Whether `placed` is a tab to a right or a center stop that moved the text after it, and
/// whether it is a center stop.
fn aligned_tab(placed: &Placed) -> Option<bool> {
    if !matches!(placed.piece, Piece::Tab(_) | Piece::PositionTab(..))
        || placed.advance <= Length::ZERO
    {
        return None;
    }
    match placed.tab {
        Some(TabKind::Right) => Some(false),
        Some(TabKind::Center) => Some(true),
        _ => None,
    }
}

impl TabTexts {
    /// After the piece `placed` at `index`, which has a width and ends the text before it:
    /// opens the text after it when it is a tab to a right or a center stop, or says where
    /// that text's first glyph goes.
    pub(super) fn after_gap(&mut self, index: usize, placed: &Placed) {
        match self {
            Self::Find { open, .. } => {
                *open = aligned_tab(placed).map(|centered| TabText {
                    tab: index,
                    centered,
                    first: None,
                    visible_end: None,
                    trails: None,
                    end: None,
                });
            }
            Self::Place { starts, pending } => {
                *pending = starts
                    .iter()
                    .find(|(tab, _)| *tab == index)
                    .map(|&(_, dot)| dot);
            }
        }
    }

    /// The dot that the next glyph goes to, when it is the first after a tab whose text
    /// [`Self::Place`] places.
    pub(super) fn take_start(&mut self) -> Option<Length> {
        match self {
            Self::Place { pending, .. } => pending.take(),
            Self::Find { .. } => None,
        }
    }

    /// Keeps the glyph at the dot `at`, whose exact place and advance are `x` and `advance`,
    /// in the open text, where `space` says that it is a space (U+0020), the only character
    /// that the width that a stop takes leaves out at the text's end ([`following_width`]).
    pub(super) fn glyph(&mut self, at: Length, (x, advance): (Length, Length), space: bool) {
        let Self::Find {
            open: Some(text), ..
        } = self
        else {
            return;
        };
        text.first.get_or_insert((at, x));
        if !space {
            text.visible_end = Some(x + advance);
            text.trails = None;
        } else if text.visible_end.is_some() && text.trails.is_none() {
            text.trails = Some(at);
        }
    }

    /// Ends the open text at `piece` when it is not a glyph, where the width that its stop
    /// takes ends too ([`following_width`]), with [`Self::close`].
    pub(super) fn at_piece(&mut self, piece: Piece, device: &Device, edge: &EdgeSteps) {
        if !matches!(piece, Piece::Glyph(_)) {
            self.close(device, edge);
        }
    }

    /// Ends the open text at a piece that is not a glyph or at the line's end, where `edge`
    /// holds the steps of its glyphs: its written end is the place of its first trailing space, or,
    /// with none, the dot that the steps give its exact end.
    pub(super) fn close(&mut self, device: &Device, edge: &EdgeSteps) {
        let Self::Find { open, found } = self else {
            return;
        };
        let Some(mut text) = open.take() else {
            return;
        };
        text.end = text.trails.or_else(|| edge.end(device, text.visible_end?));
        found.push(text);
    }

    /// The starts of the texts that a drawing found on `line`, drawn from `origin`: a text
    /// after a right stop ends on the stop's dot, and a text after a center stop starts half
    /// of its width in dots, rounded down, left of it. The stop's dot is the dot of its
    /// distance from the column's edge, with the halves of `Device::line_start`.
    fn starts(self, device: &Device, line: &Line, origin: &Origin) -> Vec<(usize, Length)> {
        let Self::Find { found, .. } = self else {
            return Vec::new();
        };
        found
            .into_iter()
            .filter_map(|text| {
                let (first_dot, first_x) = text.first?;
                let end = text.end? - first_dot;
                let tab = line.placed.get(text.tab)?;
                let after: Vec<Piece> = line
                    .placed
                    .get(text.tab + 1..)?
                    .iter()
                    .map(|placed| placed.piece)
                    .collect();
                let width = following_width(&after, None);
                let part = if text.centered {
                    width.div_toward_zero(2)
                } else {
                    width
                };
                let distance = tab.x + tab.advance + part;
                let stop = device.snap(
                    first_x + part + device.stop_halves((origin.start, origin.own), distance),
                );
                let back = if text.centered {
                    device.dots(device.count(end, Rounding::Down) / 2)
                } else {
                    end
                };
                Some((text.tab, stop - back))
            })
            .collect()
    }
}

impl Layout<'_> {
    /// How a drawing of `line` from `origin` places the text after its tabs to right and center
    /// stops. On a target that starts an aligned line on a dot, Word places such a text as it
    /// places an aligned line: from a dot, and then whole dots right, so that its written end
    /// lies on the stop's dot after a right stop, and its start half of its written width,
    /// rounded down, left of the stop's dot after a center stop. A line of a right-to-left
    /// paragraph or with an inline drawing keeps the exact places.
    pub(super) fn tab_texts(
        &mut self,
        line: &Line,
        order: super::draw::VisualOrder<'_>,
        origin: Origin,
    ) -> TabTexts {
        let boxed = line.placed.iter().any(|placed| {
            matches!(
                placed.piece,
                Piece::Object {
                    drawing: Some(_),
                    ..
                }
            )
        });
        if !self.device.aligns_on_dots()
            || boxed
            || origin.right_to_left.is_some()
            || !line
                .placed
                .iter()
                .any(|placed| aligned_tab(placed).is_some())
        {
            return TabTexts::default();
        }
        let drawn = self.items.len();
        let find = TabTexts::Find {
            open: None,
            found: Vec::new(),
        };
        let (_, _, found) = self.emit_with(line, order, origin, find);
        self.items.cut(drawn);
        TabTexts::Place {
            starts: found.starts(&self.device, line, &origin),
            pending: None,
        }
    }
}