f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! The border line list of the page items.

use std::collections::HashMap;

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

use super::Entry;
use crate::props::DashStyle;

/// The border line list: the places in the items being filled of the table border lines that
/// stand there, in the order of the items. A line that two passes give at one place, such as
/// the line between two cells side by side, a row's bottom line and the line that the row
/// draws again as the last on its page, or a header row's bottom line and the top line of the
/// row below it, is drawn once: `push_line` looks for it among these lines alone, so
/// that no other item can hide a border line. The list follows the items: a cut of the items
/// cuts it, and the part of a cell of a row that splits keeps the page's list while it fills
/// its own. A place counts only while the item there still equals
/// the line. The lines of such a part do not join the page's list when the part's items join
/// the page. Each place keeps the dashes that its line is to be drawn with, where the target
/// draws a line of a dash style as its dashes, until the line is cut at its junctions.
///
/// The list finds a line by the rectangle that stands at its place through an index. A new
/// line and a cut keep the index; a change of the items in place and a removal make it stale,
/// and the next look builds it again from the items as they stand.
#[derive(Debug, Default)]
pub(in crate::layout) struct BorderLines {
    /// The place of each line, in the order of the items, with its dashes.
    places: Vec<(usize, Option<DashStyle>)>,
    /// The places of the lines by the rectangle that stands at each, each list in the order of
    /// the items, or `None` when it is stale.
    index: Option<HashMap<LineKey, Vec<usize>>>,
}

/// The rectangle of a border line, as the index of the border line list keys it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct LineKey {
    x: Length,
    y: Length,
    width: Length,
    height: Length,
    color: Rgb,
}

impl LineKey {
    const fn of(rect: &Rect) -> Self {
        Self {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
            color: rect.color,
        }
    }
}

impl BorderLines {
    /// An empty list.
    pub(in crate::layout) const fn new() -> Self {
        Self {
            places: Vec::new(),
            index: None,
        }
    }

    /// Whether one of the lines of the list is the item `line` of `items`.
    pub(in crate::layout) fn holds(&mut self, items: &[Entry], line: &Item) -> bool {
        self.place_of(items, line).is_some()
    }

    /// The place in `items` of the first line of the list that is the item `line`, if any.
    pub(in crate::layout) fn place_of(&mut self, items: &[Entry], line: &Item) -> Option<usize> {
        let Item::Rect(rect) = line else {
            return None;
        };
        let places = &self.places;
        let index = self.index.get_or_insert_with(|| indexed(places, items));
        index
            .get(&LineKey::of(rect))?
            .iter()
            .copied()
            .find(|&at| item_at(items, at) == Some(line))
    }

    /// The dashes that the line at the place `at` is to be drawn with, if any.
    pub(in crate::layout) fn dash(&self, at: usize) -> Option<DashStyle> {
        let found = self.places.binary_search_by_key(&at, |&(place, _)| place);
        self.places.get(found.ok()?)?.1
    }

    /// Adds the line `line` at the place `at`, after the others, to be drawn with `dash`.
    pub(in crate::layout) fn push(&mut self, at: usize, dash: Option<DashStyle>, line: &Item) {
        self.places.push((at, dash));
        self.index_line(at, line);
    }

    /// Adds the lines `lines`, which are items, at the places from `at` on, after the others,
    /// drawn as they are.
    pub(in crate::layout) fn extend(&mut self, at: usize, lines: &[Entry]) {
        for (place, line) in (at..).zip(lines.iter().filter_map(Entry::item)) {
            self.places.push((place, None));
            self.index_line(place, line);
        }
    }

    /// Notes the line `line` at the place `at` in the index, while it is not stale.
    fn index_line(&mut self, at: usize, line: &Item) {
        if let (Some(index), Item::Rect(rect)) = (&mut self.index, line) {
            index.entry(LineKey::of(rect)).or_default().push(at);
        }
    }

