f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The text of a table cell with a turned text direction (`w:textDirection` of `btLr` or
//! `tbRl`).

use super::{Slot, align};
use crate::grid::TextObject;
use crate::layout::{CellPlace, Column, Layout, LineTurn, TurnedGlyphs, Within, decisions};
use crate::table::{TextDirection, VerticalAlign};
use f_office_paint::{Item, PathCommand, Turn};
use f_office_units::Length;

/// The turn of the text that reads from bottom to top: a step along a line goes up the page,
/// and a step down a glyph goes right.
pub(in crate::layout) const UP: Turn = Turn {
    xx: 0,
    yx: -Turn::SCALE,
    xy: Turn::SCALE,
    yy: 0,
};

/// The turn of the text that reads from top to bottom: a step along a line goes down the page,
/// and a step down a glyph goes left.
pub(in crate::layout) const DOWN: Turn = Turn {
    xx: 0,
    yx: Turn::SCALE,
    xy: -Turn::SCALE,
    yy: 0,
};

impl Layout<'_> {
    /// Lays out the turned cells of a row from `top` to `bottom` ([`Self::turned_content`]).
    pub(super) fn turned_contents(&mut self, slots: &[Slot], (top, bottom): (Length, Length)) {
        for slot in slots.iter().filter(|slot| slot.turned()) {
            self.turned_content(slot, (top, bottom));
        }
    }

    /// Lays out the content of a turned cell of a row from `top` to `bottom`, the row's top
    /// below its border and its bottom: upright, in a frame as wide as the row is high less the
    /// cell's top and bottom margins and as high as the cell's text is wide, aligned across the
    /// frame as the cell's vertical alignment says, then turned onto the cell. The lines run
    /// along the cell's height and stack across it, past its sides where they do not fit. The
    /// records of the turned lines keep the places of the frame, with the frame's turn onto the
    /// page.
    pub(super) fn turned_content(&mut self, slot: &Slot, (top, bottom): (Length, Length)) {
        let turn = match slot.cell.direction {
            TextDirection::Upright => return,
            TextDirection::BottomToTop => UP,
            TextDirection::TopToBottom => DOWN,
        };
        let upright = slot.column(&self.context.quirks);
        let (left, across) = (upright.left, upright.width);
        let row_top = top + slot.margins.top;
        let along = (bottom - slot.margins.bottom - row_top).max(Length::ZERO);
        let dots = self.turned_dots(turn, slot.align());
        // For text that reads up, the frame's top side turns to the cell's text start.
        let frame_top = self.turned_frame_top(row_top, left, dots);
        let (start, lines) = (self.items.len(), self.output.placed.len());
        // The frame keeps the edge of the page's column, from which the cells after it take
        // their text edges.
        self.column = Column {
            width: along,
            within: Within::TurnedFrame(dots, turn, TurnedGlyphs::WithLine),
            origin: self.column.origin,
            ..upright.clone()
        };
        self.move_to(frame_top);
        // The frame's top carries the side on which the fixed-point sum of the cell's text side
        // lies, so that a line's place exactly half a dot past a whole dot rounds as that sum.
        self.y_rest = self.turned_side_rest(&upright, dots);
        self.previous = None;
        // Only the floor is a turned cell's own: the cell keeps the place and the boxes of the
        // flow that holds it.
        let outer_floor = self.cell_floor.replace(super::CellFloor::Clear);
        let outer_place = self.cell_place.replace(CellPlace {
            table: self.table_number,
            row: slot.row + 1,
            column: slot.first + 1,
        });
        // A cell that hides its end-of-cell mark leaves out an empty last paragraph.
        self.blocks(slot.cell.shown_blocks());
        self.cell_floor = outer_floor;
        self.cell_place = outer_place;
        self.previous = None;
        let used = self.y - frame_top;
        let down = align(slot.align(), across - used);
        // The frame's top side lies at the cell's text start for text that reads up, and at
        // its text end for text that reads down; its start lies at the cell's bottom or top.
        let origin = if turn == UP {
            (left, bottom - slot.margins.bottom)
        } else {
            (left + across, row_top)
        };
        let from = (left, frame_top - down);
        for item in self.items.items_mut_from(start) {
            turn_item(
                item,
                (from, origin),
                turn,
                decisions::upright_picture(&self.context.quirks, ()).is_some(),
            );
        }
        // Lines on the page's dots take the place across that the writer writes for a text
        // object's start there.
        if dots {
            let object = TextObject::of(&self.device);
            for item in self.items.items_mut_from(start) {
                write_across(item, &object);
            }
        }
        let placed = self.output.placed.get_mut(lines..).unwrap_or_default();
        for line in placed {
            line.text.turn = Some(turn_frame(line.text.turn, (from, origin), turn));
        }
    }

    /// Whether the lines of a turned cell whose text turns by `turn` and that is aligned as
    /// `align` says lie on the page's dots across the page: where the target puts them there
    /// ([`decisions::page_dots_turn`]), for text that reads up in a cell aligned to the top;
    /// every other turned cell's lines lie on the frame's dots.
    fn turned_dots(&self, turn: Turn, align: Option<VerticalAlign>) -> bool {
        decisions::page_dots_turn(&self.context.quirks, turn)
            .is_some_and(|turn| turn == UP && matches!(align, Some(VerticalAlign::Top) | None))
    }

    /// The height rest that the top of a turned cell's frame carries: where its lines lie on
    /// the page's dots, one part of a half-EMU to the side on which the fixed-point sum of the
    /// cell's text side lies from the exact side (`Device::parts_side`), so that a place of a
    /// line exactly half a dot past a whole dot takes the dot that the sum gives; none for other
    /// frames, and none where the device does not sum the side in fixed point.
    fn turned_side_rest(&self, upright: &Column, dots: bool) -> i64 {
        let Within::Cell(parts) = upright.within else {
            return 0;
        };
        let inner = parts.inner;
        if !dots {
            return 0;
        }
        let (side, origin) = (upright.left, self.column.origin);
        self.device.parts_side(origin, side - inner - origin, inner)
    }

    /// The top of a turned cell's upright frame for a row whose text starts at `row_top`, when
    /// the frame's top side turns to `side` across the page and its lines lie on the page's dots
    /// where `dots`: the row's top for lines on the frame's dots, and for lines on the page's
    /// the place at or above it that lies as far into a dot as `side`, so that the frame's whole
    /// dots turn into whole dots of the page.
    fn turned_frame_top(&self, row_top: Length, side: Length, dots: bool) -> Length {
        if dots {
            let across = row_top - side;
            row_top - (across - self.device.floor(across))
        } else {
            row_top
        }
    }
}

