f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
//! The segment rule of `GlyphSegments::FromRestart`: each segment counts from its own first
//! glyph.

use f_office_units::Length;

use super::steps::{Restart, Segment, SegmentRule};

/// Segments each from the exact place of their own first glyph (`GlyphSegments::FromRestart`).
///
/// The glyph whose exact right edge first reaches the end on the nearest dot, counted from the
/// segment's first glyph at the device's rounded dots per point
/// ([`Device::exact_scale`](super::Device::exact_scale)) as the edge check counts it, starts the
/// next segment. Its exact place is the one that the edge check counted in the segment before
/// ([`Segment::counted_place`]). From the third segment on it counts its exact place from the
/// dot of the segment before: it adds that segment's first dot less its exact place before it
/// goes to the nearest dot, so that it rounds the dot of the segment before plus the scaled
/// distance from it, the place that the edge check counted. The glyph that starts the second
/// segment takes nothing over from the line's first glyph unless that glyph hands it on
/// (`EdgeSteps::hands_on_start`), so that a line start a dot off Word's does not carry into
/// later segments. After a gap with a width, a tab or another, the next glyph starts a segment
/// as the line's first glyph does (`EdgeSteps::tab`, `EdgeSteps::gap`).
pub(super) struct FromRestart;

impl SegmentRule for FromRestart {
    fn next(
        &self,
        device: &crate::grid::Device,
        segment: Segment,
        (x, advance): (Length, Length),
        length: Length,
        start: Length,
    ) -> Option<Restart> {
        // The glyph whose exact right edge, counted from the segment's first glyph at the
        // device's rounded dots per point as the edge check counts it, reaches the end on the
        // nearest dot starts the next segment.
        let (numerator, denominator) = device.exact_scale();
        let edge = ((x + advance - segment.first) * numerator).div_round(denominator);
        if device.snap(edge) < segment.end {
            return None;
        }
        let place = segment.counted_place(device, x);
        Some(Restart {
            place,
            segment: Segment {
                first: x,
                end: length,
                counted: place,
            },
            carried: Some(start),
            rounded_up: false,
        })
    }

    fn after_gap(&self, _: Option<Segment>) -> Option<Segment> {
        None
    }

