f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The text that a placed line shows, with where each of its clusters lies on the page, for a
//! viewer that selects, copies and searches the text of drawn pages.

use f_office_paint::Turn;
use f_office_units::Length;

use crate::lines::{EndHyphen, Line, LineEnd, Piece};
use crate::text::{AUTOMATIC_HYPHEN, LINE_END_HYPHEN, NON_BREAKING_HYPHEN, SOFT_HYPHEN};
use crate::text_map::text_offset;

/// The character that stands in a line's text for an inline object, the object replacement
/// character.
const OBJECT: char = '\u{FFFC}';

/// The text that a placed line shows (**Line text**): its characters in the order of the text,
/// its clusters in visual order with their edges on the page, its left edge, how it ends, and
/// the hyphen that it shows at its end where a word breaks, which is not in its text. The texts of a paragraph's lines, joined
/// in order, are the paragraph's text as the layout shows it: a field gives its shown result,
/// a list label is given as drawn, and hidden text is left out.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LineText {
    /// The characters in the order of the text: those of its glyphs, a tab as `\t`, a line,
    /// page or column break as `\n` and an inline object as U+FFFC.
    pub text: String,
    /// The clusters in visual order, from the left.
    pub clusters: Vec<TextCluster>,
    /// The left edge of its text on the page: its first cluster's left edge, or for a line
    /// without a cluster, such as the line of an empty paragraph, where the line starts after
    /// its indent and alignment.
    pub left: Length,
    /// How the line ends.
    pub end: LineTextEnd,
    /// The hyphen that the line draws at its end where a word breaks, at an automatic
    /// hyphenation point or a soft hyphen, which its text does not hold.
    pub hyphen: Option<EndHyphen>,
    /// For a line laid out upright in a frame that then turned onto the page, such as a line of
    /// a table cell with a turned text direction, how the frame lies on the page. The line's
    /// top, left edge and cluster edges are then places of the frame.
    pub turn: Option<LineTurn>,
    /// The parts of its text that show the glyphs of one run each, in the order of the text,
    /// which the text map reads to find where a hyperlink's text and a bookmark lie.
    pub(crate) runs: Vec<RunSpan>,
}

/// A part of a line's text from the first to the last glyph of one run of its paragraph
/// (**Run span**): the tabs and breaks between those glyphs are in it, those after the last one
/// are not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RunSpan {
    /// The first byte of the line's text that it holds.
    pub(crate) start: u32,
    /// The byte after the last that it holds.
    pub(crate) end: u32,
    /// The index of the run among the runs of the paragraph; none for a list label.
    pub(crate) run: Option<u32>,
}

/// How the upright frame of a turned line lies on the page (**Line turn**): a point of the
/// frame lands on the page at `to`, plus its offset from `from` turned by `turn`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineTurn {
    /// The point of the frame that lands at `to`.
    pub from: (Length, Length),
    /// Where `from` lies on the page.
    pub to: (Length, Length),
    /// The turn of an offset in the frame onto the page.
    pub turn: Turn,
}

/// A cluster of a line's text: one glyph or a tab with the ligature parts and combining marks
/// that join it, the bytes of the line's text that it shows, and its edges on the page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextCluster {
    /// The first byte of the line's text that it shows.
    pub start: u32,
    /// The byte after the last that it shows.
    pub end: u32,
    /// Its left edge on the page.
    pub left: Length,
    /// Its right edge on the page.
    pub right: Length,
}

/// How a line ends.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineTextEnd {
    /// Before a word that the line does not hold, or inside one.
    #[default]
    Wrap,
    /// At a line break.
    LineBreak,
    /// At a page break.
    PageBreak,
    /// At a column break.
    ColumnBreak,
    /// At the end of its paragraph.
    Paragraph,
    /// At the end of the last paragraph of a table cell, which only the text map tells apart
    /// from the end of a paragraph.
    Cell,
}

/// The text of `line`, which starts at `start` on the page and whose pieces lie in visual order
/// at `edges`, the piece at each visual place being the piece of `line` that `order` names there
/// (empty when the orders are the same); `last` when it is the last line of its paragraph.
pub(super) fn line_text(
    line: &Line,
    (start, edges): (Length, &[(Length, Length)]),
    order: &[usize],
    last: bool,
) -> LineText {
    let visual_of = visual_places(order, line.placed.len());
    let hyphen = line.hyphen.and_then(|_| {
        line.placed
            .iter()
            .rposition(|placed| matches!(placed.piece, Piece::Glyph(_)))
    });
    let mut read = Reading::default();
    for (own, placed) in line.placed.iter().enumerate() {
        if let Some(ch) = piece_char(&placed.piece).filter(|_| Some(own) != hyphen) {
            let visual = visual_of.get(own).copied().unwrap_or(own);
            let joins = matches!(placed.piece, Piece::Glyph(glyph) if glyph.part)
                || unicode_normalization::char::is_combining_mark(ch);
            let edge = edges.get(visual).copied().unwrap_or_default();
            let start = read.text.len();
            read.add(ch, joins, (visual, edge));
            if let Piece::Glyph(glyph) = placed.piece {
                let run = (!glyph.label).then_some(glyph.place.run).flatten();
                read.span(run, start);
            }
        }
    }
    let end = line_end(line.end, last);
    let right = edges.iter().map(|&(_, right)| right).max();
    LineText {
        hyphen: line.hyphen,
        ..read.close(end, right.unwrap_or(start))
    }
}