    /// Drops the lines at `len` and after, when `items`, still whole, are cut to `len`. A line
    /// whose place an item no longer holds makes the index stale.
    pub(in crate::layout) fn cut(&mut self, len: usize, items: &[Entry]) {
        let kept = self.places.partition_point(|&(at, _)| at < len);
        let mut stale = false;
        if let Some(index) = &mut self.index {
            for &(at, _) in self.places.get(kept..).unwrap_or_default() {
                let Some(Item::Rect(rect)) = item_at(items, at) else {
                    stale = true;
                    break;
                };
                if let Some(places) = index.get_mut(&LineKey::of(rect)) {
                    while places.last().is_some_and(|&place| place >= len) {
                        places.pop();
                    }
                }
            }
        }
        if stale {
            self.index = None;
        }
        self.places.truncate(kept);
    }

    /// Notes that the items may change in place: the next look builds the index again.
    pub(in crate::layout) fn stale(&mut self) {
        self.index = None;
    }
}

/// The index of the lines at `places` of `items`: the places of each rectangle, in the order of
/// the items.
fn indexed(places: &[(usize, Option<DashStyle>)], items: &[Entry]) -> HashMap<LineKey, Vec<usize>> {
    let mut index: HashMap<LineKey, Vec<usize>> = HashMap::new();
    for &(at, _) in places {
        if let Some(Item::Rect(rect)) = item_at(items, at) {
            index.entry(LineKey::of(rect)).or_default().push(at);
        }
    }
    index
}

/// The item at the place `at` of `items`, when an item stands there.
fn item_at(items: &[Entry], at: usize) -> Option<&Item> {
    items.get(at)?.item()
}

#[cfg(test)]
mod tests {
    use f_office_paint::{Item, Rect, Rgb};
    use f_office_units::Length;

    use super::{BorderLines, Entry};

    /// A line ten units wide and one high at `y`.
    fn line(y: i64) -> Item {
        Item::Rect(Rect {
            x: Length::ZERO,
            y: Length::from_units(y),
            width: Length::from_units(10),
            height: Length::from_units(1),
            color: Rgb::default(),
        })
    }

    #[test]
    fn finds_a_line_by_its_rectangle_through_a_cut_and_a_push() {
        let mut items: Vec<Entry> = [0, 5, 0].map(|y| Entry::Item(line(y))).into();
        let mut lines = BorderLines::new();
        lines.extend(0, &items);
        assert_eq!(lines.place_of(&items, &line(0)), Some(0));
        lines.cut(1, &items);
        items.truncate(1);
        assert_eq!(lines.place_of(&items, &line(5)), None);
        lines.push(1, None, &line(9));
        items.push(Entry::Item(line(9)));
        assert_eq!(lines.place_of(&items, &line(0)), Some(0));
        assert_eq!(lines.place_of(&items, &line(9)), Some(1));
    }

    #[test]
    fn finds_a_line_by_its_rectangle_after_a_take_out_and_a_change_in_place() {
        let mut items: Vec<Entry> = [9, 0].map(|y| Entry::Item(line(y))).into();
        let mut lines = BorderLines::new();
        lines.extend(1, items.get(1..).unwrap_or_default());
        assert_eq!(lines.place_of(&items, &line(0)), Some(1));
        lines.push(2, None, &line(7));
        items.push(Entry::Item(line(7)));
        // A line taken out leaves its place empty, and the line stands there no more.
        if let Some(entry) = items.get_mut(1) {
            *entry = Entry::Empty;
        }
        assert_eq!(lines.place_of(&items, &line(0)), None);
        assert_eq!(lines.place_of(&items, &line(7)), Some(2));
        if let Some(Entry::Item(Item::Rect(r))) = items.get_mut(2) {
            r.y = Length::from_units(8);
        }
        lines.stale();
        assert_eq!(lines.place_of(&items, &line(8)), Some(2));
        // A cut past the empty place leaves the index right.
        lines.cut(1, &items);
        items.truncate(1);
        assert_eq!(lines.place_of(&items, &line(8)), None);
    }
}