/// Moves each glyph of an item that turned onto the page, across the page, to where `object`'s
/// writer writes a text object's start at the glyph's place: the glyphs of a turned line share
/// one place across.
fn write_across(item: &mut Item, object: &TextObject) {
    match item {
        Item::Glyphs(run) => {
            for glyph in &mut run.glyphs {
                glyph.x = object.written_start_of(glyph.x);
            }
        }
        Item::Group(group) => {
            for item in &mut group.items {
                write_across(item, object);
            }
        }
        Item::Rect(_) | Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
    }
}

/// Moves a point `(x, y)` of the upright frame that starts at `from` to the page: its offset
/// from `from` turned by `turn` and added to `to`.
fn turn_point(
    (x, y): (Length, Length),
    ((fx, fy), (tx, ty)): Places,
    turn: Turn,
) -> (Length, Length) {
    let scale = i64::from(Turn::SCALE);
    let (dx, dy) = (x - fx, y - fy);
    (
        tx + (dx * i64::from(turn.xx) + dy * i64::from(turn.xy)).div_toward_zero(scale),
        ty + (dx * i64::from(turn.yx) + dy * i64::from(turn.yy)).div_toward_zero(scale),
    )
}

/// Turns each of `points` of the upright frame onto the page ([`turn_point`]).
fn turn_points<'a>(
    points: impl Iterator<Item = &'a mut f_office_paint::Point>,
    places: Places,
    turn: Turn,
) {
    for point in points {
        (point.x, point.y) = turn_point((point.x, point.y), places, turn);
    }
}

/// The start of an upright frame and the place on the page that it moves to.
pub(in crate::layout) type Places = ((Length, Length), (Length, Length));

/// The turn of a line of the upright frame that `places` and `turn` move onto the page, which
/// lay in a frame of its own that `own` moved into this frame, if it did.
fn turn_frame(own: Option<LineTurn>, places: Places, turn: Turn) -> LineTurn {
    match own {
        Some(own) => LineTurn {
            from: own.from,
            to: turn_point(own.to, places, turn),
            turn: after(turn, own.turn),
        },
        None => LineTurn {
            from: places.0,
            to: places.1,
            turn,
        },
    }
}

/// The turn that draws as `own` does and then as `turn` does.
pub(in crate::layout) fn after(turn: Turn, own: Turn) -> Turn {
    let scale = i64::from(Turn::SCALE);
    let entry = |a: i32, b: i32, c: i32, d: i32| {
        let value = (i64::from(a) * i64::from(b) + i64::from(c) * i64::from(d)) / scale;
        i32::try_from(value).unwrap_or(if value < 0 { i32::MIN } else { i32::MAX })
    };
    Turn {
        xx: entry(turn.xx, own.xx, turn.xy, own.yx),
        yx: entry(turn.yx, own.xx, turn.yy, own.yx),
        xy: entry(turn.xx, own.xy, turn.xy, own.yy),
        yy: entry(turn.yx, own.xy, turn.yy, own.yy),
    }
}

