f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! Kashidas: how a justified line of a paragraph aligned `lowKashida` lengthens letter joints between
//! Arabic letters with tatweel glyphs (U+0640) before it widens its spaces.
//!
//! The line's words that can take a kashida take one each, from the last word in reading order:
//! as many as the tatweels' advances on the device fit into the line's room on the device,
//! strictly. Each kashida is then as wide as the tatweel's advance on the device, and the spaces
//! take the rest of the free space. Where every such word takes one, the kashidas share the room
//! on the device, and the spaces keep their width. A kashida draws as many tatweels as cover its
//! width and the tatweel's overlap in the tatweel's advances on the device: the first in reading
//! order ends at the letter before the letter joint, each next one a tatweel's advance further, and the
//! last starts by the overlap before the end of the letter after the letter joint. The overlap is what
//! the tatweel's advance on the device exceeds its advance at the device's size without hinting,
//! rounded up to whole dots.
//!
//! From compatibility mode 15, the line's letter joints after a seen, sheen, sad or dad take a
//! kashida each instead, all of the same width: the line's room on the device shared among
//! them, but at most three widths of a space each. What they leave goes to the letter joints
//! before the last letter of a joined group that ends as an alef or a heh and to the spaces
//! together, each such joint taking three times what each space widens.

use std::borrow::Cow;

use f_office_units::Length;

use super::LinePlace;
use super::shift::{aligned_as_last, line_alignment, stretched_spaces};
use crate::grid::Rounding;
use crate::layout::decisions::KashidaJoints;
use crate::layout::{Layout, decisions};
use crate::lines::joints::{final_joints, letter_joints, seen_joints};
use crate::lines::{Line, Piece, Placed, is_space};
use crate::params;
use crate::props::{Alignment, ParaProps};
use crate::text::{FaceIndex, Glyph};

/// One kashida of a line: the index of the piece after which its tatweels go, their face, and
/// its width.
struct Kashida {
    after: usize,
    face: FaceIndex,
    width: Length,
}