    fn continues_after_inline_object(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use crate::grid::steps::tests::NUMBERS_AT_600_DPI;
    use crate::grid::{Advances, Device, EdgeSteps};
    use crate::quirks::RestartCount;
    use f_office_units::{Length, div_round};

    /// A device of 600 dots per inch whose segments of 1,024 dots start again from each
    /// restart, at 8,534 dots per 1,024 points.
    fn device() -> Device {
        device_with(crate::profile::Profile::clone)
    }

    /// The device of [`device`] with some quirks of another variant (`change`).
    fn device_with(
        change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
    ) -> Device {
        let (bias, limit, segment) = NUMBERS_AT_600_DPI;
        Device::per_inch_with(600, |p| {
            change(&p.with_variant(crate::quirks::GlyphSegments::FromRestart))
        })
        .with_advances(Advances::RightEdge {
            bias,
            limit,
            segment,
            point_steps: std::num::NonZeroU32::new(1_024),
            start: f_office_paint::WriterOffset::NONE,
        })
    }

    /// The places of the glyphs of `advance` half-EMUs from `start` half-EMUs that `edge` gives
    /// on the device of these tests, in half-EMUs.
    fn places(edge: &mut EdgeSteps, (start, advance): (i64, i64), count: i64) -> Vec<i64> {
        let (start, advance) = (Length::from_units(start), Length::from_units(advance));
        (0..count)
            .map(|k| {
                edge.place(&device(), NUMBERS_AT_600_DPI, start + advance * k, advance)
                    .units()
            })
            .collect()
    }

    #[test]
    fn starts_a_segment_at_the_nearest_dot_of_the_scaled_exact_place() {
        // Glyphs of 48.45 dots on a device of 600 dots per inch with segments of 1,024 dots.
        // The 22nd glyph ends past the first segment. Its exact place is 1,017.453 dots from
        // the first glyph, and 1,017.532 dots at the device's 8,534 dots per 1,024 points, so
        // it goes to dot 1,018, where the plain place would go to 1,017.
        let (dot, advance) = (device().dots(1).units(), 147_676);
        let places = places(&mut EdgeSteps::default(), (0, advance), 22);
        assert_eq!(places.last(), Some(&(1_018 * dot)));
        assert_eq!(div_round(21 * advance, dot), 1_017);
    }

    #[test]
    fn counts_the_rounding_of_the_advances_at_a_restart_under_edge_check_places() {
        // Glyphs of 147,091 half-EMUs (48.26 dots), each half a half-EMU longer than its exact
        // advance. The 22nd glyph starts the second segment at a scaled place of 1,013.5013
        // dots from the first glyph, 4 half-EMUs past the half dot, so the advances rounded to
        // whole half-EMUs put it on dot 1,014. With what rounding took from the 21 advances
        // before it, 10.5 half-EMUs, it lies 6.5 half-EMUs under the half dot: dot 1,013.
        let dot = device().dots(1).units();
        let advance = Length::from_units(147_091);
        let last = |count: RestartCount| {
            let device = device_with(|p| p.with_variant(count));
            let mut edge = EdgeSteps::default();
            (0..22)
                .map(|k| {
                    edge.with_advance_rounding(Some((-1, 2)));
                    edge.place(&device, NUMBERS_AT_600_DPI, advance * k, advance)
                        .units()
                })
                .last()
        };
        assert_eq!(last(RestartCount::RoundedAdvances), Some(1_014 * dot));
        assert_eq!(last(RestartCount::EdgeCheckPlaces), Some(1_013 * dot));
    }

    #[test]
    fn counts_the_counted_share_of_a_stretched_space_at_a_restart_under_edge_check_places() {
        // The glyphs of the test above, with exact advances, where the edge check counts 10.5
        // half-EMUs less than the share of the first glyph, a stretched space. The 22nd glyph's
        // scaled place lies 4 half-EMUs past the half dot without that excess, on dot 1,014,
        // and 6.5 half-EMUs under it with it: dot 1,013.
        let dot = device().dots(1).units();
        let advance = Length::from_units(147_091);
        let last = |count: RestartCount| {
            let device = device_with(|p| p.with_variant(count));
            let mut edge = EdgeSteps::default();
            edge.with_counted_share(Some((-21, 2)));
            (0..22)
                .map(|k| {
                    edge.place(&device, NUMBERS_AT_600_DPI, advance * k, advance)
                        .units()
                })
                .last()
        };
        assert_eq!(last(RestartCount::RoundedAdvances), Some(1_014 * dot));
        assert_eq!(last(RestartCount::EdgeCheckPlaces), Some(1_013 * dot));
    }

    #[test]
    fn puts_a_restart_just_below_a_half_dot_on_the_dot_below_under_edge_check_places() {
        // The glyphs of the tests above, with exact advances, where the edge check counts 4.5
        // half-EMUs less than the share of the first glyph. The 22nd glyph's scaled place
        // lies 0.18 half-EMUs under the half dot, which rounds to the half dot itself: it goes
        // to dot 1,013 all the same. With 4 half-EMUs less, it lies 0.32 half-EMUs past the
        // half dot and goes to dot 1,014.
        let dot = device().dots(1).units();
        let advance = Length::from_units(147_091);
        let last = |lost: i128| {
            let device = device_with(|p| p.with_variant(RestartCount::EdgeCheckPlaces));
            let mut edge = EdgeSteps::default();
            edge.with_counted_share(Some((lost, 2)));
            (0..22)
                .map(|k| {
                    edge.place(&device, NUMBERS_AT_600_DPI, advance * k, advance)
                        .units()
                })
                .last()
        };
        assert_eq!(last(-9), Some(1_013 * dot));
        assert_eq!(last(-8), Some(1_014 * dot));
    }

    #[test]
    fn hands_the_rounding_of_a_lines_first_glyph_on_to_the_next_segment() {
        // The line of the test above, started 0.9 dots right of a dot: its first glyph goes
        // up to the next dot, 0.1 dots right of its exact place, and the glyph that starts the
        // second segment, at an exact 1,018.432 dots from the first dot, counts those 0.1
        // dots too and goes to dot 1,019, where its plain exact place would go to 1,018.
        let (dot, advance, start) = (device().dots(1).units(), 147_676, 2_743);
        let mut edge = EdgeSteps::default();
        edge.hands_on_start(true);
        let places = places(&mut edge, (start, advance), 22);
        assert_eq!(places.first(), Some(&dot));
        assert_eq!(places.last(), Some(&(1_019 * dot)));
        assert_eq!(div_round(start + 21 * advance, dot), 1_018);
    }

    #[test]
    fn starts_a_later_segment_at_the_place_that_the_edge_check_counted() {
        // The line of the tests above, 43 glyphs long. The 22nd glyph went to dot 1,018 from its
        // scaled place of 1,017.532 dots. The 43rd starts the third segment: the edge check
        // counts it at 1,018 dots plus the scaled 1,017.532 dots after the 22nd, 2,035.53 dots,
        // so it goes to dot 2,036. Counted from the 22nd glyph's plain place of 1,017.453 dots
        // with that glyph's carry, it would lie at 2,035.45 dots and go to dot 2,035.
        let (dot, advance) = (device().dots(1).units(), 147_676);
        let places = places(&mut EdgeSteps::default(), (0, advance), 43);
        assert_eq!(places.get(21), Some(&(1_018 * dot)));
        assert_eq!(places.last(), Some(&(2_036 * dot)));
    }

    #[test]
    fn starts_a_segment_where_the_scaled_right_edge_reaches_the_end_on_the_nearest_dot() {
        // Glyphs of 48.748 dots on the device of the tests above. The 21st glyph's exact right
        // edge lies 1,023.70 dots after the first glyph, 0.30 dots under the end of the
        // segment, and at the device's 8,534 dots per 1,024 points 1,023.78 dots, whose nearest
        // dot is the end. So that glyph starts the second segment: it goes to dot 975, the
        // nearest of its scaled exact place of 975.03 dots, where the steps from the glyph
        // before would put it on 976.
        let (dot, advance) = (device().dots(1).units(), 148_583);
        let places = places(&mut EdgeSteps::default(), (0, advance), 22);
        assert_eq!(places.get(20), Some(&(975 * dot)));
        assert_eq!(places.last(), Some(&(1_024 * dot)));
        assert!(21 * advance < NUMBERS_AT_600_DPI.2.units());
    }

    #[test]
    fn starts_a_segment_after_a_gap_as_a_line_starts() {
        // The line of the test above after five glyphs and a gap, 500 dots further right: the
        // glyph after the gap starts the count of the segment, so the 22 glyphs take the
        // places of that line moved by 500 dots. With a plain restart the segment still
        // counts from the line's first glyph, and a glyph restarts elsewhere.
        let device = device();
        let (dot, advance, start) = (device.dots(1).units(), 147_676, 2_743);
        let line = |after_gap: bool| -> Vec<i64> {
            let mut edge = EdgeSteps::default();
            edge.hands_on_start(true);
            places(&mut edge, (0, advance), 5);
            if after_gap {
                edge.gap(&device);
            } else {
                edge.restart();
            }
            places(&mut edge, (500 * dot + start, advance), 22)
        };
        let after = line(true);
        assert_eq!(after.first(), Some(&(501 * dot)));
        assert_eq!(after.last(), Some(&(1_519 * dot)));
        assert_ne!(line(false), after);
    }

    #[test]
    fn inline_object_keeps_segment_and_anchor_shifted_by_width() {
        let device = device();
        let obj = device.dots(90);
        let adv = Length::from_units(139_000); // ~45.60 dots
        let mut edge = EdgeSteps::default();
        let mut x = device.dots(600);
        let step_restarts = |edge: &mut EdgeSteps, x: &mut Length, count: usize| -> usize {
            (0..count)
                .filter(|_| {
                    edge.place(&device, NUMBERS_AT_600_DPI, *x, adv);
                    *x += adv;
                    edge.take_start_place().is_some()
                })
                .count()
        };
        assert_eq!(step_restarts(&mut edge, &mut x, 3), 1); // first glyph starts segment
        // Step across a 90-dot inline object without resetting segment or anchor.
        edge.after_inline_object(&device, obj);
        x += obj;
        let after = edge.place(&device, NUMBERS_AT_600_DPI, x, adv);
        x += adv;
        // Exact text width is 3 * 139,000 = 417,000 half-EMUs (~136.81 dots) -> rounds to 137 dots,
        // plus 90 whole dots = 600 + 227 = 827 dots (where stepping from 3*46=138 would give 828).
        assert_eq!(after, device.dots(827));
        // Segment continues counting text width (excluding the 90-dot object): 1024-dot restart
        // happens only once text advances alone reach 1024 dots (~23 glyphs), not after 21 glyphs.
        assert_eq!(step_restarts(&mut edge, &mut x, 17), 0);
        assert_eq!(step_restarts(&mut edge, &mut x, 3), 1);
    }
}