/// For each piece of a line of `count` pieces, its place in visual order, where `order` gives
/// the piece at each visual place, or is empty when the orders are the same.
fn visual_places(order: &[usize], count: usize) -> Vec<usize> {
    if order.is_empty() {
        return (0..count).collect();
    }
    let mut visual_of = vec![0; count];
    for (visual, &own) in order.iter().enumerate() {
        if let Some(slot) = visual_of.get_mut(own) {
            *slot = visual;
        }
    }
    visual_of
}

/// How a line that ends at `end` ends its text, `last` when it is the last line of its
/// paragraph.
const fn line_end(end: LineEnd, last: bool) -> LineTextEnd {
    match end {
        _ if last => LineTextEnd::Paragraph,
        LineEnd::Wrap | LineEnd::Split => LineTextEnd::Wrap,
        LineEnd::Break(_) => LineTextEnd::LineBreak,
        LineEnd::PageBreak => LineTextEnd::PageBreak,
        LineEnd::ColumnBreak => LineTextEnd::ColumnBreak,
    }
}

/// A line's text as it is read, with each cluster's place in visual order and the spans of its
/// runs.
#[derive(Default)]
struct Reading {
    text: String,
    clusters: Vec<(usize, TextCluster)>,
    runs: Vec<RunSpan>,
}

impl Reading {
    /// Notes that the character just added at the byte `start` is a glyph of the run `run`: it
    /// ends the span of the last glyph when that glyph has the same run, and else starts a span.
    fn span(&mut self, run: Option<u32>, start: usize) {
        let end = text_offset(self.text.len());
        match self.runs.last_mut().filter(|span| span.run == run) {
            Some(span) => span.end = end,
            None => self.runs.push(RunSpan {
                start: text_offset(start),
                end,
                run,
            }),
        }
    }

    /// Adds the character `ch` of the piece at the visual place `visual`, whose edges are
    /// `edge`: to the last cluster when it `joins` it, and else as a cluster of its own.
    fn add(&mut self, ch: char, joins: bool, (visual, (left, right)): (usize, (Length, Length))) {
        let start = text_offset(self.text.len());
        self.text.push(ch);
        let end = text_offset(self.text.len());
        match self.clusters.last_mut().filter(|_| joins) {
            Some((_, cluster)) => {
                cluster.end = end;
                cluster.left = cluster.left.min(left);
                cluster.right = cluster.right.max(right);
            }
            None => self.clusters.push((
                visual,
                TextCluster {
                    start,
                    end,
                    left,
                    right,
                },
            )),
        }
    }

    /// The line's text, which ends at `end`, with its clusters in visual order. A break that
    /// ends the line without a piece of its own still ends its text, with an empty cluster at
    /// the line's right edge `right`, which is also the left edge of a line without a cluster.
    fn close(mut self, end: LineTextEnd, right: Length) -> LineText {
        self.clusters.sort_by_key(|&(visual, _)| visual);
        let breaks = matches!(
            end,
            LineTextEnd::LineBreak | LineTextEnd::PageBreak | LineTextEnd::ColumnBreak
        );
        if breaks && !self.text.ends_with('\n') {
            self.add('\n', false, (usize::MAX, (right, right)));
        }
        let clusters: Vec<TextCluster> = self
            .clusters
            .into_iter()
            .map(|(_, cluster)| cluster)
            .collect();
        LineText {
            text: self.text,
            left: clusters.first().map_or(right, |cluster| cluster.left),
            clusters,
            end,
            hyphen: None,
            turn: None,
            runs: self.runs,
        }
    }
}

/// The character that a piece gives a line's text, or none for a piece without text.
fn piece_char(piece: &Piece) -> Option<char> {
    match piece {
        Piece::Glyph(glyph) => match glyph.ch {
            NON_BREAKING_HYPHEN => Some('\u{2011}'),
            SOFT_HYPHEN => Some('\u{AD}'),
            AUTOMATIC_HYPHEN | LINE_END_HYPHEN => None,
            ch => Some(ch),
        },
        Piece::Tab(_) | Piece::PositionTab(..) => Some('\t'),
        Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak => Some('\n'),
        Piece::Object { .. } | Piece::CheckBox { .. } => Some(OBJECT),
        Piece::Note(_)
        | Piece::NoteMarkEnd
        | Piece::Comment(_)
        | Piece::Anchor(_)
        | Piece::Strut(_)
        | Piece::Clear
        | Piece::Rule { .. }
        | Piece::Shift(_)
        | Piece::Advance(_)
        | Piece::Bar { .. }
        | Piece::Vinculum { .. }
        | Piece::Diagonal { .. } => None,
    }
}