f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! What a line draws in the margin: its line number and the bar of a tracked change.

use f_office_paint::{Item, Rect, Rgb};
use f_office_units::Length;

use super::Origin;
use crate::body::LineNumberRestart;
use crate::grid;
use crate::layout::Layout;
use crate::lines::{Line, LineEnd, Piece, Placed};
use crate::params;
use crate::props::ParaProps;
use crate::text::FaceIndex;

/// The ID of the character style that line numbers take.
const LINE_NUMBER_STYLE: &str = "LineNumber";

impl Layout<'_> {
    /// Counts a body line for the section's line numbers, and draws the number when
    /// `w:countBy` divides it. The number ends `w:distance` left of the column, on the line's
    /// baseline, in the run properties of the default paragraph style with the character
    /// style "Line Number" on top. Lines in table cells and paragraphs with
    /// `w:suppressLineNumbers` are not counted. Where its digits lie on the device is the
    /// variant of the quirk `DeviceAdvance` that the device carries.
    pub(super) fn line_number(&mut self, props: &ParaProps, line: &Line, baseline: Length) {
        let Some(numbers) = self.section.line_numbers else {
            return;
        };
        let flags = props.flags();
        if self.column.cell.is_some() || flags.suppress_line_numbers {
            return;
        }
        // The paragraph that ends a section before a new page has no number and does not
        // count when it holds nothing. With a space, it counts.
        if flags.section_end && line.placed.is_empty() {
            return;
        }
        let page = self.output.pages.len();
        if numbers.restart == LineNumberRestart::NewPage && self.output.line_count.1 != page {
            self.output.line_count.0 = 0;
        }
        self.output.line_count = (self.output.line_count.0 + 1, page);
        // The number stops at the largest whole number, as a page number and a note number do.
        let number = numbers.start.saturating_add(self.output.line_count.0);
        if number % numbers.count_by != 0 {
            return;
        }
        let (_, mut run) = self.styles.paragraph(None, None);
        self.styles.apply_character(&mut run, LINE_NUMBER_STYLE);
        let mut glyphs = Vec::new();
        self.shaper.measure(&run, &number.to_string(), &mut glyphs);
        let mut width = Length::ZERO;
        let placed = glyphs
            .iter()
            .map(|g| {
                let x = width;
                width += g.advance;
                Placed {
                    piece: Piece::Glyph(*g),
                    x,
                    advance: g.advance,
                    leader: None,
                    tab: None,
                }
            })
            .collect();
        let line = Line {
            placed,
            end: LineEnd::Wrap,
            kept: None,
            wrapped: None,
            would_hang: false,
            hung: false,
            anchors: Vec::new(),
            hyphen: None,
            written_end_spaces: 0,
        };
        let left = self.device.snap(self.column.left);
        let (x, steps_alone) =
            self.device
                .line_number_start(left, (numbers.distance, width), || {
                    (self.column_dot(), self.alone_width(&glyphs))
                });
        let origin = Origin {
            x,
            edge: left,
            start: Length::ZERO,
            own: Length::ZERO,
            baseline,
            unrounded_baseline: baseline,
            grid_shift: Length::ZERO,
            space_extra: Length::ZERO,
            space_rest: Length::ZERO,
            counted_shares: None,
            mark_shrink: Length::ZERO,
            mark_sides: super::shift::MarkSides::BlankHalf,
            gap_extra: Length::ZERO,
            narrowing: None,
            drop: Length::ZERO,
            anchor_bottom: None,
            text_from: 0,
            mark: false,
            right_to_left: None,
            starts_at_indent: false,
            segment_rest: Length::ZERO,
            steps_alone,
        };
        // The numbers of empty paragraphs on the page that a page break began do not keep a
        // section from starting on it.
        let only_numbers =
            self.page_from_break == Some(page) && self.items.count() == self.break_numbers.0;
        let _ = self.emit(&line, super::draw::VisualOrder::ltr(&line), origin);
        if only_numbers {
            self.break_numbers.0 = self.items.count();
        }
    }

    /// Marks a line that holds a tracked change with a black bar 0.72 pt wide in the margin,
    /// from the top of the line's part of the paragraph down to where the next line starts,
    /// and gives the bar's index in the page's items. The bar sits 36 pt left of the left
    /// margin on the device grid, or halfway into a margin narrower than 72 pt, rounded down to
    /// the device grid. With different odd and even headers, the bar of an odd page sits as far
    /// right of the right margin, rounded down. `mark` is the face of the paragraph mark on the
    /// paragraph's last line, which marks that line when the mark has a tracked change.
    pub(super) fn change_bar(
        &mut self,
        line: &Line,
        mark: Option<FaceIndex>,
        (top, height): (Length, Length),
    ) -> Option<usize> {
        let faces = self.shaper.faces();
        let face = |i: FaceIndex| faces.get(i).is_some_and(|f| f.lines.change_bar);
        let changed = mark.is_some_and(face)
            || line
                .placed
                .iter()
                .any(|placed| matches!(&placed.piece, Piece::Glyph(g) if face(g.face)));
        if !changed {
            return None;
        }
        // With odd and even headers, the bar of an odd page is right of the text. The left
        // margin counts where the text starts on the device grid.
        let number = self.inner_numbers().page;
        let inset = params::CHANGE_BAR_INSET;
        let x = if self.settings.even_and_odd_headers && number % 2 != 0 {
            let margin = self.section.right;
            self.section.width - margin + margin.div_toward_zero(2).min(inset)
        } else {
            let margin = self.device.snap(self.section.left);
            margin.div_toward_zero(2).max(margin - inset)
        };
        self.items.push(Item::Rect(Rect {
            x: self.device.floor(x),
            y: top,
            width: Length::from_units(params::CHANGE_BAR_WIDTH * grid::DOT),
            height,
            color: Rgb::BLACK,
        }));
        Some(self.items.len() - 1)
    }

    /// Lengthens the change bar beside the paragraph's last line by `extra`, the room that
    /// its bottom border takes below the line, when the bar is on the current page.
    pub(in crate::layout) fn lengthen_last_bar(&mut self, extra: Length) {
        let Some((page, index)) = self.last_bar.take() else {
            return;
        };
        if page != self.output.pages.len() {
            return;
        }
        if let Some(Item::Rect(bar)) = self.items.item_mut(index) {
            bar.height += extra;
        }
    }
}