impl Layout<'_> {
    /// `line` with the kashidas that it takes at `place` in a paragraph of the properties
    /// `props`: where the line is justified and the paragraph's kashidas lengthen letter joints
    /// ([`decisions::kashida_joints`]), the tatweel glyphs of each kashida go after the letter
    /// before its letter joint, and the pieces after them move.
    pub(in crate::layout) fn with_kashidas<'l>(
        &self,
        line: &'l Line,
        props: &ParaProps,
        place: LinePlace,
    ) -> Cow<'l, Line> {
        let Some(joints) =
            decisions::kashida_joints(&self.context.quirks, self.settings, props.kashidas)
        else {
            return Cow::Borrowed(line);
        };
        let last = aligned_as_last(line, place.last, self.settings, &self.context.quirks);
        if line_alignment(props, last) != Alignment::Both {
            return Cow::Borrowed(line);
        }
        let kashidas = match joints {
            KashidaJoints::LastWords => self.kashidas(line, place.width),
            KashidaJoints::SeensThenFinals => self.seen_kashidas(line, place.width),
        };
        if kashidas.is_empty() {
            return Cow::Borrowed(line);
        }
        Cow::Owned(self.lengthened(line, &kashidas))
    }

    /// The kashidas of a justified `line` of the width `width`, in reading order.
    fn kashidas(&self, line: &Line, width: Length) -> Vec<Kashida> {
        let written = line.written();
        let pieces = line.placed.get(..written).unwrap_or_default();
        let free = width - line.width();
        let letter_joints = letter_joints(pieces, line.first_stretched());
        if free <= Length::ZERO || letter_joints.is_empty() {
            return Vec::new();
        }
        let room = self.device_room(pieces, width);
        // The words take kashidas from the last one, while their tatweels' advances on the
        // device stay below the room.
        let mut taken = 0;
        let mut sum = 0;
        for &(_, face) in letter_joints.iter().rev() {
            let Some((_, dots)) = self.tatweel_advance(face) else {
                break;
            };
            if sum + dots >= room {
                break;
            }
            sum += dots;
            taken += 1;
        }
        let chosen = letter_joints
            .get(letter_joints.len() - taken..)
            .unwrap_or_default();
        if taken == letter_joints.len() {
            return self.shared(chosen, room);
        }
        // Each kashida is as wide as the tatweel's advance on the device, and the spaces take
        // the rest, which can be less than nothing.
        chosen
            .iter()
            .filter_map(|&(after, face)| {
                let (_, dots) = self.tatweel_advance(face)?;
                Some(Kashida {
                    after,
                    face,
                    width: self.device.dots(dots),
                })
            })
            .collect()
    }

    /// The kashidas of a justified `line` of the width `width` from `KASHIDA_WORDS_MODE`, in
    /// reading order: one at each letter joint after a seen, sheen, sad or dad, sharing the
    /// line's room on the device ([`Self::shared`]) while each share is at most the widest
    /// kashida of the joint's face ([`Self::widest_seen_kashida`]), else each that widest; and
    /// at the letter joints before an alef or a heh that ends a joined group, from the room that
    /// those leave ([`Self::final_kashidas`]). The spaces take the rest of the free space.
    fn seen_kashidas(&self, line: &Line, width: Length) -> Vec<Kashida> {
        let written = line.written();
        let pieces = line.placed.get(..written).unwrap_or_default();
        let joints = seen_joints(pieces, line.first_stretched());
        let finals = final_joints(pieces, line.first_stretched());
        if width <= line.width() || (joints.is_empty() && finals.is_empty()) {
            return Vec::new();
        }
        let room = self.device_room(pieces, width);
        let mut kashidas = Vec::new();
        let mut rest = room;
        if !joints.is_empty() {
            let count = i64::try_from(joints.len()).unwrap_or(i64::MAX).max(1);
            let each = room.div_euclid(count);
            if each <= 0 {
                return Vec::new();
            }
            if joints
                .iter()
                .all(|&(_, face)| each <= self.widest_seen_kashida(face))
            {
                return self.shared(&joints, room);
            }
            for &(after, face) in &joints {
                let dots = each.min(self.widest_seen_kashida(face));
                rest -= dots;
                kashidas.push(Kashida {
                    after,
                    face,
                    width: self.device.dots(dots),
                });
            }
        }
        kashidas.extend(self.final_kashidas(line, &finals, rest));
        kashidas.sort_by_key(|kashida| kashida.after);
        kashidas
    }

    /// The kashidas at the letter joints `finals` before an alef or a heh that ends a joined
    /// group of `line`, from the room `rest` on the device in whole dots that the letter joints
    /// after a seen leave: the joints and the line's stretched spaces share it, each joint taking
    /// `FINAL_KASHIDA_SHARE` times what each space takes, not rounded to whole dots.
    fn final_kashidas(
        &self,
        line: &Line,
        finals: &[(usize, FaceIndex)],
        rest: i64,
    ) -> Vec<Kashida> {
        let joints = i64::try_from(finals.len()).unwrap_or(i64::MAX);
        let shares = joints * params::FINAL_KASHIDA_SHARE + stretched_spaces(line).unwrap_or(0);
        if rest <= 0 || shares <= 0 {
            return Vec::new();
        }
        let width = self
            .device
            .dots(rest * params::FINAL_KASHIDA_SHARE)
            .div_toward_zero(shares);
        if width <= Length::ZERO {
            return Vec::new();
        }
        finals
            .iter()
            .map(|&(after, face)| Kashida { after, face, width })
            .collect()
    }

    /// The widest kashida after a seen in the face `face`, in whole dots: `SEEN_KASHIDA_SPACES`
    /// times the advance of the face's space, rounded half up.
    fn widest_seen_kashida(&self, face: FaceIndex) -> i64 {
        self.shaper.glyph(face, ' ').map_or(0, |space| {
            self.device.count(
                space.advance * params::SEEN_KASHIDA_SPACES,
                Rounding::HalfUp,
            )
        })
    }

    /// The room of a justified line of the width `width` and the pieces `pieces` on the device,
    /// in whole dots: the width, rounded half up, less the advances on the device
    /// ([`Self::device_advance`]) of the pieces from the first that is not a space.
    fn device_room(&self, pieces: &[Placed], width: Length) -> i64 {
        let first = pieces.iter().position(|p| !is_space(&p.piece)).unwrap_or(0);
        let used: i64 = pieces
            .get(first..)
            .unwrap_or_default()
            .iter()
            .map(|p| self.device_advance(p))
            .sum();
        self.device.count(width, Rounding::HalfUp) - used
    }

    /// The kashidas at the letter joints `joints` when they share the room `room` in whole dots:
    /// each the same width, the last in reading order taking what the equal shares leave. The
    /// spaces take the rest of the free space.
    fn shared(&self, joints: &[(usize, FaceIndex)], room: i64) -> Vec<Kashida> {
        let room = self.device.dots(room);
        let taken = joints.len();
        let count = i64::try_from(taken).unwrap_or(i64::MAX).max(1);
        let each = room.div_toward_zero(count);
        let rest = room - each * count;
        joints
            .iter()
            .enumerate()
            .map(|(at, &(after, face))| Kashida {
                after,
                face,
                width: if at + 1 == taken { each + rest } else { each },
            })
            .collect()
    }

    /// The advance of a piece on the device in whole dots: that of a glyph at its face's size
    /// in pixels per em as bi-level rendering gives it, with the change that shaping made to its
    /// advance, where the fonts give it; else its advance, to the nearest dot.
    fn device_advance(&self, placed: &Placed) -> i64 {
        let nearest = self.device.count(placed.advance, Rounding::HalfUp);
        let Piece::Glyph(glyph) = &placed.piece else {
            return nearest;
        };
        if glyph.part || glyph.advance == Length::ZERO {
            return nearest;
        }
        let Some(face) = self.shaper.faces().get(glyph.face) else {
            return nearest;
        };
        let fonts = self.shaper.fonts();
        let ppem = u16::try_from(self.device.count(face.size, Rounding::HalfUp)).unwrap_or(0);
        let (Some(dots), Some(own)) = (
            fonts.bi_level_advance(face.font, glyph.id, ppem),
            fonts.advance(face.font, glyph.id),
        ) else {
            return nearest;
        };
        let change = glyph.advance - face.scale(i64::from(own));
        i64::from(dots) + self.device.count(change, Rounding::HalfUp)
    }

    /// The tatweel's advance of the face `face`, and its advance on the device in whole dots as
    /// [`Self::device_advance`] counts it; `None` when the face has no tatweel.
    fn tatweel_advance(&self, face: FaceIndex) -> Option<(Length, i64)> {
        let own = self.shaper.tatweel(face, None)?;
        let placed = Placed {
            piece: Piece::Glyph(own),
            x: Length::ZERO,
            advance: own.advance,
            leader: None,
            tab: None,
        };
        Some((own.advance, self.device_advance(&placed)))
    }

    /// `line` with the tatweels of `kashidas`: for each, as many tatweels as cover its width,
    /// each of a tatweel's advance but the last in reading order, which takes the rest, and the
    /// pieces after them moved by its width.
    fn lengthened(&self, line: &Line, kashidas: &[Kashida]) -> Line {
        let mut placed = Vec::with_capacity(line.placed.len() + kashidas.len());
        let mut moved = Length::ZERO;
        let mut added = Vec::new();
        let mut next = kashidas.iter().peekable();
        for (index, piece) in line.placed.iter().enumerate() {
            placed.push(Placed {
                x: piece.x + moved,
                ..*piece
            });
            let Some(kashida) = next.next_if(|k| k.after == index) else {
                continue;
            };
            let left = match &piece.piece {
                Piece::Glyph(glyph) => Some(*glyph),
                _ => None,
            };
            let mut x = piece.x + moved + piece.advance;
            let tatweels = self.tatweels(kashida, left.as_ref());
            added.push((index, tatweels.len()));
            for glyph in tatweels {
                placed.push(Placed {
                    piece: Piece::Glyph(glyph),
                    x,
                    advance: glyph.advance,
                    leader: None,
                    tab: None,
                });
                x += glyph.advance;
            }
            moved += kashida.width;
        }
        let mut anchors = line.anchors.clone();
        for anchor in &mut anchors {
            anchor.at += added
                .iter()
                .filter(|&&(after, _)| after < anchor.at)
                .map(|&(_, count)| count)
                .sum::<usize>();
        }
        Line {
            placed,
            anchors,
            ..line.clone()
        }
    }

    /// The whole dots by which the tatweel of the face `face` is wider on the device than its
    /// advance at the device's size in pixels per em without hinting, rounded up; zero where it
    /// is not wider.
    fn tatweel_overlap(&self, face: FaceIndex, dots: i64) -> i64 {
        let Some(f) = self.shaper.faces().get(face) else {
            return 0;
        };
        let Some(glyph) = self.shaper.tatweel(face, None) else {
            return 0;
        };
        let Some(units) = self.shaper.fonts().advance(f.font, glyph.id) else {
            return 0;
        };
        let em = i64::from(f.metrics.units_per_em.max(1));
        let ppem = self.device.count(f.size, Rounding::HalfUp);
        let over = dots * em - i64::from(units) * ppem;
        if over > 0 { ceiling(over, em) } else { 0 }
    }

    /// The tatweel glyphs of a kashida in reading order, after the glyph `left`, whose run they
    /// take. The last one in reading order starts by the tatweel's overlap
    /// ([`Self::tatweel_overlap`]) before the end of the letter after the kashida, and they are
    /// as many as cover the kashida's width and that overlap in the tatweel's advances on the
    /// device: each of a tatweel's advance but the last, which takes the rest of the width.
    fn tatweels(&self, kashida: &Kashida, left: Option<&Glyph>) -> Vec<Glyph> {
        let Some((own, dots)) = self.tatweel_advance(kashida.face) else {
            return Vec::new();
        };
        let overlap = self.device.dots(self.tatweel_overlap(kashida.face, dots));
        let step = self.device.dots(dots);
        let count = ceiling((kashida.width + overlap).units(), step.units()).max(1);
        (0..count)
            .filter_map(|at| {
                let last = at + 1 == count;
                let advance = if last {
                    kashida.width - own * (count - 1)
                } else {
                    own
                };
                let mut glyph = self.shaper.tatweel(kashida.face, Some(advance))?;
                if let Some(left) = left {
                    glyph.direction = left.direction;
                    glyph.side = left.side;
                    glyph.place = left.place;
                }
                if last {
                    glyph.offset.0 -= overlap;
                }
                Some(glyph)
            })
            .collect()
    }
}

/// `count` over `per`, rounded up, for a positive `per`; 1 for any other `per`.
fn ceiling(count: i64, per: i64) -> i64 {
    if per > 0 {
        (count + per - 1).div_euclid(per)
    } else {
        1
    }
}