/// Turns an item of the upright frame onto the page: each glyph's origin and the glyph itself,
/// a rectangle's corners, the points of a path, of a gradient and its axis and of a group's
/// clip. A picture stays
/// upright: where it stays upright on the page (`upright`) its centre moves with the frame, else
/// it stays where it is.
pub(in crate::layout) fn turn_item(item: &mut Item, places: Places, turn: Turn, upright: bool) {
    let place = |x: Length, y: Length| turn_point((x, y), places, turn);
    match item {
        Item::Glyphs(run) => {
            for glyph in &mut run.glyphs {
                (glyph.x, glyph.y) = place(glyph.x, glyph.y);
            }
            // A glyph that the run already draws with a factor of its own, such as a scaled
            // run's, takes that first.
            run.turn = Some(run.turn.map_or(turn, |own| after(turn, own)));
        }
        Item::Rect(rect) => {
            let (a, b) = (
                place(rect.x, rect.y),
                place(rect.x + rect.width, rect.y + rect.height),
            );
            let (left, right) = (a.0.min(b.0), a.0.max(b.0));
            let (upper, lower) = (a.1.min(b.1), a.1.max(b.1));
            (rect.x, rect.y, rect.width, rect.height) = (left, upper, right - left, lower - upper);
        }
        Item::Path(path) => {
            let outline = path.commands.iter_mut().flat_map(PathCommand::points_mut);
            turn_points(outline, places, turn);
        }
        Item::Gradient(gradient) => {
            let axis = [&mut gradient.start, &mut gradient.end];
            let outline = gradient
                .commands
                .iter_mut()
                .flat_map(PathCommand::points_mut);
            turn_points(outline.chain(axis), places, turn);
        }
        Item::Image(image) if upright => {
            // The picture stays upright: its box keeps its size, and its centre moves as a
            // point of the frame does, with its clip.
            let (half_width, half_height) = (
                image.width.div_toward_zero(2),
                image.height.div_toward_zero(2),
            );
            let centre = place(image.x + half_width, image.y + half_height);
            let (dx, dy) = (
                centre.0 - half_width - image.x,
                centre.1 - half_height - image.y,
            );
            (image.x, image.y) = (image.x + dx, image.y + dy);
            if let Some(clip) = &mut image.clip {
                (clip.x, clip.y) = (clip.x + dx, clip.y + dy);
            }
        }
        Item::Image(_) => {}
        Item::Group(group) => {
            for item in &mut group.items {
                turn_item(item, places, turn, upright);
            }
            let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
            for point in clip.flat_map(PathCommand::points_mut) {
                (point.x, point.y) = place(point.x, point.y);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use f_office_paint::{Clip, Image, ImageItem, Item};
    use f_office_units::Length;

    use super::{DOWN, UP, turn_item, turn_point};

    /// A length of `points` points.
    fn pt(points: i64) -> Length {
        Length::from_units(points * Length::UNITS_PER_POINT)
    }

    /// A picture of 40 by 20 pt at (100, 200) in the frame, clipped to its left half.
    fn picture() -> Item {
        Item::Image(ImageItem {
            x: pt(100),
            y: pt(200),
            width: pt(40),
            height: pt(20),
            clip: Some(Clip {
                x: pt(100),
                y: pt(200),
                width: pt(20),
                height: pt(20),
            }),
            turn: None,
            image: Image::new(Vec::new()),
        })
    }

    #[test]
    fn moves_an_upright_picture_with_the_frame_by_its_centre() {
        // A frame from (100, 150) whose start moves to (300, 500) on the page.
        let places = ((pt(100), pt(150)), (pt(300), pt(500)));
        for turn in [UP, DOWN] {
            let mut item = picture();
            turn_item(&mut item, places, turn, true);
            let Item::Image(image) = item else {
                panic!("not a picture");
            };
            // The box keeps its size and stays upright, its centre lands where the frame's
            // point lands, and the clip moves with it.
            let centre = turn_point((pt(120), pt(210)), places, turn);
            assert_eq!(
                (image.width, image.height, image.turn),
                (pt(40), pt(20), None)
            );
            assert_eq!((image.x + pt(20), image.y + pt(10)), centre);
            let clip = image.clip.unwrap();
            assert_eq!((clip.x, clip.y), (image.x, image.y));
            assert_eq!((clip.width, clip.height), (pt(20), pt(20)));
        }
    }

    #[test]
    fn leaves_a_picture_where_the_frame_drew_it() {
        let places = ((pt(100), pt(150)), (pt(300), pt(500)));
        let mut item = picture();
        turn_item(&mut item, places, UP, false);
        assert_eq!(item, picture());
    }
}